Skip to main content

rustc_resolve/
lib.rs

1//! This crate is responsible for the part of name resolution that doesn't require type checker.
2//!
3//! Module structure of the crate is built here.
4//! Paths in macros, imports, expressions, types, patterns are resolved here.
5//! Label and lifetime names are resolved here as well.
6//!
7//! Type-relative name resolution (methods, fields, associated items) happens in `rustc_hir_analysis`.
8
9// tidy-alphabetical-start
10#![allow(internal_features)]
11#![feature(arbitrary_self_types)]
12#![feature(const_default)]
13#![feature(const_trait_impl)]
14#![feature(control_flow_into_value)]
15#![feature(default_field_values)]
16#![feature(deref_patterns)]
17#![feature(iter_intersperse)]
18#![feature(option_into_flat_iter)]
19#![feature(rustc_attrs)]
20#![feature(trim_prefix_suffix)]
21#![recursion_limit = "256"]
22// tidy-alphabetical-end
23
24use std::cell::{Ref, RefMut};
25use std::collections::BTreeSet;
26use std::ops::ControlFlow;
27use std::sync::{Arc, OnceLock};
28use std::{fmt, mem};
29
30use diagnostics::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
31use effective_visibilities::EffectiveVisibilitiesVisitor;
32use hygiene::Macros20NormalizedSyntaxContext;
33use imports::{Import, ImportData, ImportKind, NameResolution, PendingDecl};
34use late::{
35    ForwardGenericParamBanReason, HasGenericParams, PathSource, PatternSource,
36    UnnecessaryQualification,
37};
38pub use macros::registered_lint_tools_ast;
39use macros::{MacroRulesDecl, MacroRulesScope, MacroRulesScopeRef};
40use rustc_arena::{DroplessArena, TypedArena};
41use rustc_ast::node_id::NodeMap;
42use rustc_ast::{
43    self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, DUMMY_NODE_ID, Expr, ExprKind,
44    GenericArg, GenericArgs, Generics, NodeId, Path, attr,
45};
46use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, default};
47use rustc_data_structures::intern::Interned;
48use rustc_data_structures::steal::Steal;
49use rustc_data_structures::sync::{FreezeReadGuard, FreezeWriteGuard, WorkerLocal};
50use rustc_data_structures::unord::{UnordItems, UnordMap, UnordSet};
51use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed, LintBuffer};
52use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind};
53use rustc_feature::{BUILTIN_ATTRIBUTES, Features};
54use rustc_hir::attrs::StrippedCfgItem;
55use rustc_hir::def::Namespace::{self, *};
56use rustc_hir::def::{
57    self, CtorOf, DefKind, DocLinkResMap, MacroKinds, NonMacroAttrKind, PartialRes, PerNS,
58};
59use rustc_hir::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalDefIdMap};
60use rustc_hir::definitions::{PerParentDisambiguatorState, PerParentDisambiguatorsMap};
61use rustc_hir::{PrimTy, TraitCandidate, find_attr};
62use rustc_index::bit_set::DenseBitSet;
63use rustc_metadata::creader::CStore;
64use rustc_middle::metadata::{AmbigModChild, ModChild, Reexport};
65use rustc_middle::middle::privacy::EffectiveVisibilities;
66use rustc_middle::query::Providers;
67use rustc_middle::ty::{
68    self, DelegationInfo, MainDefinition, PerOwnerResolverData, RegisteredTools,
69    ResolverAstLowering, ResolverGlobalCtxt, TyCtxt, TyCtxtFeed, Visibility,
70};
71use rustc_middle::{bug, span_bug};
72use rustc_session::config::CrateType;
73use rustc_session::lint::builtin::PRIVATE_MACRO_USE;
74use rustc_span::def_id::{LocalModId, ModId};
75use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
76use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
77use smallvec::{SmallVec, smallvec};
78use tracing::{debug, instrument};
79
80use crate::diagnostics::impls::{
81    ImportSuggestion, LabelSuggestion, OnUnknownData, StructCtor, Suggestion,
82};
83use crate::imports::{ImportResolution, NameResolutionRef};
84use crate::ref_mut::{CmCell, CmRef, CmRefCell};
85
86mod build_reduced_graph;
87mod check_unused;
88mod def_collector;
89mod diagnostics;
90mod effective_visibilities;
91mod ident;
92mod imports;
93mod late;
94mod macros;
95pub mod rustdoc;
96
97type Res = def::Res<NodeId>;
98
99#[derive(#[automatically_derived]
impl ::core::marker::Copy for Determinacy { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Determinacy {
    #[inline]
    fn clone(&self) -> Determinacy { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Determinacy {
    #[inline]
    fn eq(&self, other: &Determinacy) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for Determinacy {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Determinacy::Determined => "Determined",
                Determinacy::Undetermined => "Undetermined",
            })
    }
}Debug)]
100enum Determinacy {
101    Determined,
102    Undetermined,
103}
104
105impl Determinacy {
106    fn determined(determined: bool) -> Determinacy {
107        if determined { Determinacy::Determined } else { Determinacy::Undetermined }
108    }
109}
110
111/// A specific scope in which a name can be looked up.
112#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for Scope<'ra> {
    #[inline]
    fn clone(&self) -> Scope<'ra> {
        let _: ::core::clone::AssertParamIsClone<LocalExpnId>;
        let _: ::core::clone::AssertParamIsClone<MacroRulesScopeRef<'ra>>;
        let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
        let _: ::core::clone::AssertParamIsClone<Option<NodeId>>;
        let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
        let _: ::core::clone::AssertParamIsClone<Option<NodeId>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for Scope<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for Scope<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Scope::DeriveHelpers(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "DeriveHelpers", &__self_0),
            Scope::DeriveHelpersCompat =>
                ::core::fmt::Formatter::write_str(f, "DeriveHelpersCompat"),
            Scope::MacroRules(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "MacroRules", &__self_0),
            Scope::ModuleNonGlobs(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "ModuleNonGlobs", __self_0, &__self_1),
            Scope::ModuleGlobs(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "ModuleGlobs", __self_0, &__self_1),
            Scope::MacroUsePrelude =>
                ::core::fmt::Formatter::write_str(f, "MacroUsePrelude"),
            Scope::BuiltinAttrs =>
                ::core::fmt::Formatter::write_str(f, "BuiltinAttrs"),
            Scope::ExternPreludeItems =>
                ::core::fmt::Formatter::write_str(f, "ExternPreludeItems"),
            Scope::ExternPreludeFlags =>
                ::core::fmt::Formatter::write_str(f, "ExternPreludeFlags"),
            Scope::ToolAttributePrelude =>
                ::core::fmt::Formatter::write_str(f, "ToolAttributePrelude"),
            Scope::StdLibPrelude =>
                ::core::fmt::Formatter::write_str(f, "StdLibPrelude"),
            Scope::BuiltinTypes =>
                ::core::fmt::Formatter::write_str(f, "BuiltinTypes"),
        }
    }
}Debug)]
113enum Scope<'ra> {
114    /// Inert attributes registered by derive macros.
115    DeriveHelpers(LocalExpnId),
116    /// Inert attributes registered by derive macros, but used before they are actually declared.
117    /// This scope will exist until the compatibility lint `LEGACY_DERIVE_HELPERS`
118    /// is turned into a hard error.
119    DeriveHelpersCompat,
120    /// Textual `let`-like scopes introduced by `macro_rules!` items.
121    MacroRules(MacroRulesScopeRef<'ra>),
122    /// Non-glob names declared in the given module.
123    /// The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK`
124    /// lint if it should be reported.
125    ModuleNonGlobs(Module<'ra>, Option<NodeId>),
126    /// Glob names declared in the given module.
127    /// The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK`
128    /// lint if it should be reported.
129    ModuleGlobs(Module<'ra>, Option<NodeId>),
130    /// Names introduced by `#[macro_use]` attributes on `extern crate` items.
131    MacroUsePrelude,
132    /// Built-in attributes.
133    BuiltinAttrs,
134    /// Extern prelude names introduced by `extern crate` items.
135    ExternPreludeItems,
136    /// Extern prelude names introduced by `--extern` flags.
137    ExternPreludeFlags,
138    /// Tool modules introduced with `#![register_tool]` or `#![register_attribute_tool]`.
139    ToolAttributePrelude,
140    /// Standard library prelude introduced with an internal `#[prelude_import]` import.
141    StdLibPrelude,
142    /// Built-in types.
143    BuiltinTypes,
144}
145
146/// Names from different contexts may want to visit different subsets of all specific scopes
147/// with different restrictions when looking up the resolution.
148#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for ScopeSet<'ra> {
    #[inline]
    fn clone(&self) -> ScopeSet<'ra> {
        let _: ::core::clone::AssertParamIsClone<Namespace>;
        let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
        let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
        let _: ::core::clone::AssertParamIsClone<MacroKind>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for ScopeSet<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for ScopeSet<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ScopeSet::All(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "All",
                    &__self_0),
            ScopeSet::Module(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Module",
                    __self_0, &__self_1),
            ScopeSet::ModuleAndExternPrelude(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "ModuleAndExternPrelude", __self_0, &__self_1),
            ScopeSet::ExternPrelude =>
                ::core::fmt::Formatter::write_str(f, "ExternPrelude"),
            ScopeSet::Macro(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Macro",
                    &__self_0),
        }
    }
}Debug)]
149enum ScopeSet<'ra> {
150    /// All scopes with the given namespace.
151    All(Namespace),
152    /// Two scopes inside a module, for non-glob and glob bindings.
153    Module(Namespace, Module<'ra>),
154    /// A module, then extern prelude (used for mixed 2015-2018 mode in macros).
155    ModuleAndExternPrelude(Namespace, Module<'ra>),
156    /// Just two extern prelude scopes.
157    ExternPrelude,
158    /// Same as `All(MacroNS)`, but with the given macro kind restriction.
159    Macro(MacroKind),
160}
161
162/// Everything you need to know about a name's location to resolve it.
163/// Serves as a starting point for the scope visitor.
164/// This struct is currently used only for early resolution (imports and macros),
165/// but not for late resolution yet.
166#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for ParentScope<'ra> {
    #[inline]
    fn clone(&self) -> ParentScope<'ra> {
        let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
        let _: ::core::clone::AssertParamIsClone<LocalExpnId>;
        let _: ::core::clone::AssertParamIsClone<MacroRulesScopeRef<'ra>>;
        let _: ::core::clone::AssertParamIsClone<&'ra [ast::Path]>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for ParentScope<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for ParentScope<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "ParentScope",
            "module", &self.module, "expansion", &self.expansion,
            "macro_rules", &self.macro_rules, "derives", &&self.derives)
    }
}Debug)]
167struct ParentScope<'ra> {
168    module: Module<'ra>,
169    expansion: LocalExpnId,
170    macro_rules: MacroRulesScopeRef<'ra>,
171    derives: &'ra [ast::Path],
172}
173
174impl<'ra> ParentScope<'ra> {
175    /// Creates a parent scope with the passed argument used as the module scope component,
176    /// and other scope components set to default empty values.
177    fn module(module: LocalModule<'ra>, arenas: &'ra ResolverArenas<'ra>) -> ParentScope<'ra> {
178        ParentScope {
179            module: module.to_module(),
180            expansion: LocalExpnId::ROOT,
181            macro_rules: arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
182            derives: &[],
183        }
184    }
185}
186
187#[derive(#[automatically_derived]
impl ::core::marker::Copy for InvocationParent { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for InvocationParent {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "InvocationParent", "parent_def", &self.parent_def,
            "impl_trait_context", &self.impl_trait_context, "in_attr",
            &self.in_attr, "owner", &&self.owner)
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for InvocationParent {
    #[inline]
    fn clone(&self) -> InvocationParent {
        let _: ::core::clone::AssertParamIsClone<LocalDefId>;
        let _: ::core::clone::AssertParamIsClone<ImplTraitContext>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<NodeId>;
        *self
    }
}Clone)]
188struct InvocationParent {
189    parent_def: LocalDefId,
190    impl_trait_context: ImplTraitContext,
191    in_attr: bool,
192    owner: NodeId,
193}
194
195impl InvocationParent {
196    const ROOT: Self = Self {
197        parent_def: CRATE_DEF_ID,
198        impl_trait_context: ImplTraitContext::Existential,
199        in_attr: false,
200        owner: CRATE_NODE_ID,
201    };
202}
203
204#[derive(#[automatically_derived]
impl ::core::marker::Copy for ImplTraitContext { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for ImplTraitContext {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ImplTraitContext::Existential => "Existential",
                ImplTraitContext::Universal => "Universal",
                ImplTraitContext::InBinding => "InBinding",
            })
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for ImplTraitContext {
    #[inline]
    fn clone(&self) -> ImplTraitContext { *self }
}Clone)]
205enum ImplTraitContext {
206    Existential,
207    Universal,
208    InBinding,
209}
210
211/// Used for tracking import use types which will be used for redundant import checking.
212///
213/// ### Used::Scope Example
214///
215/// ```rust,compile_fail
216/// #![deny(redundant_imports)]
217/// use std::mem::drop;
218/// fn main() {
219///     let s = Box::new(32);
220///     drop(s);
221/// }
222/// ```
223///
224/// Used::Other is for other situations like module-relative uses.
225#[derive(#[automatically_derived]
impl ::core::clone::Clone for Used {
    #[inline]
    fn clone(&self) -> Used { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Used { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for Used {
    #[inline]
    fn eq(&self, other: &Used) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::PartialOrd for Used {
    #[inline]
    fn partial_cmp(&self, other: &Used)
        -> ::core::option::Option<::core::cmp::Ordering> {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        ::core::cmp::PartialOrd::partial_cmp(&__self_discr, &__arg1_discr)
    }
}PartialOrd, #[automatically_derived]
impl ::core::fmt::Debug for Used {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self { Used::Scope => "Scope", Used::Other => "Other", })
    }
}Debug)]
226enum Used {
227    Scope,
228    Other,
229}
230
231#[derive(#[automatically_derived]
impl ::core::fmt::Debug for BindingError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "BindingError",
            "name", &self.name, "origin", &self.origin, "target",
            &self.target, "could_be_path", &&self.could_be_path)
    }
}Debug)]
232struct BindingError {
233    name: Ident,
234    origin: Vec<(Span, ast::Pat)>,
235    target: Vec<ast::Pat>,
236    could_be_path: bool,
237}
238
239#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for ResolutionError<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ResolutionError::GenericParamsFromOuterItem {
                outer_res: __self_0,
                has_generic_params: __self_1,
                def_kind: __self_2,
                inner_item: __self_3,
                current_self_ty: __self_4 } =>
                ::core::fmt::Formatter::debug_struct_field5_finish(f,
                    "GenericParamsFromOuterItem", "outer_res", __self_0,
                    "has_generic_params", __self_1, "def_kind", __self_2,
                    "inner_item", __self_3, "current_self_ty", &__self_4),
            ResolutionError::NameAlreadyUsedInParameterList(__self_0,
                __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "NameAlreadyUsedInParameterList", __self_0, &__self_1),
            ResolutionError::MethodNotMemberOfTrait(__self_0, __self_1,
                __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "MethodNotMemberOfTrait", __self_0, __self_1, &__self_2),
            ResolutionError::TypeNotMemberOfTrait(__self_0, __self_1,
                __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "TypeNotMemberOfTrait", __self_0, __self_1, &__self_2),
            ResolutionError::ConstNotMemberOfTrait(__self_0, __self_1,
                __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "ConstNotMemberOfTrait", __self_0, __self_1, &__self_2),
            ResolutionError::VariableNotBoundInPattern(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "VariableNotBoundInPattern", __self_0, &__self_1),
            ResolutionError::VariableBoundWithDifferentMode(__self_0,
                __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "VariableBoundWithDifferentMode", __self_0, &__self_1),
            ResolutionError::IdentifierBoundMoreThanOnceInParameterList(__self_0)
                =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "IdentifierBoundMoreThanOnceInParameterList", &__self_0),
            ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(__self_0)
                =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "IdentifierBoundMoreThanOnceInSamePattern", &__self_0),
            ResolutionError::UndeclaredLabel {
                name: __self_0, suggestion: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "UndeclaredLabel", "name", __self_0, "suggestion",
                    &__self_1),
            ResolutionError::FailedToResolve {
                segment: __self_0,
                label: __self_1,
                suggestion: __self_2,
                module: __self_3,
                message: __self_4 } =>
                ::core::fmt::Formatter::debug_struct_field5_finish(f,
                    "FailedToResolve", "segment", __self_0, "label", __self_1,
                    "suggestion", __self_2, "module", __self_3, "message",
                    &__self_4),
            ResolutionError::CannotCaptureDynamicEnvironmentInFnItem =>
                ::core::fmt::Formatter::write_str(f,
                    "CannotCaptureDynamicEnvironmentInFnItem"),
            ResolutionError::AttemptToUseNonConstantValueInConstant {
                ident: __self_0,
                suggestion: __self_1,
                current: __self_2,
                type_span: __self_3 } =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f,
                    "AttemptToUseNonConstantValueInConstant", "ident", __self_0,
                    "suggestion", __self_1, "current", __self_2, "type_span",
                    &__self_3),
            ResolutionError::BindingShadowsSomethingUnacceptable {
                shadowing_binding: __self_0,
                name: __self_1,
                participle: __self_2,
                article: __self_3,
                shadowed_binding: __self_4,
                shadowed_binding_span: __self_5 } => {
                let names: &'static _ =
                    &["shadowing_binding", "name", "participle", "article",
                                "shadowed_binding", "shadowed_binding_span"];
                let values: &[&dyn ::core::fmt::Debug] =
                    &[__self_0, __self_1, __self_2, __self_3, __self_4,
                                &__self_5];
                ::core::fmt::Formatter::debug_struct_fields_finish(f,
                    "BindingShadowsSomethingUnacceptable", names, values)
            }
            ResolutionError::ForwardDeclaredGenericParam(__self_0, __self_1)
                =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "ForwardDeclaredGenericParam", __self_0, &__self_1),
            ResolutionError::ParamInTyOfConstParam { name: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "ParamInTyOfConstParam", "name", &__self_0),
            ResolutionError::ParamInNonTrivialAnonConst {
                is_gca: __self_0, name: __self_1, param_kind: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "ParamInNonTrivialAnonConst", "is_gca", __self_0, "name",
                    __self_1, "param_kind", &__self_2),
            ResolutionError::ParamInEnumDiscriminant {
                name: __self_0, param_kind: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "ParamInEnumDiscriminant", "name", __self_0, "param_kind",
                    &__self_1),
            ResolutionError::ForwardDeclaredSelf(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ForwardDeclaredSelf", &__self_0),
            ResolutionError::UnreachableLabel {
                name: __self_0,
                definition_span: __self_1,
                suggestion: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "UnreachableLabel", "name", __self_0, "definition_span",
                    __self_1, "suggestion", &__self_2),
            ResolutionError::TraitImplMismatch {
                name: __self_0,
                kind: __self_1,
                trait_path: __self_2,
                trait_item_span: __self_3,
                code: __self_4 } =>
                ::core::fmt::Formatter::debug_struct_field5_finish(f,
                    "TraitImplMismatch", "name", __self_0, "kind", __self_1,
                    "trait_path", __self_2, "trait_item_span", __self_3, "code",
                    &__self_4),
            ResolutionError::TraitImplDuplicate {
                name: __self_0, trait_item_span: __self_1, old_span: __self_2
                } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "TraitImplDuplicate", "name", __self_0, "trait_item_span",
                    __self_1, "old_span", &__self_2),
            ResolutionError::InvalidAsmSym =>
                ::core::fmt::Formatter::write_str(f, "InvalidAsmSym"),
            ResolutionError::LowercaseSelf =>
                ::core::fmt::Formatter::write_str(f, "LowercaseSelf"),
            ResolutionError::BindingInNeverPattern =>
                ::core::fmt::Formatter::write_str(f, "BindingInNeverPattern"),
        }
    }
}Debug)]
240enum ResolutionError<'ra> {
241    /// Error E0401: can't use type or const parameters from outer item.
242    GenericParamsFromOuterItem {
243        outer_res: Res,
244        has_generic_params: HasGenericParams,
245        def_kind: DefKind,
246        /// 1. label span, 2. item span, 3. item kind
247        inner_item: Option<(Span, Span, ast::ItemKind)>,
248        current_self_ty: Option<String>,
249    },
250    /// Error E0403: the name is already used for a type or const parameter in this generic
251    /// parameter list.
252    NameAlreadyUsedInParameterList(Ident, Span),
253    /// Error E0407: method is not a member of trait.
254    MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
255    /// Error E0437: type is not a member of trait.
256    TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
257    /// Error E0438: const is not a member of trait.
258    ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
259    /// Error E0408: variable `{}` is not bound in all patterns.
260    VariableNotBoundInPattern(BindingError, ParentScope<'ra>),
261    /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
262    VariableBoundWithDifferentMode(Ident, Span),
263    /// Error E0415: identifier is bound more than once in this parameter list.
264    IdentifierBoundMoreThanOnceInParameterList(Ident),
265    /// Error E0416: identifier is bound more than once in the same pattern.
266    IdentifierBoundMoreThanOnceInSamePattern(Ident),
267    /// Error E0426: use of undeclared label.
268    UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
269    /// Error E0433: failed to resolve.
270    FailedToResolve {
271        segment: Symbol,
272        label: String,
273        suggestion: Option<Suggestion>,
274        module: Option<ModuleOrUniformRoot<'ra>>,
275        message: String,
276    },
277    /// Error E0434: can't capture dynamic environment in a fn item.
278    CannotCaptureDynamicEnvironmentInFnItem,
279    /// Error E0435: attempt to use a non-constant value in a constant.
280    AttemptToUseNonConstantValueInConstant {
281        ident: Ident,
282        suggestion: &'static str,
283        current: &'static str,
284        type_span: Option<Span>,
285    },
286    /// Error E0530: `X` bindings cannot shadow `Y`s.
287    BindingShadowsSomethingUnacceptable {
288        shadowing_binding: PatternSource,
289        name: Symbol,
290        participle: &'static str,
291        article: &'static str,
292        shadowed_binding: Res,
293        shadowed_binding_span: Span,
294    },
295    /// Error E0128: generic parameters with a default cannot use forward-declared identifiers.
296    ForwardDeclaredGenericParam(Symbol, ForwardGenericParamBanReason),
297    // FIXME(generic_const_parameter_types): This should give custom output specifying it's only
298    // problematic to use *forward declared* parameters when the feature is enabled.
299    /// ERROR E0770: the type of const parameters must not depend on other generic parameters.
300    ParamInTyOfConstParam { name: Symbol },
301    /// generic parameters must not be used inside const evaluations.
302    ///
303    /// This error is only emitted when using `min_const_generics`.
304    ParamInNonTrivialAnonConst {
305        is_gca: bool,
306        name: Symbol,
307        param_kind: ParamKindInNonTrivialAnonConst,
308    },
309    /// generic parameters must not be used inside enum discriminants.
310    ///
311    /// This error is emitted even with `generic_const_exprs`.
312    ParamInEnumDiscriminant { name: Symbol, param_kind: ParamKindInEnumDiscriminant },
313    /// Error E0735: generic parameters with a default cannot use `Self`
314    ForwardDeclaredSelf(ForwardGenericParamBanReason),
315    /// Error E0767: use of unreachable label
316    UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
317    /// Error E0323, E0324, E0325: mismatch between trait item and impl item.
318    TraitImplMismatch {
319        name: Ident,
320        kind: &'static str,
321        trait_path: String,
322        trait_item_span: Span,
323        code: ErrCode,
324    },
325    /// Error E0201: multiple impl items for the same trait item.
326    TraitImplDuplicate { name: Ident, trait_item_span: Span, old_span: Span },
327    /// Inline asm `sym` operand must refer to a `fn` or `static`.
328    InvalidAsmSym,
329    /// `self` used instead of `Self` in a generic parameter
330    LowercaseSelf,
331    /// A never pattern has a binding.
332    BindingInNeverPattern,
333}
334
335#[derive(#[automatically_derived]
impl ::core::fmt::Debug for VisResolutionError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            VisResolutionError::Relative2018(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "Relative2018", __self_0, &__self_1),
            VisResolutionError::AncestorOnly(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "AncestorOnly", &__self_0),
            VisResolutionError::FailedToResolve(__self_0, __self_1, __self_2,
                __self_3, __self_4) =>
                ::core::fmt::Formatter::debug_tuple_field5_finish(f,
                    "FailedToResolve", __self_0, __self_1, __self_2, __self_3,
                    &__self_4),
            VisResolutionError::ExpectedFound(__self_0, __self_1, __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "ExpectedFound", __self_0, __self_1, &__self_2),
            VisResolutionError::Indeterminate(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Indeterminate", &__self_0),
            VisResolutionError::ModuleOnly(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ModuleOnly", &__self_0),
        }
    }
}Debug)]
336enum VisResolutionError {
337    Relative2018(Span, ast::Path),
338    AncestorOnly(Span),
339    FailedToResolve(Span, Symbol, String, Option<Suggestion>, String),
340    ExpectedFound(Span, String, Res),
341    Indeterminate(Span),
342    ModuleOnly(Span),
343}
344
345/// A minimal representation of a path segment. We use this in resolve because we synthesize 'path
346/// segments' which don't have the rest of an AST or HIR `PathSegment`.
347#[derive(#[automatically_derived]
impl ::core::clone::Clone for Segment {
    #[inline]
    fn clone(&self) -> Segment {
        let _: ::core::clone::AssertParamIsClone<Ident>;
        let _: ::core::clone::AssertParamIsClone<Option<NodeId>>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Segment { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Segment {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f, "Segment",
            "ident", &self.ident, "id", &self.id, "has_generic_args",
            &self.has_generic_args, "has_lifetime_args",
            &self.has_lifetime_args, "args_span", &&self.args_span)
    }
}Debug)]
348struct Segment {
349    ident: Ident,
350    id: Option<NodeId>,
351    /// Signals whether this `PathSegment` has generic arguments.
352    has_generic_args: bool,
353    /// Signals whether this `PathSegment` has lifetime arguments.
354    has_lifetime_args: bool,
355    args_span: Span,
356}
357
358impl Segment {
359    fn from_path(path: &Path) -> Vec<Segment> {
360        path.segments.iter().map(|s| s.into()).collect()
361    }
362
363    fn from_ident(ident: Ident) -> Segment {
364        Segment {
365            ident,
366            id: None,
367            has_generic_args: false,
368            has_lifetime_args: false,
369            args_span: DUMMY_SP,
370        }
371    }
372
373    fn names_to_string(segments: &[Segment]) -> String {
374        names_to_string(segments.iter().map(|seg| seg.ident.name))
375    }
376}
377
378impl<'a> From<&'a ast::PathSegment> for Segment {
379    fn from(seg: &'a ast::PathSegment) -> Segment {
380        let has_generic_args = seg.args.is_some();
381        let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
382            match args {
383                GenericArgs::AngleBracketed(args) => {
384                    let found_lifetimes = args
385                        .args
386                        .iter()
387                        .any(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
    AngleBracketedArg::Arg(GenericArg::Lifetime(_)) => true,
    _ => false,
}matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
388                    (args.span, found_lifetimes)
389                }
390                GenericArgs::Parenthesized(args) => (args.span, true),
391                GenericArgs::ParenthesizedElided(span) => (*span, true),
392            }
393        } else {
394            (DUMMY_SP, false)
395        };
396        Segment {
397            ident: seg.ident,
398            id: Some(seg.id),
399            has_generic_args,
400            has_lifetime_args,
401            args_span,
402        }
403    }
404}
405
406/// Name declaration used during late resolution.
407#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for LateDecl<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LateDecl::Decl(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Decl",
                    &__self_0),
            LateDecl::RibDef(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "RibDef",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<'ra> ::core::marker::Copy for LateDecl<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::clone::Clone for LateDecl<'ra> {
    #[inline]
    fn clone(&self) -> LateDecl<'ra> {
        let _: ::core::clone::AssertParamIsClone<Decl<'ra>>;
        let _: ::core::clone::AssertParamIsClone<Res>;
        *self
    }
}Clone)]
408enum LateDecl<'ra> {
409    /// A regular name declaration.
410    Decl(Decl<'ra>),
411    /// A name definition from a rib, e.g. a local variable.
412    /// Omits most of the data from regular `Decl` for performance reasons.
413    RibDef(Res),
414}
415
416impl<'ra> LateDecl<'ra> {
417    fn res(self) -> Res {
418        match self {
419            LateDecl::Decl(binding) => binding.res(),
420            LateDecl::RibDef(res) => res,
421        }
422    }
423}
424
425#[derive(#[automatically_derived]
impl<'ra> ::core::marker::Copy for ModuleOrUniformRoot<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::clone::Clone for ModuleOrUniformRoot<'ra> {
    #[inline]
    fn clone(&self) -> ModuleOrUniformRoot<'ra> {
        let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
        let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for ModuleOrUniformRoot<'ra> {
    #[inline]
    fn eq(&self, other: &ModuleOrUniformRoot<'ra>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (ModuleOrUniformRoot::Module(__self_0),
                    ModuleOrUniformRoot::Module(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (ModuleOrUniformRoot::ModuleAndExternPrelude(__self_0),
                    ModuleOrUniformRoot::ModuleAndExternPrelude(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (ModuleOrUniformRoot::OpenModule(__self_0),
                    ModuleOrUniformRoot::OpenModule(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for ModuleOrUniformRoot<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ModuleOrUniformRoot::Module(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Module",
                    &__self_0),
            ModuleOrUniformRoot::ModuleAndExternPrelude(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ModuleAndExternPrelude", &__self_0),
            ModuleOrUniformRoot::ExternPrelude =>
                ::core::fmt::Formatter::write_str(f, "ExternPrelude"),
            ModuleOrUniformRoot::CurrentScope =>
                ::core::fmt::Formatter::write_str(f, "CurrentScope"),
            ModuleOrUniformRoot::OpenModule(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "OpenModule", &__self_0),
        }
    }
}Debug)]
426enum ModuleOrUniformRoot<'ra> {
427    /// Regular module.
428    Module(Module<'ra>),
429
430    /// Virtual module that denotes resolution in a module with fallback to extern prelude.
431    /// Used for paths starting with `::` coming from 2015 edition macros
432    /// used in 2018+ edition crates.
433    ModuleAndExternPrelude(Module<'ra>),
434
435    /// Virtual module that denotes resolution in extern prelude.
436    /// Used for paths starting with `::` on 2018 edition.
437    ExternPrelude,
438
439    /// Virtual module that denotes resolution in current scope.
440    /// Used only for resolving single-segment imports. The reason it exists is that import paths
441    /// are always split into two parts, the first of which should be some kind of module.
442    CurrentScope,
443
444    /// Virtual module for the resolution of base names of namespaced crates,
445    /// where the base name doesn't correspond to a module in the extern prelude.
446    /// E.g. `my_api::utils` is in the prelude, but `my_api` is not.
447    OpenModule(Symbol),
448}
449
450#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for PathResult<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            PathResult::Module(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Module",
                    &__self_0),
            PathResult::NonModule(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "NonModule", &__self_0),
            PathResult::Indeterminate =>
                ::core::fmt::Formatter::write_str(f, "Indeterminate"),
            PathResult::Failed {
                span: __self_0,
                label: __self_1,
                suggestion: __self_2,
                is_error_from_last_segment: __self_3,
                module: __self_4,
                segment: __self_5,
                error_implied_by_parse_error: __self_6,
                message: __self_7,
                note: __self_8 } => {
                let names: &'static _ =
                    &["span", "label", "suggestion",
                                "is_error_from_last_segment", "module", "segment",
                                "error_implied_by_parse_error", "message", "note"];
                let values: &[&dyn ::core::fmt::Debug] =
                    &[__self_0, __self_1, __self_2, __self_3, __self_4,
                                __self_5, __self_6, __self_7, &__self_8];
                ::core::fmt::Formatter::debug_struct_fields_finish(f,
                    "Failed", names, values)
            }
        }
    }
}Debug)]
451enum PathResult<'ra> {
452    Module(ModuleOrUniformRoot<'ra>),
453    NonModule(PartialRes),
454    Indeterminate,
455    Failed {
456        span: Span,
457        label: String,
458        suggestion: Option<Suggestion>,
459        is_error_from_last_segment: bool,
460        /// The final module being resolved, for instance:
461        ///
462        /// ```compile_fail
463        /// mod a {
464        ///     mod b {
465        ///         mod c {}
466        ///     }
467        /// }
468        ///
469        /// use a::not_exist::c;
470        /// ```
471        ///
472        /// In this case, `module` will point to `a`.
473        module: Option<ModuleOrUniformRoot<'ra>>,
474        /// The segment of target
475        segment: Ident,
476        error_implied_by_parse_error: bool,
477        message: String,
478        note: Option<String>,
479    },
480}
481
482impl<'ra> PathResult<'ra> {
483    fn failed(
484        ident: Ident,
485        is_error_from_last_segment: bool,
486        finalize: bool,
487        error_implied_by_parse_error: bool,
488        module: Option<ModuleOrUniformRoot<'ra>>,
489        label_and_suggestion_and_note: impl FnOnce() -> (
490            String,
491            String,
492            Option<Suggestion>,
493            Option<String>,
494        ),
495    ) -> PathResult<'ra> {
496        let (message, label, suggestion, note) = if finalize {
497            label_and_suggestion_and_note()
498        } else {
499            // FIXME: this output isn't actually present in the test suite.
500            (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot find `{0}` in this scope",
                ident))
    })format!("cannot find `{ident}` in this scope"), String::new(), None, None)
