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