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