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

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