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