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