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