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