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 crate_root = match prefix_iter.peek() {
607            Some(seg) if !seg.ident.is_path_segment_keyword() && seg.ident.span.is_rust_2015() => {
608                Some(seg.ident.span.ctxt())
609            }
610            None if let ast::UseTreeKind::Glob(span) = use_tree.kind
611                && span.is_rust_2015() =>
612            {
613                Some(span.ctxt())
614            }
615            _ => None,
616        }
617        .map(|ctxt| {
618            Segment::from_ident(Ident::new(
619                kw::PathRoot,
620                use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt),
621            ))
622        });
623
624        let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>();
625        {
    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:625",
                        "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(625u32),
                        ::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);
626
627        match use_tree.kind {
628            ast::UseTreeKind::Simple(rename) => {
629                let mut ident = use_tree.ident();
630                let mut module_path = prefix;
631                let mut source = module_path.pop().unwrap();
632
633                // `true` for `...::{self [as target]}` imports, `false` otherwise.
634                let type_ns_only = nested && source.ident.name == kw::SelfLower;
635
636                if source.ident.name == kw::SelfLower
637                    && let Some(parent) = module_path.pop()
638                {
639                    // Suggest `use prefix::{self};` for `use prefix::self;`
640                    if !type_ns_only
641                        && (parent.ident.name != kw::PathRoot
642                            || self.r.path_root_is_crate_root(parent.ident))
643                    {
644                        let span_with_rename = match rename {
645                            Some(rename) => source.ident.span.to(rename.span),
646                            None => source.ident.span,
647                        };
648
649                        self.r.report_error(
650                            parent.ident.span.shrink_to_hi().to(source.ident.span),
651                            ResolutionError::SelfImportsOnlyAllowedWithin {
652                                root: parent.ident.name == kw::PathRoot,
653                                span_with_rename,
654                            },
655                        );
656                    }
657
658                    let self_span = source.ident.span;
659                    source = parent;
660                    if rename.is_none() {
661                        ident = Ident::new(source.ident.name, self_span);
662                    }
663                }
664
665                match source.ident.name {
666                    kw::DollarCrate => {
667                        if !module_path.is_empty() {
668                            self.r.dcx().span_err(
669                                source.ident.span,
670                                "`$crate` in paths can only be used in start position",
671                            );
672                            return;
673                        }
674                    }
675                    kw::Crate => {
676                        if !module_path.is_empty() {
677                            self.r.dcx().span_err(
678                                source.ident.span,
679                                "`crate` in paths can only be used in start position",
680                            );
681                            return;
682                        }
683                    }
684                    kw::Super => {
685                        // Allow `self::super` as a valid prefix - `self` at position 0
686                        // followed by any number of `super` segments.
687                        let valid_prefix = module_path.iter().enumerate().all(|(i, seg)| {
688                            let name = seg.ident.name;
689                            name == kw::Super || (name == kw::SelfLower && i == 0)
690                        });
691
692                        if !valid_prefix {
693                            self.r.dcx().span_err(
694                                source.ident.span,
695                                "`super` in paths can only be used in start position, after `self`, or after another `super`",
696                            );
697                            return;
698                        }
699                    }
700                    // Deny `use ::{self};` after edition 2015
701                    kw::PathRoot if !self.r.path_root_is_crate_root(source.ident) => {
702                        self.r.dcx().span_err(use_tree.span(), "extern prelude cannot be imported");
703                        return;
704                    }
705                    _ => {}
706                }
707
708                // Deny importing path-kw without renaming
709                if rename.is_none() && ident.is_path_segment_keyword() {
710                    let ident = use_tree.ident();
711
712                    // Don't suggest `use xx::self as name;` for `use xx::self;`
713                    // But it's OK to suggest `use xx::{self as name};` for `use xx::{self};`
714                    let sugg = if !type_ns_only && ident.name == kw::SelfLower {
715                        None
716                    } else {
717                        Some(errors::UnnamedImportSugg { span: ident.span, ident })
718                    };
719
720                    self.r.dcx().emit_err(errors::UnnamedImport { span: ident.span, sugg });
721                    return;
722                }
723
724                let kind = ImportKind::Single {
725                    source: source.ident,
726                    target: ident,
727                    decls: Default::default(),
728                    type_ns_only,
729                    nested,
730                    id,
731                };
732
733                self.add_import(module_path, kind, use_tree.span(), item, root_span, item.id, vis);
734            }
735            ast::UseTreeKind::Glob(_) => {
736                if !ast::attr::contains_name(&item.attrs, sym::prelude_import) {
737                    let kind = ImportKind::Glob { max_vis: CmCell::new(None), id };
738                    self.add_import(prefix, kind, use_tree.span(), item, root_span, item.id, vis);
739                } else {
740                    // Resolve the prelude import early.
741                    let path_res =
742                        self.r.cm().maybe_resolve_path(&prefix, None, &self.parent_scope, None);
743                    if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = path_res {
744                        self.r.prelude = Some(module);
745                    } else {
746                        self.r.dcx().span_err(use_tree.span(), "cannot resolve a prelude import");
747                    }
748                }
749            }
750            ast::UseTreeKind::Nested { ref items, .. } => {
751                for &(ref tree, id) in items {
752                    self.build_reduced_graph_for_use_tree(
753                        // This particular use tree
754                        tree, id, &prefix, true, false, // The whole `use` item
755                        item, vis, root_span,
756                    );
757                }
758
759                // Empty groups `a::b::{}` are turned into synthetic `self` imports
760                // `a::b::c::{self as _}`, so that their prefixes are correctly
761                // resolved and checked for privacy/stability/etc.
762                if items.is_empty()
763                    && !prefix.is_empty()
764                    && (prefix.len() > 1 || prefix[0].ident.name != kw::PathRoot)
765                {
766                    let new_span = prefix[prefix.len() - 1].ident.span;
767                    let tree = ast::UseTree {
768                        prefix: ast::Path::from_ident(Ident::new(kw::SelfLower, new_span)),
769                        kind: ast::UseTreeKind::Simple(Some(Ident::new(kw::Underscore, new_span))),
770                    };
771                    self.build_reduced_graph_for_use_tree(
772                        // This particular use tree
773                        &tree,
774                        id,
775                        &prefix,
776                        true,
777                        true,
778                        // The whole `use` item
779                        item,
780                        Visibility::Restricted(
781                            self.parent_scope.module.nearest_parent_mod().expect_local(),
782                        ),
783                        root_span,
784                    );
785                }
786            }
787        }
788    }
789
790    fn build_reduced_graph_for_struct_variant(
791        &mut self,
792        fields: &[ast::FieldDef],
793        ident: Ident,
794        feed: Feed<'tcx, LocalDefId>,
795        adt_res: Res,
796        adt_vis: Visibility,
797        adt_span: Span,
798    ) {
799        let parent_scope = &self.parent_scope;
800        let parent = parent_scope.module;
801        let expansion = parent_scope.expansion;
802
803        // Define a name in the type namespace if it is not anonymous.
804        self.r.define_local(parent, ident, TypeNS, adt_res, adt_vis, adt_span, expansion);
805        self.r.feed_visibility(feed, adt_vis);
806        let def_id = feed.key();
807
808        // Record field names for error reporting.
809        self.insert_field_idents(def_id, fields);
810        self.insert_field_visibilities_local(def_id.to_def_id(), fields);
811    }
812
813    /// Constructs the reduced graph for one item.
814    fn build_reduced_graph_for_item(&mut self, item: &'a Item) {
815        let parent_scope = &self.parent_scope;
816        let parent = parent_scope.module;
817        let expansion = parent_scope.expansion;
818        let sp = item.span;
819        let vis = self.resolve_visibility(&item.vis);
820        let feed = self.r.feed(item.id);
821        let local_def_id = feed.key();
822        let def_id = local_def_id.to_def_id();
823        let def_kind = self.r.tcx.def_kind(def_id);
824        let res = Res::Def(def_kind, def_id);
825
826        self.r.feed_visibility(feed, vis);
827
828        match item.kind {
829            ItemKind::Use(ref use_tree) => {
830                self.build_reduced_graph_for_use_tree(
831                    // This particular use tree
832                    use_tree,
833                    item.id,
834                    &[],
835                    false,
836                    false,
837                    // The whole `use` item
838                    item,
839                    vis,
840                    use_tree.span(),
841                );
842            }
843
844            ItemKind::ExternCrate(orig_name, ident) => {
845                self.build_reduced_graph_for_extern_crate(
846                    orig_name,
847                    item,
848                    ident,
849                    local_def_id,
850                    vis,
851                );
852            }
853
854            ItemKind::Mod(_, ident, ref mod_kind) => {
855                self.r.define_local(parent, ident, TypeNS, res, vis, sp, expansion);
856
857                if let ast::ModKind::Loaded(_, Inline::No { had_parse_error: Err(_) }, _) = mod_kind
858                {
859                    self.r.mods_with_parse_errors.insert(def_id);
860                }
861                self.parent_scope.module = self.r.new_local_module(
862                    Some(parent),
863                    ModuleKind::Def(def_kind, def_id, Some(ident.name)),
864                    expansion.to_expn_id(),
865                    item.span,
866                    parent.no_implicit_prelude
867                        || ast::attr::contains_name(&item.attrs, sym::no_implicit_prelude),
868                );
869            }
870
871            // These items live in the value namespace.
872            ItemKind::Const(box ConstItem { ident, .. })
873            | ItemKind::Delegation(box Delegation { ident, .. })
874            | ItemKind::Static(box StaticItem { ident, .. }) => {
875                self.r.define_local(parent, ident, ValueNS, res, vis, sp, expansion);
876            }
877            ItemKind::Fn(box Fn { ident, .. }) => {
878                self.r.define_local(parent, ident, ValueNS, res, vis, sp, expansion);
879
880                // Functions introducing procedural macros reserve a slot
881                // in the macro namespace as well (see #52225).
882                self.define_macro(item);
883            }
884
885            // These items live in the type namespace.
886            ItemKind::TyAlias(box TyAlias { ident, .. })
887            | ItemKind::TraitAlias(box TraitAlias { ident, .. }) => {
888                self.r.define_local(parent, ident, TypeNS, res, vis, sp, expansion);
889            }
890
891            ItemKind::Enum(ident, _, _) | ItemKind::Trait(box ast::Trait { ident, .. }) => {
892                self.r.define_local(parent, ident, TypeNS, res, vis, sp, expansion);
893
894                self.parent_scope.module = self.r.new_local_module(
895                    Some(parent),
896                    ModuleKind::Def(def_kind, def_id, Some(ident.name)),
897                    expansion.to_expn_id(),
898                    item.span,
899                    parent.no_implicit_prelude,
900                );
901            }
902
903            // These items live in both the type and value namespaces.
904            ItemKind::Struct(ident, ref generics, ref vdata) => {
905                self.build_reduced_graph_for_struct_variant(
906                    vdata.fields(),
907                    ident,
908                    feed,
909                    res,
910                    vis,
911                    sp,
912                );
913
914                // If this is a tuple or unit struct, define a name
915                // in the value namespace as well.
916                if let Some(ctor_node_id) = vdata.ctor_node_id() {
917                    // If the structure is marked as non_exhaustive then lower the visibility
918                    // to within the crate.
919                    let mut ctor_vis = if vis.is_public()
920                        && ast::attr::contains_name(&item.attrs, sym::non_exhaustive)
921                    {
922                        Visibility::Restricted(CRATE_DEF_ID)
923                    } else {
924                        vis
925                    };
926
927                    let mut ret_fields = Vec::with_capacity(vdata.fields().len());
928
929                    for field in vdata.fields() {
930                        // NOTE: The field may be an expansion placeholder, but expansion sets
931                        // correct visibilities for unnamed field placeholders specifically, so the
932                        // constructor visibility should still be determined correctly.
933                        let field_vis = self
934                            .try_resolve_visibility(&field.vis, false)
935                            .unwrap_or(Visibility::Public);
936                        if ctor_vis.is_at_least(field_vis, self.r.tcx) {
937                            ctor_vis = field_vis;
938                        }
939                        ret_fields.push(field_vis.to_def_id());
940                    }
941                    let feed = self.r.feed(ctor_node_id);
942                    let ctor_def_id = feed.key();
943                    let ctor_res = self.res(ctor_def_id);
944                    self.r.define_local(parent, ident, ValueNS, ctor_res, ctor_vis, sp, expansion);
945                    self.r.feed_visibility(feed, ctor_vis);
946                    // We need the field visibility spans also for the constructor for E0603.
947                    self.insert_field_visibilities_local(ctor_def_id.to_def_id(), vdata.fields());
948
949                    self.r
950                        .struct_constructors
951                        .insert(local_def_id, (ctor_res, ctor_vis.to_def_id(), ret_fields));
952                }
953                self.r.struct_generics.insert(local_def_id, generics.clone());
954            }
955
956            ItemKind::Union(ident, _, ref vdata) => {
957                self.build_reduced_graph_for_struct_variant(
958                    vdata.fields(),
959                    ident,
960                    feed,
961                    res,
962                    vis,
963                    sp,
964                );
965            }
966
967            // These items do not add names to modules.
968            ItemKind::Impl { .. }
969            | ItemKind::ForeignMod(..)
970            | ItemKind::GlobalAsm(..)
971            | ItemKind::ConstBlock(..) => {}
972
973            ItemKind::MacroDef(..) | ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
974                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
975            }
976        }
977    }
978
979    fn build_reduced_graph_for_extern_crate(
980        &mut self,
981        orig_name: Option<Symbol>,
982        item: &Item,
983        orig_ident: Ident,
984        local_def_id: LocalDefId,
985        vis: Visibility,
986    ) {
987        let sp = item.span;
988        let parent_scope = self.parent_scope;
989        let parent = parent_scope.module;
990        let expansion = parent_scope.expansion;
991
992        let (used, module, decl) = if orig_name.is_none() && orig_ident.name == kw::SelfLower {
993            self.r.dcx().emit_err(errors::ExternCrateSelfRequiresRenaming { span: sp });
994            return;
995        } else if orig_name == Some(kw::SelfLower) {
996            Some(self.r.graph_root)
997        } else {
998            let tcx = self.r.tcx;
999            let crate_id = self.r.cstore_mut().process_extern_crate(
1000                self.r.tcx,
1001                item,
1002                local_def_id,
1003                &tcx.definitions_untracked(),
1004            );
1005            crate_id.map(|crate_id| {
1006                self.r.extern_crate_map.insert(local_def_id, crate_id);
1007                self.r.expect_module(crate_id.as_def_id())
1008            })
1009        }
1010        .map(|module| {
1011            let used = self.process_macro_use_imports(item, module);
1012            let decl = self.r.arenas.new_pub_def_decl(module.res().unwrap(), sp, expansion);
1013            (used, Some(ModuleOrUniformRoot::Module(module)), decl)
1014        })
1015        .unwrap_or((true, None, self.r.dummy_decl));
1016        let import = self.r.arenas.alloc_import(ImportData {
1017            kind: ImportKind::ExternCrate { source: orig_name, target: orig_ident, id: item.id },
1018            root_id: item.id,
1019            parent_scope,
1020            imported_module: CmCell::new(module),
1021            has_attributes: !item.attrs.is_empty(),
1022            use_span_with_attributes: item.span_with_attributes(),
1023            use_span: item.span,
1024            root_span: item.span,
1025            span: item.span,
1026            module_path: Vec::new(),
1027            vis,
1028            vis_span: item.vis.span,
1029        });
1030        if used {
1031            self.r.import_use_map.insert(import, Used::Other);
1032        }
1033        self.r.potentially_unused_imports.push(import);
1034        let import_decl = self.r.new_import_decl(decl, import);
1035        let ident = IdentKey::new(orig_ident);
1036        if ident.name != kw::Underscore && parent == self.r.graph_root {
1037            // FIXME: this error is technically unnecessary now when extern prelude is split into
1038            // two scopes, remove it with lang team approval.
1039            if let Some(entry) = self.r.extern_prelude.get(&ident)
1040                && expansion != LocalExpnId::ROOT
1041                && orig_name.is_some()
1042                && entry.item_decl.is_none()
1043            {
1044                self.r.dcx().emit_err(
1045                    errors::MacroExpandedExternCrateCannotShadowExternArguments { span: item.span },
1046                );
1047            }
1048
1049            use indexmap::map::Entry;
1050            match self.r.extern_prelude.entry(ident) {
1051                Entry::Occupied(mut occupied) => {
1052                    let entry = occupied.get_mut();
1053                    if entry.item_decl.is_some() {
1054                        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");
1055                        self.r.tcx.dcx().span_delayed_bug(item.span, msg);
1056                    } else {
1057                        entry.item_decl = Some((import_decl, orig_ident.span, orig_name.is_some()));
1058                    }
1059                    entry
1060                }
1061                Entry::Vacant(vacant) => vacant.insert(ExternPreludeEntry {
1062                    item_decl: Some((import_decl, orig_ident.span, true)),
1063                    flag_decl: None,
1064                }),
1065            };
1066        }
1067        self.r.plant_decl_into_local_module(ident, orig_ident.span, TypeNS, import_decl);
1068    }
1069
1070    /// Constructs the reduced graph for one foreign item.
1071    fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem, ident: Ident) {
1072        let feed = self.r.feed(item.id);
1073        let local_def_id = feed.key();
1074        let def_id = local_def_id.to_def_id();
1075        let ns = match item.kind {
1076            ForeignItemKind::Fn(..) => ValueNS,
1077            ForeignItemKind::Static(..) => ValueNS,
1078            ForeignItemKind::TyAlias(..) => TypeNS,
1079            ForeignItemKind::MacCall(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1080        };
1081        let parent = self.parent_scope.module;
1082        let expansion = self.parent_scope.expansion;
1083        let vis = self.resolve_visibility(&item.vis);
1084        self.r.define_local(parent, ident, ns, self.res(def_id), vis, item.span, expansion);
1085        self.r.feed_visibility(feed, vis);
1086    }
1087
1088    fn build_reduced_graph_for_block(&mut self, block: &Block) {
1089        let parent = self.parent_scope.module;
1090        let expansion = self.parent_scope.expansion;
1091        if self.block_needs_anonymous_module(block) {
1092            let module = self.r.new_local_module(
1093                Some(parent),
1094                ModuleKind::Block,
1095                expansion.to_expn_id(),
1096                block.span,
1097                parent.no_implicit_prelude,
1098            );
1099            self.r.block_map.insert(block.id, module);
1100            self.parent_scope.module = module; // Descend into the block.
1101        }
1102    }
1103
1104    fn add_macro_use_decl(
1105        &mut self,
1106        name: Symbol,
1107        decl: Decl<'ra>,
1108        span: Span,
1109        allow_shadowing: bool,
1110    ) {
1111        if self.r.macro_use_prelude.insert(name, decl).is_some() && !allow_shadowing {
1112            self.r.dcx().emit_err(errors::MacroUseNameAlreadyInUse { span, name });
1113        }
1114    }
1115
1116    /// Returns `true` if we should consider the underlying `extern crate` to be used.
1117    fn process_macro_use_imports(&mut self, item: &Item, module: Module<'ra>) -> bool {
1118        let mut import_all = None;
1119        let mut single_imports = ThinVec::new();
1120        if let Some(Attribute::Parsed(AttributeKind::MacroUse { span, arguments })) =
1121            AttributeParser::parse_limited(
1122                self.r.tcx.sess,
1123                &item.attrs,
1124                sym::macro_use,
1125                item.span,
1126                item.id,
1127                None,
1128            )
1129        {
1130            if self.parent_scope.module.parent.is_some() {
1131                self.r
1132                    .dcx()
1133                    .emit_err(errors::ExternCrateLoadingMacroNotAtCrateRoot { span: item.span });
1134            }
1135            if let ItemKind::ExternCrate(Some(orig_name), _) = item.kind
1136                && orig_name == kw::SelfLower
1137            {
1138                self.r.dcx().emit_err(errors::MacroUseExternCrateSelf { span });
1139            }
1140
1141            match arguments {
1142                MacroUseArgs::UseAll => import_all = Some(span),
1143                MacroUseArgs::UseSpecific(imports) => single_imports = imports,
1144            }
1145        }
1146
1147        let macro_use_import = |this: &Self, span, warn_private| {
1148            this.r.arenas.alloc_import(ImportData {
1149                kind: ImportKind::MacroUse { warn_private },
1150                root_id: item.id,
1151                parent_scope: this.parent_scope,
1152                imported_module: CmCell::new(Some(ModuleOrUniformRoot::Module(module))),
1153                use_span_with_attributes: item.span_with_attributes(),
1154                has_attributes: !item.attrs.is_empty(),
1155                use_span: item.span,
1156                root_span: span,
1157                span,
1158                module_path: Vec::new(),
1159                vis: Visibility::Restricted(CRATE_DEF_ID),
1160                vis_span: item.vis.span,
1161            })
1162        };
1163
1164        let allow_shadowing = self.parent_scope.expansion == LocalExpnId::ROOT;
1165        if let Some(span) = import_all {
1166            let import = macro_use_import(self, span, false);
1167            self.r.potentially_unused_imports.push(import);
1168            module.for_each_child_mut(self, |this, ident, _, ns, binding| {
1169                if ns == MacroNS {
1170                    let import =
1171                        if this.r.is_accessible_from(binding.vis(), this.parent_scope.module) {
1172                            import
1173                        } else {
1174                            // FIXME: This branch is used for reporting the `private_macro_use` lint
1175                            // and should eventually be removed.
1176                            if this.r.macro_use_prelude.contains_key(&ident.name) {
1177                                // Do not override already existing entries with compatibility entries.
1178                                return;
1179                            }
1180                            macro_use_import(this, span, true)
1181                        };
1182                    let import_decl = this.r.new_import_decl(binding, import);
1183                    this.add_macro_use_decl(ident.name, import_decl, span, allow_shadowing);
1184                }
1185            });
1186        } else {
1187            for ident in single_imports.iter().cloned() {
1188                let result = self.r.cm().maybe_resolve_ident_in_module(
1189                    ModuleOrUniformRoot::Module(module),
1190                    ident,
1191                    MacroNS,
1192                    &self.parent_scope,
1193                    None,
1194                );
1195                if let Ok(binding) = result {
1196                    let import = macro_use_import(self, ident.span, false);
1197                    self.r.potentially_unused_imports.push(import);
1198                    let import_decl = self.r.new_import_decl(binding, import);
1199                    self.add_macro_use_decl(ident.name, import_decl, ident.span, allow_shadowing);
1200                } else {
1201                    self.r.dcx().emit_err(errors::ImportedMacroNotFound { span: ident.span });
1202                }
1203            }
1204        }
1205        import_all.is_some() || !single_imports.is_empty()
1206    }
1207
1208    /// Returns `true` if this attribute list contains `macro_use`.
1209    fn contains_macro_use(&self, attrs: &[ast::Attribute]) -> bool {
1210        for attr in attrs {
1211            if attr.has_name(sym::macro_escape) {
1212                let inner_attribute = #[allow(non_exhaustive_omitted_patterns)] match attr.style {
    ast::AttrStyle::Inner => true,
    _ => false,
}matches!(attr.style, ast::AttrStyle::Inner);
1213                self.r
1214                    .dcx()
1215                    .emit_warn(errors::MacroExternDeprecated { span: attr.span, inner_attribute });
1216            } else if !attr.has_name(sym::macro_use) {
1217                continue;
1218            }
1219
1220            if !attr.is_word() {
1221                self.r.dcx().emit_err(errors::ArgumentsMacroUseNotAllowed { span: attr.span });
1222            }
1223            return true;
1224        }
1225
1226        false
1227    }
1228
1229    fn visit_invoc(&mut self, id: NodeId) -> LocalExpnId {
1230        let invoc_id = id.placeholder_to_expn_id();
1231        let old_parent_scope = self.r.invocation_parent_scopes.insert(invoc_id, self.parent_scope);
1232        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");
1233        invoc_id
1234    }
1235
1236    /// Visit invocation in context in which it can emit a named item (possibly `macro_rules`)
1237    /// directly into its parent scope's module.
1238    fn visit_invoc_in_module(&mut self, id: NodeId) -> MacroRulesScopeRef<'ra> {
1239        let invoc_id = self.visit_invoc(id);
1240        self.parent_scope.module.unexpanded_invocations.borrow_mut(self.r).insert(invoc_id);
1241        self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Invocation(invoc_id))
1242    }
1243
1244    fn proc_macro_stub(
1245        &self,
1246        item: &ast::Item,
1247        fn_ident: Ident,
1248    ) -> Option<(MacroKind, Ident, Span)> {
1249        if ast::attr::contains_name(&item.attrs, sym::proc_macro) {
1250            return Some((MacroKind::Bang, fn_ident, item.span));
1251        } else if ast::attr::contains_name(&item.attrs, sym::proc_macro_attribute) {
1252            return Some((MacroKind::Attr, fn_ident, item.span));
1253        } else if let Some(attr) = ast::attr::find_by_name(&item.attrs, sym::proc_macro_derive)
1254            && let Some(meta_item_inner) =
1255                attr.meta_item_list().and_then(|list| list.get(0).cloned())
1256            && let Some(ident) = meta_item_inner.ident()
1257        {
1258            return Some((MacroKind::Derive, ident, ident.span));
1259        }
1260        None
1261    }
1262
1263    // Mark the given macro as unused unless its name starts with `_`.
1264    // Macro uses will remove items from this set, and the remaining
1265    // items will be reported as `unused_macros`.
1266    fn insert_unused_macro(&mut self, ident: Ident, def_id: LocalDefId, node_id: NodeId) {
1267        if !ident.as_str().starts_with('_') {
1268            self.r.unused_macros.insert(def_id, (node_id, ident));
1269            let nrules = self.r.local_macro_map[&def_id].nrules;
1270            self.r.unused_macro_rules.insert(node_id, DenseBitSet::new_filled(nrules));
1271        }
1272    }
1273
1274    fn define_macro(&mut self, item: &ast::Item) -> MacroRulesScopeRef<'ra> {
1275        let parent_scope = self.parent_scope;
1276        let expansion = parent_scope.expansion;
1277        let feed = self.r.feed(item.id);
1278        let def_id = feed.key();
1279        let (res, orig_ident, span, macro_rules) = match &item.kind {
1280            ItemKind::MacroDef(ident, def) => {
1281                (self.res(def_id), *ident, item.span, def.macro_rules)
1282            }
1283            ItemKind::Fn(box ast::Fn { ident: fn_ident, .. }) => {
1284                match self.proc_macro_stub(item, *fn_ident) {
1285                    Some((macro_kind, ident, span)) => {
1286                        let macro_kinds = macro_kind.into();
1287                        let res = Res::Def(DefKind::Macro(macro_kinds), def_id.to_def_id());
1288                        let macro_data = MacroData::new(self.r.dummy_ext(macro_kind));
1289                        self.r.new_local_macro(def_id, macro_data);
1290                        self.r.proc_macro_stubs.insert(def_id);
1291                        (res, ident, span, false)
1292                    }
1293                    None => return parent_scope.macro_rules,
1294                }
1295            }
1296            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1297        };
1298
1299        self.r.local_macro_def_scopes.insert(def_id, parent_scope.module);
1300
1301        if macro_rules {
1302            let ident = IdentKey::new(orig_ident);
1303            self.r.macro_names.insert(ident);
1304            let is_macro_export = ast::attr::contains_name(&item.attrs, sym::macro_export);
1305            let vis = if is_macro_export {
1306                Visibility::Public
1307            } else {
1308                Visibility::Restricted(CRATE_DEF_ID)
1309            };
1310            let decl = self.r.arenas.new_def_decl(
1311                res,
1312                vis.to_def_id(),
1313                span,
1314                expansion,
1315                Some(parent_scope.module),
1316            );
1317            self.r.all_macro_rules.insert(ident.name);
1318            if is_macro_export {
1319                let import = self.r.arenas.alloc_import(ImportData {
1320                    kind: ImportKind::MacroExport,
1321                    root_id: item.id,
1322                    parent_scope: ParentScope { module: self.r.graph_root, ..parent_scope },
1323                    imported_module: CmCell::new(None),
1324                    has_attributes: false,
1325                    use_span_with_attributes: span,
1326                    use_span: span,
1327                    root_span: span,
1328                    span,
1329                    module_path: Vec::new(),
1330                    vis,
1331                    vis_span: item.vis.span,
1332                });
1333                self.r.import_use_map.insert(import, Used::Other);
1334                let import_decl = self.r.new_import_decl(decl, import);
1335                self.r.plant_decl_into_local_module(ident, orig_ident.span, MacroNS, import_decl);
1336            } else {
1337                self.r.check_reserved_macro_name(ident.name, orig_ident.span, res);
1338                self.insert_unused_macro(orig_ident, def_id, item.id);
1339            }
1340            self.r.feed_visibility(feed, vis);
1341            let scope = self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Def(
1342                self.r.arenas.alloc_macro_rules_decl(MacroRulesDecl {
1343                    parent_macro_rules_scope: parent_scope.macro_rules,
1344                    decl,
1345                    ident,
1346                    orig_ident_span: orig_ident.span,
1347                }),
1348            ));
1349            self.r.macro_rules_scopes.insert(def_id, scope);
1350            scope
1351        } else {
1352            let module = parent_scope.module;
1353            let vis = match item.kind {
1354                // Visibilities must not be resolved non-speculatively twice
1355                // and we already resolved this one as a `fn` item visibility.
1356                ItemKind::Fn(..) => {
1357                    self.try_resolve_visibility(&item.vis, false).unwrap_or(Visibility::Public)
1358                }
1359                _ => self.resolve_visibility(&item.vis),
1360            };
1361            if !vis.is_public() {
1362                self.insert_unused_macro(orig_ident, def_id, item.id);
1363            }
1364            self.r.define_local(module, orig_ident, MacroNS, res, vis, span, expansion);
1365            self.r.feed_visibility(feed, vis);
1366            self.parent_scope.macro_rules
1367        }
1368    }
1369}
1370
1371macro_rules! method {
1372    ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
1373        fn $visit(&mut self, node: &'a $ty) {
1374            if let $invoc(..) = node.kind {
1375                self.visit_invoc(node.id);
1376            } else {
1377                visit::$walk(self, node);
1378            }
1379        }
1380    };
1381}
1382
1383impl<'a, 'ra, 'tcx> Visitor<'a> for BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
1384    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);
1385    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);
1386    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);
1387
1388    fn visit_item(&mut self, item: &'a Item) {
1389        let orig_module_scope = self.parent_scope.module;
1390        self.parent_scope.macro_rules = match item.kind {
1391            ItemKind::MacroDef(..) => {
1392                let macro_rules_scope = self.define_macro(item);
1393                visit::walk_item(self, item);
1394                macro_rules_scope
1395            }
1396            ItemKind::MacCall(..) => self.visit_invoc_in_module(item.id),
1397            _ => {
1398                let orig_macro_rules_scope = self.parent_scope.macro_rules;
1399                self.build_reduced_graph_for_item(item);
1400                match item.kind {
1401                    ItemKind::Mod(..) => {
1402                        // Visit attributes after items for backward compatibility.
1403                        // This way they can use `macro_rules` defined later.
1404                        self.visit_vis(&item.vis);
1405                        item.kind.walk(&item.attrs, item.span, item.id, &item.vis, (), self);
1406                        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);
1407                    }
1408                    _ => visit::walk_item(self, item),
1409                }
1410                match item.kind {
1411                    ItemKind::Mod(..) if self.contains_macro_use(&item.attrs) => {
1412                        self.parent_scope.macro_rules
1413                    }
1414                    _ => orig_macro_rules_scope,
1415                }
1416            }
1417        };
1418        self.parent_scope.module = orig_module_scope;
1419    }
1420
1421    fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
1422        if let ast::StmtKind::MacCall(..) = stmt.kind {
1423            self.parent_scope.macro_rules = self.visit_invoc_in_module(stmt.id);
1424        } else {
1425            visit::walk_stmt(self, stmt);
1426        }
1427    }
1428
1429    fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
1430        let ident = match foreign_item.kind {
1431            ForeignItemKind::Static(box StaticItem { ident, .. })
1432            | ForeignItemKind::Fn(box Fn { ident, .. })
1433            | ForeignItemKind::TyAlias(box TyAlias { ident, .. }) => ident,
1434            ForeignItemKind::MacCall(_) => {
1435                self.visit_invoc_in_module(foreign_item.id);
1436                return;
1437            }
1438        };
1439
1440        self.build_reduced_graph_for_foreign_item(foreign_item, ident);
1441        visit::walk_item(self, foreign_item);
1442    }
1443
1444    fn visit_block(&mut self, block: &'a Block) {
1445        let orig_current_module = self.parent_scope.module;
1446        let orig_current_macro_rules_scope = self.parent_scope.macro_rules;
1447        self.build_reduced_graph_for_block(block);
1448        visit::walk_block(self, block);
1449        self.parent_scope.module = orig_current_module;
1450        self.parent_scope.macro_rules = orig_current_macro_rules_scope;
1451    }
1452
1453    fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
1454        let (ident, ns) = match item.kind {
1455            AssocItemKind::Const(box ConstItem { ident, .. })
1456            | AssocItemKind::Fn(box Fn { ident, .. })
1457            | AssocItemKind::Delegation(box Delegation { ident, .. }) => (ident, ValueNS),
1458
1459            AssocItemKind::Type(box TyAlias { ident, .. }) => (ident, TypeNS),
1460
1461            AssocItemKind::MacCall(_) => {
1462                match ctxt {
1463                    AssocCtxt::Trait => {
1464                        self.visit_invoc_in_module(item.id);
1465                    }
1466                    AssocCtxt::Impl { .. } => {
1467                        let invoc_id = item.id.placeholder_to_expn_id();
1468                        if !self.r.glob_delegation_invoc_ids.contains(&invoc_id) {
1469                            self.r
1470                                .impl_unexpanded_invocations
1471                                .entry(self.r.invocation_parent(invoc_id))
1472                                .or_default()
1473                                .insert(invoc_id);
1474                        }
1475                        self.visit_invoc(item.id);
1476                    }
1477                }
1478                return;
1479            }
1480
1481            AssocItemKind::DelegationMac(..) => {
1482                ::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")
1483            }
1484        };
1485        let vis = self.resolve_visibility(&item.vis);
1486        let feed = self.r.feed(item.id);
1487        let local_def_id = feed.key();
1488        let def_id = local_def_id.to_def_id();
1489
1490        if !(#[allow(non_exhaustive_omitted_patterns)] match ctxt {
    AssocCtxt::Impl { of_trait: true } => true,
    _ => false,
}matches!(ctxt, AssocCtxt::Impl { of_trait: true })
1491            && #[allow(non_exhaustive_omitted_patterns)] match item.vis.kind {
    ast::VisibilityKind::Inherited => true,
    _ => false,
}matches!(item.vis.kind, ast::VisibilityKind::Inherited))
1492        {
1493            // Trait impl item visibility is inherited from its trait when not specified
1494            // explicitly. In that case we cannot determine it here in early resolve,
1495            // so we leave a hole in the visibility table to be filled later.
1496            self.r.feed_visibility(feed, vis);
1497        }
1498
1499        if ctxt == AssocCtxt::Trait {
1500            let parent = self.parent_scope.module;
1501            let expansion = self.parent_scope.expansion;
1502            self.r.define_local(parent, ident, ns, self.res(def_id), vis, item.span, expansion);
1503        } 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)
1504            && ident.name != kw::Underscore
1505        {
1506            // Don't add underscore names, they cannot be looked up anyway.
1507            let impl_def_id = self.r.tcx.local_parent(local_def_id);
1508            let key = BindingKey::new(IdentKey::new(ident), ns);
1509            self.r.impl_binding_keys.entry(impl_def_id).or_default().insert(key);
1510        }
1511
1512        visit::walk_assoc_item(self, item, ctxt);
1513    }
1514
1515    fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1516        if !attr.is_doc_comment() && attr::is_builtin_attr(attr) {
1517            self.r
1518                .builtin_attrs
1519                .push((attr.get_normal_item().path.segments[0].ident, self.parent_scope));
1520        }
1521        visit::walk_attribute(self, attr);
1522    }
1523
1524    fn visit_arm(&mut self, arm: &'a ast::Arm) {
1525        if arm.is_placeholder {
1526            self.visit_invoc(arm.id);
1527        } else {
1528            visit::walk_arm(self, arm);
1529        }
1530    }
1531
1532    fn visit_expr_field(&mut self, f: &'a ast::ExprField) {
1533        if f.is_placeholder {
1534            self.visit_invoc(f.id);
1535        } else {
1536            visit::walk_expr_field(self, f);
1537        }
1538    }
1539
1540    fn visit_pat_field(&mut self, fp: &'a ast::PatField) {
1541        if fp.is_placeholder {
1542            self.visit_invoc(fp.id);
1543        } else {
1544            visit::walk_pat_field(self, fp);
1545        }
1546    }
1547
1548    fn visit_generic_param(&mut self, param: &'a ast::GenericParam) {
1549        if param.is_placeholder {
1550            self.visit_invoc(param.id);
1551        } else {
1552            visit::walk_generic_param(self, param);
1553        }
1554    }
1555
1556    fn visit_param(&mut self, p: &'a ast::Param) {
1557        if p.is_placeholder {
1558            self.visit_invoc(p.id);
1559        } else {
1560            visit::walk_param(self, p);
1561        }
1562    }
1563
1564    fn visit_field_def(&mut self, sf: &'a ast::FieldDef) {
1565        if sf.is_placeholder {
1566            self.visit_invoc(sf.id);
1567        } else {
1568            let vis = self.resolve_visibility(&sf.vis);
1569            self.r.feed_visibility(self.r.feed(sf.id), vis);
1570            visit::walk_field_def(self, sf);
1571        }
1572    }
1573
1574    // Constructs the reduced graph for one variant. Variants exist in the
1575    // type and value namespaces.
1576    fn visit_variant(&mut self, variant: &'a ast::Variant) {
1577        if variant.is_placeholder {
1578            self.visit_invoc_in_module(variant.id);
1579            return;
1580        }
1581
1582        let parent = self.parent_scope.module;
1583        let expn_id = self.parent_scope.expansion;
1584        let ident = variant.ident;
1585
1586        // Define a name in the type namespace.
1587        let feed = self.r.feed(variant.id);
1588        let def_id = feed.key();
1589        let vis = self.resolve_visibility(&variant.vis);
1590        self.r.define_local(parent, ident, TypeNS, self.res(def_id), vis, variant.span, expn_id);
1591        self.r.feed_visibility(feed, vis);
1592
1593        // If the variant is marked as non_exhaustive then lower the visibility to within the crate.
1594        let ctor_vis =
1595            if vis.is_public() && ast::attr::contains_name(&variant.attrs, sym::non_exhaustive) {
1596                Visibility::Restricted(CRATE_DEF_ID)
1597            } else {
1598                vis
1599            };
1600
1601        // Define a constructor name in the value namespace.
1602        if let Some(ctor_node_id) = variant.data.ctor_node_id() {
1603            let feed = self.r.feed(ctor_node_id);
1604            let ctor_def_id = feed.key();
1605            let ctor_res = self.res(ctor_def_id);
1606            self.r.define_local(parent, ident, ValueNS, ctor_res, ctor_vis, variant.span, expn_id);
1607            self.r.feed_visibility(feed, ctor_vis);
1608        }
1609
1610        // Record field names for error reporting.
1611        self.insert_field_idents(def_id, variant.data.fields());
1612        self.insert_field_visibilities_local(def_id.to_def_id(), variant.data.fields());
1613
1614        visit::walk_variant(self, variant);
1615    }
1616
1617    fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) {
1618        if p.is_placeholder {
1619            self.visit_invoc(p.id);
1620        } else {
1621            visit::walk_where_predicate(self, p);
1622        }
1623    }
1624
1625    fn visit_crate(&mut self, krate: &'a ast::Crate) {
1626        if krate.is_placeholder {
1627            self.visit_invoc_in_module(krate.id);
1628        } else {
1629            // Visit attributes after items for backward compatibility.
1630            // This way they can use `macro_rules` defined later.
1631            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);
1632            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);
1633            self.contains_macro_use(&krate.attrs);
1634        }
1635    }
1636}