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