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