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, cycle_detection};
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    module_to_string,
30};
31
32#[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)]
33pub enum UsePrelude {
34    No,
35    Yes,
36}
37
38impl From<UsePrelude> for bool {
39    fn from(up: UsePrelude) -> bool {
40        #[allow(non_exhaustive_omitted_patterns)] match up {
    UsePrelude::Yes => true,
    _ => false,
}matches!(up, UsePrelude::Yes)
41    }
42}
43
44#[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)]
45enum Shadowing {
46    Restricted,
47    Unrestricted,
48}
49
50impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
51    /// A generic scope visitor.
52    /// Visits scopes in order to resolve some identifier in them or perform other actions.
53    /// If the callback returns `Some` result, we stop visiting scopes and return it.
54    pub(crate) fn visit_scopes<'r, T>(
55        mut self: CmResolver<'r, 'ra, 'tcx>,
56        scope_set: ScopeSet<'ra>,
57        parent_scope: &ParentScope<'ra>,
58        mut ctxt: Macros20NormalizedSyntaxContext,
59        orig_ident_span: Span,
60        derive_fallback_lint_id: Option<NodeId>,
61        mut visitor: impl FnMut(
62            CmResolver<'_, 'ra, 'tcx>,
63            Scope<'ra>,
64            UsePrelude,
65            Macros20NormalizedSyntaxContext,
66        ) -> ControlFlow<T>,
67    ) -> Option<T> {
68        // General principles:
69        // 1. Not controlled (user-defined) names should have higher priority than controlled names
70        //    built into the language or standard library. This way we can add new names into the
71        //    language or standard library without breaking user code.
72        // 2. "Closed set" below means new names cannot appear after the current resolution attempt.
73        // Places to search (in order of decreasing priority):
74        // (Type NS)
75        // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
76        //    (open set, not controlled).
77        // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
78        //    (open, not controlled).
79        // 3. Extern prelude (open, the open part is from macro expansions, not controlled).
80        // 4. Tool modules (closed, controlled right now, but not in the future).
81        // 5. Standard library prelude (de-facto closed, controlled).
82        // 6. Language prelude (closed, controlled).
83        // (Value NS)
84        // 1. FIXME: Ribs (local variables), there's no necessary infrastructure yet
85        //    (open set, not controlled).
86        // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
87        //    (open, not controlled).
88        // 3. Standard library prelude (de-facto closed, controlled).
89        // (Macro NS)
90        // 1-3. Derive helpers (open, not controlled). All ambiguities with other names
91        //    are currently reported as errors. They should be higher in priority than preludes
92        //    and probably even names in modules according to the "general principles" above. They
93        //    also should be subject to restricted shadowing because are effectively produced by
94        //    derives (you need to resolve the derive first to add helpers into scope), but they
95        //    should be available before the derive is expanded for compatibility.
96        //    It's mess in general, so we are being conservative for now.
97        // 1-3. `macro_rules` (open, not controlled), loop through `macro_rules` scopes. Have higher
98        //    priority than prelude macros, but create ambiguities with macros in modules.
99        // 1-3. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
100        //    (open, not controlled). Have higher priority than prelude macros, but create
101        //    ambiguities with `macro_rules`.
102        // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
103        // 4a. User-defined prelude from macro-use
104        //    (open, the open part is from macro expansions, not controlled).
105        // 4b. "Standard library prelude" part implemented through `macro-use` (closed, controlled).
106        // 4c. Standard library prelude (de-facto closed, controlled).
107        // 6. Language prelude: builtin attributes (closed, controlled).
108
109        let (ns, macro_kind) = match scope_set {
110            ScopeSet::All(ns)
111            | ScopeSet::Module(ns, _)
112            | ScopeSet::ModuleAndExternPrelude(ns, _) => (ns, None),
113            ScopeSet::ExternPrelude => (TypeNS, None),
114            ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind)),
115        };
116        let module = match scope_set {
117            // Start with the specified module.
118            ScopeSet::Module(_, module) | ScopeSet::ModuleAndExternPrelude(_, module) => module,
119            // Jump out of trait or enum modules, they do not act as scopes.
120            _ => parent_scope.module.nearest_item_scope(),
121        };
122        let module_only = #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..));
123        let module_and_extern_prelude = #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::ModuleAndExternPrelude(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::ModuleAndExternPrelude(..));
124        let extern_prelude = #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::ExternPrelude => true,
    _ => false,
}matches!(scope_set, ScopeSet::ExternPrelude);
125        let mut scope = match ns {
126            _ if module_only || module_and_extern_prelude => Scope::ModuleNonGlobs(module, None),
127            _ if extern_prelude => Scope::ExternPreludeItems,
128            TypeNS | ValueNS => Scope::ModuleNonGlobs(module, None),
129            MacroNS => Scope::DeriveHelpers(parent_scope.expansion),
130        };
131        let mut use_prelude = !module.no_implicit_prelude;
132
133        loop {
134            let visit = match scope {
135                // Derive helpers are not in scope when resolving derives in the same container.
136                Scope::DeriveHelpers(expn_id) => {
137                    !(expn_id == parent_scope.expansion && macro_kind == Some(MacroKind::Derive))
138                }
139                Scope::DeriveHelpersCompat => true,
140                Scope::MacroRules(macro_rules_scope) => {
141                    // Use "path compression" on `macro_rules` scope chains. This is an optimization
142                    // used to avoid long scope chains, see the comments on `MacroRulesScopeRef`.
143                    // As another consequence of this optimization visitors never observe invocation
144                    // scopes for macros that were already expanded.
145                    while let MacroRulesScope::Invocation(invoc_id) = macro_rules_scope.get() {
146                        if let Some(next_scope) = self.output_macro_rules_scopes.get(&invoc_id) {
147                            macro_rules_scope.set(next_scope.get());
148                        } else {
149                            break;
150                        }
151                    }
152                    true
153                }
154                Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..) => true,
155                Scope::MacroUsePrelude => use_prelude || orig_ident_span.is_rust_2015(),
156                Scope::BuiltinAttrs => true,
157                Scope::ExternPreludeItems | Scope::ExternPreludeFlags => {
158                    use_prelude || module_and_extern_prelude || extern_prelude
159                }
160                Scope::ToolPrelude => use_prelude,
161                Scope::StdLibPrelude => use_prelude || ns == MacroNS,
162                Scope::BuiltinTypes => true,
163            };
164
165            if visit {
166                let use_prelude = if use_prelude { UsePrelude::Yes } else { UsePrelude::No };
167                if let ControlFlow::Break(break_result) =
168                    visitor(self.reborrow(), scope, use_prelude, ctxt)
169                {
170                    return Some(break_result);
171                }
172            }
173
174            scope = match scope {
175                Scope::DeriveHelpers(LocalExpnId::ROOT) => Scope::DeriveHelpersCompat,
176                Scope::DeriveHelpers(expn_id) => {
177                    // Derive helpers are not visible to code generated by bang or derive macros.
178                    let expn_data = expn_id.expn_data();
179                    match expn_data.kind {
180                        ExpnKind::Root
181                        | ExpnKind::Macro(MacroKind::Bang | MacroKind::Derive, _) => {
182                            Scope::DeriveHelpersCompat
183                        }
184                        _ => Scope::DeriveHelpers(expn_data.parent.expect_local()),
185                    }
186                }
187                Scope::DeriveHelpersCompat => Scope::MacroRules(parent_scope.macro_rules),
188                Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
189                    MacroRulesScope::Def(binding) => {
190                        Scope::MacroRules(binding.parent_macro_rules_scope)
191                    }
192                    MacroRulesScope::Invocation(invoc_id) => {
193                        Scope::MacroRules(self.invocation_parent_scopes[&invoc_id].macro_rules)
194                    }
195                    MacroRulesScope::Empty => Scope::ModuleNonGlobs(module, None),
196                },
197                Scope::ModuleNonGlobs(module, lint_id) => Scope::ModuleGlobs(module, lint_id),
198                Scope::ModuleGlobs(..) if module_only => break,
199                Scope::ModuleGlobs(..) if module_and_extern_prelude => match ns {
200                    TypeNS => {
201                        ctxt.update_unchecked(|ctxt| ctxt.adjust(ExpnId::root()));
202                        Scope::ExternPreludeItems
203                    }
204                    ValueNS | MacroNS => break,
205                },
206                Scope::ModuleGlobs(module, prev_lint_id) => {
207                    use_prelude = !module.no_implicit_prelude;
208                    match self.hygienic_lexical_parent(module, &mut ctxt, derive_fallback_lint_id) {
209                        Some((parent_module, lint_id)) => {
210                            Scope::ModuleNonGlobs(parent_module, lint_id.or(prev_lint_id))
211                        }
212                        None => {
213                            ctxt.update_unchecked(|ctxt| ctxt.adjust(ExpnId::root()));
214                            match ns {
215                                TypeNS => Scope::ExternPreludeItems,
216                                ValueNS => Scope::StdLibPrelude,
217                                MacroNS => Scope::MacroUsePrelude,
218                            }
219                        }
220                    }
221                }
222                Scope::MacroUsePrelude => Scope::StdLibPrelude,
223                Scope::BuiltinAttrs => break, // nowhere else to search
224                Scope::ExternPreludeItems => Scope::ExternPreludeFlags,
225                Scope::ExternPreludeFlags if module_and_extern_prelude || extern_prelude => break,
226                Scope::ExternPreludeFlags => Scope::ToolPrelude,
227                Scope::ToolPrelude => Scope::StdLibPrelude,
228                Scope::StdLibPrelude => match ns {
229                    TypeNS => Scope::BuiltinTypes,
230                    ValueNS => break, // nowhere else to search
231                    MacroNS => Scope::BuiltinAttrs,
232                },
233                Scope::BuiltinTypes => break, // nowhere else to search
234            };
235        }
236
237        None
238    }
239
240    fn hygienic_lexical_parent(
241        &self,
242        module: Module<'ra>,
243        ctxt: &mut Macros20NormalizedSyntaxContext,
244        derive_fallback_lint_id: Option<NodeId>,
245    ) -> Option<(Module<'ra>, Option<NodeId>)> {
246        if !module.expansion.outer_expn_is_descendant_of(**ctxt) {
247            let expn_id = ctxt.update_unchecked(|ctxt| ctxt.remove_mark());
248            return Some((self.expn_def_scope(expn_id), None));
249        }
250
251        if let ModuleKind::Block = module.kind {
252            return Some((module.parent.unwrap().nearest_item_scope(), None));
253        }
254
255        // We need to support the next case under a deprecation warning
256        // ```
257        // struct MyStruct;
258        // ---- begin: this comes from a proc macro derive
259        // mod implementation_details {
260        //     // Note that `MyStruct` is not in scope here.
261        //     impl SomeTrait for MyStruct { ... }
262        // }
263        // ---- end
264        // ```
265        // So we have to fall back to the module's parent during lexical resolution in this case.
266        if derive_fallback_lint_id.is_some()
267            && let Some(parent) = module.parent
268            // Inner module is inside the macro
269            && module.expansion != parent.expansion
270            // Parent module is outside of the macro
271            && module.expansion.is_descendant_of(parent.expansion)
272            // The macro is a proc macro derive
273            && let Some(def_id) = module.expansion.expn_data().macro_def_id
274        {
275            let ext = self.get_macro_by_def_id(def_id);
276            if ext.builtin_name.is_none()
277                && ext.macro_kinds() == MacroKinds::DERIVE
278                && parent.expansion.outer_expn_is_descendant_of(**ctxt)
279            {
280                return Some((parent, derive_fallback_lint_id));
281            }
282        }
283
284        None
285    }
286
287    /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope.
288    /// More specifically, we proceed up the hierarchy of scopes and return the binding for
289    /// `ident` in the first scope that defines it (or None if no scopes define it).
290    ///
291    /// A block's items are above its local variables in the scope hierarchy, regardless of where
292    /// the items are defined in the block. For example,
293    /// ```rust
294    /// fn f() {
295    ///    g(); // Since there are no local variables in scope yet, this resolves to the item.
296    ///    let g = || {};
297    ///    fn g() {}
298    ///    g(); // This resolves to the local variable `g` since it shadows the item.
299    /// }
300    /// ```
301    ///
302    /// Invariant: This must only be called during main resolution, not during
303    /// import resolution.
304    #[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(304u32),
                                    ::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:331",
                                        "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                        ::tracing_core::__macro_support::Option::Some(331u32),
                                        ::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))]
