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