Skip to main content

rustc_resolve/
build_reduced_graph.rs

1//! After we obtain a fresh AST fragment from a macro, code in this module helps to integrate
2//! that fragment into the module structures that are already partially built.
3//!
4//! Items from the fragment are placed into modules,
5//! unexpanded macros in the fragment are visited and registered.
6//! Imports are also considered items and placed into modules here, but not resolved yet.
7
8use std::sync::Arc;
9
10use rustc_ast::visit::{self, AssocCtxt, Visitor, WalkItemKind};
11use rustc_ast::{
12    self as ast, AssocItem, AssocItemKind, Block, ConstItem, DUMMY_NODE_ID, Delegation, Fn,
13    ForeignItem, ForeignItemKind, Inline, Item, ItemKind, NodeId, StaticItem, StmtKind, TraitAlias,
14    TyAlias,
15};
16use rustc_attr_parsing::AttributeParser;
17use rustc_expand::base::{ResolverExpand, SyntaxExtension, SyntaxExtensionKind};
18use rustc_hir::Attribute;
19use rustc_hir::attrs::{AttributeKind, MacroUseArgs};
20use rustc_hir::def::{self, *};
21use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId};
22use rustc_index::bit_set::DenseBitSet;
23use rustc_metadata::creader::LoadedMacro;
24use rustc_middle::metadata::{ModChild, Reexport};
25use rustc_middle::ty::{TyCtxtFeed, Visibility};
26use rustc_middle::{bug, span_bug};
27use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind};
28use rustc_span::{Ident, Span, Symbol, kw, sym};
29use thin_vec::ThinVec;
30use tracing::debug;
31
32use crate::Namespace::{MacroNS, TypeNS, ValueNS};
33use crate::def_collector::DefCollector;
34use crate::diagnostics::StructCtor;
35use crate::imports::{ImportData, ImportKind, OnUnknownData};
36use crate::macros::{MacroRulesDecl, MacroRulesScope, MacroRulesScopeRef};
37use crate::ref_mut::CmCell;
38use crate::{
39    BindingKey, Decl, DeclData, DeclKind, DelayedVisResolutionError, ExternModule,
40    ExternPreludeEntry, Finalize, IdentKey, LocalModule, Module, ModuleKind, ModuleOrUniformRoot,
41    ParentScope, PathResult, Res, Resolver, Segment, Used, VisResolutionError, errors,
42};
43
44impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
45    /// Attempt to put the declaration with the given name and namespace into the module,
46    /// and report an error in case of a collision.
47    pub(crate) fn plant_decl_into_local_module(
48        &mut self,
49        ident: IdentKey,
50        orig_ident_span: Span,
51        ns: Namespace,
52        decl: Decl<'ra>,
53    ) {
54        if let Err(old_decl) =
55            self.try_plant_decl_into_local_module(ident, orig_ident_span, ns, decl, false)
56        {
57            self.report_conflict(ident, ns, old_decl, decl);
58        }
59    }
60
61    /// Create a name definition from the given components, and put it into the local module.
62    fn define_local(
63        &mut self,
64        parent: LocalModule<'ra>,
65        orig_ident: Ident,
66        ns: Namespace,
67        res: Res,
68        vis: Visibility,
69        span: Span,
70        expn_id: LocalExpnId,
71    ) {
72        let decl =
73            self.arenas.new_def_decl(res, vis.to_def_id(), span, expn_id, Some(parent.to_module()));
74        let ident = IdentKey::new(orig_ident);
75        self.plant_decl_into_local_module(ident, orig_ident.span, ns, decl);
76    }
77
78    /// Create a name definition from the given components, and put it into the extern module.
79    fn define_extern(
80        &self,
81        parent: ExternModule<'ra>,
82        ident: IdentKey,
83        orig_ident_span: Span,
84        ns: Namespace,
85        child_index: usize,
86        res: Res,
87        vis: Visibility<DefId>,
88        span: Span,
89        expansion: LocalExpnId,
90        ambiguity: Option<Decl<'ra>>,
91    ) {
92        let decl = self.arenas.alloc_decl(DeclData {
93            kind: DeclKind::Def(res),
94            ambiguity: CmCell::new(ambiguity),
95            // External ambiguities always report the `AMBIGUOUS_GLOB_IMPORTS` lint at the moment.
96            warn_ambiguity: CmCell::new(true),
97            initial_vis: vis,
98            ambiguity_vis_max: CmCell::new(None),
99            ambiguity_vis_min: CmCell::new(None),
100            span,
101            expansion,
102            parent_module: Some(parent.to_module()),
103        });
104        // Even if underscore names cannot be looked up, we still need to add them to modules,
105        // because they can be fetched by glob imports from those modules, and bring traits
106        // into scope both directly and through glob imports.
107        let key =
108            BindingKey::new_disambiguated(ident, ns, || (child_index + 1).try_into().unwrap()); // 0 indicates no underscore
109        if self
110            .resolution_or_default(parent.to_module(), key, orig_ident_span)
111            .borrow_mut_unchecked()
112            .non_glob_decl
113            .replace(decl)
114            .is_some()
115        {
116            ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("an external binding was already defined"));span_bug!(span, "an external binding was already defined");
117        }
118    }
119
120    /// Walks up the tree of definitions starting at `def_id`,
121    /// stopping at the first encountered module.
122    /// Parent block modules for arbitrary def-ids are not recorded for the local crate,
123    /// and are not preserved in metadata for foreign crates, so block modules are never
124    /// returned by this function.
125    ///
126    /// For the local crate ignoring block modules may be incorrect, so use this method with care.
127    ///
128    /// For foreign crates block modules can be ignored without introducing observable differences,
129    /// moreover they has to be ignored right now because they are not kept in metadata.
130    /// Foreign parent modules are used for resolving names used by foreign macros with def-site
131    /// hygiene, therefore block module ignorability relies on macros with def-site hygiene and
132    /// block module parents being unreachable from other crates.
133    /// Reachable macros with block module parents exist due to `#[macro_export] macro_rules!`,
134    /// but they cannot use def-site hygiene, so the assumption holds
135    /// (<https://github.com/rust-lang/rust/pull/77984#issuecomment-712445508>).
136    pub(crate) fn get_nearest_non_block_module(&self, mut def_id: DefId) -> Module<'ra> {
137        loop {
138            match self.get_module(def_id) {
139                Some(module) => return module,
140                None => def_id = self.tcx.parent(def_id),
141            }
142        }
143    }
144
145    pub(crate) fn expect_module(&self, def_id: DefId) -> Module<'ra> {
146        self.get_module(def_id).expect("argument `DefId` is not a module")
147    }
148
149    /// If `def_id` refers to a module (in resolver's sense, i.e. a module item, crate root, enum,
150    /// or trait), then this function returns that module's resolver representation, otherwise it
151    /// returns `None`.
152    pub(crate) fn get_module(&self, def_id: DefId) -> Option<Module<'ra>> {
153        match def_id.as_local() {
154            Some(local_def_id) => self.local_module_map.get(&local_def_id).map(|m| m.to_module()),
155            None => {
156                if let module @ Some(..) = self.extern_module_map.borrow().get(&def_id) {
157                    return module.map(|m| m.to_module());
158                }
159
160                // Query `def_kind` is not used because query system overhead is too expensive here.
161                let def_kind = self.cstore().def_kind_untracked(def_id);
162                if def_kind.is_module_like() {
163                    let parent = self.tcx.opt_parent(def_id).map(|parent_id| {
164                        self.get_nearest_non_block_module(parent_id).expect_extern()
165                    });
166                    // Query `expn_that_defined` is not used because
167                    // hashing spans in its result is expensive.
168                    let expn_id = self.cstore().expn_that_defined_untracked(self.tcx, def_id);
169                    let module = self.new_extern_module(
170                        parent,
171                        ModuleKind::Def(
172                            def_kind,
173                            def_id,
174                            DUMMY_NODE_ID,
175                            Some(self.tcx.item_name(def_id)),
176                        ),
177                        expn_id,
178                        self.def_span(def_id),
179                        // FIXME: Account for `#[no_implicit_prelude]` attributes.
180                        parent.is_some_and(|module| module.no_implicit_prelude),
181                    );
182                    return Some(module.to_module());
183                }
184
185                None
186            }
187        }
188    }
189
190    pub(crate) fn expn_def_scope(&self, expn_id: ExpnId) -> Module<'ra> {
191        match expn_id.expn_data().macro_def_id {
192            Some(def_id) => self.macro_def_scope(def_id),
193            None => expn_id
194                .as_local()
195                .and_then(|expn_id| self.ast_transform_scopes.get(&expn_id).copied())
196                .unwrap_or(self.graph_root)
197                .to_module(),
198        }
199    }
200
201    pub(crate) fn macro_def_scope(&self, def_id: DefId) -> Module<'ra> {
202        if let Some(id) = def_id.as_local() {
203            self.local_macro_def_scopes[&id].to_module()
204        } else {
205            self.get_nearest_non_block_module(def_id)
206        }
207    }
208
209    /// Gets the `SyntaxExtension` corresponding to `res`.
210    pub(crate) fn get_macro(&self, res: Res) -> Option<&'ra Arc<SyntaxExtension>> {
211        match res {
212            Res::Def(DefKind::Macro(..), def_id) => Some(self.get_macro_by_def_id(def_id)),
213            Res::NonMacroAttr(_) => Some(self.non_macro_attr),
214            _ => None,
215        }
216    }
217
218    pub(crate) fn get_macro_by_def_id(&self, def_id: DefId) -> &'ra Arc<SyntaxExtension> {
219        // Local macros are always compiled.
220        match def_id.as_local() {
221            Some(local_def_id) => self.local_macro_map[&local_def_id],
222            None => self.extern_macro_map.borrow_mut().entry(def_id).or_insert_with(|| {
223                let loaded_macro = self.cstore().load_macro_untracked(self.tcx, def_id);
224                let ext = match loaded_macro {
225                    LoadedMacro::MacroDef { def, ident, attrs, span, edition } => {
226                        self.compile_macro(&def, ident, &attrs, span, ast::DUMMY_NODE_ID, edition)
227                    }
228                    LoadedMacro::ProcMacro(ext) => ext,
229                };
230
231                self.arenas.alloc_macro(ext)
232            }),
233        }
234    }
235
236    /// Add every proc macro accessible from the current crate to the `macro_map` so diagnostics can
237    /// find them for suggestions.
238    pub(crate) fn register_macros_for_all_crates(&mut self) {
239        if !self.all_crate_macros_already_registered {
240            for def_id in self.cstore().all_proc_macro_def_ids(self.tcx) {
241                self.get_macro_by_def_id(def_id);
242            }
243            self.all_crate_macros_already_registered = true;
244        }
245    }
246
247    pub(crate) fn try_resolve_visibility(
248        &mut self,
249        parent_scope: &ParentScope<'ra>,
250        vis: &ast::Visibility,
251        finalize: bool,
252    ) -> Result<Visibility, VisResolutionError> {
253        match vis.kind {
254            ast::VisibilityKind::Public => Ok(Visibility::Public),
255            ast::VisibilityKind::Inherited => {
256                Ok(match parent_scope.module.expect_local().kind {
257                    // Any inherited visibility resolved directly inside an enum or trait
258                    // (i.e. variants, fields, and trait items) inherits from the visibility
259                    // of the enum or trait.
260                    ModuleKind::Def(DefKind::Enum | DefKind::Trait, def_id, _, _) => {
261                        self.tcx.visibility(def_id).expect_local()
262                    }
263                    // Otherwise, the visibility is restricted to the nearest parent `mod` item.
264                    _ => Visibility::Restricted(
265                        parent_scope.module.nearest_parent_mod().expect_local(),
266                    ),
267                })
268            }
269            ast::VisibilityKind::Restricted { ref path, id, .. } => {
270                // For visibilities we are not ready to provide correct implementation of "uniform
271                // paths" right now, so on 2018 edition we only allow module-relative paths for now.
272                // On 2015 edition visibilities are resolved as crate-relative by default,
273                // so we are prepending a root segment if necessary.
274                let ident = path.segments.get(0).expect("empty path in visibility").ident;
275                let crate_root = if ident.is_path_segment_keyword() {
276                    None
277                } else if ident.span.is_rust_2015() {
278                    Some(Segment::from_ident(Ident::new(
279                        kw::PathRoot,
280                        path.span.shrink_to_lo().with_ctxt(ident.span.ctxt()),
281                    )))
282                } else {
283                    return Err(VisResolutionError::Relative2018(
284                        ident.span,
285                        path.as_ref().clone(),
286                    ));
287                };
288                let segments = crate_root
289                    .into_iter()
290                    .chain(path.segments.iter().map(|seg| seg.into()))
291                    .collect::<Vec<_>>();
292                let expected_found_error = |res| {
293                    Err(VisResolutionError::ExpectedFound(
294                        path.span,
295                        Segment::names_to_string(&segments),
296                        res,
297                    ))
298                };
299                match self.cm().resolve_path(
300                    &segments,
301                    None,
302                    parent_scope,
303                    finalize.then(|| Finalize::new(id, path.span)),
304                    None,
305                    None,
306                ) {
307                    PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
308                        let res = module.res().expect("visibility resolved to unnamed block");
309                        if module.is_normal() {
310                            match res {
311                                Res::Err => {
312                                    if finalize {
313                                        self.record_partial_res(id, PartialRes::new(res));
314                                    }
315                                    Ok(Visibility::Public)
316                                }
317                                _ => {
318                                    let vis = Visibility::Restricted(res.def_id());
319                                    if self.is_accessible_from(vis, parent_scope.module) {
320                                        if finalize {
321                                            self.record_partial_res(id, PartialRes::new(res));
322                                        }
323                                        Ok(vis.expect_local())
324                                    } else {
325                                        Err(VisResolutionError::AncestorOnly(path.span))
326                                    }
327                                }
328                            }
329                        } else {
330                            expected_found_error(res)
331                        }
332                    }
333                    PathResult::Module(..) => Err(VisResolutionError::ModuleOnly(path.span)),
334                    PathResult::NonModule(partial_res) => {
335                        expected_found_error(partial_res.expect_full_res())
336                    }
337                    PathResult::Failed {
338                        span, label, suggestion, message, segment_name, ..
339                    } => Err(VisResolutionError::FailedToResolve(
340                        span,
341                        segment_name,
342                        label,
343                        suggestion,
344                        message,
345                    )),
346                    PathResult::Indeterminate => Err(VisResolutionError::Indeterminate(path.span)),
347                }
348            }
349        }
350    }
351
352    pub(crate) fn build_reduced_graph_external(&self, module: ExternModule<'ra>) {
353        let def_id = module.def_id();
354        let children = self.tcx.module_children(def_id);
355        for (i, child) in children.iter().enumerate() {
356            self.build_reduced_graph_for_external_crate_res(child, module, i, None)
357        }
358        for (i, child) in
359            self.cstore().ambig_module_children_untracked(self.tcx, def_id).enumerate()
360        {
361            self.build_reduced_graph_for_external_crate_res(
362                &child.main,
363                module,
364                children.len() + i,
365                Some(&child.second),
366            )
367        }
368    }
369
370    /// Builds the reduced graph for a single item in an external crate.
371    fn build_reduced_graph_for_external_crate_res(
372        &self,
373        child: &ModChild,
374        parent: ExternModule<'ra>,
375        child_index: usize,
376        ambig_child: Option<&ModChild>,
377    ) {
378        let child_span = |this: &Self, reexport_chain: &[Reexport], res: def::Res<_>| {
379            this.def_span(
380                reexport_chain
381                    .first()
382                    .and_then(|reexport| reexport.id())
383                    .unwrap_or_else(|| res.def_id()),
384            )
385        };
386        let ModChild { ident: orig_ident, res, vis, ref reexport_chain } = *child;
387        let ident = IdentKey::new(orig_ident);
388        let span = child_span(self, reexport_chain, res);
389        let res = res.expect_non_local();
390        let expansion = LocalExpnId::ROOT;
391        let ambig = ambig_child.map(|ambig_child| {
392            let ModChild { ident: _, res, vis, ref reexport_chain } = *ambig_child;
393            let span = child_span(self, reexport_chain, res);
394            let res = res.expect_non_local();
395            self.arenas.new_def_decl(res, vis, span, expansion, Some(parent.to_module()))
396        });
397
398        // Record primary definitions.
399        let define_extern = |ns| {
400            self.define_extern(
401                parent,
402                ident,
403                orig_ident.span,
404                ns,
405                child_index,
406                res,
407                vis,
408                span,
409                expansion,
410                ambig,
411            )
412        };
413        match res {
414            Res::Def(
415                DefKind::Mod
416                | DefKind::Enum
417                | DefKind::Trait
418                | DefKind::Struct
419                | DefKind::Union
420                | DefKind::Variant
421                | DefKind::TyAlias
422                | DefKind::ForeignTy
423                | DefKind::OpaqueTy
424                | DefKind::TraitAlias
425                | DefKind::AssocTy,
426                _,
427            )
428            | Res::PrimTy(..)
429            | Res::ToolMod => define_extern(TypeNS),
430            Res::Def(
431                DefKind::Fn
432                | DefKind::AssocFn
433                | DefKind::Static { .. }
434                | DefKind::Const { .. }
435                | DefKind::AssocConst { .. }
436                | DefKind::Ctor(..),
437                _,
438            ) => define_extern(ValueNS),
439            Res::Def(DefKind::Macro(..), _) | Res::NonMacroAttr(..) => define_extern(MacroNS),
440            Res::Def(
441                DefKind::TyParam
442                | DefKind::ConstParam
443                | DefKind::ExternCrate
444                | DefKind::Use
445                | DefKind::ForeignMod
446                | DefKind::AnonConst
447                | DefKind::InlineConst
448                | DefKind::Field
449                | DefKind::LifetimeParam
450                | DefKind::GlobalAsm
451                | DefKind::Closure
452                | DefKind::SyntheticCoroutineBody
453                | DefKind::Impl { .. },
454                _,
455            )
456            | Res::Local(..)
457            | Res::SelfTyParam { .. }
458            | Res::SelfTyAlias { .. }
459            | Res::SelfCtor(..)
460            | Res::OpenMod(..)
461            | Res::Err => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected resolution: {0:?}",
        res))bug!("unexpected resolution: {:?}", res),