305    pub(crate) fn resolve_ident_in_lexical_scope(
306        &mut self,
307        mut ident: Ident,
308        ns: Namespace,
309        parent_scope: &ParentScope<'ra>,
310        finalize: Option<Finalize>,
311        ribs: &[Rib<'ra>],
312        ignore_decl: Option<Decl<'ra>>,
313        diag_metadata: Option<&DiagMetadata<'_>>,
314    ) -> Option<LateDecl<'ra>> {
315        let orig_ident = ident;
316        let (general_span, normalized_span) = if ident.name == kw::SelfUpper {
317            // FIXME(jseyfried) improve `Self` hygiene
318            let empty_span = ident.span.with_ctxt(SyntaxContext::root());
319            (empty_span, empty_span)
320        } else if ns == TypeNS {
321            let normalized_span = ident.span.normalize_to_macros_2_0();
322            (normalized_span, normalized_span)
323        } else {
324            (ident.span.normalize_to_macro_rules(), ident.span.normalize_to_macros_2_0())
325        };
326        ident.span = general_span;
327        let normalized_ident = Ident { span: normalized_span, ..ident };
328
329        // Walk backwards up the ribs in scope.
330        for (i, rib) in ribs.iter().enumerate().rev() {
331            debug!("walk rib\n{:?}", rib.bindings);
332            // Use the rib kind to determine whether we are resolving parameters
333            // (macro 2.0 hygiene) or local variables (`macro_rules` hygiene).
334            let rib_ident = if rib.kind.contains_params() { normalized_ident } else { ident };
335            if let Some((original_rib_ident_def, res)) = rib.bindings.get_key_value(&rib_ident) {
336                // The ident resolves to a type parameter or local variable.
337                return Some(LateDecl::RibDef(self.validate_res_from_ribs(
338                    i,
339                    rib_ident,
340                    *res,
341                    finalize.map(|_| general_span),
342                    *original_rib_ident_def,
343                    ribs,
344                    diag_metadata,
345                )));
346            } else if let RibKind::Block(Some(module)) = rib.kind
347                && let Ok(binding) = self.cm().resolve_ident_in_scope_set(
348                    ident,
349                    ScopeSet::Module(ns, module.to_module()),
350                    parent_scope,
351                    finalize.map(|finalize| Finalize { used: Used::Scope, ..finalize }),
352                    ignore_decl,
353                    None,
354                )
355            {
356                // The ident resolves to an item in a block.
357                return Some(LateDecl::Decl(binding));
358            } else if let RibKind::Module(module) = rib.kind {
359                // Encountered a module item, abandon ribs and look into that module and preludes.
360                let parent_scope = &ParentScope { module: module.to_module(), ..*parent_scope };
361                let finalize = finalize.map(|f| Finalize { stage: Stage::Late, ..f });
362                return self
363                    .cm()
364                    .resolve_ident_in_scope_set(
365                        orig_ident,
366                        ScopeSet::All(ns),
367                        parent_scope,
368                        finalize,
369                        ignore_decl,
370                        None,
371                    )
372                    .ok()
373                    .map(LateDecl::Decl);
374            }
375
376            if let RibKind::MacroDefinition(def) = rib.kind
377                && def == self.macro_def(ident.span.ctxt())
378            {
379                // If an invocation of this macro created `ident`, give up on `ident`
380                // and switch to `ident`'s source from the macro definition.
381                ident.span.remove_mark();
382            }
383        }
384
385        unreachable!()
386    }
387
388    /// Resolve an identifier in the specified set of scopes.
389    pub(crate) fn resolve_ident_in_scope_set<'r>(
390        self: CmResolver<'r, 'ra, 'tcx>,
391        orig_ident: Ident,
392        scope_set: ScopeSet<'ra>,
393        parent_scope: &ParentScope<'ra>,
394        finalize: Option<Finalize>,
395        ignore_decl: Option<Decl<'ra>>,
396        ignore_import: Option<Import<'ra>>,
397    ) -> Result<Decl<'ra>, Determinacy> {
398        self.resolve_ident_in_scope_set_inner(
399            IdentKey::new(orig_ident),
400            orig_ident.span,
401            scope_set,
402            parent_scope,
403            finalize,
404            ignore_decl,
405            ignore_import,
406        )
407    }
408
409    fn resolve_ident_in_scope_set_inner<'r>(
410        self: CmResolver<'r, 'ra, 'tcx>,
411        ident: IdentKey,
412        orig_ident_span: Span,
413        scope_set: ScopeSet<'ra>,
414        parent_scope: &ParentScope<'ra>,
415        finalize: Option<Finalize>,
416        ignore_decl: Option<Decl<'ra>>,
417        ignore_import: Option<Import<'ra>>,
418    ) -> Result<Decl<'ra>, Determinacy> {
419        // Make sure `self`, `super` etc produce an error when passed to here.
420        if !#[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..)) && ident.name.is_path_segment_keyword() {
421            return Err(Determinacy::Determined);
422        }
423
424        let (ns, macro_kind) = match scope_set {
425            ScopeSet::All(ns)
426            | ScopeSet::Module(ns, _)
427            | ScopeSet::ModuleAndExternPrelude(ns, _) => (ns, None),
428            ScopeSet::ExternPrelude => (TypeNS, None),
429            ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind)),
430        };
431        let derive_fallback_lint_id = match finalize {
432            Some(Finalize { node_id, stage: Stage::Late, .. }) => Some(node_id),
433            _ => None,
434        };
435
436        // This is *the* result, resolution from the scope closest to the resolved identifier.
437        // However, sometimes this result is "weak" because it comes from a glob import or
438        // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
439        // mod m { ... } // solution in outer scope
440        // {
441        //     use prefix::*; // imports another `m` - innermost solution
442        //                    // weak, cannot shadow the outer `m`, need to report ambiguity error
443        //     m::mac!();
444        // }
445        // So we have to save the innermost solution and continue searching in outer scopes
446        // to detect potential ambiguities.
447        let mut innermost_results: SmallVec<[(Decl<'_>, Scope<'_>); 2]> = SmallVec::new();
448        let mut determinacy = Determinacy::Determined;
449
450        // Go through all the scopes and try to resolve the name.
451        let break_result = self.visit_scopes(
452            scope_set,
453            parent_scope,
454            ident.ctxt,
455            orig_ident_span,
456            derive_fallback_lint_id,
457            |mut this, scope, use_prelude, ctxt| {
458                let ident = IdentKey { name: ident.name, ctxt };
459                let res = match this.reborrow().resolve_ident_in_scope(
460                    ident,
461                    orig_ident_span,
462                    ns,
463                    scope,
464                    use_prelude,
465                    scope_set,
466                    parent_scope,
467                    // Shadowed decls don't need to be marked as used or non-speculatively loaded.
468                    if innermost_results.is_empty() { finalize } else { None },
469                    ignore_decl,
470                    ignore_import,
471                ) {
472                    Ok(decl) => Ok(decl),
473                    // We can break with an error at this step, it means we cannot determine the
474                    // resolution right now, but we must block and wait until we can, instead of
475                    // considering outer scopes. Although there's no need to do that if we already
476                    // have a better solution.
477                    Err(ControlFlow::Break(determinacy)) if innermost_results.is_empty() => {
478                        return ControlFlow::Break(Err(determinacy));
479                    }
480                    Err(determinacy) => Err(determinacy.into_value()),
481                };
482                match res {
483                    Ok(decl) if sub_namespace_match(decl.macro_kinds(), macro_kind) => {
484                        // Below we report various ambiguity errors.
485                        // We do not need to report them if we are either in speculative resolution,
486                        // or in late resolution when everything is already imported and expanded
487                        // and no ambiguities exist.
488                        let import = match finalize {
489                            None | Some(Finalize { stage: Stage::Late, .. }) => {
490                                return ControlFlow::Break(Ok(decl));
491                            }
492                            Some(Finalize { import, .. }) => import,
493                        };
494                        this.get_mut().maybe_push_glob_vs_glob_vis_ambiguity(
495                            ident,
496                            orig_ident_span,
497                            decl,
498                            import,
499                        );
500
501                        if let Some(&(innermost_decl, _)) = innermost_results.first() {
502                            // Found another solution, if the first one was "weak", report an error.
503                            if this.get_mut().maybe_push_ambiguity(
504                                ident,
505                                orig_ident_span,
506                                ns,
507                                scope_set,
508                                parent_scope,
509                                decl,
510                                scope,
511                                &innermost_results,
512                                import,
513                            ) {
514                                // No need to search for more potential ambiguities, one is enough.
515                                return ControlFlow::Break(Ok(innermost_decl));
516                            }
517                        }
518
519                        innermost_results.push((decl, scope));
520                    }
521                    Ok(_) | Err(Determinacy::Determined) => {}
522                    Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
523                }
524
525                ControlFlow::Continue(())
526            },
527        );
528
529        // Scope visiting returned some result early.
530        if let Some(break_result) = break_result {
531            return break_result;
532        }
533
534        // Scope visiting walked all the scopes and maybe found something in one of them.
535        match innermost_results.first() {
536            Some(&(decl, ..)) => Ok(decl),
537            None => Err(determinacy),
538        }
539    }
540
541    fn resolve_ident_in_scope<'r>(
542        mut self: CmResolver<'r, 'ra, 'tcx>,
543        ident: IdentKey,
544        orig_ident_span: Span,
545        ns: Namespace,
546        scope: Scope<'ra>,
547        use_prelude: UsePrelude,
548        scope_set: ScopeSet<'ra>,
549        parent_scope: &ParentScope<'ra>,
550        finalize: Option<Finalize>,
551        ignore_decl: Option<Decl<'ra>>,
552        ignore_import: Option<Import<'ra>>,
553    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
554        let ret = match scope {
555            Scope::DeriveHelpers(expn_id) => {
556                if let Some(decl) = self
557                    .helper_attrs
558                    .get(&expn_id)
559                    .and_then(|attrs| attrs.iter().rfind(|(i, ..)| ident == *i).map(|(.., d)| *d))
560                {
561                    Ok(decl)
562                } else {
563                    Err(Determinacy::Determined)
564                }
565            }
566            Scope::DeriveHelpersCompat => {
567                let mut result = Err(Determinacy::Determined);
568                for derive in parent_scope.derives {
569                    let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
570                    match self.reborrow().resolve_derive_macro_path(
571                        derive,
572                        parent_scope,
573                        false,
574                        ignore_import,
575                    ) {
576                        Ok((Some(ext), _)) => {
577                            if ext.helper_attrs.contains(&ident.name) {
578                                let decl = self.arenas.new_pub_def_decl(
579                                    Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat),
580                                    derive.span,
581                                    LocalExpnId::ROOT,
582                                );
583                                result = Ok(decl);
584                                break;
585                            }
586                        }
587                        Ok(_) | Err(Determinacy::Determined) => {}
588                        Err(Determinacy::Undetermined) => result = Err(Determinacy::Undetermined),
589                    }
590                }
591                result
592            }
593            Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
594                MacroRulesScope::Def(macro_rules_def) if ident == macro_rules_def.ident => {
595                    Ok(macro_rules_def.decl)
596                }
597                MacroRulesScope::Invocation(_) => Err(Determinacy::Undetermined),
598                _ => Err(Determinacy::Determined),
599            },
600            Scope::ModuleNonGlobs(module, derive_fallback_lint_id) => {
601                let (adjusted_parent_scope, adjusted_finalize) = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..) => true,
    _ => false,
}matches!(
602                    scope_set,
603                    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..)
604                ) {
605                    (parent_scope, finalize)
606                } else {
607                    (
608                        &ParentScope { module, ..*parent_scope },
609                        finalize.map(|f| Finalize { used: Used::Scope, ..f }),
610                    )
611                };
612                let shadowing = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..)) {
613                    Shadowing::Unrestricted
614                } else {
615                    Shadowing::Restricted
616                };
617                let decl = if module.is_local() {
618                    self.reborrow().resolve_ident_in_local_module_non_globs_unadjusted(
619                        module.expect_local(),
620                        ident,
621                        orig_ident_span,
622                        ns,
623                        adjusted_parent_scope,
624                        shadowing,
625                        adjusted_finalize,
626                        ignore_decl,
627                        ignore_import,
628                    )
629                } else {
630                    self.reborrow().resolve_ident_in_extern_module_non_globs_unadjusted(
631                        module.expect_extern(),
632                        ident,
633                        orig_ident_span,
634                        ns,
635                        adjusted_parent_scope,
636                        shadowing,
637                        adjusted_finalize,
638                        ignore_decl,
639                    )
640                };
641
642                match decl {
643                    Ok(decl) => {
644                        if let Some(lint_id) = derive_fallback_lint_id {
645                            self.get_mut().lint_buffer.buffer_lint(
646                                PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
647                                lint_id,
648                                orig_ident_span,
649                                diagnostics::ProcMacroDeriveResolutionFallback {
650                                    span: orig_ident_span,
651                                    ns_descr: ns.descr(),
652                                    ident: ident.name,
653                                },
654                            );
655                        }
656                        Ok(decl)
657                    }
658                    Err(ControlFlow::Continue(determinacy)) => Err(determinacy),
659                    Err(ControlFlow::Break(..)) => return decl,
660                }
661            }
662            Scope::ModuleGlobs(module, _) if !module.is_local() => {
663                // Fast path: external module decoding only creates non-glob declarations.
664                Err(Determined)
665            }
666            Scope::ModuleGlobs(module, derive_fallback_lint_id) => {
667                let (adjusted_parent_scope, adjusted_finalize) = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..) => true,
    _ => false,
}matches!(
668                    scope_set,
669                    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..)
670                ) {
671                    (parent_scope, finalize)
672                } else {
673                    (
674                        &ParentScope { module, ..*parent_scope },
675                        finalize.map(|f| Finalize { used: Used::Scope, ..f }),
676                    )
677                };
678                let binding = self.reborrow().resolve_ident_in_module_globs_unadjusted(
679                    module.expect_local(),
680                    ident,
681                    orig_ident_span,
682                    ns,
683                    adjusted_parent_scope,
684                    if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..)) {
685                        Shadowing::Unrestricted
686                    } else {
687                        Shadowing::Restricted
688                    },
689                    adjusted_finalize,
690                    ignore_decl,
691                    ignore_import,
692                );
693                match binding {
694                    Ok(binding) => {
695                        if let Some(lint_id) = derive_fallback_lint_id {
696                            self.get_mut().lint_buffer.buffer_lint(
697                                PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
698                                lint_id,
699                                orig_ident_span,
700                                diagnostics::ProcMacroDeriveResolutionFallback {
701                                    span: orig_ident_span,
702                                    ns_descr: ns.descr(),
703                                    ident: ident.name,
704                                },
705                            );
706                        }
707                        Ok(binding)
708                    }
709                    Err(ControlFlow::Continue(determinacy)) => Err(determinacy),
710                    Err(ControlFlow::Break(..)) => return binding,
711                }
712            }
713            Scope::MacroUsePrelude => match self.macro_use_prelude.get(&ident.name).cloned() {
714                Some(decl) => Ok(decl),
715                None => Err(Determinacy::determined(!self.graph_root.has_unexpanded_invocations())),
716            },
717            Scope::BuiltinAttrs => match self.builtin_attr_decls.get(&ident.name) {
718                Some(decl) => Ok(*decl),
719                None => Err(Determinacy::Determined),
720            },
721            Scope::ExternPreludeItems => {
722                match self.reborrow().extern_prelude_get_item(
723                    ident,
724                    orig_ident_span,
725                    finalize.is_some(),
726                ) {
727                    Some(decl) => Ok(decl),
728                    None => {
729                        Err(Determinacy::determined(!self.graph_root.has_unexpanded_invocations()))
730                    }
731                }
732            }
733            Scope::ExternPreludeFlags => {
734                match self.extern_prelude_get_flag(ident, orig_ident_span, finalize.is_some()) {
735                    Some(decl) => Ok(decl),
736                    None => Err(Determinacy::Determined),
737                }
738            }
739            Scope::ToolPrelude => match self.registered_tool_decls.get(&ident) {
740                Some(decl) => Ok(*decl),
741                None => Err(Determinacy::Determined),
742            },
743            Scope::StdLibPrelude => {
744                let mut result = Err(Determinacy::Determined);
745                if let Some(prelude) = self.prelude
746                    && let Ok(decl) = self.reborrow().resolve_ident_in_scope_set_inner(
747                        ident,
748                        orig_ident_span,
749                        ScopeSet::Module(ns, prelude),
750                        parent_scope,
751                        None,
752                        ignore_decl,
753                        ignore_import,
754                    )
755                    && (#[allow(non_exhaustive_omitted_patterns)] match use_prelude {
    UsePrelude::Yes => true,
    _ => false,
}matches!(use_prelude, UsePrelude::Yes) || self.is_builtin_macro(decl.res()))
756                {
757                    result = Ok(decl)
758                }
759
760                result
761            }
762            Scope::BuiltinTypes => match self.builtin_type_decls.get(&ident.name) {
763                Some(decl) => {
764                    if #[allow(non_exhaustive_omitted_patterns)] match ident.name {
    sym::f16 => true,
    _ => false,
}matches!(ident.name, sym::f16)
765                        && !self.features.f16()
766                        && !orig_ident_span.allows_unstable(sym::f16)
767                        && finalize.is_some()
768                    {
769                        feature_err(
770                            self.tcx.sess,
771                            sym::f16,
772                            orig_ident_span,
773                            "the type `f16` is unstable",
774                        )
775                        .emit();
776                    }
777                    if #[allow(non_exhaustive_omitted_patterns)] match ident.name {
    sym::f128 => true,
    _ => false,
}matches!(ident.name, sym::f128)
778                        && !self.features.f128()
779                        && !orig_ident_span.allows_unstable(sym::f128)
780                        && finalize.is_some()
781                    {
782                        feature_err(
783                            self.tcx.sess,
784                            sym::f128,
785                            orig_ident_span,
786                            "the type `f128` is unstable",
787                        )
788                        .emit();
789                    }
790                    Ok(*decl)
791                }
792                None => Err(Determinacy::Determined),
793            },
794        };
795
796        ret.map_err(ControlFlow::Continue)
797    }
798
799    fn maybe_push_glob_vs_glob_vis_ambiguity(
800        &mut self,
801        ident: IdentKey,
802        orig_ident_span: Span,
803        decl: Decl<'ra>,
804        import: Option<ImportSummary>,
805    ) {
806        let Some(import) = import else { return };
807        let vis1 = self.import_decl_vis(decl, import);
808        let vis2 = self.import_decl_vis_ext(decl, import, true);
809        if vis1 != vis2 {
810            self.ambiguity_errors.push(AmbiguityError {
811                kind: AmbiguityKind::GlobVsGlob,
812                ambig_vis: Some((vis1, vis2)),
813                ident: ident.orig(orig_ident_span),
814                b1: decl.ambiguity_vis_max.get().unwrap_or(decl),
815                b2: decl.ambiguity_vis_min.get().unwrap_or(decl),
816                scope1: Scope::ModuleGlobs(decl.parent_module.unwrap(), None),
817                scope2: Scope::ModuleGlobs(decl.parent_module.unwrap(), None),
818                warning: Some(AmbiguityWarning::GlobImport),
819            });
820        }
821    }
822
823    fn maybe_push_ambiguity(
824        &mut self,
825        ident: IdentKey,
826        orig_ident_span: Span,
827        ns: Namespace,
828        scope_set: ScopeSet<'ra>,
829        parent_scope: &ParentScope<'ra>,
830        decl: Decl<'ra>,
831        scope: Scope<'ra>,
832        innermost_results: &[(Decl<'ra>, Scope<'ra>)],
833        import: Option<ImportSummary>,
834    ) -> bool {
835        let (innermost_decl, innermost_scope) = innermost_results[0];
836        let (res, innermost_res) = (decl.res(), innermost_decl.res());
837        let ambig_vis = if res != innermost_res {
838            None
839        } else if let Some(import) = import
840            && let vis1 = self.import_decl_vis(decl, import)
841            && let vis2 = self.import_decl_vis(innermost_decl, import)
842            && vis1 != vis2
843        {
844            Some((vis1, vis2))
845        } else {
846            return false;
847        };
848
849        // FIXME: Use `scope` instead of `res` to detect built-in attrs and derive helpers,
850        // it will exclude imports, make slightly more code legal, and will require lang approval.
851        let module_only = #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..));
852        let is_builtin = |res| #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)) => true,
    _ => false,
}matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)));
853        let derive_helper = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
854        let derive_helper_compat = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
855
856        let ambiguity_error_kind = if is_builtin(innermost_res) || is_builtin(res) {
857            Some(AmbiguityKind::BuiltinAttr)
858        } else if innermost_res == derive_helper_compat {
859            Some(AmbiguityKind::DeriveHelper)
860        } else if res == derive_helper_compat && innermost_res != derive_helper {
861            ::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")
862        } else if #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
    Scope::MacroRules(_) => true,
    _ => false,
}matches!(innermost_scope, Scope::MacroRules(_))
863            && #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..) => true,
    _ => false,
}matches!(scope, Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..))
864            && !self.disambiguate_macro_rules_vs_modularized(innermost_decl, decl)
865        {
866            Some(AmbiguityKind::MacroRulesVsModularized)
867        } else if #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::MacroRules(_) => true,
    _ => false,
}matches!(scope, Scope::MacroRules(_))
868            && #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
    Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..) => true,
    _ => false,
}matches!(innermost_scope, Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..))
869        {
870            // should be impossible because of visitation order in
871            // visit_scopes
872            //
873            // we visit all macro_rules scopes (e.g. textual scope macros)
874            // before we visit any modules (e.g. path-based scope macros)
875            ::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!(
876                orig_ident_span,
877                "ambiguous scoped macro resolutions with path-based \
878                                        scope resolution as first candidate"
879            )
880        } else if innermost_decl.is_glob_import() {
881            Some(AmbiguityKind::GlobVsOuter)
882        } else if !module_only && innermost_decl.may_appear_after(parent_scope.expansion, decl) {
883            Some(AmbiguityKind::MoreExpandedVsOuter)
884        } else if innermost_decl.expansion != LocalExpnId::ROOT
885            && (!module_only || ns == MacroNS)
886            && let Scope::ModuleGlobs(m1, _) = scope
887            && let Scope::ModuleNonGlobs(m2, _) = innermost_scope
888            && m1 == m2
889        {
890            // FIXME: this error is too conservative and technically unnecessary now when module
891            // scope is split into two scopes, at least when not resolving in `ScopeSet::Module`,
892            // remove it with lang team approval.
893            Some(AmbiguityKind::GlobVsExpanded)
894        } else {
895            None
896        };
897
898        if let Some(kind) = ambiguity_error_kind {
899            // Skip ambiguity errors for extern flag bindings "overridden"
900            // by extern item bindings.
901            // FIXME: Remove with lang team approval.
902            let issue_145575_hack = #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::ExternPreludeFlags => true,
    _ => false,
}matches!(scope, Scope::ExternPreludeFlags)
903                && innermost_results[1..]
904                    .iter()
905                    .any(|(b, s)| #[allow(non_exhaustive_omitted_patterns)] match s {
    Scope::ExternPreludeItems => true,
    _ => false,
}matches!(s, Scope::ExternPreludeItems) && *b != innermost_decl);
906            // Skip ambiguity errors for nonglob module bindings "overridden"
907            // by glob module bindings in the same module.
908            // FIXME: Remove with lang team approval.
909            let issue_149681_hack = match scope {
910                Scope::ModuleGlobs(m1, _)
911                    if innermost_results[1..]
912                        .iter()
913                        .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)) =>
914                {
915                    true
916                }
917                _ => false,
918            };
919
920            if issue_145575_hack || issue_149681_hack {
921                self.issue_145575_hack_applied = true;
922            } else {
923                // Turn ambiguity errors for core vs std panic into warnings.
924                // FIXME: Remove with lang team approval.
925                let is_issue_147319_hack = orig_ident_span.edition() <= Edition::Edition2024
926                    && #[allow(non_exhaustive_omitted_patterns)] match ident.name {
    sym::panic => true,
    _ => false,
}matches!(ident.name, sym::panic)
927                    && #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::StdLibPrelude => true,
    _ => false,
}matches!(scope, Scope::StdLibPrelude)
928                    && #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
    Scope::ModuleGlobs(_, _) => true,
    _ => false,
}matches!(innermost_scope, Scope::ModuleGlobs(_, _))
929                    && ((self.is_specific_builtin_macro(res, sym::std_panic)
930                        && self.is_specific_builtin_macro(innermost_res, sym::core_panic))
931                        || (self.is_specific_builtin_macro(res, sym::core_panic)
932                            && self.is_specific_builtin_macro(innermost_res, sym::std_panic)));
933
934                let warning = if ambig_vis.is_some() {
935                    Some(AmbiguityWarning::GlobImport)
936                } else if is_issue_147319_hack {
937                    Some(AmbiguityWarning::PanicImport)
938                } else {
939                    None
940                };
941
942                self.ambiguity_errors.push(AmbiguityError {
943                    kind,
944                    ambig_vis,
945                    ident: ident.orig(orig_ident_span),
946                    b1: innermost_decl,
947                    b2: decl,
948                    scope1: innermost_scope,
949                    scope2: scope,
950                    warning,
951                });
952                return true;
953            }
954        }
955
956        false
957    }
958
959    #[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(959u32),
                                    ::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))]
