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