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, DelayedVisResolutionError, ExternModule,
39    ExternPreludeEntry, Finalize, IdentKey, LocalModule, MacroData, Module, ModuleKind,
40    ModuleOrUniformRoot, ParentScope, PathResult, Res, Resolver, Segment, Used, VisResolutionError,
41    errors,
42};
43
44impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
45    /// Attempt to put the declaration with the given name and namespace into the module,
46    /// and report an error in case of a collision.
47    pub(crate) fn plant_decl_into_local_module(
48        &mut self,
49        ident: IdentKey,
50        orig_ident_span: Span,
51        ns: Namespace,
52        decl: Decl<'ra>,
53    ) {
54        if let Err(old_decl) =
55            self.try_plant_decl_into_local_module(ident, orig_ident_span, ns, decl, false)
56        {
57            self.report_conflict(ident, ns, old_decl, decl);
58        }
59    }
60
61    /// Create a name definition from the given components, and put it into the local module.
62    fn define_local(
63        &mut self,
64        parent: LocalModule<'ra>,
65        orig_ident: Ident,
66        ns: Namespace,
67        res: Res,
68        vis: Visibility,
69        span: Span,
70        expn_id: LocalExpnId,
71    ) {
72        let decl =
73            self.arenas.new_def_decl(res, vis.to_def_id(), span, expn_id, Some(parent.to_module()));
74        let ident = IdentKey::new(orig_ident);
75        self.plant_decl_into_local_module(ident, orig_ident.span, ns, decl);
76    }
77
78    /// Create a name definition from the given components, and put it into the extern module.
79    fn define_extern(
80        &self,
81        parent: ExternModule<'ra>,
82        ident: IdentKey,
83        orig_ident_span: Span,
84        ns: Namespace,
85        child_index: usize,
86        res: Res,
87        vis: Visibility<DefId>,
88        span: Span,
89        expansion: LocalExpnId,
90        ambiguity: Option<Decl<'ra>>,
91    ) {
92        let decl = self.arenas.alloc_decl(DeclData {
93            kind: DeclKind::Def(res),
94            ambiguity: CmCell::new(ambiguity),
95            // External ambiguities always report the `AMBIGUOUS_GLOB_IMPORTS` lint at the moment.
96            warn_ambiguity: CmCell::new(true),
97            initial_vis: vis,
98            ambiguity_vis_max: CmCell::new(None),
99            ambiguity_vis_min: CmCell::new(None),
100            span,
101            expansion,
102            parent_module: Some(parent.to_module()),
103        });
104        // Even if underscore names cannot be looked up, we still need to add them to modules,
105        // because they can be fetched by glob imports from those modules, and bring traits
106        // into scope both directly and through glob imports.
107        let key =
108            BindingKey::new_disambiguated(ident, ns, || (child_index + 1).try_into().unwrap()); // 0 indicates no underscore
109        if self
110            .resolution_or_default(parent.to_module(), key, orig_ident_span)
111            .borrow_mut_unchecked()
112            .non_glob_decl
113            .replace(decl)
114            .is_some()
115        {
116            ::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");
117        }
118    }
119
120    /// Walks up the tree of definitions starting at `def_id`,
121    /// stopping at the first encountered module.
122    /// Parent block modules for arbitrary def-ids are not recorded for the local crate,
123    /// and are not preserved in metadata for foreign crates, so block modules are never
124    /// returned by this function.
125    ///
126    /// For the local crate ignoring block modules may be incorrect, so use this method with care.
127    ///
128    /// For foreign crates block modules can be ignored without introducing observable differences,
129    /// moreover they has to be ignored right now because they are not kept in metadata.
130    /// Foreign parent modules are used for resolving names used by foreign macros with def-site
131    /// hygiene, therefore block module ignorability relies on macros with def-site hygiene and
132    /// block module parents being unreachable from other crates.
133    /// Reachable macros with block module parents exist due to `#[macro_export] macro_rules!`,
134    /// but they cannot use def-site hygiene, so the assumption holds
135    /// (<https://github.com/rust-lang/rust/pull/77984#issuecomment-712445508>).
136    pub(crate) fn get_nearest_non_block_module(&self, mut def_id: DefId) -> Module<'ra> {
137        loop {
138            match self.get_module(def_id) {
139                Some(module) => return module,
140                None => def_id = self.tcx.parent(def_id),
141            }
142        }
143    }
144
145    pub(crate) fn expect_module(&self, def_id: DefId) -> Module<'ra> {
146        self.get_module(def_id).expect("argument `DefId` is not a module")
147    }
148
149    /// If `def_id` refers to a module (in resolver's sense, i.e. a module item, crate root, enum,
150    /// or trait), then this function returns that module's resolver representation, otherwise it
151    /// returns `None`.
152    pub(crate) fn get_module(&self, def_id: DefId) -> Option<Module<'ra>> {
153        match def_id.as_local() {
154            Some(local_def_id) => self.local_module_map.get(&local_def_id).map(|m| m.to_module()),
155            None => {
156                if let module @ Some(..) = self.extern_module_map.borrow().get(&def_id) {
157                    return module.map(|m| m.to_module());
158                }
159
160                // Query `def_kind` is not used because query system overhead is too expensive here.
161                let def_kind = self.cstore().def_kind_untracked(def_id);
162                if def_kind.is_module_like() {
163                    let parent = self.tcx.opt_parent(def_id).map(|parent_id| {
164                        self.get_nearest_non_block_module(parent_id).expect_extern()
165                    });
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                    let module = 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                    return Some(module.to_module());
178                }
179
180                None
181            }
182        }
183    }
184
185    pub(crate) fn expn_def_scope(&self, expn_id: ExpnId) -> Module<'ra> {
186        match expn_id.expn_data().macro_def_id {
187            Some(def_id) => self.macro_def_scope(def_id),
188            None => expn_id
189                .as_local()
190                .and_then(|expn_id| self.ast_transform_scopes.get(&expn_id).copied())
191                .unwrap_or(self.graph_root)
192                .to_module(),
193        }
194    }
195
196    pub(crate) fn macro_def_scope(&self, def_id: DefId) -> Module<'ra> {
197        if let Some(id) = def_id.as_local() {
198            self.local_macro_def_scopes[&id].to_module()
199        } else {
200            self.get_nearest_non_block_module(def_id)
201        }
202    }
203
204    pub(crate) fn get_macro(&self, res: Res) -> Option<&'ra MacroData> {
205        match res {
206            Res::Def(DefKind::Macro(..), def_id) => Some(self.get_macro_by_def_id(def_id)),
207            Res::NonMacroAttr(_) => Some(self.non_macro_attr),
208            _ => None,
209        }
210    }
211
212    pub(crate) fn get_macro_by_def_id(&self, def_id: DefId) -> &'ra MacroData {
213        // Local macros are always compiled.
214        match def_id.as_local() {
215            Some(local_def_id) => self.local_macro_map[&local_def_id],
216            None => *self.extern_macro_map.borrow_mut().entry(def_id).or_insert_with(|| {
217                let loaded_macro = self.cstore().load_macro_untracked(self.tcx, def_id);
218                let macro_data = match loaded_macro {
219                    LoadedMacro::MacroDef { def, ident, attrs, span, edition } => {
220                        self.compile_macro(&def, ident, &attrs, span, ast::DUMMY_NODE_ID, edition)
221                    }
222                    LoadedMacro::ProcMacro(ext) => MacroData::new(Arc::new(ext)),
223                };
224
225                self.arenas.alloc_macro(macro_data)
226            }),
227        }
228    }
229
230    /// Add every proc macro accessible from the current crate to the `macro_map` so diagnostics can
231    /// find them for suggestions.
232    pub(crate) fn register_macros_for_all_crates(&mut self) {
233        if !self.all_crate_macros_already_registered {
234            for def_id in self.cstore().all_proc_macro_def_ids(self.tcx) {
235                self.get_macro_by_def_id(def_id);
236            }
237            self.all_crate_macros_already_registered = true;
238        }
239    }
240
241    pub(crate) fn try_resolve_visibility(
242        &mut self,
243        parent_scope: &ParentScope<'ra>,
244        vis: &ast::Visibility,
245        finalize: bool,
246    ) -> Result<Visibility, VisResolutionError> {
247        match vis.kind {
248            ast::VisibilityKind::Public => Ok(Visibility::Public),
249            ast::VisibilityKind::Inherited => {
250                Ok(match parent_scope.module.kind {
251                    // Any inherited visibility resolved directly inside an enum or trait
252                    // (i.e. variants, fields, and trait items) inherits from the visibility
253                    // of the enum or trait.
254                    ModuleKind::Def(DefKind::Enum | DefKind::Trait, def_id, _) => {
255                        self.tcx.visibility(def_id).expect_local()
256                    }
257                    // Otherwise, the visibility is restricted to the nearest parent `mod` item.
258                    _ => Visibility::Restricted(
259                        parent_scope.module.nearest_parent_mod().expect_local(),
260                    ),
261                })
262            }
263            ast::VisibilityKind::Restricted { ref path, id, .. } => {
264                // For visibilities we are not ready to provide correct implementation of "uniform
265                // paths" right now, so on 2018 edition we only allow module-relative paths for now.
266                // On 2015 edition visibilities are resolved as crate-relative by default,
267                // so we are prepending a root segment if necessary.
268                let ident = path.segments.get(0).expect("empty path in visibility").ident;
269                let crate_root = if ident.is_path_segment_keyword() {
270                    None
271                } else if ident.span.is_rust_2015() {
272                    Some(Segment::from_ident(Ident::new(
273                        kw::PathRoot,
274                        path.span.shrink_to_lo().with_ctxt(ident.span.ctxt()),
275                    )))
276                } else {
277                    return Err(VisResolutionError::Relative2018(
278                        ident.span,
279                        path.as_ref().clone(),
280                    ));
281                };
282                let segments = crate_root
283                    .into_iter()
284                    .chain(path.segments.iter().map(|seg| seg.into()))
285                    .collect::<Vec<_>>();
286                let expected_found_error = |res| {
287                    Err(VisResolutionError::ExpectedFound(
288                        path.span,
289                        Segment::names_to_string(&segments),
290                        res,
291                    ))
292                };
293                match self.cm().resolve_path(
294                    &segments,
295                    None,
296                    parent_scope,
297                    finalize.then(|| Finalize::new(id, path.span)),
298                    None,
299                    None,
300                ) {
301                    PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
302                        let res = module.res().expect("visibility resolved to unnamed block");
303                        if module.is_normal() {
304                            match res {
305                                Res::Err => {
306                                    if finalize {
307                                        self.record_partial_res(id, PartialRes::new(res));
308                                    }
309                                    Ok(Visibility::Public)
310                                }
311                                _ => {
312                                    let vis = Visibility::Restricted(res.def_id());
313                                    if self.is_accessible_from(vis, parent_scope.module) {
314                                        if finalize {
315                                            self.record_partial_res(id, PartialRes::new(res));
316                                        }
317                                        Ok(vis.expect_local())
318                                    } else {
319                                        Err(VisResolutionError::AncestorOnly(path.span))
320                                    }
321                                }
322                            }
323                        } else {
324                            expected_found_error(res)
325                        }
326                    }
327                    PathResult::Module(..) => Err(VisResolutionError::ModuleOnly(path.span)),
328                    PathResult::NonModule(partial_res) => {
329                        expected_found_error(partial_res.expect_full_res())
330                    }
331                    PathResult::Failed {
332                        span, label, suggestion, message, segment_name, ..
333                    } => Err(VisResolutionError::FailedToResolve(
334                        span,
335                        segment_name,
336                        label,
337                        suggestion,
338                        message,
339                    )),
340                    PathResult::Indeterminate => Err(VisResolutionError::Indeterminate(path.span)),
341                }
342            }
343        }
344    }
345
346    pub(crate) fn build_reduced_graph_external(&self, module: ExternModule<'ra>) {
347        let def_id = module.def_id();
348        let children = self.tcx.module_children(def_id);
349        for (i, child) in children.iter().enumerate() {
350            self.build_reduced_graph_for_external_crate_res(child, module, i, None)
351        }
352        for (i, child) in
353            self.cstore().ambig_module_children_untracked(self.tcx, def_id).enumerate()
354        {
355            self.build_reduced_graph_for_external_crate_res(
356                &child.main,
357                module,
358                children.len() + i,
359                Some(&child.second),
360            )
361        }
362    }
363
364    /// Builds the reduced graph for a single item in an external crate.
365    fn build_reduced_graph_for_external_crate_res(
366        &self,
367        child: &ModChild,
368        parent: ExternModule<'ra>,
369        child_index: usize,
370        ambig_child: Option<&ModChild>,
371    ) {
372        let child_span = |this: &Self, reexport_chain: &[Reexport], res: def::Res<_>| {
373            this.def_span(
374                reexport_chain
375                    .first()
376                    .and_then(|reexport| reexport.id())
377                    .unwrap_or_else(|| res.def_id()),
378            )
379        };
380        let ModChild { ident: orig_ident, res, vis, ref reexport_chain } = *child;
381        let ident = IdentKey::new(orig_ident);
382        let span = child_span(self, reexport_chain, res);
383        let res = res.expect_non_local();
384        let expansion = LocalExpnId::ROOT;
385        let ambig = ambig_child.map(|ambig_child| {
386            let ModChild { ident: _, res, vis, ref reexport_chain } = *ambig_child;
387            let span = child_span(self, reexport_chain, res);
388            let res = res.expect_non_local();
389            self.arenas.new_def_decl(res, vis, span, expansion, Some(parent.to_module()))
390        });
391
392        // Record primary definitions.
393        let define_extern = |ns| {
394            self.define_extern(
395                parent,
396                ident,
397                orig_ident.span,
398                ns,
399                child_index,
400                res,
401                vis,
402                span,
403                expansion,
404                ambig,
405            )
406        };
407        match res {
408            Res::Def(
409                DefKind::Mod
410                | DefKind::Enum
411                | DefKind::Trait
412                | DefKind::Struct
413                | DefKind::Union
414                | DefKind::Variant
415                | DefKind::TyAlias
416                | DefKind::ForeignTy
417                | DefKind::OpaqueTy
418                | DefKind::TraitAlias
419                | DefKind::AssocTy,
420                _,
421            )
422            | Res::PrimTy(..)
423            | Res::ToolMod => define_extern(TypeNS),
424            Res::Def(
425                DefKind::Fn
426                | DefKind::AssocFn
427                | DefKind::Static { .. }
428                | DefKind::Const { .. }
429                | DefKind::AssocConst { .. }
430                | DefKind::Ctor(..),
431                _,
432            ) => define_extern(ValueNS),
433            Res::Def(DefKind::Macro(..), _) | Res::NonMacroAttr(..) => define_extern(MacroNS),
434            Res::Def(
435                DefKind::TyParam
436                | DefKind::ConstParam
437                | DefKind::ExternCrate
438                | DefKind::Use
439                | DefKind::ForeignMod
440                | DefKind::AnonConst
441                | DefKind::InlineConst
442                | DefKind::Field
443                | DefKind::LifetimeParam
444                | DefKind::GlobalAsm
445                | DefKind::Closure
446                | DefKind::SyntheticCoroutineBody
447                | DefKind::Impl { .. },
448                _,
449            )
450            | Res::Local(..)
451            | Res::SelfTyParam { .. }
452            | Res::SelfTyAlias { .. }
453            | Res::SelfCtor(..)
454            | Res::OpenMod(..)
455            | Res::Err => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected resolution: {0:?}",
        res))bug!("unexpected resolution: {:?}", res),
