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