Skip to main content

rustc_resolve/
lib.rs

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