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::ty::Visibility;
9use rustc_middle::{bug, span_bug};
10use rustc_session::lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK;
11use rustc_session::parse::feature_err;
12use rustc_span::edition::Edition;
13use rustc_span::hygiene::{ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext};
14use rustc_span::{Ident, Span, kw, sym};
15use smallvec::SmallVec;
16use tracing::{debug, instrument};
17
18use crate::errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
19use crate::hygiene::Macros20NormalizedSyntaxContext;
20use crate::imports::{Import, NameResolution};
21use crate::late::{
22    ConstantHasGenerics, DiagMetadata, NoConstantGenericsReason, PathSource, Rib, RibKind,
23};
24use crate::macros::{MacroRulesScope, sub_namespace_match};
25use crate::{
26    AmbiguityError, AmbiguityKind, AmbiguityWarning, BindingKey, CmResolver, Decl, DeclKind,
27    Determinacy, Finalize, IdentKey, ImportKind, LateDecl, Module, ModuleKind, ModuleOrUniformRoot,
28    ParentScope, PathResult, PrivacyError, Res, ResolutionError, Resolver, Scope, ScopeSet,
29    Segment, Stage, Symbol, Used, errors,
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).ext;
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), 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, ..*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),
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, ..*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_vis = match finalize {
489                            None | Some(Finalize { stage: Stage::Late, .. }) => {
490                                return ControlFlow::Break(Ok(decl));
491                            }
492                            Some(Finalize { import_vis, .. }) => import_vis,
493                        };
494
495                        if let Some(&(innermost_decl, _)) = innermost_results.first() {
496                            // Found another solution, if the first one was "weak", report an error.
497                            if this.get_mut().maybe_push_ambiguity(
498                                ident,
499                                orig_ident_span,
500                                ns,
501                                scope_set,
502                                parent_scope,
503                                decl,
504                                scope,
505                                &innermost_results,
506                                import_vis,
507                            ) {
508                                // No need to search for more potential ambiguities, one is enough.
509                                return ControlFlow::Break(Ok(innermost_decl));
510                            }
511                        }
512
513                        innermost_results.push((decl, scope));
514                    }
515                    Ok(_) | Err(Determinacy::Determined) => {}
516                    Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
517                }
518
519                ControlFlow::Continue(())
520            },
521        );
522
523        // Scope visiting returned some result early.
524        if let Some(break_result) = break_result {
525            return break_result;
526        }
527
528        // Scope visiting walked all the scopes and maybe found something in one of them.
529        match innermost_results.first() {
530            Some(&(decl, ..)) => Ok(decl),
531            None => Err(determinacy),
532        }
533    }
534
535    fn resolve_ident_in_scope<'r>(
536        mut self: CmResolver<'r, 'ra, 'tcx>,
537        ident: IdentKey,
538        orig_ident_span: Span,
539        ns: Namespace,
540        scope: Scope<'ra>,
541        use_prelude: UsePrelude,
542        scope_set: ScopeSet<'ra>,
543        parent_scope: &ParentScope<'ra>,
544        finalize: Option<Finalize>,
545        ignore_decl: Option<Decl<'ra>>,
546        ignore_import: Option<Import<'ra>>,
547    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
548        let ret = match scope {
549            Scope::DeriveHelpers(expn_id) => {
550                if let Some(decl) = self
551                    .helper_attrs
552                    .get(&expn_id)
553                    .and_then(|attrs| attrs.iter().rfind(|(i, ..)| ident == *i).map(|(.., d)| *d))
554                {
555                    Ok(decl)
556                } else {
557                    Err(Determinacy::Determined)
558                }
559            }
560            Scope::DeriveHelpersCompat => {
561                let mut result = Err(Determinacy::Determined);
562                for derive in parent_scope.derives {
563                    let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
564                    match self.reborrow().resolve_derive_macro_path(
565                        derive,
566                        parent_scope,
567                        false,
568                        ignore_import,
569                    ) {
570                        Ok((Some(ext), _)) => {
571                            if ext.helper_attrs.contains(&ident.name) {
572                                let decl = self.arenas.new_pub_def_decl(
573                                    Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat),
574                                    derive.span,
575                                    LocalExpnId::ROOT,
576                                );
577                                result = Ok(decl);
578                                break;
579                            }
580                        }
581                        Ok(_) | Err(Determinacy::Determined) => {}
582                        Err(Determinacy::Undetermined) => result = Err(Determinacy::Undetermined),
583                    }
584                }
585                result
586            }
587            Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
588                MacroRulesScope::Def(macro_rules_def) if ident == macro_rules_def.ident => {
589                    Ok(macro_rules_def.decl)
590                }
591                MacroRulesScope::Invocation(_) => Err(Determinacy::Undetermined),
592                _ => Err(Determinacy::Determined),
593            },
594            Scope::ModuleNonGlobs(module, derive_fallback_lint_id) => {
595                let (adjusted_parent_scope, adjusted_finalize) = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..) => true,
    _ => false,
}matches!(
596                    scope_set,
597                    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..)
598                ) {
599                    (parent_scope, finalize)
600                } else {
601                    (
602                        &ParentScope { module, ..*parent_scope },
603                        finalize.map(|f| Finalize { used: Used::Scope, ..f }),
604                    )
605                };
606                let decl = self.reborrow().resolve_ident_in_module_non_globs_unadjusted(
607                    module,
608                    ident,
609                    orig_ident_span,
610                    ns,
611                    adjusted_parent_scope,
612                    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                    adjusted_finalize,
618                    ignore_decl,
619                    ignore_import,
620                );
621                match decl {
622                    Ok(decl) => {
623                        if let Some(lint_id) = derive_fallback_lint_id {
624                            self.get_mut().lint_buffer.buffer_lint(
625                                PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
626                                lint_id,
627                                orig_ident_span,
628                                errors::ProcMacroDeriveResolutionFallback {
629                                    span: orig_ident_span,
630                                    ns_descr: ns.descr(),
631                                    ident: ident.name,
632                                },
633                            );
634                        }
635                        Ok(decl)
636                    }
637                    Err(ControlFlow::Continue(determinacy)) => Err(determinacy),
638                    Err(ControlFlow::Break(..)) => return decl,
639                }
640            }
641            Scope::ModuleGlobs(module, _)
642                if let ModuleKind::Def(_, def_id, _) = module.kind
643                    && !def_id.is_local() =>
644            {
645                // Fast path: external module decoding only creates non-glob declarations.
646                Err(Determined)
647            }
648            Scope::ModuleGlobs(module, derive_fallback_lint_id) => {
649                let (adjusted_parent_scope, adjusted_finalize) = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..) => true,
    _ => false,
}matches!(
650                    scope_set,
651                    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..)
652                ) {
653                    (parent_scope, finalize)
654                } else {
655                    (
656                        &ParentScope { module, ..*parent_scope },
657                        finalize.map(|f| Finalize { used: Used::Scope, ..f }),
658                    )
659                };
660                let binding = self.reborrow().resolve_ident_in_module_globs_unadjusted(
661                    module,
662                    ident,
663                    orig_ident_span,
664                    ns,
665                    adjusted_parent_scope,
666                    if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..)) {
667                        Shadowing::Unrestricted
668                    } else {
669                        Shadowing::Restricted
670                    },
671                    adjusted_finalize,
672                    ignore_decl,
673                    ignore_import,
674                );
675                match binding {
676                    Ok(binding) => {
677                        if let Some(lint_id) = derive_fallback_lint_id {
678                            self.get_mut().lint_buffer.buffer_lint(
679                                PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
680                                lint_id,
681                                orig_ident_span,
682                                errors::ProcMacroDeriveResolutionFallback {
683                                    span: orig_ident_span,
684                                    ns_descr: ns.descr(),
685                                    ident: ident.name,
686                                },
687                            );
688                        }
689                        Ok(binding)
690                    }
691                    Err(ControlFlow::Continue(determinacy)) => Err(determinacy),
692                    Err(ControlFlow::Break(..)) => return binding,
693                }
694            }
695            Scope::MacroUsePrelude => match self.macro_use_prelude.get(&ident.name).cloned() {
696                Some(decl) => Ok(decl),
697                None => Err(Determinacy::determined(
698                    self.graph_root.unexpanded_invocations.borrow().is_empty(),
699                )),
700            },
701            Scope::BuiltinAttrs => match self.builtin_attr_decls.get(&ident.name) {
702                Some(decl) => Ok(*decl),
703                None => Err(Determinacy::Determined),
704            },
705            Scope::ExternPreludeItems => {
706                match self.reborrow().extern_prelude_get_item(
707                    ident,
708                    orig_ident_span,
709                    finalize.is_some(),
710                ) {
711                    Some(decl) => Ok(decl),
712                    None => Err(Determinacy::determined(
713                        self.graph_root.unexpanded_invocations.borrow().is_empty(),
714                    )),
715                }
716            }
717            Scope::ExternPreludeFlags => {
718                match self.extern_prelude_get_flag(ident, orig_ident_span, finalize.is_some()) {
719                    Some(decl) => Ok(decl),
720                    None => Err(Determinacy::Determined),
721                }
722            }
723            Scope::ToolPrelude => match self.registered_tool_decls.get(&ident) {
724                Some(decl) => Ok(*decl),
725                None => Err(Determinacy::Determined),
726            },
727            Scope::StdLibPrelude => {
728                let mut result = Err(Determinacy::Determined);
729                if let Some(prelude) = self.prelude
730                    && let Ok(decl) = self.reborrow().resolve_ident_in_scope_set_inner(
731                        ident,
732                        orig_ident_span,
733                        ScopeSet::Module(ns, prelude),
734                        parent_scope,
735                        None,
736                        ignore_decl,
737                        ignore_import,
738                    )
739                    && (#[allow(non_exhaustive_omitted_patterns)] match use_prelude {
    UsePrelude::Yes => true,
    _ => false,
}matches!(use_prelude, UsePrelude::Yes) || self.is_builtin_macro(decl.res()))
740                {
741                    result = Ok(decl)
742                }
743
744                result
745            }
746            Scope::BuiltinTypes => match self.builtin_type_decls.get(&ident.name) {
747                Some(decl) => {
748                    if #[allow(non_exhaustive_omitted_patterns)] match ident.name {
    sym::f16 => true,
    _ => false,
}matches!(ident.name, sym::f16)
749                        && !self.tcx.features().f16()
750                        && !orig_ident_span.allows_unstable(sym::f16)
751                        && finalize.is_some()
752                    {
753                        feature_err(
754                            self.tcx.sess,
755                            sym::f16,
756                            orig_ident_span,
757                            "the type `f16` is unstable",
758                        )
759                        .emit();
760                    }
761                    if #[allow(non_exhaustive_omitted_patterns)] match ident.name {
    sym::f128 => true,
    _ => false,
}matches!(ident.name, sym::f128)
762                        && !self.tcx.features().f128()
763                        && !orig_ident_span.allows_unstable(sym::f128)
764                        && finalize.is_some()
765                    {
766                        feature_err(
767                            self.tcx.sess,
768                            sym::f128,
769                            orig_ident_span,
770                            "the type `f128` is unstable",
771                        )
772                        .emit();
773                    }
774                    Ok(*decl)
775                }
776                None => Err(Determinacy::Determined),
777            },
778        };
779
780        ret.map_err(ControlFlow::Continue)
781    }
782
783    fn maybe_push_ambiguity(
784        &mut self,
785        ident: IdentKey,
786        orig_ident_span: Span,
787        ns: Namespace,
788        scope_set: ScopeSet<'ra>,
789        parent_scope: &ParentScope<'ra>,
790        decl: Decl<'ra>,
791        scope: Scope<'ra>,
792        innermost_results: &[(Decl<'ra>, Scope<'ra>)],
793        import_vis: Option<Visibility>,
794    ) -> bool {
795        let (innermost_decl, innermost_scope) = innermost_results[0];
796        let (res, innermost_res) = (decl.res(), innermost_decl.res());
797        let ambig_vis = if res != innermost_res {
798            None
799        } else if let Some(import_vis) = import_vis
800            && let min =
801                (|d: Decl<'_>| d.vis().min(import_vis.to_def_id(), self.tcx).expect_local())
802            && let (min1, min2) = (min(decl), min(innermost_decl))
803            && min1 != min2
804        {
805            Some((min1, min2))
806        } else {
807            return false;
808        };
809
810        // FIXME: Use `scope` instead of `res` to detect built-in attrs and derive helpers,
811        // it will exclude imports, make slightly more code legal, and will require lang approval.
812        let module_only = #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..));
813        let is_builtin = |res| #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)) => true,
    _ => false,
}matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)));
814        let derive_helper = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
815        let derive_helper_compat = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
816
817        let ambiguity_error_kind = if is_builtin(innermost_res) || is_builtin(res) {
818            Some(AmbiguityKind::BuiltinAttr)
819        } else if innermost_res == derive_helper_compat {
820            Some(AmbiguityKind::DeriveHelper)
821        } else if res == derive_helper_compat && innermost_res != derive_helper {
822            ::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")
823        } else if #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
    Scope::MacroRules(_) => true,
    _ => false,
}matches!(innermost_scope, Scope::MacroRules(_))
824            && #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..) => true,
    _ => false,
}matches!(scope, Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..))
825            && !self.disambiguate_macro_rules_vs_modularized(innermost_decl, decl)
826        {
827            Some(AmbiguityKind::MacroRulesVsModularized)
828        } else if #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::MacroRules(_) => true,
    _ => false,
}matches!(scope, Scope::MacroRules(_))
829            && #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
    Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..) => true,
    _ => false,
}matches!(innermost_scope, Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..))
830        {
831            // should be impossible because of visitation order in
832            // visit_scopes
833            //
834            // we visit all macro_rules scopes (e.g. textual scope macros)
835            // before we visit any modules (e.g. path-based scope macros)
836            ::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!(
837                orig_ident_span,
838                "ambiguous scoped macro resolutions with path-based \
839                                        scope resolution as first candidate"
840            )
841        } else if innermost_decl.is_glob_import() {
842            Some(AmbiguityKind::GlobVsOuter)
843        } else if !module_only && innermost_decl.may_appear_after(parent_scope.expansion, decl) {
844            Some(AmbiguityKind::MoreExpandedVsOuter)
845        } else if innermost_decl.expansion != LocalExpnId::ROOT
846            && (!module_only || ns == MacroNS)
847            && let Scope::ModuleGlobs(m1, _) = scope
848            && let Scope::ModuleNonGlobs(m2, _) = innermost_scope
849            && m1 == m2
850        {
851            // FIXME: this error is too conservative and technically unnecessary now when module
852            // scope is split into two scopes, at least when not resolving in `ScopeSet::Module`,
853            // remove it with lang team approval.
854            Some(AmbiguityKind::GlobVsExpanded)
855        } else {
856            None
857        };
858
859        if let Some(kind) = ambiguity_error_kind {
860            // Skip ambiguity errors for extern flag bindings "overridden"
861            // by extern item bindings.
862            // FIXME: Remove with lang team approval.
863            let issue_145575_hack = #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::ExternPreludeFlags => true,
    _ => false,
}matches!(scope, Scope::ExternPreludeFlags)
864                && innermost_results[1..]
865                    .iter()
866                    .any(|(b, s)| #[allow(non_exhaustive_omitted_patterns)] match s {
    Scope::ExternPreludeItems => true,
    _ => false,
}matches!(s, Scope::ExternPreludeItems) && *b != innermost_decl);
867            // Skip ambiguity errors for nonglob module bindings "overridden"
868            // by glob module bindings in the same module.
869            // FIXME: Remove with lang team approval.
870            let issue_149681_hack = match scope {
871                Scope::ModuleGlobs(m1, _)
872                    if innermost_results[1..]
873                        .iter()
874                        .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)) =>
875                {
876                    true
877                }
878                _ => false,
879            };
880
881            if issue_145575_hack || issue_149681_hack {
882                self.issue_145575_hack_applied = true;
883            } else {
884                // Turn ambiguity errors for core vs std panic into warnings.
885                // FIXME: Remove with lang team approval.
886                let is_issue_147319_hack = orig_ident_span.edition() <= Edition::Edition2024
887                    && #[allow(non_exhaustive_omitted_patterns)] match ident.name {
    sym::panic => true,
    _ => false,
}matches!(ident.name, sym::panic)
888                    && #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::StdLibPrelude => true,
    _ => false,
}matches!(scope, Scope::StdLibPrelude)
889                    && #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
    Scope::ModuleGlobs(_, _) => true,
    _ => false,
}matches!(innermost_scope, Scope::ModuleGlobs(_, _))
890                    && ((self.is_specific_builtin_macro(res, sym::std_panic)
891                        && self.is_specific_builtin_macro(innermost_res, sym::core_panic))
892                        || (self.is_specific_builtin_macro(res, sym::core_panic)
893                            && self.is_specific_builtin_macro(innermost_res, sym::std_panic)));
894
895                let warning = if ambig_vis.is_some() {
896                    Some(AmbiguityWarning::GlobImport)
897                } else if is_issue_147319_hack {
898                    Some(AmbiguityWarning::PanicImport)
899                } else {
900                    None
901                };
902
903                self.ambiguity_errors.push(AmbiguityError {
904                    kind,
905                    ambig_vis,
906                    ident: ident.orig(orig_ident_span),
907                    b1: innermost_decl,
908                    b2: decl,
909                    scope1: innermost_scope,
910                    scope2: scope,
911                    warning,
912                });
913                return true;
914            }
915        }
916
917        false
918    }
919
920    #[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(920u32),
                                    ::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))]
