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, _) => {
1465                let expn_id = expn_id.as_local().unwrap_or(LocalExpnId::ROOT);
1466                Some(self.new_def_decl(Res::Def(def_kind, def_id), vis, span, expn_id, parent))
1467            }
1468            ModuleKind::Block => None,
1469        };
1470        Module(Interned::new_unchecked(self.modules.alloc(ModuleData::new(
1471            parent,
1472            kind,
1473            expn_id,
1474            span,
1475            no_implicit_prelude,
1476            self_decl,
1477        ))))
1478    }
1479    fn alloc_decl(&'ra self, data: DeclData<'ra>) -> Decl<'ra> {
1480        Interned::new_unchecked(self.dropless.alloc(data))
1481    }
1482    fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1483        Interned::new_unchecked(self.imports.alloc(import))
1484    }
1485    fn alloc_name_resolution(
1486        &'ra self,
1487        orig_ident_span: Span,
1488    ) -> &'ra CmRefCell<NameResolution<'ra>> {
1489        self.name_resolutions.alloc(CmRefCell::new(NameResolution::new(orig_ident_span)))
1490    }
1491    fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1492        self.dropless.alloc(CacheCell::new(scope))
1493    }
1494    fn alloc_macro_rules_decl(&'ra self, decl: MacroRulesDecl<'ra>) -> &'ra MacroRulesDecl<'ra> {
1495        self.dropless.alloc(decl)
1496    }
1497    fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1498        self.ast_paths.alloc_from_iter(paths.iter().cloned())
1499    }
1500    fn alloc_macro(&'ra self, macro_data: MacroData) -> &'ra MacroData {
1501        self.macros.alloc(macro_data)
1502    }
1503    fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1504        self.dropless.alloc_from_iter(spans)
1505    }
1506}
1507
1508impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1509    fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1510        self
1511    }
1512}
1513
1514impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1515    fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1516        self
1517    }
1518}
1519
1520impl<'tcx> Resolver<'_, 'tcx> {
1521    fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1522        self.opt_feed(node).map(|f| f.key())
1523    }
1524
1525    fn local_def_id(&self, node: NodeId) -> LocalDefId {
1526        self.feed(node).key()
1527    }
1528
1529    fn opt_feed(&self, node: NodeId) -> Option<Feed<'tcx, LocalDefId>> {
1530        self.node_id_to_def_id.get(&node).copied()
1531    }
1532
1533    fn feed(&self, node: NodeId) -> Feed<'tcx, LocalDefId> {
1534        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:?}`"))
1535    }
1536
1537    fn local_def_kind(&self, node: NodeId) -> DefKind {
1538        self.tcx.def_kind(self.local_def_id(node))
1539    }
1540
1541    /// Adds a definition with a parent definition.
1542    fn create_def(
1543        &mut self,
1544        parent: LocalDefId,
1545        node_id: ast::NodeId,
1546        name: Option<Symbol>,
1547        def_kind: DefKind,
1548        expn_id: ExpnId,
1549        span: Span,
1550    ) -> TyCtxtFeed<'tcx, LocalDefId> {
1551        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!(
1552            !self.node_id_to_def_id.contains_key(&node_id),
1553            "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1554            node_id,
1555            name,
1556            def_kind,
1557            self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id].key()),
1558        );
1559
1560        // FIXME: remove `def_span` body, pass in the right spans here and call `tcx.at().create_def()`
1561        let feed = self.tcx.create_def(parent, name, def_kind, None, &mut self.disambiguator);
1562        let def_id = feed.def_id();
1563
1564        // Create the definition.
1565        if expn_id != ExpnId::root() {
1566            self.expn_that_defined.insert(def_id, expn_id);
1567        }
1568
1569        // A relative span's parent must be an absolute span.
1570        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);
1571        let _id = self.tcx.untracked().source_span.push(span);
1572        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);
1573
1574        // Some things for which we allocate `LocalDefId`s don't correspond to
1575        // anything in the AST, so they don't have a `NodeId`. For these cases
1576        // we don't need a mapping from `NodeId` to `LocalDefId`.
1577        if node_id != ast::DUMMY_NODE_ID {
1578            {
    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:1578",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1578u32),
                        ::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);
1579            self.node_id_to_def_id.insert(node_id, feed.downgrade());
1580        }
1581
1582        feed
1583    }
1584
1585    fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1586        if let Some(def_id) = def_id.as_local() {
1587            self.item_generics_num_lifetimes[&def_id]
1588        } else {
1589            self.tcx.generics_of(def_id).own_counts().lifetimes
1590        }
1591    }
1592
1593    fn item_required_generic_args_suggestion(&self, def_id: DefId) -> String {
1594        if let Some(def_id) = def_id.as_local() {
1595            self.item_required_generic_args_suggestions.get(&def_id).cloned().unwrap_or_default()
1596        } else {
1597            let required = self
1598                .tcx
1599                .generics_of(def_id)
1600                .own_params
1601                .iter()
1602                .filter_map(|param| match param.kind {
1603                    ty::GenericParamDefKind::Lifetime => Some("'_"),
1604                    ty::GenericParamDefKind::Type { has_default, .. }
1605                    | ty::GenericParamDefKind::Const { has_default } => {
1606                        if has_default {
1607                            None
1608                        } else {
1609                            Some("_")
1610                        }
1611                    }
1612                })
1613                .collect::<Vec<_>>();
1614
1615            if required.is_empty() { String::new() } else { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>", required.join(", ")))
    })format!("<{}>", required.join(", ")) }
1616        }
1617    }
1618
1619    pub fn tcx(&self) -> TyCtxt<'tcx> {
1620        self.tcx
1621    }
1622
1623    /// This function is very slow, as it iterates over the entire
1624    /// [Resolver::node_id_to_def_id] map just to find the [NodeId]
1625    /// that corresponds to the given [LocalDefId]. Only use this in
1626    /// diagnostics code paths.
1627    fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1628        self.node_id_to_def_id
1629            .items()
1630            .filter(|(_, v)| v.key() == def_id)
1631            .map(|(k, _)| *k)
1632            .get_only()
1633            .unwrap()
1634    }
1635}
1636
1637impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1638    pub fn new(
1639        tcx: TyCtxt<'tcx>,
1640        attrs: &[ast::Attribute],
1641        crate_span: Span,
1642        current_crate_outer_attr_insert_span: Span,
1643        arenas: &'ra ResolverArenas<'ra>,
1644    ) -> Resolver<'ra, 'tcx> {
1645        let root_def_id = CRATE_DEF_ID.to_def_id();
1646        let graph_root = arenas.new_module(
1647            None,
1648            ModuleKind::Def(DefKind::Mod, root_def_id, None),
1649            Visibility::Public,
1650            ExpnId::root(),
1651            crate_span,
1652            attr::contains_name(attrs, sym::no_implicit_prelude),
1653        );
1654        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];
1655        let local_module_map = FxIndexMap::from_iter([(CRATE_DEF_ID, graph_root)]);
1656        let empty_module = arenas.new_module(
1657            None,
1658            ModuleKind::Def(DefKind::Mod, root_def_id, None),
1659            Visibility::Public,
1660            ExpnId::root(),
1661            DUMMY_SP,
1662            true,
1663        );
1664
1665        let mut node_id_to_def_id = NodeMap::default();
1666        let crate_feed = tcx.create_local_crate_def_id(crate_span);
1667
1668        crate_feed.def_kind(DefKind::Mod);
1669        let crate_feed = crate_feed.downgrade();
1670        node_id_to_def_id.insert(CRATE_NODE_ID, crate_feed);
1671
1672        let mut invocation_parents = FxHashMap::default();
1673        invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1674
1675        let extern_prelude = build_extern_prelude(tcx, attrs);
1676        let registered_tools = tcx.registered_tools(());
1677        let edition = tcx.sess.edition();
1678
1679        let mut resolver = Resolver {
1680            tcx,
1681
1682            // The outermost module has def ID 0; this is not reflected in the
1683            // AST.
1684            graph_root,
1685            assert_speculative: false, // Only set/cleared in Resolver::resolve_imports for now
1686            extern_prelude,
1687
1688            empty_module,
1689            local_modules,
1690            local_module_map,
1691            extern_module_map: Default::default(),
1692
1693            glob_map: Default::default(),
1694            maybe_unused_trait_imports: Default::default(),
1695
1696            arenas,
1697            dummy_decl: arenas.new_pub_def_decl(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1698            builtin_type_decls: PrimTy::ALL
1699                .iter()
1700                .map(|prim_ty| {
1701                    let res = Res::PrimTy(*prim_ty);
1702                    let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1703                    (prim_ty.name(), decl)
1704                })
1705                .collect(),
1706            builtin_attr_decls: BUILTIN_ATTRIBUTES
1707                .iter()
1708                .map(|builtin_attr| {
1709                    let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(builtin_attr.name));
1710                    let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1711                    (builtin_attr.name, decl)
1712                })
1713                .collect(),
1714            registered_tool_decls: registered_tools
1715                .iter()
1716                .map(|&ident| {
1717                    let res = Res::ToolMod;
1718                    let decl = arenas.new_pub_def_decl(res, ident.span, LocalExpnId::ROOT);
1719                    (IdentKey::new(ident), decl)
1720                })
1721                .collect(),
1722            registered_tools,
1723            macro_use_prelude: Default::default(),
1724            extern_macro_map: Default::default(),
1725            dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)),
1726            dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)),
1727            non_macro_attr: arenas
1728                .alloc_macro(MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition)))),
1729            unused_macros: Default::default(),
1730            unused_macro_rules: Default::default(),
1731            single_segment_macro_resolutions: Default::default(),
1732            multi_segment_macro_resolutions: Default::default(),
1733            lint_buffer: LintBuffer::default(),
1734            node_id_to_def_id,
1735            invocation_parents,
1736            trait_impls: Default::default(),
1737            confused_type_with_std_module: Default::default(),
1738            stripped_cfg_items: Default::default(),
1739            effective_visibilities: Default::default(),
1740            doc_link_resolutions: Default::default(),
1741            doc_link_traits_in_scope: Default::default(),
1742            current_crate_outer_attr_insert_span,
1743            ..
1744        };
1745
1746        let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
1747        resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1748        resolver.feed_visibility(crate_feed, Visibility::Public);
1749
1750        resolver
1751    }
1752
1753    fn new_local_module(
1754        &mut self,
1755        parent: Option<Module<'ra>>,
1756        kind: ModuleKind,
1757        expn_id: ExpnId,
1758        span: Span,
1759        no_implicit_prelude: bool,
1760    ) -> Module<'ra> {
1761        let vis =
1762            kind.opt_def_id().map_or(Visibility::Public, |def_id| self.tcx.visibility(def_id));
1763        let module = self.arenas.new_module(parent, kind, vis, expn_id, span, no_implicit_prelude);
1764        self.local_modules.push(module);
1765        if let Some(def_id) = module.opt_def_id() {
1766            self.local_module_map.insert(def_id.expect_local(), module);
1767        }
1768        module
1769    }
1770
1771    fn new_extern_module(
1772        &self,
1773        parent: Option<Module<'ra>>,
1774        kind: ModuleKind,
1775        expn_id: ExpnId,
1776        span: Span,
1777        no_implicit_prelude: bool,
1778    ) -> Module<'ra> {
1779        let vis =
1780            kind.opt_def_id().map_or(Visibility::Public, |def_id| self.tcx.visibility(def_id));
1781        let module = self.arenas.new_module(parent, kind, vis, expn_id, span, no_implicit_prelude);
1782        self.extern_module_map.borrow_mut().insert(module.def_id(), module);
1783        module
1784    }
1785
1786    fn new_local_macro(&mut self, def_id: LocalDefId, macro_data: MacroData) -> &'ra MacroData {
1787        let mac = self.arenas.alloc_macro(macro_data);
1788        self.local_macro_map.insert(def_id, mac);
1789        mac
1790    }
1791
1792    fn next_node_id(&mut self) -> NodeId {
1793        let start = self.next_node_id;
1794        let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1795        self.next_node_id = ast::NodeId::from_u32(next);
1796        start
1797    }
1798
1799    fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1800        let start = self.next_node_id;
1801        let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1802        self.next_node_id = ast::NodeId::from_usize(end);
1803        start..self.next_node_id
1804    }
1805
1806    pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1807        &mut self.lint_buffer
1808    }
1809
1810    pub fn arenas() -> ResolverArenas<'ra> {
1811        Default::default()
1812    }
1813
1814    fn feed_visibility(&mut self, feed: Feed<'tcx, LocalDefId>, vis: Visibility) {
1815        let feed = feed.upgrade(self.tcx);
1816        feed.visibility(vis.to_def_id());
1817        self.visibilities_for_hashing.push((feed.def_id(), vis));
1818    }
1819
1820    pub fn into_outputs(self) -> ResolverOutputs<'tcx> {
1821        let proc_macros = self.proc_macros;
1822        let expn_that_defined = self.expn_that_defined;
1823        let extern_crate_map = self.extern_crate_map;
1824        let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1825        let glob_map = self.glob_map;
1826        let main_def = self.main_def;
1827        let confused_type_with_std_module = self.confused_type_with_std_module;
1828        let effective_visibilities = self.effective_visibilities;
1829
1830        let stripped_cfg_items = self
1831            .stripped_cfg_items
1832            .into_iter()
1833            .filter_map(|item| {
1834                let parent_scope =
1835                    self.node_id_to_def_id.get(&item.parent_scope)?.key().to_def_id();
1836                Some(StrippedCfgItem { parent_scope, ident: item.ident, cfg: item.cfg })
1837            })
1838            .collect();
1839
1840        let global_ctxt = ResolverGlobalCtxt {
1841            expn_that_defined,
1842            visibilities_for_hashing: self.visibilities_for_hashing,
1843            effective_visibilities,
1844            extern_crate_map,
1845            module_children: self.module_children,
1846            ambig_module_children: self.ambig_module_children,
1847            glob_map,
1848            maybe_unused_trait_imports,
1849            main_def,
1850            trait_impls: self.trait_impls,
1851            proc_macros,
1852            confused_type_with_std_module,
1853            doc_link_resolutions: self.doc_link_resolutions,
1854            doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1855            all_macro_rules: self.all_macro_rules,
1856            stripped_cfg_items,
1857        };
1858        let ast_lowering = ty::ResolverAstLowering {
1859            partial_res_map: self.partial_res_map,
1860            import_res_map: self.import_res_map,
1861            label_res_map: self.label_res_map,
1862            lifetimes_res_map: self.lifetimes_res_map,
1863            extra_lifetime_params_map: self.extra_lifetime_params_map,
1864            next_node_id: self.next_node_id,
1865            node_id_to_def_id: self
1866                .node_id_to_def_id
1867                .into_items()
1868                .map(|(k, f)| (k, f.key()))
1869                .collect(),
1870            trait_map: self.trait_map,
1871            lifetime_elision_allowed: self.lifetime_elision_allowed,
1872            lint_buffer: Steal::new(self.lint_buffer),
1873            delegation_infos: self.delegation_infos,
1874        };
1875        ResolverOutputs { global_ctxt, ast_lowering }
1876    }
1877
1878    fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1879        CStore::from_tcx(self.tcx)
1880    }
1881
1882    fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
1883        CStore::from_tcx_mut(self.tcx)
1884    }
1885
1886    fn dummy_ext(&self, macro_kind: MacroKind) -> Arc<SyntaxExtension> {
1887        match macro_kind {
1888            MacroKind::Bang => Arc::clone(&self.dummy_ext_bang),
1889            MacroKind::Derive => Arc::clone(&self.dummy_ext_derive),
1890            MacroKind::Attr => Arc::clone(&self.non_macro_attr.ext),
1891        }
1892    }
1893
1894    /// Returns a conditionally mutable resolver.
1895    ///
1896    /// Currently only dependent on `assert_speculative`, if `assert_speculative` is false,
1897    /// the resolver will allow mutation; otherwise, it will be immutable.
1898    fn cm(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
1899        CmResolver::new(self, !self.assert_speculative)
1900    }
1901
1902    /// Runs the function on each namespace.
1903    fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1904        f(self, TypeNS);
1905        f(self, ValueNS);
1906        f(self, MacroNS);
1907    }
1908
1909    fn per_ns_cm<'r, F: FnMut(CmResolver<'_, 'ra, 'tcx>, Namespace)>(
1910        mut self: CmResolver<'r, 'ra, 'tcx>,
1911        mut f: F,
1912    ) {
1913        f(self.reborrow(), TypeNS);
1914        f(self.reborrow(), ValueNS);
1915        f(self, MacroNS);
1916    }
1917
1918    fn is_builtin_macro(&self, res: Res) -> bool {
1919        self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name.is_some())
1920    }
1921
1922    fn is_specific_builtin_macro(&self, res: Res, symbol: Symbol) -> bool {
1923        self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name == Some(symbol))
1924    }
1925
1926    fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1927        loop {
1928            match ctxt.outer_expn_data().macro_def_id {
1929                Some(def_id) => return def_id,
1930                None => ctxt.remove_mark(),
1931            };
1932        }
1933    }
1934
1935    /// Entry point to crate resolution.
1936    pub fn resolve_crate(&mut self, krate: &Crate) {
1937        self.tcx.sess.time("resolve_crate", || {
1938            self.tcx.sess.time("finalize_imports", || self.finalize_imports());
1939            let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
1940                EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
1941            });
1942            self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
1943            self.tcx
1944                .sess
1945                .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
1946            self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
1947            self.tcx.sess.time("resolve_main", || self.resolve_main());
1948            self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate));
1949            self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate));
1950            self.tcx
1951                .sess
1952                .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
1953        });
1954
1955        // Make sure we don't mutate the cstore from here on.
1956        self.tcx.untracked().cstore.freeze();
1957    }
1958
1959    fn traits_in_scope(
1960        &mut self,
1961        current_trait: Option<Module<'ra>>,
1962        parent_scope: &ParentScope<'ra>,
1963        sp: Span,
1964        assoc_item: Option<(Symbol, Namespace)>,
1965    ) -> &'tcx [TraitCandidate<'tcx>] {
1966        let mut found_traits = Vec::new();
1967
1968        if let Some(module) = current_trait {
1969            if self.trait_may_have_item(Some(module), assoc_item) {
1970                let def_id = module.def_id();
1971                found_traits.push(TraitCandidate {
1972                    def_id,
1973                    import_ids: &[],
1974                    lint_ambiguous: false,
1975                });
1976            }
1977        }
1978
1979        let scope_set = ScopeSet::All(TypeNS);
1980        let ctxt = Macros20NormalizedSyntaxContext::new(sp.ctxt());
1981        self.cm().visit_scopes(scope_set, parent_scope, ctxt, sp, None, |mut this, scope, _, _| {
1982            match scope {
1983                Scope::ModuleNonGlobs(module, _) => {
1984                    this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1985                }
1986                Scope::ModuleGlobs(..) => {
1987                    // Already handled in `ModuleNonGlobs` (but see #144993).
1988                }
1989                Scope::StdLibPrelude => {
1990                    if let Some(module) = this.prelude {
1991                        this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1992                    }
1993                }
1994                Scope::ExternPreludeItems
1995                | Scope::ExternPreludeFlags
1996                | Scope::ToolPrelude
1997                | Scope::BuiltinTypes => {}
1998                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1999            }
2000            ControlFlow::<()>::Continue(())
2001        });
2002
2003        self.tcx.hir_arena.alloc_slice(&found_traits)
2004    }
2005
2006    fn traits_in_module(
2007        &mut self,
2008        module: Module<'ra>,
2009        assoc_item: Option<(Symbol, Namespace)>,
2010        found_traits: &mut Vec<TraitCandidate<'tcx>>,
2011    ) {
2012        module.ensure_traits(self);
2013        let traits = module.traits.borrow();
2014        for &(trait_name, trait_binding, trait_module, lint_ambiguous) in
2015            traits.as_ref().unwrap().iter()
2016        {
2017            if self.trait_may_have_item(trait_module, assoc_item) {
2018                let def_id = trait_binding.res().def_id();
2019                let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name);
2020                found_traits.push(TraitCandidate { def_id, import_ids, lint_ambiguous });
2021            }
2022        }
2023    }
2024
2025    // List of traits in scope is pruned on best effort basis. We reject traits not having an
2026    // associated item with the given name and namespace (if specified). This is a conservative
2027    // optimization, proper hygienic type-based resolution of associated items is done in typeck.
2028    // We don't reject trait aliases (`trait_module == None`) because we don't have access to their
2029    // associated items.
2030    fn trait_may_have_item(
2031        &self,
2032        trait_module: Option<Module<'ra>>,
2033        assoc_item: Option<(Symbol, Namespace)>,
2034    ) -> bool {
2035        match (trait_module, assoc_item) {
2036            (Some(trait_module), Some((name, ns))) => self
2037                .resolutions(trait_module)
2038                .borrow()
2039                .iter()
2040                .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
2041            _ => true,
2042        }
2043    }
2044
2045    fn find_transitive_imports(
2046        &mut self,
2047        mut kind: &DeclKind<'_>,
2048        trait_name: Symbol,
2049    ) -> &'tcx [LocalDefId] {
2050        let mut import_ids: SmallVec<[LocalDefId; 1]> = ::smallvec::SmallVec::new()smallvec![];
2051        while let DeclKind::Import { import, source_decl, .. } = kind {
2052            if let Some(node_id) = import.id() {
2053                let def_id = self.local_def_id(node_id);
2054                self.maybe_unused_trait_imports.insert(def_id);
2055                import_ids.push(def_id);
2056            }
2057            self.add_to_glob_map(*import, trait_name);
2058            kind = &source_decl.kind;
2059        }
2060
2061        self.tcx.hir_arena.alloc_slice(&import_ids)
2062    }
2063
2064    fn resolutions(&self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
2065        if module.populate_on_access.get() {
2066            module.populate_on_access.set(false);
2067            self.build_reduced_graph_external(module);
2068        }
2069        &module.0.0.lazy_resolutions
2070    }
2071
2072    fn resolution(
2073        &self,
2074        module: Module<'ra>,
2075        key: BindingKey,
2076    ) -> Option<Ref<'ra, NameResolution<'ra>>> {
2077        self.resolutions(module).borrow().get(&key).map(|resolution| resolution.borrow())
2078    }
2079
2080    fn resolution_or_default(
2081        &self,
2082        module: Module<'ra>,
2083        key: BindingKey,
2084        orig_ident_span: Span,
2085    ) -> &'ra CmRefCell<NameResolution<'ra>> {
2086        self.resolutions(module)
2087            .borrow_mut_unchecked()
2088            .entry(key)
2089            .or_insert_with(|| self.arenas.alloc_name_resolution(orig_ident_span))
2090    }
2091
2092    /// Test if AmbiguityError ambi is any identical to any one inside ambiguity_errors
2093    fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
2094        for ambiguity_error in &self.ambiguity_errors {
2095            // if the span location and ident as well as its span are the same
2096            if ambiguity_error.kind == ambi.kind
2097                && ambiguity_error.ident == ambi.ident
2098                && ambiguity_error.ident.span == ambi.ident.span
2099                && ambiguity_error.b1.span == ambi.b1.span
2100                && ambiguity_error.b2.span == ambi.b2.span
2101            {
2102                return true;
2103            }
2104        }
2105        false
2106    }
2107
2108    fn record_use(&mut self, ident: Ident, used_decl: Decl<'ra>, used: Used) {
2109        self.record_use_inner(ident, used_decl, used, used_decl.warn_ambiguity.get());
2110    }
2111
2112    fn record_use_inner(
2113        &mut self,
2114        ident: Ident,
2115        used_decl: Decl<'ra>,
2116        used: Used,
2117        warn_ambiguity: bool,
2118    ) {
2119        if let Some(b2) = used_decl.ambiguity.get() {
2120            let ambiguity_error = AmbiguityError {
2121                kind: AmbiguityKind::GlobVsGlob,
2122                ambig_vis: None,
2123                ident,
2124                b1: used_decl,
2125                b2,
2126                scope1: Scope::ModuleGlobs(used_decl.parent_module.unwrap(), None),
2127                scope2: Scope::ModuleGlobs(b2.parent_module.unwrap(), None),
2128                warning: if warn_ambiguity { Some(AmbiguityWarning::GlobImport) } else { None },
2129            };
2130            if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2131                // avoid duplicated span information to be emit out
2132                self.ambiguity_errors.push(ambiguity_error);
2133            }
2134        }
2135        if let DeclKind::Import { import, source_decl } = used_decl.kind {
2136            if let ImportKind::MacroUse { warn_private: true } = import.kind {
2137                // Do not report the lint if the macro name resolves in stdlib prelude
2138                // even without the problematic `macro_use` import.
2139                let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2140                    let empty_module = self.empty_module;
2141                    let arenas = self.arenas;
2142                    self.cm()
2143                        .maybe_resolve_ident_in_module(
2144                            ModuleOrUniformRoot::Module(prelude),
2145                            ident,
2146                            MacroNS,
2147                            &ParentScope::module(empty_module, arenas),
2148                            None,
2149                        )
2150                        .is_ok()
2151                });
2152                if !found_in_stdlib_prelude {
2153                    self.lint_buffer().buffer_lint(
2154                        PRIVATE_MACRO_USE,
2155                        import.root_id,
2156                        ident.span,
2157                        errors::MacroIsPrivate { ident },
2158                    );
2159                }
2160            }
2161            // Avoid marking `extern crate` items that refer to a name from extern prelude,
2162            // but not introduce it, as used if they are accessed from lexical scope.
2163            if used == Used::Scope
2164                && let Some(entry) = self.extern_prelude.get(&IdentKey::new(ident))
2165                && let Some((item_decl, _, false)) = entry.item_decl
2166                && item_decl == used_decl
2167            {
2168                return;
2169            }
2170            let old_used = self.import_use_map.entry(import).or_insert(used);
2171            if *old_used < used {
2172                *old_used = used;
2173            }
2174            if let Some(id) = import.id() {
2175                self.used_imports.insert(id);
2176            }
2177            self.add_to_glob_map(import, ident.name);
2178            self.record_use_inner(
2179                ident,
2180                source_decl,
2181                Used::Other,
2182                warn_ambiguity || source_decl.warn_ambiguity.get(),
2183            );
2184        }
2185    }
2186
2187    #[inline]
2188    fn add_to_glob_map(&mut self, import: Import<'_>, name: Symbol) {
2189        if let ImportKind::Glob { id, .. } = import.kind {
2190            let def_id = self.local_def_id(id);
2191            self.glob_map.entry(def_id).or_default().insert(name);
2192        }
2193    }
2194
2195    fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2196        {
    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:2196",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2196u32),
                        ::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);
2197        let mut ctxt = ident.span.ctxt();
2198        let mark = if ident.name == kw::DollarCrate {
2199            // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
2200            // we don't want to pretend that the `macro_rules!` definition is in the `macro`
2201            // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks.
2202            // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
2203            // definitions actually produced by `macro` and `macro` definitions produced by
2204            // `macro_rules!`, but at least such configurations are not stable yet.
2205            ctxt = ctxt.normalize_to_macro_rules();
2206            {
    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:2206",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2206u32),
                        ::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!(
2207                "resolve_crate_root: marks={:?}",
2208                ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2209            );
2210            let mut iter = ctxt.marks().into_iter().rev().peekable();
2211            let mut result = None;
2212            // Find the last opaque mark from the end if it exists.
2213            while let Some(&(mark, transparency)) = iter.peek() {
2214                if transparency == Transparency::Opaque {
2215                    result = Some(mark);
2216                    iter.next();
2217                } else {
2218                    break;
2219                }
2220            }
2221            {
    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:2221",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2221u32),
                        ::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!(
2222                "resolve_crate_root: found opaque mark {:?} {:?}",
2223                result,
2224                result.map(|r| r.expn_data())
2225            );
2226            // Then find the last semi-opaque mark from the end if it exists.
2227            for (mark, transparency) in iter {
2228                if transparency == Transparency::SemiOpaque {
2229                    result = Some(mark);
2230                } else {
2231                    break;
2232                }
2233            }
2234            {
    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:2234",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2234u32),
                        ::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!(
2235                "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2236                result,
2237                result.map(|r| r.expn_data())
2238            );
2239            result
2240        } else {
2241            {
    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:2241",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2241u32),
                        ::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");
2242            ctxt = ctxt.normalize_to_macros_2_0();
2243            ctxt.adjust(ExpnId::root())
2244        };
2245        let module = match mark {
2246            Some(def) => self.expn_def_scope(def),
2247            None => {
2248                {
    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:2248",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2248u32),
                        ::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!(
2249                    "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2250                    ident, ident.span
2251                );
2252                return self.graph_root;
2253            }
2254        };
2255        let module = self.expect_module(
2256            module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2257        );
2258        {
    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:2258",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2258u32),
                        ::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!(
2259            "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2260            ident,
2261            module,
2262            module.kind.name(),
2263            ident.span
2264        );
2265        module
2266    }
2267
2268    fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2269        let mut module = self.expect_module(module.nearest_parent_mod());
2270        while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2271            let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2272            module = self.expect_module(parent.nearest_parent_mod());
2273        }
2274        module
2275    }
2276
2277    fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2278        {
    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:2278",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2278u32),
                        ::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);
2279        if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2280            {
    ::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)");
2281        }
2282    }
2283
2284    fn record_pat_span(&mut self, node: NodeId, span: Span) {
2285        {
    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:2285",
                        "rustc_resolve", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(2285u32),
                        ::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);
2286        self.pat_span_map.insert(node, span);
2287    }
2288
2289    fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
2290        vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2291    }
2292
2293    fn disambiguate_macro_rules_vs_modularized(
2294        &self,
2295        macro_rules: Decl<'ra>,
2296        modularized: Decl<'ra>,
2297    ) -> bool {
2298        // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules"
2299        // is disambiguated to mitigate regressions from macro modularization.
2300        // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
2301        //
2302        // Panic on unwrap should be impossible, the only name_bindings passed in should be from
2303        // `resolve_ident_in_scope_set` which will always refer to a local binding from an
2304        // import or macro definition.
2305        let macro_rules = macro_rules.parent_module.unwrap();
2306        let modularized = modularized.parent_module.unwrap();
2307        macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2308            && modularized.is_ancestor_of(macro_rules)
2309    }
2310
2311    fn extern_prelude_get_item<'r>(
2312        mut self: CmResolver<'r, 'ra, 'tcx>,
2313        ident: IdentKey,
2314        orig_ident_span: Span,
2315        finalize: bool,
2316    ) -> Option<Decl<'ra>> {
2317        let entry = self.extern_prelude.get(&ident);
2318        entry.and_then(|entry| entry.item_decl).map(|(decl, ..)| {
2319            if finalize {
2320                self.get_mut().record_use(ident.orig(orig_ident_span), decl, Used::Scope);
2321            }
2322            decl
2323        })
2324    }
2325
2326    fn extern_prelude_get_flag(
2327        &self,
2328        ident: IdentKey,
2329        orig_ident_span: Span,
2330        finalize: bool,
2331    ) -> Option<Decl<'ra>> {
2332        let entry = self.extern_prelude.get(&ident);
2333        entry.and_then(|entry| entry.flag_decl.as_ref()).and_then(|flag_decl| {
2334            let (pending_decl, finalized, is_open) = flag_decl.get();
2335            let decl = match pending_decl {
2336                PendingDecl::Ready(decl) => {
2337                    if finalize && !finalized && !is_open {
2338                        self.cstore_mut().process_path_extern(
2339                            self.tcx,
2340                            ident.name,
2341                            orig_ident_span,
2342                        );
2343                    }
2344                    decl
2345                }
2346                PendingDecl::Pending => {
2347                    if true {
    if !!finalized {
        ::core::panicking::panic("assertion failed: !finalized")
    };
};debug_assert!(!finalized);
2348                    if is_open {
2349                        let res = Res::OpenMod(ident.name);
2350                        Some(self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT))
2351                    } else {
2352                        let crate_id = if finalize {
2353                            self.cstore_mut().process_path_extern(
2354                                self.tcx,
2355                                ident.name,
2356                                orig_ident_span,
2357                            )
2358                        } else {
2359                            self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2360                        };
2361                        crate_id.map(|crate_id| {
2362                            let def_id = crate_id.as_def_id();
2363                            let res = Res::Def(DefKind::Mod, def_id);
2364                            self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT)
2365                        })
2366                    }
2367                }
2368            };
2369            flag_decl.set((PendingDecl::Ready(decl), finalize || finalized, is_open));
2370            decl.or_else(|| finalize.then_some(self.dummy_decl))
2371        })
2372    }
2373
2374    /// Rustdoc uses this to resolve doc link paths in a recoverable way. `PathResult<'a>`
2375    /// isn't something that can be returned because it can't be made to live that long,
2376    /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
2377    /// just that an error occurred.
2378    fn resolve_rustdoc_path(
2379        &mut self,
2380        path_str: &str,
2381        ns: Namespace,
2382        parent_scope: ParentScope<'ra>,
2383    ) -> Option<Res> {
2384        let segments: Result<Vec<_>, ()> = path_str
2385            .split("::")
2386            .enumerate()
2387            .map(|(i, s)| {
2388                let sym = if s.is_empty() {
2389                    if i == 0 {
2390                        // For a path like `::a::b`, use `kw::PathRoot` as the leading segment.
2391                        kw::PathRoot
2392                    } else {
2393                        return Err(()); // occurs in cases like `String::`
2394                    }
2395                } else {
2396                    Symbol::intern(s)
2397                };
2398                Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2399            })
2400            .collect();
2401        let Ok(segments) = segments else { return None };
2402
2403        match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2404            PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2405            PathResult::NonModule(path_res) => {
2406                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(..), _)))
2407            }
2408            PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2409                None
2410            }
2411            path_result @ (PathResult::Module(..) | PathResult::Indeterminate) => {
2412                ::rustc_middle::util::bug::bug_fmt(format_args!("got invalid path_result: {0:?}",
        path_result))bug!("got invalid path_result: {path_result:?}")
2413            }
2414        }
2415    }
2416
2417    /// Retrieves definition span of the given `DefId`.
2418    fn def_span(&self, def_id: DefId) -> Span {
2419        match def_id.as_local() {
2420            Some(def_id) => self.tcx.source_span(def_id),
2421            // Query `def_span` is not used because hashing its result span is expensive.
2422            None => self.cstore().def_span_untracked(self.tcx(), def_id),
2423        }
2424    }
2425
2426    fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2427        match def_id.as_local() {
2428            Some(def_id) => self.field_names.get(&def_id).cloned(),
2429            None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
    DefKind::Struct | DefKind::Union | DefKind::Variant => true,
    _ => false,
}matches!(
2430                self.tcx.def_kind(def_id),
2431                DefKind::Struct | DefKind::Union | DefKind::Variant
2432            ) =>
2433            {
2434                Some(
2435                    self.tcx
2436                        .associated_item_def_ids(def_id)
2437                        .iter()
2438                        .map(|&def_id| {
2439                            Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2440                        })
2441                        .collect(),
2442                )
2443            }
2444            _ => None,
2445        }
2446    }
2447
2448    fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2449        match def_id.as_local() {
2450            Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2451            None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
    DefKind::Struct | DefKind::Union | DefKind::Variant => true,
    _ => false,
}matches!(
2452                self.tcx.def_kind(def_id),
2453                DefKind::Struct | DefKind::Union | DefKind::Variant
2454            ) =>
2455            {
2456                Some(
2457                    self.tcx
2458                        .associated_item_def_ids(def_id)
2459                        .iter()
2460                        .filter_map(|&def_id| {
2461                            self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2462                        })
2463                        .collect(),
2464                )
2465            }
2466            _ => None,
2467        }
2468    }
2469
2470    /// Checks if an expression refers to a function marked with
2471    /// `#[rustc_legacy_const_generics]` and returns the argument index list
2472    /// from the attribute.
2473    fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2474        let ExprKind::Path(None, path) = &expr.kind else {
2475            return None;
2476        };
2477        // Don't perform legacy const generics rewriting if the path already
2478        // has generic arguments.
2479        if path.segments.last().unwrap().args.is_some() {
2480            return None;
2481        }
2482
2483        let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
2484
2485        // We only support cross-crate argument rewriting. Uses
2486        // within the same crate should be updated to use the new
2487        // const generics style.
2488        if def_id.is_local() {
2489            return None;
2490        }
2491
2492        {
    {
        '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!(
2493            // we can use parsed attrs here since for other crates they're already available
2494            self.tcx, def_id,
2495            RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
2496        )
2497        .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
2498    }
2499
2500    fn resolve_main(&mut self) {
2501        let any_exe = self.tcx.crate_types().contains(&CrateType::Executable);
2502        // Don't try to resolve main unless it's an executable
2503        if !any_exe {
2504            return;
2505        }
2506
2507        let module = self.graph_root;
2508        let ident = Ident::with_dummy_span(sym::main);
2509        let parent_scope = &ParentScope::module(module, self.arenas);
2510
2511        let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2512            ModuleOrUniformRoot::Module(module),
2513            ident,
2514            ValueNS,
2515            parent_scope,
2516            None,
2517        ) else {
2518            return;
2519        };
2520
2521        let res = name_binding.res();
2522        let is_import = name_binding.is_import();
2523        let span = name_binding.span;
2524        if let Res::Def(DefKind::Fn, _) = res {
2525            self.record_use(ident, name_binding, Used::Other);
2526        }
2527        self.main_def = Some(MainDefinition { res, is_import, span });
2528    }
2529}
2530
2531fn build_extern_prelude<'tcx, 'ra>(
2532    tcx: TyCtxt<'tcx>,
2533    attrs: &[ast::Attribute],
2534) -> FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> {
2535    let mut extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> = tcx
2536        .sess
2537        .opts
2538        .externs
2539        .iter()
2540        .filter_map(|(name, entry)| {
2541            // Make sure `self`, `super`, `_` etc do not get into extern prelude.
2542            // FIXME: reject `--extern self` and similar in option parsing instead.
2543            if entry.add_prelude
2544                && let sym = Symbol::intern(name)
2545                && sym.can_be_raw()
2546            {
2547                Some((IdentKey::with_root_ctxt(sym), ExternPreludeEntry::flag()))
2548            } else {
2549                None
2550            }
2551        })
2552        .collect();
2553
2554    // Add open base entries for namespaced crates whose base segment
2555    // is missing from the prelude (e.g. `foo::bar` without `foo`).
2556    // These are necessary in order to resolve the open modules, whereas
2557    // the namespaced names are necessary in `extern_prelude` for actually
2558    // resolving the namespaced crates.
2559    let missing_open_bases: Vec<IdentKey> = extern_prelude
2560        .keys()
2561        .filter_map(|ident| {
2562            let (base, _) = ident.name.as_str().split_once("::")?;
2563            let base_sym = Symbol::intern(base);
2564            base_sym.can_be_raw().then(|| IdentKey::with_root_ctxt(base_sym))
2565        })
2566        .filter(|base_ident| !extern_prelude.contains_key(base_ident))
2567        .collect();
2568
2569    extern_prelude.extend(
2570        missing_open_bases.into_iter().map(|ident| (ident, ExternPreludeEntry::open_flag())),
2571    );
2572
2573    // Inject `core` / `std` unless suppressed by attributes.
2574    if !attr::contains_name(attrs, sym::no_core) {
2575        extern_prelude.insert(IdentKey::with_root_ctxt(sym::core), ExternPreludeEntry::flag());
2576
2577        if !attr::contains_name(attrs, sym::no_std) {
2578            extern_prelude.insert(IdentKey::with_root_ctxt(sym::std), ExternPreludeEntry::flag());
2579        }
2580    }
2581
2582    extern_prelude
2583}
2584
2585fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2586    let mut result = String::new();
2587    for (i, name) in names.enumerate().filter(|(_, name)| *name != kw::PathRoot) {
2588        if i > 0 {
2589            result.push_str("::");
2590        }
2591        if Ident::with_dummy_span(name).is_raw_guess() {
2592            result.push_str("r#");
2593        }
2594        result.push_str(name.as_str());
2595    }
2596    result
2597}
2598
2599fn path_names_to_string(path: &Path) -> String {
2600    names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2601}
2602
2603/// A somewhat inefficient routine to obtain the name of a module.
2604fn module_to_string(mut module: Module<'_>) -> Option<String> {
2605    let mut names = Vec::new();
2606    loop {
2607        if let ModuleKind::Def(.., name) = module.kind {
2608            if let Some(parent) = module.parent {
2609                // `unwrap` is safe: the presence of a parent means it's not the crate root.
2610                names.push(name.unwrap());
2611                module = parent
2612            } else {
2613                break;
2614            }
2615        } else {
2616            names.push(sym::opaque_module_name_placeholder);
2617            let Some(parent) = module.parent else {
2618                return None;
2619            };
2620            module = parent;
2621        }
2622    }
2623    if names.is_empty() {
2624        return None;
2625    }
2626    Some(names_to_string(names.iter().rev().copied()))
2627}
2628
2629#[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)]
2630enum Stage {
2631    /// Resolving an import or a macro.
2632    /// Used when macro expansion is either not yet finished, or we are finalizing its results.
2633    /// Used by default as a more restrictive variant that can produce additional errors.
2634    Early,
2635    /// Resolving something in late resolution when all imports are resolved
2636    /// and all macros are expanded.
2637    Late,
2638}
2639
2640/// Invariant: if `Finalize` is used, expansion and import resolution must be complete.
2641#[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)]
2642struct Finalize {
2643    /// Node ID for linting.
2644    node_id: NodeId,
2645    /// Span of the whole path or some its characteristic fragment.
2646    /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths.
2647    path_span: Span,
2648    /// Span of the path start, suitable for prepending something to it.
2649    /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths.
2650    root_span: Span,
2651    /// Whether to report privacy errors or silently return "no resolution" for them,
2652    /// similarly to speculative resolution.
2653    report_private: bool = true,
2654    /// Tracks whether an item is used in scope or used relatively to a module.
2655    used: Used = Used::Other,
2656    /// Finalizing early or late resolution.
2657    stage: Stage = Stage::Early,
2658    /// Nominal visibility of the import item, in case we are resolving an import's final segment.
2659    import_vis: Option<Visibility> = None,
2660}
2661
2662impl Finalize {
2663    fn new(node_id: NodeId, path_span: Span) -> Finalize {
2664        Finalize::with_root_span(node_id, path_span, path_span)
2665    }
2666
2667    fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2668        Finalize { node_id, path_span, root_span, .. }
2669    }
2670}
2671
2672pub fn provide(providers: &mut Providers) {
2673    providers.registered_tools = macros::registered_tools;
2674}
2675
2676/// A wrapper around `&mut Resolver` that may be mutable or immutable, depending on a conditions.
2677///
2678/// `Cm` stands for "conditionally mutable".
2679///
2680/// Prefer constructing it through [`Resolver::cm`] to ensure correctness.
2681type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;
2682
2683// FIXME: These are cells for caches that can be populated even during speculative resolution,
2684// and should be replaced with mutexes, atomics, or other synchronized data when migrating to
2685// parallel name resolution.
2686use std::cell::{Cell as CacheCell, RefCell as CacheRefCell};
2687
2688// FIXME: `*_unchecked` methods in the module below should be eliminated in the process
2689// of migration to parallel name resolution.
2690mod ref_mut {
2691    use std::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut};
2692    use std::fmt;
2693    use std::ops::Deref;
2694
2695    use crate::Resolver;
2696
2697    /// A wrapper around a mutable reference that conditionally allows mutable access.
2698    pub(crate) struct RefOrMut<'a, T> {
2699        p: &'a mut T,
2700        mutable: bool,
2701    }
2702
2703    impl<'a, T> Deref for RefOrMut<'a, T> {
2704        type Target = T;
2705
2706        fn deref(&self) -> &Self::Target {
2707            self.p
2708        }
2709    }
2710
2711    impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2712        fn as_ref(&self) -> &T {
2713            self.p
2714        }
2715    }
2716
2717    impl<'a, T> RefOrMut<'a, T> {
2718        pub(crate) fn new(p: &'a mut T, mutable: bool) -> Self {
2719            RefOrMut { p, mutable }
2720        }
2721
2722        /// This is needed because this wraps a `&mut T` and is therefore not `Copy`.
2723        pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2724            RefOrMut { p: self.p, mutable: self.mutable }
2725        }
2726
2727        /// Returns a mutable reference to the inner value if allowed.
2728        ///
2729        /// # Panics
2730        /// Panics if the `mutable` flag is false.
2731        #[track_caller]
2732        pub(crate) fn get_mut(&mut self) -> &mut T {
2733            match self.mutable {
2734                false => {
    ::core::panicking::panic_fmt(format_args!("Can\'t mutably borrow speculative resolver"));
}panic!("Can't mutably borrow speculative resolver"),
2735                true => self.p,
2736            }
2737        }
2738
2739        /// Returns a mutable reference to the inner value without checking if
2740        /// it's in a mutable state.
2741        pub(crate) fn get_mut_unchecked(&mut self) -> &mut T {
2742            self.p
2743        }
2744    }
2745
2746    /// A wrapper around a [`Cell`] that only allows mutation based on a condition in the resolver.
2747    #[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)]
2748    pub(crate) struct CmCell<T>(Cell<T>);
2749
2750    impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> {
2751        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2752            f.debug_tuple("CmCell").field(&self.get()).finish()
2753        }
2754    }
2755
2756    impl<T: Copy> Clone for CmCell<T> {
2757        fn clone(&self) -> CmCell<T> {
2758            CmCell::new(self.get())
2759        }
2760    }
2761
2762    impl<T: Copy> CmCell<T> {
2763        pub(crate) const fn get(&self) -> T {
2764            self.0.get()
2765        }
2766
2767        pub(crate) fn update_unchecked(&self, f: impl FnOnce(T) -> T)
2768        where
2769            T: Copy,
2770        {
2771            let old = self.get();
2772            self.set_unchecked(f(old));
2773        }
2774    }
2775
2776    impl<T> CmCell<T> {
2777        pub(crate) const fn new(value: T) -> CmCell<T> {
2778            CmCell(Cell::new(value))
2779        }
2780
2781        pub(crate) fn set_unchecked(&self, val: T) {
2782            self.0.set(val);
2783        }
2784
2785        pub(crate) fn into_inner(self) -> T {
2786            self.0.into_inner()
2787        }
2788    }
2789
2790    /// A wrapper around a [`RefCell`] that only allows mutable borrows based on a condition in the resolver.
2791    #[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)]
2792    pub(crate) struct CmRefCell<T>(RefCell<T>);
2793
2794    impl<T> CmRefCell<T> {
2795        pub(crate) const fn new(value: T) -> CmRefCell<T> {
2796            CmRefCell(RefCell::new(value))
2797        }
2798
2799        #[track_caller]
2800        pub(crate) fn borrow_mut_unchecked(&self) -> RefMut<'_, T> {
2801            self.0.borrow_mut()
2802        }
2803
2804        #[track_caller]
2805        pub(crate) fn borrow_mut<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> RefMut<'_, T> {
2806            if r.assert_speculative {
2807                {
    ::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");
2808            }
2809            self.borrow_mut_unchecked()
2810        }
2811
2812        #[track_caller]
2813        pub(crate) fn try_borrow_mut_unchecked(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
2814            self.0.try_borrow_mut()
2815        }
2816
2817        #[track_caller]
2818        pub(crate) fn borrow(&self) -> Ref<'_, T> {
2819            self.0.borrow()
2820        }
2821    }
2822
2823    impl<T: Default> CmRefCell<T> {
2824        pub(crate) fn take<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> T {
2825            if r.assert_speculative {
2826                {
    ::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");
2827            }
2828            self.0.take()
2829        }
2830    }
2831}
2832
2833mod hygiene {
2834    use rustc_span::{ExpnId, SyntaxContext};
2835
2836    /// A newtype around `SyntaxContext` that can only keep contexts produced by
2837    /// [SyntaxContext::normalize_to_macros_2_0].
2838    #[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)]
2839    pub(crate) struct Macros20NormalizedSyntaxContext(SyntaxContext);
2840
2841    impl Macros20NormalizedSyntaxContext {
2842        #[inline]
2843        pub(crate) fn new(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
2844            Macros20NormalizedSyntaxContext(ctxt.normalize_to_macros_2_0())
2845        }
2846
2847        #[inline]
2848        pub(crate) fn new_adjusted(
2849            mut ctxt: SyntaxContext,
2850            expn_id: ExpnId,
2851        ) -> (Macros20NormalizedSyntaxContext, Option<ExpnId>) {
2852            let def = ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
2853            (Macros20NormalizedSyntaxContext(ctxt), def)
2854        }
2855
2856        #[inline]
2857        pub(crate) fn new_unchecked(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
2858            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());
2859            Macros20NormalizedSyntaxContext(ctxt)
2860        }
2861
2862        /// The passed closure must preserve the context's normalized-ness.
2863        #[inline]
2864        pub(crate) fn update_unchecked<R>(&mut self, f: impl FnOnce(&mut SyntaxContext) -> R) -> R {
2865            let ret = f(&mut self.0);
2866            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());
2867            ret
2868        }
2869    }
2870
2871    impl std::ops::Deref for Macros20NormalizedSyntaxContext {
2872        type Target = SyntaxContext;
2873        fn deref(&self) -> &Self::Target {
2874            &self.0
2875        }
2876    }
2877}