960    pub(crate) fn maybe_resolve_ident_in_module<'r>(
961        self: CmResolver<'r, 'ra, 'tcx>,
962        module: ModuleOrUniformRoot<'ra>,
963        ident: Ident,
964        ns: Namespace,
965        parent_scope: &ParentScope<'ra>,
966        ignore_import: Option<Import<'ra>>,
967    ) -> Result<Decl<'ra>, Determinacy> {
968        self.resolve_ident_in_module(module, ident, ns, parent_scope, None, None, ignore_import)
969    }
970
971    fn resolve_super_in_module(
972        &self,
973        ident: Ident,
974        module: Option<Module<'ra>>,
975        parent_scope: &ParentScope<'ra>,
976    ) -> Option<Module<'ra>> {
977        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
978        module
979            .unwrap_or_else(|| self.resolve_self(&mut ctxt, parent_scope.module))
980            .parent
981            .map(|parent| self.resolve_self(&mut ctxt, parent))
982    }
983
984    pub(crate) fn path_root_is_crate_root(&self, ident: Ident) -> bool {
985        ident.name == kw::PathRoot && ident.span.is_rust_2015() && self.tcx.sess.is_rust_2015()
986    }
987
988    #[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(988u32),
                                    ::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))]
989    pub(crate) fn resolve_ident_in_module<'r>(
990        self: CmResolver<'r, 'ra, 'tcx>,
991        module: ModuleOrUniformRoot<'ra>,
992        ident: Ident,
993        ns: Namespace,
994        parent_scope: &ParentScope<'ra>,
995        finalize: Option<Finalize>,
996        ignore_decl: Option<Decl<'ra>>,
997        ignore_import: Option<Import<'ra>>,
998    ) -> Result<Decl<'ra>, Determinacy> {
999        match module {
1000            ModuleOrUniformRoot::Module(module) => {
1001                if ns == TypeNS {
1002                    if ident.name == kw::SelfLower {
1003                        return Ok(module.self_decl.unwrap());
1004                    }
1005                    if ident.name == kw::Super
1006                        && let Some(module) =
1007                            self.resolve_super_in_module(ident, Some(module), parent_scope)
1008                    {
1009                        return Ok(module.self_decl.unwrap());
1010                    }
1011                }
1012
1013                let (ident_key, def) = IdentKey::new_adjusted(ident, module.expansion);
1014                let adjusted_parent_scope = match def {
1015                    Some(def) => ParentScope { module: self.expn_def_scope(def), ..*parent_scope },
1016                    None => *parent_scope,
1017                };
1018                self.resolve_ident_in_scope_set_inner(
1019                    ident_key,
1020                    ident.span,
1021                    ScopeSet::Module(ns, module),
1022                    &adjusted_parent_scope,
1023                    finalize,
1024                    ignore_decl,
1025                    ignore_import,
1026                )
1027            }
1028            ModuleOrUniformRoot::OpenModule(sym) => {
1029                let open_ns_name = format!("{}::{}", sym.as_str(), ident.name);
1030                let ns_ident = IdentKey::with_root_ctxt(Symbol::intern(&open_ns_name));
1031                match self.extern_prelude_get_flag(ns_ident, ident.span, finalize.is_some()) {
1032                    Some(decl) => Ok(decl),
1033                    None => Err(Determinacy::Determined),
1034                }
1035            }
1036            ModuleOrUniformRoot::ModuleAndExternPrelude(module) => self.resolve_ident_in_scope_set(
1037                ident,
1038                ScopeSet::ModuleAndExternPrelude(ns, module),
1039                parent_scope,
1040                finalize,
1041                ignore_decl,
1042                ignore_import,
1043            ),
1044            ModuleOrUniformRoot::ExternPrelude => {
1045                if ns != TypeNS {
1046                    Err(Determined)
1047                } else {
1048                    self.resolve_ident_in_scope_set_inner(
1049                        IdentKey::new_adjusted(ident, ExpnId::root()).0,
1050                        ident.span,
1051                        ScopeSet::ExternPrelude,
1052                        parent_scope,
1053                        finalize,
1054                        ignore_decl,
1055                        ignore_import,
1056                    )
1057                }
1058            }
1059            ModuleOrUniformRoot::CurrentScope => {
1060                if ns == TypeNS {
1061                    if ident.name == kw::SelfLower {
1062                        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1063                        let module = self.resolve_self(&mut ctxt, parent_scope.module);
1064                        return Ok(module.self_decl.unwrap());
1065                    }
1066                    if ident.name == kw::Super
1067                        && let Some(module) =
1068                            self.resolve_super_in_module(ident, None, parent_scope)
1069                    {
1070                        return Ok(module.self_decl.unwrap());
1071                    }
1072                    if ident.name == kw::Crate
1073                        || ident.name == kw::DollarCrate
1074                        || self.path_root_is_crate_root(ident)
1075                    {
1076                        let module = self.resolve_crate_root(ident);
1077                        return Ok(module.self_decl.unwrap());
1078                    } else if ident.name == kw::Super {
1079                        // FIXME: Implement these with renaming requirements so that e.g.
1080                        // `use super;` doesn't work, but `use super as name;` does.
1081                        // Fall through here to get an error from `early_resolve_...`.
1082                    }
1083                }
1084
1085                self.resolve_ident_in_scope_set(
1086                    ident,
1087                    ScopeSet::All(ns),
1088                    parent_scope,
1089                    finalize,
1090                    ignore_decl,
1091                    ignore_import,
1092                )
1093            }
1094        }
1095    }
1096
1097    /// Attempts to resolve `ident` in namespace `ns` of non-glob bindings in an external `module`.
1098    fn resolve_ident_in_extern_module_non_globs_unadjusted<'r>(
1099        mut self: CmResolver<'r, 'ra, 'tcx>,
1100        module: ExternModule<'ra>,
1101        ident: IdentKey,
1102        orig_ident_span: Span,
1103        ns: Namespace,
1104        parent_scope: &ParentScope<'ra>,
1105        shadowing: Shadowing,
1106        finalize: Option<Finalize>,
1107        // This binding should be ignored during in-module resolution, so that we don't get
1108        // "self-confirming" import resolutions during import validation and checking.
1109        ignore_decl: Option<Decl<'ra>>,
1110    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1111        let key = BindingKey::new(ident, ns);
1112        let resolution =
1113            &*self.resolution(module.to_module(), key).ok_or(ControlFlow::Continue(Determined))?;
1114
1115        let binding = resolution.non_glob_decl.filter(|b| Some(*b) != ignore_decl);
1116
1117        if let Some(finalize) = finalize {
1118            return self.get_mut().finalize_module_binding(
1119                ident,
1120                orig_ident_span,
1121                binding,
1122                parent_scope,
1123                finalize,
1124                shadowing,
1125            );
1126        }
1127
1128        // Items and single imports are not shadowable, if we have one, then it's determined.
1129        if let Some(binding) = binding {
1130            let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1131            return if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) };
1132        }
1133        Err(ControlFlow::Continue(Determined))
1134    }
1135
1136    /// Attempts to resolve `ident` in namespace `ns` of non-glob bindings in a local `module`.
1137    fn resolve_ident_in_local_module_non_globs_unadjusted<'r>(
1138        mut self: CmResolver<'r, 'ra, 'tcx>,
1139        module: LocalModule<'ra>,
1140        ident: IdentKey,
1141        orig_ident_span: Span,
1142        ns: Namespace,
1143        parent_scope: &ParentScope<'ra>,
1144        shadowing: Shadowing,
1145        finalize: Option<Finalize>,
1146        // This binding should be ignored during in-module resolution, so that we don't get
1147        // "self-confirming" import resolutions during import validation and checking.
1148        ignore_decl: Option<Decl<'ra>>,
1149        ignore_import: Option<Import<'ra>>,
1150    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1151        let key = BindingKey::new(ident, ns);
1152        let resolution = self.resolution(module.to_module(), key);
1153
1154        let binding =
1155            resolution.as_ref().and_then(|r| r.non_glob_decl).filter(|b| Some(*b) != ignore_decl);
1156
1157        if let Some(finalize) = finalize {
1158            // finalize implies that the module is fully expanded
1159            if !!module.has_unexpanded_invocations() {
    ::core::panicking::panic("assertion failed: !module.has_unexpanded_invocations()")
};assert!(!module.has_unexpanded_invocations());
1160            return self.get_mut().finalize_module_binding(
1161                ident,
1162                orig_ident_span,
1163                binding,
1164                parent_scope,
1165                finalize,
1166                shadowing,
1167            );
1168        }
1169
1170        // Items and single imports are not shadowable, if we have one, then it's determined.
1171        if let Some(binding) = binding {
1172            let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1173            return if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) };
1174        }
1175
1176        if let Some(resolution) = resolution {
1177            // We need to detect resolution cycles to avoid infinite recursion. The guard ensures
1178            // the resolution is removed when this resolve call ends.
1179            let _cycle_guard = cycle_detection::enter_cycle_detector(module, key)
1180                .map_err(|_| ControlFlow::Continue(Determined))?;
1181
1182            // Check if one of single imports can still define the name, block if it can.
1183            if self.reborrow().single_import_can_define_name(
1184                &resolution,
1185                None,
1186                ns,
1187                ignore_import,
1188                ignore_decl,
1189                parent_scope,
1190            ) {
1191                return Err(ControlFlow::Break(Undetermined));
1192            }
1193        }
1194
1195        // Check if one of unexpanded macros can still define the name.
1196        if module.has_unexpanded_invocations() {
1197            return Err(ControlFlow::Continue(Undetermined));
1198        }
1199
1200        // No resolution and no one else can define the name - determinate error.
1201        Err(ControlFlow::Continue(Determined))
1202    }
1203
1204    /// Attempts to resolve `ident` in namespace `ns` of glob bindings in `module`.
1205    fn resolve_ident_in_module_globs_unadjusted<'r>(
1206        mut self: CmResolver<'r, 'ra, 'tcx>,
1207        module: LocalModule<'ra>,
1208        ident: IdentKey,
1209        orig_ident_span: Span,
1210        ns: Namespace,
1211        parent_scope: &ParentScope<'ra>,
1212        shadowing: Shadowing,
1213        finalize: Option<Finalize>,
1214        ignore_decl: Option<Decl<'ra>>,
1215        ignore_import: Option<Import<'ra>>,
1216    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1217        let key = BindingKey::new(ident, ns);
1218        let resolution = self.resolution(module.to_module(), key);
1219
1220        let binding =
1221            resolution.as_ref().and_then(|r| r.glob_decl).filter(|b| Some(*b) != ignore_decl);
1222
1223        if let Some(finalize) = finalize {
1224            // finalize implies that the module is fully expanded
1225            if !!module.has_unexpanded_invocations() {
    ::core::panicking::panic("assertion failed: !module.has_unexpanded_invocations()")
};assert!(!module.has_unexpanded_invocations());
1226            return self.get_mut().finalize_module_binding(
1227                ident,
1228                orig_ident_span,
1229                binding,
1230                parent_scope,
1231                finalize,
1232                shadowing,
1233            );
1234        }
1235
1236        // We need to detect resolution cycles to avoid infinite recursion. The guard ensures
1237        // the resolution is removed when this resolve call ends.
1238        let _cycle_guard = cycle_detection::enter_cycle_detector(module, key)
1239            .map_err(|_| ControlFlow::Continue(Determined))?;
1240
1241        // Check if one of single imports can still define the name,
1242        // if it can then our result is not determined and can be invalidated.
1243        if let Some(resolution) = resolution {
1244            if self.reborrow().single_import_can_define_name(
1245                &resolution,
1246                binding,
1247                ns,
1248                ignore_import,
1249                ignore_decl,
1250                parent_scope,
1251            ) {
1252                return Err(ControlFlow::Break(Undetermined));
1253            }
1254        }
1255
1256        // So we have a resolution that's from a glob import. This resolution is determined
1257        // if it cannot be shadowed by some new item/import expanded from a macro.
1258        // This happens either if there are no unexpanded macros, or expanded names cannot
1259        // shadow globs (that happens in macro namespace or with restricted shadowing).
1260        //
1261        // Additionally, any macro in any module can plant names in the root module if it creates
1262        // `macro_export` macros, so the root module effectively has unresolved invocations if any
1263        // module has unresolved invocations.
1264        // However, it causes resolution/expansion to stuck too often (#53144), so, to make
1265        // progress, we have to ignore those potential unresolved invocations from other modules
1266        // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
1267        // shadowing is enabled, see `macro_expanded_macro_export_errors`).
1268        if let Some(binding) = binding {
1269            return if binding.determined() || ns == MacroNS || shadowing == Shadowing::Restricted {
1270                let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1271                if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) }
1272            } else {
1273                Err(ControlFlow::Break(Undetermined))
1274            };
1275        }
1276
1277        // Now we are in situation when new item/import can appear only from a glob or a macro
1278        // expansion. With restricted shadowing names from globs and macro expansions cannot
1279        // shadow names from outer scopes, so we can freely fallback from module search to search
1280        // in outer scopes. For `resolve_ident_in_scope_set` to continue search in outer
1281        // scopes we return `Undetermined` with `ControlFlow::Continue`.
1282        // Check if one of unexpanded macros can still define the name,
1283        // if it can then our "no resolution" result is not determined and can be invalidated.
1284        if module.has_unexpanded_invocations() {
1285            return Err(ControlFlow::Continue(Undetermined));
1286        }
1287
1288        // Check if one of glob imports can still define the name,
1289        // if it can then our "no resolution" result is not determined and can be invalidated.
1290        for glob_import in module.globs.borrow().iter() {
1291            if ignore_import == Some(*glob_import) {
1292                continue;
1293            }
1294            if !self.is_accessible_from(glob_import.vis, parent_scope.module) {
1295                continue;
1296            }
1297            let module = match glob_import.imported_module.get() {
1298                Some(ModuleOrUniformRoot::Module(module)) => module,
1299                Some(_) => continue,
1300                None => return Err(ControlFlow::Continue(Undetermined)),
1301            };
1302            let tmp_parent_scope;
1303            let (mut adjusted_parent_scope, mut adjusted_ident) = (parent_scope, ident);
1304            match adjusted_ident
1305                .ctxt
1306                .update_unchecked(|ctxt| ctxt.glob_adjust(module.expansion, glob_import.span))
1307            {
1308                Some(Some(def)) => {
1309                    tmp_parent_scope =
1310                        ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
1311                    adjusted_parent_scope = &tmp_parent_scope;
1312                }
1313                Some(None) => {}
1314                None => continue,
1315            };
1316            let result = self.reborrow().resolve_ident_in_scope_set_inner(
1317                adjusted_ident,
1318                orig_ident_span,
1319                ScopeSet::Module(ns, module),
1320                adjusted_parent_scope,
1321                None,
1322                ignore_decl,
1323                ignore_import,
1324            );
1325
1326            match result {
1327                Err(Determined) => continue,
1328                Ok(binding)
1329                    if !self.is_accessible_from(binding.vis(), glob_import.parent_scope.module) =>
1330                {
1331                    continue;
1332                }
1333                Ok(_) | Err(Undetermined) => return Err(ControlFlow::Continue(Undetermined)),
1334            }
1335        }
1336
1337        // No resolution and no one else can define the name - determinate error.
1338        Err(ControlFlow::Continue(Determined))
1339    }
1340
1341    fn finalize_module_binding(
1342        &mut self,
1343        ident: IdentKey,
1344        orig_ident_span: Span,
1345        binding: Option<Decl<'ra>>,
1346        parent_scope: &ParentScope<'ra>,
1347        finalize: Finalize,
1348        shadowing: Shadowing,
1349    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1350        let Finalize { path_span, report_private, used, root_span, .. } = finalize;
1351
1352        let Some(binding) = binding else {
1353            return Err(ControlFlow::Continue(Determined));
1354        };
1355
1356        let ident = ident.orig(orig_ident_span);
1357        if !self.is_accessible_from(binding.vis(), parent_scope.module) {
1358            if report_private {
1359                self.privacy_errors.push(PrivacyError {
1360                    ident,
1361                    decl: binding,
1362                    dedup_span: path_span,
1363                    outermost_res: None,
1364                    source: None,
1365                    parent_scope: *parent_scope,
1366                    single_nested: path_span != root_span,
1367                });
1368            } else {
1369                return Err(ControlFlow::Break(Determined));
1370            }
1371        }
1372
1373        if shadowing == Shadowing::Unrestricted
1374            && binding.expansion != LocalExpnId::ROOT
1375            && let DeclKind::Import { import, .. } = binding.kind
1376            && #[allow(non_exhaustive_omitted_patterns)] match import.kind {
    ImportKind::MacroExport => true,
    _ => false,
}matches!(import.kind, ImportKind::MacroExport)
1377        {
1378            self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
1379        }
1380
1381        self.record_use(ident, binding, used);
1382        return Ok(binding);
1383    }
1384
1385    // Checks if a single import can define the `Ident` corresponding to `binding`.
1386    // This is used to check whether we can definitively accept a glob as a resolution.
1387    fn single_import_can_define_name<'r>(
1388        mut self: CmResolver<'r, 'ra, 'tcx>,
1389        resolution: &NameResolution<'ra>,
1390        binding: Option<Decl<'ra>>,
1391        ns: Namespace,
1392        ignore_import: Option<Import<'ra>>,
1393        ignore_decl: Option<Decl<'ra>>,
1394        parent_scope: &ParentScope<'ra>,
1395    ) -> bool {
1396        for single_import in &resolution.single_imports {
1397            if let Some(decl) = resolution.non_glob_decl
1398                && let DeclKind::Import { import, .. } = decl.kind
1399                && import == *single_import
1400            {
1401                // Single import has already defined the name and we are aware of it,
1402                // no need to block the globs.
1403                continue;
1404            }
1405            if ignore_import == Some(*single_import) {
1406                continue;
1407            }
1408            if !self.is_accessible_from(single_import.vis, parent_scope.module) {
1409                continue;
1410            }
1411            if let Some(ignored) = ignore_decl
1412                && let DeclKind::Import { import, .. } = ignored.kind
1413                && import == *single_import
1414            {
1415                continue;
1416            }
1417
1418            let Some(module) = single_import.imported_module.get() else {
1419                return true;
1420            };
1421            let ImportKind::Single { source, target, decls, .. } = &single_import.kind else {
1422                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1423            };
1424            if source != target {
1425                if decls.iter().all(|d| d.get().decl().is_none()) {
1426                    return true;
1427                } else if decls[ns].get().decl().is_none() && binding.is_some() {
1428                    return true;
1429                }
1430            }
1431
1432            match self.reborrow().resolve_ident_in_module(
1433                module,
1434                *source,
1435                ns,
1436                &single_import.parent_scope,
1437                None,
1438                ignore_decl,
1439                None,
1440            ) {
1441                Err(Determined) => continue,
1442                Ok(binding)
1443                    if !self
1444                        .is_accessible_from(binding.vis(), single_import.parent_scope.module) =>
1445                {
1446                    continue;
1447                }
1448                Ok(_) | Err(Undetermined) => return true,
1449            }
1450        }
1451
1452        false
1453    }
1454
1455    /// Validate a local resolution (from ribs).
1456    #[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(1456u32),
                                    ::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:1467",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1467u32),
                                    ::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))]
