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