Skip to main content

rustc_resolve/
def_collector.rs

1use std::mem;
2
3use rustc_ast::visit::FnKind;
4use rustc_ast::*;
5use rustc_attr_parsing as attr;
6use rustc_attr_parsing::{AttributeParser, ShouldEmit};
7use rustc_expand::expand::AstFragment;
8use rustc_hir as hir;
9use rustc_hir::Target;
10use rustc_hir::def::DefKind;
11use rustc_hir::def::Namespace::{TypeNS, ValueNS};
12use rustc_hir::def_id::LocalDefId;
13use rustc_middle::middle::resolve::PerOwnerResolverData;
14use rustc_middle::span_bug;
15use rustc_middle::ty::TyCtxtFeed;
16use rustc_span::{Span, Symbol, sym};
17use tracing::{debug, instrument};
18
19use crate::macros::MacroRulesScopeRef;
20use crate::{
21    ImplTraitContext, InvocationParent, ParentScope, Resolver, with_owner, with_owner_tables,
22};
23
24pub(crate) fn collect_definitions<'ra>(
25    resolver: &mut Resolver<'ra, '_>,
26    fragment: &AstFragment,
27    parent_scope: ParentScope<'ra>,
28) -> MacroRulesScopeRef<'ra> {
29    let invocation_parent = resolver.invocation_parents[&parent_scope.expansion];
30    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/def_collector.rs:30",
                        "rustc_resolve::def_collector", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/def_collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(30u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::def_collector"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("new fragment to visit with invocation_parent: {0:?}",
                                                    invocation_parent) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("new fragment to visit with invocation_parent: {invocation_parent:?}");