1457    fn validate_res_from_ribs(
1458        &mut self,
1459        rib_index: usize,
1460        rib_ident: Ident,
1461        res: Res,
1462        finalize: Option<Span>,
1463        original_rib_ident_def: Ident,
1464        all_ribs: &[Rib<'ra>],
1465        diag_metadata: Option<&DiagMetadata<'_>>,
1466    ) -> Res {
1467        debug!("validate_res_from_ribs({:?})", res);
1468        let ribs = &all_ribs[rib_index + 1..];
1469
1470        // An invalid forward use of a generic parameter from a previous default
1471        // or in a const param ty.
1472        if let RibKind::ForwardGenericParamBan(reason) = all_ribs[rib_index].kind {
1473            if let Some(span) = finalize {
1474                let res_error = if rib_ident.name == kw::SelfUpper {
1475                    ResolutionError::ForwardDeclaredSelf(reason)
1476                } else {
1477                    ResolutionError::ForwardDeclaredGenericParam(rib_ident.name, reason)
1478                };
1479                self.report_error(span, res_error);
1480            }
1481            assert_eq!(res, Res::Err);
1482            return Res::Err;
1483        }
1484
1485        match res {
1486            Res::Local(_) => {
1487                use ResolutionError::*;
1488                let mut res_err = None;
1489
1490                for rib in ribs {
1491                    match rib.kind {
1492                        RibKind::Normal
1493                        | RibKind::Block(..)
1494                        | RibKind::FnOrCoroutine
1495                        | RibKind::Module(..)
1496                        | RibKind::MacroDefinition(..)
1497                        | RibKind::ForwardGenericParamBan(_) => {
1498                            // Nothing to do. Continue.
1499                        }
1500                        RibKind::Item(..) | RibKind::AssocItem => {
1501                            // This was an attempt to access an upvar inside a
1502                            // named function item. This is not allowed, so we
1503                            // report an error.
1504                            if let Some(span) = finalize {
1505                                // We don't immediately trigger a resolve error, because
1506                                // we want certain other resolution errors (namely those
1507                                // emitted for `ConstantItemRibKind` below) to take
1508                                // precedence.
1509                                res_err = Some((span, CannotCaptureDynamicEnvironmentInFnItem));
1510                            }
1511                        }
1512                        RibKind::ConstantItem(_, item) => {
1513                            // Still doesn't deal with upvars
1514                            if let Some(span) = finalize {
1515                                let (span, resolution_error) = match item {
1516                                    None if rib_ident.name == kw::SelfLower => {
1517                                        (span, LowercaseSelf)
1518                                    }
1519                                    None => {
1520                                        // If we have a `let name = expr;`, we have the span for
1521                                        // `name` and use that to see if it is followed by a type
1522                                        // specifier. If not, then we know we need to suggest
1523                                        // `const name: Ty = expr;`. This is a heuristic, it will
1524                                        // break down in the presence of macros.
1525                                        let sm = self.tcx.sess.source_map();
1526                                        let type_span = match sm
1527                                            .span_followed_by(original_rib_ident_def.span, ":")
1528                                        {
1529                                            None => {
1530                                                Some(original_rib_ident_def.span.shrink_to_hi())
1531                                            }
1532                                            Some(_) => None,
1533                                        };
1534                                        (
1535                                            rib_ident.span,
1536                                            AttemptToUseNonConstantValueInConstant {
1537                                                ident: original_rib_ident_def,
1538                                                suggestion: "const",
1539                                                current: "let",
1540                                                type_span,
1541                                            },
1542                                        )
1543                                    }
1544                                    Some((ident, kind)) => (
1545                                        span,
1546                                        AttemptToUseNonConstantValueInConstant {
1547                                            ident,
1548                                            suggestion: "let",
1549                                            current: kind.as_str(),
1550                                            type_span: None,
1551                                        },
1552                                    ),
1553                                };
1554                                self.report_error(span, resolution_error);
1555                            }
1556                            return Res::Err;
1557                        }
1558                        RibKind::ConstParamTy => {
1559                            if let Some(span) = finalize {
1560                                self.report_error(
1561                                    span,
1562                                    ParamInTyOfConstParam { name: rib_ident.name },
1563                                );
1564                            }
1565                            return Res::Err;
1566                        }
1567                        RibKind::InlineAsmSym => {
1568                            if let Some(span) = finalize {
1569                                self.report_error(span, InvalidAsmSym);
1570                            }
1571                            return Res::Err;
1572                        }
1573                    }
1574                }
1575                if let Some((span, res_err)) = res_err {
1576                    self.report_error(span, res_err);
1577                    return Res::Err;
1578                }
1579            }
1580            Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {
1581                for rib in ribs {
1582                    let (has_generic_params, def_kind) = match rib.kind {
1583                        RibKind::Normal
1584                        | RibKind::Block(..)
1585                        | RibKind::FnOrCoroutine
1586                        | RibKind::Module(..)
1587                        | RibKind::MacroDefinition(..)
1588                        | RibKind::InlineAsmSym
1589                        | RibKind::AssocItem
1590                        | RibKind::ForwardGenericParamBan(_) => {
1591                            // Nothing to do. Continue.
1592                            continue;
1593                        }
1594
1595                        RibKind::ConstParamTy => {
1596                            if !self.features.generic_const_parameter_types() {
1597                                if let Some(span) = finalize {
1598                                    self.report_error(
1599                                        span,
1600                                        ResolutionError::ParamInTyOfConstParam {
1601                                            name: rib_ident.name,
1602                                        },
1603                                    );
1604                                }
1605                                return Res::Err;
1606                            } else {
1607                                continue;
1608                            }
1609                        }
1610
1611                        RibKind::ConstantItem(trivial, _) => {
1612                            if let ConstantHasGenerics::No(cause) = trivial
1613                                && !matches!(res, Res::SelfTyAlias { .. })
1614                            {
1615                                if let Some(span) = finalize {
1616                                    let error = match cause {
1617                                        NoConstantGenericsReason::IsEnumDiscriminant => {
1618                                            ResolutionError::ParamInEnumDiscriminant {
1619                                                name: rib_ident.name,
1620                                                param_kind: ParamKindInEnumDiscriminant::Type,
1621                                            }
1622                                        }
1623                                        NoConstantGenericsReason::NonTrivialConstArg => {
1624                                            ResolutionError::ParamInNonTrivialAnonConst {
1625                                                is_gca: self.features.generic_const_args(),
1626                                                name: rib_ident.name,
1627                                                param_kind: ParamKindInNonTrivialAnonConst::Type,
1628                                            }
1629                                        }
1630                                    };
1631                                    let _: ErrorGuaranteed = self.report_error(span, error);
1632                                }
1633
1634                                return Res::Err;
1635                            }
1636
1637                            continue;
1638                        }
1639
1640                        // This was an attempt to use a type parameter outside its scope.
1641                        RibKind::Item(has_generic_params, def_kind) => {
1642                            (has_generic_params, def_kind)
1643                        }
1644                    };
1645
1646                    if let Some(span) = finalize {
1647                        let item = if let Some(diag_metadata) = diag_metadata
1648                            && let Some(current_item) = diag_metadata.current_item
1649                        {
1650                            let label_span = current_item
1651                                .kind
1652                                .ident()
1653                                .map(|i| i.span)
1654                                .unwrap_or(current_item.span);
1655                            Some((label_span, current_item.span, current_item.kind.clone()))
1656                        } else {
1657                            None
1658                        };
1659                        self.report_error(
1660                            span,
1661                            ResolutionError::GenericParamsFromOuterItem {
1662                                outer_res: res,
1663                                has_generic_params,
1664                                def_kind,
1665                                inner_item: item,
1666                                current_self_ty: diag_metadata
1667                                    .and_then(|m| m.current_self_type.as_ref())
1668                                    .and_then(|ty| {
1669                                        self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1670                                    }),
1671                            },
1672                        );
1673                    }
1674                    return Res::Err;
1675                }
1676            }
1677            Res::Def(DefKind::ConstParam, _) => {
1678                for rib in ribs {
1679                    let (has_generic_params, def_kind) = match rib.kind {
1680                        RibKind::Normal
1681                        | RibKind::Block(..)
1682                        | RibKind::FnOrCoroutine
1683                        | RibKind::Module(..)
1684                        | RibKind::MacroDefinition(..)
1685                        | RibKind::InlineAsmSym
1686                        | RibKind::AssocItem
1687                        | RibKind::ForwardGenericParamBan(_) => continue,
1688
1689                        RibKind::ConstParamTy => {
1690                            if !self.features.generic_const_parameter_types() {
1691                                if let Some(span) = finalize {
1692                                    self.report_error(
1693                                        span,
1694                                        ResolutionError::ParamInTyOfConstParam {
1695                                            name: rib_ident.name,
1696                                        },
1697                                    );
1698                                }
1699                                return Res::Err;
1700                            } else {
1701                                continue;
1702                            }
1703                        }
1704
1705                        RibKind::ConstantItem(trivial, _) => {
1706                            if let ConstantHasGenerics::No(cause) = trivial {
1707                                if let Some(span) = finalize {
1708                                    let error = match cause {
1709                                        NoConstantGenericsReason::IsEnumDiscriminant => {
1710                                            ResolutionError::ParamInEnumDiscriminant {
1711                                                name: rib_ident.name,
1712                                                param_kind: ParamKindInEnumDiscriminant::Const,
1713                                            }
1714                                        }
1715                                        NoConstantGenericsReason::NonTrivialConstArg => {
1716                                            ResolutionError::ParamInNonTrivialAnonConst {
1717                                                is_gca: self.features.generic_const_args(),
1718                                                name: rib_ident.name,
1719                                                param_kind: ParamKindInNonTrivialAnonConst::Const {
1720                                                    name: rib_ident.name,
1721                                                },
1722                                            }
1723                                        }
1724                                    };
1725                                    self.report_error(span, error);
1726                                }
1727
1728                                return Res::Err;
1729                            }
1730
1731                            continue;
1732                        }
1733
1734                        RibKind::Item(has_generic_params, def_kind) => {
1735                            (has_generic_params, def_kind)
1736                        }
1737                    };
1738
1739                    // This was an attempt to use a const parameter outside its scope.
1740                    if let Some(span) = finalize {
1741                        let item = if let Some(diag_metadata) = diag_metadata
1742                            && let Some(current_item) = diag_metadata.current_item
1743                        {
1744                            let label_span = current_item
1745                                .kind
1746                                .ident()
1747                                .map(|i| i.span)
1748                                .unwrap_or(current_item.span);
1749                            Some((label_span, current_item.span, current_item.kind.clone()))
1750                        } else {
1751                            None
1752                        };
1753                        self.report_error(
1754                            span,
1755                            ResolutionError::GenericParamsFromOuterItem {
1756                                outer_res: res,
1757                                has_generic_params,
1758                                def_kind,
1759                                inner_item: item,
1760                                current_self_ty: diag_metadata
1761                                    .and_then(|m| m.current_self_type.as_ref())
1762                                    .and_then(|ty| {
1763                                        self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1764                                    }),
1765                            },
1766                        );
1767                    }
1768                    return Res::Err;
1769                }
1770            }
1771            _ => {}
1772        }
1773
1774        res
1775    }
1776
1777    #[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(1777u32),
                                    ::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))]
