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