501        };
502        PathResult::Failed {
503            span: ident.span,
504            segment: ident,
505            label,
506            suggestion,
507            is_error_from_last_segment,
508            module,
509            error_implied_by_parse_error,
510            message,
511            note,
512        }
513    }
514}
515
516#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ModuleKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ModuleKind::Block =>
                ::core::fmt::Formatter::write_str(f, "Block"),
            ModuleKind::Def(__self_0, __self_1, __self_2, __self_3) =>
                ::core::fmt::Formatter::debug_tuple_field4_finish(f, "Def",
                    __self_0, __self_1, __self_2, &__self_3),
        }
    }
}Debug)]
517enum ModuleKind {
518    /// An anonymous module; e.g., just a block.
519    ///
520    /// ```
521    /// fn main() {
522    ///     fn f() {} // (1)
523    ///     { // This is an anonymous module
524    ///         f(); // This resolves to (2) as we are inside the block.
525    ///         fn f() {} // (2)
526    ///     }
527    ///     f(); // Resolves to (1)
528    /// }
529    /// ```
530    Block,
531    /// Any module with a name.
532    ///
533    /// This could be:
534    ///
535    /// * A normal module – either `mod from_file;` or `mod from_block { }` –
536    ///   or the crate root (which is conceptually a top-level module).
537    ///   The crate root will have `None` for the symbol.
538    /// * A trait or an enum (it implicitly contains associated types, methods and variant
539    ///   constructors).
540    Def(DefKind, DefId, NodeId, Option<Symbol>),
541}
542
543impl ModuleKind {
544    fn opt_def_id(&self) -> Option<DefId> {
545        match self {
546            ModuleKind::Def(_, def_id, _, _) => Some(*def_id),
547            _ => None,
548        }
549    }
550
551    fn def_id(&self) -> DefId {
552        self.opt_def_id().expect("`Module::def_id` is called on a block module")
553    }
554
555    fn is_local(&self) -> bool {
556        match self {
557            ModuleKind::Def(_, def_id, ..) => def_id.is_local(),
558            ModuleKind::Block => true,
559        }
560    }
561}
562
563/// Combination of a symbol and its macros 2.0 normalized hygiene context.
564/// Used as a key in various kinds of name containers, including modules (as a part of slightly
565/// larger `BindingKey`) and preludes.
566///
567/// Often passed around together with `orig_ident_span: Span`, which is an unnormalized span
568/// of the original `Ident` from which `IdentKey` was obtained. This span is not used in map keys,
569/// but used in a number of other scenarios - diagnostics, edition checks, `allow_unstable` checks
570/// and similar. This is required because macros 2.0 normalization is lossy and the normalized
571/// spans / syntax contexts no longer contain parts of macro backtraces, while the original span
572/// contains everything.
573#[derive(#[automatically_derived]
impl ::core::clone::Clone for IdentKey {
    #[inline]
    fn clone(&self) -> IdentKey {
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        let _:
                ::core::clone::AssertParamIsClone<Macros20NormalizedSyntaxContext>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for IdentKey { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for IdentKey {
    #[inline]
    fn eq(&self, other: &IdentKey) -> bool {
        self.name == other.name && self.ctxt == other.ctxt
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for IdentKey {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Symbol>;
        let _: ::core::cmp::AssertParamIsEq<Macros20NormalizedSyntaxContext>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for IdentKey {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.name, state);
        ::core::hash::Hash::hash(&self.ctxt, state)
    }
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for IdentKey {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "IdentKey",
            "name", &self.name, "ctxt", &&self.ctxt)
    }
}Debug)]
574struct IdentKey {
575    name: Symbol,
576    ctxt: Macros20NormalizedSyntaxContext,
577}
578
579impl IdentKey {
580    #[inline]
581    fn new(ident: Ident) -> IdentKey {
582        IdentKey { name: ident.name, ctxt: Macros20NormalizedSyntaxContext::new(ident.span.ctxt()) }
583    }
584
585    #[inline]
586    fn new_adjusted(ident: Ident, expn_id: ExpnId) -> (IdentKey, Option<ExpnId>) {
587        let (ctxt, def) = Macros20NormalizedSyntaxContext::new_adjusted(ident.span.ctxt(), expn_id);
588        (IdentKey { name: ident.name, ctxt }, def)
589    }
590
591    #[inline]
592    fn with_root_ctxt(name: Symbol) -> Self {
593        let ctxt = Macros20NormalizedSyntaxContext::new_unchecked(SyntaxContext::root());
594        IdentKey { name, ctxt }
595    }
596
597    #[inline]
598    fn orig(self, orig_ident_span: Span) -> Ident {
599        Ident::new(self.name, orig_ident_span)
600    }
601}
602
603/// A key that identifies a binding in a given `Module`.
604///
605/// Multiple bindings in the same module can have the same key (in a valid
606/// program) if all but one of them come from glob imports.
607#[derive(#[automatically_derived]
impl ::core::marker::Copy for BindingKey { }Copy, #[automatically_derived]
impl ::core::clone::Clone for BindingKey {
    #[inline]
    fn clone(&self) -> BindingKey {
        let _: ::core::clone::AssertParamIsClone<IdentKey>;
        let _: ::core::clone::AssertParamIsClone<Namespace>;
        let _: ::core::clone::AssertParamIsClone<u32>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for BindingKey {
    #[inline]
    fn eq(&self, other: &BindingKey) -> bool {
        self.disambiguator == other.disambiguator && self.ident == other.ident
            && self.ns == other.ns
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for BindingKey {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<IdentKey>;
        let _: ::core::cmp::AssertParamIsEq<Namespace>;
        let _: ::core::cmp::AssertParamIsEq<u32>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for BindingKey {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.ident, state);
        ::core::hash::Hash::hash(&self.ns, state);
        ::core::hash::Hash::hash(&self.disambiguator, state)
    }
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for BindingKey {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "BindingKey",
            "ident", &self.ident, "ns", &self.ns, "disambiguator",
            &&self.disambiguator)
    }
}Debug)]
608struct BindingKey {
609    /// The identifier for the binding, always the `normalize_to_macros_2_0` version of the
610    /// identifier.
611    ident: IdentKey,
612    ns: Namespace,
613    /// When we add an underscore binding (with ident `_`) to some module, this field has
614    /// a non-zero value that uniquely identifies this binding in that module.
615    /// For non-underscore bindings this field is zero.
616    /// When a key is constructed for name lookup (as opposed to name definition), this field is
617    /// also zero, even for underscore names, so for underscores the lookup will never succeed.
618    disambiguator: u32,
619}
620
621impl BindingKey {
622    fn new(ident: IdentKey, ns: Namespace) -> Self {
623        BindingKey { ident, ns, disambiguator: 0 }
624    }
625
626    fn new_disambiguated(
627        ident: IdentKey,
628        ns: Namespace,
629        disambiguator: impl FnOnce() -> u32,
630    ) -> BindingKey {
631        let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 };
632        BindingKey { ident, ns, disambiguator }
633    }
634}
635
636type ResolutionTable<'ra> = FxIndexMap<BindingKey, NameResolutionRef<'ra>>;
637
638enum Resolutions<'ra> {
639    Local(CmRefCell<ResolutionTable<'ra>>),
640    Extern(OnceLock<ResolutionTable<'ra>>),
641}
642
643impl<'ra> Resolutions<'ra> {
644    fn new(local: bool) -> Self {
645        if local {
646            Resolutions::Local(Default::default())
647        } else {
648            Resolutions::Extern(Default::default())
649        }
650    }
651}
652
653/// One node in the tree of modules.
654///
655/// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these:
656///
657/// * `mod`
658/// * crate root (aka, top-level anonymous module)
659/// * `enum`
660/// * `trait`
661/// * curly-braced block with statements
662///
663/// You can use [`ModuleData::kind`] to determine the kind of module this is.
664struct ModuleData<'ra> {
665    /// The direct parent module (it may not be a `mod`, however).
666    parent: Option<Module<'ra>>,
667    /// What kind of module this is, because this may not be a `mod`.
668    kind: ModuleKind,
669
670    /// Mapping between names and their (possibly in-progress) resolutions in this module.
671    /// Resolutions in modules from other crates are not populated until accessed.
672    lazy_resolutions: Resolutions<'ra>,
673    /// Used to disambiguate underscore items (`const _: T = ...`) in the module.
674    underscore_disambiguator: CmCell<u32>,
675
676    /// Macro invocations that can expand into items in this module.
677    unexpanded_invocations: CmRefCell<FxHashSet<LocalExpnId>>,
678
679    /// Whether `#[no_implicit_prelude]` is active.
680    no_implicit_prelude: bool,
681
682    glob_importers: CmRefCell<Vec<Import<'ra>>>,
683    globs: CmRefCell<Vec<Import<'ra>>>,
684
685    /// Used to memoize the traits in this module for faster searches through all traits in scope.
686    traits: CmRefCell<
687        Option<Box<[(Symbol, Decl<'ra>, Option<Module<'ra>>, bool /* lint ambiguous */)]>>,
688    >,
689
690    /// Span of the module itself. Used for error reporting.
691    span: Span,
692
693    expansion: ExpnId,
694
695    /// Declaration for implicitly declared names that come with a module,
696    /// like `self` (not yet used), or `crate`/`$crate` (for root modules).
697    self_decl: Option<Decl<'ra>>,
698}
699
700/// `Interned` is used because values of this type have "identity" and compare as unequal even if
701/// they have the same contents.
702#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for Module<'ra> {
    #[inline]
    fn clone(&self) -> Module<'ra> {
        let _:
                ::core::clone::AssertParamIsClone<Interned<'ra,
                ModuleData<'ra>>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for Module<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for Module<'ra> {
    #[inline]
    fn eq(&self, other: &Module<'ra>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<'ra> ::core::cmp::Eq for Module<'ra> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Interned<'ra, ModuleData<'ra>>>;
    }
}Eq, #[automatically_derived]
impl<'ra> ::core::hash::Hash for Module<'ra> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash)]
703#[rustc_pass_by_value]
704struct Module<'ra>(Interned<'ra, ModuleData<'ra>>);
705
706/// Same as `Module`, but is guaranteed to be from the current crate.
707#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for LocalModule<'ra> {
    #[inline]
    fn clone(&self) -> LocalModule<'ra> {
        let _:
                ::core::clone::AssertParamIsClone<Interned<'ra,
                ModuleData<'ra>>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for LocalModule<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for LocalModule<'ra> {
    #[inline]
    fn eq(&self, other: &LocalModule<'ra>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<'ra> ::core::cmp::Eq for LocalModule<'ra> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Interned<'ra, ModuleData<'ra>>>;
    }
}Eq, #[automatically_derived]
impl<'ra> ::core::hash::Hash for LocalModule<'ra> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash)]
708#[rustc_pass_by_value]
709struct LocalModule<'ra>(Interned<'ra, ModuleData<'ra>>);
710
711/// Same as `Module`, but is guaranteed to be from an external crate.
712#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for ExternModule<'ra> {
    #[inline]
    fn clone(&self) -> ExternModule<'ra> {
        let _:
                ::core::clone::AssertParamIsClone<Interned<'ra,
                ModuleData<'ra>>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for ExternModule<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for ExternModule<'ra> {
    #[inline]
    fn eq(&self, other: &ExternModule<'ra>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<'ra> ::core::cmp::Eq for ExternModule<'ra> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Interned<'ra, ModuleData<'ra>>>;
    }
}Eq, #[automatically_derived]
impl<'ra> ::core::hash::Hash for ExternModule<'ra> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash)]
713#[rustc_pass_by_value]
714struct ExternModule<'ra>(Interned<'ra, ModuleData<'ra>>);
715
716impl<'ra> ModuleData<'ra> {
717    fn new(
718        parent: Option<Module<'ra>>,
719        kind: ModuleKind,
720        expansion: ExpnId,
721        span: Span,
722        no_implicit_prelude: bool,
723        vis: Visibility<ModId>,
724        arenas: &'ra ResolverArenas<'ra>,
725    ) -> Self {
726        let lazy_resolutions = Resolutions::new(kind.is_local());
727        let self_decl = match kind {
728            ModuleKind::Def(def_kind, def_id, ..) => {
729                let expn_id = expansion.as_local().unwrap_or(LocalExpnId::ROOT);
730                Some(arenas.new_def_decl(Res::Def(def_kind, def_id), vis, span, expn_id, parent))
731            }
732            ModuleKind::Block => None,
733        };
734        ModuleData {
735            parent,
736            kind,
737            lazy_resolutions,
738            underscore_disambiguator: CmCell::new(0),
739            unexpanded_invocations: Default::default(),
740            no_implicit_prelude,
741            glob_importers: CmRefCell::new(Vec::new()),
742            globs: CmRefCell::new(Vec::new()),
743            traits: CmRefCell::new(None),
744            span,
745            expansion,
746            self_decl,
747        }
748    }
749
750    /// Get name of the module.
751    fn name(&self) -> Option<Symbol> {
752        match self.kind {
753            ModuleKind::Block => None,
754            ModuleKind::Def(.., name) => name,
755        }
756    }
757
758    fn opt_def_id(&self) -> Option<DefId> {
759        self.kind.opt_def_id()
760    }
761
762    fn def_id(&self) -> DefId {
763        self.kind.def_id()
764    }
765
766    fn is_local(&self) -> bool {
767        self.kind.is_local()
768    }
769
770    fn has_unexpanded_invocations(&self) -> bool {
771        !self.unexpanded_invocations.borrow().is_empty()
772    }
773
774    fn res(&self) -> Option<Res> {
775        match self.kind {
776            ModuleKind::Def(kind, def_id, _, _) => Some(Res::Def(kind, def_id)),
777            _ => None,
778        }
779    }
780
781    fn def_kind(&self) -> Option<DefKind> {
782        match self.kind {
783            ModuleKind::Def(def_kind, ..) => Some(def_kind),
784            ModuleKind::Block => None,
785        }
786    }
787}
788
789impl<'ra> Module<'ra> {
790    fn for_each_child<'tcx, R: AsRef<Resolver<'ra, 'tcx>>>(
791        self,
792        resolver: &R,
793        mut f: impl FnMut(&R, IdentKey, Span, Namespace, Decl<'ra>),
794    ) {
795        for (key, name_resolution) in resolver.as_ref().resolutions(self).iter() {
796            let name_resolution = name_resolution.borrow();
797            if let Some(decl) = name_resolution.best_decl() {
798                f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
799            }
800        }
801    }
802
803    fn for_each_child_mut<'tcx, R: AsMut<Resolver<'ra, 'tcx>>>(
804        self,
805        resolver: &mut R,
806        mut f: impl FnMut(&mut R, IdentKey, Span, Namespace, Decl<'ra>),
807    ) {
808        for (key, name_resolution) in resolver.as_mut().resolutions(self).iter() {
809            let name_resolution = name_resolution.borrow();
810            if let Some(decl) = name_resolution.best_decl() {
811                f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
812            }
813        }
814    }
815
816    /// This modifies `self` in place. The traits will be stored in `self.traits`.
817    fn ensure_traits<'tcx>(self, resolver: &Resolver<'ra, 'tcx>) {
818        let mut traits = self.traits.borrow_mut(resolver.as_ref());
819        if traits.is_none() {
820            let mut collected_traits = Vec::new();
821            self.for_each_child(resolver, |r, ident, _, ns, mut decl| {
822                if ns != TypeNS {
823                    return;
824                }
825
826                let ambiguous = decl.is_ambiguity_recursive();
827                let mut try_record_trait = |decl: Decl<'ra>| {
828                    if let Res::Def(DefKind::Trait | DefKind::TraitAlias, def_id) = decl.res() {
829                        collected_traits.push((
830                            ident.name,
831                            decl,
832                            r.as_ref().get_module(def_id),
833                            ambiguous,
834                        ));
835                        true
836                    } else {
837                        false
838                    }
839                };
840                // Try to record at least one trait if the decl is ambiguous, such that we can
841                // report the `ambiguous_glob_imported_traits` lint. Otherwise we would report an
842                // error that the trait is not found.
843                while !try_record_trait(decl)
844                    && let Some((_, ambig_decl)) = decl.descent_to_ambiguity()
845                {
846                    decl = ambig_decl;
847                }
848            });
849            *traits = Some(collected_traits.into_boxed_slice());
850        }
851    }
852
853    // `self` resolves to the first module ancestor that `is_normal`.
854    fn is_normal(self) -> bool {
855        self.def_kind() == Some(DefKind::Mod)
856    }
857
858    fn is_trait(self) -> bool {
859        #[allow(non_exhaustive_omitted_patterns)] match self.def_kind() {
    Some(DefKind::Trait) => true,
    _ => false,
}matches!(self.def_kind(), Some(DefKind::Trait))
860    }
861
862    fn nearest_item_scope(self) -> Module<'ra> {
863        match self.def_kind() {
864            Some(DefKind::Enum | DefKind::Trait) => {
865                self.parent.expect("enum or trait module without a parent")
866            }
867            _ => self,
868        }
869    }
870
871    /// The [`ModId`] of the nearest `mod` item ancestor (which may be this module).
872    /// This may be the crate root.
873    fn nearest_parent_mod(self) -> ModId {
874        match self.kind {
875            ModuleKind::Def(DefKind::Mod, def_id, _, _) => ModId::new_unchecked(def_id),
876            _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
877        }
878    }
879
880    /// The [`NodeId`] of the nearest `mod` item ancestor (which may be this module).
881    /// This may be the crate root.
882    fn nearest_parent_mod_node_id(self) -> NodeId {
883        match self.kind {
884            ModuleKind::Def(DefKind::Mod, _, node_id, _) => node_id,
885            _ => self.parent.expect("non-root module without parent").nearest_parent_mod_node_id(),
886        }
887    }
888
889    fn is_ancestor_of(self, mut other: Self) -> bool {
890        while self != other {
891            if let Some(parent) = other.parent {
892                other = parent;
893            } else {
894                return false;
895            }
896        }
897        true
898    }
899
900    #[track_caller]
901    fn expect_local(self) -> LocalModule<'ra> {
902        match self.kind {
903            ModuleKind::Def(_, def_id, _, _) if !def_id.is_local() => {
904                ::rustc_middle::util::bug::span_bug_fmt(self.span,
    format_args!("unexpected extern module: {0:?}", self))span_bug!(self.span, "unexpected extern module: {self:?}")
905            }
906            ModuleKind::Def(..) | ModuleKind::Block => LocalModule(self.0),
907        }
908    }
909
910    #[track_caller]
911    fn expect_extern(self) -> ExternModule<'ra> {
912        match self.kind {
913            ModuleKind::Def(_, def_id, _, _) if !def_id.is_local() => ExternModule(self.0),
914            ModuleKind::Def(..) | ModuleKind::Block => {
915                ::rustc_middle::util::bug::span_bug_fmt(self.span,
    format_args!("unexpected local module: {0:?}", self))span_bug!(self.span, "unexpected local module: {self:?}")
916            }
917        }
918    }
919}
920
921impl<'ra> LocalModule<'ra> {
922    fn new(
923        parent: Option<LocalModule<'ra>>,
924        kind: ModuleKind,
925        vis: Visibility<ModId>,
926        expn_id: ExpnId,
927        span: Span,
928        no_implicit_prelude: bool,
929        arenas: &'ra ResolverArenas<'ra>,
930    ) -> LocalModule<'ra> {
931        if !kind.is_local() {
    ::core::panicking::panic("assertion failed: kind.is_local()")
};assert!(kind.is_local());
932        let parent = parent.map(|m| m.to_module());
933        let data = ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude, vis, arenas);
934        // SAFETY: `Interned` is valid because values of this type have "identity".
935        LocalModule(Interned::new_unchecked(arenas.modules.alloc(data)))
936    }
937
938    fn to_module(self) -> Module<'ra> {
939        Module(self.0)
940    }
941}
942
943impl<'ra> ExternModule<'ra> {
944    fn new(
945        parent: Option<ExternModule<'ra>>,
946        kind: ModuleKind,
947        vis: Visibility<ModId>,
948        expn_id: ExpnId,
949        span: Span,
950        no_implicit_prelude: bool,
951        arenas: &'ra ResolverArenas<'ra>,
952    ) -> ExternModule<'ra> {
953        if !!kind.is_local() {
    ::core::panicking::panic("assertion failed: !kind.is_local()")
};assert!(!kind.is_local());
954        let parent = parent.map(|m| m.to_module());
955        let data = ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude, vis, arenas);
956        // SAFETY: `Interned` is valid because values of this type have "identity".
957        ExternModule(Interned::new_unchecked(arenas.modules.alloc(data)))
958    }
959
960    fn to_module(self) -> Module<'ra> {
961        Module(self.0)
962    }
963}
964
965impl<'ra> std::ops::Deref for Module<'ra> {
966    type Target = ModuleData<'ra>;
967
968    fn deref(&self) -> &Self::Target {
969        &self.0
970    }
971}
972
973impl<'ra> std::ops::Deref for LocalModule<'ra> {
974    type Target = ModuleData<'ra>;
975
976    fn deref(&self) -> &Self::Target {
977        &self.0
978    }
979}
980
981impl<'ra> std::ops::Deref for ExternModule<'ra> {
982    type Target = ModuleData<'ra>;
983
984    fn deref(&self) -> &Self::Target {
985        &self.0
986    }
987}
988
989impl<'ra> fmt::Debug for Module<'ra> {
990    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
991        match self.res() {
992            None => f.write_fmt(format_args!("block"))write!(f, "block"),
993            Some(res) => f.write_fmt(format_args!("{0:?}", res))write!(f, "{:?}", res),
994        }
995    }
996}
997
998impl<'ra> fmt::Debug for LocalModule<'ra> {
999    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1000        self.to_module().fmt(f)
1001    }
1002}
1003
1004/// Data associated with any name declaration.
1005#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for DeclData<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["kind", "ambiguity", "expansion", "span", "initial_vis",
                        "ambiguity_vis_max", "ambiguity_vis_min", "parent_module"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.kind, &self.ambiguity, &self.expansion, &self.span,
                        &self.initial_vis, &self.ambiguity_vis_max,
                        &self.ambiguity_vis_min, &&self.parent_module];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "DeclData",
            names, values)
    }
}Debug)]
1006struct DeclData<'ra> {
1007    kind: DeclKind<'ra>,
1008    ambiguity: CmCell<Option<(Decl<'ra>, bool /*warning*/)>>,
1009    expansion: LocalExpnId,
1010    span: Span,
1011    initial_vis: Visibility<ModId>,
1012    /// If the declaration refers to an ambiguous glob set, then this is the most visible
1013    /// declaration from the set, if its visibility is different from `initial_vis`.
1014    ambiguity_vis_max: CmCell<Option<Decl<'ra>>>,
1015    /// If the declaration refers to an ambiguous glob set, then this is the least visible
1016    /// declaration from the set, if its visibility is different from `initial_vis`.
1017    ambiguity_vis_min: CmCell<Option<Decl<'ra>>>,
1018    parent_module: Option<Module<'ra>>,
1019}
1020
1021/// `Interned` is used because values of this type have "identity" and compare as unequal even if
1022/// they have the same contents.
1023type Decl<'ra> = Interned<'ra, DeclData<'ra>>;
1024
1025/// Name declaration kind.
1026#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for DeclKind<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            DeclKind::Def(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Def",
                    &__self_0),
            DeclKind::Import { source_decl: __self_0, import: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Import", "source_decl", __self_0, "import", &__self_1),
        }
    }
}Debug)]
1027enum DeclKind<'ra> {
1028    /// The name declaration is a definition (possibly without a `DefId`),
1029    /// can be provided by source code or built into the language.
1030    Def(Res),
1031    /// The name declaration is a link to another name declaration.
1032    Import { source_decl: Decl<'ra>, import: Import<'ra> },
1033}
1034
1035impl<'ra> DeclKind<'ra> {
1036    /// Is this an import declaration?
1037    fn is_import(&self) -> bool {
1038        #[allow(non_exhaustive_omitted_patterns)] match *self {
    DeclKind::Import { .. } => true,
    _ => false,
}matches!(*self, DeclKind::Import { .. })
1039    }
1040}
1041
1042#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for PrivacyError<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["ident", "decl", "dedup_span", "outermost_res", "parent_scope",
                        "single_nested", "source"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.ident, &self.decl, &self.dedup_span, &self.outermost_res,
                        &self.parent_scope, &self.single_nested, &&self.source];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "PrivacyError",
            names, values)
    }
}Debug)]
1043struct PrivacyError<'ra> {
1044    ident: Ident,
1045    decl: Decl<'ra>,
1046    dedup_span: Span,
1047    outermost_res: Option<(Res, Ident)>,
1048    parent_scope: ParentScope<'ra>,
1049    /// Is the format `use a::{b,c}`?
1050    single_nested: bool,
1051    source: Option<ast::Expr>,
1052}
1053
1054#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for UseError<'a> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["err", "candidates", "node_id", "instead", "suggestion", "path",
                        "is_call"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.err, &self.candidates, &self.node_id, &self.instead,
                        &self.suggestion, &self.path, &&self.is_call];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "UseError",
            names, values)
    }
}Debug)]
1055struct UseError<'a> {
1056    err: Diag<'a>,
1057    /// Candidates which user could `use` to access the missing type.
1058    candidates: Vec<ImportSuggestion>,
1059    /// The `NodeId` of the module to place the use-statements in.
1060    node_id: NodeId,
1061    /// Whether the diagnostic should say "instead" (as in `consider importing ... instead`).
1062    instead: bool,
1063    /// Extra free-form suggestion.
1064    suggestion: Option<(Span, &'static str, String, Applicability)>,
1065    /// Path `Segment`s at the place of use that failed. Used for accurate suggestion after telling
1066    /// the user to import the item directly.
1067    path: Vec<Segment>,
1068    /// Whether the expected source is a call
1069    is_call: bool,
1070}
1071
1072#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for DelayedVisResolutionError<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "DelayedVisResolutionError", "vis", &self.vis, "parent_scope",
            &self.parent_scope, "error", &&self.error)
    }
}Debug)]
1073struct DelayedVisResolutionError<'ra> {
1074    vis: ast::Visibility,
1075    parent_scope: ParentScope<'ra>,
1076    error: VisResolutionError,
1077}
1078
1079#[derive(#[automatically_derived]
impl ::core::clone::Clone for AmbiguityKind {
    #[inline]
    fn clone(&self) -> AmbiguityKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AmbiguityKind { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for AmbiguityKind {
    #[inline]
    fn eq(&self, other: &AmbiguityKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for AmbiguityKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                AmbiguityKind::BuiltinAttr => "BuiltinAttr",
                AmbiguityKind::DeriveHelper => "DeriveHelper",
                AmbiguityKind::MacroRulesVsModularized =>
                    "MacroRulesVsModularized",
                AmbiguityKind::GlobVsOuter => "GlobVsOuter",
                AmbiguityKind::GlobVsGlob => "GlobVsGlob",
                AmbiguityKind::GlobVsExpanded => "GlobVsExpanded",
                AmbiguityKind::MoreExpandedVsOuter => "MoreExpandedVsOuter",
            })
    }
}Debug)]
1080enum AmbiguityKind {
1081    BuiltinAttr,
1082    DeriveHelper,
1083    MacroRulesVsModularized,
1084    GlobVsOuter,
1085    GlobVsGlob,
1086    GlobVsExpanded,
1087    MoreExpandedVsOuter,
1088}
1089
1090impl AmbiguityKind {
1091    fn descr(self) -> &'static str {
1092        match self {
1093            AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
1094            AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
1095            AmbiguityKind::MacroRulesVsModularized => {
1096                "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
1097            }
1098            AmbiguityKind::GlobVsOuter => {
1099                "a conflict between a name from a glob import and an outer scope during import or macro resolution"
1100            }
1101            AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
1102            AmbiguityKind::GlobVsExpanded => {
1103                "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
1104            }
1105            AmbiguityKind::MoreExpandedVsOuter => {
1106                "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
1107            }
1108        }
1109    }
1110}
1111
1112#[derive(#[automatically_derived]
impl ::core::clone::Clone for AmbiguityWarning {
    #[inline]
    fn clone(&self) -> AmbiguityWarning { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AmbiguityWarning { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for AmbiguityWarning {
    #[inline]
    fn eq(&self, other: &AmbiguityWarning) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
1113enum AmbiguityWarning {
1114    GlobImport,
1115    PanicImport,
1116}
1117
1118struct AmbiguityError<'ra> {
1119    kind: AmbiguityKind,
1120    ambig_vis: Option<(Visibility, Visibility)>,
1121    ident: Ident,
1122    b1: Decl<'ra>,
1123    b2: Decl<'ra>,
1124    scope1: Scope<'ra>,
1125    scope2: Scope<'ra>,
1126    warning: Option<AmbiguityWarning>,
1127}
1128
1129impl<'ra> DeclData<'ra> {
1130    fn vis(&self) -> Visibility<ModId> {
1131        // Select the maximum visibility if there are multiple ambiguous glob imports.
1132        self.ambiguity_vis_max.get().map(|d| d.vis()).unwrap_or_else(|| self.initial_vis)
1133    }
1134
1135    fn min_vis(&self) -> Visibility<ModId> {
1136        // Select the minimum visibility if there are multiple ambiguous glob imports.
1137        self.ambiguity_vis_min.get().map(|d| d.vis()).unwrap_or_else(|| self.initial_vis)
1138    }
1139
1140    fn res(&self) -> Res {
1141        match self.kind {
1142            DeclKind::Def(res) => res,
1143            DeclKind::Import { source_decl, .. } => source_decl.res(),
1144        }
1145    }
1146
1147    fn import_source(&self) -> Decl<'ra> {
1148        match self.kind {
1149            DeclKind::Import { source_decl, .. } => source_decl,
1150            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1151        }
1152    }
1153
1154    fn descent_to_ambiguity(self: Decl<'ra>) -> Option<(Decl<'ra>, Decl<'ra>)> {
1155        match self.ambiguity.get() {
1156            Some((ambig_binding, _)) => Some((self, ambig_binding)),
1157            None => match self.kind {
1158                DeclKind::Import { source_decl, .. } => source_decl.descent_to_ambiguity(),
1159                _ => None,
1160            },
1161        }
1162    }
1163
1164    fn is_ambiguity_recursive(&self) -> bool {
1165        self.ambiguity.get().is_some()
1166            || match self.kind {
1167                DeclKind::Import { source_decl, .. } => source_decl.is_ambiguity_recursive(),
1168                _ => false,
1169            }
1170    }
1171
1172    fn is_possibly_imported_variant(&self) -> bool {
1173        match self.kind {
1174            DeclKind::Import { source_decl, .. } => source_decl.is_possibly_imported_variant(),
1175            DeclKind::Def(Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _)) => {
1176                true
1177            }
1178            DeclKind::Def(..) => false,
1179        }
1180    }
1181
1182    fn is_extern_crate(&self) -> bool {
1183        match self.kind {
1184            DeclKind::Import { import, .. } => {
1185                #[allow(non_exhaustive_omitted_patterns)] match import.kind {
    ImportKind::ExternCrate { .. } => true,
    _ => false,
}matches!(import.kind, ImportKind::ExternCrate { .. })
1186            }
1187            DeclKind::Def(Res::Def(_, def_id)) => def_id.is_crate_root(),
1188            _ => false,
1189        }
1190    }
1191
1192    fn is_import(&self) -> bool {
1193        #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    DeclKind::Import { .. } => true,
    _ => false,
}matches!(self.kind, DeclKind::Import { .. })
1194    }
1195
1196    /// The binding introduced by `#[macro_export] macro_rules` is a public import, but it might
1197    /// not be perceived as such by users, so treat it as a non-import in some diagnostics.
1198    fn is_import_user_facing(&self) -> bool {
1199        #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    DeclKind::Import { import, .. } if
        !#[allow(non_exhaustive_omitted_patterns)] match import.kind {
                ImportKind::MacroExport => true,
                _ => false,
            } => true,
    _ => false,
}matches!(self.kind, DeclKind::Import { import, .. }
1200            if !matches!(import.kind, ImportKind::MacroExport))
1201    }
1202
1203    fn is_glob_import(&self) -> bool {
1204        match self.kind {
1205            DeclKind::Import { import, .. } => import.is_glob(),
1206            _ => false,
1207        }
1208    }
1209
1210    fn is_assoc_item(&self) -> bool {
1211        #[allow(non_exhaustive_omitted_patterns)] match self.res() {
    Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy,
        _) => true,
    _ => false,
}matches!(
1212            self.res(),
1213            Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy, _)
1214        )
1215    }
1216
1217    fn macro_kinds(&self) -> Option<MacroKinds> {
1218        self.res().macro_kinds()
1219    }
1220
1221    fn reexport_chain(self: Decl<'ra>) -> SmallVec<[Reexport; 2]> {
1222        let mut reexport_chain = SmallVec::new();
1223        let mut next_binding = self;
1224        while let DeclKind::Import { source_decl, import, .. } = next_binding.kind {
1225            reexport_chain.push(import.simplify());
1226            next_binding = source_decl;
1227        }
1228        reexport_chain
1229    }
1230
1231    // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
1232    // at some expansion round `max(invoc, binding)` when they both emerged from macros.
1233    // Then this function returns `true` if `self` may emerge from a macro *after* that
1234    // in some later round and screw up our previously found resolution.
1235    // See more detailed explanation in
1236    // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
1237    fn may_appear_after(&self, invoc_parent_expansion: LocalExpnId, decl: Decl<'_>) -> bool {
1238        // self > max(invoc, decl) => !(self <= invoc || self <= decl)
1239        // Expansions are partially ordered, so "may appear after" is an inversion of
1240        // "certainly appears before or simultaneously" and includes unordered cases.
1241        let self_parent_expansion = self.expansion;
1242        let other_parent_expansion = decl.expansion;
1243        let certainly_before_other_or_simultaneously =
1244            other_parent_expansion.is_descendant_of(self_parent_expansion);
1245        let certainly_before_invoc_or_simultaneously =
1246            invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1247        !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1248    }
1249
1250    /// Returns whether this declaration may be shadowed or overwritten by something else later.
1251    /// FIXME: this function considers `unexpanded_invocations`, but not `single_imports`, so
1252    /// the declaration may not be as "determined" as we think.
1253    /// FIXME: relationship between this function and similar `NameResolution::determined_decl`
1254    /// is unclear.
1255    fn determined(&self) -> bool {
1256        match &self.kind {
1257            DeclKind::Import { source_decl, import, .. } if import.is_glob() => {
1258                !import.parent_scope.module.has_unexpanded_invocations() && source_decl.determined()
1259            }
1260            _ => true,
1261        }
1262    }
1263}
1264
1265#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for ExternPreludeEntry<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "ExternPreludeEntry", "item_decl", &self.item_decl, "flag_decl",
            &&self.flag_decl)
    }
}Debug)]
1266struct ExternPreludeEntry<'ra> {
1267    /// Name declaration from an `extern crate` item.
1268    /// The boolean flag is true is `item_decl` is non-redundant, happens either when
1269    /// `flag_decl` is `None`, or when `extern crate` introducing `item_decl` used renaming.
1270    item_decl: Option<(Decl<'ra>, Span, /* introduced by item */ bool)>,
1271    /// Name declaration from an `--extern` flag, lazily populated on first use.
1272    flag_decl: Option<
1273        CacheCell<(
1274            PendingDecl<'ra>,
1275            /* finalized */ bool,
1276            /* open flag (namespaced crate) */ bool,
1277        )>,
1278    >,
1279}
1280
1281impl ExternPreludeEntry<'_> {
1282    fn introduced_by_item(&self) -> bool {
1283        #[allow(non_exhaustive_omitted_patterns)] match self.item_decl {
    Some((.., true)) => true,
    _ => false,
}matches!(self.item_decl, Some((.., true)))
1284    }
1285
1286    fn flag() -> Self {
1287        ExternPreludeEntry {
1288            item_decl: None,
1289            flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, false))),
1290        }
1291    }
1292
1293    fn open_flag() -> Self {
1294        ExternPreludeEntry {
1295            item_decl: None,
1296            flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, true))),
1297        }
1298    }
1299
1300    fn span(&self) -> Span {
1301        match self.item_decl {
1302            Some((_, span, _)) => span,
1303            None => DUMMY_SP,
1304        }
1305    }
1306}
1307
1308struct DeriveData {
1309    resolutions: Vec<DeriveResolution>,
1310    helper_attrs: Vec<(usize, IdentKey, Span)>,
1311    // if this list keeps getting extended, we could use `bitflags`,
1312    // something like what [`rustc_type_ir::flags::TypeFlags`] is doing.
1313    has_derive_copy: bool,
1314    has_derive_ord: bool,
1315}
1316
1317pub struct ResolverOutputs<'tcx> {
1318    pub global_ctxt: ResolverGlobalCtxt,
1319    pub ast_lowering: ResolverAstLowering<'tcx>,
1320}
1321
1322#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DelegationFnSig {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "DelegationFnSig", "has_self", &&self.has_self)
    }
}Debug)]
1323struct DelegationFnSig {
1324    pub has_self: bool,
1325}
1326
1327/// The main resolver class.
1328///
1329/// This is the visitor that walks the whole crate.
1330pub struct Resolver<'ra, 'tcx> {
1331    tcx: TyCtxt<'tcx>,
1332
1333    /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
1334    expn_that_defined: UnordMap<LocalDefId, ExpnId> = Default::default(),
1335
1336    graph_root: LocalModule<'ra>,
1337
1338    /// Assert that we are in speculative resolution mode (unsafe field).
1339    assert_speculative: bool,
1340
1341    prelude: Option<Module<'ra>> = None,
1342    extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>>,
1343
1344    /// N.B., this is used only for better diagnostics, not name resolution itself.
1345    field_names: LocalDefIdMap<Vec<Ident>> = Default::default(),
1346    field_defaults: LocalDefIdMap<Vec<Symbol>> = Default::default(),
1347
1348    /// Span of the privacy modifier in fields of an item `DefId` accessible with dot syntax.
1349    /// Used for hints during error reporting.
1350    field_visibility_spans: FxHashMap<DefId, Vec<Span>> = default::fx_hash_map(),
1351
1352    /// All imports known to succeed or fail.
1353    determined_imports: Vec<Import<'ra>> = Vec::new(),
1354
1355    /// All non-determined imports.
1356    indeterminate_imports: Vec<(Import<'ra>, Option<ImportResolution<'ra>>, usize)> = Vec::new(),
1357
1358    // Spans for local variables found during pattern resolution.
1359    // Used for suggestions during error reporting.
1360    pat_span_map: NodeMap<Span> = Default::default(),
1361
1362    /// Resolutions for nodes that have a single resolution.
1363    partial_res_map: NodeMap<PartialRes> = Default::default(),
1364    /// An import will be inserted into this map if it has been used.
1365    import_use_map: FxHashMap<Import<'ra>, Used> = default::fx_hash_map(),
1366
1367    /// `CrateNum` resolutions of `extern crate` items.
1368    extern_crate_map: UnordMap<LocalDefId, CrateNum> = Default::default(),
1369    module_children: LocalDefIdMap<Vec<ModChild>> = Default::default(),
1370    ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>> = Default::default(),
1371
1372    /// A map from nodes to anonymous modules.
1373    /// Anonymous modules are pseudo-modules that are implicitly created around items
1374    /// contained within blocks.
1375    ///
1376    /// For example, if we have this:
1377    ///
1378    ///  fn f() {
1379    ///      fn g() {
1380    ///          ...
1381    ///      }
1382    ///  }
1383    ///
1384    /// There will be an anonymous module created around `g` with the ID of the
1385    /// entry block for `f`.
1386    block_map: NodeMap<LocalModule<'ra>> = Default::default(),
1387    /// A fake module that contains no definition and no prelude. Used so that
1388    /// some AST passes can generate identifiers that only resolve to local or
1389    /// lang items.
1390    empty_module: LocalModule<'ra>,
1391    /// All local modules, including blocks.
1392    local_modules: Vec<LocalModule<'ra>>,
1393    /// Eagerly populated map of all local non-block modules.
1394    local_module_map: FxIndexMap<LocalDefId, LocalModule<'ra>>,
1395    /// Lazily populated cache of modules loaded from external crates.
1396    extern_module_map: CacheRefCell<FxIndexMap<DefId, ExternModule<'ra>>>,
1397
1398    /// Maps glob imports to the names of items actually imported.
1399    glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
1400    glob_error: Option<ErrorGuaranteed> = None,
1401    visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(),
1402    used_imports: FxHashSet<NodeId> = default::fx_hash_set(),
1403    maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
1404
1405    /// Privacy errors are delayed until the end in order to deduplicate them.
1406    privacy_errors: Vec<PrivacyError<'ra>> = Vec::new(),
1407    /// Ambiguity errors are delayed for deduplication.
1408    ambiguity_errors: Vec<AmbiguityError<'ra>> = Vec::new(),
1409    issue_145575_hack_applied: bool = false,
1410    /// Visibility path resolution failures are delayed until all modules are collected.
1411    delayed_vis_resolution_errors: Vec<DelayedVisResolutionError<'ra>> = Vec::new(),
1412    /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
1413    macro_expanded_macro_export_errors: BTreeSet<(Span, Span)> = BTreeSet::new(),
1414
1415    arenas: &'ra WorkerLocal<ResolverArenas<'ra>>,
1416    dummy_decl: Decl<'ra>,
1417    builtin_type_decls: FxHashMap<Symbol, Decl<'ra>>,
1418    builtin_attr_decls: FxHashMap<Symbol, Decl<'ra>>,
1419    registered_attr_tool_decls: FxHashMap<IdentKey, Decl<'ra>>,
1420    macro_names: FxHashSet<IdentKey> = default::fx_hash_set(),
1421    builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind> = default::fx_hash_map(),
1422    registered_attr_tools: &'tcx RegisteredTools,
1423    registered_lint_tools: &'tcx RegisteredTools,
1424    macro_use_prelude: FxIndexMap<Symbol, Decl<'ra>>,
1425    /// Eagerly populated map of all local macro definitions.
1426    local_macro_map: FxHashMap<LocalDefId, &'ra Arc<SyntaxExtension>> = default::fx_hash_map(),
1427    /// Lazily populated cache of macro definitions loaded from external crates.
1428    extern_macro_map: CacheRefCell<FxHashMap<DefId, &'ra Arc<SyntaxExtension>>>,
1429    dummy_ext_bang: &'ra Arc<SyntaxExtension>,
1430    dummy_ext_derive: &'ra Arc<SyntaxExtension>,
1431    non_macro_attr: &'ra Arc<SyntaxExtension>,
1432    local_macro_def_scopes: FxHashMap<LocalDefId, LocalModule<'ra>> = default::fx_hash_map(),
1433    ast_transform_scopes: FxHashMap<LocalExpnId, LocalModule<'ra>> = default::fx_hash_map(),
1434    unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
1435    /// A map from the macro to all its potentially unused arms and the `LocalDefId` of the macro itself.
1436    unused_macro_rules: FxIndexMap<NodeId, (LocalDefId, DenseBitSet<usize>)>,
1437    proc_macro_stubs: FxHashSet<LocalDefId> = default::fx_hash_set(),
1438    /// Traces collected during macro resolution and validated when it's complete.
1439    single_segment_macro_resolutions:
1440        CmRefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<Decl<'ra>>, Option<Span>)>>,
1441    multi_segment_macro_resolutions:
1442        CmRefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,
1443    builtin_attrs: Vec<(Ident, ParentScope<'ra>)> = Vec::new(),
1444    /// `derive(Copy)` marks items they are applied to so they are treated specially later.
1445    /// Derive macros cannot modify the item themselves and have to store the markers in the global
1446    /// context, so they attach the markers to derive container IDs using this resolver table.
1447    containers_deriving_copy: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1448    containers_deriving_ord: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1449    /// Parent scopes in which the macros were invoked.
1450    /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
1451    invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>> = default::fx_hash_map(),
1452    /// `macro_rules` scopes *produced* by expanding the macro invocations,
1453    /// include all the `macro_rules` items and other invocations generated by them.
1454    output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),
1455    /// `macro_rules` scopes produced by `macro_rules` item definitions.
1456    macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),
1457    /// Helper attributes that are in scope for the given expansion.
1458    helper_attrs: FxHashMap<LocalExpnId, Vec<(IdentKey, Span, Decl<'ra>)>> = default::fx_hash_map(),
1459    /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute
1460    /// with the given `ExpnId`.
1461    derive_data: FxHashMap<LocalExpnId, DeriveData> = default::fx_hash_map(),
1462
1463    /// Avoid duplicated errors for "name already defined".
1464    name_already_seen: FxHashMap<Symbol, Span> = default::fx_hash_map(),
1465
1466    potentially_unused_imports: Vec<Import<'ra>> = Vec::new(),
1467
1468    potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>> = Vec::new(),
1469
1470    /// Table for mapping struct IDs into struct constructor IDs,
1471    /// it's not used during normal resolution, only for better error reporting.
1472    /// Also includes of list of each fields visibility
1473    struct_ctors: LocalDefIdMap<StructCtor> = Default::default(),
1474
1475    /// for all the struct
1476    /// it's not used during normal resolution, only for better error reporting.
1477    struct_generics: LocalDefIdMap<Generics> = Default::default(),
1478
1479    lint_buffer: LintBuffer,
1480
1481    next_node_id: NodeId = CRATE_NODE_ID,
1482
1483    /// Preserves per owner data once the owner is finished resolving.
1484    owners: NodeMap<PerOwnerResolverData<'tcx>>,
1485
1486    /// An entry of `owners` that gets taken out and reinserted whenever an owner is handled.
1487    current_owner: PerOwnerResolverData<'tcx>,
1488
1489    disambiguators: LocalDefIdMap<PerParentDisambiguatorState>,
1490
1491    /// Indices of unnamed struct or variant fields with unresolved attributes.
1492    placeholder_field_indices: FxHashMap<NodeId, usize> = default::fx_hash_map(),
1493    /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
1494    /// we know what parent node that fragment should be attached to thanks to this table,
1495    /// and how the `impl Trait` fragments were introduced.
1496    invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
1497
1498    /// Amount of lifetime parameters for each item in the crate.
1499    item_generics_num_lifetimes: FxHashMap<LocalDefId, usize> = default::fx_hash_map(),
1500    /// Generic args to suggest for required params (e.g. `<'_>`, `<_, _>`), if any.
1501    item_required_generic_args_suggestions: FxHashMap<LocalDefId, String> = default::fx_hash_map(),
1502    delegation_fn_sigs: LocalDefIdMap<DelegationFnSig> = Default::default(),
1503    delegation_infos: FxIndexMap<LocalDefId, DelegationInfo>,
1504
1505    main_def: Option<MainDefinition> = None,
1506    trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1507    /// A list of proc macro LocalDefIds, written out in the order in which
1508    /// they are declared in the static array generated by proc_macro_harness.
1509    proc_macros: Vec<LocalDefId> = Vec::new(),
1510    confused_type_with_std_module: FxIndexMap<Span, Span>,
1511
1512    /// Names of items that were stripped out via cfg with their corresponding cfg meta item.
1513    stripped_cfg_items: Vec<StrippedCfgItem<NodeId>> = Vec::new(),
1514
1515    effective_visibilities: EffectiveVisibilities,
1516    macro_reachable_adts: FxIndexMap<LocalDefId, FxIndexSet<LocalDefId>>,
1517
1518    doc_link_resolutions: FxIndexMap<LocalModId, DocLinkResMap>,
1519    doc_link_traits_in_scope: FxIndexMap<LocalModId, Vec<DefId>>,
1520    all_macro_rules: UnordSet<Symbol> = Default::default(),
1521
1522    /// Invocation ids of all glob delegations.
1523    glob_delegation_invoc_ids: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1524    /// Analogue of module `unexpanded_invocations` but in trait impls, excluding glob delegations.
1525    /// Needed because glob delegations wait for all other neighboring macros to expand.
1526    impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>> = default::fx_hash_map(),
1527    /// Simplified analogue of module `resolutions` but in trait impls, excluding glob delegations.
1528    /// Needed because glob delegations exclude explicitly defined names.
1529    impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>> = default::fx_hash_map(),
1530
1531    /// This is the `Span` where an `extern crate foo;` suggestion would be inserted, if `foo`
1532    /// could be a crate that wasn't imported. For diagnostics use only.
1533    current_crate_outer_attr_insert_span: Span,
1534
1535    mods_with_parse_errors: FxHashSet<DefId> = default::fx_hash_set(),
1536
1537    /// Whether `Resolver::register_macros_for_all_crates` has been called once already, as we
1538    /// don't need to run it more than once.
1539    all_crate_macros_already_registered: bool = false,
1540
1541    // Stores pre-expansion and pre-placeholder-fragment-insertion names for `impl Trait` types
1542    // that were encountered during resolution. These names are used to generate item names
1543    // for APITs, so we don't want to leak details of resolution into these names.
1544    impl_trait_names: FxHashMap<NodeId, Symbol> = default::fx_hash_map(),
1545
1546    /// Stores `#[diagnostic::on_unknown]` attributes placed on module declarations.
1547    on_unknown_data: FxHashMap<LocalDefId, OnUnknownData> = default::fx_hash_map(),
1548    features: &'tcx Features,
1549}
1550
1551/// This provides memory for the rest of the crate. The `'ra` lifetime that is
1552/// used by many types in this crate is an abbreviation of `ResolverArenas`.
1553#[derive(#[automatically_derived]
impl<'ra> ::core::default::Default for ResolverArenas<'ra> {
    #[inline]
    fn default() -> ResolverArenas<'ra> {
        ResolverArenas {
            modules: ::core::default::Default::default(),
            imports: ::core::default::Default::default(),
            name_resolutions: ::core::default::Default::default(),
            ast_paths: ::core::default::Default::default(),
            macros: ::core::default::Default::default(),
            dropless: ::core::default::Default::default(),
        }
    }
}Default)]
1554pub struct ResolverArenas<'ra> {
1555    modules: TypedArena<ModuleData<'ra>>,
1556    imports: TypedArena<ImportData<'ra>>,
1557    name_resolutions: TypedArena<CmRefCell<NameResolution<'ra>>>,
1558    ast_paths: TypedArena<ast::Path>,
1559    macros: TypedArena<Arc<SyntaxExtension>>,
1560    dropless: DroplessArena,
1561}
1562
1563impl<'ra> ResolverArenas<'ra> {
1564    fn new_def_decl(
1565        &'ra self,
1566        res: Res,
1567        vis: Visibility<ModId>,
1568        span: Span,
1569        expansion: LocalExpnId,
1570        parent_module: Option<Module<'ra>>,
1571    ) -> Decl<'ra> {
1572        self.alloc_decl(DeclData {
1573            kind: DeclKind::Def(res),
1574            ambiguity: CmCell::new(None),
1575            initial_vis: vis,
1576            ambiguity_vis_max: CmCell::new(None),
1577            ambiguity_vis_min: CmCell::new(None),
1578            span,
1579            expansion,
1580            parent_module,
1581        })
1582    }
1583
1584    fn new_pub_def_decl(&'ra self, res: Res, span: Span, expn_id: LocalExpnId) -> Decl<'ra> {
1585        self.new_def_decl(res, Visibility::Public, span, expn_id, None)
1586    }
1587
1588    fn alloc_decl(&'ra self, data: DeclData<'ra>) -> Decl<'ra> {
1589        // SAFETY: `Interned` is valid because values of this type have "identity".
1590        Interned::new_unchecked(self.dropless.alloc(data))
1591    }
1592    fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1593        // SAFETY: `Interned` is valid because values of this type have "identity".
1594        Interned::new_unchecked(self.imports.alloc(import))
1595    }
1596    fn alloc_name_resolution(&'ra self, resolution: NameResolution<'ra>) -> NameResolutionRef<'ra> {
1597        // SAFETY: `Interned` is valid because values of this type have "identity".
1598        Interned::new_unchecked(self.name_resolutions.alloc(CmRefCell::new(resolution)))
1599    }
1600    fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1601        self.dropless.alloc(CacheCell::new(scope))
1602    }
1603    fn alloc_macro_rules_decl(&'ra self, decl: MacroRulesDecl<'ra>) -> &'ra MacroRulesDecl<'ra> {
1604        self.dropless.alloc(decl)
1605    }
1606    fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1607        self.ast_paths.alloc_from_iter(paths.iter().cloned())
1608    }
1609    fn alloc_macro(&'ra self, ext: SyntaxExtension) -> &'ra Arc<SyntaxExtension> {
1610        self.macros.alloc(Arc::new(ext))
1611    }
1612    fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1613        self.dropless.alloc_from_iter(spans)
1614    }
1615}
1616
1617impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1618    fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1619        self
1620    }
1621}
1622
1623impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1624    fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1625        self
1626    }
1627}
1628
1629impl<'tcx> Resolver<'_, 'tcx> {
1630    /// Only call this in analyses after the resolver has finished.
1631    /// Panics if the node id is currently not in the owner storage,
1632    /// e.g. because it's further up in the current visitor stack.
1633    fn owner_def_id(&self, owner: NodeId) -> LocalDefId {
1634        self.owners[&owner].def_id
1635    }
1636
1637    /// Only call this in analyses after the resolver has finished.
1638    /// Panics if the node id is currently not in the owner storage,
1639    /// e.g. because it's further up in the current visitor stack.
1640    fn child_def_id(&self, owner: NodeId, id: NodeId) -> LocalDefId {
1641        self.owners[&owner].node_id_to_def_id[&id]
1642    }
1643
1644    /// Get the `DefId` of a child of the current owner
1645    fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1646        self.current_owner.node_id_to_def_id.get(&node).copied()
1647    }
1648
1649    /// Get the `DefId` of a child of the current owner
1650    fn local_def_id(&self, node: NodeId) -> LocalDefId {
1651        self.opt_local_def_id(node).unwrap_or_else(|| {
    ::core::panicking::panic_fmt(format_args!("no entry for node id: `{0:?}`",
            node));
}panic!("no entry for node id: `{node:?}`"))
1652    }
1653
1654    /// Adds a definition with a parent definition.
1655    fn create_def(
1656        &mut self,
1657        parent: LocalDefId,
1658        node_id: ast::NodeId,
1659        name: Option<Symbol>,
1660        def_kind: DefKind,
1661        expn_id: ExpnId,
1662        span: Span,
1663        is_owner: bool,
1664    ) -> TyCtxtFeed<'tcx, LocalDefId> {
1665        if !!self.current_owner.node_id_to_def_id.contains_key(&node_id) {
    {
        ::core::panicking::panic_fmt(format_args!("adding a def for node-id {0:?}, name {1:?}, data {2:?} but a previous def exists: {3:?}",
                node_id, name, def_kind,
                self.tcx.definitions_untracked().def_key(self.current_owner.node_id_to_def_id[&node_id])));
    }
};assert!(
1666            !self.current_owner.node_id_to_def_id.contains_key(&node_id),
1667            "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1668            node_id,
1669            name,
1670            def_kind,
1671            self.tcx
1672                .definitions_untracked()
1673                .def_key(self.current_owner.node_id_to_def_id[&node_id]),
1674        );
1675
1676        let disambiguator = self.disambiguators.get_or_create(parent);
1677
1678        // FIXME: remove `def_span` body, pass in the right spans here and call `tcx.at().create_def()`
1679        let feed = self.tcx.create_def(parent, name, def_kind, None, disambiguator);
1680        let def_id = feed.def_id();
1681
1682        // Create the definition.
1683        if expn_id != ExpnId::root() {
1684            self.expn_that_defined.insert(def_id, expn_id);
1685        }
1686
1687        // A relative span's parent must be an absolute span.
1688        if true {
    {
        match (&span.data_untracked().parent, &None) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(span.data_untracked().parent, None);
1689        let _id = self.tcx.untracked().source_span.push(span);
1690        if true {
    {
        match (&_id, &def_id) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(_id, def_id);
1691
1692        // Some things for which we allocate `LocalDefId`s don't correspond to
1693        // anything in the AST, so they don't have a `NodeId`. For these cases
1694        // we don't need a mapping from `NodeId` to `LocalDefId`.
1695        if node_id != ast::DUMMY_NODE_ID && !is_owner {
1696            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:1696",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1696u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::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!("create_def: def_id_to_node_id[{0:?}] <-> {1:?}",
                                                    def_id, node_id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1697            self.current_owner.node_id_to_def_id.insert(node_id, def_id);
1698        }
1699
1700        feed
1701    }
1702
1703    fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1704        if let Some(def_id) = def_id.as_local() {
1705            self.item_generics_num_lifetimes[&def_id]
1706        } else {
1707            self.tcx.generics_of(def_id).own_counts().lifetimes
1708        }
1709    }
1710
1711    fn item_required_generic_args_suggestion(&self, def_id: DefId) -> String {
1712        if let Some(def_id) = def_id.as_local() {
1713            self.item_required_generic_args_suggestions.get(&def_id).cloned().unwrap_or_default()
1714        } else {
1715            let required = self
1716                .tcx
1717                .generics_of(def_id)
1718                .own_params
1719                .iter()
1720                .filter_map(|param| match param.kind {
1721                    ty::GenericParamDefKind::Lifetime => Some("'_"),
1722                    ty::GenericParamDefKind::Type { has_default, .. }
1723                    | ty::GenericParamDefKind::Const { has_default } => {
1724                        if has_default {
1725                            None
1726                        } else {
1727                            Some("_")
1728                        }
1729                    }
1730                })
1731                .collect::<Vec<_>>();
1732
1733            if required.is_empty() { String::new() } else { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>", required.join(", ")))
    })format!("<{}>", required.join(", ")) }
1734        }
1735    }
1736
1737    pub fn tcx(&self) -> TyCtxt<'tcx> {
1738        self.tcx
1739    }
1740
1741    /// This function is very slow, as it iterates over the entire
1742    /// [PerOwnerResolverData::node_id_to_def_id] map for all [Resolver::owners]
1743    /// just to find the [NodeId]
1744    /// that corresponds to the given [LocalDefId]. Only use this in
1745    /// diagnostics code paths. Do not use this during macro expansion,
1746    /// as it will not find any node ids within your current expansion's stack.
1747    fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1748        self.owners
1749            .items()
1750            .flat_map(|(_, data)| {
1751                data.node_id_to_def_id
1752                    .items()
1753                    .chain(UnordItems::new([(&data.id, &data.def_id)].into_iter()))
1754            })
1755            .filter(|(_, v)| **v == def_id)
1756            .map(|(k, _)| *k)
1757            .get_only()
1758            .unwrap()
1759    }
1760}
1761
1762impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1763    pub fn new(
1764        tcx: TyCtxt<'tcx>,
1765        attrs: &[ast::Attribute],
1766        crate_span: Span,
1767        current_crate_outer_attr_insert_span: Span,
1768        arenas: &'ra WorkerLocal<ResolverArenas<'ra>>,
1769    ) -> Resolver<'ra, 'tcx> {
1770        let root_def_id = CRATE_DEF_ID.to_def_id();
1771        let graph_root = LocalModule::new(
1772            None,
1773            ModuleKind::Def(DefKind::Mod, root_def_id, CRATE_NODE_ID, None),
1774            Visibility::Public,
1775            ExpnId::root(),
1776            crate_span,
1777            attr::contains_name(attrs, sym::no_implicit_prelude),
1778            arenas,
1779        );
1780        let local_modules = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [graph_root]))vec![graph_root];
1781        let local_module_map = FxIndexMap::from_iter([(CRATE_DEF_ID, graph_root)]);
1782        let empty_module = LocalModule::new(
1783            None,
1784            ModuleKind::Def(DefKind::Mod, root_def_id, CRATE_NODE_ID, None),
1785            Visibility::Public,
1786            ExpnId::root(),
1787            DUMMY_SP,
1788            true,
1789            arenas,
1790        );
1791
1792        let owner_data = PerOwnerResolverData::new(CRATE_NODE_ID, CRATE_DEF_ID);
1793        let crate_feed = tcx.create_local_crate_def_id(crate_span);
1794
1795        crate_feed.def_kind(DefKind::Mod);
1796        let mut owners = NodeMap::default();
1797        owners.insert(CRATE_NODE_ID, owner_data);
1798
1799        let mut invocation_parents = FxHashMap::default();
1800        invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1801
1802        let extern_prelude = build_extern_prelude(tcx, attrs);
1803        let registered_attr_tools = tcx.registered_attr_tools(());
1804        let registered_lint_tools = tcx.registered_lint_tools(());
1805        let edition = tcx.sess.edition();
1806
1807        let mut resolver = Resolver {
1808            tcx,
1809
1810            // The outermost module has def ID 0; this is not reflected in the
1811            // AST.
1812            graph_root,
1813            assert_speculative: false, // Only set/cleared in Resolver::resolve_imports for now
1814            extern_prelude,
1815
1816            empty_module,
1817            local_modules,
1818            local_module_map,
1819            extern_module_map: Default::default(),
1820
1821            glob_map: Default::default(),
1822            maybe_unused_trait_imports: Default::default(),
1823
1824            arenas,
1825            dummy_decl: arenas.new_pub_def_decl(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1826            builtin_type_decls: PrimTy::ALL
1827                .iter()
1828                .map(|prim_ty| {
1829                    let res = Res::PrimTy(*prim_ty);
1830                    let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1831                    (prim_ty.name(), decl)
1832                })
1833                .collect(),
1834            builtin_attr_decls: BUILTIN_ATTRIBUTES
1835                .iter()
1836                .map(|builtin_attr| {
1837                    let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(*builtin_attr));
1838                    let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1839                    (*builtin_attr, decl)
1840                })
1841                .collect(),
1842            registered_attr_tool_decls: registered_attr_tools
1843                .iter()
1844                .map(|&ident| {
1845                    let res = Res::ToolMod;
1846                    let decl = arenas.new_pub_def_decl(res, ident.span, LocalExpnId::ROOT);
1847                    (IdentKey::new(ident), decl)
1848                })
1849                .collect(),
1850            registered_attr_tools,
1851            registered_lint_tools,
1852            macro_use_prelude: Default::default(),
1853            extern_macro_map: Default::default(),
1854            dummy_ext_bang: arenas.alloc_macro(SyntaxExtension::dummy_bang(edition)),
1855            dummy_ext_derive: arenas.alloc_macro(SyntaxExtension::dummy_derive(edition)),
1856            non_macro_attr: arenas.alloc_macro(SyntaxExtension::non_macro_attr(edition)),
1857            unused_macros: Default::default(),
1858            unused_macro_rules: Default::default(),
1859            single_segment_macro_resolutions: Default::default(),
1860            multi_segment_macro_resolutions: Default::default(),
1861            lint_buffer: LintBuffer::default(),
1862            owners,
1863            current_owner: PerOwnerResolverData::new(DUMMY_NODE_ID, CRATE_DEF_ID),
1864            invocation_parents,
1865            trait_impls: Default::default(),
1866            confused_type_with_std_module: Default::default(),
1867            stripped_cfg_items: Default::default(),
1868            effective_visibilities: Default::default(),
1869            macro_reachable_adts: Default::default(),
1870            doc_link_resolutions: Default::default(),
1871            doc_link_traits_in_scope: Default::default(),
1872            current_crate_outer_attr_insert_span,
1873            disambiguators: Default::default(),
1874            delegation_infos: Default::default(),
1875            features: tcx.features(),
1876            ..
1877        };
1878
1879        if let Some(directive) = OnUnknownData::from_attrs(&resolver, attrs) {
1880            resolver.on_unknown_data.insert(CRATE_DEF_ID, directive);
1881        }
1882
1883        let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
1884        resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1885        resolver.feed_visibility(crate_feed, Visibility::Public);
1886
1887        resolver
1888    }
1889
1890    fn new_local_module(
1891        &mut self,
1892        parent: Option<LocalModule<'ra>>,
1893        kind: ModuleKind,
1894        expn_id: ExpnId,
1895        span: Span,
1896        no_implicit_prelude: bool,
1897    ) -> LocalModule<'ra> {
1898        let vis =
1899            kind.opt_def_id().map_or(Visibility::Public, |def_id| self.tcx.visibility(def_id));
1900        let module =
1901            LocalModule::new(parent, kind, vis, expn_id, span, no_implicit_prelude, self.arenas);
1902        self.local_modules.push(module);
1903        if let Some(def_id) = module.opt_def_id() {
1904            self.local_module_map.insert(def_id.expect_local(), module);
1905        }
1906        module
1907    }
1908
1909    fn next_node_id(&mut self) -> NodeId {
1910        let start = self.next_node_id;
1911        let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1912        self.next_node_id = ast::NodeId::from_u32(next);
1913        start
1914    }
1915
1916    fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1917        let start = self.next_node_id;
1918        let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1919        self.next_node_id = ast::NodeId::from_usize(end);
1920        start..self.next_node_id
1921    }
1922
1923    pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1924        &mut self.lint_buffer
1925    }
1926
1927    pub fn arenas() -> ResolverArenas<'ra> {
1928        Default::default()
1929    }
1930
1931    fn feed_visibility(&mut self, feed: TyCtxtFeed<'tcx, LocalDefId>, vis: Visibility) {
1932        feed.visibility(vis.to_mod_id());
1933        self.visibilities_for_hashing.push((feed.def_id(), vis));
1934    }
1935
1936    pub fn into_outputs(self) -> ResolverOutputs<'tcx> {
1937        let proc_macros = self.proc_macros;
1938        let expn_that_defined = self.expn_that_defined;
1939        let extern_crate_map = self.extern_crate_map;
1940        let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1941        let glob_map = self.glob_map;
1942        let main_def = self.main_def;
1943        let confused_type_with_std_module = self.confused_type_with_std_module;
1944        let effective_visibilities = self.effective_visibilities;
1945
1946        let stripped_cfg_items = self
1947            .stripped_cfg_items
1948            .into_iter()
1949            .filter_map(|item| {
1950                let parent_scope = self.owners.get(&item.parent_scope)?.def_id.to_def_id();
1951                Some(StrippedCfgItem { parent_scope, ident: item.ident, cfg: item.cfg })
1952            })
1953            .collect();
1954        let disambiguators = self
1955            .disambiguators
1956            .into_items()
1957            .map(|(def_id, disamb)| (def_id, Steal::new(disamb)))
1958            .collect();
1959
1960        let global_ctxt = ResolverGlobalCtxt {
1961            expn_that_defined,
1962            visibilities_for_hashing: self.visibilities_for_hashing,
1963            effective_visibilities,
1964            macro_reachable_adts: self.macro_reachable_adts,
1965            extern_crate_map,
1966            module_children: self.module_children,
1967            ambig_module_children: self.ambig_module_children,
1968            glob_map,
1969            maybe_unused_trait_imports,
1970            main_def,
1971            trait_impls: self.trait_impls,
1972            proc_macros,
1973            confused_type_with_std_module,
1974            doc_link_resolutions: self.doc_link_resolutions,
1975            doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1976            all_macro_rules: self.all_macro_rules,
1977            stripped_cfg_items,
1978            delegation_infos: self.delegation_infos,
1979        };
1980        let ast_lowering = ty::ResolverAstLowering {
1981            partial_res_map: self.partial_res_map,
1982            next_node_id: self.next_node_id,
1983            owners: self.owners,
1984            lint_buffer: Steal::new(self.lint_buffer),
1985            disambiguators,
1986        };
1987        ResolverOutputs { global_ctxt, ast_lowering }
1988    }
1989
1990    fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1991        CStore::from_tcx(self.tcx)
1992    }
1993
1994    fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
1995        CStore::from_tcx_mut(self.tcx)
1996    }
1997
1998    fn dummy_ext(&self, macro_kind: MacroKind) -> &'ra Arc<SyntaxExtension> {
1999        match macro_kind {
2000            MacroKind::Bang => self.dummy_ext_bang,
2001            MacroKind::Derive => self.dummy_ext_derive,
2002            MacroKind::Attr => self.non_macro_attr,
2003        }
2004    }
2005
2006    /// Returns a conditionally mutable resolver that cannot be mutated.
2007    fn cm(&self) -> CmResolver<'_, 'ra, 'tcx> {
2008        CmResolver::Ref(self)
2009    }
2010
2011    /// Returns a conditionally mutable resolver that can be mutated.
2012    /// Will panic if the `assert_speculative` field is true.
2013    fn cm_mut(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
2014        if !!self.assert_speculative {
    {
        ::core::panicking::panic_fmt(format_args!("can\'t mutably borrow speculative resolver"));
    }
};assert!(!self.assert_speculative, "can't mutably borrow speculative resolver");
2015        CmResolver::Mut(self)
2016    }
2017
2018    /// Runs the function on each namespace.
2019    fn per_ns<F: FnMut(&Self, Namespace)>(&self, mut f: F) {
2020        f(self, TypeNS);
2021        f(self, ValueNS);
2022        f(self, MacroNS);
2023    }
2024
2025    fn per_ns_mut<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
2026        f(self, TypeNS);
2027        f(self, ValueNS);
2028        f(self, MacroNS);
2029    }
2030
2031    fn is_builtin_macro(&self, res: Res) -> bool {
2032        self.get_macro(res).is_some_and(|ext| ext.builtin_name.is_some())
2033    }
2034
2035    fn is_specific_builtin_macro(&self, res: Res, symbol: Symbol) -> bool {
2036        self.get_macro(res).is_some_and(|ext| ext.builtin_name == Some(symbol))
2037    }
2038
2039    fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
2040        loop {
2041            match ctxt.outer_expn_data().macro_def_id {
2042                Some(def_id) => return def_id,
2043                None => ctxt.remove_mark(),
2044            };
2045        }
2046    }
2047
2048    /// Entry point to crate resolution.
2049    pub fn resolve_crate(&mut self, krate: &Crate) {
2050        self.tcx.sess.time("resolve_crate", || {
2051            self.tcx.sess.time("finalize_imports", || self.finalize_imports());
2052            let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
2053                EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
2054            });
2055            self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
2056            self.tcx
2057                .sess
2058                .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
2059            let (use_items, use_injections) =
2060                self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
2061            self.tcx.sess.time("resolve_main", || self.resolve_main());
2062            self.tcx.sess.time("resolve_check_unused", || self.check_unused(use_items));
2063            self.tcx
2064                .sess
2065                .time("resolve_report_errors", || self.report_errors(krate, use_injections));
2066            self.tcx
2067                .sess
2068                .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
2069        });
2070
2071        // Don't mutate the cstore or stable crate id map from here on.
2072        self.tcx.untracked().freeze_cstore();
2073    }
2074
2075    fn traits_in_scope(
2076        &mut self,
2077        current_trait: Option<Module<'ra>>,
2078        parent_scope: &ParentScope<'ra>,
2079        sp: Span,
2080        assoc_item: Option<(Symbol, Namespace)>,
2081    ) -> &'tcx [TraitCandidate<'tcx>] {
2082        let mut found_traits = Vec::new();
2083
2084        if let Some(module) = current_trait {
2085            if self.trait_may_have_item(Some(module), assoc_item) {
2086                let def_id = module.def_id();
2087                found_traits.push(TraitCandidate {
2088                    def_id,
2089                    import_ids: &[],
2090                    lint_ambiguous: false,
2091                });
2092            }
2093        }
2094
2095        let scope_set = ScopeSet::All(TypeNS);
2096        let ctxt = Macros20NormalizedSyntaxContext::new(sp.ctxt());
2097        let cmr = self.cm_mut();
2098        cmr.visit_scopes(scope_set, parent_scope, ctxt, sp, None, |mut this, scope, _, _| {
2099            match scope {
2100                Scope::ModuleNonGlobs(module, _) => {
2101                    this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
2102                }
2103                Scope::ModuleGlobs(..) => {
2104                    // Already handled in `ModuleNonGlobs` (but see #144993).
2105                }
2106                Scope::StdLibPrelude => {
2107                    if let Some(module) = this.prelude {
2108                        this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
2109                    }
2110                }
2111                Scope::ExternPreludeItems
2112                | Scope::ExternPreludeFlags
2113                | Scope::ToolAttributePrelude
2114                | Scope::BuiltinTypes => {}
2115                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2116            }
2117            ControlFlow::<()>::Continue(())
2118        });
2119
2120        self.tcx.hir_arena.alloc_slice(&found_traits)
2121    }
2122
2123    fn traits_in_module(
2124        &mut self,
2125        module: Module<'ra>,
2126        assoc_item: Option<(Symbol, Namespace)>,
2127        found_traits: &mut Vec<TraitCandidate<'tcx>>,
2128    ) {
2129        module.ensure_traits(self);
2130        let traits = module.traits.borrow();
2131        for &(trait_name, trait_binding, trait_module, lint_ambiguous) in
2132            traits.as_ref().unwrap().iter()
2133        {
2134            if self.trait_may_have_item(trait_module, assoc_item) {
2135                let def_id = trait_binding.res().def_id();
2136                let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name);
2137                found_traits.push(TraitCandidate { def_id, import_ids, lint_ambiguous });
2138            }
2139        }
2140    }
2141
2142    // List of traits in scope is pruned on best effort basis. We reject traits not having an
2143    // associated item with the given name and namespace (if specified). This is a conservative
2144    // optimization, proper hygienic type-based resolution of associated items is done in typeck.
2145    // We don't reject trait aliases (`trait_module == None`) because we don't have access to their
2146    // associated items.
2147    fn trait_may_have_item(
2148        &self,
2149        trait_module: Option<Module<'ra>>,
2150        assoc_item: Option<(Symbol, Namespace)>,
2151    ) -> bool {
2152        match (trait_module, assoc_item) {
2153            (Some(trait_module), Some((name, ns))) => self
2154                .resolutions(trait_module)
2155                .iter()
2156                .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
2157            _ => true,
2158        }
2159    }
2160
2161    fn find_transitive_imports(
2162        &mut self,
2163        mut kind: &DeclKind<'_>,
2164        trait_name: Symbol,
2165    ) -> &'tcx [LocalDefId] {
2166        let mut import_ids: SmallVec<[LocalDefId; 1]> = ::smallvec::SmallVec::new()smallvec![];
2167        while let DeclKind::Import { import, source_decl, .. } = kind {
2168            if let Some(def_id) = import.def_id() {
2169                self.maybe_unused_trait_imports.insert(def_id);
2170                import_ids.push(def_id);
2171            }
2172            self.add_to_glob_map(*import, trait_name);
2173            kind = &source_decl.kind;
2174        }
2175
2176        self.tcx.hir_arena.alloc_slice(&import_ids)
2177    }
2178
2179    fn resolutions(&self, module: Module<'ra>) -> CmRef<'ra, ResolutionTable<'ra>> {
2180        match &module.0.0.lazy_resolutions {
2181            Resolutions::Local(local_res) => CmRef::Tracked(local_res.borrow()),
2182            Resolutions::Extern(extern_res) => {
2183                // It is fine to return a `CmRef::Untracked`, we never give out a `&mut`
2184                // to an external table.
2185                CmRef::Untracked(
2186                    // As long as 1 thread is building this external table, all other threads will wait.
2187                    extern_res
2188                        .get_or_init(|| self.build_reduced_graph_external(module.expect_extern())),
2189                )
2190            }
2191        }
2192    }
2193
2194    fn resolutions_mut(&self, module: Module<'ra>) -> RefMut<'ra, ResolutionTable<'ra>> {
2195        match &module.0.0.lazy_resolutions {
2196            Resolutions::Local(local_res) => local_res.borrow_mut(self),
2197            Resolutions::Extern(_) => {
2198                // We do not allow in place mutations of the external resolution table. In fact,
2199                // we never attempt it.
2200                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Attempted to mutably borrow an extenral resolution table")));
}unreachable!("Attempted to mutably borrow an extenral resolution table")
2201            }
2202        }
2203    }
2204
2205    fn resolution(
2206        &self,
2207        module: Module<'ra>,
2208        key: BindingKey,
2209    ) -> Option<Ref<'ra, NameResolution<'ra>>> {
2210        self.resolutions(module).get(&key).map(|resolution| resolution.0.borrow())
2211    }
2212
2213    #[track_caller]
2214    fn resolution_or_default(
2215        &self,
2216        module: Module<'ra>,
2217        key: BindingKey,
2218        orig_ident_span: Span,
2219    ) -> NameResolutionRef<'ra> {
2220        *self.resolutions_mut(module).entry(key).or_insert_with(|| {
2221            self.arenas.alloc_name_resolution(NameResolution::new(orig_ident_span))
2222        })
2223    }
2224
2225    /// Test if AmbiguityError ambi is any identical to any one inside ambiguity_errors
2226    fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
2227        for ambiguity_error in &self.ambiguity_errors {
2228            // if the span location and ident as well as its span are the same
2229            if ambiguity_error.kind == ambi.kind
2230                && ambiguity_error.ident == ambi.ident
2231                && ambiguity_error.ident.span == ambi.ident.span
2232                && ambiguity_error.b1.span == ambi.b1.span
2233                && ambiguity_error.b2.span == ambi.b2.span
2234            {
2235                return true;
2236            }
2237        }
2238        false
2239    }
2240
2241    fn record_use(&mut self, ident: Ident, used_decl: Decl<'ra>, used: Used) {
2242        if let Some((b2, warning)) = used_decl.ambiguity.get() {
2243            let ambiguity_error = AmbiguityError {
2244                kind: AmbiguityKind::GlobVsGlob,
2245                ambig_vis: None,
2246                ident,
2247                b1: used_decl,
2248                b2,
2249                scope1: Scope::ModuleGlobs(used_decl.parent_module.unwrap(), None),
2250                scope2: Scope::ModuleGlobs(b2.parent_module.unwrap(), None),
2251                warning: if warning { Some(AmbiguityWarning::GlobImport) } else { None },
2252            };
2253            if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2254                // avoid duplicated span information to be emit out
2255                self.ambiguity_errors.push(ambiguity_error);
2256            }
2257        }
2258        if let DeclKind::Import { import, source_decl } = used_decl.kind {
2259            if let ImportKind::MacroUse { warn_private: true } = import.kind {
2260                // Do not report the lint if the macro name resolves in stdlib prelude
2261                // even without the problematic `macro_use` import.
2262                let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2263                    let empty_module = self.empty_module;
2264                    let arenas = self.arenas;
2265                    self.cm()
2266                        .maybe_resolve_ident_in_module(
2267                            ModuleOrUniformRoot::Module(prelude),
2268                            ident,
2269                            MacroNS,
2270                            &ParentScope::module(empty_module, arenas),
2271                            None,
2272                        )
2273                        .is_ok()
2274                });
2275                if !found_in_stdlib_prelude {
2276                    self.lint_buffer().buffer_lint(
2277                        PRIVATE_MACRO_USE,
2278                        import.root_id,
2279                        ident.span,
2280                        diagnostics::MacroIsPrivate { ident },
2281                    );
2282                }
2283            }
2284            // Avoid marking `extern crate` items that refer to a name from extern prelude,
2285            // but not introduce it, as used if they are accessed from lexical scope.
2286            if used == Used::Scope
2287                && let Some(entry) = self.extern_prelude.get(&IdentKey::new(ident))
2288                && let Some((item_decl, _, false)) = entry.item_decl
2289                && item_decl == used_decl
2290            {
2291                return;
2292            }
2293            let old_used = self.import_use_map.entry(import).or_insert(used);
2294            if *old_used < used {
2295                *old_used = used;
2296            }
2297            if let Some(id) = import.id() {
2298                self.used_imports.insert(id);
2299            }
2300            self.add_to_glob_map(import, ident.name);
2301            self.record_use(ident, source_decl, Used::Other);
2302        }
2303    }
2304
2305    #[inline]
2306    fn add_to_glob_map(&mut self, import: Import<'_>, name: Symbol) {
2307        if let ImportKind::Glob { def_id, .. } = import.kind {
2308            self.glob_map.entry(def_id).or_default().insert(name);
2309        }
2310    }
2311
2312    fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2313        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2313",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2313u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::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!("resolve_crate_root({0:?})",
                                                    ident) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolve_crate_root({:?})", ident);