1778    pub(crate) fn maybe_resolve_path<'r>(
1779        self: CmResolver<'r, 'ra, 'tcx>,
1780        path: &[Segment],
1781        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1782        parent_scope: &ParentScope<'ra>,
1783        ignore_import: Option<Import<'ra>>,
1784    ) -> PathResult<'ra> {
1785        self.resolve_path_with_ribs(
1786            path,
1787            opt_ns,
1788            parent_scope,
1789            None,
1790            None,
1791            None,
1792            None,
1793            ignore_import,
1794            None,
1795        )
1796    }
1797    #[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(1797u32),
                                    ::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))]
1798    pub(crate) fn resolve_path<'r>(
1799        self: CmResolver<'r, 'ra, 'tcx>,
1800        path: &[Segment],
1801        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1802        parent_scope: &ParentScope<'ra>,
1803        finalize: Option<Finalize>,
1804        ignore_decl: Option<Decl<'ra>>,
1805        ignore_import: Option<Import<'ra>>,
1806    ) -> PathResult<'ra> {
1807        self.resolve_path_with_ribs(
1808            path,
1809            opt_ns,
1810            parent_scope,
1811            None,
1812            finalize,
1813            None,
1814            ignore_decl,
1815            ignore_import,
1816            None,
1817        )
1818    }
1819
1820    pub(crate) fn resolve_path_with_ribs<'r>(
1821        mut self: CmResolver<'r, 'ra, 'tcx>,
1822        path: &[Segment],
1823        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1824        parent_scope: &ParentScope<'ra>,
1825        source: Option<PathSource<'_, '_, '_>>,
1826        finalize: Option<Finalize>,
1827        ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
1828        ignore_decl: Option<Decl<'ra>>,
1829        ignore_import: Option<Import<'ra>>,
1830        diag_metadata: Option<&DiagMetadata<'_>>,
1831    ) -> PathResult<'ra> {
1832        let mut module = None;
1833        let mut module_had_parse_errors = !self.mods_with_parse_errors.is_empty()
1834            && self.mods_with_parse_errors.contains(&parent_scope.module.nearest_parent_mod());
1835        let mut allow_super = true;
1836        let mut second_binding = None;
1837
1838        // We'll provide more context to the privacy errors later, up to `len`.
1839        let privacy_errors_len = self.privacy_errors.len();
1840        fn record_segment_res<'r, 'ra, 'tcx>(
1841            mut this: CmResolver<'r, 'ra, 'tcx>,
1842            finalize: Option<Finalize>,
1843            res: Res,
1844            id: Option<NodeId>,
1845        ) {
1846            if finalize.is_some()
1847                && let Some(id) = id
1848                && !this.partial_res_map.contains_key(&id)
1849            {
1850                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");
1851                this.get_mut().record_partial_res(id, PartialRes::new(res));
1852            }
1853        }
1854
1855        for (segment_idx, &Segment { ident, id, .. }) in path.iter().enumerate() {
1856            {
    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:1856",
                        "rustc_resolve::ident", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                        ::tracing_core::__macro_support::Option::Some(1856u32),
                        ::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);
1857
1858            let is_last = segment_idx + 1 == path.len();
1859            let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1860            let name = ident.name;
1861
1862            allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super);
1863
1864            if ns == TypeNS {
1865                if allow_super && name == kw::Super {
1866                    let parent = if segment_idx == 0 {
1867                        self.resolve_super_in_module(ident, None, parent_scope)
1868                    } else if let Some(ModuleOrUniformRoot::Module(module)) = module {
1869                        self.resolve_super_in_module(ident, Some(module), parent_scope)
1870                    } else {
1871                        None
1872                    };
1873                    if let Some(parent) = parent {
1874                        module = Some(ModuleOrUniformRoot::Module(parent));
1875                        continue;
1876                    }
1877                    let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1878                    let current_module = self.resolve_self(&mut ctxt, parent_scope.module);
1879                    let current_module_path = module_to_string(current_module)
1880                        .map_or_else(|| "crate".to_string(), |path| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("crate::{0}", path))
    })format!("crate::{path}"));
