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, OmitDoc, 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::span_bug;
14use rustc_middle::ty::{PerOwnerResolverData, TyCtxtFeed};
15use rustc_span::{Span, Symbol, sym};
16use tracing::{debug, instrument};
17
18use crate::macros::MacroRulesScopeRef;
19use crate::{
20    ImplTraitContext, InvocationParent, ParentScope, Resolver, with_owner, with_owner_tables,
21};
22
23pub(crate) fn collect_definitions<'ra>(
24    resolver: &mut Resolver<'ra, '_>,
25    fragment: &AstFragment,
26    parent_scope: ParentScope<'ra>,
27) -> MacroRulesScopeRef<'ra> {
28    let invocation_parent = resolver.invocation_parents[&parent_scope.expansion];
29    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/def_collector.rs:29",
                        "rustc_resolve::def_collector", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/def_collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(29u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("new fragment to visit with invocation_parent: {0:?}",
                                                    invocation_parent) as &dyn Value))])
            });
    } else { ; }
};debug!("new fragment to visit with invocation_parent: {invocation_parent:?}");
30    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);
31    with_owner(resolver, invocation_parent.owner, |r| {
32        let mut visitor = DefCollector { r, invocation_parent, parent_scope };
33        fragment.visit_with(&mut visitor);
34        visitor.parent_scope.macro_rules
35    })
36}
37
38/// Creates `DefId`s for nodes in the AST.
39pub(crate) struct DefCollector<'a, 'ra, 'tcx> {
40    pub(crate) r: &'a mut Resolver<'ra, 'tcx>,
41    invocation_parent: InvocationParent,
42    pub(crate) parent_scope: ParentScope<'ra>,
43}
44
45impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> {
46    pub(super) fn create_def(
47        &mut self,
48        node_id: NodeId,
49        name: Option<Symbol>,
50        def_kind: DefKind,
51        span: Span,
52    ) -> TyCtxtFeed<'tcx, LocalDefId> {
53        let parent_def = self.invocation_parent.parent_def;
54        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/def_collector.rs:54",
                        "rustc_resolve::def_collector", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/def_collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(54u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::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 Value))])
            });
    } else { ; }
};debug!(
55            "create_def(node_id={:?}, def_kind={:?}, parent_def={:?})",
56            node_id, def_kind, parent_def
57        );
58        self.r.create_def(
59            parent_def,
60            node_id,
61            name,
62            def_kind,
63            self.parent_scope.expansion.to_expn_id(),
64            span.with_parent(None),
65            false,
66        )
67    }
68
69    fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: LocalDefId, f: F) {
70        let orig_parent_def = mem::replace(&mut self.invocation_parent.parent_def, parent_def);
71        f(self);
72        self.invocation_parent.parent_def = orig_parent_def;
73    }
74
75    pub(super) fn with_owner<F: FnOnce(&mut Self, TyCtxtFeed<'tcx, LocalDefId>)>(
76        &mut self,
77        owner: NodeId,
78        name: Option<Symbol>,
79        def_kind: DefKind,
80        span: Span,
81        f: F,
82    ) {
83        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);
84        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);
85        // We only get here if the owner didn't exist yet. After the owner has been created,
86        // future invocations of `collect_definitions` will get the owner out of the `owners`
87        // table.
88        let parent_def = self.invocation_parent.parent_def;
89        let feed = self.r.create_def(
90            parent_def,
91            owner,
92            name,
93            def_kind,
94            self.parent_scope.expansion.to_expn_id(),
95            span.with_parent(None),
96            true,
97        );
98        let tables = PerOwnerResolverData::new(owner, feed.key());
99
100        let orig_invoc_owner = mem::replace(&mut self.invocation_parent.owner, owner);
101        with_owner_tables(self, owner, tables, |this| f(this, feed));
102        let old = mem::replace(&mut self.invocation_parent.owner, orig_invoc_owner);
103        {
    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);