2314        let mut ctxt = ident.span.ctxt();
2315        let mark = if ident.name == kw::DollarCrate {
2316            // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
2317            // we don't want to pretend that the `macro_rules!` definition is in the `macro`
2318            // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks.
2319            // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
2320            // definitions actually produced by `macro` and `macro` definitions produced by
2321            // `macro_rules!`, but at least such configurations are not stable yet.
2322            ctxt = ctxt.normalize_to_macro_rules();
2323            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2323",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2323u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::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!("resolve_crate_root: marks={0:?}",
                                                    ctxt.marks().into_iter().map(|(i, t)|
                                                                (i.expn_data(), t)).collect::<Vec<_>>()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
2324                "resolve_crate_root: marks={:?}",
2325                ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2326            );
2327            let mut iter = ctxt.marks().into_iter().rev().peekable();
2328            let mut result = None;
2329            // Find the last opaque mark from the end if it exists.
2330            while let Some(&(mark, transparency)) = iter.peek() {
2331                if transparency == Transparency::Opaque {
2332                    result = Some(mark);
2333                    iter.next();
2334                } else {
2335                    break;
2336                }
2337            }
2338            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2338",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2338u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::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!("resolve_crate_root: found opaque mark {0:?} {1:?}",
                                                    result, result.map(|r| r.expn_data())) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