1881                    return PathResult::failed(
1882                        ident,
1883                        false,
1884                        finalize.is_some(),
1885                        module_had_parse_errors,
1886                        module,
1887                        || {
1888                            (
1889                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("too many leading `super` keywords within `{0}`",
                current_module_path))
    })format!(
1890                                    "too many leading `super` keywords within `{current_module_path}`"
1891                                ),
1892                                "this `super` would go above the crate root".to_string(),
1893                                None,
1894                                None,
1895                            )
1896                        },
1897                    );
1898                }
1899                if segment_idx == 0 {
1900                    if name == kw::SelfLower {
1901                        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1902                        let self_mod = self.resolve_self(&mut ctxt, parent_scope.module);
1903                        if let Some(res) = self_mod.res() {
1904                            record_segment_res(self.reborrow(), finalize, res, id);
1905                        }
1906                        module = Some(ModuleOrUniformRoot::Module(self_mod));
1907                        continue;
1908                    }
1909                    if name == kw::PathRoot && ident.span.at_least_rust_2018() {
1910                        module = Some(ModuleOrUniformRoot::ExternPrelude);
1911                        continue;
1912                    }
1913                    if name == kw::PathRoot
1914                        && ident.span.is_rust_2015()
1915                        && self.tcx.sess.at_least_rust_2018()
1916                    {
1917                        // `::a::b` from 2015 macro on 2018 global edition
1918                        let crate_root = self.resolve_crate_root(ident);
1919                        module = Some(ModuleOrUniformRoot::ModuleAndExternPrelude(crate_root));
1920                        continue;
1921                    }
1922                    if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate {
1923                        // `::a::b`, `crate::a::b` or `$crate::a::b`
1924                        let crate_root = self.resolve_crate_root(ident);
1925                        if let Some(res) = crate_root.res() {
1926                            record_segment_res(self.reborrow(), finalize, res, id);
1927                        }
1928                        module = Some(ModuleOrUniformRoot::Module(crate_root));
1929                        continue;
1930                    }
1931                }
1932            }
1933
1934            let allow_trailing_self = is_last && name == kw::SelfLower;
1935
1936            // Report special messages for path segment keywords in wrong positions.
1937            if ident.is_path_segment_keyword() && segment_idx != 0 && !allow_trailing_self {
1938                return PathResult::failed(
1939                    ident,
1940                    false,
1941                    finalize.is_some(),
1942                    module_had_parse_errors,
1943                    module,
1944                    || {
1945                        let name_str = if name == kw::PathRoot {
1946                            "the crate root".to_string()
1947                        } else {
1948                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", name))
    })format!("`{name}`")
1949                        };
1950                        let (message, label) = if segment_idx == 1
1951                            && path[0].ident.name == kw::PathRoot
1952                        {
1953                            (
1954                                ::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}"),
1955                                "cannot start with this".to_string(),
1956                            )
1957                        } else if name == kw::SelfLower {
1958                            (
1959                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`self` in paths can only be used in start position or last position"))
    })format!(
1960                                    "`self` in paths can only be used in start position or last position"
1961                                ),
1962                                "can only be used in path start position or last position"
1963                                    .to_string(),
1964                            )
1965                        } else {
1966                            (
1967                                ::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"),
1968                                "can only be used in path start position".to_string(),
1969                            )
1970                        };
1971                        (message, label, None, None)
1972                    },
1973                );
1974            }
1975
1976            let binding = if let Some(module) = module {
1977                self.reborrow().resolve_ident_in_module(
1978                    module,
1979                    ident,
1980                    ns,
1981                    parent_scope,
1982                    finalize,
1983                    ignore_decl,
1984                    ignore_import,
1985                )
1986            } else if let Some(ribs) = ribs
1987                && let Some(TypeNS | ValueNS) = opt_ns
1988            {
1989                if !ignore_import.is_none() {
    ::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
1990                match self.get_mut().resolve_ident_in_lexical_scope(
1991                    ident,
1992                    ns,
1993                    parent_scope,
1994                    finalize,
1995                    &ribs[ns],
1996                    ignore_decl,
1997                    diag_metadata,
1998                ) {
1999                    // we found a locally-imported or available item/module
2000                    Some(LateDecl::Decl(binding)) => Ok(binding),
2001                    // we found a local variable or type param
2002                    Some(LateDecl::RibDef(res)) => {
2003                        record_segment_res(self.reborrow(), finalize, res, id);
2004                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
2005                            res,
2006                            path.len() - 1,
2007                        ));
2008                    }
2009                    _ => Err(Determinacy::determined(finalize.is_some())),
2010                }
2011            } else {
2012                self.reborrow().resolve_ident_in_scope_set(
2013                    ident,
2014                    ScopeSet::All(ns),
2015                    parent_scope,
2016                    finalize,
2017                    ignore_decl,
2018                    ignore_import,
2019                )
2020            };
2021
2022            match binding {
2023                Ok(binding) => {
2024                    if segment_idx == 1 {
2025                        second_binding = Some(binding);
2026                    }
2027                    let res = binding.res();
2028
2029                    // Mark every privacy error in this path with the res to the last element. This allows us
2030                    // to detect the item the user cares about and either find an alternative import, or tell
2031                    // the user it is not accessible.
2032                    if finalize.is_some() {
2033                        for error in &mut self.get_mut().privacy_errors[privacy_errors_len..] {
2034                            error.outermost_res = Some((res, ident));
2035                            error.source = match source {
2036                                Some(PathSource::Struct(Some(expr)))
2037                                | Some(PathSource::Expr(Some(expr))) => Some(expr.clone()),
2038                                _ => None,
2039                            };
2040                        }
2041                    }
2042
2043                    let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
2044                    if let Res::OpenMod(sym) = binding.res() {
2045                        module = Some(ModuleOrUniformRoot::OpenModule(sym));
2046                        record_segment_res(self.reborrow(), finalize, res, id);
2047                    } else if let Some(def_id) = binding.res().module_like_def_id() {
2048                        if self.mods_with_parse_errors.contains(&def_id) {
2049                            module_had_parse_errors = true;
2050                        }
2051                        module = Some(ModuleOrUniformRoot::Module(self.expect_module(def_id)));
2052                        record_segment_res(self.reborrow(), finalize, res, id);
2053                    } else if res == Res::ToolMod && !is_last && opt_ns.is_some() {
2054                        if binding.is_import() {
2055                            self.dcx().emit_err(diagnostics::ToolModuleImported {
2056                                span: ident.span,
2057                                import: binding.span,
2058                            });
2059                        }
2060                        let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
2061                        return PathResult::NonModule(PartialRes::new(res));
2062                    } else if res == Res::Err {
2063                        return PathResult::NonModule(PartialRes::new(Res::Err));
2064                    } else if opt_ns.is_some() && (is_last || maybe_assoc) {
2065                        if let Some(finalize) = finalize {
2066                            self.get_mut().lint_if_path_starts_with_module(
2067                                finalize,
2068                                path,
2069                                second_binding,
2070                            );
2071                        }
2072                        record_segment_res(self.reborrow(), finalize, res, id);
2073                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
2074                            res,
2075                            path.len() - segment_idx - 1,
2076                        ));
2077                    } else {
2078                        return PathResult::failed(
2079                            ident,
2080                            is_last,
2081                            finalize.is_some(),
2082                            module_had_parse_errors,
2083                            module,
2084                            || {
2085                                let import_inherent_item_error_flag =
2086                                    self.features.import_trait_associated_functions()
2087                                        && #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union |
        DefKind::ForeignTy, _) => true,
    _ => false,
}matches!(
2088                                            res,
2089                                            Res::Def(
2090                                                DefKind::Struct
2091                                                    | DefKind::Enum
2092                                                    | DefKind::Union
2093                                                    | DefKind::ForeignTy,
2094                                                _
2095                                            )
2096                                        );
2097                                // Show a different error message for items that can have associated items.
2098                                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!(
2099                                    "`{ident}` is {} {}, not a module{}",
2100                                    res.article(),
2101                                    res.descr(),
2102                                    if import_inherent_item_error_flag {
2103                                        " or a trait"
2104                                    } else {
2105                                        ""
2106                                    }
2107                                );
2108                                let scope = match &path[..segment_idx] {
2109                                    [.., prev] => {
2110                                        if prev.ident.name == kw::PathRoot {
2111                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the crate root"))
    })format!("the crate root")
2112                                        } else {
2113                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", prev.ident))
    })format!("`{}`", prev.ident)
