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