2339                "resolve_crate_root: found opaque mark {:?} {:?}",
2340                result,
2341                result.map(|r| r.expn_data())
2342            );
2343            // Then find the last semi-opaque mark from the end if it exists.
2344            for (mark, transparency) in iter {
2345                if transparency == Transparency::SemiOpaque {
2346                    result = Some(mark);
2347                } else {
2348                    break;
2349                }
2350            }
2351            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2351",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2351u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::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!("resolve_crate_root: found semi-opaque mark {0:?} {1:?}",
                                                    result, result.map(|r| r.expn_data())) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
2352                "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2353                result,
2354                result.map(|r| r.expn_data())
2355            );
2356            result
2357        } else {
2358            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2358",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2358u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::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!("resolve_crate_root: not DollarCrate")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolve_crate_root: not DollarCrate");
2359            ctxt = ctxt.normalize_to_macros_2_0();
2360            ctxt.adjust(ExpnId::root())
2361        };
2362        let module = match mark {
2363            Some(def) => self.expn_def_scope(def),
2364            None => {
2365                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2365",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2365u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::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!("resolve_crate_root({0:?}): found no mark (ident.span = {1:?})",
                                                    ident, ident.span) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
2366                    "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2367                    ident, ident.span
2368                );
2369                return self.graph_root.to_module();
2370            }
2371        };
2372        let module = self.expect_module(
2373            module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2374        );
2375        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2375",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2375u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::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!("resolve_crate_root({0:?}): got module {1:?} ({2:?}) (ident.span = {3:?})",
                                                    ident, module, module.name(), ident.span) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
