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