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