2376            "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2377            ident,
2378            module,
2379            module.name(),
2380            ident.span
2381        );
2382        module
2383    }
2384
2385    fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2386        let mut module = self.expect_module(module.nearest_parent_mod().to_def_id());
2387        while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2388            let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2389            module = self.expect_module(parent.nearest_parent_mod().to_def_id());
2390        }
2391        module
2392    }
2393
2394    fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2395        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2395",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2395u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::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!("(recording res) recording {0:?} for {1}",
                                                    resolution, node_id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("(recording res) recording {:?} for {}", resolution, node_id);
2396        if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2397            {
    ::core::panicking::panic_fmt(format_args!("path resolved multiple times ({0:?} before, {1:?} now)",
            prev_res, resolution));
};panic!("path resolved multiple times ({prev_res:?} before, {resolution:?} now)");
2398        }
2399    }
2400
2401    fn record_pat_span(&mut self, node: NodeId, span: Span) {
2402        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2402",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2402u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                        ::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!("(recording pat) recording {0:?} for {1:?}",
                                                    node, span) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("(recording pat) recording {:?} for {:?}", node, span);
2403        self.pat_span_map.insert(node, span);
2404    }
2405
2406    fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
2407        vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2408    }
2409
2410    fn disambiguate_macro_rules_vs_modularized(
2411        &self,
2412        macro_rules: Decl<'ra>,
2413        modularized: Decl<'ra>,
2414    ) -> bool {
2415        // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules"
2416        // is disambiguated to mitigate regressions from macro modularization.
2417        // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
2418        //
2419        // Panic on unwrap should be impossible, the only name_bindings passed in should be from
2420        // `resolve_ident_in_scope_set` which will always refer to a local binding from an
2421        // import or macro definition.
2422        let macro_rules = macro_rules.parent_module.unwrap();
2423        let modularized = modularized.parent_module.unwrap();
2424        macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2425            && modularized.is_ancestor_of(macro_rules)
2426    }
2427
2428    fn extern_prelude_get_item<'r>(
2429        mut self: CmResolver<'r, 'ra, 'tcx>,
2430        ident: IdentKey,
2431        orig_ident_span: Span,
2432        finalize: bool,
2433    ) -> Option<Decl<'ra>> {
2434        let entry = self.extern_prelude.get(&ident);
2435        entry.and_then(|entry| entry.item_decl).map(|(decl, ..)| {
2436            if finalize {
2437                self.get_mut().record_use(ident.orig(orig_ident_span), decl, Used::Scope);
2438            }
2439            decl
2440        })
2441    }
2442
2443    fn extern_prelude_get_flag(
2444        &self,
2445        ident: IdentKey,
2446        orig_ident_span: Span,
2447        finalize: bool,
2448    ) -> Option<Decl<'ra>> {
2449        let entry = self.extern_prelude.get(&ident);
2450        entry.and_then(|entry| entry.flag_decl.as_ref()).and_then(|flag_decl| {
2451            let (pending_decl, finalized, is_open) = flag_decl.get();
2452            let decl = match pending_decl {
2453                PendingDecl::Ready(decl) => {
2454                    if finalize && !finalized && !is_open {
2455                        self.cstore_mut().process_path_extern(
2456                            self.tcx,
2457                            ident.name,
2458                            orig_ident_span,
2459                        );
2460                    }
2461                    decl
2462                }
2463                PendingDecl::Pending => {
2464                    if true {
    if !!finalized {
        ::core::panicking::panic("assertion failed: !finalized")
    };
};debug_assert!(!finalized);
2465                    if is_open {
2466                        let res = Res::OpenMod(ident.name);
2467                        Some(self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT))
2468                    } else {
2469                        let crate_id = if finalize {
2470                            self.cstore_mut().process_path_extern(
2471                                self.tcx,
2472                                ident.name,
2473                                orig_ident_span,
2474                            )
2475                        } else {
2476                            self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2477                        };
2478                        crate_id.map(|crate_id| {
2479                            let def_id = crate_id.as_def_id();
2480                            let res = Res::Def(DefKind::Mod, def_id);
2481                            self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT)
2482                        })
2483                    }
2484                }
2485            };
2486            flag_decl.set((PendingDecl::Ready(decl), finalize || finalized, is_open));
2487            decl.or_else(|| finalize.then_some(self.dummy_decl))
2488        })
2489    }
2490
2491    /// Rustdoc uses this to resolve doc link paths in a recoverable way. `PathResult<'a>`
2492    /// isn't something that can be returned because it can't be made to live that long,
2493    /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
2494    /// just that an error occurred.
2495    fn resolve_rustdoc_path(
2496        &self,
2497        path_str: &str,
2498        ns: Namespace,
2499        parent_scope: ParentScope<'ra>,
2500    ) -> Option<Res> {
2501        let segments: Result<Vec<_>, ()> = path_str
2502            .split("::")
2503            .enumerate()
2504            .map(|(i, s)| {
2505                let sym = if s.is_empty() {
2506                    if i == 0 {
2507                        // For a path like `::a::b`, use `kw::PathRoot` as the leading segment.
2508                        kw::PathRoot
2509                    } else {
2510                        return Err(()); // occurs in cases like `String::`
2511                    }
2512                } else {
2513                    Symbol::intern(s)
2514                };
2515                Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2516            })
2517            .collect();
2518        let Ok(segments) = segments else { return None };
2519
2520        match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2521            PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2522            PathResult::NonModule(path_res) => {
2523                path_res.full_res().filter(|res| !#[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Ctor(..), _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Ctor(..), _)))
2524            }
2525            PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2526                None
2527            }
2528            path_result @ (PathResult::Module(..) | PathResult::Indeterminate) => {
2529                ::rustc_middle::util::bug::bug_fmt(format_args!("got invalid path_result: {0:?}",
        path_result))bug!("got invalid path_result: {path_result:?}")
2530            }
2531        }
2532    }
2533
2534    /// Retrieves definition span of the given `DefId`.
2535    fn def_span(&self, def_id: DefId) -> Span {
2536        match def_id.as_local() {
2537            Some(def_id) => self.tcx.source_span(def_id),
2538            // Query `def_span` is not used because hashing its result span is expensive.
2539            None => self.cstore().def_span_untracked(self.tcx(), def_id),
2540        }
2541    }
2542
2543    fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2544        match def_id.as_local() {
2545            Some(def_id) => self.field_names.get(&def_id).cloned(),
2546            None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
    DefKind::Struct | DefKind::Union | DefKind::Variant => true,
    _ => false,
}matches!(
2547                self.tcx.def_kind(def_id),
2548                DefKind::Struct | DefKind::Union | DefKind::Variant
2549            ) =>
2550            {
2551                Some(
2552                    self.tcx
2553                        .associated_item_def_ids(def_id)
2554                        .iter()
2555                        .map(|&def_id| {
2556                            Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2557                        })
2558                        .collect(),
2559                )
2560            }
2561            _ => None,
2562        }
2563    }
2564
2565    fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2566        match def_id.as_local() {
2567            Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2568            None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
    DefKind::Struct | DefKind::Union | DefKind::Variant => true,
    _ => false,
}matches!(
2569                self.tcx.def_kind(def_id),
2570                DefKind::Struct | DefKind::Union | DefKind::Variant
2571            ) =>
2572            {
2573                Some(
2574                    self.tcx
2575                        .associated_item_def_ids(def_id)
2576                        .iter()
2577                        .filter_map(|&def_id| {
2578                            self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2579                        })
2580                        .collect(),
2581                )
2582            }
2583            _ => None,
2584        }
2585    }
2586
2587    /// Checks if an expression refers to a function marked with
2588    /// `#[rustc_legacy_const_generics]` and returns the argument index list
2589    /// from the attribute.
2590    fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2591        let ExprKind::Path(None, path) = &expr.kind else {
2592            return None;
2593        };
2594        // Don't perform legacy const generics rewriting if the path already
2595        // has generic arguments.
2596        if path.segments.last().unwrap().args.is_some() {
2597            return None;
2598        }
2599
2600        let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
2601
2602        // We only support cross-crate argument rewriting. Uses
2603        // within the same crate should be updated to use the new
2604        // const generics style.
2605        if def_id.is_local() {
2606            return None;
2607        }
2608
2609        {
    {
        'done:
            {
            for i in
                ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &self.tcx) {
                #[allow(unused_imports)]
                use ::rustc_hir::attrs::AttributeKind::*;
                let i: &::rustc_hir::Attribute = i;
                match i {
                    ::rustc_hir::Attribute::Parsed(RustcLegacyConstGenerics {
                        fn_indexes, .. }) => {
                        break 'done Some(fn_indexes);
                    }
                    ::rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(
2610            // we can use parsed attrs here since for other crates they're already available
2611            self.tcx, def_id,
2612            RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
2613        )
2614        .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
2615    }
2616
2617    fn resolve_main(&mut self) {
2618        let any_exe = self.tcx.crate_types().contains(&CrateType::Executable);
2619        // Don't try to resolve main unless it's an executable
2620        if !any_exe {
2621            return;
2622        }
2623
2624        let module = self.graph_root;
2625        let ident = Ident::with_dummy_span(sym::main);
2626        let parent_scope = &ParentScope::module(module, self.arenas);
2627
2628        let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2629            ModuleOrUniformRoot::Module(module.to_module()),
2630            ident,
2631            ValueNS,
2632            parent_scope,
2633            None,
2634        ) else {
2635            return;
2636        };
2637
2638        let res = name_binding.res();
2639        let is_import = name_binding.is_import();
2640        let span = name_binding.span;
2641        if let Res::Def(DefKind::Fn, _) = res {
2642            self.record_use(ident, name_binding, Used::Other);
2643        }
2644        self.main_def = Some(MainDefinition { res, is_import, span });
2645    }
2646}
2647
2648fn with_owner<'ra, 'tcx, R: AsMut<Resolver<'ra, 'tcx>>, T>(
2649    this: &mut R,
2650    owner: NodeId,
2651    work: impl FnOnce(&mut R) -> T,
2652) -> T {
2653    let tables = this.as_mut().owners.remove(&owner).unwrap();
2654    with_owner_tables(this, owner, tables, work)
2655}
2656
2657#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("with_owner_tables",
                                    "rustc_resolve", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2657u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("owner")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("owner");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("tables")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("tables");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&owner)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tables)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: T = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if true {
                if !!this.as_mut().owners.contains_key(&owner) {
                    ::core::panicking::panic("assertion failed: !this.as_mut().owners.contains_key(&owner)")
                };
            };
            let resolver = this.as_mut();
            let old_owner = mem::replace(&mut resolver.current_owner, tables);
            let ret = work(this);
            let resolver = this.as_mut();
            let overwritten =
                resolver.owners.insert(owner,
                    mem::replace(&mut resolver.current_owner, old_owner));
            if !overwritten.is_none() {
                ::core::panicking::panic("assertion failed: overwritten.is_none()")
            };
            ret
        }
    }
}#[instrument(level = "debug", skip(this, work))]
2658fn with_owner_tables<'ra, 'tcx, R: AsMut<Resolver<'ra, 'tcx>>, T>(
2659    this: &mut R,
2660    owner: NodeId,
2661    tables: PerOwnerResolverData<'tcx>,
2662    work: impl FnOnce(&mut R) -> T,
2663) -> T {
2664    debug_assert!(!this.as_mut().owners.contains_key(&owner));
2665    let resolver = this.as_mut();
2666    let old_owner = mem::replace(&mut resolver.current_owner, tables);
2667    let ret = work(this);
2668    let resolver = this.as_mut();
2669    let overwritten =
2670        resolver.owners.insert(owner, mem::replace(&mut resolver.current_owner, old_owner));
2671    assert!(overwritten.is_none());
2672    ret
2673}
2674
2675fn build_extern_prelude<'tcx, 'ra>(
2676    tcx: TyCtxt<'tcx>,
2677    attrs: &[ast::Attribute],
2678) -> FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> {
2679    let mut extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> = tcx
2680        .sess
2681        .opts
2682        .externs
2683        .iter()
2684        .filter_map(|(name, entry)| {
2685            // Make sure `self`, `super`, `_` etc do not get into extern prelude.
2686            // FIXME: reject `--extern self` and similar in option parsing instead.
2687            if entry.add_prelude
2688                && let sym = Symbol::intern(name)
2689                && sym.can_be_raw()
2690            {
2691                Some((IdentKey::with_root_ctxt(sym), ExternPreludeEntry::flag()))
2692            } else {
2693                None
2694            }
2695        })
2696        .collect();
2697
2698    // Add open base entries for namespaced crates whose base segment
2699    // is missing from the prelude (e.g. `foo::bar` without `foo`).
2700    // These are necessary in order to resolve the open modules, whereas
2701    // the namespaced names are necessary in `extern_prelude` for actually
2702    // resolving the namespaced crates.
2703    let missing_open_bases: Vec<IdentKey> = extern_prelude
2704        .keys()
2705        .filter_map(|ident| {
2706            let (base, _) = ident.name.as_str().split_once("::")?;
2707            let base_sym = Symbol::intern(base);
2708            base_sym.can_be_raw().then(|| IdentKey::with_root_ctxt(base_sym))
2709        })
2710        .filter(|base_ident| !extern_prelude.contains_key(base_ident))
2711        .collect();
2712
2713    extern_prelude.extend(
2714        missing_open_bases.into_iter().map(|ident| (ident, ExternPreludeEntry::open_flag())),
2715    );
2716
2717    // Inject `core` / `std` unless suppressed by attributes.
2718    if !attr::contains_name(attrs, sym::no_core) {
2719        extern_prelude.insert(IdentKey::with_root_ctxt(sym::core), ExternPreludeEntry::flag());
2720
2721        if !attr::contains_name(attrs, sym::no_std) {
2722            extern_prelude.insert(IdentKey::with_root_ctxt(sym::std), ExternPreludeEntry::flag());
2723        }
2724    }
2725
2726    extern_prelude
2727}
2728
2729fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2730    let mut result = String::new();
2731    for (i, name) in names.enumerate().filter(|(_, name)| *name != kw::PathRoot) {
2732        if i > 0 {
2733            result.push_str("::");
2734        }
2735        if Ident::with_dummy_span(name).is_raw_guess() {
2736            result.push_str("r#");
2737        }
2738        result.push_str(name.as_str());
2739    }
2740    result
2741}
2742
2743fn path_names_to_string(path: &Path) -> String {
2744    names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2745}
2746
2747/// A somewhat inefficient routine to obtain the name of a module.
2748fn module_to_string(mut module: Module<'_>) -> Option<String> {
2749    let mut names = Vec::new();
2750    while let Some(parent) = module.parent {
2751        names.push(module.name().unwrap_or(sym::opaque_module_name_placeholder));
2752        module = parent;
2753    }
2754    if names.is_empty() {
2755        return None;
2756    }
2757    Some(names_to_string(names.iter().rev().copied()))
2758}
2759
2760#[derive(#[automatically_derived]
impl ::core::marker::Copy for Stage { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Stage {
    #[inline]
    fn clone(&self) -> Stage { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Stage {
    #[inline]
    fn eq(&self, other: &Stage) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for Stage {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self { Stage::Early => "Early", Stage::Late => "Late", })
    }
}Debug)]
2761enum Stage {
2762    /// Resolving an import or a macro.
2763    /// Used when macro expansion is either not yet finished, or we are finalizing its results.
2764    /// Used by default as a more restrictive variant that can produce additional errors.
2765    Early,
2766    /// Resolving something in late resolution when all imports are resolved
2767    /// and all macros are expanded.
2768    Late,
2769}
2770
2771/// Parts of import data required for finalizing import resolution.
2772/// Does not carry a lifetime, so it can be stored in `Finalize`.
2773#[derive(#[automatically_derived]
impl ::core::marker::Copy for ImportSummary { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ImportSummary {
    #[inline]
    fn clone(&self) -> ImportSummary {
        let _: ::core::clone::AssertParamIsClone<Visibility>;
        let _: ::core::clone::AssertParamIsClone<LocalModId>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ImportSummary {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f, "ImportSummary",
            "vis", &self.vis, "nearest_parent_mod", &self.nearest_parent_mod,
            "is_single", &self.is_single, "priv_macro_use",
            &self.priv_macro_use, "span", &&self.span)
    }
}Debug)]
2774struct ImportSummary {
2775    vis: Visibility,
2776    nearest_parent_mod: LocalModId,
2777    is_single: bool,
2778    priv_macro_use: bool,
2779    span: Span,
2780}
2781
2782/// Invariant: if `Finalize` is used, expansion and import resolution must be complete.
2783#[derive(#[automatically_derived]
impl ::core::marker::Copy for Finalize { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Finalize {
    #[inline]
    fn clone(&self) -> Finalize {
        let _: ::core::clone::AssertParamIsClone<NodeId>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<Used>;
        let _: ::core::clone::AssertParamIsClone<Stage>;
        let _: ::core::clone::AssertParamIsClone<Option<ImportSummary>>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Finalize {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["node_id", "path_span", "root_span", "report_private", "used",
                        "stage", "import"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.node_id, &self.path_span, &self.root_span,
                        &self.report_private, &self.used, &self.stage,
                        &&self.import];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "Finalize",
            names, values)
    }
}Debug)]
2784struct Finalize {
2785    /// Node ID for linting.
2786    node_id: NodeId,
2787    /// Span of the whole path or some its characteristic fragment.
2788    /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths.
2789    path_span: Span,
2790    /// Span of the path start, suitable for prepending something to it.
2791    /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths.
2792    root_span: Span,
2793    /// Whether to report privacy errors or silently return "no resolution" for them,
2794    /// similarly to speculative resolution.
2795    report_private: bool = true,
2796    /// Tracks whether an item is used in scope or used relatively to a module.
2797    used: Used = Used::Other,
2798    /// Finalizing early or late resolution.
2799    stage: Stage = Stage::Early,
2800    /// Some import data, in case we are resolving an import's final segment.
2801    import: Option<ImportSummary> = None,
2802}
2803
2804impl Finalize {
2805    fn new(node_id: NodeId, path_span: Span) -> Finalize {
2806        Finalize::with_root_span(node_id, path_span, path_span)
2807    }
2808
2809    fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2810        Finalize { node_id, path_span, root_span, .. }
2811    }
2812}
2813
2814pub fn provide(providers: &mut Providers) {
2815    providers.registered_attr_tools = macros::registered_attr_tools;
2816    providers.registered_lint_tools = macros::registered_lint_tools;
2817}
2818
2819/// A wrapper around `&mut Resolver` that may be mutable or immutable, depending on a conditions.
2820///
2821/// `Cm` stands for "conditionally mutable".
2822///
2823/// Prefer constructing it through `Resolver::cm(_mut)` to ensure correctness.
2824type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;
2825
2826// FIXME: These are cells for caches that can be populated even during speculative resolution,
2827// and should be replaced with mutexes, atomics, or other synchronized data when migrating to
2828// parallel name resolution.
2829use std::cell::{Cell as CacheCell, RefCell as CacheRefCell};
2830
2831mod ref_mut {
2832    use std::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut};
2833    use std::fmt;
2834    use std::ops::Deref;
2835
2836    use crate::Resolver;
2837
2838    /// A reference type that conditionally allows mutable access.
2839    pub(crate) enum RefOrMut<'a, T> {
2840        Ref(&'a T),
2841        Mut(&'a mut T),
2842    }
2843
2844    impl<'a, T> Deref for RefOrMut<'a, T> {
2845        type Target = T;
2846
2847        fn deref(&self) -> &Self::Target {
2848            match self {
2849                RefOrMut::Ref(r) => r,
2850                RefOrMut::Mut(r) => r,
2851            }
2852        }
2853    }
2854
2855    impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2856        fn as_ref(&self) -> &T {
2857            &*self
2858        }
2859    }
2860
2861    impl<'a, T> RefOrMut<'a, T> {
2862        /// This is needed because the type may allow mutable access and is therefore not `Copy`.
2863        pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2864            match self {
2865                RefOrMut::Ref(r) => RefOrMut::Ref(r),
2866                RefOrMut::Mut(r) => RefOrMut::Mut(r),
2867            }
2868        }
2869
2870        /// Returns a mutable reference to the inner value if allowed.
2871        ///
2872        /// # Panics
2873        ///
2874        /// Panics if the wrapped reference is immutable.
2875        #[track_caller]
2876        pub(crate) fn get_mut(&mut self) -> &mut T {
2877            match self {
2878                RefOrMut::Ref(_) => {
    ::core::panicking::panic_fmt(format_args!("can\'t mutably borrow an immutable reference"));
}panic!("can't mutably borrow an immutable reference"),
2879                RefOrMut::Mut(r) => r,
2880            }
2881        }
2882    }
2883
2884    /// A wrapper around a [`Cell`] that only allows mutation based on a condition in the resolver.
2885    #[derive(#[automatically_derived]
impl<T: ::core::default::Default> ::core::default::Default for CmCell<T> {
    #[inline]
    fn default() -> CmCell<T> { CmCell(::core::default::Default::default()) }
}Default)]
2886    pub(crate) struct CmCell<T>(Cell<T>);
2887
2888    impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> {
2889        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2890            f.debug_tuple("CmCell").field(&self.get()).finish()
2891        }
2892    }
2893
2894    impl<T: Copy> Clone for CmCell<T> {
2895        fn clone(&self) -> CmCell<T> {
2896            CmCell::new(self.get())
2897        }
2898    }
2899
2900    impl<T: Copy> CmCell<T> {
2901        pub(crate) const fn get(&self) -> T {
2902            self.0.get()
2903        }
2904
2905        pub(crate) fn update<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>, f: impl FnOnce(T) -> T)
2906        where
2907            T: Copy,
2908        {
2909            let old = self.get();
2910            self.set(f(old), r);
2911        }
2912    }
2913
2914    impl<T> CmCell<T> {
2915        pub(crate) const fn new(value: T) -> CmCell<T> {
2916            CmCell(Cell::new(value))
2917        }
2918
2919        pub(crate) fn set<'ra, 'tcx>(&self, val: T, r: &Resolver<'ra, 'tcx>) {
2920            if r.assert_speculative {
2921                {
    ::core::panicking::panic_fmt(format_args!("not allowed to mutate a `CmCell` during speculative resolution"));
}panic!("not allowed to mutate a `CmCell` during speculative resolution")
2922            }
2923            self.0.set(val);
2924        }
2925
2926        pub(crate) fn into_inner(self) -> T {
2927            self.0.into_inner()
2928        }
2929    }
2930
2931    pub(crate) enum CmRef<'b, T> {
2932        /// A tracked borrow of a [`CmRefCell`]
2933        Tracked(Ref<'b, T>),
2934        /// An untracked or normal reference (not dynamically borrow-checked by `RefCell`)
2935        Untracked(&'b T),
2936    }
2937
2938    impl<'b, T> Deref for CmRef<'b, T> {
2939        type Target = T;
2940
2941        fn deref(&self) -> &Self::Target {
2942            match self {
2943                CmRef::Tracked(r) => r,
2944                CmRef::Untracked(r) => r,
2945            }
2946        }
2947    }
2948
2949    /// A wrapper around a [`RefCell`] that only allows writes (mutable borrows) based on a condition in the resolver.
2950    #[derive(#[automatically_derived]
impl<T: ::core::default::Default> ::core::default::Default for CmRefCell<T> {
    #[inline]
    fn default() -> CmRefCell<T> {
        CmRefCell(::core::default::Default::default())
    }
}Default)]
2951    pub(crate) struct CmRefCell<T>(RefCell<T>);
2952
2953    impl<T> CmRefCell<T> {
2954        pub(crate) fn new(value: T) -> CmRefCell<T> {
2955            CmRefCell(RefCell::new(value))
2956        }
2957
2958        #[track_caller]
2959        pub(crate) fn borrow_mut<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> RefMut<'_, T> {
2960            self.try_borrow_mut(r).unwrap()
2961        }
2962
2963        #[track_caller]
2964        pub(crate) fn try_borrow_mut<'ra, 'tcx>(
2965            &self,
2966            r: &Resolver<'ra, 'tcx>,
2967        ) -> Result<RefMut<'_, T>, BorrowMutError> {
2968            if r.assert_speculative {
2969                {
    ::core::panicking::panic_fmt(format_args!("not allowed to mutably borrow a `CmRefCell` during speculative resolution"));
};panic!("not allowed to mutably borrow a `CmRefCell` during speculative resolution");
2970            }
2971            self.0.try_borrow_mut()
2972        }
2973
2974        #[track_caller]
2975        pub(crate) fn borrow(&self) -> Ref<'_, T> {
2976            self.0.borrow()
2977        }
2978    }
2979
2980    impl<T: Default> CmRefCell<T> {
2981        pub(crate) fn take<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> T {
2982            if r.assert_speculative {
2983                {
    ::core::panicking::panic_fmt(format_args!("not allowed to mutate a CmRefCell during speculative resolution"));
};panic!("not allowed to mutate a CmRefCell during speculative resolution");
2984            }
2985            self.0.take()
2986        }
2987    }
2988}
2989
2990mod hygiene {
2991    use rustc_span::{ExpnId, SyntaxContext};
2992
2993    /// A newtype around `SyntaxContext` that can only keep contexts produced by
2994    /// [SyntaxContext::normalize_to_macros_2_0].
2995    #[derive(#[automatically_derived]
impl ::core::clone::Clone for Macros20NormalizedSyntaxContext {
    #[inline]
    fn clone(&self) -> Macros20NormalizedSyntaxContext {
        let _: ::core::clone::AssertParamIsClone<SyntaxContext>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Macros20NormalizedSyntaxContext { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for Macros20NormalizedSyntaxContext {
    #[inline]
    fn eq(&self, other: &Macros20NormalizedSyntaxContext) -> bool {
        self.0 == other.0
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Macros20NormalizedSyntaxContext {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<SyntaxContext>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for Macros20NormalizedSyntaxContext {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for Macros20NormalizedSyntaxContext {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f,
            "Macros20NormalizedSyntaxContext", &&self.0)
    }
}Debug)]
2996    pub(crate) struct Macros20NormalizedSyntaxContext(SyntaxContext);
2997
2998    impl Macros20NormalizedSyntaxContext {
2999        #[inline]
3000        pub(crate) fn new(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
3001            Macros20NormalizedSyntaxContext(ctxt.normalize_to_macros_2_0())
3002        }
3003
3004        #[inline]
3005        pub(crate) fn new_adjusted(
3006            mut ctxt: SyntaxContext,
3007            expn_id: ExpnId,
3008        ) -> (Macros20NormalizedSyntaxContext, Option<ExpnId>) {
3009            let def = ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
3010            (Macros20NormalizedSyntaxContext(ctxt), def)
3011        }
3012
3013        #[inline]
3014        pub(crate) fn new_unchecked(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
3015            if true {
    {
        match (&ctxt, &ctxt.normalize_to_macros_2_0()) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(ctxt, ctxt.normalize_to_macros_2_0());
3016            Macros20NormalizedSyntaxContext(ctxt)
3017        }
3018
3019        /// The passed closure must preserve the context's normalized-ness.
3020        #[inline]
3021        pub(crate) fn update_unchecked<R>(&mut self, f: impl FnOnce(&mut SyntaxContext) -> R) -> R {
3022            let ret = f(&mut self.0);
3023            if true {
    {
        match (&self.0, &self.0.normalize_to_macros_2_0()) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(self.0, self.0.normalize_to_macros_2_0());
3024            ret
3025        }
3026    }
3027
3028    impl std::ops::Deref for Macros20NormalizedSyntaxContext {
3029        type Target = SyntaxContext;
3030        fn deref(&self) -> &Self::Target {
3031            &self.0
3032        }
3033    }
3034}