104    }
105
106    fn with_impl_trait<F: FnOnce(&mut Self)>(
107        &mut self,
108        impl_trait_context: ImplTraitContext,
109        f: F,
110    ) {
111        let orig_itc =
112            mem::replace(&mut self.invocation_parent.impl_trait_context, impl_trait_context);
113        f(self);
114        self.invocation_parent.impl_trait_context = orig_itc;
115    }
116
117    fn collect_field(&mut self, field: &'a FieldDef, index: Option<usize>) {
118        let index = |this: &Self| {
119            index.unwrap_or_else(|| {
120                let node_id = NodeId::placeholder_from_expn_id(this.parent_scope.expansion);
121                this.r.placeholder_field_indices[&node_id]
122            })
123        };
124
125        if field.is_placeholder {
126            let old_index = self.r.placeholder_field_indices.insert(field.id, index(self));
127            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");
128            self.visit_macro_invoc(field.id);
129            self.visit_invoc(field.id);
130        } else {
131            let name = field.ident.map_or_else(|| sym::integer(index(self)), |ident| ident.name);
132            let def = self.create_def(field.id, Some(name), DefKind::Field, field.span);
133            self.with_parent(def.def_id(), |this| this.brg_visit_field_def(field, def));
134        }
135    }
136
137    #[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("compiler/rustc_resolve/src/def_collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(137u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::def_collector"),
                                    ::tracing_core::field::FieldSet::new(&["id"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn 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 compiler/rustc_resolve/src/def_collector.rs:139",
                                    "rustc_resolve::def_collector", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/def_collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(139u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::def_collector"),
                                    ::tracing_core::field::FieldSet::new(&["self.invocation_parent"],
                                        ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&self.invocation_parent)
                                                        as &dyn 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))]
