Skip to main content

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