921    pub(crate) fn maybe_resolve_ident_in_module<'r>(
922        self: CmResolver<'r, 'ra, 'tcx>,
923        module: ModuleOrUniformRoot<'ra>,
924        ident: Ident,
925        ns: Namespace,
926        parent_scope: &ParentScope<'ra>,
927        ignore_import: Option<Import<'ra>>,
928    ) -> Result<Decl<'ra>, Determinacy> {
929        self.resolve_ident_in_module(module, ident, ns, parent_scope, None, None, ignore_import)
930    }
931
932    fn resolve_super_in_module(
933        &self,
934        ident: Ident,
935        module: Option<Module<'ra>>,
936        parent_scope: &ParentScope<'ra>,
937    ) -> Option<Module<'ra>> {
938        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
939        module
940            .unwrap_or_else(|| self.resolve_self(&mut ctxt, parent_scope.module))
941            .parent
942            .map(|parent| self.resolve_self(&mut ctxt, parent))
943    }
944
945    pub(crate) fn path_root_is_crate_root(&self, ident: Ident) -> bool {
946        ident.name == kw::PathRoot && ident.span.is_rust_2015() && self.tcx.sess.is_rust_2015()
947    }
948
949    #[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(949u32),
                                    ::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 && 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 ||
                                ident.name == kw::SelfLower {}
                    }
                    self.resolve_ident_in_scope_set(ident, ScopeSet::All(ns),
                        parent_scope, finalize, ignore_decl, ignore_import)
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
950    pub(crate) fn resolve_ident_in_module<'r>(
951        self: CmResolver<'r, 'ra, 'tcx>,
952        module: ModuleOrUniformRoot<'ra>,
953        ident: Ident,
954        ns: Namespace,
955        parent_scope: &ParentScope<'ra>,
956        finalize: Option<Finalize>,
957        ignore_decl: Option<Decl<'ra>>,
958        ignore_import: Option<Import<'ra>>,
959    ) -> Result<Decl<'ra>, Determinacy> {
960        match module {
961            ModuleOrUniformRoot::Module(module) => {
962                if ns == TypeNS
963                    && ident.name == kw::Super
964                    && let Some(module) =
965                        self.resolve_super_in_module(ident, Some(module), parent_scope)
966                {
967                    return Ok(module.self_decl.unwrap());
968                }
969
970                let (ident_key, def) = IdentKey::new_adjusted(ident, module.expansion);
971                let adjusted_parent_scope = match def {
972                    Some(def) => ParentScope { module: self.expn_def_scope(def), ..*parent_scope },
973                    None => *parent_scope,
974                };
975                self.resolve_ident_in_scope_set_inner(
976                    ident_key,
977                    ident.span,
978                    ScopeSet::Module(ns, module),
979                    &adjusted_parent_scope,
980                    finalize,
981                    ignore_decl,
982                    ignore_import,
983                )
984            }
985            ModuleOrUniformRoot::OpenModule(sym) => {
986                let open_ns_name = format!("{}::{}", sym.as_str(), ident.name);
987                let ns_ident = IdentKey::with_root_ctxt(Symbol::intern(&open_ns_name));
988                match self.extern_prelude_get_flag(ns_ident, ident.span, finalize.is_some()) {
989                    Some(decl) => Ok(decl),
990                    None => Err(Determinacy::Determined),
991                }
992            }
993            ModuleOrUniformRoot::ModuleAndExternPrelude(module) => self.resolve_ident_in_scope_set(
994                ident,
995                ScopeSet::ModuleAndExternPrelude(ns, module),
996                parent_scope,
997                finalize,
998                ignore_decl,
999                ignore_import,
1000            ),
1001            ModuleOrUniformRoot::ExternPrelude => {
1002                if ns != TypeNS {
1003                    Err(Determined)
1004                } else {
1005                    self.resolve_ident_in_scope_set_inner(
1006                        IdentKey::new_adjusted(ident, ExpnId::root()).0,
1007                        ident.span,
1008                        ScopeSet::ExternPrelude,
1009                        parent_scope,
1010                        finalize,
1011                        ignore_decl,
1012                        ignore_import,
1013                    )
1014                }
1015            }
1016            ModuleOrUniformRoot::CurrentScope => {
1017                if ns == TypeNS {
1018                    if ident.name == kw::SelfLower {
1019                        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1020                        let module = self.resolve_self(&mut ctxt, parent_scope.module);
1021                        return Ok(module.self_decl.unwrap());
1022                    }
1023                    if ident.name == kw::Super
1024                        && let Some(module) =
1025                            self.resolve_super_in_module(ident, None, parent_scope)
1026                    {
1027                        return Ok(module.self_decl.unwrap());
1028                    }
1029                    if ident.name == kw::Crate
1030                        || ident.name == kw::DollarCrate
1031                        || self.path_root_is_crate_root(ident)
1032                    {
1033                        let module = self.resolve_crate_root(ident);
1034                        return Ok(module.self_decl.unwrap());
1035                    } else if ident.name == kw::Super || ident.name == kw::SelfLower {
1036                        // FIXME: Implement these with renaming requirements so that e.g.
1037                        // `use super;` doesn't work, but `use super as name;` does.
1038                        // Fall through here to get an error from `early_resolve_...`.
1039                    }
1040                }
1041
1042                self.resolve_ident_in_scope_set(
1043                    ident,
1044                    ScopeSet::All(ns),
1045                    parent_scope,
1046                    finalize,
1047                    ignore_decl,
1048                    ignore_import,
1049                )
1050            }
1051        }
1052    }
1053
1054    /// Attempts to resolve `ident` in namespace `ns` of non-glob bindings in `module`.
1055    fn resolve_ident_in_module_non_globs_unadjusted<'r>(
1056        mut self: CmResolver<'r, 'ra, 'tcx>,
1057        module: Module<'ra>,
1058        ident: IdentKey,
1059        orig_ident_span: Span,
1060        ns: Namespace,
1061        parent_scope: &ParentScope<'ra>,
1062        shadowing: Shadowing,
1063        finalize: Option<Finalize>,
1064        // This binding should be ignored during in-module resolution, so that we don't get
1065        // "self-confirming" import resolutions during import validation and checking.
1066        ignore_decl: Option<Decl<'ra>>,
1067        ignore_import: Option<Import<'ra>>,
1068    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1069        let key = BindingKey::new(ident, ns);
1070        // `try_borrow_mut` is required to ensure exclusive access, even if the resulting binding
1071        // doesn't need to be mutable. It will fail when there is a cycle of imports, and without
1072        // the exclusive access infinite recursion will crash the compiler with stack overflow.
1073        let resolution = &*self
1074            .resolution_or_default(module, key, orig_ident_span)
1075            .try_borrow_mut_unchecked()
1076            .map_err(|_| ControlFlow::Continue(Determined))?;
1077
1078        let binding = resolution.non_glob_decl.filter(|b| Some(*b) != ignore_decl);
1079
1080        if let Some(finalize) = finalize {
1081            return self.get_mut().finalize_module_binding(
1082                ident,
1083                orig_ident_span,
1084                binding,
1085                parent_scope,
1086                module,
1087                finalize,
1088                shadowing,
1089            );
1090        }
1091
1092        // Items and single imports are not shadowable, if we have one, then it's determined.
1093        if let Some(binding) = binding {
1094            let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1095            return if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) };
1096        }
1097
1098        // Check if one of single imports can still define the name, block if it can.
1099        if self.reborrow().single_import_can_define_name(
1100            &resolution,
1101            None,
1102            ns,
1103            ignore_import,
1104            ignore_decl,
1105            parent_scope,
1106        ) {
1107            return Err(ControlFlow::Break(Undetermined));
1108        }
1109
1110        // Check if one of unexpanded macros can still define the name.
1111        if !module.unexpanded_invocations.borrow().is_empty() {
1112            return Err(ControlFlow::Continue(Undetermined));
1113        }
1114
1115        // No resolution and no one else can define the name - determinate error.
1116        Err(ControlFlow::Continue(Determined))
1117    }
1118
1119    /// Attempts to resolve `ident` in namespace `ns` of glob bindings in `module`.
1120    fn resolve_ident_in_module_globs_unadjusted<'r>(
1121        mut self: CmResolver<'r, 'ra, 'tcx>,
1122        module: Module<'ra>,
1123        ident: IdentKey,
1124        orig_ident_span: Span,
1125        ns: Namespace,
1126        parent_scope: &ParentScope<'ra>,
1127        shadowing: Shadowing,
1128        finalize: Option<Finalize>,
1129        ignore_decl: Option<Decl<'ra>>,
1130        ignore_import: Option<Import<'ra>>,
1131    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1132        let key = BindingKey::new(ident, ns);
1133        // `try_borrow_mut` is required to ensure exclusive access, even if the resulting binding
1134        // doesn't need to be mutable. It will fail when there is a cycle of imports, and without
1135        // the exclusive access infinite recursion will crash the compiler with stack overflow.
1136        let resolution = &*self
1137            .resolution_or_default(module, key, orig_ident_span)
1138            .try_borrow_mut_unchecked()
1139            .map_err(|_| ControlFlow::Continue(Determined))?;
1140
1141        let binding = resolution.glob_decl.filter(|b| Some(*b) != ignore_decl);
1142
1143        if let Some(finalize) = finalize {
1144            return self.get_mut().finalize_module_binding(
1145                ident,
1146                orig_ident_span,
1147                binding,
1148                parent_scope,
1149                module,
1150                finalize,
1151                shadowing,
1152            );
1153        }
1154
1155        // Check if one of single imports can still define the name,
1156        // if it can then our result is not determined and can be invalidated.
1157        if self.reborrow().single_import_can_define_name(
1158            &resolution,
1159            binding,
1160            ns,
1161            ignore_import,
1162            ignore_decl,
1163            parent_scope,
1164        ) {
1165            return Err(ControlFlow::Break(Undetermined));
1166        }
1167
1168        // So we have a resolution that's from a glob import. This resolution is determined
1169        // if it cannot be shadowed by some new item/import expanded from a macro.
1170        // This happens either if there are no unexpanded macros, or expanded names cannot
1171        // shadow globs (that happens in macro namespace or with restricted shadowing).
1172        //
1173        // Additionally, any macro in any module can plant names in the root module if it creates
1174        // `macro_export` macros, so the root module effectively has unresolved invocations if any
1175        // module has unresolved invocations.
1176        // However, it causes resolution/expansion to stuck too often (#53144), so, to make
1177        // progress, we have to ignore those potential unresolved invocations from other modules
1178        // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
1179        // shadowing is enabled, see `macro_expanded_macro_export_errors`).
1180        if let Some(binding) = binding {
1181            return if binding.determined() || ns == MacroNS || shadowing == Shadowing::Restricted {
1182                let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1183                if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) }
1184            } else {
1185                Err(ControlFlow::Break(Undetermined))
1186            };
1187        }
1188
1189        // Now we are in situation when new item/import can appear only from a glob or a macro
1190        // expansion. With restricted shadowing names from globs and macro expansions cannot
1191        // shadow names from outer scopes, so we can freely fallback from module search to search
1192        // in outer scopes. For `resolve_ident_in_scope_set` to continue search in outer
1193        // scopes we return `Undetermined` with `ControlFlow::Continue`.
1194        // Check if one of unexpanded macros can still define the name,
1195        // if it can then our "no resolution" result is not determined and can be invalidated.
1196        if !module.unexpanded_invocations.borrow().is_empty() {
1197            return Err(ControlFlow::Continue(Undetermined));
1198        }
1199
1200        // Check if one of glob imports can still define the name,
1201        // if it can then our "no resolution" result is not determined and can be invalidated.
1202        for glob_import in module.globs.borrow().iter() {
1203            if ignore_import == Some(*glob_import) {
1204                continue;
1205            }
1206            if !self.is_accessible_from(glob_import.vis, parent_scope.module) {
1207                continue;
1208            }
1209            let module = match glob_import.imported_module.get() {
1210                Some(ModuleOrUniformRoot::Module(module)) => module,
1211                Some(_) => continue,
1212                None => return Err(ControlFlow::Continue(Undetermined)),
1213            };
1214            let tmp_parent_scope;
1215            let (mut adjusted_parent_scope, mut adjusted_ident) = (parent_scope, ident);
1216            match adjusted_ident
1217                .ctxt
1218                .update_unchecked(|ctxt| ctxt.glob_adjust(module.expansion, glob_import.span))
1219            {
1220                Some(Some(def)) => {
1221                    tmp_parent_scope =
1222                        ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
1223                    adjusted_parent_scope = &tmp_parent_scope;
1224                }
1225                Some(None) => {}
1226                None => continue,
1227            };
1228            let result = self.reborrow().resolve_ident_in_scope_set_inner(
1229                adjusted_ident,
1230                orig_ident_span,
1231                ScopeSet::Module(ns, module),
1232                adjusted_parent_scope,
1233                None,
1234                ignore_decl,
1235                ignore_import,
1236            );
1237
1238            match result {
1239                Err(Determined) => continue,
1240                Ok(binding)
1241                    if !self.is_accessible_from(binding.vis(), glob_import.parent_scope.module) =>
1242                {
1243                    continue;
1244                }
1245                Ok(_) | Err(Undetermined) => return Err(ControlFlow::Continue(Undetermined)),
1246            }
1247        }
1248
1249        // No resolution and no one else can define the name - determinate error.
1250        Err(ControlFlow::Continue(Determined))
1251    }
1252
1253    fn finalize_module_binding(
1254        &mut self,
1255        ident: IdentKey,
1256        orig_ident_span: Span,
1257        binding: Option<Decl<'ra>>,
1258        parent_scope: &ParentScope<'ra>,
1259        module: Module<'ra>,
1260        finalize: Finalize,
1261        shadowing: Shadowing,
1262    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1263        let Finalize { path_span, report_private, used, root_span, .. } = finalize;
1264
1265        let Some(binding) = binding else {
1266            return Err(ControlFlow::Continue(Determined));
1267        };
1268
1269        let ident = ident.orig(orig_ident_span);
1270        if !self.is_accessible_from(binding.vis(), parent_scope.module) {
1271            if report_private {
1272                self.privacy_errors.push(PrivacyError {
1273                    ident,
1274                    decl: binding,
1275                    dedup_span: path_span,
1276                    outermost_res: None,
1277                    source: None,
1278                    parent_scope: *parent_scope,
1279                    single_nested: path_span != root_span,
1280                });
1281            } else {
1282                return Err(ControlFlow::Break(Determined));
1283            }
1284        }
1285
1286        if shadowing == Shadowing::Unrestricted
1287            && binding.expansion != LocalExpnId::ROOT
1288            && let DeclKind::Import { import, .. } = binding.kind
1289            && #[allow(non_exhaustive_omitted_patterns)] match import.kind {
    ImportKind::MacroExport => true,
    _ => false,
}matches!(import.kind, ImportKind::MacroExport)
1290        {
1291            self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
1292        }
1293
1294        // If we encounter a re-export for a type with private fields, it will not be able to
1295        // be constructed through this re-export. We track that case here to expand later
1296        // privacy errors with appropriate information.
1297        if let Res::Def(_, def_id) = binding.res() {
1298            let struct_ctor = match def_id.as_local() {
1299                Some(def_id) => self.struct_constructors.get(&def_id).cloned(),
1300                None => {
1301                    let ctor = self.cstore().ctor_untracked(self.tcx(), def_id);
1302                    ctor.map(|(ctor_kind, ctor_def_id)| {
1303                        let ctor_res = Res::Def(
1304                            DefKind::Ctor(rustc_hir::def::CtorOf::Struct, ctor_kind),
1305                            ctor_def_id,
1306                        );
1307                        let ctor_vis = self.tcx.visibility(ctor_def_id);
1308                        let field_visibilities = self
1309                            .tcx
1310                            .associated_item_def_ids(def_id)
1311                            .iter()
1312                            .map(|&field_id| self.tcx.visibility(field_id))
1313                            .collect();
1314                        (ctor_res, ctor_vis, field_visibilities)
1315                    })
1316                }
1317            };
1318            if let Some((_, _, fields)) = struct_ctor
1319                && fields.iter().any(|vis| !self.is_accessible_from(*vis, module))
1320            {
1321                self.inaccessible_ctor_reexport.insert(path_span, binding.span);
1322            }
1323        }
1324
1325        self.record_use(ident, binding, used);
1326        return Ok(binding);
1327    }
1328
1329    // Checks if a single import can define the `Ident` corresponding to `binding`.
1330    // This is used to check whether we can definitively accept a glob as a resolution.
1331    fn single_import_can_define_name<'r>(
1332        mut self: CmResolver<'r, 'ra, 'tcx>,
1333        resolution: &NameResolution<'ra>,
1334        binding: Option<Decl<'ra>>,
1335        ns: Namespace,
1336        ignore_import: Option<Import<'ra>>,
1337        ignore_decl: Option<Decl<'ra>>,
1338        parent_scope: &ParentScope<'ra>,
1339    ) -> bool {
1340        for single_import in &resolution.single_imports {
1341            if let Some(decl) = resolution.non_glob_decl
1342                && let DeclKind::Import { import, .. } = decl.kind
1343                && import == *single_import
1344            {
1345                // Single import has already defined the name and we are aware of it,
1346                // no need to block the globs.
1347                continue;
1348            }
1349            if ignore_import == Some(*single_import) {
1350                continue;
1351            }
1352            if !self.is_accessible_from(single_import.vis, parent_scope.module) {
1353                continue;
1354            }
1355            if let Some(ignored) = ignore_decl
1356                && let DeclKind::Import { import, .. } = ignored.kind
1357                && import == *single_import
1358            {
1359                continue;
1360            }
1361
1362            let Some(module) = single_import.imported_module.get() else {
1363                return true;
1364            };
1365            let ImportKind::Single { source, target, decls, .. } = &single_import.kind else {
1366                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1367            };
1368            if source != target {
1369                if decls.iter().all(|d| d.get().decl().is_none()) {
1370                    return true;
1371                } else if decls[ns].get().decl().is_none() && binding.is_some() {
1372                    return true;
1373                }
1374            }
1375
1376            match self.reborrow().resolve_ident_in_module(
1377                module,
1378                *source,
1379                ns,
1380                &single_import.parent_scope,
1381                None,
1382                ignore_decl,
1383                None,
1384            ) {
1385                Err(Determined) => continue,
1386                Ok(binding)
1387                    if !self
1388                        .is_accessible_from(binding.vis(), single_import.parent_scope.module) =>
1389                {
1390                    continue;
1391                }
1392                Ok(_) | Err(Undetermined) => return true,
1393            }
1394        }
1395
1396        false
1397    }
1398
1399    /// Validate a local resolution (from ribs).
1400    #[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(1400u32),
                                    ::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:1411",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1411u32),
                                    ::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_look_ahead(original_rib_ident_def.span, ":",
                                                            None) {
                                                        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.tcx.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_ogca: self.tcx.features().opaque_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 span =
                                        current_item.kind.ident().map(|i|
                                                    i.span).unwrap_or(current_item.span);
                                    Some((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.tcx.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_ogca: self.tcx.features().opaque_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 span =
                                        current_item.kind.ident().map(|i|
                                                    i.span).unwrap_or(current_item.span);
                                    Some((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))]
1401    fn validate_res_from_ribs(
1402        &mut self,
1403        rib_index: usize,
1404        rib_ident: Ident,
1405        res: Res,
1406        finalize: Option<Span>,
1407        original_rib_ident_def: Ident,
1408        all_ribs: &[Rib<'ra>],
1409        diag_metadata: Option<&DiagMetadata<'_>>,
1410    ) -> Res {
1411        debug!("validate_res_from_ribs({:?})", res);
1412        let ribs = &all_ribs[rib_index + 1..];
1413
1414        // An invalid forward use of a generic parameter from a previous default
1415        // or in a const param ty.
1416        if let RibKind::ForwardGenericParamBan(reason) = all_ribs[rib_index].kind {
1417            if let Some(span) = finalize {
1418                let res_error = if rib_ident.name == kw::SelfUpper {
1419                    ResolutionError::ForwardDeclaredSelf(reason)
1420                } else {
1421                    ResolutionError::ForwardDeclaredGenericParam(rib_ident.name, reason)
1422                };
1423                self.report_error(span, res_error);
1424            }
1425            assert_eq!(res, Res::Err);
1426            return Res::Err;
1427        }
1428
1429        match res {
1430            Res::Local(_) => {
1431                use ResolutionError::*;
1432                let mut res_err = None;
1433
1434                for rib in ribs {
1435                    match rib.kind {
1436                        RibKind::Normal
1437                        | RibKind::Block(..)
1438                        | RibKind::FnOrCoroutine
1439                        | RibKind::Module(..)
1440                        | RibKind::MacroDefinition(..)
1441                        | RibKind::ForwardGenericParamBan(_) => {
1442                            // Nothing to do. Continue.
1443                        }
1444                        RibKind::Item(..) | RibKind::AssocItem => {
1445                            // This was an attempt to access an upvar inside a
1446                            // named function item. This is not allowed, so we
1447                            // report an error.
1448                            if let Some(span) = finalize {
1449                                // We don't immediately trigger a resolve error, because
1450                                // we want certain other resolution errors (namely those
1451                                // emitted for `ConstantItemRibKind` below) to take
1452                                // precedence.
1453                                res_err = Some((span, CannotCaptureDynamicEnvironmentInFnItem));
1454                            }
1455                        }
1456                        RibKind::ConstantItem(_, item) => {
1457                            // Still doesn't deal with upvars
1458                            if let Some(span) = finalize {
1459                                let (span, resolution_error) = match item {
1460                                    None if rib_ident.name == kw::SelfLower => {
1461                                        (span, LowercaseSelf)
1462                                    }
1463                                    None => {
1464                                        // If we have a `let name = expr;`, we have the span for
1465                                        // `name` and use that to see if it is followed by a type
1466                                        // specifier. If not, then we know we need to suggest
1467                                        // `const name: Ty = expr;`. This is a heuristic, it will
1468                                        // break down in the presence of macros.
1469                                        let sm = self.tcx.sess.source_map();
1470                                        let type_span = match sm.span_look_ahead(
1471                                            original_rib_ident_def.span,
1472                                            ":",
1473                                            None,
1474                                        ) {
1475                                            None => {
1476                                                Some(original_rib_ident_def.span.shrink_to_hi())
1477                                            }
1478                                            Some(_) => None,
1479                                        };
1480                                        (
1481                                            rib_ident.span,
1482                                            AttemptToUseNonConstantValueInConstant {
1483                                                ident: original_rib_ident_def,
1484                                                suggestion: "const",
1485                                                current: "let",
1486                                                type_span,
1487                                            },
1488                                        )
1489                                    }
1490                                    Some((ident, kind)) => (
1491                                        span,
1492                                        AttemptToUseNonConstantValueInConstant {
1493                                            ident,
1494                                            suggestion: "let",
1495                                            current: kind.as_str(),
1496                                            type_span: None,
1497                                        },
1498                                    ),
1499                                };
1500                                self.report_error(span, resolution_error);
1501                            }
1502                            return Res::Err;
1503                        }
1504                        RibKind::ConstParamTy => {
1505                            if let Some(span) = finalize {
1506                                self.report_error(
1507                                    span,
1508                                    ParamInTyOfConstParam { name: rib_ident.name },
1509                                );
1510                            }
1511                            return Res::Err;
1512                        }
1513                        RibKind::InlineAsmSym => {
1514                            if let Some(span) = finalize {
1515                                self.report_error(span, InvalidAsmSym);
1516                            }
1517                            return Res::Err;
1518                        }
1519                    }
1520                }
1521                if let Some((span, res_err)) = res_err {
1522                    self.report_error(span, res_err);
1523                    return Res::Err;
1524                }
1525            }
1526            Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {
1527                for rib in ribs {
1528                    let (has_generic_params, def_kind) = match rib.kind {
1529                        RibKind::Normal
1530                        | RibKind::Block(..)
1531                        | RibKind::FnOrCoroutine
1532                        | RibKind::Module(..)
1533                        | RibKind::MacroDefinition(..)
1534                        | RibKind::InlineAsmSym
1535                        | RibKind::AssocItem
1536                        | RibKind::ForwardGenericParamBan(_) => {
1537                            // Nothing to do. Continue.
1538                            continue;
1539                        }
1540
1541                        RibKind::ConstParamTy => {
1542                            if !self.tcx.features().generic_const_parameter_types() {
1543                                if let Some(span) = finalize {
1544                                    self.report_error(
1545                                        span,
1546                                        ResolutionError::ParamInTyOfConstParam {
1547                                            name: rib_ident.name,
1548                                        },
1549                                    );
1550                                }
1551                                return Res::Err;
1552                            } else {
1553                                continue;
1554                            }
1555                        }
1556
1557                        RibKind::ConstantItem(trivial, _) => {
1558                            if let ConstantHasGenerics::No(cause) = trivial
1559                                && !matches!(res, Res::SelfTyAlias { .. })
1560                            {
1561                                if let Some(span) = finalize {
1562                                    let error = match cause {
1563                                        NoConstantGenericsReason::IsEnumDiscriminant => {
1564                                            ResolutionError::ParamInEnumDiscriminant {
1565                                                name: rib_ident.name,
1566                                                param_kind: ParamKindInEnumDiscriminant::Type,
1567                                            }
1568                                        }
1569                                        NoConstantGenericsReason::NonTrivialConstArg => {
1570                                            ResolutionError::ParamInNonTrivialAnonConst {
1571                                                is_ogca: self
1572                                                    .tcx
1573                                                    .features()
1574                                                    .opaque_generic_const_args(),
1575                                                name: rib_ident.name,
1576                                                param_kind: ParamKindInNonTrivialAnonConst::Type,
1577                                            }
1578                                        }
1579                                    };
1580                                    let _: ErrorGuaranteed = self.report_error(span, error);
1581                                }
1582
1583                                return Res::Err;
1584                            }
1585
1586                            continue;
1587                        }
1588
1589                        // This was an attempt to use a type parameter outside its scope.
1590                        RibKind::Item(has_generic_params, def_kind) => {
1591                            (has_generic_params, def_kind)
1592                        }
1593                    };
1594
1595                    if let Some(span) = finalize {
1596                        let item = if let Some(diag_metadata) = diag_metadata
1597                            && let Some(current_item) = diag_metadata.current_item
1598                        {
1599                            let span = current_item
1600                                .kind
1601                                .ident()
1602                                .map(|i| i.span)
1603                                .unwrap_or(current_item.span);
1604                            Some((span, current_item.kind.clone()))
1605                        } else {
1606                            None
1607                        };
1608                        self.report_error(
1609                            span,
1610                            ResolutionError::GenericParamsFromOuterItem {
1611                                outer_res: res,
1612                                has_generic_params,
1613                                def_kind,
1614                                inner_item: item,
1615                                current_self_ty: diag_metadata
1616                                    .and_then(|m| m.current_self_type.as_ref())
1617                                    .and_then(|ty| {
1618                                        self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1619                                    }),
1620                            },
1621                        );
1622                    }
1623                    return Res::Err;
1624                }
1625            }
1626            Res::Def(DefKind::ConstParam, _) => {
1627                for rib in ribs {
1628                    let (has_generic_params, def_kind) = match rib.kind {
1629                        RibKind::Normal
1630                        | RibKind::Block(..)
1631                        | RibKind::FnOrCoroutine
1632                        | RibKind::Module(..)
1633                        | RibKind::MacroDefinition(..)
1634                        | RibKind::InlineAsmSym
1635                        | RibKind::AssocItem
1636                        | RibKind::ForwardGenericParamBan(_) => continue,
1637
1638                        RibKind::ConstParamTy => {
1639                            if !self.tcx.features().generic_const_parameter_types() {
1640                                if let Some(span) = finalize {
1641                                    self.report_error(
1642                                        span,
1643                                        ResolutionError::ParamInTyOfConstParam {
1644                                            name: rib_ident.name,
1645                                        },
1646                                    );
1647                                }
1648                                return Res::Err;
1649                            } else {
1650                                continue;
1651                            }
1652                        }
1653
1654                        RibKind::ConstantItem(trivial, _) => {
1655                            if let ConstantHasGenerics::No(cause) = trivial {
1656                                if let Some(span) = finalize {
1657                                    let error = match cause {
1658                                        NoConstantGenericsReason::IsEnumDiscriminant => {
1659                                            ResolutionError::ParamInEnumDiscriminant {
1660                                                name: rib_ident.name,
1661                                                param_kind: ParamKindInEnumDiscriminant::Const,
1662                                            }
1663                                        }
1664                                        NoConstantGenericsReason::NonTrivialConstArg => {
1665                                            ResolutionError::ParamInNonTrivialAnonConst {
1666                                                is_ogca: self
1667                                                    .tcx
1668                                                    .features()
1669                                                    .opaque_generic_const_args(),
1670                                                name: rib_ident.name,
1671                                                param_kind: ParamKindInNonTrivialAnonConst::Const {
1672                                                    name: rib_ident.name,
1673                                                },
1674                                            }
1675                                        }
1676                                    };
1677                                    self.report_error(span, error);
1678                                }
1679
1680                                return Res::Err;
1681                            }
1682
1683                            continue;
1684                        }
1685
1686                        RibKind::Item(has_generic_params, def_kind) => {
1687                            (has_generic_params, def_kind)
1688                        }
1689                    };
1690
1691                    // This was an attempt to use a const parameter outside its scope.
1692                    if let Some(span) = finalize {
1693                        let item = if let Some(diag_metadata) = diag_metadata
1694                            && let Some(current_item) = diag_metadata.current_item
1695                        {
1696                            let span = current_item
1697                                .kind
1698                                .ident()
1699                                .map(|i| i.span)
1700                                .unwrap_or(current_item.span);
1701                            Some((span, current_item.kind.clone()))
1702                        } else {
1703                            None
1704                        };
1705                        self.report_error(
1706                            span,
1707                            ResolutionError::GenericParamsFromOuterItem {
1708                                outer_res: res,
1709                                has_generic_params,
1710                                def_kind,
1711                                inner_item: item,
1712                                current_self_ty: diag_metadata
1713                                    .and_then(|m| m.current_self_type.as_ref())
1714                                    .and_then(|ty| {
1715                                        self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1716                                    }),
1717                            },
1718                        );
1719                    }
1720                    return Res::Err;
1721                }
1722            }
1723            _ => {}
1724        }
1725
1726        res
1727    }
1728
1729    #[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(1729u32),
                                    ::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))]
