Skip to main content

rustc_resolve/
lib.rs

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