2114                                        }
2115                                    }
2116                                    _ => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this scope"))
    })format!("this scope"),
2117                                };
2118                                // FIXME: reword, as the reason we expected a module is because of
2119                                // the following path segment.
2120                                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}");
2121                                let note = if import_inherent_item_error_flag {
2122                                    Some(
2123                                        "cannot import inherent associated items, only trait associated items".to_string(),
2124                                    )
2125                                } else {
2126                                    None
2127                                };
2128                                (message, label, None, note)
2129                            },
2130                        );
2131                    }
2132                }
2133                Err(Undetermined) if finalize.is_none() => return PathResult::Indeterminate,
2134                Err(Determined | Undetermined) => {
2135                    if let Some(ModuleOrUniformRoot::Module(module)) = module
2136                        && opt_ns.is_some()
2137                        && !module.is_normal()
2138                    {
2139                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
2140                            module.res().unwrap(),
2141                            path.len() - segment_idx,
2142                        ));
2143                    }
2144
2145                    let mut this = self.reborrow();
2146                    return PathResult::failed(
2147                        ident,
2148                        is_last,
2149                        finalize.is_some(),
2150                        module_had_parse_errors,
2151                        module,
2152                        || {
2153                            let (message, label, suggestion) =
2154                                this.get_mut().report_path_resolution_error(
2155                                    path,
2156                                    opt_ns,
2157                                    parent_scope,
2158                                    ribs,
2159                                    ignore_decl,
2160                                    ignore_import,
2161                                    module,
2162                                    segment_idx,
2163                                    ident,
2164                                    diag_metadata,
2165                                );
2166                            (message, label, suggestion, None)
2167                        },
2168                    );
2169                }
2170            }
2171        }
2172
2173        if let Some(finalize) = finalize {
2174            self.get_mut().lint_if_path_starts_with_module(finalize, path, second_binding);
2175        }
2176
2177        PathResult::Module(match module {
2178            Some(module) => module,
2179            None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
2180            _ => ::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),
2181        })
2182    }
2183}