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