Skip to main content

rustc_resolve/
lib.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: T = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if true {
                if !!this.as_mut().owners.contains_key(&owner) {
                    ::core::panicking::panic("assertion failed: !this.as_mut().owners.contains_key(&owner)")
                };
            };
            let resolver = this.as_mut();
            let old_owner = mem::replace(&mut resolver.current_owner, tables);
            let ret = work(this);
            let resolver = this.as_mut();
            let overwritten =
                resolver.owners.insert(owner,
                    mem::replace(&mut resolver.current_owner, old_owner));
            if !overwritten.is_none() {
                ::core::panicking::panic("assertion failed: overwritten.is_none()")
            };
            ret
        }
    }
}#[instrument(level = "debug", skip(this, work))]
2654fn with_owner_tables<'ra, 'tcx, R: AsMut<Resolver<'ra, 'tcx>>, T>(
2655    this: &mut R,
2656    owner: NodeId,
2657    tables: PerOwnerResolverData<'tcx>,
2658    work: impl FnOnce(&mut R) -> T,
2659) -> T {
2660    debug_assert!(!this.as_mut().owners.contains_key(&owner));
2661    let resolver = this.as_mut();
2662    let old_owner = mem::replace(&mut resolver.current_owner, tables);
2663    let ret = work(this);
2664    let resolver = this.as_mut();
2665    let overwritten =
2666        resolver.owners.insert(owner, mem::replace(&mut resolver.current_owner, old_owner));
2667    assert!(overwritten.is_none());
2668    ret
2669}
2670
2671fn build_extern_prelude<'tcx, 'ra>(
2672    tcx: TyCtxt<'tcx>,
2673    attrs: &[ast::Attribute],
2674) -> FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> {
2675    let mut extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> = tcx
2676        .sess
2677        .opts
2678        .externs
2679        .iter()
2680        .filter_map(|(name, entry)| {
2681            // Make sure `self`, `super`, `_` etc do not get into extern prelude.
2682            // FIXME: reject `--extern self` and similar in option parsing instead.
2683            if entry.add_prelude
2684                && let sym = Symbol::intern(name)
2685                && sym.can_be_raw()
2686            {
2687                Some((IdentKey::with_root_ctxt(sym), ExternPreludeEntry::flag()))
2688            } else {
2689                None
2690            }
2691        })
2692        .collect();
2693
2694    // Add open base entries for namespaced crates whose base segment
2695    // is missing from the prelude (e.g. `foo::bar` without `foo`).
2696    // These are necessary in order to resolve the open modules, whereas
2697    // the namespaced names are necessary in `extern_prelude` for actually
2698    // resolving the namespaced crates.
2699    let missing_open_bases: Vec<IdentKey> = extern_prelude
2700        .keys()
2701        .filter_map(|ident| {
2702            let (base, _) = ident.name.as_str().split_once("::")?;
2703            let base_sym = Symbol::intern(base);
2704            base_sym.can_be_raw().then(|| IdentKey::with_root_ctxt(base_sym))
2705        })
2706        .filter(|base_ident| !extern_prelude.contains_key(base_ident))
2707        .collect();
2708
2709    extern_prelude.extend(
2710        missing_open_bases.into_iter().map(|ident| (ident, ExternPreludeEntry::open_flag())),
2711    );
2712
2713    // Inject `core` / `std` unless suppressed by attributes.
2714    if !attr::contains_name(attrs, sym::no_core) {
2715        extern_prelude.insert(IdentKey::with_root_ctxt(sym::core), ExternPreludeEntry::flag());
2716
2717        if !attr::contains_name(attrs, sym::no_std) {
2718            extern_prelude.insert(IdentKey::with_root_ctxt(sym::std), ExternPreludeEntry::flag());
2719        }
2720    }
2721
2722    extern_prelude
2723}
2724
2725fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2726    let mut result = String::new();
2727    for (i, name) in names.enumerate().filter(|(_, name)| *name != kw::PathRoot) {
2728        if i > 0 {
2729            result.push_str("::");
2730        }
2731        if Ident::with_dummy_span(name).is_raw_guess() {
2732            result.push_str("r#");
2733        }
2734        result.push_str(name.as_str());
2735    }
2736    result
2737}
2738
2739fn path_names_to_string(path: &Path) -> String {
2740    names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2741}
2742
2743/// A somewhat inefficient routine to obtain the name of a module.
2744fn module_to_string(mut module: Module<'_>) -> Option<String> {
2745    let mut names = Vec::new();
2746    while let Some(parent) = module.parent {
2747        names.push(module.name().unwrap_or(sym::opaque_module_name_placeholder));
2748        module = parent;
2749    }
2750    if names.is_empty() {
2751        return None;
2752    }
2753    Some(names_to_string(names.iter().rev().copied()))
2754}
2755
2756#[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)]
2757enum Stage {
2758    /// Resolving an import or a macro.
2759    /// Used when macro expansion is either not yet finished, or we are finalizing its results.
2760    /// Used by default as a more restrictive variant that can produce additional errors.
2761    Early,
2762    /// Resolving something in late resolution when all imports are resolved
2763    /// and all macros are expanded.
2764    Late,
2765}
2766
2767/// Parts of import data required for finalizing import resolution.
2768/// Does not carry a lifetime, so it can be stored in `Finalize`.
2769#[derive(#[automatically_derived]
impl ::core::marker::Copy for ImportSummary { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ImportSummary {
    #[inline]
    fn clone(&self) -> ImportSummary {
        let _: ::core::clone::AssertParamIsClone<Visibility>;
        let _: ::core::clone::AssertParamIsClone<LocalDefId>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ImportSummary {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f, "ImportSummary",
            "vis", &self.vis, "nearest_parent_mod", &self.nearest_parent_mod,
            "is_single", &self.is_single, "priv_macro_use",
            &self.priv_macro_use, "span", &&self.span)
    }
}Debug)]
2770struct ImportSummary {
2771    vis: Visibility,
2772    nearest_parent_mod: LocalDefId,
2773    is_single: bool,
2774    priv_macro_use: bool,
2775    span: Span,
2776}
2777
2778/// Invariant: if `Finalize` is used, expansion and import resolution must be complete.
2779#[derive(#[automatically_derived]
impl ::core::marker::Copy for Finalize { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Finalize {
    #[inline]
    fn clone(&self) -> Finalize {
        let _: ::core::clone::AssertParamIsClone<NodeId>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<Used>;
        let _: ::core::clone::AssertParamIsClone<Stage>;
        let _: ::core::clone::AssertParamIsClone<Option<ImportSummary>>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Finalize {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["node_id", "path_span", "root_span", "report_private", "used",
                        "stage", "import"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.node_id, &self.path_span, &self.root_span,
                        &self.report_private, &self.used, &self.stage,
                        &&self.import];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "Finalize",
            names, values)
    }
}Debug)]
2780struct Finalize {
2781    /// Node ID for linting.
2782    node_id: NodeId,
2783    /// Span of the whole path or some its characteristic fragment.
2784    /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths.
2785    path_span: Span,
2786    /// Span of the path start, suitable for prepending something to it.
2787    /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths.
2788    root_span: Span,
2789    /// Whether to report privacy errors or silently return "no resolution" for them,
2790    /// similarly to speculative resolution.
2791    report_private: bool = true,
2792    /// Tracks whether an item is used in scope or used relatively to a module.
2793    used: Used = Used::Other,
2794    /// Finalizing early or late resolution.
2795    stage: Stage = Stage::Early,
2796    /// Some import data, in case we are resolving an import's final segment.
2797    import: Option<ImportSummary> = None,
2798}
2799
2800impl Finalize {
2801    fn new(node_id: NodeId, path_span: Span) -> Finalize {
2802        Finalize::with_root_span(node_id, path_span, path_span)
2803    }
2804
2805    fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2806        Finalize { node_id, path_span, root_span, .. }
2807    }
2808}
2809
2810pub fn provide(providers: &mut Providers) {
2811    providers.registered_tools = macros::registered_tools;
2812}
2813
2814/// A wrapper around `&mut Resolver` that may be mutable or immutable, depending on a conditions.
2815///
2816/// `Cm` stands for "conditionally mutable".
2817///
2818/// Prefer constructing it through [`Resolver::cm`] to ensure correctness.
2819type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;
2820
2821// FIXME: These are cells for caches that can be populated even during speculative resolution,
2822// and should be replaced with mutexes, atomics, or other synchronized data when migrating to
2823// parallel name resolution.
2824use std::cell::{Cell as CacheCell, RefCell as CacheRefCell};
2825
2826// FIXME: `*_unchecked` methods in the module below should be eliminated in the process
2827// of migration to parallel name resolution.
2828mod ref_mut {
2829    use std::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut};
2830    use std::fmt;
2831    use std::ops::Deref;
2832
2833    use crate::Resolver;
2834
2835    /// A wrapper around a mutable reference that conditionally allows mutable access.
2836    pub(crate) struct RefOrMut<'a, T> {
2837        p: &'a mut T,
2838        mutable: bool,
2839    }
2840
2841    impl<'a, T> Deref for RefOrMut<'a, T> {
2842        type Target = T;
2843
2844        fn deref(&self) -> &Self::Target {
2845            self.p
2846        }
2847    }
2848
2849    impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2850        fn as_ref(&self) -> &T {
2851            self.p
2852        }
2853    }
2854
2855    impl<'a, T> RefOrMut<'a, T> {
2856        pub(crate) fn new(p: &'a mut T, mutable: bool) -> Self {
2857            RefOrMut { p, mutable }
2858        }
2859
2860        /// This is needed because this wraps a `&mut T` and is therefore not `Copy`.
2861        pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2862            RefOrMut { p: self.p, mutable: self.mutable }
2863        }
2864
2865        /// Returns a mutable reference to the inner value if allowed.
2866        ///
2867        /// # Panics
2868        /// Panics if the `mutable` flag is false.
2869        #[track_caller]
2870        pub(crate) fn get_mut(&mut self) -> &mut T {
2871            match self.mutable {
2872                false => {
    ::core::panicking::panic_fmt(format_args!("can\'t mutably borrow speculative resolver"));
}panic!("can't mutably borrow speculative resolver"),
2873                true => self.p,
2874            }
2875        }
2876    }
2877
2878    /// A wrapper around a [`Cell`] that only allows mutation based on a condition in the resolver.
2879    #[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)]
2880    pub(crate) struct CmCell<T>(Cell<T>);
2881
2882    impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> {
2883        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2884            f.debug_tuple("CmCell").field(&self.get()).finish()
2885        }
2886    }
2887
2888    impl<T: Copy> Clone for CmCell<T> {
2889        fn clone(&self) -> CmCell<T> {
2890            CmCell::new(self.get())
2891        }
2892    }
2893
2894    impl<T: Copy> CmCell<T> {
2895        pub(crate) const fn get(&self) -> T {
2896            self.0.get()
2897        }
2898
2899        pub(crate) fn update<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>, f: impl FnOnce(T) -> T)
2900        where
2901            T: Copy,
2902        {
2903            let old = self.get();
2904            self.set(f(old), r);
2905        }
2906    }
2907
2908    impl<T> CmCell<T> {
2909        pub(crate) const fn new(value: T) -> CmCell<T> {
2910            CmCell(Cell::new(value))
2911        }
2912
2913        pub(crate) fn set<'ra, 'tcx>(&self, val: T, r: &Resolver<'ra, 'tcx>) {
2914            if r.assert_speculative {
2915                {
    ::core::panicking::panic_fmt(format_args!("not allowed to mutate a `CmCell` during speculative resolution"));
}panic!("not allowed to mutate a `CmCell` during speculative resolution")
2916            }
2917            self.0.set(val);
2918        }
2919
2920        pub(crate) fn into_inner(self) -> T {
2921            self.0.into_inner()
2922        }
2923    }
2924
2925    /// A wrapper around a [`RefCell`] that only allows mutable borrows based on a condition in the resolver.
2926    #[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)]
2927    pub(crate) struct CmRefCell<T>(RefCell<T>);
2928
2929    impl<T> CmRefCell<T> {
2930        pub(crate) const fn new(value: T) -> CmRefCell<T> {
2931            CmRefCell(RefCell::new(value))
2932        }
2933
2934        #[track_caller]
2935        pub(crate) fn borrow_mut_unchecked(&self) -> RefMut<'_, T> {
2936            self.0.borrow_mut()
2937        }
2938
2939        #[track_caller]
2940        pub(crate) fn borrow_mut<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> RefMut<'_, T> {
2941            if r.assert_speculative {
2942                {
    ::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");
2943            }
2944            self.0.borrow_mut()
2945        }
2946
2947        pub(crate) fn try_borrow_mut_unchecked(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
2948            self.0.try_borrow_mut()
2949        }
2950
2951        #[track_caller]
2952        pub(crate) fn try_borrow_mut<'ra, 'tcx>(
2953            &self,
2954            r: &Resolver<'ra, 'tcx>,
2955        ) -> Result<RefMut<'_, T>, BorrowMutError> {
2956            if r.assert_speculative {
2957                {
    ::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");
2958            }
2959            self.0.try_borrow_mut()
2960        }
2961
2962        #[track_caller]
2963        pub(crate) fn borrow(&self) -> Ref<'_, T> {
2964            self.0.borrow()
2965        }
2966    }
2967
2968    impl<T: Default> CmRefCell<T> {
2969        pub(crate) fn take<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> T {
2970            if r.assert_speculative {
2971                {
    ::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");
2972            }
2973            self.0.take()
2974        }
2975    }
2976}
2977
2978mod hygiene {
2979    use rustc_span::{ExpnId, SyntaxContext};
2980
2981    /// A newtype around `SyntaxContext` that can only keep contexts produced by
2982    /// [SyntaxContext::normalize_to_macros_2_0].
2983    #[derive(#[automatically_derived]
impl ::core::clone::Clone for Macros20NormalizedSyntaxContext {
    #[inline]
    fn clone(&self) -> Macros20NormalizedSyntaxContext {
        let _: ::core::clone::AssertParamIsClone<SyntaxContext>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Macros20NormalizedSyntaxContext { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for Macros20NormalizedSyntaxContext {
    #[inline]
    fn eq(&self, other: &Macros20NormalizedSyntaxContext) -> bool {
        self.0 == other.0
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Macros20NormalizedSyntaxContext {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<SyntaxContext>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for Macros20NormalizedSyntaxContext {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for Macros20NormalizedSyntaxContext {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f,
            "Macros20NormalizedSyntaxContext", &&self.0)
    }
}Debug)]
2984    pub(crate) struct Macros20NormalizedSyntaxContext(SyntaxContext);
2985
2986    impl Macros20NormalizedSyntaxContext {
2987        #[inline]
2988        pub(crate) fn new(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
2989            Macros20NormalizedSyntaxContext(ctxt.normalize_to_macros_2_0())
2990        }
2991
2992        #[inline]
2993        pub(crate) fn new_adjusted(
2994            mut ctxt: SyntaxContext,
2995            expn_id: ExpnId,
2996        ) -> (Macros20NormalizedSyntaxContext, Option<ExpnId>) {
2997            let def = ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
2998            (Macros20NormalizedSyntaxContext(ctxt), def)
2999        }
3000
3001        #[inline]
3002        pub(crate) fn new_unchecked(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
3003            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());
3004            Macros20NormalizedSyntaxContext(ctxt)
3005        }
3006
3007        /// The passed closure must preserve the context's normalized-ness.
3008        #[inline]
3009        pub(crate) fn update_unchecked<R>(&mut self, f: impl FnOnce(&mut SyntaxContext) -> R) -> R {
3010            let ret = f(&mut self.0);
3011            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());
3012            ret
3013        }
3014    }
3015
3016    impl std::ops::Deref for Macros20NormalizedSyntaxContext {
3017        type Target = SyntaxContext;
3018        fn deref(&self) -> &Self::Target {
3019            &self.0
3020        }
3021    }
3022}