462        }
463    }
464}
465
466impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for DefCollector<'_, 'ra, 'tcx> {
467    fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
468        self.r
469    }
470}
471
472impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> {
473    fn res(&self, def_id: impl Into<DefId>) -> Res {
474        let def_id = def_id.into();
475        Res::Def(self.r.tcx.def_kind(def_id), def_id)
476    }
477
478    fn resolve_visibility(&mut self, vis: &ast::Visibility) -> Visibility {
479        match self.r.try_resolve_visibility(&self.parent_scope, vis, true) {
480            Ok(vis) => vis,
481            Err(error) => {
482                self.r.delayed_vis_resolution_errors.push(DelayedVisResolutionError {
483                    vis: vis.clone(),
484                    parent_scope: self.parent_scope,
485                    error,
486                });
487                Visibility::Public
488            }
489        }
490    }
491
492    fn insert_field_idents(&mut self, def_id: LocalDefId, fields: &[ast::FieldDef]) {
493        if fields.iter().any(|field| field.is_placeholder) {
494            // The fields are not expanded yet.
495            return;
496        }
497        let field_name = |i, field: &ast::FieldDef| {
498            field.ident.unwrap_or_else(|| Ident::from_str_and_span(&::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("{0}", i)) })format!("{i}"), field.span))
499        };
500        let field_names: Vec<_> =
501            fields.iter().enumerate().map(|(i, field)| field_name(i, field)).collect();
502        let defaults = fields
503            .iter()
504            .enumerate()
505            .filter_map(|(i, field)| field.default.as_ref().map(|_| field_name(i, field).name))
506            .collect();
507        self.r.field_names.insert(def_id, field_names);
508        self.r.field_defaults.insert(def_id, defaults);
509    }
510
511    fn insert_field_visibilities_local(&mut self, def_id: DefId, fields: &[ast::FieldDef]) {
512        let field_vis = fields
513            .iter()
514            .map(|field| field.vis.span.until(field.ident.map_or(field.ty.span, |i| i.span)))
515            .collect();
516        self.r.field_visibility_spans.insert(def_id, field_vis);
517    }
518
519    fn block_needs_anonymous_module(&self, block: &Block) -> bool {
520        // If any statements are items, we need to create an anonymous module
521        block
522            .stmts
523            .iter()
524            .any(|statement| #[allow(non_exhaustive_omitted_patterns)] match statement.kind {
    StmtKind::Item(_) | StmtKind::MacCall(_) => true,
    _ => false,
}matches!(statement.kind, StmtKind::Item(_) | StmtKind::MacCall(_)))
525    }
526
527    // Add an import to the current module.
528    fn add_import(
529        &mut self,
530        module_path: Vec<Segment>,
531        kind: ImportKind<'ra>,
532        span: Span,
533        item: &ast::Item,
534        root_span: Span,
535        root_id: NodeId,
536        vis: Visibility,
537    ) {
538        let current_module = self.parent_scope.module.expect_local();
539        let import = self.r.arenas.alloc_import(ImportData {
540            kind,
541            parent_scope: self.parent_scope,
542            module_path,
543            imported_module: CmCell::new(None),
544            span,
545            use_span: item.span,
546            use_span_with_attributes: item.span_with_attributes(),
547            has_attributes: !item.attrs.is_empty(),
548            root_span,
549            root_id,
550            vis,
551            vis_span: item.vis.span,
552            on_unknown_attr: OnUnknownData::from_attrs(self.r.tcx, item),
553        });
554
555        self.r.indeterminate_imports.push(import);
556        match import.kind {
557            ImportKind::Single { target, .. } => {
558                // Don't add underscore imports to `single_imports`
559                // because they cannot define any usable names.
560                if target.name != kw::Underscore {
561                    self.r.per_ns(|this, ns| {
562                        let key = BindingKey::new(IdentKey::new(target), ns);
563                        this.resolution_or_default(current_module.to_module(), key, target.span)
564                            .borrow_mut(this)
565                            .single_imports
566                            .insert(import);
567                    });
568                }
569            }
570            ImportKind::Glob { .. } => current_module.globs.borrow_mut(self.r).push(import),
571            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
572        }
573    }
574
575    fn build_reduced_graph_for_use_tree(
576        &mut self,
577        // This particular use tree
578        use_tree: &ast::UseTree,
579        id: NodeId,
580        parent_prefix: &[Segment],
581        nested: bool,
582        list_stem: bool,
583        // The whole `use` item
584        item: &Item,
585        vis: Visibility,
586        root_span: Span,
587        feed: TyCtxtFeed<'tcx, LocalDefId>,
588    ) {
589        {
    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/build_reduced_graph.rs:589",
                        "rustc_resolve::build_reduced_graph",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/build_reduced_graph.rs"),
                        ::tracing_core::__macro_support::Option::Some(589u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::build_reduced_graph"),
                        ::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!("build_reduced_graph_for_use_tree(parent_prefix={0:?}, use_tree={1:?}, nested={2})",
                                                    parent_prefix, use_tree, nested) as &dyn Value))])
            });
    } else { ; }
};debug!(
590            "build_reduced_graph_for_use_tree(parent_prefix={:?}, use_tree={:?}, nested={})",
591            parent_prefix, use_tree, nested
592        );
593
594        // Top level use tree reuses the item's id and list stems reuse their parent
595        // use tree's ids, so in both cases their visibilities are already filled.
596        if nested && !list_stem {
597            self.r.feed_visibility(feed, vis);
598        }
599
600        let mut prefix_iter = parent_prefix
601            .iter()
602            .cloned()
603            .chain(use_tree.prefix.segments.iter().map(|seg| seg.into()))
604            .peekable();
605
606        // On 2015 edition imports are resolved as crate-relative by default,
607        // so prefixes are prepended with crate root segment if necessary.
608        // The root is prepended lazily, when the first non-empty prefix or terminating glob
609        // appears, so imports in braced groups can have roots prepended independently.
610        let crate_root = match prefix_iter.peek() {
611            Some(seg) if !seg.ident.is_path_segment_keyword() && seg.ident.span.is_rust_2015() => {
612                Some(seg.ident.span.ctxt())
613            }
614            None if let ast::UseTreeKind::Glob(span) = use_tree.kind
615                && span.is_rust_2015() =>
616            {
617                Some(span.ctxt())
618            }
619            _ => None,
620        }
621        .map(|ctxt| {
622            Segment::from_ident(Ident::new(
623                kw::PathRoot,
624                use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt),
625            ))
626        });
627
628        let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>();
629        {
    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/build_reduced_graph.rs:629",
                        "rustc_resolve::build_reduced_graph",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/build_reduced_graph.rs"),
                        ::tracing_core::__macro_support::Option::Some(629u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::build_reduced_graph"),
                        ::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!("build_reduced_graph_for_use_tree: prefix={0:?}",
                                                    prefix) as &dyn Value))])
            });
    } else { ; }
};debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix);
630
631        match use_tree.kind {
632            ast::UseTreeKind::Simple(rename) => {
633                let mut module_path = prefix;
634                let source = module_path.pop().unwrap();
635
636                // If the identifier is `self` without a rename,
637                // then it is replaced with the parent identifier.
638                let ident = if source.ident.name == kw::SelfLower
639                    && rename.is_none()
640                    && let Some(parent) = module_path.last()
641                {
642                    Ident::new(parent.ident.name, source.ident.span)
643                } else {
644                    use_tree.ident()
645                };
646
647                match source.ident.name {
648                    kw::DollarCrate => {
649                        if !module_path.is_empty() {
650                            self.r.dcx().span_err(
651                                source.ident.span,
652                                "`$crate` in paths can only be used in start position",
653                            );
654                            return;
655                        }
656                    }
657                    kw::Crate => {
658                        if !module_path.is_empty() {
659                            self.r.dcx().span_err(
660                                source.ident.span,
661                                "`crate` in paths can only be used in start position",
662                            );
663                            return;
664                        }
665                    }
666                    kw::Super => {
667                        // Allow `self::super` as a valid prefix - `self` at position 0
668                        // followed by any number of `super` segments.
669                        let valid_prefix = module_path.iter().enumerate().all(|(i, seg)| {
670                            let name = seg.ident.name;
671                            name == kw::Super || (name == kw::SelfLower && i == 0)
672                        });
673
674                        if !valid_prefix {
675                            self.r.dcx().span_err(
676                                source.ident.span,
677                                "`super` in paths can only be used in start position, after `self`, or after another `super`",
678                            );
679                            return;
680                        }
681                    }
682                    // Deny `use ::{self};` after edition 2015
683                    kw::SelfLower
684                        if let Some(parent) = module_path.last()
685                            && parent.ident.name == kw::PathRoot
686                            && !self.r.path_root_is_crate_root(parent.ident) =>
687                    {
688                        self.r.dcx().span_err(use_tree.span(), "extern prelude cannot be imported");
689                        return;
690                    }
691                    _ => (),
692                }
693
694                // Deny `use ...::self::source [as target];` or `use ...::self::self [as target];`,
695                // but allow `use self::source [as target];` and `use self::self as target;`.
696                if let Some(parent) = module_path.last()
697                    && parent.ident.name == kw::SelfLower
698                    && module_path.len() > 1
699                {
700                    self.r.dcx().span_err(
701                        parent.ident.span,
702                        "`self` in paths can only be used in start position or last position",
703                    );
704                    return;
705                }
706
707                // Deny importing path-kw without renaming
708                if rename.is_none() && ident.is_path_segment_keyword() {
709                    let ident = use_tree.ident();
710                    self.r.dcx().emit_err(errors::UnnamedImport {
711                        span: ident.span,
712                        sugg: errors::UnnamedImportSugg { span: ident.span, ident },
713                    });
714                    return;
715                }
716
717                let kind = ImportKind::Single {
718                    source: source.ident,
719                    target: ident,
720                    decls: Default::default(),
721                    nested,
722                    id,
723                    def_id: feed.def_id(),
724                };
725
726                self.add_import(module_path, kind, use_tree.span(), item, root_span, item.id, vis);
727            }
728            ast::UseTreeKind::Glob(_) => {
729                if !ast::attr::contains_name(&item.attrs, sym::prelude_import) {
730                    let kind =
731                        ImportKind::Glob { max_vis: CmCell::new(None), id, def_id: feed.def_id() };
732                    self.add_import(prefix, kind, use_tree.span(), item, root_span, item.id, vis);
733                } else {
734                    // Resolve the prelude import early.
735                    let path_res =
736                        self.r.cm().maybe_resolve_path(&prefix, None, &self.parent_scope, None);
737                    if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = path_res {
738                        self.r.prelude = Some(module);
739                    } else {
740                        self.r.dcx().span_err(use_tree.span(), "cannot resolve a prelude import");
741                    }
742                }
743            }
744            ast::UseTreeKind::Nested { ref items, .. } => {
745                for &(ref tree, id) in items {
746                    self.with_owner(id, None, DefKind::Use, use_tree.span(), |this, feed| {
747                        this.build_reduced_graph_for_use_tree(
748                            // This particular use tree
749                            tree, id, &prefix, true, false, // The whole `use` item
750                            item, vis, root_span, feed,
751                        )
752                    });
753                }
754
755                // Empty groups `a::b::{}` are turned into synthetic `self` imports
756                // `a::b::c::{self as _}`, so that their prefixes are correctly
757                // resolved and checked for privacy/stability/etc.
758                if items.is_empty()
759                    && !prefix.is_empty()
760                    && (prefix.len() > 1 || prefix[0].ident.name != kw::PathRoot)
761                {
762                    let new_span = prefix[prefix.len() - 1].ident.span;
763                    let tree = ast::UseTree {
764                        prefix: ast::Path::from_ident(Ident::new(kw::SelfLower, new_span)),
765                        kind: ast::UseTreeKind::Simple(Some(Ident::new(kw::Underscore, new_span))),
766                    };
767                    self.build_reduced_graph_for_use_tree(
768                        // This particular use tree
769                        &tree,
770                        id,
771                        &prefix,
772                        true,
773                        true,
774                        // The whole `use` item
775                        item,
776                        Visibility::Restricted(
777                            self.parent_scope.module.nearest_parent_mod().expect_local(),
778                        ),
779                        root_span,
780                        feed,
781                    );
782                }
783            }
784        }
785    }
786
787    fn build_reduced_graph_for_struct_variant(
788        &mut self,
789        fields: &[ast::FieldDef],
790        ident: Ident,
791        feed: TyCtxtFeed<'tcx, LocalDefId>,
792        adt_res: Res,
793        adt_vis: Visibility,
794        adt_span: Span,
795    ) {
796        let parent_scope = &self.parent_scope;
797        let parent = parent_scope.module.expect_local();
798        let expansion = parent_scope.expansion;
799
800        // Define a name in the type namespace if it is not anonymous.
801        self.r.define_local(parent, ident, TypeNS, adt_res, adt_vis, adt_span, expansion);
802        self.r.feed_visibility(feed, adt_vis);
803        let def_id = feed.key();
804
805        // Record field names for error reporting.
806        self.insert_field_idents(def_id, fields);
807        self.insert_field_visibilities_local(def_id.to_def_id(), fields);
808    }
809
810    /// Constructs the reduced graph for one item.
811    fn build_reduced_graph_for_item(&mut self, item: &'a Item, feed: TyCtxtFeed<'tcx, LocalDefId>) {
812        let parent_scope = &self.parent_scope;
813        let parent = parent_scope.module.expect_local();
814        let expansion = parent_scope.expansion;
815        let sp = item.span;
816        let vis = self.resolve_visibility(&item.vis);
817        let local_def_id = feed.key();
818        let def_id = local_def_id.to_def_id();
819        let def_kind = self.r.tcx.def_kind(def_id);
820        let res = Res::Def(def_kind, def_id);
821
822        self.r.feed_visibility(feed, vis);
823
824        match item.kind {
825            ItemKind::Use(ref use_tree) => {
826                self.build_reduced_graph_for_use_tree(
827                    // This particular use tree
828                    use_tree,
829                    item.id,
830                    &[],
831                    false,
832                    false,
833                    // The whole `use` item
834                    item,
835                    vis,
836                    use_tree.span(),
837                    feed,
838                );
839            }
840
841            ItemKind::ExternCrate(orig_name, ident) => {
842                self.build_reduced_graph_for_extern_crate(
843                    orig_name,
844                    item,
845                    ident,
846                    local_def_id,
847                    vis,
848                );
849            }
850
851            ItemKind::Mod(_, ident, ref mod_kind) => {
852                self.r.define_local(parent, ident, TypeNS, res, vis, sp, expansion);
853
854                if let ast::ModKind::Loaded(_, Inline::No { had_parse_error: Err(_) }, _) = mod_kind
855                {
856                    self.r.mods_with_parse_errors.insert(def_id);
857                }
858                let module = self.r.new_local_module(
859                    Some(parent),
860                    ModuleKind::Def(def_kind, def_id, item.id, Some(ident.name)),
861                    expansion.to_expn_id(),
862                    item.span,
863                    parent.no_implicit_prelude
864                        || ast::attr::contains_name(&item.attrs, sym::no_implicit_prelude),
865                );
866                self.parent_scope.module = module.to_module();
867            }
868
869            // These items live in the value namespace.
870            ItemKind::Const(ConstItem { ident, .. })
871            | ItemKind::Delegation(Delegation { ident, .. })
872            | ItemKind::Static(StaticItem { ident, .. }) => {
873                self.r.define_local(parent, ident, ValueNS, res, vis, sp, expansion);
874            }
875            ItemKind::Fn(Fn { ident, .. }) => {
876                self.r.define_local(parent, ident, ValueNS, res, vis, sp, expansion);
877
878                // Functions introducing procedural macros reserve a slot
879                // in the macro namespace as well (see #52225).
880                self.define_macro(item, feed);
881            }
882
883            // These items live in the type namespace.
884            ItemKind::TyAlias(TyAlias { ident, .. })
885            | ItemKind::TraitAlias(TraitAlias { ident, .. }) => {
886                self.r.define_local(parent, ident, TypeNS, res, vis, sp, expansion);
887            }
888
889            ItemKind::Enum(ident, _, _) | ItemKind::Trait(ast::Trait { ident, .. }) => {
890                self.r.define_local(parent, ident, TypeNS, res, vis, sp, expansion);
891
892                let module = self.r.new_local_module(
893                    Some(parent),
894                    ModuleKind::Def(def_kind, def_id, item.id, Some(ident.name)),
895                    expansion.to_expn_id(),
896                    item.span,
897                    parent.no_implicit_prelude,
898                );
899                self.parent_scope.module = module.to_module();
900            }
901
902            // These items live in both the type and value namespaces.
903            ItemKind::Struct(ident, ref generics, ref vdata) => {
904                self.build_reduced_graph_for_struct_variant(
905                    vdata.fields(),
906                    ident,
907                    feed,
908                    res,
909                    vis,
910                    sp,
911                );
912
913                // If this is a tuple or unit struct, define a name
914                // in the value namespace as well.
915                if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(vdata) {
916                    // If the structure is marked as non_exhaustive then lower the visibility
917                    // to within the crate.
918                    let mut ctor_vis = if vis.is_public()
919                        && ast::attr::contains_name(&item.attrs, sym::non_exhaustive)
920                    {
921                        Visibility::Restricted(CRATE_DEF_ID)
922                    } else {
923                        vis
924                    };
925
926                    let mut field_visibilities = Vec::with_capacity(vdata.fields().len());
927
928                    for field in vdata.fields() {
929                        // NOTE: The field may be an expansion placeholder, but expansion sets
930                        // correct visibilities for unnamed field placeholders specifically, so the
931                        // constructor visibility should still be determined correctly.
932                        let field_vis = self
933                            .r
934                            .try_resolve_visibility(&self.parent_scope, &field.vis, false)
935                            .unwrap_or(Visibility::Public);
936                        if ctor_vis.greater_than(field_vis, self.r.tcx) {
937                            ctor_vis = field_vis;
938                        }
939                        field_visibilities.push(field_vis.to_def_id());
940                    }
941                    // If this is a unit or tuple-like struct, register the constructor.
942                    let feed = self.create_def(
943                        ctor_node_id,
944                        None,
945                        DefKind::Ctor(CtorOf::Struct, ctor_kind),
946                        item.span,
947                    );
948
949                    let ctor_def_id = feed.key();
950                    let ctor_res = self.res(ctor_def_id);
951                    self.r.define_local(parent, ident, ValueNS, ctor_res, ctor_vis, sp, expansion);
952                    self.r.feed_visibility(feed, ctor_vis);
953                    // We need the field visibility spans also for the constructor for E0603.
954                    self.insert_field_visibilities_local(ctor_def_id.to_def_id(), vdata.fields());
955
956                    let ctor =
957                        StructCtor { res: ctor_res, vis: ctor_vis.to_def_id(), field_visibilities };
958                    self.r.struct_ctors.insert(local_def_id, ctor);
959                }
960                self.r.struct_generics.insert(local_def_id, generics.clone());
961            }
962
963            ItemKind::Union(ident, _, ref vdata) => {
964                self.build_reduced_graph_for_struct_variant(
965                    vdata.fields(),
966                    ident,
967                    feed,
968                    res,
969                    vis,
970                    sp,
971                );
972            }
973
974            // These items do not add names to modules.
975            ItemKind::Impl { .. }
976            | ItemKind::ForeignMod(..)
977            | ItemKind::GlobalAsm(..)
978            | ItemKind::ConstBlock(..) => {}
979
980            ItemKind::MacroDef(..) | ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
981                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
982            }
983        }
984    }
985
986    fn build_reduced_graph_for_extern_crate(
987        &mut self,
988        orig_name: Option<Symbol>,
989        item: &Item,
990        orig_ident: Ident,
991        local_def_id: LocalDefId,
992        vis: Visibility,
993    ) {
994        let sp = item.span;
995        let parent_scope = self.parent_scope;
996        let parent = parent_scope.module;
997        let expansion = parent_scope.expansion;
998
999        let (used, module, decl) = if orig_name.is_none() && orig_ident.name == kw::SelfLower {
1000            self.r.dcx().emit_err(errors::ExternCrateSelfRequiresRenaming { span: sp });
1001            return;
1002        } else if orig_name == Some(kw::SelfLower) {
1003            Some(self.r.graph_root.to_module())
1004        } else {
1005            let tcx = self.r.tcx;
1006            let crate_id = self.r.cstore_mut().process_extern_crate(
1007                self.r.tcx,
1008                item,
1009                local_def_id,
1010                &tcx.definitions_untracked(),
1011            );
1012            crate_id.map(|crate_id| {
1013                self.r.extern_crate_map.insert(local_def_id, crate_id);
1014                self.r.expect_module(crate_id.as_def_id())
1015            })
1016        }
1017        .map(|module| {
1018            let used = self.process_macro_use_imports(item, module);
1019            let decl = self.r.arenas.new_pub_def_decl(module.res().unwrap(), sp, expansion);
1020            (used, Some(ModuleOrUniformRoot::Module(module)), decl)
1021        })
1022        .unwrap_or((true, None, self.r.dummy_decl));
1023        let import = self.r.arenas.alloc_import(ImportData {
1024            kind: ImportKind::ExternCrate {
1025                source: orig_name,
1026                target: orig_ident,
1027                id: item.id,
1028                def_id: local_def_id,
1029            },
1030            root_id: item.id,
1031            parent_scope,
1032            imported_module: CmCell::new(module),
1033            has_attributes: !item.attrs.is_empty(),
1034            use_span_with_attributes: item.span_with_attributes(),
1035            use_span: item.span,
1036            root_span: item.span,
1037            span: item.span,
1038            module_path: Vec::new(),
1039            vis,
1040            vis_span: item.vis.span,
1041            on_unknown_attr: OnUnknownData::from_attrs(self.r.tcx, item),
1042        });
1043        if used {
1044            self.r.import_use_map.insert(import, Used::Other);
1045        }
1046        self.r.potentially_unused_imports.push(import);
1047        let import_decl = self.r.new_import_decl(decl, import);
1048        let ident = IdentKey::new(orig_ident);
1049        if ident.name != kw::Underscore && parent == self.r.graph_root.to_module() {
1050            // FIXME: this error is technically unnecessary now when extern prelude is split into
1051            // two scopes, remove it with lang team approval.
1052            if let Some(entry) = self.r.extern_prelude.get(&ident)
1053                && expansion != LocalExpnId::ROOT
1054                && orig_name.is_some()
1055                && entry.item_decl.is_none()
1056            {
1057                self.r.dcx().emit_err(
1058                    errors::MacroExpandedExternCrateCannotShadowExternArguments { span: item.span },
1059                );
1060            }
1061
1062            use indexmap::map::Entry;
1063            match self.r.extern_prelude.entry(ident) {
1064                Entry::Occupied(mut occupied) => {
1065                    let entry = occupied.get_mut();
1066                    if entry.item_decl.is_some() {
1067                        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("extern crate `{0}` already in extern prelude",
                orig_ident))
    })format!("extern crate `{orig_ident}` already in extern prelude");
1068                        self.r.tcx.dcx().span_delayed_bug(item.span, msg);
1069                    } else {
1070                        entry.item_decl = Some((import_decl, orig_ident.span, orig_name.is_some()));
1071                    }
1072                    entry
1073                }
1074                Entry::Vacant(vacant) => vacant.insert(ExternPreludeEntry {
1075                    item_decl: Some((import_decl, orig_ident.span, true)),
1076                    flag_decl: None,
1077                }),
1078            };
1079        }
1080        self.r.plant_decl_into_local_module(ident, orig_ident.span, TypeNS, import_decl);
1081    }
1082
1083    /// Constructs the reduced graph for one foreign item.
1084    pub(crate) fn build_reduced_graph_for_foreign_item(
1085        &mut self,
1086        item: &ForeignItem,
1087        ident: Ident,
1088        feed: TyCtxtFeed<'tcx, LocalDefId>,
1089    ) {
1090        let local_def_id = feed.key();
1091        let def_id = local_def_id.to_def_id();
1092        let ns = match item.kind {
1093            ForeignItemKind::Fn(..) => ValueNS,
1094            ForeignItemKind::Static(..) => ValueNS,
1095            ForeignItemKind::TyAlias(..) => TypeNS,
1096            ForeignItemKind::MacCall(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1097        };
1098        let parent = self.parent_scope.module.expect_local();
1099        let expansion = self.parent_scope.expansion;
1100        let vis = self.resolve_visibility(&item.vis);
1101        self.r.define_local(parent, ident, ns, self.res(def_id), vis, item.span, expansion);
1102        self.r.feed_visibility(feed, vis);
1103    }
1104
1105    fn build_reduced_graph_for_block(&mut self, block: &Block) {
1106        let parent = self.parent_scope.module.expect_local();
1107        let expansion = self.parent_scope.expansion;
1108        if self.block_needs_anonymous_module(block) {
1109            let module = self.r.new_local_module(
1110                Some(parent),
1111                ModuleKind::Block,
1112                expansion.to_expn_id(),
1113                block.span,
1114                parent.no_implicit_prelude,
1115            );
1116            self.r.block_map.insert(block.id, module);
1117            self.parent_scope.module = module.to_module(); // Descend into the block.
1118        }
1119    }
1120
1121    fn add_macro_use_decl(
1122        &mut self,
1123        name: Symbol,
1124        decl: Decl<'ra>,
1125        span: Span,
1126        allow_shadowing: bool,
1127    ) {
1128        if self.r.macro_use_prelude.insert(name, decl).is_some() && !allow_shadowing {
1129            self.r.dcx().emit_err(errors::MacroUseNameAlreadyInUse { span, name });
1130        }
1131    }
1132
1133    /// Returns `true` if we should consider the underlying `extern crate` to be used.
1134    fn process_macro_use_imports(&mut self, item: &Item, module: Module<'ra>) -> bool {
1135        let mut import_all = None;
1136        let mut single_imports = ThinVec::new();
1137        if let Some(Attribute::Parsed(AttributeKind::MacroUse { span, arguments })) =
1138            AttributeParser::parse_limited(self.r.tcx.sess, &item.attrs, &[sym::macro_use])
1139        {
1140            if self.parent_scope.module.expect_local().parent.is_some() {
1141                self.r
1142                    .dcx()
1143                    .emit_err(errors::ExternCrateLoadingMacroNotAtCrateRoot { span: item.span });
1144            }
1145            if let ItemKind::ExternCrate(Some(orig_name), _) = item.kind
1146                && orig_name == kw::SelfLower
1147            {
1148                self.r.dcx().emit_err(errors::MacroUseExternCrateSelf { span });
1149            }
1150
1151            match arguments {
1152                MacroUseArgs::UseAll => import_all = Some(span),
1153                MacroUseArgs::UseSpecific(imports) => single_imports = imports,
1154            }
1155        }
1156
1157        let macro_use_import = |this: &Self, span, warn_private| {
1158            this.r.arenas.alloc_import(ImportData {
1159                kind: ImportKind::MacroUse { warn_private },
1160                root_id: item.id,
1161                parent_scope: this.parent_scope,
1162                imported_module: CmCell::new(Some(ModuleOrUniformRoot::Module(module))),
1163                use_span_with_attributes: item.span_with_attributes(),
1164                has_attributes: !item.attrs.is_empty(),
1165                use_span: item.span,
1166                root_span: span,
1167                span,
1168                module_path: Vec::new(),
1169                vis: Visibility::Restricted(CRATE_DEF_ID),
1170                vis_span: item.vis.span,
1171                on_unknown_attr: OnUnknownData::from_attrs(this.r.tcx, item),
1172            })
1173        };
1174
1175        let allow_shadowing = self.parent_scope.expansion == LocalExpnId::ROOT;
1176        if let Some(span) = import_all {
1177            let import = macro_use_import(self, span, false);
1178            self.r.potentially_unused_imports.push(import);
1179            module.for_each_child_mut(self, |this, ident, _, ns, binding| {
1180                if ns == MacroNS {
1181                    let import =
1182                        if this.r.is_accessible_from(binding.vis(), this.parent_scope.module) {
1183                            import
1184                        } else {
1185                            // FIXME: This branch is used for reporting the `private_macro_use` lint
1186                            // and should eventually be removed.
1187                            if this.r.macro_use_prelude.contains_key(&ident.name) {
1188                                // Do not override already existing entries with compatibility entries.
1189                                return;
1190                            }
1191                            macro_use_import(this, span, true)
1192                        };
1193                    let import_decl = this.r.new_import_decl(binding, import);
1194                    this.add_macro_use_decl(ident.name, import_decl, span, allow_shadowing);
1195                }
1196            });
1197        } else {
1198            for ident in single_imports.iter().cloned() {
1199                let result = self.r.cm().maybe_resolve_ident_in_module(
1200                    ModuleOrUniformRoot::Module(module),
1201                    ident,
1202                    MacroNS,
1203                    &self.parent_scope,
1204                    None,
1205                );
1206                if let Ok(binding) = result {
1207                    let import = macro_use_import(self, ident.span, false);
1208                    self.r.potentially_unused_imports.push(import);
1209                    let import_decl = self.r.new_import_decl(binding, import);
1210                    self.add_macro_use_decl(ident.name, import_decl, ident.span, allow_shadowing);
1211                } else {
1212                    self.r.dcx().emit_err(errors::ImportedMacroNotFound { span: ident.span });
1213                }
1214            }
1215        }
1216        import_all.is_some() || !single_imports.is_empty()
1217    }
1218
1219    /// Returns `true` if this attribute list contains `macro_use`.
1220    pub(crate) fn contains_macro_use(&self, attrs: &[ast::Attribute]) -> bool {
1221        for attr in attrs {
1222            if attr.has_name(sym::macro_escape) {
1223                let inner_attribute = #[allow(non_exhaustive_omitted_patterns)] match attr.style {
    ast::AttrStyle::Inner => true,
    _ => false,
}matches!(attr.style, ast::AttrStyle::Inner);
1224                self.r
1225                    .dcx()
1226                    .emit_warn(errors::MacroExternDeprecated { span: attr.span, inner_attribute });
1227            } else if !attr.has_name(sym::macro_use) {
1228                continue;
1229            }
1230
1231            if !attr.is_word() {
1232                self.r.dcx().emit_err(errors::ArgumentsMacroUseNotAllowed { span: attr.span });
1233            }
1234            return true;
1235        }
1236
1237        false
1238    }
1239
1240    pub(crate) fn visit_invoc(&mut self, id: NodeId) -> LocalExpnId {
1241        let invoc_id = id.placeholder_to_expn_id();
1242        let old_parent_scope = self.r.invocation_parent_scopes.insert(invoc_id, self.parent_scope);
1243        if !old_parent_scope.is_none() {
    {
        ::core::panicking::panic_fmt(format_args!("invocation data is reset for an invocation"));
    }
};assert!(old_parent_scope.is_none(), "invocation data is reset for an invocation");
1244        invoc_id
1245    }
1246
1247    /// Visit invocation in context in which it can emit a named item (possibly `macro_rules`)
1248    /// directly into its parent scope's module.
1249    pub(crate) fn visit_invoc_in_module(&mut self, id: NodeId) -> MacroRulesScopeRef<'ra> {
1250        let invoc_id = self.visit_invoc(id);
1251        let module = self.parent_scope.module.expect_local();
1252        module.unexpanded_invocations.borrow_mut(self.r).insert(invoc_id);
1253        self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Invocation(invoc_id))
1254    }
1255
1256    fn proc_macro_stub(
1257        &self,
1258        item: &ast::Item,
1259        fn_ident: Ident,
1260    ) -> Option<(MacroKind, Ident, Span)> {
1261        if ast::attr::contains_name(&item.attrs, sym::proc_macro) {
1262            return Some((MacroKind::Bang, fn_ident, item.span));
1263        } else if ast::attr::contains_name(&item.attrs, sym::proc_macro_attribute) {
1264            return Some((MacroKind::Attr, fn_ident, item.span));
1265        } else if let Some(attr) = ast::attr::find_by_name(&item.attrs, sym::proc_macro_derive)
1266            && let Some(meta_item_inner) =
1267                attr.meta_item_list().and_then(|list| list.get(0).cloned())
1268            && let Some(ident) = meta_item_inner.ident()
1269        {
1270            return Some((MacroKind::Derive, ident, ident.span));
1271        }
1272        None
1273    }
1274
1275    // Mark the given macro as unused unless its name starts with `_`.
1276    // Macro uses will remove items from this set, and the remaining
1277    // items will be reported as `unused_macros`.
1278    fn insert_unused_macro(&mut self, ident: Ident, def_id: LocalDefId, node_id: NodeId) {
1279        if !ident.as_str().starts_with('_') {
1280            self.r.unused_macros.insert(def_id, (node_id, ident));
1281            if let SyntaxExtensionKind::MacroRules(mr) = &self.r.local_macro_map[&def_id].kind {
1282                let value = (def_id, DenseBitSet::new_filled(mr.nrules()));
1283                self.r.unused_macro_rules.insert(node_id, value);
1284            }
1285        }
1286    }
1287
1288    fn define_macro(
1289        &mut self,
1290        item: &ast::Item,
1291        feed: TyCtxtFeed<'tcx, LocalDefId>,
1292    ) -> MacroRulesScopeRef<'ra> {
1293        let parent_scope = self.parent_scope;
1294        let expansion = parent_scope.expansion;
1295        let def_id = feed.key();
1296        let (res, orig_ident, span, macro_rules) = match &item.kind {
1297            ItemKind::MacroDef(ident, def) => {
1298                (self.res(def_id), *ident, item.span, def.macro_rules)
1299            }
1300            ItemKind::Fn(ast::Fn { ident: fn_ident, .. }) => {
1301                match self.proc_macro_stub(item, *fn_ident) {
1302                    Some((macro_kind, ident, span)) => {
1303                        let macro_kinds = macro_kind.into();
1304                        let res = Res::Def(DefKind::Macro(macro_kinds), def_id.to_def_id());
1305                        self.r.local_macro_map.insert(def_id, self.r.dummy_ext(macro_kind));
1306                        self.r.proc_macro_stubs.insert(def_id);
1307                        (res, ident, span, false)
1308                    }
1309                    None => return parent_scope.macro_rules,
1310                }
1311            }
1312            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1313        };
1314
1315        self.r.local_macro_def_scopes.insert(def_id, parent_scope.module.expect_local());
1316
1317        if macro_rules {
1318            let ident = IdentKey::new(orig_ident);
1319            self.r.macro_names.insert(ident);
1320            let is_macro_export = ast::attr::contains_name(&item.attrs, sym::macro_export);
1321            let vis = if is_macro_export {
1322                Visibility::Public
1323            } else {
1324                Visibility::Restricted(CRATE_DEF_ID)
1325            };
1326            let decl = self.r.arenas.new_def_decl(
1327                res,
1328                vis.to_def_id(),
1329                span,
1330                expansion,
1331                Some(parent_scope.module),
1332            );
1333            self.r.all_macro_rules.insert(ident.name);
1334            if is_macro_export {
1335                let import = self.r.arenas.alloc_import(ImportData {
1336                    kind: ImportKind::MacroExport,
1337                    root_id: item.id,
1338                    parent_scope: ParentScope {
1339                        module: self.r.graph_root.to_module(),
1340                        ..parent_scope
1341                    },
1342                    imported_module: CmCell::new(None),
1343                    has_attributes: false,
1344                    use_span_with_attributes: span,
1345                    use_span: span,
1346                    root_span: span,
1347                    span,
1348                    module_path: Vec::new(),
1349                    vis,
1350                    vis_span: item.vis.span,
1351                    on_unknown_attr: OnUnknownData::from_attrs(self.r.tcx, item),
1352                });
1353                self.r.import_use_map.insert(import, Used::Other);
1354                let import_decl = self.r.new_import_decl(decl, import);
1355                self.r.plant_decl_into_local_module(ident, orig_ident.span, MacroNS, import_decl);
1356            } else {
1357                self.r.check_reserved_macro_name(ident.name, orig_ident.span, res);
1358                self.insert_unused_macro(orig_ident, def_id, item.id);
1359            }
1360            self.r.feed_visibility(feed, vis);
1361            let scope = self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Def(
1362                self.r.arenas.alloc_macro_rules_decl(MacroRulesDecl {
1363                    parent_macro_rules_scope: parent_scope.macro_rules,
1364                    decl,
1365                    ident,
1366                    orig_ident_span: orig_ident.span,
1367                }),
1368            ));
1369            self.r.macro_rules_scopes.insert(def_id, scope);
1370            scope
1371        } else {
1372            let module = parent_scope.module.expect_local();
1373            let vis = match item.kind {
1374                // Visibilities must not be resolved non-speculatively twice
1375                // and we already resolved this one as a `fn` item visibility.
1376                ItemKind::Fn(..) => self
1377                    .r
1378                    .try_resolve_visibility(&self.parent_scope, &item.vis, false)
1379                    .unwrap_or(Visibility::Public),
1380                _ => self.resolve_visibility(&item.vis),
1381            };
1382            if !vis.is_public() {
1383                self.insert_unused_macro(orig_ident, def_id, item.id);
1384            }
1385            self.r.define_local(module, orig_ident, MacroNS, res, vis, span, expansion);
1386            self.r.feed_visibility(feed, vis);
1387            self.parent_scope.macro_rules
1388        }
1389    }
1390}
1391
1392impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> {
1393    pub(crate) fn brg_visit_item(&mut self, item: &'a Item, feed: TyCtxtFeed<'tcx, LocalDefId>) {
1394        let orig_module_scope = self.parent_scope.module;
1395        self.parent_scope.macro_rules = match item.kind {
1396            ItemKind::MacroDef(..) => {
1397                let macro_rules_scope = self.define_macro(item, feed);
1398                visit::walk_item(self, item);
1399                macro_rules_scope
1400            }
1401            _ => {
1402                let orig_macro_rules_scope = self.parent_scope.macro_rules;
1403                self.build_reduced_graph_for_item(item, feed);
1404                match item.kind {
1405                    ItemKind::Mod(..) => {
1406                        // Visit attributes after items for backward compatibility.
1407                        // This way they can use `macro_rules` defined later.
1408                        self.visit_vis(&item.vis);
1409                        item.kind.walk(&item.attrs, item.span, item.id, &item.vis, (), self);
1410                        for elem in &item.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, &item.attrs);
1411                    }
1412                    _ => visit::walk_item(self, item),
1413                }
1414                match item.kind {
1415                    ItemKind::Mod(..) if self.contains_macro_use(&item.attrs) => {
1416                        self.parent_scope.macro_rules
1417                    }
1418                    _ => orig_macro_rules_scope,
1419                }
1420            }
1421        };
1422        self.parent_scope.module = orig_module_scope;
1423    }
1424
1425    /// Handle a macro call that itself can produce new `macro_rules` items
1426    /// in the current module.
1427    pub(crate) fn brg_visit_mac_call_in_module(&mut self, id: NodeId) {
1428        self.parent_scope.macro_rules = self.visit_invoc_in_module(id);
1429    }
1430
1431    pub(crate) fn brg_visit_block(&mut self, block: &'a Block) {
1432        let orig_current_module = self.parent_scope.module;
1433        let orig_current_macro_rules_scope = self.parent_scope.macro_rules;
1434        self.build_reduced_graph_for_block(block);
1435        visit::walk_block(self, block);
1436        self.parent_scope.module = orig_current_module;
1437        self.parent_scope.macro_rules = orig_current_macro_rules_scope;
1438    }
1439
1440    pub(crate) fn brg_visit_assoc_item(
1441        &mut self,
1442        item: &'a AssocItem,
1443        ctxt: AssocCtxt,
1444        ident: Ident,
1445        ns: Namespace,
1446        feed: TyCtxtFeed<'tcx, LocalDefId>,
1447    ) {
1448        let vis = self.resolve_visibility(&item.vis);
1449        let local_def_id = feed.key();
1450        let def_id = local_def_id.to_def_id();
1451
1452        if !(#[allow(non_exhaustive_omitted_patterns)] match ctxt {
    AssocCtxt::Impl { of_trait: true } => true,
    _ => false,
}matches!(ctxt, AssocCtxt::Impl { of_trait: true })
1453            && #[allow(non_exhaustive_omitted_patterns)] match item.vis.kind {
    ast::VisibilityKind::Inherited => true,
    _ => false,
}matches!(item.vis.kind, ast::VisibilityKind::Inherited))
1454        {
1455            // Trait impl item visibility is inherited from its trait when not specified
1456            // explicitly. In that case we cannot determine it here in early resolve,
1457            // so we leave a hole in the visibility table to be filled later.
1458            self.r.feed_visibility(feed, vis);
1459        }
1460
1461        if ctxt == AssocCtxt::Trait {
1462            let parent = self.parent_scope.module.expect_local();
1463            let expansion = self.parent_scope.expansion;
1464            self.r.define_local(parent, ident, ns, self.res(def_id), vis, item.span, expansion);
1465        } else if !#[allow(non_exhaustive_omitted_patterns)] match &item.kind {
    AssocItemKind::Delegation(deleg) if deleg.from_glob => true,
    _ => false,
}matches!(&item.kind, AssocItemKind::Delegation(deleg) if deleg.from_glob)
1466            && ident.name != kw::Underscore
1467        {
1468            // Don't add underscore names, they cannot be looked up anyway.
1469            let impl_def_id = self.r.tcx.local_parent(local_def_id);
1470            let key = BindingKey::new(IdentKey::new(ident), ns);
1471            self.r.impl_binding_keys.entry(impl_def_id).or_default().insert(key);
1472        }
1473
1474        visit::walk_assoc_item(self, item, ctxt);
1475    }
1476
1477    pub(crate) fn visit_assoc_item_mac_call(
1478        &mut self,
1479        item: &'a Item<AssocItemKind>,
1480        ctxt: AssocCtxt,
1481    ) {
1482        match ctxt {
1483            AssocCtxt::Trait => {
1484                self.visit_invoc_in_module(item.id);
1485            }
1486            AssocCtxt::Impl { .. } => {
1487                let invoc_id = item.id.placeholder_to_expn_id();
1488                if !self.r.glob_delegation_invoc_ids.contains(&invoc_id) {
1489                    self.r
1490                        .impl_unexpanded_invocations
1491                        .entry(self.r.invocation_parent(invoc_id))
1492                        .or_default()
1493                        .insert(invoc_id);
1494                }
1495                self.visit_invoc(item.id);
1496            }
1497        }
1498    }
1499
1500    pub(crate) fn brg_visit_field_def(
1501        &mut self,
1502        sf: &'a ast::FieldDef,
1503        feed: TyCtxtFeed<'tcx, LocalDefId>,
1504    ) {
1505        let vis = self.resolve_visibility(&sf.vis);
1506        self.r.feed_visibility(feed, vis);
1507        visit::walk_field_def(self, sf);
1508    }
1509
1510    // Constructs the reduced graph for one variant. Variants exist in the
1511    // type and value namespaces.
1512    pub(crate) fn brg_visit_variant(
1513        &mut self,
1514        variant: &'a ast::Variant,
1515        feed: TyCtxtFeed<'tcx, LocalDefId>,
1516    ) {
1517        let parent = self.parent_scope.module.expect_local();
1518        let expn_id = self.parent_scope.expansion;
1519        let ident = variant.ident;
1520
1521        // Define a name in the type namespace.
1522        let def_id = feed.key();
1523        let vis = self.resolve_visibility(&variant.vis);
1524        self.r.define_local(parent, ident, TypeNS, self.res(def_id), vis, variant.span, expn_id);
1525        self.r.feed_visibility(feed, vis);
1526
1527        // If the variant is marked as non_exhaustive then lower the visibility to within the crate.
1528        let ctor_vis =
1529            if vis.is_public() && ast::attr::contains_name(&variant.attrs, sym::non_exhaustive) {
1530                Visibility::Restricted(CRATE_DEF_ID)
1531            } else {
1532                vis
1533            };
1534
1535        // Define a constructor name in the value namespace.
1536        if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(&variant.data) {
1537            let feed = self.create_def(
1538                ctor_node_id,
1539                None,
1540                DefKind::Ctor(CtorOf::Variant, ctor_kind),
1541                variant.span,
1542            );
1543            let ctor_def_id = feed.key();
1544            let ctor_res = self.res(ctor_def_id);
1545            self.r.define_local(parent, ident, ValueNS, ctor_res, ctor_vis, variant.span, expn_id);
1546            self.r.feed_visibility(feed, ctor_vis);
1547        }
1548
1549        // Record field names for error reporting.
1550        self.insert_field_idents(def_id, variant.data.fields());
1551        self.insert_field_visibilities_local(def_id.to_def_id(), variant.data.fields());
1552
1553        visit::walk_variant(self, variant);
1554    }
1555}