Skip to main content

rustc_resolve/
ident.rs

1use std::ops::ControlFlow;
2
3use Determinacy::*;
4use Namespace::*;
5use rustc_ast::{self as ast, NodeId};
6use rustc_errors::ErrorGuaranteed;
7use rustc_hir::def::{DefKind, MacroKinds, Namespace, NonMacroAttrKind, PartialRes, PerNS};
8use rustc_middle::{bug, span_bug};
9use rustc_session::errors::feature_err;
10use rustc_session::lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK;
11use rustc_span::edition::Edition;
12use rustc_span::hygiene::{ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext};
13use rustc_span::{Ident, Span, kw, sym};
14use smallvec::SmallVec;
15use tracing::{debug, instrument};
16
17use crate::diagnostics::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
18use crate::hygiene::Macros20NormalizedSyntaxContext;
19use crate::imports::{Import, NameResolution};
20use crate::late::{
21    ConstantHasGenerics, DiagMetadata, NoConstantGenericsReason, PathSource, Rib, RibKind,
22};
23use crate::macros::{MacroRulesScope, sub_namespace_match};
24use crate::{
25    AmbiguityError, AmbiguityKind, AmbiguityWarning, BindingKey, CmResolver, Decl, DeclKind,
26    Determinacy, ExternModule, Finalize, IdentKey, ImportKind, ImportSummary, LateDecl,
27    LocalModule, Module, ModuleKind, ModuleOrUniformRoot, ParentScope, PathResult, PrivacyError,
28    Res, ResolutionError, Resolver, Scope, ScopeSet, Segment, Stage, Symbol, Used, diagnostics,
29};
30
31#[derive(#[automatically_derived]
impl ::core::marker::Copy for UsePrelude { }Copy, #[automatically_derived]
impl ::core::clone::Clone for UsePrelude {
    #[inline]
    fn clone(&self) -> UsePrelude { *self }
}Clone)]
32pub enum UsePrelude {
33    No,
34    Yes,
35}
36
37impl From<UsePrelude> for bool {
38    fn from(up: UsePrelude) -> bool {
39        #[allow(non_exhaustive_omitted_patterns)] match up {
    UsePrelude::Yes => true,
    _ => false,
}matches!(up, UsePrelude::Yes)
40    }
41}
42
43#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Shadowing {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Shadowing::Restricted => "Restricted",
                Shadowing::Unrestricted => "Unrestricted",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for Shadowing {
    #[inline]
    fn eq(&self, other: &Shadowing) -> 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::clone::Clone for Shadowing {
    #[inline]
    fn clone(&self) -> Shadowing { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Shadowing { }Copy)]
44enum Shadowing {
45    Restricted,
46    Unrestricted,
47}
48
49impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
50    /// A generic scope visitor.
51    /// Visits scopes in order to resolve some identifier in them or perform other actions.
52    /// If the callback returns `Some` result, we stop visiting scopes and return it.
53    pub(crate) fn visit_scopes<'r, T>(
54        mut self: CmResolver<'r, 'ra, 'tcx>,
55        scope_set: ScopeSet<'ra>,
56        parent_scope: &ParentScope<'ra>,
57        mut ctxt: Macros20NormalizedSyntaxContext,
58        orig_ident_span: Span,
59        derive_fallback_lint_id: Option<NodeId>,
60        mut visitor: impl FnMut(
61            CmResolver<'_, 'ra, 'tcx>,
62            Scope<'ra>,
63            UsePrelude,
64            Macros20NormalizedSyntaxContext,
65        ) -> ControlFlow<T>,
66    ) -> Option<T> {
67        // General principles:
68        // 1. Not controlled (user-defined) names should have higher priority than controlled names
69        //    built into the language or standard library. This way we can add new names into the
70        //    language or standard library without breaking user code.
71        // 2. "Closed set" below means new names cannot appear after the current resolution attempt.
72        // Places to search (in order of decreasing priority):
73        // (Type NS)
74        // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
75        //    (open set, not controlled).
76        // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
77        //    (open, not controlled).
78        // 3. Extern prelude (open, the open part is from macro expansions, not controlled).
79        // 4. Tool modules (closed, controlled right now, but not in the future).
80        // 5. Standard library prelude (de-facto closed, controlled).
81        // 6. Language prelude (closed, controlled).
82        // (Value NS)
83        // 1. FIXME: Ribs (local variables), there's no necessary infrastructure yet
84        //    (open set, not controlled).
85        // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
86        //    (open, not controlled).
87        // 3. Standard library prelude (de-facto closed, controlled).
88        // (Macro NS)
89        // 1-3. Derive helpers (open, not controlled). All ambiguities with other names
90        //    are currently reported as errors. They should be higher in priority than preludes
91        //    and probably even names in modules according to the "general principles" above. They
92        //    also should be subject to restricted shadowing because are effectively produced by
93        //    derives (you need to resolve the derive first to add helpers into scope), but they
94        //    should be available before the derive is expanded for compatibility.
95        //    It's mess in general, so we are being conservative for now.
96        // 1-3. `macro_rules` (open, not controlled), loop through `macro_rules` scopes. Have higher
97        //    priority than prelude macros, but create ambiguities with macros in modules.
98        // 1-3. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
99        //    (open, not controlled). Have higher priority than prelude macros, but create
100        //    ambiguities with `macro_rules`.
101        // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
102        // 4a. User-defined prelude from macro-use
103        //    (open, the open part is from macro expansions, not controlled).
104        // 4b. "Standard library prelude" part implemented through `macro-use` (closed, controlled).
105        // 4c. Standard library prelude (de-facto closed, controlled).
106        // 6. Language prelude: builtin attributes (closed, controlled).
107
108        let (ns, macro_kind) = match scope_set {
109            ScopeSet::All(ns)
110            | ScopeSet::Module(ns, _)
111            | ScopeSet::ModuleAndExternPrelude(ns, _) => (ns, None),
112            ScopeSet::ExternPrelude => (TypeNS, None),
113            ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind)),
114        };
115        let module = match scope_set {
116            // Start with the specified module.
117            ScopeSet::Module(_, module) | ScopeSet::ModuleAndExternPrelude(_, module) => module,
118            // Jump out of trait or enum modules, they do not act as scopes.
119            _ => parent_scope.module.nearest_item_scope(),
120        };
121        let module_only = #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..));
122        let module_and_extern_prelude = #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::ModuleAndExternPrelude(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::ModuleAndExternPrelude(..));
123        let extern_prelude = #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::ExternPrelude => true,
    _ => false,
}matches!(scope_set, ScopeSet::ExternPrelude);
124        let mut scope = match ns {
125            _ if module_only || module_and_extern_prelude => Scope::ModuleNonGlobs(module, None),
126            _ if extern_prelude => Scope::ExternPreludeItems,
127            TypeNS | ValueNS => Scope::ModuleNonGlobs(module, None),
128            MacroNS => Scope::DeriveHelpers(parent_scope.expansion),
129        };
130        let mut use_prelude = !module.no_implicit_prelude;
131
132        loop {
133            let visit = match scope {
134                // Derive helpers are not in scope when resolving derives in the same container.
135                Scope::DeriveHelpers(expn_id) => {
136                    !(expn_id == parent_scope.expansion && macro_kind == Some(MacroKind::Derive))
137                }
138                Scope::DeriveHelpersCompat => true,
139                Scope::MacroRules(macro_rules_scope) => {
140                    // Use "path compression" on `macro_rules` scope chains. This is an optimization
141                    // used to avoid long scope chains, see the comments on `MacroRulesScopeRef`.
142                    // As another consequence of this optimization visitors never observe invocation
143                    // scopes for macros that were already expanded.
144                    while let MacroRulesScope::Invocation(invoc_id) = macro_rules_scope.get() {
145                        if let Some(next_scope) = self.output_macro_rules_scopes.get(&invoc_id) {
146                            macro_rules_scope.set(next_scope.get());
147                        } else {
148                            break;
149                        }
150                    }
151                    true
152                }
153                Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..) => true,
154                Scope::MacroUsePrelude => use_prelude || orig_ident_span.is_rust_2015(),
155                Scope::BuiltinAttrs => true,
156                Scope::ExternPreludeItems | Scope::ExternPreludeFlags => {
157                    use_prelude || module_and_extern_prelude || extern_prelude
158                }
159                Scope::ToolPrelude => use_prelude,
160                Scope::StdLibPrelude => use_prelude || ns == MacroNS,
161                Scope::BuiltinTypes => true,
162            };
163
164            if visit {
165                let use_prelude = if use_prelude { UsePrelude::Yes } else { UsePrelude::No };
166                if let ControlFlow::Break(break_result) =
167                    visitor(self.reborrow(), scope, use_prelude, ctxt)
168                {
169                    return Some(break_result);
170                }
171            }
172
173            scope = match scope {
174                Scope::DeriveHelpers(LocalExpnId::ROOT) => Scope::DeriveHelpersCompat,
175                Scope::DeriveHelpers(expn_id) => {
176                    // Derive helpers are not visible to code generated by bang or derive macros.
177                    let expn_data = expn_id.expn_data();
178                    match expn_data.kind {
179                        ExpnKind::Root
180                        | ExpnKind::Macro(MacroKind::Bang | MacroKind::Derive, _) => {
181                            Scope::DeriveHelpersCompat
182                        }
183                        _ => Scope::DeriveHelpers(expn_data.parent.expect_local()),
184                    }
185                }
186                Scope::DeriveHelpersCompat => Scope::MacroRules(parent_scope.macro_rules),
187                Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
188                    MacroRulesScope::Def(binding) => {
189                        Scope::MacroRules(binding.parent_macro_rules_scope)
190                    }
191                    MacroRulesScope::Invocation(invoc_id) => {
192                        Scope::MacroRules(self.invocation_parent_scopes[&invoc_id].macro_rules)
193                    }
194                    MacroRulesScope::Empty => Scope::ModuleNonGlobs(module, None),
195                },
196                Scope::ModuleNonGlobs(module, lint_id) => Scope::ModuleGlobs(module, lint_id),
197                Scope::ModuleGlobs(..) if module_only => break,
198                Scope::ModuleGlobs(..) if module_and_extern_prelude => match ns {
199                    TypeNS => {
200                        ctxt.update_unchecked(|ctxt| ctxt.adjust(ExpnId::root()));
201                        Scope::ExternPreludeItems
202                    }
203                    ValueNS | MacroNS => break,
204                },
205                Scope::ModuleGlobs(module, prev_lint_id) => {
206                    use_prelude = !module.no_implicit_prelude;
207                    match self.hygienic_lexical_parent(module, &mut ctxt, derive_fallback_lint_id) {
208                        Some((parent_module, lint_id)) => {
209                            Scope::ModuleNonGlobs(parent_module, lint_id.or(prev_lint_id))
210                        }
211                        None => {
212                            ctxt.update_unchecked(|ctxt| ctxt.adjust(ExpnId::root()));
213                            match ns {
214                                TypeNS => Scope::ExternPreludeItems,
215                                ValueNS => Scope::StdLibPrelude,
216                                MacroNS => Scope::MacroUsePrelude,
217                            }
218                        }
219                    }
220                }
221                Scope::MacroUsePrelude => Scope::StdLibPrelude,
222                Scope::BuiltinAttrs => break, // nowhere else to search
223                Scope::ExternPreludeItems => Scope::ExternPreludeFlags,
224                Scope::ExternPreludeFlags if module_and_extern_prelude || extern_prelude => break,
225                Scope::ExternPreludeFlags => Scope::ToolPrelude,
226                Scope::ToolPrelude => Scope::StdLibPrelude,
227                Scope::StdLibPrelude => match ns {
228                    TypeNS => Scope::BuiltinTypes,
229                    ValueNS => break, // nowhere else to search
230                    MacroNS => Scope::BuiltinAttrs,
231                },
232                Scope::BuiltinTypes => break, // nowhere else to search
233            };
234        }
235
236        None
237    }
238
239    fn hygienic_lexical_parent(
240        &self,
241        module: Module<'ra>,
242        ctxt: &mut Macros20NormalizedSyntaxContext,
243        derive_fallback_lint_id: Option<NodeId>,
244    ) -> Option<(Module<'ra>, Option<NodeId>)> {
245        if !module.expansion.outer_expn_is_descendant_of(**ctxt) {
246            let expn_id = ctxt.update_unchecked(|ctxt| ctxt.remove_mark());
247            return Some((self.expn_def_scope(expn_id), None));
248        }
249
250        if let ModuleKind::Block = module.kind {
251            return Some((module.parent.unwrap().nearest_item_scope(), None));
252        }
253
254        // We need to support the next case under a deprecation warning
255        // ```
256        // struct MyStruct;
257        // ---- begin: this comes from a proc macro derive
258        // mod implementation_details {
259        //     // Note that `MyStruct` is not in scope here.
260        //     impl SomeTrait for MyStruct { ... }
261        // }
262        // ---- end
263        // ```
264        // So we have to fall back to the module's parent during lexical resolution in this case.
265        if derive_fallback_lint_id.is_some()
266            && let Some(parent) = module.parent
267            // Inner module is inside the macro
268            && module.expansion != parent.expansion
269            // Parent module is outside of the macro
270            && module.expansion.is_descendant_of(parent.expansion)
271            // The macro is a proc macro derive
272            && let Some(def_id) = module.expansion.expn_data().macro_def_id
273        {
274            let ext = self.get_macro_by_def_id(def_id);
275            if ext.builtin_name.is_none()
276                && ext.macro_kinds() == MacroKinds::DERIVE
277                && parent.expansion.outer_expn_is_descendant_of(**ctxt)
278            {
279                return Some((parent, derive_fallback_lint_id));
280            }
281        }
282
283        None
284    }
285
286    /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
287    /// More specifically, we proceed up the hierarchy of scopes and return the binding for
288    /// `ident` in the first scope that defines it (or None if no scopes define it).
289    ///
290    /// A block's items are above its local variables in the scope hierarchy, regardless of where
291    /// the items are defined in the block. For example,
292    /// ```rust
293    /// fn f() {
294    ///    g(); // Since there are no local variables in scope yet, this resolves to the item.
295    ///    let g = || {};
296    ///    fn g() {}
297    ///    g(); // This resolves to the local variable `g` since it shadows the item.
298    /// }
299    /// ```
300    ///
301    /// Invariant: This must only be called during main resolution, not during
302    /// import resolution.
303    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("resolve_ident_in_lexical_scope",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(303u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["ident", "ns",
                                                    "parent_scope", "finalize", "ignore_decl", "diag_metadata"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ns)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_decl)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_metadata)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<LateDecl<'ra>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let orig_ident = ident;
            let (general_span, normalized_span) =
                if ident.name == kw::SelfUpper {
                    let empty_span =
                        ident.span.with_ctxt(SyntaxContext::root());
                    (empty_span, empty_span)
                } else if ns == TypeNS {
                    let normalized_span = ident.span.normalize_to_macros_2_0();
                    (normalized_span, normalized_span)
                } else {
                    (ident.span.normalize_to_macro_rules(),
                        ident.span.normalize_to_macros_2_0())
                };
            ident.span = general_span;
            let normalized_ident = Ident { span: normalized_span, ..ident };
            for (i, rib) in ribs.iter().enumerate().rev() {
                {
                    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/ident.rs:330",
                                        "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                        ::tracing_core::__macro_support::Option::Some(330u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                        ::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!("walk rib\n{0:?}",
                                                                    rib.bindings) as &dyn Value))])
                            });
                    } else { ; }
                };
                let rib_ident =
                    if rib.kind.contains_params() {
                        normalized_ident
                    } else { ident };
                if let Some((original_rib_ident_def, res)) =
                        rib.bindings.get_key_value(&rib_ident) {
                    return Some(LateDecl::RibDef(self.validate_res_from_ribs(i,
                                    rib_ident, *res, finalize.map(|_| general_span),
                                    *original_rib_ident_def, ribs, diag_metadata)));
                } else if let RibKind::Block(Some(module)) = rib.kind &&
                        let Ok(binding) =
                            self.cm().resolve_ident_in_scope_set(ident,
                                ScopeSet::Module(ns, module.to_module()), parent_scope,
                                finalize.map(|finalize|
                                        Finalize { used: Used::Scope, ..finalize }), ignore_decl,
                                None) {
                    return Some(LateDecl::Decl(binding));
                } else if let RibKind::Module(module) = rib.kind {
                    let parent_scope =
                        &ParentScope {
                                module: module.to_module(),
                                ..*parent_scope
                            };
                    let finalize =
                        finalize.map(|f| Finalize { stage: Stage::Late, ..f });
                    return self.cm().resolve_ident_in_scope_set(orig_ident,
                                    ScopeSet::All(ns), parent_scope, finalize, ignore_decl,
                                    None).ok().map(LateDecl::Decl);
                }
                if let RibKind::MacroDefinition(def) = rib.kind &&
                        def == self.macro_def(ident.span.ctxt()) {
                    ident.span.remove_mark();
                }
            }
            ::core::panicking::panic("internal error: entered unreachable code")
        }
    }
}#[instrument(level = "debug", skip(self, ribs))]
304    pub(crate) fn resolve_ident_in_lexical_scope(
305        &mut self,
306        mut ident: Ident,
307        ns: Namespace,
308        parent_scope: &ParentScope<'ra>,
309        finalize: Option<Finalize>,
310        ribs: &[Rib<'ra>],
311        ignore_decl: Option<Decl<'ra>>,
312        diag_metadata: Option<&DiagMetadata<'_>>,
313    ) -> Option<LateDecl<'ra>> {
314        let orig_ident = ident;
315        let (general_span, normalized_span) = if ident.name == kw::SelfUpper {
316            // FIXME(jseyfried) improve `Self` hygiene
317            let empty_span = ident.span.with_ctxt(SyntaxContext::root());
318            (empty_span, empty_span)
319        } else if ns == TypeNS {
320            let normalized_span = ident.span.normalize_to_macros_2_0();
321            (normalized_span, normalized_span)
322        } else {
323            (ident.span.normalize_to_macro_rules(), ident.span.normalize_to_macros_2_0())
324        };
325        ident.span = general_span;
326        let normalized_ident = Ident { span: normalized_span, ..ident };
327
328        // Walk backwards up the ribs in scope.
329        for (i, rib) in ribs.iter().enumerate().rev() {
330            debug!("walk rib\n{:?}", rib.bindings);
331            // Use the rib kind to determine whether we are resolving parameters
332            // (macro 2.0 hygiene) or local variables (`macro_rules` hygiene).
333            let rib_ident = if rib.kind.contains_params() { normalized_ident } else { ident };
334            if let Some((original_rib_ident_def, res)) = rib.bindings.get_key_value(&rib_ident) {
335                // The ident resolves to a type parameter or local variable.
336                return Some(LateDecl::RibDef(self.validate_res_from_ribs(
337                    i,
338                    rib_ident,
339                    *res,
340                    finalize.map(|_| general_span),
341                    *original_rib_ident_def,
342                    ribs,
343                    diag_metadata,
344                )));
345            } else if let RibKind::Block(Some(module)) = rib.kind
346                && let Ok(binding) = self.cm().resolve_ident_in_scope_set(
347                    ident,
348                    ScopeSet::Module(ns, module.to_module()),
349                    parent_scope,
350                    finalize.map(|finalize| Finalize { used: Used::Scope, ..finalize }),
351                    ignore_decl,
352                    None,
353                )
354            {
355                // The ident resolves to an item in a block.
356                return Some(LateDecl::Decl(binding));
357            } else if let RibKind::Module(module) = rib.kind {
358                // Encountered a module item, abandon ribs and look into that module and preludes.
359                let parent_scope = &ParentScope { module: module.to_module(), ..*parent_scope };
360                let finalize = finalize.map(|f| Finalize { stage: Stage::Late, ..f });
361                return self
362                    .cm()
363                    .resolve_ident_in_scope_set(
364                        orig_ident,
365                        ScopeSet::All(ns),
366                        parent_scope,
367                        finalize,
368                        ignore_decl,
369                        None,
370                    )
371                    .ok()
372                    .map(LateDecl::Decl);
373            }
374
375            if let RibKind::MacroDefinition(def) = rib.kind
376                && def == self.macro_def(ident.span.ctxt())
377            {
378                // If an invocation of this macro created `ident`, give up on `ident`
379                // and switch to `ident`'s source from the macro definition.
380                ident.span.remove_mark();
381            }
382        }
383
384        unreachable!()
385    }
386
387    /// Resolve an identifier in the specified set of scopes.
388    pub(crate) fn resolve_ident_in_scope_set<'r>(
389        self: CmResolver<'r, 'ra, 'tcx>,
390        orig_ident: Ident,
391        scope_set: ScopeSet<'ra>,
392        parent_scope: &ParentScope<'ra>,
393        finalize: Option<Finalize>,
394        ignore_decl: Option<Decl<'ra>>,
395        ignore_import: Option<Import<'ra>>,
396    ) -> Result<Decl<'ra>, Determinacy> {
397        self.resolve_ident_in_scope_set_inner(
398            IdentKey::new(orig_ident),
399            orig_ident.span,
400            scope_set,
401            parent_scope,
402            finalize,
403            ignore_decl,
404            ignore_import,
405        )
406    }
407
408    fn resolve_ident_in_scope_set_inner<'r>(
409        self: CmResolver<'r, 'ra, 'tcx>,
410        ident: IdentKey,
411        orig_ident_span: Span,
412        scope_set: ScopeSet<'ra>,
413        parent_scope: &ParentScope<'ra>,
414        finalize: Option<Finalize>,
415        ignore_decl: Option<Decl<'ra>>,
416        ignore_import: Option<Import<'ra>>,
417    ) -> Result<Decl<'ra>, Determinacy> {
418        // Make sure `self`, `super` etc produce an error when passed to here.
419        if !#[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..)) && ident.name.is_path_segment_keyword() {
420            return Err(Determinacy::Determined);
421        }
422
423        let (ns, macro_kind) = match scope_set {
424            ScopeSet::All(ns)
425            | ScopeSet::Module(ns, _)
426            | ScopeSet::ModuleAndExternPrelude(ns, _) => (ns, None),
427            ScopeSet::ExternPrelude => (TypeNS, None),
428            ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind)),
429        };
430        let derive_fallback_lint_id = match finalize {
431            Some(Finalize { node_id, stage: Stage::Late, .. }) => Some(node_id),
432            _ => None,
433        };
434
435        // This is *the* result, resolution from the scope closest to the resolved identifier.
436        // However, sometimes this result is "weak" because it comes from a glob import or
437        // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
438        // mod m { ... } // solution in outer scope
439        // {
440        //     use prefix::*; // imports another `m` - innermost solution
441        //                    // weak, cannot shadow the outer `m`, need to report ambiguity error
442        //     m::mac!();
443        // }
444        // So we have to save the innermost solution and continue searching in outer scopes
445        // to detect potential ambiguities.
446        let mut innermost_results: SmallVec<[(Decl<'_>, Scope<'_>); 2]> = SmallVec::new();
447        let mut determinacy = Determinacy::Determined;
448
449        // Go through all the scopes and try to resolve the name.
450        let break_result = self.visit_scopes(
451            scope_set,
452            parent_scope,
453            ident.ctxt,
454            orig_ident_span,
455            derive_fallback_lint_id,
456            |mut this, scope, use_prelude, ctxt| {
457                let ident = IdentKey { name: ident.name, ctxt };
458                let res = match this.reborrow().resolve_ident_in_scope(
459                    ident,
460                    orig_ident_span,
461                    ns,
462                    scope,
463                    use_prelude,
464                    scope_set,
465                    parent_scope,
466                    // Shadowed decls don't need to be marked as used or non-speculatively loaded.
467                    if innermost_results.is_empty() { finalize } else { None },
468                    ignore_decl,
469                    ignore_import,
470                ) {
471                    Ok(decl) => Ok(decl),
472                    // We can break with an error at this step, it means we cannot determine the
473                    // resolution right now, but we must block and wait until we can, instead of
474                    // considering outer scopes. Although there's no need to do that if we already
475                    // have a better solution.
476                    Err(ControlFlow::Break(determinacy)) if innermost_results.is_empty() => {
477                        return ControlFlow::Break(Err(determinacy));
478                    }
479                    Err(determinacy) => Err(determinacy.into_value()),
480                };
481                match res {
482                    Ok(decl) if sub_namespace_match(decl.macro_kinds(), macro_kind) => {
483                        // Below we report various ambiguity errors.
484                        // We do not need to report them if we are either in speculative resolution,
485                        // or in late resolution when everything is already imported and expanded
486                        // and no ambiguities exist.
487                        let import = match finalize {
488                            None | Some(Finalize { stage: Stage::Late, .. }) => {
489                                return ControlFlow::Break(Ok(decl));
490                            }
491                            Some(Finalize { import, .. }) => import,
492                        };
493                        this.get_mut().maybe_push_glob_vs_glob_vis_ambiguity(
494                            ident,
495                            orig_ident_span,
496                            decl,
497                            import,
498                        );
499
500                        if let Some(&(innermost_decl, _)) = innermost_results.first() {
501                            // Found another solution, if the first one was "weak", report an error.
502                            if this.get_mut().maybe_push_ambiguity(
503                                ident,
504                                orig_ident_span,
505                                ns,
506                                scope_set,
507                                parent_scope,
508                                decl,
509                                scope,
510                                &innermost_results,
511                                import,
512                            ) {
513                                // No need to search for more potential ambiguities, one is enough.
514                                return ControlFlow::Break(Ok(innermost_decl));
515                            }
516                        }
517
518                        innermost_results.push((decl, scope));
519                    }
520                    Ok(_) | Err(Determinacy::Determined) => {}
521                    Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
522                }
523
524                ControlFlow::Continue(())
525            },
526        );
527
528        // Scope visiting returned some result early.
529        if let Some(break_result) = break_result {
530            return break_result;
531        }
532
533        // Scope visiting walked all the scopes and maybe found something in one of them.
534        match innermost_results.first() {
535            Some(&(decl, ..)) => Ok(decl),
536            None => Err(determinacy),
537        }
538    }
539
540    fn resolve_ident_in_scope<'r>(
541        mut self: CmResolver<'r, 'ra, 'tcx>,
542        ident: IdentKey,
543        orig_ident_span: Span,
544        ns: Namespace,
545        scope: Scope<'ra>,
546        use_prelude: UsePrelude,
547        scope_set: ScopeSet<'ra>,
548        parent_scope: &ParentScope<'ra>,
549        finalize: Option<Finalize>,
550        ignore_decl: Option<Decl<'ra>>,
551        ignore_import: Option<Import<'ra>>,
552    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
553        let ret = match scope {
554            Scope::DeriveHelpers(expn_id) => {
555                if let Some(decl) = self
556                    .helper_attrs
557                    .get(&expn_id)
558                    .and_then(|attrs| attrs.iter().rfind(|(i, ..)| ident == *i).map(|(.., d)| *d))
559                {
560                    Ok(decl)
561                } else {
562                    Err(Determinacy::Determined)
563                }
564            }
565            Scope::DeriveHelpersCompat => {
566                let mut result = Err(Determinacy::Determined);
567                for derive in parent_scope.derives {
568                    let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
569                    match self.reborrow().resolve_derive_macro_path(
570                        derive,
571                        parent_scope,
572                        false,
573                        ignore_import,
574                    ) {
575                        Ok((Some(ext), _)) => {
576                            if ext.helper_attrs.contains(&ident.name) {
577                                let decl = self.arenas.new_pub_def_decl(
578                                    Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat),
579                                    derive.span,
580                                    LocalExpnId::ROOT,
581                                );
582                                result = Ok(decl);
583                                break;
584                            }
585                        }
586                        Ok(_) | Err(Determinacy::Determined) => {}
587                        Err(Determinacy::Undetermined) => result = Err(Determinacy::Undetermined),
588                    }
589                }
590                result
591            }
592            Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
593                MacroRulesScope::Def(macro_rules_def) if ident == macro_rules_def.ident => {
594                    Ok(macro_rules_def.decl)
595                }
596                MacroRulesScope::Invocation(_) => Err(Determinacy::Undetermined),
597                _ => Err(Determinacy::Determined),
598            },
599            Scope::ModuleNonGlobs(module, derive_fallback_lint_id) => {
600                let (adjusted_parent_scope, adjusted_finalize) = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..) => true,
    _ => false,
}matches!(
601                    scope_set,
602                    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..)
603                ) {
604                    (parent_scope, finalize)
605                } else {
606                    (
607                        &ParentScope { module, ..*parent_scope },
608                        finalize.map(|f| Finalize { used: Used::Scope, ..f }),
609                    )
610                };
611                let shadowing = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..)) {
612                    Shadowing::Unrestricted
613                } else {
614                    Shadowing::Restricted
615                };
616                let decl = if module.is_local() {
617                    self.reborrow().resolve_ident_in_local_module_non_globs_unadjusted(
618                        module.expect_local(),
619                        ident,
620                        orig_ident_span,
621                        ns,
622                        adjusted_parent_scope,
623                        shadowing,
624                        adjusted_finalize,
625                        ignore_decl,
626                        ignore_import,
627                    )
628                } else {
629                    self.reborrow().resolve_ident_in_extern_module_non_globs_unadjusted(
630                        module.expect_extern(),
631                        ident,
632                        orig_ident_span,
633                        ns,
634                        adjusted_parent_scope,
635                        shadowing,
636                        adjusted_finalize,
637                        ignore_decl,
638                    )
639                };
640
641                match decl {
642                    Ok(decl) => {
643                        if let Some(lint_id) = derive_fallback_lint_id {
644                            self.get_mut().lint_buffer.buffer_lint(
645                                PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
646                                lint_id,
647                                orig_ident_span,
648                                diagnostics::ProcMacroDeriveResolutionFallback {
649                                    span: orig_ident_span,
650                                    ns_descr: ns.descr(),
651                                    ident: ident.name,
652                                },
653                            );
654                        }
655                        Ok(decl)
656                    }
657                    Err(ControlFlow::Continue(determinacy)) => Err(determinacy),
658                    Err(ControlFlow::Break(..)) => return decl,
659                }
660            }
661            Scope::ModuleGlobs(module, _) if !module.is_local() => {
662                // Fast path: external module decoding only creates non-glob declarations.
663                Err(Determined)
664            }
665            Scope::ModuleGlobs(module, derive_fallback_lint_id) => {
666                let (adjusted_parent_scope, adjusted_finalize) = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..) => true,
    _ => false,
}matches!(
667                    scope_set,
668                    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..)
669                ) {
670                    (parent_scope, finalize)
671                } else {
672                    (
673                        &ParentScope { module, ..*parent_scope },
674                        finalize.map(|f| Finalize { used: Used::Scope, ..f }),
675                    )
676                };
677                let binding = self.reborrow().resolve_ident_in_module_globs_unadjusted(
678                    module.expect_local(),
679                    ident,
680                    orig_ident_span,
681                    ns,
682                    adjusted_parent_scope,
683                    if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..)) {
684                        Shadowing::Unrestricted
685                    } else {
686                        Shadowing::Restricted
687                    },
688                    adjusted_finalize,
689                    ignore_decl,
690                    ignore_import,
691                );
692                match binding {
693                    Ok(binding) => {
694                        if let Some(lint_id) = derive_fallback_lint_id {
695                            self.get_mut().lint_buffer.buffer_lint(
696                                PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
697                                lint_id,
698                                orig_ident_span,
699                                diagnostics::ProcMacroDeriveResolutionFallback {
700                                    span: orig_ident_span,
701                                    ns_descr: ns.descr(),
702                                    ident: ident.name,
703                                },
704                            );
705                        }
706                        Ok(binding)
707                    }
708                    Err(ControlFlow::Continue(determinacy)) => Err(determinacy),
709                    Err(ControlFlow::Break(..)) => return binding,
710                }
711            }
712            Scope::MacroUsePrelude => match self.macro_use_prelude.get(&ident.name).cloned() {
713                Some(decl) => Ok(decl),
714                None => Err(Determinacy::determined(!self.graph_root.has_unexpanded_invocations())),
715            },
716            Scope::BuiltinAttrs => match self.builtin_attr_decls.get(&ident.name) {
717                Some(decl) => Ok(*decl),
718                None => Err(Determinacy::Determined),
719            },
720            Scope::ExternPreludeItems => {
721                match self.reborrow().extern_prelude_get_item(
722                    ident,
723                    orig_ident_span,
724                    finalize.is_some(),
725                ) {
726                    Some(decl) => Ok(decl),
727                    None => {
728                        Err(Determinacy::determined(!self.graph_root.has_unexpanded_invocations()))
729                    }
730                }
731            }
732            Scope::ExternPreludeFlags => {
733                match self.extern_prelude_get_flag(ident, orig_ident_span, finalize.is_some()) {
734                    Some(decl) => Ok(decl),
735                    None => Err(Determinacy::Determined),
736                }
737            }
738            Scope::ToolPrelude => match self.registered_tool_decls.get(&ident) {
739                Some(decl) => Ok(*decl),
740                None => Err(Determinacy::Determined),
741            },
742            Scope::StdLibPrelude => {
743                let mut result = Err(Determinacy::Determined);
744                if let Some(prelude) = self.prelude
745                    && let Ok(decl) = self.reborrow().resolve_ident_in_scope_set_inner(
746                        ident,
747                        orig_ident_span,
748                        ScopeSet::Module(ns, prelude),
749                        parent_scope,
750                        None,
751                        ignore_decl,
752                        ignore_import,
753                    )
754                    && (#[allow(non_exhaustive_omitted_patterns)] match use_prelude {
    UsePrelude::Yes => true,
    _ => false,
}matches!(use_prelude, UsePrelude::Yes) || self.is_builtin_macro(decl.res()))
755                {
756                    result = Ok(decl)
757                }
758
759                result
760            }
761            Scope::BuiltinTypes => match self.builtin_type_decls.get(&ident.name) {
762                Some(decl) => {
763                    if #[allow(non_exhaustive_omitted_patterns)] match ident.name {
    sym::f16 => true,
    _ => false,
}matches!(ident.name, sym::f16)
764                        && !self.features.f16()
765                        && !orig_ident_span.allows_unstable(sym::f16)
766                        && finalize.is_some()
767                    {
768                        feature_err(
769                            self.tcx.sess,
770                            sym::f16,
771                            orig_ident_span,
772                            "the type `f16` is unstable",
773                        )
774                        .emit();
775                    }
776                    if #[allow(non_exhaustive_omitted_patterns)] match ident.name {
    sym::f128 => true,
    _ => false,
}matches!(ident.name, sym::f128)
777                        && !self.features.f128()
778                        && !orig_ident_span.allows_unstable(sym::f128)
779                        && finalize.is_some()
780                    {
781                        feature_err(
782                            self.tcx.sess,
783                            sym::f128,
784                            orig_ident_span,
785                            "the type `f128` is unstable",
786                        )
787                        .emit();
788                    }
789                    Ok(*decl)
790                }
791                None => Err(Determinacy::Determined),
792            },
793        };
794
795        ret.map_err(ControlFlow::Continue)
796    }
797
798    fn maybe_push_glob_vs_glob_vis_ambiguity(
799        &mut self,
800        ident: IdentKey,
801        orig_ident_span: Span,
802        decl: Decl<'ra>,
803        import: Option<ImportSummary>,
804    ) {
805        let Some(import) = import else { return };
806        let vis1 = self.import_decl_vis(decl, import);
807        let vis2 = self.import_decl_vis_ext(decl, import, true);
808        if vis1 != vis2 {
809            self.ambiguity_errors.push(AmbiguityError {
810                kind: AmbiguityKind::GlobVsGlob,
811                ambig_vis: Some((vis1, vis2)),
812                ident: ident.orig(orig_ident_span),
813                b1: decl.ambiguity_vis_max.get().unwrap_or(decl),
814                b2: decl.ambiguity_vis_min.get().unwrap_or(decl),
815                scope1: Scope::ModuleGlobs(decl.parent_module.unwrap(), None),
816                scope2: Scope::ModuleGlobs(decl.parent_module.unwrap(), None),
817                warning: Some(AmbiguityWarning::GlobImport),
818            });
819        }
820    }
821
822    fn maybe_push_ambiguity(
823        &mut self,
824        ident: IdentKey,
825        orig_ident_span: Span,
826        ns: Namespace,
827        scope_set: ScopeSet<'ra>,
828        parent_scope: &ParentScope<'ra>,
829        decl: Decl<'ra>,
830        scope: Scope<'ra>,
831        innermost_results: &[(Decl<'ra>, Scope<'ra>)],
832        import: Option<ImportSummary>,
833    ) -> bool {
834        let (innermost_decl, innermost_scope) = innermost_results[0];
835        let (res, innermost_res) = (decl.res(), innermost_decl.res());
836        let ambig_vis = if res != innermost_res {
837            None
838        } else if let Some(import) = import
839            && let vis1 = self.import_decl_vis(decl, import)
840            && let vis2 = self.import_decl_vis(innermost_decl, import)
841            && vis1 != vis2
842        {
843            Some((vis1, vis2))
844        } else {
845            return false;
846        };
847
848        // FIXME: Use `scope` instead of `res` to detect built-in attrs and derive helpers,
849        // it will exclude imports, make slightly more code legal, and will require lang approval.
850        let module_only = #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..));
851        let is_builtin = |res| #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)) => true,
    _ => false,
}matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)));
852        let derive_helper = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
853        let derive_helper_compat = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
854
855        let ambiguity_error_kind = if is_builtin(innermost_res) || is_builtin(res) {
856            Some(AmbiguityKind::BuiltinAttr)
857        } else if innermost_res == derive_helper_compat {
858            Some(AmbiguityKind::DeriveHelper)
859        } else if res == derive_helper_compat && innermost_res != derive_helper {
860            ::rustc_middle::util::bug::span_bug_fmt(orig_ident_span,
    format_args!("impossible inner resolution kind"))span_bug!(orig_ident_span, "impossible inner resolution kind")
861        } else if #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
    Scope::MacroRules(_) => true,
    _ => false,
}matches!(innermost_scope, Scope::MacroRules(_))
862            && #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..) => true,
    _ => false,
}matches!(scope, Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..))
863            && !self.disambiguate_macro_rules_vs_modularized(innermost_decl, decl)
864        {
865            Some(AmbiguityKind::MacroRulesVsModularized)
866        } else if #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::MacroRules(_) => true,
    _ => false,
}matches!(scope, Scope::MacroRules(_))
867            && #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
    Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..) => true,
    _ => false,
}matches!(innermost_scope, Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..))
868        {
869            // should be impossible because of visitation order in
870            // visit_scopes
871            //
872            // we visit all macro_rules scopes (e.g. textual scope macros)
873            // before we visit any modules (e.g. path-based scope macros)
874            ::rustc_middle::util::bug::span_bug_fmt(orig_ident_span,
    format_args!("ambiguous scoped macro resolutions with path-based scope resolution as first candidate"))span_bug!(
875                orig_ident_span,
876                "ambiguous scoped macro resolutions with path-based \
877                                        scope resolution as first candidate"
878            )
879        } else if innermost_decl.is_glob_import() {
880            Some(AmbiguityKind::GlobVsOuter)
881        } else if !module_only && innermost_decl.may_appear_after(parent_scope.expansion, decl) {
882            Some(AmbiguityKind::MoreExpandedVsOuter)
883        } else if innermost_decl.expansion != LocalExpnId::ROOT
884            && (!module_only || ns == MacroNS)
885            && let Scope::ModuleGlobs(m1, _) = scope
886            && let Scope::ModuleNonGlobs(m2, _) = innermost_scope
887            && m1 == m2
888        {
889            // FIXME: this error is too conservative and technically unnecessary now when module
890            // scope is split into two scopes, at least when not resolving in `ScopeSet::Module`,
891            // remove it with lang team approval.
892            Some(AmbiguityKind::GlobVsExpanded)
893        } else {
894            None
895        };
896
897        if let Some(kind) = ambiguity_error_kind {
898            // Skip ambiguity errors for extern flag bindings "overridden"
899            // by extern item bindings.
900            // FIXME: Remove with lang team approval.
901            let issue_145575_hack = #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::ExternPreludeFlags => true,
    _ => false,
}matches!(scope, Scope::ExternPreludeFlags)
902                && innermost_results[1..]
903                    .iter()
904                    .any(|(b, s)| #[allow(non_exhaustive_omitted_patterns)] match s {
    Scope::ExternPreludeItems => true,
    _ => false,
}matches!(s, Scope::ExternPreludeItems) && *b != innermost_decl);
905            // Skip ambiguity errors for nonglob module bindings "overridden"
906            // by glob module bindings in the same module.
907            // FIXME: Remove with lang team approval.
908            let issue_149681_hack = match scope {
909                Scope::ModuleGlobs(m1, _)
910                    if innermost_results[1..]
911                        .iter()
912                        .any(|(_, s)| #[allow(non_exhaustive_omitted_patterns)] match *s {
    Scope::ModuleNonGlobs(m2, _) if m1 == m2 => true,
    _ => false,
}matches!(*s, Scope::ModuleNonGlobs(m2, _) if m1 == m2)) =>
913                {
914                    true
915                }
916                _ => false,
917            };
918
919            if issue_145575_hack || issue_149681_hack {
920                self.issue_145575_hack_applied = true;
921            } else {
922                // Turn ambiguity errors for core vs std panic into warnings.
923                // FIXME: Remove with lang team approval.
924                let is_issue_147319_hack = orig_ident_span.edition() <= Edition::Edition2024
925                    && #[allow(non_exhaustive_omitted_patterns)] match ident.name {
    sym::panic => true,
    _ => false,
}matches!(ident.name, sym::panic)
926                    && #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::StdLibPrelude => true,
    _ => false,
}matches!(scope, Scope::StdLibPrelude)
927                    && #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
    Scope::ModuleGlobs(_, _) => true,
    _ => false,
}matches!(innermost_scope, Scope::ModuleGlobs(_, _))
928                    && ((self.is_specific_builtin_macro(res, sym::std_panic)
929                        && self.is_specific_builtin_macro(innermost_res, sym::core_panic))
930                        || (self.is_specific_builtin_macro(res, sym::core_panic)
931                            && self.is_specific_builtin_macro(innermost_res, sym::std_panic)));
932
933                let warning = if ambig_vis.is_some() {
934                    Some(AmbiguityWarning::GlobImport)
935                } else if is_issue_147319_hack {
936                    Some(AmbiguityWarning::PanicImport)
937                } else {
938                    None
939                };
940
941                self.ambiguity_errors.push(AmbiguityError {
942                    kind,
943                    ambig_vis,
944                    ident: ident.orig(orig_ident_span),
945                    b1: innermost_decl,
946                    b2: decl,
947                    scope1: innermost_scope,
948                    scope2: scope,
949                    warning,
950                });
951                return true;
952            }
953        }
954
955        false
956    }
957
958    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("maybe_resolve_ident_in_module",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(958u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["module", "ident",
                                                    "ns", "parent_scope", "ignore_import"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&module)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ns)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<Decl<'ra>, Determinacy> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.resolve_ident_in_module(module, ident, ns, parent_scope,
                None, None, ignore_import)
        }
    }
}#[instrument(level = "debug", skip(self))]
959    pub(crate) fn maybe_resolve_ident_in_module<'r>(
960        self: CmResolver<'r, 'ra, 'tcx>,
961        module: ModuleOrUniformRoot<'ra>,
962        ident: Ident,
963        ns: Namespace,
964        parent_scope: &ParentScope<'ra>,
965        ignore_import: Option<Import<'ra>>,
966    ) -> Result<Decl<'ra>, Determinacy> {
967        self.resolve_ident_in_module(module, ident, ns, parent_scope, None, None, ignore_import)
968    }
969
970    fn resolve_super_in_module(
971        &self,
972        ident: Ident,
973        module: Option<Module<'ra>>,
974        parent_scope: &ParentScope<'ra>,
975    ) -> Option<Module<'ra>> {
976        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
977        module
978            .unwrap_or_else(|| self.resolve_self(&mut ctxt, parent_scope.module))
979            .parent
980            .map(|parent| self.resolve_self(&mut ctxt, parent))
981    }
982
983    pub(crate) fn path_root_is_crate_root(&self, ident: Ident) -> bool {
984        ident.name == kw::PathRoot && ident.span.is_rust_2015() && self.tcx.sess.is_rust_2015()
985    }
986
987    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("resolve_ident_in_module",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(987u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["module", "ident",
                                                    "ns", "parent_scope", "finalize", "ignore_decl",
                                                    "ignore_import"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&module)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ns)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_decl)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<Decl<'ra>, Determinacy> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            match module {
                ModuleOrUniformRoot::Module(module) => {
                    if ns == TypeNS {
                        if ident.name == kw::SelfLower {
                            return Ok(module.self_decl.unwrap());
                        }
                        if ident.name == kw::Super &&
                                let Some(module) =
                                    self.resolve_super_in_module(ident, Some(module),
                                        parent_scope) {
                            return Ok(module.self_decl.unwrap());
                        }
                    }
                    let (ident_key, def) =
                        IdentKey::new_adjusted(ident, module.expansion);
                    let adjusted_parent_scope =
                        match def {
                            Some(def) =>
                                ParentScope {
                                    module: self.expn_def_scope(def),
                                    ..*parent_scope
                                },
                            None => *parent_scope,
                        };
                    self.resolve_ident_in_scope_set_inner(ident_key, ident.span,
                        ScopeSet::Module(ns, module), &adjusted_parent_scope,
                        finalize, ignore_decl, ignore_import)
                }
                ModuleOrUniformRoot::OpenModule(sym) => {
                    let open_ns_name =
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("{0}::{1}", sym.as_str(),
                                        ident.name))
                            });
                    let ns_ident =
                        IdentKey::with_root_ctxt(Symbol::intern(&open_ns_name));
                    match self.extern_prelude_get_flag(ns_ident, ident.span,
                            finalize.is_some()) {
                        Some(decl) => Ok(decl),
                        None => Err(Determinacy::Determined),
                    }
                }
                ModuleOrUniformRoot::ModuleAndExternPrelude(module) =>
                    self.resolve_ident_in_scope_set(ident,
                        ScopeSet::ModuleAndExternPrelude(ns, module), parent_scope,
                        finalize, ignore_decl, ignore_import),
                ModuleOrUniformRoot::ExternPrelude => {
                    if ns != TypeNS {
                        Err(Determined)
                    } else {
                        self.resolve_ident_in_scope_set_inner(IdentKey::new_adjusted(ident,
                                    ExpnId::root()).0, ident.span, ScopeSet::ExternPrelude,
                            parent_scope, finalize, ignore_decl, ignore_import)
                    }
                }
                ModuleOrUniformRoot::CurrentScope => {
                    if ns == TypeNS {
                        if ident.name == kw::SelfLower {
                            let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
                            let module =
                                self.resolve_self(&mut ctxt, parent_scope.module);
                            return Ok(module.self_decl.unwrap());
                        }
                        if ident.name == kw::Super &&
                                let Some(module) =
                                    self.resolve_super_in_module(ident, None, parent_scope) {
                            return Ok(module.self_decl.unwrap());
                        }
                        if ident.name == kw::Crate || ident.name == kw::DollarCrate
                                || self.path_root_is_crate_root(ident) {
                            let module = self.resolve_crate_root(ident);
                            return Ok(module.self_decl.unwrap());
                        } else if ident.name == kw::Super {}
                    }
                    self.resolve_ident_in_scope_set(ident, ScopeSet::All(ns),
                        parent_scope, finalize, ignore_decl, ignore_import)
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
988    pub(crate) fn resolve_ident_in_module<'r>(
989        self: CmResolver<'r, 'ra, 'tcx>,
990        module: ModuleOrUniformRoot<'ra>,
991        ident: Ident,
992        ns: Namespace,
993        parent_scope: &ParentScope<'ra>,
994        finalize: Option<Finalize>,
995        ignore_decl: Option<Decl<'ra>>,
996        ignore_import: Option<Import<'ra>>,
997    ) -> Result<Decl<'ra>, Determinacy> {
998        match module {
999            ModuleOrUniformRoot::Module(module) => {
1000                if ns == TypeNS {
1001                    if ident.name == kw::SelfLower {
1002                        return Ok(module.self_decl.unwrap());
1003                    }
1004                    if ident.name == kw::Super
1005                        && let Some(module) =
1006                            self.resolve_super_in_module(ident, Some(module), parent_scope)
1007                    {
1008                        return Ok(module.self_decl.unwrap());
1009                    }
1010                }
1011
1012                let (ident_key, def) = IdentKey::new_adjusted(ident, module.expansion);
1013                let adjusted_parent_scope = match def {
1014                    Some(def) => ParentScope { module: self.expn_def_scope(def), ..*parent_scope },
1015                    None => *parent_scope,
1016                };
1017                self.resolve_ident_in_scope_set_inner(
1018                    ident_key,
1019                    ident.span,
1020                    ScopeSet::Module(ns, module),
1021                    &adjusted_parent_scope,
1022                    finalize,
1023                    ignore_decl,
1024                    ignore_import,
1025                )
1026            }
1027            ModuleOrUniformRoot::OpenModule(sym) => {
1028                let open_ns_name = format!("{}::{}", sym.as_str(), ident.name);
1029                let ns_ident = IdentKey::with_root_ctxt(Symbol::intern(&open_ns_name));
1030                match self.extern_prelude_get_flag(ns_ident, ident.span, finalize.is_some()) {
1031                    Some(decl) => Ok(decl),
1032                    None => Err(Determinacy::Determined),
1033                }
1034            }
1035            ModuleOrUniformRoot::ModuleAndExternPrelude(module) => self.resolve_ident_in_scope_set(
1036                ident,
1037                ScopeSet::ModuleAndExternPrelude(ns, module),
1038                parent_scope,
1039                finalize,
1040                ignore_decl,
1041                ignore_import,
1042            ),
1043            ModuleOrUniformRoot::ExternPrelude => {
1044                if ns != TypeNS {
1045                    Err(Determined)
1046                } else {
1047                    self.resolve_ident_in_scope_set_inner(
1048                        IdentKey::new_adjusted(ident, ExpnId::root()).0,
1049                        ident.span,
1050                        ScopeSet::ExternPrelude,
1051                        parent_scope,
1052                        finalize,
1053                        ignore_decl,
1054                        ignore_import,
1055                    )
1056                }
1057            }
1058            ModuleOrUniformRoot::CurrentScope => {
1059                if ns == TypeNS {
1060                    if ident.name == kw::SelfLower {
1061                        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1062                        let module = self.resolve_self(&mut ctxt, parent_scope.module);
1063                        return Ok(module.self_decl.unwrap());
1064                    }
1065                    if ident.name == kw::Super
1066                        && let Some(module) =
1067                            self.resolve_super_in_module(ident, None, parent_scope)
1068                    {
1069                        return Ok(module.self_decl.unwrap());
1070                    }
1071                    if ident.name == kw::Crate
1072                        || ident.name == kw::DollarCrate
1073                        || self.path_root_is_crate_root(ident)
1074                    {
1075                        let module = self.resolve_crate_root(ident);
1076                        return Ok(module.self_decl.unwrap());
1077                    } else if ident.name == kw::Super {
1078                        // FIXME: Implement these with renaming requirements so that e.g.
1079                        // `use super;` doesn't work, but `use super as name;` does.
1080                        // Fall through here to get an error from `early_resolve_...`.
1081                    }
1082                }
1083
1084                self.resolve_ident_in_scope_set(
1085                    ident,
1086                    ScopeSet::All(ns),
1087                    parent_scope,
1088                    finalize,
1089                    ignore_decl,
1090                    ignore_import,
1091                )
1092            }
1093        }
1094    }
1095
1096    /// Attempts to resolve `ident` in namespace `ns` of non-glob bindings in an external `module`.
1097    fn resolve_ident_in_extern_module_non_globs_unadjusted<'r>(
1098        mut self: CmResolver<'r, 'ra, 'tcx>,
1099        module: ExternModule<'ra>,
1100        ident: IdentKey,
1101        orig_ident_span: Span,
1102        ns: Namespace,
1103        parent_scope: &ParentScope<'ra>,
1104        shadowing: Shadowing,
1105        finalize: Option<Finalize>,
1106        // This binding should be ignored during in-module resolution, so that we don't get
1107        // "self-confirming" import resolutions during import validation and checking.
1108        ignore_decl: Option<Decl<'ra>>,
1109    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1110        let key = BindingKey::new(ident, ns);
1111        let resolution =
1112            &*self.resolution(module.to_module(), key).ok_or(ControlFlow::Continue(Determined))?;
1113
1114        let binding = resolution.non_glob_decl.filter(|b| Some(*b) != ignore_decl);
1115
1116        if let Some(finalize) = finalize {
1117            return self.get_mut().finalize_module_binding(
1118                ident,
1119                orig_ident_span,
1120                binding,
1121                parent_scope,
1122                finalize,
1123                shadowing,
1124            );
1125        }
1126
1127        // Items and single imports are not shadowable, if we have one, then it's determined.
1128        if let Some(binding) = binding {
1129            let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1130            return if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) };
1131        }
1132        Err(ControlFlow::Continue(Determined))
1133    }
1134
1135    /// Attempts to resolve `ident` in namespace `ns` of non-glob bindings in a local `module`.
1136    fn resolve_ident_in_local_module_non_globs_unadjusted<'r>(
1137        mut self: CmResolver<'r, 'ra, 'tcx>,
1138        module: LocalModule<'ra>,
1139        ident: IdentKey,
1140        orig_ident_span: Span,
1141        ns: Namespace,
1142        parent_scope: &ParentScope<'ra>,
1143        shadowing: Shadowing,
1144        finalize: Option<Finalize>,
1145        // This binding should be ignored during in-module resolution, so that we don't get
1146        // "self-confirming" import resolutions during import validation and checking.
1147        ignore_decl: Option<Decl<'ra>>,
1148        ignore_import: Option<Import<'ra>>,
1149    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1150        let key = BindingKey::new(ident, ns);
1151        // `try_borrow_mut` is required to ensure exclusive access, even if the resulting binding
1152        // doesn't need to be mutable. It will fail when there is a cycle of imports, and without
1153        // the exclusive access infinite recursion will crash the compiler with stack overflow.
1154        let resolution = &*self
1155            .resolution_or_default(module.to_module(), key, orig_ident_span)
1156            .try_borrow_mut_unchecked()
1157            .map_err(|_| ControlFlow::Continue(Determined))?;
1158
1159        let binding = resolution.non_glob_decl.filter(|b| Some(*b) != ignore_decl);
1160
1161        if let Some(finalize) = finalize {
1162            return self.get_mut().finalize_module_binding(
1163                ident,
1164                orig_ident_span,
1165                binding,
1166                parent_scope,
1167                finalize,
1168                shadowing,
1169            );
1170        }
1171
1172        // Items and single imports are not shadowable, if we have one, then it's determined.
1173        if let Some(binding) = binding {
1174            let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1175            return if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) };
1176        }
1177
1178        // Check if one of single imports can still define the name, block if it can.
1179        if self.reborrow().single_import_can_define_name(
1180            &resolution,
1181            None,
1182            ns,
1183            ignore_import,
1184            ignore_decl,
1185            parent_scope,
1186        ) {
1187            return Err(ControlFlow::Break(Undetermined));
1188        }
1189
1190        // Check if one of unexpanded macros can still define the name.
1191        if module.has_unexpanded_invocations() {
1192            return Err(ControlFlow::Continue(Undetermined));
1193        }
1194
1195        // No resolution and no one else can define the name - determinate error.
1196        Err(ControlFlow::Continue(Determined))
1197    }
1198
1199    /// Attempts to resolve `ident` in namespace `ns` of glob bindings in `module`.
1200    fn resolve_ident_in_module_globs_unadjusted<'r>(
1201        mut self: CmResolver<'r, 'ra, 'tcx>,
1202        module: LocalModule<'ra>,
1203        ident: IdentKey,
1204        orig_ident_span: Span,
1205        ns: Namespace,
1206        parent_scope: &ParentScope<'ra>,
1207        shadowing: Shadowing,
1208        finalize: Option<Finalize>,
1209        ignore_decl: Option<Decl<'ra>>,
1210        ignore_import: Option<Import<'ra>>,
1211    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1212        let key = BindingKey::new(ident, ns);
1213        // `try_borrow_mut` is required to ensure exclusive access, even if the resulting binding
1214        // doesn't need to be mutable. It will fail when there is a cycle of imports, and without
1215        // the exclusive access infinite recursion will crash the compiler with stack overflow.
1216        let resolution = &*self
1217            .resolution_or_default(module.to_module(), key, orig_ident_span)
1218            .try_borrow_mut_unchecked()
1219            .map_err(|_| ControlFlow::Continue(Determined))?;
1220
1221        let binding = resolution.glob_decl.filter(|b| Some(*b) != ignore_decl);
1222
1223        if let Some(finalize) = finalize {
1224            return self.get_mut().finalize_module_binding(
1225                ident,
1226                orig_ident_span,
1227                binding,
1228                parent_scope,
1229                finalize,
1230                shadowing,
1231            );
1232        }
1233
1234        // Check if one of single imports can still define the name,
1235        // if it can then our result is not determined and can be invalidated.
1236        if self.reborrow().single_import_can_define_name(
1237            &resolution,
1238            binding,
1239            ns,
1240            ignore_import,
1241            ignore_decl,
1242            parent_scope,
1243        ) {
1244            return Err(ControlFlow::Break(Undetermined));
1245        }
1246
1247        // So we have a resolution that's from a glob import. This resolution is determined
1248        // if it cannot be shadowed by some new item/import expanded from a macro.
1249        // This happens either if there are no unexpanded macros, or expanded names cannot
1250        // shadow globs (that happens in macro namespace or with restricted shadowing).
1251        //
1252        // Additionally, any macro in any module can plant names in the root module if it creates
1253        // `macro_export` macros, so the root module effectively has unresolved invocations if any
1254        // module has unresolved invocations.
1255        // However, it causes resolution/expansion to stuck too often (#53144), so, to make
1256        // progress, we have to ignore those potential unresolved invocations from other modules
1257        // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
1258        // shadowing is enabled, see `macro_expanded_macro_export_errors`).
1259        if let Some(binding) = binding {
1260            return if binding.determined() || ns == MacroNS || shadowing == Shadowing::Restricted {
1261                let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1262                if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) }
1263            } else {
1264                Err(ControlFlow::Break(Undetermined))
1265            };
1266        }
1267
1268        // Now we are in situation when new item/import can appear only from a glob or a macro
1269        // expansion. With restricted shadowing names from globs and macro expansions cannot
1270        // shadow names from outer scopes, so we can freely fallback from module search to search
1271        // in outer scopes. For `resolve_ident_in_scope_set` to continue search in outer
1272        // scopes we return `Undetermined` with `ControlFlow::Continue`.
1273        // Check if one of unexpanded macros can still define the name,
1274        // if it can then our "no resolution" result is not determined and can be invalidated.
1275        if module.has_unexpanded_invocations() {
1276            return Err(ControlFlow::Continue(Undetermined));
1277        }
1278
1279        // Check if one of glob imports can still define the name,
1280        // if it can then our "no resolution" result is not determined and can be invalidated.
1281        for glob_import in module.globs.borrow().iter() {
1282            if ignore_import == Some(*glob_import) {
1283                continue;
1284            }
1285            if !self.is_accessible_from(glob_import.vis, parent_scope.module) {
1286                continue;
1287            }
1288            let module = match glob_import.imported_module.get() {
1289                Some(ModuleOrUniformRoot::Module(module)) => module,
1290                Some(_) => continue,
1291                None => return Err(ControlFlow::Continue(Undetermined)),
1292            };
1293            let tmp_parent_scope;
1294            let (mut adjusted_parent_scope, mut adjusted_ident) = (parent_scope, ident);
1295            match adjusted_ident
1296                .ctxt
1297                .update_unchecked(|ctxt| ctxt.glob_adjust(module.expansion, glob_import.span))
1298            {
1299                Some(Some(def)) => {
1300                    tmp_parent_scope =
1301                        ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
1302                    adjusted_parent_scope = &tmp_parent_scope;
1303                }
1304                Some(None) => {}
1305                None => continue,
1306            };
1307            let result = self.reborrow().resolve_ident_in_scope_set_inner(
1308                adjusted_ident,
1309                orig_ident_span,
1310                ScopeSet::Module(ns, module),
1311                adjusted_parent_scope,
1312                None,
1313                ignore_decl,
1314                ignore_import,
1315            );
1316
1317            match result {
1318                Err(Determined) => continue,
1319                Ok(binding)
1320                    if !self.is_accessible_from(binding.vis(), glob_import.parent_scope.module) =>
1321                {
1322                    continue;
1323                }
1324                Ok(_) | Err(Undetermined) => return Err(ControlFlow::Continue(Undetermined)),
1325            }
1326        }
1327
1328        // No resolution and no one else can define the name - determinate error.
1329        Err(ControlFlow::Continue(Determined))
1330    }
1331
1332    fn finalize_module_binding(
1333        &mut self,
1334        ident: IdentKey,
1335        orig_ident_span: Span,
1336        binding: Option<Decl<'ra>>,
1337        parent_scope: &ParentScope<'ra>,
1338        finalize: Finalize,
1339        shadowing: Shadowing,
1340    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1341        let Finalize { path_span, report_private, used, root_span, .. } = finalize;
1342
1343        let Some(binding) = binding else {
1344            return Err(ControlFlow::Continue(Determined));
1345        };
1346
1347        let ident = ident.orig(orig_ident_span);
1348        if !self.is_accessible_from(binding.vis(), parent_scope.module) {
1349            if report_private {
1350                self.privacy_errors.push(PrivacyError {
1351                    ident,
1352                    decl: binding,
1353                    dedup_span: path_span,
1354                    outermost_res: None,
1355                    source: None,
1356                    parent_scope: *parent_scope,
1357                    single_nested: path_span != root_span,
1358                });
1359            } else {
1360                return Err(ControlFlow::Break(Determined));
1361            }
1362        }
1363
1364        if shadowing == Shadowing::Unrestricted
1365            && binding.expansion != LocalExpnId::ROOT
1366            && let DeclKind::Import { import, .. } = binding.kind
1367            && #[allow(non_exhaustive_omitted_patterns)] match import.kind {
    ImportKind::MacroExport => true,
    _ => false,
}matches!(import.kind, ImportKind::MacroExport)
1368        {
1369            self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
1370        }
1371
1372        self.record_use(ident, binding, used);
1373        return Ok(binding);
1374    }
1375
1376    // Checks if a single import can define the `Ident` corresponding to `binding`.
1377    // This is used to check whether we can definitively accept a glob as a resolution.
1378    fn single_import_can_define_name<'r>(
1379        mut self: CmResolver<'r, 'ra, 'tcx>,
1380        resolution: &NameResolution<'ra>,
1381        binding: Option<Decl<'ra>>,
1382        ns: Namespace,
1383        ignore_import: Option<Import<'ra>>,
1384        ignore_decl: Option<Decl<'ra>>,
1385        parent_scope: &ParentScope<'ra>,
1386    ) -> bool {
1387        for single_import in &resolution.single_imports {
1388            if let Some(decl) = resolution.non_glob_decl
1389                && let DeclKind::Import { import, .. } = decl.kind
1390                && import == *single_import
1391            {
1392                // Single import has already defined the name and we are aware of it,
1393                // no need to block the globs.
1394                continue;
1395            }
1396            if ignore_import == Some(*single_import) {
1397                continue;
1398            }
1399            if !self.is_accessible_from(single_import.vis, parent_scope.module) {
1400                continue;
1401            }
1402            if let Some(ignored) = ignore_decl
1403                && let DeclKind::Import { import, .. } = ignored.kind
1404                && import == *single_import
1405            {
1406                continue;
1407            }
1408
1409            let Some(module) = single_import.imported_module.get() else {
1410                return true;
1411            };
1412            let ImportKind::Single { source, target, decls, .. } = &single_import.kind else {
1413                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1414            };
1415            if source != target {
1416                if decls.iter().all(|d| d.get().decl().is_none()) {
1417                    return true;
1418                } else if decls[ns].get().decl().is_none() && binding.is_some() {
1419                    return true;
1420                }
1421            }
1422
1423            match self.reborrow().resolve_ident_in_module(
1424                module,
1425                *source,
1426                ns,
1427                &single_import.parent_scope,
1428                None,
1429                ignore_decl,
1430                None,
1431            ) {
1432                Err(Determined) => continue,
1433                Ok(binding)
1434                    if !self
1435                        .is_accessible_from(binding.vis(), single_import.parent_scope.module) =>
1436                {
1437                    continue;
1438                }
1439                Ok(_) | Err(Undetermined) => return true,
1440            }
1441        }
1442
1443        false
1444    }
1445
1446    /// Validate a local resolution (from ribs).
1447    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("validate_res_from_ribs",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1447u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["rib_index",
                                                    "rib_ident", "res", "finalize", "original_rib_ident_def",
                                                    "diag_metadata"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&rib_index as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rib_ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&original_rib_ident_def)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_metadata)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Res = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                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/ident.rs:1458",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1458u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::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!("validate_res_from_ribs({0:?})",
                                                                res) as &dyn Value))])
                        });
                } else { ; }
            };
            let ribs = &all_ribs[rib_index + 1..];
            if let RibKind::ForwardGenericParamBan(reason) =
                    all_ribs[rib_index].kind {
                if let Some(span) = finalize {
                    let res_error =
                        if rib_ident.name == kw::SelfUpper {
                            ResolutionError::ForwardDeclaredSelf(reason)
                        } else {
                            ResolutionError::ForwardDeclaredGenericParam(rib_ident.name,
                                reason)
                        };
                    self.report_error(span, res_error);
                }
                {
                    match (&res, &Res::Err) {
                        (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);
                            }
                        }
                    }
                };
                return Res::Err;
            }
            match res {
                Res::Local(_) => {
                    use ResolutionError::*;
                    let mut res_err = None;
                    for rib in ribs {
                        match rib.kind {
                            RibKind::Normal | RibKind::Block(..) |
                                RibKind::FnOrCoroutine | RibKind::Module(..) |
                                RibKind::MacroDefinition(..) |
                                RibKind::ForwardGenericParamBan(_) => {}
                            RibKind::Item(..) | RibKind::AssocItem => {
                                if let Some(span) = finalize {
                                    res_err =
                                        Some((span, CannotCaptureDynamicEnvironmentInFnItem));
                                }
                            }
                            RibKind::ConstantItem(_, item) => {
                                if let Some(span) = finalize {
                                    let (span, resolution_error) =
                                        match item {
                                            None if rib_ident.name == kw::SelfLower => {
                                                (span, LowercaseSelf)
                                            }
                                            None => {
                                                let sm = self.tcx.sess.source_map();
                                                let type_span =
                                                    match sm.span_followed_by(original_rib_ident_def.span, ":")
                                                        {
                                                        None => { Some(original_rib_ident_def.span.shrink_to_hi()) }
                                                        Some(_) => None,
                                                    };
                                                (rib_ident.span,
                                                    AttemptToUseNonConstantValueInConstant {
                                                        ident: original_rib_ident_def,
                                                        suggestion: "const",
                                                        current: "let",
                                                        type_span,
                                                    })
                                            }
                                            Some((ident, kind)) =>
                                                (span,
                                                    AttemptToUseNonConstantValueInConstant {
                                                        ident,
                                                        suggestion: "let",
                                                        current: kind.as_str(),
                                                        type_span: None,
                                                    }),
                                        };
                                    self.report_error(span, resolution_error);
                                }
                                return Res::Err;
                            }
                            RibKind::ConstParamTy => {
                                if let Some(span) = finalize {
                                    self.report_error(span,
                                        ParamInTyOfConstParam { name: rib_ident.name });
                                }
                                return Res::Err;
                            }
                            RibKind::InlineAsmSym => {
                                if let Some(span) = finalize {
                                    self.report_error(span, InvalidAsmSym);
                                }
                                return Res::Err;
                            }
                        }
                    }
                    if let Some((span, res_err)) = res_err {
                        self.report_error(span, res_err);
                        return Res::Err;
                    }
                }
                Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } |
                    Res::SelfTyAlias { .. } => {
                    for rib in ribs {
                        let (has_generic_params, def_kind) =
                            match rib.kind {
                                RibKind::Normal | RibKind::Block(..) |
                                    RibKind::FnOrCoroutine | RibKind::Module(..) |
                                    RibKind::MacroDefinition(..) | RibKind::InlineAsmSym |
                                    RibKind::AssocItem | RibKind::ForwardGenericParamBan(_) => {
                                    continue;
                                }
                                RibKind::ConstParamTy => {
                                    if !self.features.generic_const_parameter_types() {
                                        if let Some(span) = finalize {
                                            self.report_error(span,
                                                ResolutionError::ParamInTyOfConstParam {
                                                    name: rib_ident.name,
                                                });
                                        }
                                        return Res::Err;
                                    } else { continue; }
                                }
                                RibKind::ConstantItem(trivial, _) => {
                                    if let ConstantHasGenerics::No(cause) = trivial &&
                                            !#[allow(non_exhaustive_omitted_patterns)] match res {
                                                    Res::SelfTyAlias { .. } => true,
                                                    _ => false,
                                                } {
                                        if let Some(span) = finalize {
                                            let error =
                                                match cause {
                                                    NoConstantGenericsReason::IsEnumDiscriminant => {
                                                        ResolutionError::ParamInEnumDiscriminant {
                                                            name: rib_ident.name,
                                                            param_kind: ParamKindInEnumDiscriminant::Type,
                                                        }
                                                    }
                                                    NoConstantGenericsReason::NonTrivialConstArg => {
                                                        ResolutionError::ParamInNonTrivialAnonConst {
                                                            is_gca: self.features.generic_const_args(),
                                                            name: rib_ident.name,
                                                            param_kind: ParamKindInNonTrivialAnonConst::Type,
                                                        }
                                                    }
                                                };
                                            let _: ErrorGuaranteed = self.report_error(span, error);
                                        }
                                        return Res::Err;
                                    }
                                    continue;
                                }
                                RibKind::Item(has_generic_params, def_kind) => {
                                    (has_generic_params, def_kind)
                                }
                            };
                        if let Some(span) = finalize {
                            let item =
                                if let Some(diag_metadata) = diag_metadata &&
                                        let Some(current_item) = diag_metadata.current_item {
                                    let label_span =
                                        current_item.kind.ident().map(|i|
                                                    i.span).unwrap_or(current_item.span);
                                    Some((label_span, current_item.span,
                                            current_item.kind.clone()))
                                } else { None };
                            self.report_error(span,
                                ResolutionError::GenericParamsFromOuterItem {
                                    outer_res: res,
                                    has_generic_params,
                                    def_kind,
                                    inner_item: item,
                                    current_self_ty: diag_metadata.and_then(|m|
                                                m.current_self_type.as_ref()).and_then(|ty|
                                            {
                                                self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
                                            }),
                                });
                        }
                        return Res::Err;
                    }
                }
                Res::Def(DefKind::ConstParam, _) => {
                    for rib in ribs {
                        let (has_generic_params, def_kind) =
                            match rib.kind {
                                RibKind::Normal | RibKind::Block(..) |
                                    RibKind::FnOrCoroutine | RibKind::Module(..) |
                                    RibKind::MacroDefinition(..) | RibKind::InlineAsmSym |
                                    RibKind::AssocItem | RibKind::ForwardGenericParamBan(_) =>
                                    continue,
                                RibKind::ConstParamTy => {
                                    if !self.features.generic_const_parameter_types() {
                                        if let Some(span) = finalize {
                                            self.report_error(span,
                                                ResolutionError::ParamInTyOfConstParam {
                                                    name: rib_ident.name,
                                                });
                                        }
                                        return Res::Err;
                                    } else { continue; }
                                }
                                RibKind::ConstantItem(trivial, _) => {
                                    if let ConstantHasGenerics::No(cause) = trivial {
                                        if let Some(span) = finalize {
                                            let error =
                                                match cause {
                                                    NoConstantGenericsReason::IsEnumDiscriminant => {
                                                        ResolutionError::ParamInEnumDiscriminant {
                                                            name: rib_ident.name,
                                                            param_kind: ParamKindInEnumDiscriminant::Const,
                                                        }
                                                    }
                                                    NoConstantGenericsReason::NonTrivialConstArg => {
                                                        ResolutionError::ParamInNonTrivialAnonConst {
                                                            is_gca: self.features.generic_const_args(),
                                                            name: rib_ident.name,
                                                            param_kind: ParamKindInNonTrivialAnonConst::Const {
                                                                name: rib_ident.name,
                                                            },
                                                        }
                                                    }
                                                };
                                            self.report_error(span, error);
                                        }
                                        return Res::Err;
                                    }
                                    continue;
                                }
                                RibKind::Item(has_generic_params, def_kind) => {
                                    (has_generic_params, def_kind)
                                }
                            };
                        if let Some(span) = finalize {
                            let item =
                                if let Some(diag_metadata) = diag_metadata &&
                                        let Some(current_item) = diag_metadata.current_item {
                                    let label_span =
                                        current_item.kind.ident().map(|i|
                                                    i.span).unwrap_or(current_item.span);
                                    Some((label_span, current_item.span,
                                            current_item.kind.clone()))
                                } else { None };
                            self.report_error(span,
                                ResolutionError::GenericParamsFromOuterItem {
                                    outer_res: res,
                                    has_generic_params,
                                    def_kind,
                                    inner_item: item,
                                    current_self_ty: diag_metadata.and_then(|m|
                                                m.current_self_type.as_ref()).and_then(|ty|
                                            {
                                                self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
                                            }),
                                });
                        }
                        return Res::Err;
                    }
                }
                _ => {}
            }
            res
        }
    }
}#[instrument(level = "debug", skip(self, all_ribs))]
1448    fn validate_res_from_ribs(
1449        &mut self,
1450        rib_index: usize,
1451        rib_ident: Ident,
1452        res: Res,
1453        finalize: Option<Span>,
1454        original_rib_ident_def: Ident,
1455        all_ribs: &[Rib<'ra>],
1456        diag_metadata: Option<&DiagMetadata<'_>>,
1457    ) -> Res {
1458        debug!("validate_res_from_ribs({:?})", res);
1459        let ribs = &all_ribs[rib_index + 1..];
1460
1461        // An invalid forward use of a generic parameter from a previous default
1462        // or in a const param ty.
1463        if let RibKind::ForwardGenericParamBan(reason) = all_ribs[rib_index].kind {
1464            if let Some(span) = finalize {
1465                let res_error = if rib_ident.name == kw::SelfUpper {
1466                    ResolutionError::ForwardDeclaredSelf(reason)
1467                } else {
1468                    ResolutionError::ForwardDeclaredGenericParam(rib_ident.name, reason)
1469                };
1470                self.report_error(span, res_error);
1471            }
1472            assert_eq!(res, Res::Err);
1473            return Res::Err;
1474        }
1475
1476        match res {
1477            Res::Local(_) => {
1478                use ResolutionError::*;
1479                let mut res_err = None;
1480
1481                for rib in ribs {
1482                    match rib.kind {
1483                        RibKind::Normal
1484                        | RibKind::Block(..)
1485                        | RibKind::FnOrCoroutine
1486                        | RibKind::Module(..)
1487                        | RibKind::MacroDefinition(..)
1488                        | RibKind::ForwardGenericParamBan(_) => {
1489                            // Nothing to do. Continue.
1490                        }
1491                        RibKind::Item(..) | RibKind::AssocItem => {
1492                            // This was an attempt to access an upvar inside a
1493                            // named function item. This is not allowed, so we
1494                            // report an error.
1495                            if let Some(span) = finalize {
1496                                // We don't immediately trigger a resolve error, because
1497                                // we want certain other resolution errors (namely those
1498                                // emitted for `ConstantItemRibKind` below) to take
1499                                // precedence.
1500                                res_err = Some((span, CannotCaptureDynamicEnvironmentInFnItem));
1501                            }
1502                        }
1503                        RibKind::ConstantItem(_, item) => {
1504                            // Still doesn't deal with upvars
1505                            if let Some(span) = finalize {
1506                                let (span, resolution_error) = match item {
1507                                    None if rib_ident.name == kw::SelfLower => {
1508                                        (span, LowercaseSelf)
1509                                    }
1510                                    None => {
1511                                        // If we have a `let name = expr;`, we have the span for
1512                                        // `name` and use that to see if it is followed by a type
1513                                        // specifier. If not, then we know we need to suggest
1514                                        // `const name: Ty = expr;`. This is a heuristic, it will
1515                                        // break down in the presence of macros.
1516                                        let sm = self.tcx.sess.source_map();
1517                                        let type_span = match sm
1518                                            .span_followed_by(original_rib_ident_def.span, ":")
1519                                        {
1520                                            None => {
1521                                                Some(original_rib_ident_def.span.shrink_to_hi())
1522                                            }
1523                                            Some(_) => None,
1524                                        };
1525                                        (
1526                                            rib_ident.span,
1527                                            AttemptToUseNonConstantValueInConstant {
1528                                                ident: original_rib_ident_def,
1529                                                suggestion: "const",
1530                                                current: "let",
1531                                                type_span,
1532                                            },
1533                                        )
1534                                    }
1535                                    Some((ident, kind)) => (
1536                                        span,
1537                                        AttemptToUseNonConstantValueInConstant {
1538                                            ident,
1539                                            suggestion: "let",
1540                                            current: kind.as_str(),
1541                                            type_span: None,
1542                                        },
1543                                    ),
1544                                };
1545                                self.report_error(span, resolution_error);
1546                            }
1547                            return Res::Err;
1548                        }
1549                        RibKind::ConstParamTy => {
1550                            if let Some(span) = finalize {
1551                                self.report_error(
1552                                    span,
1553                                    ParamInTyOfConstParam { name: rib_ident.name },
1554                                );
1555                            }
1556                            return Res::Err;
1557                        }
1558                        RibKind::InlineAsmSym => {
1559                            if let Some(span) = finalize {
1560                                self.report_error(span, InvalidAsmSym);
1561                            }
1562                            return Res::Err;
1563                        }
1564                    }
1565                }
1566                if let Some((span, res_err)) = res_err {
1567                    self.report_error(span, res_err);
1568                    return Res::Err;
1569                }
1570            }
1571            Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {
1572                for rib in ribs {
1573                    let (has_generic_params, def_kind) = match rib.kind {
1574                        RibKind::Normal
1575                        | RibKind::Block(..)
1576                        | RibKind::FnOrCoroutine
1577                        | RibKind::Module(..)
1578                        | RibKind::MacroDefinition(..)
1579                        | RibKind::InlineAsmSym
1580                        | RibKind::AssocItem
1581                        | RibKind::ForwardGenericParamBan(_) => {
1582                            // Nothing to do. Continue.
1583                            continue;
1584                        }
1585
1586                        RibKind::ConstParamTy => {
1587                            if !self.features.generic_const_parameter_types() {
1588                                if let Some(span) = finalize {
1589                                    self.report_error(
1590                                        span,
1591                                        ResolutionError::ParamInTyOfConstParam {
1592                                            name: rib_ident.name,
1593                                        },
1594                                    );
1595                                }
1596                                return Res::Err;
1597                            } else {
1598                                continue;
1599                            }
1600                        }
1601
1602                        RibKind::ConstantItem(trivial, _) => {
1603                            if let ConstantHasGenerics::No(cause) = trivial
1604                                && !matches!(res, Res::SelfTyAlias { .. })
1605                            {
1606                                if let Some(span) = finalize {
1607                                    let error = match cause {
1608                                        NoConstantGenericsReason::IsEnumDiscriminant => {
1609                                            ResolutionError::ParamInEnumDiscriminant {
1610                                                name: rib_ident.name,
1611                                                param_kind: ParamKindInEnumDiscriminant::Type,
1612                                            }
1613                                        }
1614                                        NoConstantGenericsReason::NonTrivialConstArg => {
1615                                            ResolutionError::ParamInNonTrivialAnonConst {
1616                                                is_gca: self.features.generic_const_args(),
1617                                                name: rib_ident.name,
1618                                                param_kind: ParamKindInNonTrivialAnonConst::Type,
1619                                            }
1620                                        }
1621                                    };
1622                                    let _: ErrorGuaranteed = self.report_error(span, error);
1623                                }
1624
1625                                return Res::Err;
1626                            }
1627
1628                            continue;
1629                        }
1630
1631                        // This was an attempt to use a type parameter outside its scope.
1632                        RibKind::Item(has_generic_params, def_kind) => {
1633                            (has_generic_params, def_kind)
1634                        }
1635                    };
1636
1637                    if let Some(span) = finalize {
1638                        let item = if let Some(diag_metadata) = diag_metadata
1639                            && let Some(current_item) = diag_metadata.current_item
1640                        {
1641                            let label_span = current_item
1642                                .kind
1643                                .ident()
1644                                .map(|i| i.span)
1645                                .unwrap_or(current_item.span);
1646                            Some((label_span, current_item.span, current_item.kind.clone()))
1647                        } else {
1648                            None
1649                        };
1650                        self.report_error(
1651                            span,
1652                            ResolutionError::GenericParamsFromOuterItem {
1653                                outer_res: res,
1654                                has_generic_params,
1655                                def_kind,
1656                                inner_item: item,
1657                                current_self_ty: diag_metadata
1658                                    .and_then(|m| m.current_self_type.as_ref())
1659                                    .and_then(|ty| {
1660                                        self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1661                                    }),
1662                            },
1663                        );
1664                    }
1665                    return Res::Err;
1666                }
1667            }
1668            Res::Def(DefKind::ConstParam, _) => {
1669                for rib in ribs {
1670                    let (has_generic_params, def_kind) = match rib.kind {
1671                        RibKind::Normal
1672                        | RibKind::Block(..)
1673                        | RibKind::FnOrCoroutine
1674                        | RibKind::Module(..)
1675                        | RibKind::MacroDefinition(..)
1676                        | RibKind::InlineAsmSym
1677                        | RibKind::AssocItem
1678                        | RibKind::ForwardGenericParamBan(_) => continue,
1679
1680                        RibKind::ConstParamTy => {
1681                            if !self.features.generic_const_parameter_types() {
1682                                if let Some(span) = finalize {
1683                                    self.report_error(
1684                                        span,
1685                                        ResolutionError::ParamInTyOfConstParam {
1686                                            name: rib_ident.name,
1687                                        },
1688                                    );
1689                                }
1690                                return Res::Err;
1691                            } else {
1692                                continue;
1693                            }
1694                        }
1695
1696                        RibKind::ConstantItem(trivial, _) => {
1697                            if let ConstantHasGenerics::No(cause) = trivial {
1698                                if let Some(span) = finalize {
1699                                    let error = match cause {
1700                                        NoConstantGenericsReason::IsEnumDiscriminant => {
1701                                            ResolutionError::ParamInEnumDiscriminant {
1702                                                name: rib_ident.name,
1703                                                param_kind: ParamKindInEnumDiscriminant::Const,
1704                                            }
1705                                        }
1706                                        NoConstantGenericsReason::NonTrivialConstArg => {
1707                                            ResolutionError::ParamInNonTrivialAnonConst {
1708                                                is_gca: self.features.generic_const_args(),
1709                                                name: rib_ident.name,
1710                                                param_kind: ParamKindInNonTrivialAnonConst::Const {
1711                                                    name: rib_ident.name,
1712                                                },
1713                                            }
1714                                        }
1715                                    };
1716                                    self.report_error(span, error);
1717                                }
1718
1719                                return Res::Err;
1720                            }
1721
1722                            continue;
1723                        }
1724
1725                        RibKind::Item(has_generic_params, def_kind) => {
1726                            (has_generic_params, def_kind)
1727                        }
1728                    };
1729
1730                    // This was an attempt to use a const parameter outside its scope.
1731                    if let Some(span) = finalize {
1732                        let item = if let Some(diag_metadata) = diag_metadata
1733                            && let Some(current_item) = diag_metadata.current_item
1734                        {
1735                            let label_span = current_item
1736                                .kind
1737                                .ident()
1738                                .map(|i| i.span)
1739                                .unwrap_or(current_item.span);
1740                            Some((label_span, current_item.span, current_item.kind.clone()))
1741                        } else {
1742                            None
1743                        };
1744                        self.report_error(
1745                            span,
1746                            ResolutionError::GenericParamsFromOuterItem {
1747                                outer_res: res,
1748                                has_generic_params,
1749                                def_kind,
1750                                inner_item: item,
1751                                current_self_ty: diag_metadata
1752                                    .and_then(|m| m.current_self_type.as_ref())
1753                                    .and_then(|ty| {
1754                                        self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1755                                    }),
1756                            },
1757                        );
1758                    }
1759                    return Res::Err;
1760                }
1761            }
1762            _ => {}
1763        }
1764
1765        res
1766    }
1767
1768    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("maybe_resolve_path",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1768u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["path", "opt_ns",
                                                    "parent_scope", "ignore_import"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&opt_ns)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: PathResult<'ra> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.resolve_path_with_ribs(path, opt_ns, parent_scope, None,
                None, None, None, ignore_import, None)
        }
    }
}#[instrument(level = "debug", skip(self))]
1769    pub(crate) fn maybe_resolve_path<'r>(
1770        self: CmResolver<'r, 'ra, 'tcx>,
1771        path: &[Segment],
1772        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1773        parent_scope: &ParentScope<'ra>,
1774        ignore_import: Option<Import<'ra>>,
1775    ) -> PathResult<'ra> {
1776        self.resolve_path_with_ribs(
1777            path,
1778            opt_ns,
1779            parent_scope,
1780            None,
1781            None,
1782            None,
1783            None,
1784            ignore_import,
1785            None,
1786        )
1787    }
1788    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("resolve_path",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1788u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["path", "opt_ns",
                                                    "parent_scope", "finalize", "ignore_decl", "ignore_import"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&opt_ns)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_decl)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: PathResult<'ra> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.resolve_path_with_ribs(path, opt_ns, parent_scope, None,
                finalize, None, ignore_decl, ignore_import, None)
        }
    }
}#[instrument(level = "debug", skip(self))]
1789    pub(crate) fn resolve_path<'r>(
1790        self: CmResolver<'r, 'ra, 'tcx>,
1791        path: &[Segment],
1792        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1793        parent_scope: &ParentScope<'ra>,
1794        finalize: Option<Finalize>,
1795        ignore_decl: Option<Decl<'ra>>,
1796        ignore_import: Option<Import<'ra>>,
1797    ) -> PathResult<'ra> {
1798        self.resolve_path_with_ribs(
1799            path,
1800            opt_ns,
1801            parent_scope,
1802            None,
1803            finalize,
1804            None,
1805            ignore_decl,
1806            ignore_import,
1807            None,
1808        )
1809    }
1810
1811    pub(crate) fn resolve_path_with_ribs<'r>(
1812        mut self: CmResolver<'r, 'ra, 'tcx>,
1813        path: &[Segment],
1814        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1815        parent_scope: &ParentScope<'ra>,
1816        source: Option<PathSource<'_, '_, '_>>,
1817        finalize: Option<Finalize>,
1818        ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
1819        ignore_decl: Option<Decl<'ra>>,
1820        ignore_import: Option<Import<'ra>>,
1821        diag_metadata: Option<&DiagMetadata<'_>>,
1822    ) -> PathResult<'ra> {
1823        let mut module = None;
1824        let mut module_had_parse_errors = !self.mods_with_parse_errors.is_empty()
1825            && self.mods_with_parse_errors.contains(&parent_scope.module.nearest_parent_mod());
1826        let mut allow_super = true;
1827        let mut second_binding = None;
1828
1829        // We'll provide more context to the privacy errors later, up to `len`.
1830        let privacy_errors_len = self.privacy_errors.len();
1831        fn record_segment_res<'r, 'ra, 'tcx>(
1832            mut this: CmResolver<'r, 'ra, 'tcx>,
1833            finalize: Option<Finalize>,
1834            res: Res,
1835            id: Option<NodeId>,
1836        ) {
1837            if finalize.is_some()
1838                && let Some(id) = id
1839                && !this.partial_res_map.contains_key(&id)
1840            {
1841                if !(id != ast::DUMMY_NODE_ID) {
    {
        ::core::panicking::panic_fmt(format_args!("Trying to resolve dummy id"));
    }
};assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
1842                this.get_mut().record_partial_res(id, PartialRes::new(res));
1843            }
1844        }
1845
1846        for (segment_idx, &Segment { ident, id, .. }) in path.iter().enumerate() {
1847            {
    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/ident.rs:1847",
                        "rustc_resolve::ident", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                        ::tracing_core::__macro_support::Option::Some(1847u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                        ::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_path ident {0} {1:?} {2:?}",
                                                    segment_idx, ident, id) as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_path ident {} {:?} {:?}", segment_idx, ident, id);
1848
1849            let is_last = segment_idx + 1 == path.len();
1850            let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1851            let name = ident.name;
1852
1853            allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super);
1854
1855            if ns == TypeNS {
1856                if allow_super && name == kw::Super {
1857                    let parent = if segment_idx == 0 {
1858                        self.resolve_super_in_module(ident, None, parent_scope)
1859                    } else if let Some(ModuleOrUniformRoot::Module(module)) = module {
1860                        self.resolve_super_in_module(ident, Some(module), parent_scope)
1861                    } else {
1862                        None
1863                    };
1864                    if let Some(parent) = parent {
1865                        module = Some(ModuleOrUniformRoot::Module(parent));
1866                        continue;
1867                    }
1868                    return PathResult::failed(
1869                        ident,
1870                        false,
1871                        finalize.is_some(),
1872                        module_had_parse_errors,
1873                        module,
1874                        || {
1875                            (
1876                                "too many leading `super` keywords".to_string(),
1877                                "there are too many leading `super` keywords".to_string(),
1878                                None,
1879                                None,
1880                            )
1881                        },
1882                    );
1883                }
1884                if segment_idx == 0 {
1885                    if name == kw::SelfLower {
1886                        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1887                        let self_mod = self.resolve_self(&mut ctxt, parent_scope.module);
1888                        if let Some(res) = self_mod.res() {
1889                            record_segment_res(self.reborrow(), finalize, res, id);
1890                        }
1891                        module = Some(ModuleOrUniformRoot::Module(self_mod));
1892                        continue;
1893                    }
1894                    if name == kw::PathRoot && ident.span.at_least_rust_2018() {
1895                        module = Some(ModuleOrUniformRoot::ExternPrelude);
1896                        continue;
1897                    }
1898                    if name == kw::PathRoot
1899                        && ident.span.is_rust_2015()
1900                        && self.tcx.sess.at_least_rust_2018()
1901                    {
1902                        // `::a::b` from 2015 macro on 2018 global edition
1903                        let crate_root = self.resolve_crate_root(ident);
1904                        module = Some(ModuleOrUniformRoot::ModuleAndExternPrelude(crate_root));
1905                        continue;
1906                    }
1907                    if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate {
1908                        // `::a::b`, `crate::a::b` or `$crate::a::b`
1909                        let crate_root = self.resolve_crate_root(ident);
1910                        if let Some(res) = crate_root.res() {
1911                            record_segment_res(self.reborrow(), finalize, res, id);
1912                        }
1913                        module = Some(ModuleOrUniformRoot::Module(crate_root));
1914                        continue;
1915                    }
1916                }
1917            }
1918
1919            let allow_trailing_self = is_last && name == kw::SelfLower;
1920
1921            // Report special messages for path segment keywords in wrong positions.
1922            if ident.is_path_segment_keyword() && segment_idx != 0 && !allow_trailing_self {
1923                return PathResult::failed(
1924                    ident,
1925                    false,
1926                    finalize.is_some(),
1927                    module_had_parse_errors,
1928                    module,
1929                    || {
1930                        let name_str = if name == kw::PathRoot {
1931                            "the crate root".to_string()
1932                        } else {
1933                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", name))
    })format!("`{name}`")
1934                        };
1935                        let (message, label) = if segment_idx == 1
1936                            && path[0].ident.name == kw::PathRoot
1937                        {
1938                            (
1939                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("global paths cannot start with {0}",
                name_str))
    })format!("global paths cannot start with {name_str}"),
1940                                "cannot start with this".to_string(),
1941                            )
1942                        } else if name == kw::SelfLower {
1943                            (
1944                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`self` in paths can only be used in start position or last position"))
    })format!(
1945                                    "`self` in paths can only be used in start position or last position"
1946                                ),
1947                                "can only be used in path start position or last position"
1948                                    .to_string(),
1949                            )
1950                        } else {
1951                            (
1952                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} in paths can only be used in start position",
                name_str))
    })format!("{name_str} in paths can only be used in start position"),
