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