Skip to main content

rustc_resolve/
def_collector.rs

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