1730    pub(crate) fn maybe_resolve_path<'r>(
1731        self: CmResolver<'r, 'ra, 'tcx>,
1732        path: &[Segment],
1733        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1734        parent_scope: &ParentScope<'ra>,
1735        ignore_import: Option<Import<'ra>>,
1736    ) -> PathResult<'ra> {
1737        self.resolve_path_with_ribs(
1738            path,
1739            opt_ns,
1740            parent_scope,
1741            None,
1742            None,
1743            None,
1744            None,
1745            ignore_import,
1746            None,
1747        )
1748    }
1749    #[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(1749u32),
                                    ::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))]
1750    pub(crate) fn resolve_path<'r>(
1751        self: CmResolver<'r, 'ra, 'tcx>,
1752        path: &[Segment],
1753        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1754        parent_scope: &ParentScope<'ra>,
1755        finalize: Option<Finalize>,
1756        ignore_decl: Option<Decl<'ra>>,
1757        ignore_import: Option<Import<'ra>>,
1758    ) -> PathResult<'ra> {
1759        self.resolve_path_with_ribs(
1760            path,
1761            opt_ns,
1762            parent_scope,
1763            None,
1764            finalize,
1765            None,
1766            ignore_decl,
1767            ignore_import,
1768            None,
1769        )
1770    }
1771
1772    pub(crate) fn resolve_path_with_ribs<'r>(
1773        mut self: CmResolver<'r, 'ra, 'tcx>,
1774        path: &[Segment],
1775        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1776        parent_scope: &ParentScope<'ra>,
1777        source: Option<PathSource<'_, '_, '_>>,
1778        finalize: Option<Finalize>,
1779        ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
1780        ignore_decl: Option<Decl<'ra>>,
1781        ignore_import: Option<Import<'ra>>,
1782        diag_metadata: Option<&DiagMetadata<'_>>,
1783    ) -> PathResult<'ra> {
1784        let mut module = None;
1785        let mut module_had_parse_errors = !self.mods_with_parse_errors.is_empty()
1786            && self.mods_with_parse_errors.contains(&parent_scope.module.nearest_parent_mod());
1787        let mut allow_super = true;
1788        let mut second_binding = None;
1789
1790        // We'll provide more context to the privacy errors later, up to `len`.
1791        let privacy_errors_len = self.privacy_errors.len();
1792        fn record_segment_res<'r, 'ra, 'tcx>(
1793            mut this: CmResolver<'r, 'ra, 'tcx>,
1794            finalize: Option<Finalize>,
1795            res: Res,
1796            id: Option<NodeId>,
1797        ) {
1798            if finalize.is_some()
1799                && let Some(id) = id
1800                && !this.partial_res_map.contains_key(&id)
1801            {
1802                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");
1803                this.get_mut().record_partial_res(id, PartialRes::new(res));
1804            }
1805        }
1806
1807        for (segment_idx, &Segment { ident, id, .. }) in path.iter().enumerate() {
1808            {
    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:1808",
                        "rustc_resolve::ident", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                        ::tracing_core::__macro_support::Option::Some(1808u32),
                        ::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);
1809
1810            let is_last = segment_idx + 1 == path.len();
1811            let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1812            let name = ident.name;
1813
1814            allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super);
1815
1816            if ns == TypeNS {
1817                if allow_super && name == kw::Super {
1818                    let parent = if segment_idx == 0 {
1819                        self.resolve_super_in_module(ident, None, parent_scope)
1820                    } else if let Some(ModuleOrUniformRoot::Module(module)) = module {
1821                        self.resolve_super_in_module(ident, Some(module), parent_scope)
1822                    } else {
1823                        None
1824                    };
1825                    if let Some(parent) = parent {
1826                        module = Some(ModuleOrUniformRoot::Module(parent));
1827                        continue;
1828                    }
1829                    return PathResult::failed(
1830                        ident,
1831                        false,
1832                        finalize.is_some(),
1833                        module_had_parse_errors,
1834                        module,
1835                        || {
1836                            (
1837                                "too many leading `super` keywords".to_string(),
1838                                "there are too many leading `super` keywords".to_string(),
1839                                None,
1840                            )
1841                        },
1842                    );
1843                }
1844                if segment_idx == 0 {
1845                    if name == kw::SelfLower {
1846                        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1847                        let self_mod = self.resolve_self(&mut ctxt, parent_scope.module);
1848                        if let Some(res) = self_mod.res() {
1849                            record_segment_res(self.reborrow(), finalize, res, id);
1850                        }
1851                        module = Some(ModuleOrUniformRoot::Module(self_mod));
1852                        continue;
1853                    }
1854                    if name == kw::PathRoot && ident.span.at_least_rust_2018() {
1855                        module = Some(ModuleOrUniformRoot::ExternPrelude);
1856                        continue;
1857                    }
1858                    if name == kw::PathRoot
1859                        && ident.span.is_rust_2015()
1860                        && self.tcx.sess.at_least_rust_2018()
1861                    {
1862                        // `::a::b` from 2015 macro on 2018 global edition
1863                        let crate_root = self.resolve_crate_root(ident);
1864                        module = Some(ModuleOrUniformRoot::ModuleAndExternPrelude(crate_root));
1865                        continue;
1866                    }
1867                    if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate {
1868                        // `::a::b`, `crate::a::b` or `$crate::a::b`
1869                        let crate_root = self.resolve_crate_root(ident);
1870                        if let Some(res) = crate_root.res() {
1871                            record_segment_res(self.reborrow(), finalize, res, id);
1872                        }
1873                        module = Some(ModuleOrUniformRoot::Module(crate_root));
1874                        continue;
1875                    }
1876                }
1877            }
1878
1879            // Report special messages for path segment keywords in wrong positions.
1880            if ident.is_path_segment_keyword() && segment_idx != 0 {
1881                return PathResult::failed(
1882                    ident,
1883                    false,
1884                    finalize.is_some(),
1885                    module_had_parse_errors,
1886                    module,
1887                    || {
1888                        let name_str = if name == kw::PathRoot {
1889                            "the crate root".to_string()
1890                        } else {
1891                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", name))
    })format!("`{name}`")
1892                        };
1893                        let (message, label) = if segment_idx == 1
1894                            && path[0].ident.name == kw::PathRoot
1895                        {
1896                            (
1897                                ::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}"),
1898                                "cannot start with this".to_string(),
1899                            )
1900                        } else {
1901                            (
1902                                ::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"),
1903                                "can only be used in path start position".to_string(),
1904                            )
1905                        };
1906                        (message, label, None)
1907                    },
1908                );
1909            }
1910
1911            let binding = if let Some(module) = module {
1912                self.reborrow().resolve_ident_in_module(
1913                    module,
1914                    ident,
1915                    ns,
1916                    parent_scope,
1917                    finalize,
1918                    ignore_decl,
1919                    ignore_import,
1920                )
1921            } else if let Some(ribs) = ribs
1922                && let Some(TypeNS | ValueNS) = opt_ns
1923            {
1924                if !ignore_import.is_none() {
    ::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
1925                match self.get_mut().resolve_ident_in_lexical_scope(
1926                    ident,
1927                    ns,
1928                    parent_scope,
1929                    finalize,
1930                    &ribs[ns],
1931                    ignore_decl,
1932                    diag_metadata,
1933                ) {
1934                    // we found a locally-imported or available item/module
1935                    Some(LateDecl::Decl(binding)) => Ok(binding),
1936                    // we found a local variable or type param
1937                    Some(LateDecl::RibDef(res)) => {
1938                        record_segment_res(self.reborrow(), finalize, res, id);
1939                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
1940                            res,
1941                            path.len() - 1,
1942                        ));
1943                    }
1944                    _ => Err(Determinacy::determined(finalize.is_some())),
1945                }
1946            } else {
1947                self.reborrow().resolve_ident_in_scope_set(
1948                    ident,
1949                    ScopeSet::All(ns),
1950                    parent_scope,
1951                    finalize,
1952                    ignore_decl,
1953                    ignore_import,
1954                )
1955            };
1956
1957            match binding {
1958                Ok(binding) => {
1959                    if segment_idx == 1 {
1960                        second_binding = Some(binding);
1961                    }
1962                    let res = binding.res();
1963
1964                    // Mark every privacy error in this path with the res to the last element. This allows us
1965                    // to detect the item the user cares about and either find an alternative import, or tell
1966                    // the user it is not accessible.
1967                    if finalize.is_some() {
1968                        for error in &mut self.get_mut().privacy_errors[privacy_errors_len..] {
1969                            error.outermost_res = Some((res, ident));
1970                            error.source = match source {
1971                                Some(PathSource::Struct(Some(expr)))
1972                                | Some(PathSource::Expr(Some(expr))) => Some(expr.clone()),
1973                                _ => None,
1974                            };
1975                        }
1976                    }
1977
1978                    let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
1979                    if let Res::OpenMod(sym) = binding.res() {
1980                        module = Some(ModuleOrUniformRoot::OpenModule(sym));
1981                        record_segment_res(self.reborrow(), finalize, res, id);
1982                    } else if let Some(def_id) = binding.res().module_like_def_id() {
1983                        if self.mods_with_parse_errors.contains(&def_id) {
1984                            module_had_parse_errors = true;
1985                        }
1986                        module = Some(ModuleOrUniformRoot::Module(self.expect_module(def_id)));
1987                        record_segment_res(self.reborrow(), finalize, res, id);
1988                    } else if res == Res::ToolMod && !is_last && opt_ns.is_some() {
1989                        if binding.is_import() {
1990                            self.dcx().emit_err(errors::ToolModuleImported {
1991                                span: ident.span,
1992                                import: binding.span,
1993                            });
1994                        }
1995                        let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1996                        return PathResult::NonModule(PartialRes::new(res));
1997                    } else if res == Res::Err {
1998                        return PathResult::NonModule(PartialRes::new(Res::Err));
1999                    } else if opt_ns.is_some() && (is_last || maybe_assoc) {
2000                        if let Some(finalize) = finalize {
2001                            self.get_mut().lint_if_path_starts_with_module(
2002                                finalize,
2003                                path,
2004                                second_binding,
2005                            );
2006                        }
2007                        record_segment_res(self.reborrow(), finalize, res, id);
2008                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
2009                            res,
2010                            path.len() - segment_idx - 1,
2011                        ));
2012                    } else {
2013                        return PathResult::failed(
2014                            ident,
2015                            is_last,
2016                            finalize.is_some(),
2017                            module_had_parse_errors,
2018                            module,
2019                            || {
2020                                let label = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{2}` is {0} {1}, not a module",
                res.article(), res.descr(), ident))
    })format!(
2021                                    "`{ident}` is {} {}, not a module",
2022                                    res.article(),
2023                                    res.descr()
2024                                );
2025                                let scope = match &path[..segment_idx] {
2026                                    [.., prev] => {
2027                                        if prev.ident.name == kw::PathRoot {
2028                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the crate root"))
    })format!("the crate root")
2029                                        } else {
2030                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", prev.ident))
    })format!("`{}`", prev.ident)
2031                                        }
2032                                    }
2033                                    _ => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this scope"))
    })format!("this scope"),
2034                                };
2035                                // FIXME: reword, as the reason we expected a module is because of
2036                                // the following path segment.
2037                                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}");
2038                                (message, label, None)
2039                            },
2040                        );
2041                    }
2042                }
2043                Err(Undetermined) if finalize.is_none() => return PathResult::Indeterminate,
2044                Err(Determined | Undetermined) => {
2045                    if let Some(ModuleOrUniformRoot::Module(module)) = module
2046                        && opt_ns.is_some()
2047                        && !module.is_normal()
2048                    {
2049                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
2050                            module.res().unwrap(),
2051                            path.len() - segment_idx,
2052                        ));
2053                    }
2054
2055                    let mut this = self.reborrow();
2056                    return PathResult::failed(
2057                        ident,
2058                        is_last,
2059                        finalize.is_some(),
2060                        module_had_parse_errors,
2061                        module,
2062                        || {
2063                            this.get_mut().report_path_resolution_error(
2064                                path,
2065                                opt_ns,
2066                                parent_scope,
2067                                ribs,
2068                                ignore_decl,
2069                                ignore_import,
2070                                module,
2071                                segment_idx,
2072                                ident,
2073                                diag_metadata,
2074                            )
2075                        },
2076                    );
2077                }
2078            }
2079        }
2080
2081        if let Some(finalize) = finalize {
2082            self.get_mut().lint_if_path_starts_with_module(finalize, path, second_binding);
2083        }
2084
2085        PathResult::Module(match module {
2086            Some(module) => module,
2087            None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
2088            _ => ::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),
2089        })
2090    }
2091}