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