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