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