456        }
457    }
458}
459
460impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for DefCollector<'_, 'ra, 'tcx> {
461    fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
462        self.r
463    }
464}
465
466impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> {
467    fn res(&self, def_id: impl Into<DefId>) -> Res {
468        let def_id = def_id.into();
469        Res::Def(self.r.tcx.def_kind(def_id), def_id)
470    }
471
472    fn resolve_visibility(&mut self, vis: &ast::Visibility) -> Visibility {
473        match self.r.try_resolve_visibility(&self.parent_scope, vis, true) {
474            Ok(vis) => vis,
475            Err(error) => {
476                self.r.delayed_vis_resolution_errors.push(DelayedVisResolutionError {
477                    vis: vis.clone(),
478                    parent_scope: self.parent_scope,
479                    error,
480                });
481                Visibility::Public
482            }
483        }
484    }
485
486    fn insert_field_idents(&mut self, def_id: LocalDefId, fields: &[ast::FieldDef]) {
487        if fields.iter().any(|field| field.is_placeholder) {
488            // The fields are not expanded yet.
489            return;
490        }
491        let field_name = |i, field: &ast::FieldDef| {
492            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))
493        };
494        let field_names: Vec<_> =
495            fields.iter().enumerate().map(|(i, field)| field_name(i, field)).collect();
496        let defaults = fields
497            .iter()
498            .enumerate()
499            .filter_map(|(i, field)| field.default.as_ref().map(|_| field_name(i, field).name))
500            .collect();
501        self.r.field_names.insert(def_id, field_names);
502        self.r.field_defaults.insert(def_id, defaults);
503    }
504
505    fn insert_field_visibilities_local(&mut self, def_id: DefId, fields: &[ast::FieldDef]) {
506        let field_vis = fields
507            .iter()
508            .map(|field| field.vis.span.until(field.ident.map_or(field.ty.span, |i| i.span)))
509            .collect();
510        self.r.field_visibility_spans.insert(def_id, field_vis);
511    }
512
513    fn block_needs_anonymous_module(&self, block: &Block) -> bool {
514        // If any statements are items, we need to create an anonymous module
515        block
516            .stmts
517            .iter()
518            .any(|statement| #[allow(non_exhaustive_omitted_patterns)] match statement.kind {
    StmtKind::Item(_) | StmtKind::MacCall(_) => true,
    _ => false,
}matches!(statement.kind, StmtKind::Item(_) | StmtKind::MacCall(_)))
519    }
520
521    // Add an import to the current module.
522    fn add_import(
523        &mut self,
524        module_path: Vec<Segment>,
525        kind: ImportKind<'ra>,
526        span: Span,
527        item: &ast::Item,
528        root_span: Span,
529        root_id: NodeId,
530        vis: Visibility,
531    ) {
532        let current_module = self.parent_scope.module;
533        let import = self.r.arenas.alloc_import(ImportData {
534            kind,
535            parent_scope: self.parent_scope,
536            module_path,
537            imported_module: CmCell::new(None),
538            span,
539            use_span: item.span,
540            use_span_with_attributes: item.span_with_attributes(),
541            has_attributes: !item.attrs.is_empty(),
542            root_span,
543            root_id,
544            vis,
545            vis_span: item.vis.span,
546            on_unknown_attr: OnUnknownData::from_attrs(self.r.tcx, item),
547        });
548
549        self.r.indeterminate_imports.push(import);
550        match import.kind {
551            ImportKind::Single { target, .. } => {
552                // Don't add underscore imports to `single_imports`
553                // because they cannot define any usable names.
554                if target.name != kw::Underscore {
555                    self.r.per_ns(|this, ns| {
556                        let key = BindingKey::new(IdentKey::new(target), ns);
557                        this.resolution_or_default(current_module, key, target.span)
558                            .borrow_mut(this)
559                            .single_imports
560                            .insert(import);
561                    });
562                }
563            }
564            ImportKind::Glob { .. } => current_module.globs.borrow_mut(self.r).push(import),
565            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
566        }
567    }
568
569    fn build_reduced_graph_for_use_tree(
570        &mut self,
571        // This particular use tree
572        use_tree: &ast::UseTree,
573        id: NodeId,
574        parent_prefix: &[Segment],
575        nested: bool,
576        list_stem: bool,
577        // The whole `use` item
578        item: &Item,
579        vis: Visibility,
580        root_span: Span,
581        feed: TyCtxtFeed<'tcx, LocalDefId>,
582    ) {
583        {
    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:583",
                        "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(583u32),
                        ::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!(
584            "build_reduced_graph_for_use_tree(parent_prefix={:?}, use_tree={:?}, nested={})",
585            parent_prefix, use_tree, nested
586        );
587
588        // Top level use tree reuses the item's id and list stems reuse their parent
589        // use tree's ids, so in both cases their visibilities are already filled.
590        if nested && !list_stem {
591            self.r.feed_visibility(feed, vis);
592        }
593
594        let mut prefix_iter = parent_prefix
595            .iter()
596            .cloned()
597            .chain(use_tree.prefix.segments.iter().map(|seg| seg.into()))
598            .peekable();
599
600        // On 2015 edition imports are resolved as crate-relative by default,
601        // so prefixes are prepended with crate root segment if necessary.
602        // The root is prepended lazily, when the first non-empty prefix or terminating glob
603        // appears, so imports in braced groups can have roots prepended independently.
604        let crate_root = match prefix_iter.peek() {
605            Some(seg) if !seg.ident.is_path_segment_keyword() && seg.ident.span.is_rust_2015() => {
606                Some(seg.ident.span.ctxt())
607            }
608            None if let ast::UseTreeKind::Glob(span) = use_tree.kind
609                && span.is_rust_2015() =>
610            {
611                Some(span.ctxt())
612            }
613            _ => None,
614        }
615        .map(|ctxt| {
616            Segment::from_ident(Ident::new(
617                kw::PathRoot,
618                use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt),
619            ))
620        });
621
622        let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>();
623        {
    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:623",
                        "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(623u32),
                        ::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);
624
625        match use_tree.kind {
626            ast::UseTreeKind::Simple(rename) => {
627                let mut module_path = prefix;
628                let source = module_path.pop().unwrap();
629
630                // If the identifier is `self` without a rename,
631                // then it is replaced with the parent identifier.
632                let ident = if source.ident.name == kw::SelfLower
633                    && rename.is_none()
634                    && let Some(parent) = module_path.last()
635                {
636                    Ident::new(parent.ident.name, source.ident.span)
637                } else {
638                    use_tree.ident()
639                };
640
641                match source.ident.name {
642                    kw::DollarCrate => {
643                        if !module_path.is_empty() {
644                            self.r.dcx().span_err(
645                                source.ident.span,
646                                "`$crate` in paths can only be used in start position",
647                            );
648                            return;
649                        }
650                    }
651                    kw::Crate => {
652                        if !module_path.is_empty() {
653                            self.r.dcx().span_err(
654                                source.ident.span,
655                                "`crate` in paths can only be used in start position",
656                            );
657                            return;
658                        }
659                    }
660                    kw::Super => {
661                        // Allow `self::super` as a valid prefix - `self` at position 0
662                        // followed by any number of `super` segments.
663                        let valid_prefix = module_path.iter().enumerate().all(|(i, seg)| {
664                            let name = seg.ident.name;
665                            name == kw::Super || (name == kw::SelfLower && i == 0)
666                        });
667
668                        if !valid_prefix {
669                            self.r.dcx().span_err(
670                                source.ident.span,
671                                "`super` in paths can only be used in start position, after `self`, or after another `super`",
672                            );
673                            return;
674                        }
675                    }
676                    // Deny `use ::{self};` after edition 2015
677                    kw::SelfLower
678                        if let Some(parent) = module_path.last()
679                            && parent.ident.name == kw::PathRoot
680                            && !self.r.path_root_is_crate_root(parent.ident) =>
681                    {
682                        self.r.dcx().span_err(use_tree.span(), "extern prelude cannot be imported");
683                        return;
684                    }
685                    _ => (),
686                }
687
688                // Deny `use ...::self::source [as target];` or `use ...::self::self [as target];`,
689                // but allow `use self::source [as target];` and `use self::self as target;`.
690                if let Some(parent) = module_path.last()
691                    && parent.ident.name == kw::SelfLower
692                    && module_path.len() > 1
693                {
694                    self.r.dcx().span_err(
695                        parent.ident.span,
696                        "`self` in paths can only be used in start position or last position",
697                    );
698                    return;
699                }
700
701                // Deny importing path-kw without renaming
702                if rename.is_none() && ident.is_path_segment_keyword() {
703                    let ident = use_tree.ident();
704                    self.r.dcx().emit_err(errors::UnnamedImport {
705                        span: ident.span,
706                        sugg: errors::UnnamedImportSugg { span: ident.span, ident },
707                    });
708                    return;
709                }
710
711                let kind = ImportKind::Single {
712                    source: source.ident,
713                    target: ident,
714                    decls: Default::default(),
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                for &(ref tree, id) in items {
738                    let feed = self.create_def(id, None, DefKind::Use, use_tree.span());
739                    self.build_reduced_graph_for_use_tree(
740                        // This particular use tree
741                        tree, id, &prefix, true, false, // The whole `use` item
742                        item, vis, root_span, feed,
743                    );
744                }
745
746                // Empty groups `a::b::{}` are turned into synthetic `self` imports
747                // `a::b::c::{self as _}`, so that their prefixes are correctly
748                // resolved and checked for privacy/stability/etc.
749                if items.is_empty()
750                    && !prefix.is_empty()
751                    && (prefix.len() > 1 || prefix[0].ident.name != kw::PathRoot)
752                {
753                    let new_span = prefix[prefix.len() - 1].ident.span;
754                    let tree = ast::UseTree {
755                        prefix: ast::Path::from_ident(Ident::new(kw::SelfLower, new_span)),
756                        kind: ast::UseTreeKind::Simple(Some(Ident::new(kw::Underscore, new_span))),
757                    };
758                    self.build_reduced_graph_for_use_tree(
759                        // This particular use tree
760                        &tree,
761                        id,
762                        &prefix,
763                        true,
764                        true,
765                        // The whole `use` item
766                        item,
767                        Visibility::Restricted(
768                            self.parent_scope.module.nearest_parent_mod().expect_local(),
769                        ),
770                        root_span,
771                        feed,
772                    );
773                }
774            }
775        }
776    }
777
778    fn build_reduced_graph_for_struct_variant(
779        &mut self,
780        fields: &[ast::FieldDef],
781        ident: Ident,
782        feed: TyCtxtFeed<'tcx, LocalDefId>,
783        adt_res: Res,
784        adt_vis: Visibility,
785        adt_span: Span,
786    ) {
787        let parent_scope = &self.parent_scope;
788        let parent = parent_scope.module.expect_local();
789        let expansion = parent_scope.expansion;
790
791        // Define a name in the type namespace if it is not anonymous.
792        self.r.define_local(parent, ident, TypeNS, adt_res, adt_vis, adt_span, expansion);
793        self.r.feed_visibility(feed, adt_vis);
794        let def_id = feed.key();
795
796        // Record field names for error reporting.
797        self.insert_field_idents(def_id, fields);
798        self.insert_field_visibilities_local(def_id.to_def_id(), fields);
799    }
800
801    /// Constructs the reduced graph for one item.
802    fn build_reduced_graph_for_item(&mut self, item: &'a Item, feed: TyCtxtFeed<'tcx, LocalDefId>) {
803        let parent_scope = &self.parent_scope;
804        let parent = parent_scope.module.expect_local();
805        let expansion = parent_scope.expansion;
806        let sp = item.span;
807        let vis = self.resolve_visibility(&item.vis);
808        let local_def_id = feed.key();
809        let def_id = local_def_id.to_def_id();
810        let def_kind = self.r.tcx.def_kind(def_id);
811        let res = Res::Def(def_kind, def_id);
812
813        self.r.feed_visibility(feed, vis);
814
815        match item.kind {
816            ItemKind::Use(ref use_tree) => {
817                self.build_reduced_graph_for_use_tree(
818                    // This particular use tree
819                    use_tree,
820                    item.id,
821                    &[],
822                    false,
823                    false,
824                    // The whole `use` item
825                    item,
826                    vis,
827                    use_tree.span(),
828                    feed,
829                );
830            }
831
832            ItemKind::ExternCrate(orig_name, ident) => {
833                self.build_reduced_graph_for_extern_crate(
834                    orig_name,
835                    item,
836                    ident,
837                    local_def_id,
838                    vis,
839                );
840            }
841
842            ItemKind::Mod(_, ident, ref mod_kind) => {
843                self.r.define_local(parent, ident, TypeNS, res, vis, sp, expansion);
844
845                if let ast::ModKind::Loaded(_, Inline::No { had_parse_error: Err(_) }, _) = mod_kind
846                {
847                    self.r.mods_with_parse_errors.insert(def_id);
848                }
849                let module = self.r.new_local_module(
850                    Some(parent),
851                    ModuleKind::Def(def_kind, def_id, Some(ident.name)),
852                    expansion.to_expn_id(),
853                    item.span,
854                    parent.no_implicit_prelude
855                        || ast::attr::contains_name(&item.attrs, sym::no_implicit_prelude),
856                );
857                self.parent_scope.module = module.to_module();
858            }
859
860            // These items live in the value namespace.
861            ItemKind::Const(box ConstItem { ident, .. })
862            | ItemKind::Delegation(box Delegation { ident, .. })
863            | ItemKind::Static(box StaticItem { ident, .. }) => {
864                self.r.define_local(parent, ident, ValueNS, res, vis, sp, expansion);
865            }
866            ItemKind::Fn(box Fn { ident, .. }) => {
867                self.r.define_local(parent, ident, ValueNS, res, vis, sp, expansion);
868
869                // Functions introducing procedural macros reserve a slot
870                // in the macro namespace as well (see #52225).
871                self.define_macro(item, feed);
872            }
873
874            // These items live in the type namespace.
875            ItemKind::TyAlias(box TyAlias { ident, .. })
876            | ItemKind::TraitAlias(box TraitAlias { ident, .. }) => {
877                self.r.define_local(parent, ident, TypeNS, res, vis, sp, expansion);
878            }
879
880            ItemKind::Enum(ident, _, _) | ItemKind::Trait(box ast::Trait { ident, .. }) => {
881                self.r.define_local(parent, ident, TypeNS, res, vis, sp, expansion);
882
883                let module = self.r.new_local_module(
884                    Some(parent),
885                    ModuleKind::Def(def_kind, def_id, Some(ident.name)),
886                    expansion.to_expn_id(),
887                    item.span,
888                    parent.no_implicit_prelude,
889                );
890                self.parent_scope.module = module.to_module();
891            }
892
893            // These items live in both the type and value namespaces.
894            ItemKind::Struct(ident, ref generics, ref vdata) => {
895                self.build_reduced_graph_for_struct_variant(
896                    vdata.fields(),
897                    ident,
898                    feed,
899                    res,
900                    vis,
901                    sp,
902                );
903
904                // If this is a tuple or unit struct, define a name
905                // in the value namespace as well.
906                if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(vdata) {
907                    // If the structure is marked as non_exhaustive then lower the visibility
908                    // to within the crate.
909                    let mut ctor_vis = if vis.is_public()
910                        && ast::attr::contains_name(&item.attrs, sym::non_exhaustive)
911                    {
912                        Visibility::Restricted(CRATE_DEF_ID)
913                    } else {
914                        vis
915                    };
916
917                    let mut field_visibilities = Vec::with_capacity(vdata.fields().len());
918
919                    for field in vdata.fields() {
920                        // NOTE: The field may be an expansion placeholder, but expansion sets
921                        // correct visibilities for unnamed field placeholders specifically, so the
922                        // constructor visibility should still be determined correctly.
923                        let field_vis = self
924                            .r
925                            .try_resolve_visibility(&self.parent_scope, &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(..) => self
1361                    .r
1362                    .try_resolve_visibility(&self.parent_scope, &item.vis, false)
1363                    .unwrap_or(Visibility::Public),
1364                _ => self.resolve_visibility(&item.vis),
1365            };
1366            if !vis.is_public() {
1367                self.insert_unused_macro(orig_ident, def_id, item.id);
1368            }
1369            self.r.define_local(module, orig_ident, MacroNS, res, vis, span, expansion);
1370            self.r.feed_visibility(feed, vis);
1371            self.parent_scope.macro_rules
1372        }
1373    }
1374}
1375
1376impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> {
1377    pub(crate) fn brg_visit_item(&mut self, item: &'a Item, feed: TyCtxtFeed<'tcx, LocalDefId>) {
1378        let orig_module_scope = self.parent_scope.module;
1379        self.parent_scope.macro_rules = match item.kind {
1380            ItemKind::MacroDef(..) => {
1381                let macro_rules_scope = self.define_macro(item, feed);
1382                visit::walk_item(self, item);
1383                macro_rules_scope
1384            }
1385            _ => {
1386                let orig_macro_rules_scope = self.parent_scope.macro_rules;
1387                self.build_reduced_graph_for_item(item, feed);
1388                match item.kind {
1389                    ItemKind::Mod(..) => {
1390                        // Visit attributes after items for backward compatibility.
1391                        // This way they can use `macro_rules` defined later.
1392                        self.visit_vis(&item.vis);
1393                        item.kind.walk(&item.attrs, item.span, item.id, &item.vis, (), self);
1394                        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);
1395                    }
1396                    _ => visit::walk_item(self, item),
1397                }
1398                match item.kind {
1399                    ItemKind::Mod(..) if self.contains_macro_use(&item.attrs) => {
1400                        self.parent_scope.macro_rules
1401                    }
1402                    _ => orig_macro_rules_scope,
1403                }
1404            }
1405        };
1406        self.parent_scope.module = orig_module_scope;
1407    }
1408
1409    /// Handle a macro call that itself can produce new `macro_rules` items
1410    /// in the current module.
1411    pub(crate) fn brg_visit_mac_call_in_module(&mut self, id: NodeId) {
1412        self.parent_scope.macro_rules = self.visit_invoc_in_module(id);
1413    }
1414
1415    pub(crate) fn brg_visit_block(&mut self, block: &'a Block) {
1416        let orig_current_module = self.parent_scope.module;
1417        let orig_current_macro_rules_scope = self.parent_scope.macro_rules;
1418        self.build_reduced_graph_for_block(block);
1419        visit::walk_block(self, block);
1420        self.parent_scope.module = orig_current_module;
1421        self.parent_scope.macro_rules = orig_current_macro_rules_scope;
1422    }
1423
1424    pub(crate) fn brg_visit_assoc_item(
1425        &mut self,
1426        item: &'a AssocItem,
1427        ctxt: AssocCtxt,
1428        ident: Ident,
1429        ns: Namespace,
1430        feed: TyCtxtFeed<'tcx, LocalDefId>,
1431    ) {
1432        let vis = self.resolve_visibility(&item.vis);
1433        let local_def_id = feed.key();
1434        let def_id = local_def_id.to_def_id();
1435
1436        if !(#[allow(non_exhaustive_omitted_patterns)] match ctxt {
    AssocCtxt::Impl { of_trait: true } => true,
    _ => false,
}matches!(ctxt, AssocCtxt::Impl { of_trait: true })
1437            && #[allow(non_exhaustive_omitted_patterns)] match item.vis.kind {
    ast::VisibilityKind::Inherited => true,
    _ => false,
}matches!(item.vis.kind, ast::VisibilityKind::Inherited))
1438        {
1439            // Trait impl item visibility is inherited from its trait when not specified
1440            // explicitly. In that case we cannot determine it here in early resolve,
1441            // so we leave a hole in the visibility table to be filled later.
1442            self.r.feed_visibility(feed, vis);
1443        }
1444
1445        if ctxt == AssocCtxt::Trait {
1446            let parent = self.parent_scope.module.expect_local();
1447            let expansion = self.parent_scope.expansion;
1448            self.r.define_local(parent, ident, ns, self.res(def_id), vis, item.span, expansion);
1449        } 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)
1450            && ident.name != kw::Underscore
1451        {
1452            // Don't add underscore names, they cannot be looked up anyway.
1453            let impl_def_id = self.r.tcx.local_parent(local_def_id);
1454            let key = BindingKey::new(IdentKey::new(ident), ns);
1455            self.r.impl_binding_keys.entry(impl_def_id).or_default().insert(key);
1456        }
1457
1458        visit::walk_assoc_item(self, item, ctxt);
1459    }
1460
1461    pub(crate) fn visit_assoc_item_mac_call(
1462        &mut self,
1463        item: &'a Item<AssocItemKind>,
1464        ctxt: AssocCtxt,
1465    ) {
1466        match ctxt {
1467            AssocCtxt::Trait => {
1468                self.visit_invoc_in_module(item.id);
1469            }
1470            AssocCtxt::Impl { .. } => {
1471                let invoc_id = item.id.placeholder_to_expn_id();
1472                if !self.r.glob_delegation_invoc_ids.contains(&invoc_id) {
1473                    self.r
1474                        .impl_unexpanded_invocations
1475                        .entry(self.r.invocation_parent(invoc_id))
1476                        .or_default()
1477                        .insert(invoc_id);
1478                }
1479                self.visit_invoc(item.id);
1480            }
1481        }
1482    }
1483
1484    pub(crate) fn brg_visit_field_def(
1485        &mut self,
1486        sf: &'a ast::FieldDef,
1487        feed: TyCtxtFeed<'tcx, LocalDefId>,
1488    ) {
1489        let vis = self.resolve_visibility(&sf.vis);
1490        self.r.feed_visibility(feed, vis);
1491        visit::walk_field_def(self, sf);
1492    }
1493
1494    // Constructs the reduced graph for one variant. Variants exist in the
1495    // type and value namespaces.
1496    pub(crate) fn brg_visit_variant(
1497        &mut self,
1498        variant: &'a ast::Variant,
1499        feed: TyCtxtFeed<'tcx, LocalDefId>,
1500    ) {
1501        let parent = self.parent_scope.module.expect_local();
1502        let expn_id = self.parent_scope.expansion;
1503        let ident = variant.ident;
1504
1505        // Define a name in the type namespace.
1506        let def_id = feed.key();
1507        let vis = self.resolve_visibility(&variant.vis);
1508        self.r.define_local(parent, ident, TypeNS, self.res(def_id), vis, variant.span, expn_id);
1509        self.r.feed_visibility(feed, vis);
1510
1511        // If the variant is marked as non_exhaustive then lower the visibility to within the crate.
1512        let ctor_vis =
1513            if vis.is_public() && ast::attr::contains_name(&variant.attrs, sym::non_exhaustive) {
1514                Visibility::Restricted(CRATE_DEF_ID)
1515            } else {
1516                vis
1517            };
1518
1519        // Define a constructor name in the value namespace.
1520        if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(&variant.data) {
1521            let feed = self.create_def(
1522                ctor_node_id,
1523                None,
1524                DefKind::Ctor(CtorOf::Variant, ctor_kind),
1525                variant.span,
1526            );
1527            let ctor_def_id = feed.key();
1528            let ctor_res = self.res(ctor_def_id);
1529            self.r.define_local(parent, ident, ValueNS, ctor_res, ctor_vis, variant.span, expn_id);
1530            self.r.feed_visibility(feed, ctor_vis);
1531        }
1532
1533        // Record field names for error reporting.
1534        self.insert_field_idents(def_id, variant.data.fields());
1535        self.insert_field_visibilities_local(def_id.to_def_id(), variant.data.fields());
1536
1537        visit::walk_variant(self, variant);
1538    }
1539}