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

    #[allow(deprecated)]
    {
        {
            'done:
                {
                for i in self.tcx.get_all_attrs(def_id) {
                    #[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!(
2463            // we can use parsed attrs here since for other crates they're already available
2464            self.tcx, def_id,
2465            RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
2466        )
2467        .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
2468    }
2469
2470    fn resolve_main(&mut self) {
2471        let any_exe = self.tcx.crate_types().contains(&CrateType::Executable);
2472        // Don't try to resolve main unless it's an executable
2473        if !any_exe {
2474            return;
2475        }
2476
2477        let module = self.graph_root;
2478        let ident = Ident::with_dummy_span(sym::main);
2479        let parent_scope = &ParentScope::module(module, self.arenas);
2480
2481        let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2482            ModuleOrUniformRoot::Module(module),
2483            ident,
2484            ValueNS,
2485            parent_scope,
2486            None,
2487        ) else {
2488            return;
2489        };
2490
2491        let res = name_binding.res();
2492        let is_import = name_binding.is_import();
2493        let span = name_binding.span;
2494        if let Res::Def(DefKind::Fn, _) = res {
2495            self.record_use(ident, name_binding, Used::Other);
2496        }
2497        self.main_def = Some(MainDefinition { res, is_import, span });
2498    }
2499}
2500
2501fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2502    let mut result = String::new();
2503    for (i, name) in names.filter(|name| *name != kw::PathRoot).enumerate() {
2504        if i > 0 {
2505            result.push_str("::");
2506        }
2507        if Ident::with_dummy_span(name).is_raw_guess() {
2508            result.push_str("r#");
2509        }
2510        result.push_str(name.as_str());
2511    }
2512    result
2513}
2514
2515fn path_names_to_string(path: &Path) -> String {
2516    names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2517}
2518
2519/// A somewhat inefficient routine to obtain the name of a module.
2520fn module_to_string(mut module: Module<'_>) -> Option<String> {
2521    let mut names = Vec::new();
2522    loop {
2523        if let ModuleKind::Def(.., name) = module.kind {
2524            if let Some(parent) = module.parent {
2525                // `unwrap` is safe: the presence of a parent means it's not the crate root.
2526                names.push(name.unwrap());
2527                module = parent
2528            } else {
2529                break;
2530            }
2531        } else {
2532            names.push(sym::opaque_module_name_placeholder);
2533            let Some(parent) = module.parent else {
2534                return None;
2535            };
2536            module = parent;
2537        }
2538    }
2539    if names.is_empty() {
2540        return None;
2541    }
2542    Some(names_to_string(names.iter().rev().copied()))
2543}
2544
2545#[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)]
2546enum Stage {
2547    /// Resolving an import or a macro.
2548    /// Used when macro expansion is either not yet finished, or we are finalizing its results.
2549    /// Used by default as a more restrictive variant that can produce additional errors.
2550    Early,
2551    /// Resolving something in late resolution when all imports are resolved
2552    /// and all macros are expanded.
2553    Late,
2554}
2555
2556/// Invariant: if `Finalize` is used, expansion and import resolution must be complete.
2557#[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)]
2558struct Finalize {
2559    /// Node ID for linting.
2560    node_id: NodeId,
2561    /// Span of the whole path or some its characteristic fragment.
2562    /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths.
2563    path_span: Span,
2564    /// Span of the path start, suitable for prepending something to it.
2565    /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths.
2566    root_span: Span,
2567    /// Whether to report privacy errors or silently return "no resolution" for them,
2568    /// similarly to speculative resolution.
2569    report_private: bool = true,
2570    /// Tracks whether an item is used in scope or used relatively to a module.
2571    used: Used = Used::Other,
2572    /// Finalizing early or late resolution.
2573    stage: Stage = Stage::Early,
2574    /// Nominal visibility of the import item, in case we are resolving an import's final segment.
2575    import_vis: Option<Visibility> = None,
2576}
2577
2578impl Finalize {
2579    fn new(node_id: NodeId, path_span: Span) -> Finalize {
2580        Finalize::with_root_span(node_id, path_span, path_span)
2581    }
2582
2583    fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2584        Finalize { node_id, path_span, root_span, .. }
2585    }
2586}
2587
2588pub fn provide(providers: &mut Providers) {
2589    providers.registered_tools = macros::registered_tools;
2590}
2591
2592/// A wrapper around `&mut Resolver` that may be mutable or immutable, depending on a conditions.
2593///
2594/// `Cm` stands for "conditionally mutable".
2595///
2596/// Prefer constructing it through [`Resolver::cm`] to ensure correctness.
2597type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;
2598
2599// FIXME: These are cells for caches that can be populated even during speculative resolution,
2600// and should be replaced with mutexes, atomics, or other synchronized data when migrating to
2601// parallel name resolution.
2602use std::cell::{Cell as CacheCell, RefCell as CacheRefCell};
2603
2604// FIXME: `*_unchecked` methods in the module below should be eliminated in the process
2605// of migration to parallel name resolution.
2606mod ref_mut {
2607    use std::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut};
2608    use std::fmt;
2609    use std::ops::Deref;
2610
2611    use crate::Resolver;
2612
2613    /// A wrapper around a mutable reference that conditionally allows mutable access.
2614    pub(crate) struct RefOrMut<'a, T> {
2615        p: &'a mut T,
2616        mutable: bool,
2617    }
2618
2619    impl<'a, T> Deref for RefOrMut<'a, T> {
2620        type Target = T;
2621
2622        fn deref(&self) -> &Self::Target {
2623            self.p
2624        }
2625    }
2626
2627    impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2628        fn as_ref(&self) -> &T {
2629            self.p
2630        }
2631    }
2632
2633    impl<'a, T> RefOrMut<'a, T> {
2634        pub(crate) fn new(p: &'a mut T, mutable: bool) -> Self {
2635            RefOrMut { p, mutable }
2636        }
2637
2638        /// This is needed because this wraps a `&mut T` and is therefore not `Copy`.
2639        pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2640            RefOrMut { p: self.p, mutable: self.mutable }
2641        }
2642
2643        /// Returns a mutable reference to the inner value if allowed.
2644        ///
2645        /// # Panics
2646        /// Panics if the `mutable` flag is false.
2647        #[track_caller]
2648        pub(crate) fn get_mut(&mut self) -> &mut T {
2649            match self.mutable {
2650                false => {
    ::core::panicking::panic_fmt(format_args!("Can\'t mutably borrow speculative resolver"));
}panic!("Can't mutably borrow speculative resolver"),
2651                true => self.p,
2652            }
2653        }
2654
2655        /// Returns a mutable reference to the inner value without checking if
2656        /// it's in a mutable state.
2657        pub(crate) fn get_mut_unchecked(&mut self) -> &mut T {
2658            self.p
2659        }
2660    }
2661
2662    /// A wrapper around a [`Cell`] that only allows mutation based on a condition in the resolver.
2663    #[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)]
2664    pub(crate) struct CmCell<T>(Cell<T>);
2665
2666    impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> {
2667        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2668            f.debug_tuple("CmCell").field(&self.get()).finish()
2669        }
2670    }
2671
2672    impl<T: Copy> Clone for CmCell<T> {
2673        fn clone(&self) -> CmCell<T> {
2674            CmCell::new(self.get())
2675        }
2676    }
2677
2678    impl<T: Copy> CmCell<T> {
2679        pub(crate) const fn get(&self) -> T {
2680            self.0.get()
2681        }
2682
2683        pub(crate) fn update_unchecked(&self, f: impl FnOnce(T) -> T)
2684        where
2685            T: Copy,
2686        {
2687            let old = self.get();
2688            self.set_unchecked(f(old));
2689        }
2690    }
2691
2692    impl<T> CmCell<T> {
2693        pub(crate) const fn new(value: T) -> CmCell<T> {
2694            CmCell(Cell::new(value))
2695        }
2696
2697        pub(crate) fn set_unchecked(&self, val: T) {
2698            self.0.set(val);
2699        }
2700
2701        pub(crate) fn into_inner(self) -> T {
2702            self.0.into_inner()
2703        }
2704    }
2705
2706    /// A wrapper around a [`RefCell`] that only allows mutable borrows based on a condition in the resolver.
2707    #[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)]
2708    pub(crate) struct CmRefCell<T>(RefCell<T>);
2709
2710    impl<T> CmRefCell<T> {
2711        pub(crate) const fn new(value: T) -> CmRefCell<T> {
2712            CmRefCell(RefCell::new(value))
2713        }
2714
2715        #[track_caller]
2716        pub(crate) fn borrow_mut_unchecked(&self) -> RefMut<'_, T> {
2717            self.0.borrow_mut()
2718        }
2719
2720        #[track_caller]
2721        pub(crate) fn borrow_mut<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> RefMut<'_, T> {
2722            if r.assert_speculative {
2723                {
    ::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");
2724            }
2725            self.borrow_mut_unchecked()
2726        }
2727
2728        #[track_caller]
2729        pub(crate) fn try_borrow_mut_unchecked(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
2730            self.0.try_borrow_mut()
2731        }
2732
2733        #[track_caller]
2734        pub(crate) fn borrow(&self) -> Ref<'_, T> {
2735            self.0.borrow()
2736        }
2737    }
2738
2739    impl<T: Default> CmRefCell<T> {
2740        pub(crate) fn take<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> T {
2741            if r.assert_speculative {
2742                {
    ::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");
2743            }
2744            self.0.take()
2745        }
2746    }
2747}
2748
2749mod hygiene {
2750    use rustc_span::{ExpnId, SyntaxContext};
2751
2752    /// A newtype around `SyntaxContext` that can only keep contexts produced by
2753    /// [SyntaxContext::normalize_to_macros_2_0].
2754    #[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_receiver_is_total_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)]
2755    pub(crate) struct Macros20NormalizedSyntaxContext(SyntaxContext);
2756
2757    impl Macros20NormalizedSyntaxContext {
2758        #[inline]
2759        pub(crate) fn new(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
2760            Macros20NormalizedSyntaxContext(ctxt.normalize_to_macros_2_0())
2761        }
2762
2763        #[inline]
2764        pub(crate) fn new_adjusted(
2765            mut ctxt: SyntaxContext,
2766            expn_id: ExpnId,
2767        ) -> (Macros20NormalizedSyntaxContext, Option<ExpnId>) {
2768            let def = ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
2769            (Macros20NormalizedSyntaxContext(ctxt), def)
2770        }
2771
2772        #[inline]
2773        pub(crate) fn new_unchecked(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
2774            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());
2775            Macros20NormalizedSyntaxContext(ctxt)
2776        }
2777
2778        /// The passed closure must preserve the context's normalized-ness.
2779        #[inline]
2780        pub(crate) fn update_unchecked<R>(&mut self, f: impl FnOnce(&mut SyntaxContext) -> R) -> R {
2781            let ret = f(&mut self.0);
2782            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());
2783            ret
2784        }
2785    }
2786
2787    impl std::ops::Deref for Macros20NormalizedSyntaxContext {
2788        type Target = SyntaxContext;
2789        fn deref(&self) -> &Self::Target {
2790            &self.0
2791        }
2792    }
2793}