rustc_resolve/
build_reduced_graph.rs

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