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