138    fn visit_macro_invoc(&mut self, id: NodeId) {
139        debug!(?self.invocation_parent);
140
141        let id = id.placeholder_to_expn_id();
142        let old_parent = self.r.invocation_parents.insert(id, self.invocation_parent);
143        assert!(old_parent.is_none(), "parent `LocalDefId` is reset for an invocation");
144    }
145}
146
147impl<'a, 'ra, 'tcx> visit::Visitor<'a> for DefCollector<'a, 'ra, 'tcx> {
148    fn visit_item(&mut self, i: &'a Item) {
149        // Pick the def data. This need not be unique, but the more
150        // information we encapsulate into, the better
151        let mut opt_syn_ext = None;
152        let def_kind = match &i.kind {
153            ItemKind::Impl(i) => DefKind::Impl { of_trait: i.of_trait.is_some() },
154            ItemKind::ForeignMod(..) => DefKind::ForeignMod,
155            ItemKind::Mod(..) => DefKind::Mod,
156            ItemKind::Trait(..) => DefKind::Trait,
157            ItemKind::TraitAlias(..) => DefKind::TraitAlias,
158            ItemKind::Enum(..) => DefKind::Enum,
159            ItemKind::Struct(..) => DefKind::Struct,
160            ItemKind::Union(..) => DefKind::Union,
161            ItemKind::ExternCrate(..) => DefKind::ExternCrate,
162            ItemKind::TyAlias(..) => DefKind::TyAlias,
163            ItemKind::Static(s) => DefKind::Static {
164                safety: hir::Safety::Safe,
165                mutability: s.mutability,
166                nested: false,
167            },
168            ItemKind::Const(citem) => {
169                let is_type_const = #[allow(non_exhaustive_omitted_patterns)] match citem.rhs_kind {
    ConstItemRhsKind::TypeConst { .. } => true,
    _ => false,
}matches!(citem.rhs_kind, ConstItemRhsKind::TypeConst { .. });
170                DefKind::Const { is_type_const }
171            }
172            ItemKind::ConstBlock(..) => DefKind::Const { is_type_const: false },
173            ItemKind::Fn(..) | ItemKind::Delegation(..) => DefKind::Fn,
174            ItemKind::MacroDef(ident, def) => {
175                let edition = i.span.edition();
176
177                // FIXME(jdonszelmann) make one of these in the resolver?
178                // FIXME(jdonszelmann) don't care about tools here maybe? Just parse what we can.
179                // Does that prevents errors from happening? maybe
180                let mut parser = AttributeParser::new(
181                    &self.r.tcx.sess,
182                    self.r.features,
183                    self.r.tcx().registered_tools(()),
184                    ShouldEmit::Nothing,
185                );
186                let attrs = parser.parse_attribute_list(
187                    &i.attrs,
188                    i.span,
189                    Target::MacroDef,
190                    OmitDoc::Skip,
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        };
217        self.with_owner(
218            i.id,
219            i.kind.ident().map(|ident| ident.name),
220            def_kind,
221            i.span,
222            |this, feed| {
223                if let Some(ext) = opt_syn_ext {
224                    this.r.local_macro_map.insert(feed.def_id(), self.r.arenas.alloc_macro(ext));
225                }
226
227                this.with_parent(feed.def_id(), |this| {
228                    this.with_impl_trait(ImplTraitContext::Existential, |this| {
229                        this.brg_visit_item(i, feed)
230                    })
231                });
232            },
233        );
234    }
235
236    fn visit_block(&mut self, block: &'a Block) {
237        self.brg_visit_block(block);
238    }
239
240    fn visit_fn(&mut self, fn_kind: FnKind<'a>, _: &AttrVec, span: Span, _: NodeId) {
241        match fn_kind {
242            FnKind::Fn(
243                ctxt,
244                _vis,
245                Fn {
246                    sig: FnSig { header, decl, span: _ }, ident, generics, contract, body, ..
247                },
248            ) if let Some(coroutine_kind) = header.coroutine_kind
249                // Foreign ones are denied, so don't create them here.
250                && ctxt != visit::FnCtxt::Foreign =>
251            {
252                self.visit_ident(ident);
253                self.visit_fn_header(header);
254                self.visit_generics(generics);
255                if let Some(contract) = contract {
256                    self.visit_contract(contract);
257                }
258
259                // For async functions, we need to create their inner defs inside of a
260                // closure to match their desugared representation. Besides that,
261                // we must mirror everything that `visit::walk_fn` below does.
262                let FnDecl { inputs, output } = &**decl;
263                for param in inputs {
264                    self.visit_param(param);
265                }
266
267                let (return_id, return_span) = coroutine_kind.return_id();
268                let return_def =
269                    self.create_def(return_id, None, DefKind::OpaqueTy, return_span).def_id();
270                self.with_parent(return_def, |this| this.visit_fn_ret_ty(output));
271
272                // If this async fn has no body (i.e. it's an async fn signature in a trait)
273                // then the closure_def will never be used, and we should avoid generating a
274                // def-id for it.
275                if let Some(body) = body {
276                    let closure_def = self
277                        .create_def(coroutine_kind.closure_id(), None, DefKind::Closure, span)
278                        .def_id();
279                    self.with_parent(closure_def, |this| this.visit_block(body));
280                }
281            }
282            FnKind::Closure(binder, Some(coroutine_kind), decl, body) => {
283                self.visit_closure_binder(binder);
284                visit::walk_fn_decl(self, decl);
285
286                // Async closures desugar to closures inside of closures, so
287                // we must create two defs.
288                let coroutine_def = self
289                    .create_def(coroutine_kind.closure_id(), None, DefKind::Closure, span)
290                    .def_id();
291                self.with_parent(coroutine_def, |this| this.visit_expr(body));
292            }
293            _ => visit::walk_fn(self, fn_kind),
294        }
295    }
296
297    fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
298        let (ident, def_kind) = match fi.kind {
299            ForeignItemKind::Static(StaticItem {
300                ident,
301                ty: _,
302                mutability,
303                expr: _,
304                safety,
305                define_opaque: _,
306                eii_impls: _,
307            }) => {
308                let safety = match safety {
309                    ast::Safety::Unsafe(_) | ast::Safety::Default => hir::Safety::Unsafe,
310                    ast::Safety::Safe(_) => hir::Safety::Safe,
311                };
312
313                (ident, DefKind::Static { safety, mutability, nested: false })
314            }
315            ForeignItemKind::Fn(Fn { ident, .. }) => (ident, DefKind::Fn),
316            ForeignItemKind::TyAlias(TyAlias { ident, .. }) => (ident, DefKind::ForeignTy),
317            ForeignItemKind::MacCall(_) => {
318                self.visit_invoc_in_module(fi.id);
319                self.visit_macro_invoc(fi.id);
320                return;
321            }
322        };
323
324        self.with_owner(fi.id, Some(ident.name), def_kind, fi.span, |this, def| {
325            this.with_parent(def.def_id(), |this| {
326                this.build_reduced_graph_for_foreign_item(fi, ident, def);
327                visit::walk_item(this, fi)
328            });
329        })
330    }
331
332    fn visit_variant(&mut self, v: &'a Variant) {
333        if v.is_placeholder {
334            self.visit_macro_invoc(v.id);
335            self.visit_invoc_in_module(v.id);
336            return;
337        }
338        let feed = self.create_def(v.id, Some(v.ident.name), DefKind::Variant, v.span);
339        self.with_parent(feed.def_id(), |this| this.brg_visit_variant(v, feed));
340    }
341
342    fn visit_where_predicate(&mut self, pred: &'a WherePredicate) {
343        if pred.is_placeholder {
344            self.visit_macro_invoc(pred.id);
345            self.visit_invoc(pred.id);
346        } else {
347            visit::walk_where_predicate(self, pred)
348        }
349    }
350
351    fn visit_variant_data(&mut self, data: &'a VariantData) {
352        // The assumption here is that non-`cfg` macro expansion cannot change field indices.
353        // It currently holds because only inert attributes are accepted on fields,
354        // and every such attribute expands into a single field after it's resolved.
355        for (index, field) in data.fields().iter().enumerate() {
356            self.collect_field(field, Some(index));
357        }
358    }
359
360    fn visit_generic_param(&mut self, param: &'a GenericParam) {
361        if param.is_placeholder {
362            self.visit_macro_invoc(param.id);
363            self.visit_invoc(param.id);
364            return;
365        }
366        let def_kind = match param.kind {
367            GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
368            GenericParamKind::Type { .. } => DefKind::TyParam,
369            GenericParamKind::Const { .. } => DefKind::ConstParam,
370        };
371        self.create_def(param.id, Some(param.ident.name), def_kind, param.ident.span);
372
373        // impl-Trait can happen inside generic parameters, like
374        // ```
375        // fn foo<U: Iterator<Item = impl Clone>>() {}
376        // ```
377        //
378        // In that case, the impl-trait is lowered as an additional generic parameter.
379        self.with_impl_trait(ImplTraitContext::Universal, |this| {
380            visit::walk_generic_param(this, param)
381        });
382    }
383
384    fn visit_assoc_item(&mut self, i: &'a AssocItem, ctxt: visit::AssocCtxt) {
385        let (ident, def_kind, ns) = match &i.kind {
386            AssocItemKind::Fn(Fn { ident, .. })
387            | AssocItemKind::Delegation(Delegation { ident, .. }) => {
388                (*ident, DefKind::AssocFn, ValueNS)
389            }
390            AssocItemKind::Const(ConstItem { ident, rhs_kind, .. }) => (
391                *ident,
392                DefKind::AssocConst {
393                    is_type_const: #[allow(non_exhaustive_omitted_patterns)] match rhs_kind {
    ConstItemRhsKind::TypeConst { .. } => true,
    _ => false,
}matches!(rhs_kind, ConstItemRhsKind::TypeConst { .. }),
394                },
395                ValueNS,
396            ),
397            AssocItemKind::Type(TyAlias { ident, .. }) => (*ident, DefKind::AssocTy, TypeNS),
398            AssocItemKind::MacCall(..) => {
399                self.visit_macro_invoc(i.id);
400                self.visit_assoc_item_mac_call(i, ctxt);
401                return;
402            }
403            AssocItemKind::DelegationMac(..) => {
404                ::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")
405            }
406        };
407
408        self.with_owner(i.id, Some(ident.name), def_kind, i.span, |this, feed| {
409            this.with_parent(feed.def_id(), |this| {
410                this.brg_visit_assoc_item(i, ctxt, ident, ns, feed)
411            });
412        })
413    }
414
415    fn visit_pat(&mut self, pat: &'a Pat) {
416        match pat.kind {
417            PatKind::MacCall(..) => {
418                self.visit_macro_invoc(pat.id);
419                self.visit_invoc(pat.id);
420            }
421            _ => visit::walk_pat(self, pat),
422        }
423    }
424
425    fn visit_anon_const(&mut self, constant: &'a AnonConst) {
426        // Note that `visit_anon_const` is skipped for AnonConst nodes wrapped in an
427        // ExprKind::ConstBlock - these are handled in visit_expr, and are DefKind::InlineConst.
428
429        // `MgcaDisambiguation::Direct` is set even when MGCA is disabled, so
430        // to avoid affecting stable we have to feature gate the not creating
431        // anon consts
432        if !self.r.features.min_generic_const_args() {
433            let parent = self
434                .create_def(constant.id, None, DefKind::AnonConst, constant.value.span)
435                .def_id();
436            return self.with_parent(parent, |this| visit::walk_anon_const(this, constant));
437        }
438
439        match constant.mgca_disambiguation {
440            MgcaDisambiguation::Direct => visit::walk_anon_const(self, constant),
441            MgcaDisambiguation::AnonConst => {
442                let parent = self
443                    .create_def(constant.id, None, DefKind::AnonConst, constant.value.span)
444                    .def_id();
445                self.with_parent(parent, |this| visit::walk_anon_const(this, constant));
446            }
447        };
448    }
449
450    #[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("compiler/rustc_resolve/src/def_collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(450u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::def_collector"),
                                    ::tracing_core::field::FieldSet::new(&["expr"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
                                                            as &dyn 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 compiler/rustc_resolve/src/def_collector.rs:452",
                                    "rustc_resolve::def_collector", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/def_collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(452u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::def_collector"),
                                    ::tracing_core::field::FieldSet::new(&["self.invocation_parent"],
                                        ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&self.invocation_parent)
                                                        as &dyn 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));
                }
                ExprKind::ConstBlock(constant) => {
                    for attr in &expr.attrs {
                        visit::walk_attribute(self, attr);
                    }
                    let def =
                        self.create_def(constant.id, None, DefKind::InlineConst,
                                constant.value.span).def_id();
                    self.with_parent(def,
                        |this| visit::walk_anon_const(this, constant));
                }
                _ => visit::walk_expr(self, expr),
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
451    fn visit_expr(&mut self, expr: &'a Expr) {
452        debug!(?self.invocation_parent);
453
454        match &expr.kind {
455            ExprKind::MacCall(..) => {
456                self.visit_macro_invoc(expr.id);
457                self.visit_invoc(expr.id);
458            }
459            ExprKind::Closure(..) | ExprKind::Gen(..) => {
460                let def = self.create_def(expr.id, None, DefKind::Closure, expr.span).def_id();
461                self.with_parent(def, |this| visit::walk_expr(this, expr));
462            }
463            ExprKind::ConstBlock(constant) => {
464                for attr in &expr.attrs {
465                    visit::walk_attribute(self, attr);
466                }
467
468                let def = self
469                    .create_def(constant.id, None, DefKind::InlineConst, constant.value.span)
470                    .def_id();
471                // use specifically walk_anon_const, not walk_expr, to skip self.visit_anon_const
472                self.with_parent(def, |this| visit::walk_anon_const(this, constant));
473            }
474            _ => visit::walk_expr(self, expr),
475        }
476    }
477
478    fn visit_ty(&mut self, ty: &'a Ty) {
479        match ty.kind {
480            TyKind::MacCall(..) => {
481                self.visit_macro_invoc(ty.id);
482                self.visit_invoc(ty.id);
483            }
484            TyKind::ImplTrait(opaque_id, _) => {
485                let name = *self
486                    .r
487                    .impl_trait_names
488                    .get(&ty.id)
489                    .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"));
490                let kind = match self.invocation_parent.impl_trait_context {
491                    ImplTraitContext::Universal => DefKind::TyParam,
492                    ImplTraitContext::Existential => DefKind::OpaqueTy,
493                    ImplTraitContext::InBinding => return visit::walk_ty(self, ty),
494                };
495                let id = self.create_def(opaque_id, Some(name), kind, ty.span).def_id();
496                match self.invocation_parent.impl_trait_context {
497                    // Do not nest APIT, as we desugar them as `impl_trait: bounds`,
498                    // so the `impl_trait` node is not a parent to `bounds`.
499                    ImplTraitContext::Universal => visit::walk_ty(self, ty),
500                    ImplTraitContext::Existential => {
501                        self.with_parent(id, |this| visit::walk_ty(this, ty))
502                    }
503                    ImplTraitContext::InBinding => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
504                };
505            }
506            _ => visit::walk_ty(self, ty),
507        }
508    }
509
510    fn visit_stmt(&mut self, stmt: &'a Stmt) {
511        match stmt.kind {
512            StmtKind::MacCall(..) => {
513                self.brg_visit_mac_call_in_module(stmt.id);
514                self.visit_macro_invoc(stmt.id)
515            }
516            // FIXME(impl_trait_in_bindings): We don't really have a good way of
517            // introducing the right `ImplTraitContext` here for all the cases we
518            // care about, in case we want to introduce ITIB to other positions
519            // such as turbofishes (e.g. `foo::<impl Fn()>(|| {})`).
520            StmtKind::Let(ref local) => self.with_impl_trait(ImplTraitContext::InBinding, |this| {
521                visit::walk_local(this, local)
522            }),
523            _ => visit::walk_stmt(self, stmt),
524        }
525    }
526
527    fn visit_arm(&mut self, arm: &'a Arm) {
528        if arm.is_placeholder {
529            self.visit_macro_invoc(arm.id);
530            self.visit_invoc(arm.id);
531        } else {
532            visit::walk_arm(self, arm)
533        }
534    }
535
536    fn visit_expr_field(&mut self, f: &'a ExprField) {
537        if f.is_placeholder {
538            self.visit_macro_invoc(f.id);
539            self.visit_invoc(f.id);
540        } else {
541            visit::walk_expr_field(self, f)
542        }
543    }
544
545    fn visit_pat_field(&mut self, fp: &'a PatField) {
546        if fp.is_placeholder {
547            self.visit_macro_invoc(fp.id);
548            self.visit_invoc(fp.id);
549        } else {
550            visit::walk_pat_field(self, fp)
551        }
552    }
553
554    fn visit_param(&mut self, p: &'a Param) {
555        if p.is_placeholder {
556            self.visit_macro_invoc(p.id);
557            self.visit_invoc(p.id);
558        } else {
559            self.with_impl_trait(ImplTraitContext::Universal, |this| visit::walk_param(this, p))
560        }
561    }
562
563    // This method is called only when we are visiting an individual field
564    // after expanding an attribute on it.
565    fn visit_field_def(&mut self, field: &'a FieldDef) {
566        self.collect_field(field, None);
567    }
568
569    fn visit_crate(&mut self, krate: &'a Crate) {
570        if krate.is_placeholder {
571            self.visit_macro_invoc(krate.id);
572            self.visit_invoc_in_module(krate.id);
573        } else {
574            // Visit attributes after items for backward compatibility.
575            // This way they can use `macro_rules` defined later.
576
577            // We always have an invocation parent (set in `collect_definitions`)
578            // of at least the crate root, even for visiting the crate root,
579            // which would then remove the crate root from the tables
580            // list twice and try to insert it twice afterwards.
581            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);
582
583            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);
584            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);
585            self.contains_macro_use(&krate.attrs);
586        }
587    }
588
589    fn visit_attribute(&mut self, attr: &'a Attribute) {
590        let orig_in_attr = mem::replace(&mut self.invocation_parent.in_attr, true);
591        if !attr.is_doc_comment() && attr::is_builtin_attr(attr) {
592            self.r
593                .builtin_attrs
594                .push((attr.get_normal_item().path.segments[0].ident, self.parent_scope));
595        }
596        visit::walk_attribute(self, attr);
597        self.invocation_parent.in_attr = orig_in_attr;
598    }
599
600    fn visit_inline_asm(&mut self, asm: &'a InlineAsm) {
601        let InlineAsm {
602            asm_macro: _,
603            template: _,
604            template_strs: _,
605            operands,
606            clobber_abis: _,
607            options: _,
608            line_spans: _,
609        } = asm;
610        for (op, _span) in operands {
611            match op {
612                InlineAsmOperand::In { expr, reg: _ }
613                | InlineAsmOperand::Out { expr: Some(expr), reg: _, late: _ }
614                | InlineAsmOperand::InOut { expr, reg: _, late: _ } => {
615                    self.visit_expr(expr);
616                }
617                InlineAsmOperand::Out { expr: None, reg: _, late: _ } => {}
618                InlineAsmOperand::SplitInOut { in_expr, out_expr, reg: _, late: _ } => {
619                    self.visit_expr(in_expr);
620                    if let Some(expr) = out_expr {
621                        self.visit_expr(expr);
622                    }
623                }
624                InlineAsmOperand::Const { anon_const } => {
625                    let def = self
626                        .create_def(
627                            anon_const.id,
628                            None,
629                            DefKind::InlineConst,
630                            anon_const.value.span,
631                        )
632                        .def_id();
633                    self.with_parent(def, |this| visit::walk_anon_const(this, anon_const));
634                }
635                InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
636                InlineAsmOperand::Label { block } => self.visit_block(block),
637            }
638        }
639    }
640}