31    if true {
    {
        match (&resolver.current_owner.id, &DUMMY_NODE_ID) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(resolver.current_owner.id, DUMMY_NODE_ID);
32    with_owner(resolver, invocation_parent.owner, |r| {
33        let mut visitor = DefCollector { r, invocation_parent, parent_scope };
34        fragment.visit_with(&mut visitor);
35        visitor.parent_scope.macro_rules
36    })
37}
38
39/// Creates `DefId`s for nodes in the AST.
40pub(crate) struct DefCollector<'a, 'ra, 'tcx> {
41    pub(crate) r: &'a mut Resolver<'ra, 'tcx>,
42    invocation_parent: InvocationParent,
43    pub(crate) parent_scope: ParentScope<'ra>,
44}
45
46impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> {
47    pub(super) fn create_def(
48        &mut self,
49        node_id: NodeId,
50        name: Option<Symbol>,
51        def_kind: DefKind,
52        span: Span,
53    ) -> TyCtxtFeed<'tcx, LocalDefId> {
54        let parent_def = self.invocation_parent.parent_def;
55        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/def_collector.rs:55",
                        "rustc_resolve::def_collector", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/def_collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(55u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::def_collector"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("create_def(node_id={0:?}, def_kind={1:?}, parent_def={2:?})",
                                                    node_id, def_kind, parent_def) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
56            "create_def(node_id={:?}, def_kind={:?}, parent_def={:?})",
57            node_id, def_kind, parent_def
58        );
59        self.r.create_def(
60            parent_def,
61            node_id,
62            name,
63            def_kind,
64            self.parent_scope.expansion.to_expn_id(),
65            span.with_parent(None),
66            false,
67        )
68    }
69
70    fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: LocalDefId, f: F) {
71        let orig_parent_def = mem::replace(&mut self.invocation_parent.parent_def, parent_def);
72        f(self);
73        self.invocation_parent.parent_def = orig_parent_def;
74    }
75
76    pub(super) fn with_owner<F: FnOnce(&mut Self, TyCtxtFeed<'tcx, LocalDefId>)>(
77        &mut self,
78        owner: NodeId,
79        name: Option<Symbol>,
80        def_kind: DefKind,
81        span: Span,
82        f: F,
83    ) {
84        if true {
    {
        match (&owner, &DUMMY_NODE_ID) {
            (left_val, right_val) => {
                if *left_val == *right_val {
                    let kind = ::core::panicking::AssertKind::Ne;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_ne!(owner, DUMMY_NODE_ID);
85        if true {
    {
        match (&owner, &CRATE_NODE_ID) {
            (left_val, right_val) => {
                if *left_val == *right_val {
                    let kind = ::core::panicking::AssertKind::Ne;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_ne!(owner, CRATE_NODE_ID);
86        // We only get here if the owner didn't exist yet. After the owner has been created,
87        // future invocations of `collect_definitions` will get the owner out of the `owners`
88        // table.
89        let parent_def = self.invocation_parent.parent_def;
90        let feed = self.r.create_def(
91            parent_def,
92            owner,
93            name,
94            def_kind,
95            self.parent_scope.expansion.to_expn_id(),
96            span.with_parent(None),
97            true,
98        );
99        let tables = PerOwnerResolverData::new(owner, feed.key());
100
101        let orig_invoc_owner = mem::replace(&mut self.invocation_parent.owner, owner);
102        with_owner_tables(self, owner, tables, |this| f(this, feed));
103        let old = mem::replace(&mut self.invocation_parent.owner, orig_invoc_owner);
104        {
    match (&old, &owner) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(old, owner);
105    }
106
107    fn with_impl_trait<F: FnOnce(&mut Self)>(
108        &mut self,
109        impl_trait_context: ImplTraitContext,
110        f: F,
111    ) {
112        let orig_itc =
113            mem::replace(&mut self.invocation_parent.impl_trait_context, impl_trait_context);
114        f(self);
115        self.invocation_parent.impl_trait_context = orig_itc;
116    }
117
118    fn collect_field(&mut self, field: &'a FieldDef, index: Option<usize>) {
119        let index = |this: &Self| {
120            index.unwrap_or_else(|| {
121                let node_id = NodeId::placeholder_from_expn_id(this.parent_scope.expansion);
122                this.r.placeholder_field_indices[&node_id]
123            })
124        };
125
126        if field.is_placeholder {
127            let old_index = self.r.placeholder_field_indices.insert(field.id, index(self));
128            if !old_index.is_none() {
    {
        ::core::panicking::panic_fmt(format_args!("placeholder field index is reset for a node ID"));
    }
};assert!(old_index.is_none(), "placeholder field index is reset for a node ID");
129            self.visit_macro_invoc(field.id);
130            self.visit_invoc(field.id);
131        } else {
132            let name = field.ident.map_or_else(|| sym::integer(index(self)), |ident| ident.name);
133            let def = self.create_def(field.id, Some(name), DefKind::Field, field.span);
134            self.with_parent(def.def_id(), |this| this.brg_visit_field_def(field, def));
135        }
136    }
137
138    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("visit_macro_invoc",
                                    "rustc_resolve::def_collector", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/def_collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(138u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::def_collector"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/def_collector.rs:140",
                                    "rustc_resolve::def_collector", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/def_collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(140u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::def_collector"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self.invocation_parent")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self.invocation_parent");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.invocation_parent)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let id = id.placeholder_to_expn_id();
            let old_parent =
                self.r.invocation_parents.insert(id, self.invocation_parent);
            if !old_parent.is_none() {
                {
                    ::core::panicking::panic_fmt(format_args!("parent `LocalDefId` is reset for an invocation"));
                }
            };
        }
    }
}#[instrument(level = "debug", skip(self))]
139    fn visit_macro_invoc(&mut self, id: NodeId) {
140        debug!(?self.invocation_parent);
141
142        let id = id.placeholder_to_expn_id();
143        let old_parent = self.r.invocation_parents.insert(id, self.invocation_parent);
144        assert!(old_parent.is_none(), "parent `LocalDefId` is reset for an invocation");
145    }
146}
147
148impl<'a, 'ra, 'tcx> visit::Visitor<'a> for DefCollector<'a, 'ra, 'tcx> {
149    fn visit_item(&mut self, i: &'a Item) {
150        // Pick the def data. This need not be unique, but the more
151        // information we encapsulate into, the better
152        let mut opt_syn_ext = None;
153        let def_kind = match &i.kind {
154            ItemKind::Impl(i) => DefKind::Impl { of_trait: i.of_trait.is_some() },
155            ItemKind::ForeignMod(..) => DefKind::ForeignMod,
156            ItemKind::Mod(..) => DefKind::Mod,
157            ItemKind::Trait(..) => DefKind::Trait,
158            ItemKind::TraitAlias(..) => DefKind::TraitAlias,
159            ItemKind::Enum(..) => DefKind::Enum,
160            ItemKind::Struct(..) => DefKind::Struct,
161            ItemKind::Union(..) => DefKind::Union,
162            ItemKind::ExternCrate(..) => DefKind::ExternCrate,
163            ItemKind::TyAlias(..) => DefKind::TyAlias,
164            ItemKind::Static(s) => DefKind::Static {
165                safety: hir::Safety::Safe,
166                mutability: s.mutability,
167                nested: false,
168            },
169            ItemKind::Const(citem) => {
170                let is_type_const = citem.kind == ConstItemKind::TypeConst;
171                DefKind::Const { is_type_const }
172            }
173            ItemKind::ConstBlock(..) => DefKind::Const { is_type_const: false },
174            ItemKind::Fn(..) | ItemKind::Delegation(..) => DefKind::Fn,
175            ItemKind::MacroDef(ident, def) => {
176                let edition = i.span.edition();
177
178                // FIXME(jdonszelmann) make one of these in the resolver?
179                // FIXME(jdonszelmann) don't care about tools here maybe? Just parse what we can.
180                // Does that prevents errors from happening? maybe
181                let mut parser = AttributeParser::new(
182                    &self.r.tcx.sess,
183                    self.r.features,
184                    self.r.tcx().registered_attr_tools(()),
185                    ShouldEmit::Nothing,
186                );
187                let attrs = parser.parse_attribute_list(
188                    &i.attrs,
189                    i.span,
190                    Target::MacroDef,
191                    std::convert::identity,
192                    |_lint_id, _span, _kind| {
193                        // FIXME(jdonszelmann): emit lints here properly
194                        // NOTE that before new attribute parsing, they didn't happen either
195                        // but it would be nice if we could change that.
196                    },
197                );
198
199                let ext = self.r.compile_macro(def, *ident, &attrs, i.span, i.id, edition);
200                let macro_kinds = ext.macro_kinds();
201                opt_syn_ext = Some(ext);
202                DefKind::Macro(macro_kinds)
203            }
204            ItemKind::GlobalAsm(..) => DefKind::GlobalAsm,
205            ItemKind::Use(_) => {
206                return self.with_owner(i.id, None, DefKind::Use, i.span, |this, feed| {
207                    this.brg_visit_item(i, feed);
208                });
209            }
210            ItemKind::MacCall(..) => {
211                self.visit_macro_invoc(i.id);
212                self.brg_visit_mac_call_in_module(i.id);
213                return;
214            }
215            ItemKind::DelegationMac(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
216            ItemKind::TestBinderConstraints(..) => DefKind::TestBinderConstraints,
217        };
218        self.with_owner(
219            i.id,
220            i.kind.ident().map(|ident| ident.name),
221            def_kind,
222            i.span,
223            |this, feed| {
224                if let Some(ext) = opt_syn_ext {
225                    this.r.local_macro_map.insert(feed.def_id(), this.r.arenas.alloc_macro(ext));
226                }
227
228                this.with_parent(feed.def_id(), |this| {
229                    this.with_impl_trait(ImplTraitContext::Existential, |this| {
230                        this.brg_visit_item(i, feed)
231                    })
232                });
233            },
234        );
235    }
236
237    fn visit_block(&mut self, block: &'a Block) {
238        self.brg_visit_block(block);
239    }
240
241    fn visit_fn(&mut self, fn_kind: FnKind<'a>, _: &AttrVec, span: Span, _: NodeId) {
242        match fn_kind {
243            FnKind::Fn(
244                ctxt,
245                _vis,
246                Fn {
247                    sig: FnSig { header, decl, span: _ }, ident, generics, contract, body, ..
248                },
249            ) if let Some(coroutine_marker) = header.coroutine_marker
250                // Foreign ones are denied, so don't create them here.
251                && ctxt != visit::FnCtxt::Foreign =>
252            {
253                self.visit_ident(ident);
254                self.visit_fn_header(header);
255                self.visit_generics(generics);
256                if let Some(contract) = contract {
257                    self.visit_contract(contract);
258                }
259
260                // For async functions, we need to create their inner defs inside of a
261                // closure to match their desugared representation. Besides that,
262                // we must mirror everything that `visit::walk_fn` below does.
263                let FnDecl { inputs, output } = &**decl;
264                for param in inputs {
265                    self.visit_param(param);
266                }
267
268                let return_def = self
269                    .create_def(
270                        coroutine_marker.return_impl_trait_id,
271                        None,
272                        DefKind::OpaqueTy,
273                        coroutine_marker.span,
274                    )
275                    .def_id();
276                self.with_parent(return_def, |this| this.visit_fn_ret_ty(output));
277
278                // If this async fn has no body (i.e. it's an async fn signature in a trait)
279                // then the closure_def will never be used, and we should avoid generating a
280                // def-id for it.
281                if let Some(body) = body {
282                    let closure_def = self
283                        .create_def(coroutine_marker.closure_id, None, DefKind::Closure, span)
284                        .def_id();
285                    self.with_parent(closure_def, |this| this.visit_block(body));
286                }
287            }
288            FnKind::Closure(binder, Some(coroutine_marker), decl, body) => {
289                self.visit_closure_binder(binder);
290                visit::walk_fn_decl(self, decl);
291
292                // Async closures desugar to closures inside of closures, so
293                // we must create two defs.
294                let coroutine_def = self
295                    .create_def(coroutine_marker.closure_id, None, DefKind::Closure, span)
296                    .def_id();
297                self.with_parent(coroutine_def, |this| this.visit_expr(body));
298            }
299            _ => visit::walk_fn(self, fn_kind),
300        }
301    }
302
303    fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
304        let (ident, def_kind) = match fi.kind {
305            ForeignItemKind::Static(StaticItem {
306                ident,
307                ty: _,
308                mutability,
309                expr: _,
310                safety,
311                define_opaque: _,
312                eii_impl: _,
313            }) => {
314                let safety = match safety {
315                    ast::Safety::Unsafe(_) | ast::Safety::Default => hir::Safety::Unsafe,
316                    ast::Safety::Safe(_) => hir::Safety::Safe,
317                };
318
319                (ident, DefKind::Static { safety, mutability, nested: false })
320            }
321            ForeignItemKind::Fn(Fn { ident, .. }) => (ident, DefKind::Fn),
322            ForeignItemKind::TyAlias(TyAlias { ident, .. }) => (ident, DefKind::ForeignTy),
323            ForeignItemKind::MacCall(_) => {
324                self.visit_invoc_in_module(fi.id);
325                self.visit_macro_invoc(fi.id);
326                return;
327            }
328        };
329
330        self.with_owner(fi.id, Some(ident.name), def_kind, fi.span, |this, def| {
331            this.with_parent(def.def_id(), |this| {
332                this.build_reduced_graph_for_foreign_item(fi, ident, def);
333                visit::walk_item(this, fi)
334            });
335        })
336    }
337
338    fn visit_variant(&mut self, v: &'a Variant) {
339        if v.is_placeholder {
340            self.visit_macro_invoc(v.id);
341            self.visit_invoc_in_module(v.id);
342            return;
343        }
344        let feed = self.create_def(v.id, Some(v.ident.name), DefKind::Variant, v.span);
345        self.with_parent(feed.def_id(), |this| this.brg_visit_variant(v, feed));
346    }
347
348    fn visit_where_predicate(&mut self, pred: &'a WherePredicate) {
349        if pred.is_placeholder {
350            self.visit_macro_invoc(pred.id);
351            self.visit_invoc(pred.id);
352        } else {
353            visit::walk_where_predicate(self, pred)
354        }
355    }
356
357    fn visit_variant_data(&mut self, data: &'a VariantData) {
358        // The assumption here is that non-`cfg` macro expansion cannot change field indices.
359        // It currently holds because only inert attributes are accepted on fields,
360        // and every such attribute expands into a single field after it's resolved.
361        for (index, field) in data.fields().iter().enumerate() {
362            self.collect_field(field, Some(index));
363        }
364    }
365
366    fn visit_generic_param(&mut self, param: &'a GenericParam) {
367        if param.is_placeholder {
368            self.visit_macro_invoc(param.id);
369            self.visit_invoc(param.id);
370            return;
371        }
372        let def_kind = match param.kind {
373            GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
374            GenericParamKind::Type { .. } => DefKind::TyParam,
375            GenericParamKind::Const { .. } => DefKind::ConstParam,
376        };
377        self.create_def(param.id, Some(param.ident.name), def_kind, param.ident.span);
378
379        // impl-Trait can happen inside generic parameters, like
380        // ```
381        // fn foo<U: Iterator<Item = impl Clone>>() {}
382        // ```
383        //
384        // In that case, the impl-trait is lowered as an additional generic parameter.
385        self.with_impl_trait(ImplTraitContext::Universal, |this| {
386            visit::walk_generic_param(this, param)
387        });
388    }
389
390    fn visit_assoc_item(&mut self, i: &'a AssocItem, ctxt: visit::AssocCtxt) {
391        let (ident, def_kind, ns) = match &i.kind {
392            AssocItemKind::Fn(Fn { ident, .. })
393            | AssocItemKind::Delegation(Delegation { ident, .. }) => {
394                (*ident, DefKind::AssocFn, ValueNS)
395            }
396            AssocItemKind::Const(ConstItem { ident, kind, .. }) => (
397                *ident,
398                DefKind::AssocConst { is_type_const: *kind == ConstItemKind::TypeConst },
399                ValueNS,
400            ),
401            AssocItemKind::Type(TyAlias { ident, .. }) => (*ident, DefKind::AssocTy, TypeNS),
402            AssocItemKind::MacCall(..) => {
403                self.visit_macro_invoc(i.id);
404                self.visit_assoc_item_mac_call(i, ctxt);
405                return;
406            }
407            AssocItemKind::DelegationMac(..) => {
408                ::rustc_middle::util::bug::span_bug_fmt(i.span,
    format_args!("degation mac invoc should have already been handled"))span_bug!(i.span, "degation mac invoc should have already been handled")
409            }
410        };
411
412        self.with_owner(i.id, Some(ident.name), def_kind, i.span, |this, feed| {
413            this.with_parent(feed.def_id(), |this| {
414                this.brg_visit_assoc_item(i, ctxt, ident, ns, feed)
415            });
416        })
417    }
418
419    fn visit_pat(&mut self, pat: &'a Pat) {
420        match pat.kind {
421            PatKind::MacCall(..) => {
422                self.visit_macro_invoc(pat.id);
423                self.visit_invoc(pat.id);
424            }
425            _ => visit::walk_pat(self, pat),
426        }
427    }
428
429    fn visit_anon_const(&mut self, constant: &'a AnonConst) {
430        let parent =
431            self.create_def(constant.id, None, DefKind::AnonConst, constant.value.span).def_id();
432        self.with_parent(parent, |this| visit::walk_anon_const(this, constant));
433    }
434
435    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("visit_expr",
                                    "rustc_resolve::def_collector", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/def_collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(435u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::def_collector"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expr");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/def_collector.rs:437",
                                    "rustc_resolve::def_collector", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_resolve/src/def_collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(437u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::def_collector"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self.invocation_parent")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self.invocation_parent");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.invocation_parent)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            match &expr.kind {
                ExprKind::MacCall(..) => {
                    self.visit_macro_invoc(expr.id);
                    self.visit_invoc(expr.id);
                }
                ExprKind::Closure(..) | ExprKind::Gen(..) => {
                    let def =
                        self.create_def(expr.id, None, DefKind::Closure,
                                expr.span).def_id();
                    self.with_parent(def, |this| visit::walk_expr(this, expr));
                }
                _ => visit::walk_expr(self, expr),
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
436    fn visit_expr(&mut self, expr: &'a Expr) {
437        debug!(?self.invocation_parent);
438
439        match &expr.kind {
440            ExprKind::MacCall(..) => {
441                self.visit_macro_invoc(expr.id);
442                self.visit_invoc(expr.id);
443            }
444            ExprKind::Closure(..) | ExprKind::Gen(..) => {
445                let def = self.create_def(expr.id, None, DefKind::Closure, expr.span).def_id();
446                self.with_parent(def, |this| visit::walk_expr(this, expr));
447            }
448            _ => visit::walk_expr(self, expr),
449        }
450    }
451
452    fn visit_ty(&mut self, ty: &'a Ty) {
453        match ty.kind {
454            TyKind::MacCall(..) => {
455                self.visit_macro_invoc(ty.id);
456                self.visit_invoc(ty.id);
457            }
458            TyKind::ImplTrait(opaque_id, _) => {
459                let name = *self
460                    .r
461                    .impl_trait_names
462                    .get(&ty.id)
463                    .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(ty.span,
    format_args!("expected this opaque to be named"))span_bug!(ty.span, "expected this opaque to be named"));
464                let kind = match self.invocation_parent.impl_trait_context {
465                    ImplTraitContext::Universal => DefKind::TyParam,
466                    ImplTraitContext::Existential => DefKind::OpaqueTy,
467                    ImplTraitContext::InBinding => return visit::walk_ty(self, ty),
468                };
469                let id = self.create_def(opaque_id, Some(name), kind, ty.span).def_id();
470                match self.invocation_parent.impl_trait_context {
471                    // Do not nest APIT, as we desugar them as `impl_trait: bounds`,
472                    // so the `impl_trait` node is not a parent to `bounds`.
473                    ImplTraitContext::Universal => visit::walk_ty(self, ty),
474                    ImplTraitContext::Existential => {
475                        self.with_parent(id, |this| visit::walk_ty(this, ty))
476                    }
477                    ImplTraitContext::InBinding => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
478                };
479            }
480            _ => visit::walk_ty(self, ty),
481        }
482    }
483
484    fn visit_stmt(&mut self, stmt: &'a Stmt) {
485        match stmt.kind {
486            StmtKind::MacCall(..) => {
487                self.brg_visit_mac_call_in_module(stmt.id);
488                self.visit_macro_invoc(stmt.id)
489            }
490            // FIXME(impl_trait_in_bindings): We don't really have a good way of
491            // introducing the right `ImplTraitContext` here for all the cases we
492            // care about, in case we want to introduce ITIB to other positions
493            // such as turbofishes (e.g. `foo::<impl Fn()>(|| {})`).
494            StmtKind::Let(ref local) => self.with_impl_trait(ImplTraitContext::InBinding, |this| {
495                visit::walk_local(this, local)
496            }),
497            _ => visit::walk_stmt(self, stmt),
498        }
499    }
500
501    fn visit_arm(&mut self, arm: &'a Arm) {
502        if arm.is_placeholder {
503            self.visit_macro_invoc(arm.id);
504            self.visit_invoc(arm.id);
505        } else {
506            visit::walk_arm(self, arm)
507        }
508    }
509
510    fn visit_expr_field(&mut self, f: &'a ExprField) {
511        if f.is_placeholder {
512            self.visit_macro_invoc(f.id);
513            self.visit_invoc(f.id);
514        } else {
515            visit::walk_expr_field(self, f)
516        }
517    }
518
519    fn visit_pat_field(&mut self, fp: &'a PatField) {
520        if fp.is_placeholder {
521            self.visit_macro_invoc(fp.id);
522            self.visit_invoc(fp.id);
523        } else {
524            visit::walk_pat_field(self, fp)
525        }
526    }
527
528    fn visit_param(&mut self, p: &'a Param) {
529        if p.is_placeholder {
530            self.visit_macro_invoc(p.id);
531            self.visit_invoc(p.id);
532        } else {
533            self.with_impl_trait(ImplTraitContext::Universal, |this| visit::walk_param(this, p))
534        }
535    }
536
537    // This method is called only when we are visiting an individual field
538    // after expanding an attribute on it.
539    fn visit_field_def(&mut self, field: &'a FieldDef) {
540        self.collect_field(field, None);
541    }
542
543    fn visit_crate(&mut self, krate: &'a Crate) {
544        if krate.is_placeholder {
545            self.visit_macro_invoc(krate.id);
546            self.visit_invoc_in_module(krate.id);
547        } else {
548            // Visit attributes after items for backward compatibility.
549            // This way they can use `macro_rules` defined later.
550
551            // We always have an invocation parent (set in `collect_definitions`)
552            // of at least the crate root, even for visiting the crate root,
553            // which would then remove the crate root from the tables
554            // list twice and try to insert it twice afterwards.
555            if true {
    {
        match (&self.r.current_owner.id, &CRATE_NODE_ID) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(self.r.current_owner.id, CRATE_NODE_ID);
556
557            for elem in &krate.items {
    match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_item(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};visit::walk_list!(self, visit_item, &krate.items);
558            for elem in &krate.attrs {
    match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_attribute(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};visit::walk_list!(self, visit_attribute, &krate.attrs);
559            self.contains_macro_use(&krate.attrs);
560        }
561    }
562
563    fn visit_attribute(&mut self, attr: &'a Attribute) {
564        use SyntheticAttr::*;
565        let orig_in_attr = mem::replace(&mut self.invocation_parent.in_attr, true);
566        match &attr.kind {
567            AttrKind::Normal(normal) => {
568                if attr::is_builtin_attr(&normal.item) {
569                    self.r
570                        .builtin_attrs
571                        .push((normal.item.path.segments[0].ident, self.parent_scope));
572                }
573            }
574            AttrKind::Synthetic(CfgTrace(_) | CfgAttrTrace(_)) => {}
575            AttrKind::DocComment(..) => {}
576        }
577        visit::walk_attribute(self, attr);
578        self.invocation_parent.in_attr = orig_in_attr;
579    }
580
581    fn visit_inline_asm(&mut self, asm: &'a InlineAsm) {
582        let InlineAsm {
583            asm_macro: _,
584            template: _,
585            template_strs: _,
586            operands,
587            clobber_abis: _,
588            options: _,
589            line_spans: _,
590        } = asm;
591        for (op, _span) in operands {
592            match op {
593                InlineAsmOperand::In { expr, reg: _ }
594                | InlineAsmOperand::Out { expr: Some(expr), reg: _, late: _ }
595                | InlineAsmOperand::InOut { expr, reg: _, late: _ } => {
596                    self.visit_expr(expr);
597                }
598                InlineAsmOperand::Out { expr: None, reg: _, late: _ } => {}
599                InlineAsmOperand::SplitInOut { in_expr, out_expr, reg: _, late: _ } => {
600                    self.visit_expr(in_expr);
601                    if let Some(expr) = out_expr {
602                        self.visit_expr(expr);
603                    }
604                }
605                InlineAsmOperand::Const { anon_const } => {
606                    let def = self
607                        .create_def(anon_const.id, None, DefKind::AnonConst, anon_const.value.span)
608                        .def_id();
609                    self.with_parent(def, |this| visit::walk_anon_const(this, anon_const));
610                }
611                InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
612                InlineAsmOperand::Label { block } => self.visit_block(block),
613            }
614        }
615    }
616}