1953                                "can only be used in path start position".to_string(),
1954                            )
1955                        };
1956                        (message, label, None, None)
1957                    },
1958                );
1959            }
1960
1961            let binding = if let Some(module) = module {
1962                self.reborrow().resolve_ident_in_module(
1963                    module,
1964                    ident,
1965                    ns,
1966                    parent_scope,
1967                    finalize,
1968                    ignore_decl,
1969                    ignore_import,
1970                )
1971            } else if let Some(ribs) = ribs
1972                && let Some(TypeNS | ValueNS) = opt_ns
1973            {
1974                if !ignore_import.is_none() {
    ::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
1975                match self.get_mut().resolve_ident_in_lexical_scope(
1976                    ident,
1977                    ns,
1978                    parent_scope,
1979                    finalize,
1980                    &ribs[ns],
1981                    ignore_decl,
1982                    diag_metadata,
1983                ) {
1984                    // we found a locally-imported or available item/module
1985                    Some(LateDecl::Decl(binding)) => Ok(binding),
1986                    // we found a local variable or type param
1987                    Some(LateDecl::RibDef(res)) => {
1988                        record_segment_res(self.reborrow(), finalize, res, id);
1989                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
1990                            res,
1991                            path.len() - 1,
1992                        ));
1993                    }
1994                    _ => Err(Determinacy::determined(finalize.is_some())),
1995                }
1996            } else {
1997                self.reborrow().resolve_ident_in_scope_set(
1998                    ident,
1999                    ScopeSet::All(ns),
2000                    parent_scope,
2001                    finalize,
2002                    ignore_decl,
2003                    ignore_import,
2004                )
2005            };
2006
2007            match binding {
2008                Ok(binding) => {
2009                    if segment_idx == 1 {
2010                        second_binding = Some(binding);
2011                    }
2012                    let res = binding.res();
2013
2014                    // Mark every privacy error in this path with the res to the last element. This allows us
2015                    // to detect the item the user cares about and either find an alternative import, or tell
2016                    // the user it is not accessible.
2017                    if finalize.is_some() {
2018                        for error in &mut self.get_mut().privacy_errors[privacy_errors_len..] {
2019                            error.outermost_res = Some((res, ident));
2020                            error.source = match source {
2021                                Some(PathSource::Struct(Some(expr)))
2022                                | Some(PathSource::Expr(Some(expr))) => Some(expr.clone()),
2023                                _ => None,
2024                            };
2025                        }
2026                    }
2027
2028                    let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
2029                    if let Res::OpenMod(sym) = binding.res() {
2030                        module = Some(ModuleOrUniformRoot::OpenModule(sym));
2031                        record_segment_res(self.reborrow(), finalize, res, id);
2032                    } else if let Some(def_id) = binding.res().module_like_def_id() {
2033                        if self.mods_with_parse_errors.contains(&def_id) {
2034                            module_had_parse_errors = true;
2035                        }
2036                        module = Some(ModuleOrUniformRoot::Module(self.expect_module(def_id)));
2037                        record_segment_res(self.reborrow(), finalize, res, id);
2038                    } else if res == Res::ToolMod && !is_last && opt_ns.is_some() {
2039                        if binding.is_import() {
2040                            self.dcx().emit_err(diagnostics::ToolModuleImported {
2041                                span: ident.span,
2042                                import: binding.span,
2043                            });
2044                        }
2045                        let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
2046                        return PathResult::NonModule(PartialRes::new(res));
2047                    } else if res == Res::Err {
2048                        return PathResult::NonModule(PartialRes::new(Res::Err));
2049                    } else if opt_ns.is_some() && (is_last || maybe_assoc) {
2050                        if let Some(finalize) = finalize {
2051                            self.get_mut().lint_if_path_starts_with_module(
2052                                finalize,
2053                                path,
2054                                second_binding,
2055                            );
2056                        }
2057                        record_segment_res(self.reborrow(), finalize, res, id);
2058                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
2059                            res,
2060                            path.len() - segment_idx - 1,
2061                        ));
2062                    } else {
2063                        return PathResult::failed(
2064                            ident,
2065                            is_last,
2066                            finalize.is_some(),
2067                            module_had_parse_errors,
2068                            module,
2069                            || {
2070                                let import_inherent_item_error_flag =
2071                                    self.features.import_trait_associated_functions()
2072                                        && #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union |
        DefKind::ForeignTy, _) => true,
    _ => false,
}matches!(
2073                                            res,
2074                                            Res::Def(
2075                                                DefKind::Struct
2076                                                    | DefKind::Enum
2077                                                    | DefKind::Union
2078                                                    | DefKind::ForeignTy,
2079                                                _
2080                                            )
2081                                        );
2082                                // Show a different error message for items that can have associated items.
2083                                let label = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{3}` is {0} {1}, not a module{2}",
                res.article(), res.descr(),
                if import_inherent_item_error_flag {
                    " or a trait"
                } else { "" }, ident))
    })format!(
2084                                    "`{ident}` is {} {}, not a module{}",
2085                                    res.article(),
2086                                    res.descr(),
2087                                    if import_inherent_item_error_flag {
2088                                        " or a trait"
2089                                    } else {
2090                                        ""
2091                                    }
2092                                );
2093                                let scope = match &path[..segment_idx] {
2094                                    [.., prev] => {
2095                                        if prev.ident.name == kw::PathRoot {
2096                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the crate root"))
    })format!("the crate root")
2097                                        } else {
2098                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", prev.ident))
    })format!("`{}`", prev.ident)
2099                                        }
2100                                    }
2101                                    _ => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this scope"))
    })format!("this scope"),
2102                                };
2103                                // FIXME: reword, as the reason we expected a module is because of
2104                                // the following path segment.
2105                                let message = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot find module `{0}` in {1}",
                ident, scope))
    })format!("cannot find module `{ident}` in {scope}");
2106                                let note = if import_inherent_item_error_flag {
2107                                    Some(
2108                                        "cannot import inherent associated items, only trait associated items".to_string(),
2109                                    )
2110                                } else {
2111                                    None
2112                                };
2113                                (message, label, None, note)
2114                            },
2115                        );
2116                    }
2117                }
2118                Err(Undetermined) if finalize.is_none() => return PathResult::Indeterminate,
2119                Err(Determined | Undetermined) => {
2120                    if let Some(ModuleOrUniformRoot::Module(module)) = module
2121                        && opt_ns.is_some()
2122                        && !module.is_normal()
2123                    {
2124                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
2125                            module.res().unwrap(),
2126                            path.len() - segment_idx,
2127                        ));
2128                    }
2129
2130                    let mut this = self.reborrow();
2131                    return PathResult::failed(
2132                        ident,
2133                        is_last,
2134                        finalize.is_some(),
2135                        module_had_parse_errors,
2136                        module,
2137                        || {
2138                            let (message, label, suggestion) =
2139                                this.get_mut().report_path_resolution_error(
2140                                    path,
2141                                    opt_ns,
2142                                    parent_scope,
2143                                    ribs,
2144                                    ignore_decl,
2145                                    ignore_import,
2146                                    module,
2147                                    segment_idx,
2148                                    ident,
2149                                    diag_metadata,
2150                                );
2151                            (message, label, suggestion, None)
2152                        },
2153                    );
2154                }
2155            }
2156        }
2157
2158        if let Some(finalize) = finalize {
2159            self.get_mut().lint_if_path_starts_with_module(finalize, path, second_binding);
2160        }
2161
2162        PathResult::Module(match module {
2163            Some(module) => module,
2164            None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
2165            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("resolve_path: non-empty path `{0:?}` has no module",
        path))bug!("resolve_path: non-empty path `{:?}` has no module", path),
2166        })
2167    }
2168}