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_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, Some(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::new(source.ident.name, 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 let Some(crate_name) = crate_name {
598                            // `crate_name` should not be interpreted as relative.
599                            module_path.push(Segment::from_ident_and_id(
600                                Ident::new(kw::PathRoot, 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 = sym::dummy;
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 sp = item.span;
739        let vis = self.resolve_visibility(&item.vis);
740        let feed = self.r.feed(item.id);
741        let local_def_id = feed.key();
742        let def_id = local_def_id.to_def_id();
743        let def_kind = self.r.tcx.def_kind(def_id);
744        let res = Res::Def(def_kind, def_id);
745
746        self.r.feed_visibility(feed, vis);
747
748        match item.kind {
749            ItemKind::Use(ref use_tree) => {
750                self.build_reduced_graph_for_use_tree(
751                    // This particular use tree
752                    use_tree,
753                    item.id,
754                    &[],
755                    false,
756                    false,
757                    // The whole `use` item
758                    item,
759                    vis,
760                    use_tree.span,
761                );
762            }
763
764            ItemKind::ExternCrate(orig_name, ident) => {
765                self.build_reduced_graph_for_extern_crate(
766                    orig_name,
767                    item,
768                    ident,
769                    local_def_id,
770                    vis,
771                    parent,
772                );
773            }
774
775            ItemKind::Mod(_, ident, ref mod_kind) => {
776                let module = self.r.new_module(
777                    Some(parent),
778                    ModuleKind::Def(def_kind, def_id, Some(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(box ConstItem { ident, .. })
796            | ItemKind::Delegation(box Delegation { ident, .. })
797            | ItemKind::Static(box StaticItem { ident, .. }) => {
798                self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion));
799            }
800            ItemKind::Fn(box Fn { ident, .. }) => {
801                self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion));
802
803                // Functions introducing procedural macros reserve a slot
804                // in the macro namespace as well (see #52225).
805                self.define_macro(item);
806            }
807
808            // These items live in the type namespace.
809            ItemKind::TyAlias(box TyAlias { ident, .. }) | ItemKind::TraitAlias(ident, ..) => {
810                self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion));
811            }
812
813            ItemKind::Enum(ident, _, _) | ItemKind::Trait(box ast::Trait { ident, .. }) => {
814                let module = self.r.new_module(
815                    Some(parent),
816                    ModuleKind::Def(def_kind, def_id, Some(ident.name)),
817                    expansion.to_expn_id(),
818                    item.span,
819                    parent.no_implicit_prelude,
820                );
821                self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion));
822                self.parent_scope.module = module;
823            }
824
825            // These items live in both the type and value namespaces.
826            ItemKind::Struct(ident, _, ref vdata) => {
827                self.build_reduced_graph_for_struct_variant(
828                    vdata.fields(),
829                    ident,
830                    feed,
831                    res,
832                    vis,
833                    sp,
834                );
835
836                // If this is a tuple or unit struct, define a name
837                // in the value namespace as well.
838                if let Some(ctor_node_id) = vdata.ctor_node_id() {
839                    // If the structure is marked as non_exhaustive then lower the visibility
840                    // to within the crate.
841                    let mut ctor_vis = if vis.is_public()
842                        && ast::attr::contains_name(&item.attrs, sym::non_exhaustive)
843                    {
844                        ty::Visibility::Restricted(CRATE_DEF_ID)
845                    } else {
846                        vis
847                    };
848
849                    let mut ret_fields = Vec::with_capacity(vdata.fields().len());
850
851                    for field in vdata.fields() {
852                        // NOTE: The field may be an expansion placeholder, but expansion sets
853                        // correct visibilities for unnamed field placeholders specifically, so the
854                        // constructor visibility should still be determined correctly.
855                        let field_vis = self
856                            .try_resolve_visibility(&field.vis, false)
857                            .unwrap_or(ty::Visibility::Public);
858                        if ctor_vis.is_at_least(field_vis, self.r.tcx) {
859                            ctor_vis = field_vis;
860                        }
861                        ret_fields.push(field_vis.to_def_id());
862                    }
863                    let feed = self.r.feed(ctor_node_id);
864                    let ctor_def_id = feed.key();
865                    let ctor_res = self.res(ctor_def_id);
866                    self.r.define(parent, ident, ValueNS, (ctor_res, ctor_vis, sp, expansion));
867                    self.r.feed_visibility(feed, ctor_vis);
868                    // We need the field visibility spans also for the constructor for E0603.
869                    self.insert_field_visibilities_local(ctor_def_id.to_def_id(), vdata.fields());
870
871                    self.r
872                        .struct_constructors
873                        .insert(local_def_id, (ctor_res, ctor_vis.to_def_id(), ret_fields));
874                }
875            }
876
877            ItemKind::Union(ident, _, ref vdata) => {
878                self.build_reduced_graph_for_struct_variant(
879                    vdata.fields(),
880                    ident,
881                    feed,
882                    res,
883                    vis,
884                    sp,
885                );
886            }
887
888            // These items do not add names to modules.
889            ItemKind::Impl(box Impl { of_trait: Some(..), .. })
890            | ItemKind::Impl { .. }
891            | ItemKind::ForeignMod(..)
892            | ItemKind::GlobalAsm(..) => {}
893
894            ItemKind::MacroDef(..) | ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
895                unreachable!()
896            }
897        }
898    }
899
900    fn build_reduced_graph_for_extern_crate(
901        &mut self,
902        orig_name: Option<Symbol>,
903        item: &Item,
904        ident: Ident,
905        local_def_id: LocalDefId,
906        vis: ty::Visibility,
907        parent: Module<'ra>,
908    ) {
909        let sp = item.span;
910        let parent_scope = self.parent_scope;
911        let expansion = parent_scope.expansion;
912
913        let (used, module, binding) = if orig_name.is_none() && ident.name == kw::SelfLower {
914            self.r.dcx().emit_err(errors::ExternCrateSelfRequiresRenaming { span: sp });
915            return;
916        } else if orig_name == Some(kw::SelfLower) {
917            Some(self.r.graph_root)
918        } else {
919            let tcx = self.r.tcx;
920            let crate_id = self.r.crate_loader(|c| {
921                c.process_extern_crate(item, local_def_id, &tcx.definitions_untracked())
922            });
923            crate_id.map(|crate_id| {
924                self.r.extern_crate_map.insert(local_def_id, crate_id);
925                self.r.expect_module(crate_id.as_def_id())
926            })
927        }
928        .map(|module| {
929            let used = self.process_macro_use_imports(item, module);
930            let vis = ty::Visibility::<LocalDefId>::Public;
931            let binding = (module, vis, sp, expansion).to_name_binding(self.r.arenas);
932            (used, Some(ModuleOrUniformRoot::Module(module)), binding)
933        })
934        .unwrap_or((true, None, self.r.dummy_binding));
935        let import = self.r.arenas.alloc_import(ImportData {
936            kind: ImportKind::ExternCrate { source: orig_name, target: ident, id: item.id },
937            root_id: item.id,
938            parent_scope: self.parent_scope,
939            imported_module: Cell::new(module),
940            has_attributes: !item.attrs.is_empty(),
941            use_span_with_attributes: item.span_with_attributes(),
942            use_span: item.span,
943            root_span: item.span,
944            span: item.span,
945            module_path: Vec::new(),
946            vis,
947        });
948        if used {
949            self.r.import_use_map.insert(import, Used::Other);
950        }
951        self.r.potentially_unused_imports.push(import);
952        let imported_binding = self.r.import(binding, import);
953        if parent == self.r.graph_root {
954            let ident = ident.normalize_to_macros_2_0();
955            if let Some(entry) = self.r.extern_prelude.get(&ident)
956                && expansion != LocalExpnId::ROOT
957                && orig_name.is_some()
958                && !entry.is_import()
959            {
960                self.r.dcx().emit_err(
961                    errors::MacroExpandedExternCrateCannotShadowExternArguments { span: item.span },
962                );
963                // `return` is intended to discard this binding because it's an
964                // unregistered ambiguity error which would result in a panic
965                // caused by inconsistency `path_res`
966                // more details: https://github.com/rust-lang/rust/pull/111761
967                return;
968            }
969            let entry = self
970                .r
971                .extern_prelude
972                .entry(ident)
973                .or_insert(ExternPreludeEntry { binding: None, introduced_by_item: true });
974            if orig_name.is_some() {
975                entry.introduced_by_item = true;
976            }
977            // Binding from `extern crate` item in source code can replace
978            // a binding from `--extern` on command line here.
979            if !entry.is_import() {
980                entry.binding = Some(imported_binding)
981            } else if ident.name != kw::Underscore {
982                self.r.dcx().span_delayed_bug(
983                    item.span,
984                    format!("it had been define the external module '{ident}' multiple times"),
985                );
986            }
987        }
988        self.r.define(parent, ident, TypeNS, imported_binding);
989    }
990
991    /// Constructs the reduced graph for one foreign item.
992    fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem, ident: Ident) {
993        let feed = self.r.feed(item.id);
994        let local_def_id = feed.key();
995        let def_id = local_def_id.to_def_id();
996        let ns = match item.kind {
997            ForeignItemKind::Fn(..) => ValueNS,
998            ForeignItemKind::Static(..) => ValueNS,
999            ForeignItemKind::TyAlias(..) => TypeNS,
1000            ForeignItemKind::MacCall(..) => unreachable!(),
1001        };
1002        let parent = self.parent_scope.module;
1003        let expansion = self.parent_scope.expansion;
1004        let vis = self.resolve_visibility(&item.vis);
1005        self.r.define(parent, ident, ns, (self.res(def_id), vis, item.span, expansion));
1006        self.r.feed_visibility(feed, vis);
1007    }
1008
1009    fn build_reduced_graph_for_block(&mut self, block: &Block) {
1010        let parent = self.parent_scope.module;
1011        let expansion = self.parent_scope.expansion;
1012        if self.block_needs_anonymous_module(block) {
1013            let module = self.r.new_module(
1014                Some(parent),
1015                ModuleKind::Block,
1016                expansion.to_expn_id(),
1017                block.span,
1018                parent.no_implicit_prelude,
1019            );
1020            self.r.block_map.insert(block.id, module);
1021            self.parent_scope.module = module; // Descend into the block.
1022        }
1023    }
1024
1025    fn add_macro_use_binding(
1026        &mut self,
1027        name: Symbol,
1028        binding: NameBinding<'ra>,
1029        span: Span,
1030        allow_shadowing: bool,
1031    ) {
1032        if self.r.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing {
1033            self.r.dcx().emit_err(errors::MacroUseNameAlreadyInUse { span, name });
1034        }
1035    }
1036
1037    /// Returns `true` if we should consider the underlying `extern crate` to be used.
1038    fn process_macro_use_imports(&mut self, item: &Item, module: Module<'ra>) -> bool {
1039        let mut import_all = None;
1040        let mut single_imports = Vec::new();
1041        for attr in &item.attrs {
1042            if attr.has_name(sym::macro_use) {
1043                if self.parent_scope.module.parent.is_some() {
1044                    self.r.dcx().emit_err(errors::ExternCrateLoadingMacroNotAtCrateRoot {
1045                        span: item.span,
1046                    });
1047                }
1048                if let ItemKind::ExternCrate(Some(orig_name), _) = item.kind
1049                    && orig_name == kw::SelfLower
1050                {
1051                    self.r.dcx().emit_err(errors::MacroUseExternCrateSelf { span: attr.span });
1052                }
1053                let ill_formed = |span| {
1054                    self.r.dcx().emit_err(errors::BadMacroImport { span });
1055                };
1056                match attr.meta() {
1057                    Some(meta) => match meta.kind {
1058                        MetaItemKind::Word => {
1059                            import_all = Some(meta.span);
1060                            break;
1061                        }
1062                        MetaItemKind::List(meta_item_inners) => {
1063                            for meta_item_inner in meta_item_inners {
1064                                match meta_item_inner.ident() {
1065                                    Some(ident) if meta_item_inner.is_word() => {
1066                                        single_imports.push(ident)
1067                                    }
1068                                    _ => ill_formed(meta_item_inner.span()),
1069                                }
1070                            }
1071                        }
1072                        MetaItemKind::NameValue(..) => ill_formed(meta.span),
1073                    },
1074                    None => ill_formed(attr.span),
1075                }
1076            }
1077        }
1078
1079        let macro_use_import = |this: &Self, span, warn_private| {
1080            this.r.arenas.alloc_import(ImportData {
1081                kind: ImportKind::MacroUse { warn_private },
1082                root_id: item.id,
1083                parent_scope: this.parent_scope,
1084                imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
1085                use_span_with_attributes: item.span_with_attributes(),
1086                has_attributes: !item.attrs.is_empty(),
1087                use_span: item.span,
1088                root_span: span,
1089                span,
1090                module_path: Vec::new(),
1091                vis: ty::Visibility::Restricted(CRATE_DEF_ID),
1092            })
1093        };
1094
1095        let allow_shadowing = self.parent_scope.expansion == LocalExpnId::ROOT;
1096        if let Some(span) = import_all {
1097            let import = macro_use_import(self, span, false);
1098            self.r.potentially_unused_imports.push(import);
1099            module.for_each_child(self, |this, ident, ns, binding| {
1100                if ns == MacroNS {
1101                    let import = if this.r.is_accessible_from(binding.vis, this.parent_scope.module)
1102                    {
1103                        import
1104                    } else {
1105                        // FIXME: This branch is used for reporting the `private_macro_use` lint
1106                        // and should eventually be removed.
1107                        if this.r.macro_use_prelude.contains_key(&ident.name) {
1108                            // Do not override already existing entries with compatibility entries.
1109                            return;
1110                        }
1111                        macro_use_import(this, span, true)
1112                    };
1113                    let import_binding = this.r.import(binding, import);
1114                    this.add_macro_use_binding(ident.name, import_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(
1181        &self,
1182        item: &ast::Item,
1183        fn_ident: Ident,
1184    ) -> Option<(MacroKind, Ident, Span)> {
1185        if ast::attr::contains_name(&item.attrs, sym::proc_macro) {
1186            return Some((MacroKind::Bang, fn_ident, item.span));
1187        } else if ast::attr::contains_name(&item.attrs, sym::proc_macro_attribute) {
1188            return Some((MacroKind::Attr, fn_ident, item.span));
1189        } else if let Some(attr) = ast::attr::find_by_name(&item.attrs, sym::proc_macro_derive)
1190            && let Some(meta_item_inner) =
1191                attr.meta_item_list().and_then(|list| list.get(0).cloned())
1192            && let Some(ident) = meta_item_inner.ident()
1193        {
1194            return Some((MacroKind::Derive, ident, ident.span));
1195        }
1196        None
1197    }
1198
1199    // Mark the given macro as unused unless its name starts with `_`.
1200    // Macro uses will remove items from this set, and the remaining
1201    // items will be reported as `unused_macros`.
1202    fn insert_unused_macro(&mut self, ident: Ident, def_id: LocalDefId, node_id: NodeId) {
1203        if !ident.as_str().starts_with('_') {
1204            self.r.unused_macros.insert(def_id, (node_id, ident));
1205            for (rule_i, rule_span) in &self.r.macro_map[&def_id.to_def_id()].rule_spans {
1206                self.r
1207                    .unused_macro_rules
1208                    .entry(node_id)
1209                    .or_default()
1210                    .insert(*rule_i, (ident, *rule_span));
1211            }
1212        }
1213    }
1214
1215    fn define_macro(&mut self, item: &ast::Item) -> MacroRulesScopeRef<'ra> {
1216        let parent_scope = self.parent_scope;
1217        let expansion = parent_scope.expansion;
1218        let feed = self.r.feed(item.id);
1219        let def_id = feed.key();
1220        let (res, ident, span, macro_rules) = match &item.kind {
1221            ItemKind::MacroDef(ident, def) => {
1222                (self.res(def_id), *ident, item.span, def.macro_rules)
1223            }
1224            ItemKind::Fn(box ast::Fn { ident: fn_ident, .. }) => {
1225                match self.proc_macro_stub(item, *fn_ident) {
1226                    Some((macro_kind, ident, span)) => {
1227                        let res = Res::Def(DefKind::Macro(macro_kind), def_id.to_def_id());
1228                        let macro_data = MacroData::new(self.r.dummy_ext(macro_kind));
1229                        self.r.macro_map.insert(def_id.to_def_id(), macro_data);
1230                        self.r.proc_macro_stubs.insert(def_id);
1231                        (res, ident, span, false)
1232                    }
1233                    None => return parent_scope.macro_rules,
1234                }
1235            }
1236            _ => unreachable!(),
1237        };
1238
1239        self.r.local_macro_def_scopes.insert(def_id, parent_scope.module);
1240
1241        if macro_rules {
1242            let ident = ident.normalize_to_macros_2_0();
1243            self.r.macro_names.insert(ident);
1244            let is_macro_export = ast::attr::contains_name(&item.attrs, sym::macro_export);
1245            let vis = if is_macro_export {
1246                ty::Visibility::Public
1247            } else {
1248                ty::Visibility::Restricted(CRATE_DEF_ID)
1249            };
1250            let binding = (res, vis, span, expansion).to_name_binding(self.r.arenas);
1251            self.r.set_binding_parent_module(binding, parent_scope.module);
1252            self.r.all_macro_rules.insert(ident.name);
1253            if is_macro_export {
1254                let import = self.r.arenas.alloc_import(ImportData {
1255                    kind: ImportKind::MacroExport,
1256                    root_id: item.id,
1257                    parent_scope: self.parent_scope,
1258                    imported_module: Cell::new(None),
1259                    has_attributes: false,
1260                    use_span_with_attributes: span,
1261                    use_span: span,
1262                    root_span: span,
1263                    span,
1264                    module_path: Vec::new(),
1265                    vis,
1266                });
1267                self.r.import_use_map.insert(import, Used::Other);
1268                let import_binding = self.r.import(binding, import);
1269                self.r.define(self.r.graph_root, ident, MacroNS, import_binding);
1270            } else {
1271                self.r.check_reserved_macro_name(ident, res);
1272                self.insert_unused_macro(ident, def_id, item.id);
1273            }
1274            self.r.feed_visibility(feed, vis);
1275            let scope = self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Binding(
1276                self.r.arenas.alloc_macro_rules_binding(MacroRulesBinding {
1277                    parent_macro_rules_scope: parent_scope.macro_rules,
1278                    binding,
1279                    ident,
1280                }),
1281            ));
1282            self.r.macro_rules_scopes.insert(def_id, scope);
1283            scope
1284        } else {
1285            let module = parent_scope.module;
1286            let vis = match item.kind {
1287                // Visibilities must not be resolved non-speculatively twice
1288                // and we already resolved this one as a `fn` item visibility.
1289                ItemKind::Fn(..) => {
1290                    self.try_resolve_visibility(&item.vis, false).unwrap_or(ty::Visibility::Public)
1291                }
1292                _ => self.resolve_visibility(&item.vis),
1293            };
1294            if !vis.is_public() {
1295                self.insert_unused_macro(ident, def_id, item.id);
1296            }
1297            self.r.define(module, ident, MacroNS, (res, vis, span, expansion));
1298            self.r.feed_visibility(feed, vis);
1299            self.parent_scope.macro_rules
1300        }
1301    }
1302}
1303
1304macro_rules! method {
1305    ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
1306        fn $visit(&mut self, node: &'a $ty) {
1307            if let $invoc(..) = node.kind {
1308                self.visit_invoc(node.id);
1309            } else {
1310                visit::$walk(self, node);
1311            }
1312        }
1313    };
1314}
1315
1316impl<'a, 'ra, 'tcx> Visitor<'a> for BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
1317    method!(visit_expr: ast::Expr, ast::ExprKind::MacCall, walk_expr);
1318    method!(visit_pat: ast::Pat, ast::PatKind::MacCall, walk_pat);
1319    method!(visit_ty: ast::Ty, ast::TyKind::MacCall, walk_ty);
1320
1321    fn visit_item(&mut self, item: &'a Item) {
1322        let orig_module_scope = self.parent_scope.module;
1323        self.parent_scope.macro_rules = match item.kind {
1324            ItemKind::MacroDef(..) => {
1325                let macro_rules_scope = self.define_macro(item);
1326                visit::walk_item(self, item);
1327                macro_rules_scope
1328            }
1329            ItemKind::MacCall(..) => self.visit_invoc_in_module(item.id),
1330            _ => {
1331                let orig_macro_rules_scope = self.parent_scope.macro_rules;
1332                self.build_reduced_graph_for_item(item);
1333                match item.kind {
1334                    ItemKind::Mod(..) => {
1335                        // Visit attributes after items for backward compatibility.
1336                        // This way they can use `macro_rules` defined later.
1337                        self.visit_vis(&item.vis);
1338                        item.kind.walk(item.span, item.id, &item.vis, (), self);
1339                        visit::walk_list!(self, visit_attribute, &item.attrs);
1340                    }
1341                    _ => visit::walk_item(self, item),
1342                }
1343                match item.kind {
1344                    ItemKind::Mod(..) if self.contains_macro_use(&item.attrs) => {
1345                        self.parent_scope.macro_rules
1346                    }
1347                    _ => orig_macro_rules_scope,
1348                }
1349            }
1350        };
1351        self.parent_scope.module = orig_module_scope;
1352    }
1353
1354    fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
1355        if let ast::StmtKind::MacCall(..) = stmt.kind {
1356            self.parent_scope.macro_rules = self.visit_invoc_in_module(stmt.id);
1357        } else {
1358            visit::walk_stmt(self, stmt);
1359        }
1360    }
1361
1362    fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
1363        let ident = match foreign_item.kind {
1364            ForeignItemKind::Static(box StaticItem { ident, .. })
1365            | ForeignItemKind::Fn(box Fn { ident, .. })
1366            | ForeignItemKind::TyAlias(box TyAlias { ident, .. }) => ident,
1367            ForeignItemKind::MacCall(_) => {
1368                self.visit_invoc_in_module(foreign_item.id);
1369                return;
1370            }
1371        };
1372
1373        self.build_reduced_graph_for_foreign_item(foreign_item, ident);
1374        visit::walk_item(self, foreign_item);
1375    }
1376
1377    fn visit_block(&mut self, block: &'a Block) {
1378        let orig_current_module = self.parent_scope.module;
1379        let orig_current_macro_rules_scope = self.parent_scope.macro_rules;
1380        self.build_reduced_graph_for_block(block);
1381        visit::walk_block(self, block);
1382        self.parent_scope.module = orig_current_module;
1383        self.parent_scope.macro_rules = orig_current_macro_rules_scope;
1384    }
1385
1386    fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
1387        let (ident, ns) = match item.kind {
1388            AssocItemKind::Const(box ConstItem { ident, .. })
1389            | AssocItemKind::Fn(box Fn { ident, .. })
1390            | AssocItemKind::Delegation(box Delegation { ident, .. }) => (ident, ValueNS),
1391
1392            AssocItemKind::Type(box TyAlias { ident, .. }) => (ident, TypeNS),
1393
1394            AssocItemKind::MacCall(_) => {
1395                match ctxt {
1396                    AssocCtxt::Trait => {
1397                        self.visit_invoc_in_module(item.id);
1398                    }
1399                    AssocCtxt::Impl { .. } => {
1400                        let invoc_id = item.id.placeholder_to_expn_id();
1401                        if !self.r.glob_delegation_invoc_ids.contains(&invoc_id) {
1402                            self.r
1403                                .impl_unexpanded_invocations
1404                                .entry(self.r.invocation_parent(invoc_id))
1405                                .or_default()
1406                                .insert(invoc_id);
1407                        }
1408                        self.visit_invoc(item.id);
1409                    }
1410                }
1411                return;
1412            }
1413
1414            AssocItemKind::DelegationMac(..) => bug!(),
1415        };
1416        let vis = self.resolve_visibility(&item.vis);
1417        let feed = self.r.feed(item.id);
1418        let local_def_id = feed.key();
1419        let def_id = local_def_id.to_def_id();
1420
1421        if !(matches!(ctxt, AssocCtxt::Impl { of_trait: true })
1422            && matches!(item.vis.kind, ast::VisibilityKind::Inherited))
1423        {
1424            // Trait impl item visibility is inherited from its trait when not specified
1425            // explicitly. In that case we cannot determine it here in early resolve,
1426            // so we leave a hole in the visibility table to be filled later.
1427            self.r.feed_visibility(feed, vis);
1428        }
1429
1430        if ctxt == AssocCtxt::Trait {
1431            let parent = self.parent_scope.module;
1432            let expansion = self.parent_scope.expansion;
1433            self.r.define(parent, ident, ns, (self.res(def_id), vis, item.span, expansion));
1434        } else if !matches!(&item.kind, AssocItemKind::Delegation(deleg) if deleg.from_glob) {
1435            let impl_def_id = self.r.tcx.local_parent(local_def_id);
1436            let key = BindingKey::new(ident.normalize_to_macros_2_0(), ns);
1437            self.r.impl_binding_keys.entry(impl_def_id).or_default().insert(key);
1438        }
1439
1440        visit::walk_assoc_item(self, item, ctxt);
1441    }
1442
1443    fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1444        if !attr.is_doc_comment() && attr::is_builtin_attr(attr) {
1445            self.r
1446                .builtin_attrs
1447                .push((attr.get_normal_item().path.segments[0].ident, self.parent_scope));
1448        }
1449        visit::walk_attribute(self, attr);
1450    }
1451
1452    fn visit_arm(&mut self, arm: &'a ast::Arm) {
1453        if arm.is_placeholder {
1454            self.visit_invoc(arm.id);
1455        } else {
1456            visit::walk_arm(self, arm);
1457        }
1458    }
1459
1460    fn visit_expr_field(&mut self, f: &'a ast::ExprField) {
1461        if f.is_placeholder {
1462            self.visit_invoc(f.id);
1463        } else {
1464            visit::walk_expr_field(self, f);
1465        }
1466    }
1467
1468    fn visit_pat_field(&mut self, fp: &'a ast::PatField) {
1469        if fp.is_placeholder {
1470            self.visit_invoc(fp.id);
1471        } else {
1472            visit::walk_pat_field(self, fp);
1473        }
1474    }
1475
1476    fn visit_generic_param(&mut self, param: &'a ast::GenericParam) {
1477        if param.is_placeholder {
1478            self.visit_invoc(param.id);
1479        } else {
1480            visit::walk_generic_param(self, param);
1481        }
1482    }
1483
1484    fn visit_param(&mut self, p: &'a ast::Param) {
1485        if p.is_placeholder {
1486            self.visit_invoc(p.id);
1487        } else {
1488            visit::walk_param(self, p);
1489        }
1490    }
1491
1492    fn visit_field_def(&mut self, sf: &'a ast::FieldDef) {
1493        if sf.is_placeholder {
1494            self.visit_invoc(sf.id);
1495        } else {
1496            let vis = self.resolve_visibility(&sf.vis);
1497            self.r.feed_visibility(self.r.feed(sf.id), vis);
1498            visit::walk_field_def(self, sf);
1499        }
1500    }
1501
1502    // Constructs the reduced graph for one variant. Variants exist in the
1503    // type and value namespaces.
1504    fn visit_variant(&mut self, variant: &'a ast::Variant) {
1505        if variant.is_placeholder {
1506            self.visit_invoc_in_module(variant.id);
1507            return;
1508        }
1509
1510        let parent = self.parent_scope.module;
1511        let expn_id = self.parent_scope.expansion;
1512        let ident = variant.ident;
1513
1514        // Define a name in the type namespace.
1515        let feed = self.r.feed(variant.id);
1516        let def_id = feed.key();
1517        let vis = self.resolve_visibility(&variant.vis);
1518        self.r.define(parent, ident, TypeNS, (self.res(def_id), vis, variant.span, expn_id));
1519        self.r.feed_visibility(feed, vis);
1520
1521        // If the variant is marked as non_exhaustive then lower the visibility to within the crate.
1522        let ctor_vis =
1523            if vis.is_public() && ast::attr::contains_name(&variant.attrs, sym::non_exhaustive) {
1524                ty::Visibility::Restricted(CRATE_DEF_ID)
1525            } else {
1526                vis
1527            };
1528
1529        // Define a constructor name in the value namespace.
1530        if let Some(ctor_node_id) = variant.data.ctor_node_id() {
1531            let feed = self.r.feed(ctor_node_id);
1532            let ctor_def_id = feed.key();
1533            let ctor_res = self.res(ctor_def_id);
1534            self.r.define(parent, ident, ValueNS, (ctor_res, ctor_vis, variant.span, expn_id));
1535            self.r.feed_visibility(feed, ctor_vis);
1536        }
1537
1538        // Record field names for error reporting.
1539        self.insert_field_idents(def_id, variant.data.fields());
1540        self.insert_field_visibilities_local(def_id.to_def_id(), variant.data.fields());
1541
1542        visit::walk_variant(self, variant);
1543    }
1544
1545    fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) {
1546        if p.is_placeholder {
1547            self.visit_invoc(p.id);
1548        } else {
1549            visit::walk_where_predicate(self, p);
1550        }
1551    }
1552
1553    fn visit_crate(&mut self, krate: &'a ast::Crate) {
1554        if krate.is_placeholder {
1555            self.visit_invoc_in_module(krate.id);
1556        } else {
1557            // Visit attributes after items for backward compatibility.
1558            // This way they can use `macro_rules` defined later.
1559            visit::walk_list!(self, visit_item, &krate.items);
1560            visit::walk_list!(self, visit_attribute, &krate.attrs);
1561            self.contains_macro_use(&krate.attrs);
1562        }
1563    }
1564}