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 {
                        if ident.name == kw::SelfLower {
                            return Ok(module.self_decl.unwrap());
                        }
                        if ident.name == kw::Super &&
                                let Some(module) =
                                    self.resolve_super_in_module(ident, Some(module),
                                        parent_scope) {
                            return Ok(module.self_decl.unwrap());
                        }
                    }
                    let (ident_key, def) =
                        IdentKey::new_adjusted(ident, module.expansion);
                    let adjusted_parent_scope =
                        match def {
                            Some(def) =>
                                ParentScope {
                                    module: self.expn_def_scope(def),
                                    ..*parent_scope
                                },
                            None => *parent_scope,
                        };
                    self.resolve_ident_in_scope_set_inner(ident_key, ident.span,
                        ScopeSet::Module(ns, module), &adjusted_parent_scope,
                        finalize, ignore_decl, ignore_import)
                }
                ModuleOrUniformRoot::OpenModule(sym) => {
                    let open_ns_name =
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("{0}::{1}", sym.as_str(),
                                        ident.name))
                            });
                    let ns_ident =
                        IdentKey::with_root_ctxt(Symbol::intern(&open_ns_name));
                    match self.extern_prelude_get_flag(ns_ident, ident.span,
                            finalize.is_some()) {
                        Some(decl) => Ok(decl),
                        None => Err(Determinacy::Determined),
                    }
                }
                ModuleOrUniformRoot::ModuleAndExternPrelude(module) =>
                    self.resolve_ident_in_scope_set(ident,
                        ScopeSet::ModuleAndExternPrelude(ns, module), parent_scope,
                        finalize, ignore_decl, ignore_import),
                ModuleOrUniformRoot::ExternPrelude => {
                    if ns != TypeNS {
                        Err(Determined)
                    } else {
                        self.resolve_ident_in_scope_set_inner(IdentKey::new_adjusted(ident,
                                    ExpnId::root()).0, ident.span, ScopeSet::ExternPrelude,
                            parent_scope, finalize, ignore_decl, ignore_import)
                    }
                }
                ModuleOrUniformRoot::CurrentScope => {
                    if ns == TypeNS {
                        if ident.name == kw::SelfLower {
                            let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
                            let module =
                                self.resolve_self(&mut ctxt, parent_scope.module);
                            return Ok(module.self_decl.unwrap());
                        }
                        if ident.name == kw::Super &&
                                let Some(module) =
                                    self.resolve_super_in_module(ident, None, parent_scope) {
                            return Ok(module.self_decl.unwrap());
                        }
                        if ident.name == kw::Crate || ident.name == kw::DollarCrate
                                || self.path_root_is_crate_root(ident) {
                            let module = self.resolve_crate_root(ident);
                            return Ok(module.self_decl.unwrap());
                        } else if ident.name == kw::Super {}
                    }
                    self.resolve_ident_in_scope_set(ident, ScopeSet::All(ns),
                        parent_scope, finalize, ignore_decl, ignore_import)
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
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                    if ident.name == kw::SelfLower {
964                        return Ok(module.self_decl.unwrap());
965                    }
966                    if ident.name == kw::Super
967                        && let Some(module) =
968                            self.resolve_super_in_module(ident, Some(module), parent_scope)
969                    {
970                        return Ok(module.self_decl.unwrap());
971                    }
972                }
973
974                let (ident_key, def) = IdentKey::new_adjusted(ident, module.expansion);
975                let adjusted_parent_scope = match def {
976                    Some(def) => ParentScope { module: self.expn_def_scope(def), ..*parent_scope },
977                    None => *parent_scope,
978                };
979                self.resolve_ident_in_scope_set_inner(
980                    ident_key,
981                    ident.span,
982                    ScopeSet::Module(ns, module),
983                    &adjusted_parent_scope,
984                    finalize,
985                    ignore_decl,
986                    ignore_import,
987                )
988            }
989            ModuleOrUniformRoot::OpenModule(sym) => {
990                let open_ns_name = format!("{}::{}", sym.as_str(), ident.name);
991                let ns_ident = IdentKey::with_root_ctxt(Symbol::intern(&open_ns_name));
992                match self.extern_prelude_get_flag(ns_ident, ident.span, finalize.is_some()) {
993                    Some(decl) => Ok(decl),
994                    None => Err(Determinacy::Determined),
995                }
996            }
997            ModuleOrUniformRoot::ModuleAndExternPrelude(module) => self.resolve_ident_in_scope_set(
998                ident,
999                ScopeSet::ModuleAndExternPrelude(ns, module),
1000                parent_scope,
1001                finalize,
1002                ignore_decl,
1003                ignore_import,
1004            ),
1005            ModuleOrUniformRoot::ExternPrelude => {
1006                if ns != TypeNS {
1007                    Err(Determined)
1008                } else {
1009                    self.resolve_ident_in_scope_set_inner(
1010                        IdentKey::new_adjusted(ident, ExpnId::root()).0,
1011                        ident.span,
1012                        ScopeSet::ExternPrelude,
1013                        parent_scope,
1014                        finalize,
1015                        ignore_decl,
1016                        ignore_import,
1017                    )
1018                }
1019            }
1020            ModuleOrUniformRoot::CurrentScope => {
1021                if ns == TypeNS {
1022                    if ident.name == kw::SelfLower {
1023                        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1024                        let module = self.resolve_self(&mut ctxt, parent_scope.module);
1025                        return Ok(module.self_decl.unwrap());
1026                    }
1027                    if ident.name == kw::Super
1028                        && let Some(module) =
1029                            self.resolve_super_in_module(ident, None, parent_scope)
1030                    {
1031                        return Ok(module.self_decl.unwrap());
1032                    }
1033                    if ident.name == kw::Crate
1034                        || ident.name == kw::DollarCrate
1035                        || self.path_root_is_crate_root(ident)
1036                    {
1037                        let module = self.resolve_crate_root(ident);
1038                        return Ok(module.self_decl.unwrap());
1039                    } else if ident.name == kw::Super {
1040                        // FIXME: Implement these with renaming requirements so that e.g.
1041                        // `use super;` doesn't work, but `use super as name;` does.
1042                        // Fall through here to get an error from `early_resolve_...`.
1043                    }
1044                }
1045
1046                self.resolve_ident_in_scope_set(
1047                    ident,
1048                    ScopeSet::All(ns),
1049                    parent_scope,
1050                    finalize,
1051                    ignore_decl,
1052                    ignore_import,
1053                )
1054            }
1055        }
1056    }
1057
1058    /// Attempts to resolve `ident` in namespace `ns` of non-glob bindings in `module`.
1059    fn resolve_ident_in_module_non_globs_unadjusted<'r>(
1060        mut self: CmResolver<'r, 'ra, 'tcx>,
1061        module: Module<'ra>,
1062        ident: IdentKey,
1063        orig_ident_span: Span,
1064        ns: Namespace,
1065        parent_scope: &ParentScope<'ra>,
1066        shadowing: Shadowing,
1067        finalize: Option<Finalize>,
1068        // This binding should be ignored during in-module resolution, so that we don't get
1069        // "self-confirming" import resolutions during import validation and checking.
1070        ignore_decl: Option<Decl<'ra>>,
1071        ignore_import: Option<Import<'ra>>,
1072    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1073        let key = BindingKey::new(ident, ns);
1074        // `try_borrow_mut` is required to ensure exclusive access, even if the resulting binding
1075        // doesn't need to be mutable. It will fail when there is a cycle of imports, and without
1076        // the exclusive access infinite recursion will crash the compiler with stack overflow.
1077        let resolution = &*self
1078            .resolution_or_default(module, key, orig_ident_span)
1079            .try_borrow_mut_unchecked()
1080            .map_err(|_| ControlFlow::Continue(Determined))?;
1081
1082        let binding = resolution.non_glob_decl.filter(|b| Some(*b) != ignore_decl);
1083
1084        if let Some(finalize) = finalize {
1085            return self.get_mut().finalize_module_binding(
1086                ident,
1087                orig_ident_span,
1088                binding,
1089                parent_scope,
1090                module,
1091                finalize,
1092                shadowing,
1093            );
1094        }
1095
1096        // Items and single imports are not shadowable, if we have one, then it's determined.
1097        if let Some(binding) = binding {
1098            let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1099            return if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) };
1100        }
1101
1102        // Check if one of single imports can still define the name, block if it can.
1103        if self.reborrow().single_import_can_define_name(
1104            &resolution,
1105            None,
1106            ns,
1107            ignore_import,
1108            ignore_decl,
1109            parent_scope,
1110        ) {
1111            return Err(ControlFlow::Break(Undetermined));
1112        }
1113
1114        // Check if one of unexpanded macros can still define the name.
1115        if !module.unexpanded_invocations.borrow().is_empty() {
1116            return Err(ControlFlow::Continue(Undetermined));
1117        }
1118
1119        // No resolution and no one else can define the name - determinate error.
1120        Err(ControlFlow::Continue(Determined))
1121    }
1122
1123    /// Attempts to resolve `ident` in namespace `ns` of glob bindings in `module`.
1124    fn resolve_ident_in_module_globs_unadjusted<'r>(
1125        mut self: CmResolver<'r, 'ra, 'tcx>,
1126        module: Module<'ra>,
1127        ident: IdentKey,
1128        orig_ident_span: Span,
1129        ns: Namespace,
1130        parent_scope: &ParentScope<'ra>,
1131        shadowing: Shadowing,
1132        finalize: Option<Finalize>,
1133        ignore_decl: Option<Decl<'ra>>,
1134        ignore_import: Option<Import<'ra>>,
1135    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1136        let key = BindingKey::new(ident, ns);
1137        // `try_borrow_mut` is required to ensure exclusive access, even if the resulting binding
1138        // doesn't need to be mutable. It will fail when there is a cycle of imports, and without
1139        // the exclusive access infinite recursion will crash the compiler with stack overflow.
1140        let resolution = &*self
1141            .resolution_or_default(module, key, orig_ident_span)
1142            .try_borrow_mut_unchecked()
1143            .map_err(|_| ControlFlow::Continue(Determined))?;
1144
1145        let binding = resolution.glob_decl.filter(|b| Some(*b) != ignore_decl);
1146
1147        if let Some(finalize) = finalize {
1148            return self.get_mut().finalize_module_binding(
1149                ident,
1150                orig_ident_span,
1151                binding,
1152                parent_scope,
1153                module,
1154                finalize,
1155                shadowing,
1156            );
1157        }
1158
1159        // Check if one of single imports can still define the name,
1160        // if it can then our result is not determined and can be invalidated.
1161        if self.reborrow().single_import_can_define_name(
1162            &resolution,
1163            binding,
1164            ns,
1165            ignore_import,
1166            ignore_decl,
1167            parent_scope,
1168        ) {
1169            return Err(ControlFlow::Break(Undetermined));
1170        }
1171
1172        // So we have a resolution that's from a glob import. This resolution is determined
1173        // if it cannot be shadowed by some new item/import expanded from a macro.
1174        // This happens either if there are no unexpanded macros, or expanded names cannot
1175        // shadow globs (that happens in macro namespace or with restricted shadowing).
1176        //
1177        // Additionally, any macro in any module can plant names in the root module if it creates
1178        // `macro_export` macros, so the root module effectively has unresolved invocations if any
1179        // module has unresolved invocations.
1180        // However, it causes resolution/expansion to stuck too often (#53144), so, to make
1181        // progress, we have to ignore those potential unresolved invocations from other modules
1182        // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
1183        // shadowing is enabled, see `macro_expanded_macro_export_errors`).
1184        if let Some(binding) = binding {
1185            return if binding.determined() || ns == MacroNS || shadowing == Shadowing::Restricted {
1186                let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1187                if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) }
1188            } else {
1189                Err(ControlFlow::Break(Undetermined))
1190            };
1191        }
1192
1193        // Now we are in situation when new item/import can appear only from a glob or a macro
1194        // expansion. With restricted shadowing names from globs and macro expansions cannot
1195        // shadow names from outer scopes, so we can freely fallback from module search to search
1196        // in outer scopes. For `resolve_ident_in_scope_set` to continue search in outer
1197        // scopes we return `Undetermined` with `ControlFlow::Continue`.
1198        // Check if one of unexpanded macros can still define the name,
1199        // if it can then our "no resolution" result is not determined and can be invalidated.
1200        if !module.unexpanded_invocations.borrow().is_empty() {
1201            return Err(ControlFlow::Continue(Undetermined));
1202        }
1203
1204        // Check if one of glob imports can still define the name,
1205        // if it can then our "no resolution" result is not determined and can be invalidated.
1206        for glob_import in module.globs.borrow().iter() {
1207            if ignore_import == Some(*glob_import) {
1208                continue;
1209            }
1210            if !self.is_accessible_from(glob_import.vis, parent_scope.module) {
1211                continue;
1212            }
1213            let module = match glob_import.imported_module.get() {
1214                Some(ModuleOrUniformRoot::Module(module)) => module,
1215                Some(_) => continue,
1216                None => return Err(ControlFlow::Continue(Undetermined)),
1217            };
1218            let tmp_parent_scope;
1219            let (mut adjusted_parent_scope, mut adjusted_ident) = (parent_scope, ident);
1220            match adjusted_ident
1221                .ctxt
1222                .update_unchecked(|ctxt| ctxt.glob_adjust(module.expansion, glob_import.span))
1223            {
1224                Some(Some(def)) => {
1225                    tmp_parent_scope =
1226                        ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
1227                    adjusted_parent_scope = &tmp_parent_scope;
1228                }
1229                Some(None) => {}
1230                None => continue,
1231            };
1232            let result = self.reborrow().resolve_ident_in_scope_set_inner(
1233                adjusted_ident,
1234                orig_ident_span,
1235                ScopeSet::Module(ns, module),
1236                adjusted_parent_scope,
1237                None,
1238                ignore_decl,
1239                ignore_import,
1240            );
1241
1242            match result {
1243                Err(Determined) => continue,
1244                Ok(binding)
1245                    if !self.is_accessible_from(binding.vis(), glob_import.parent_scope.module) =>
1246                {
1247                    continue;
1248                }
1249                Ok(_) | Err(Undetermined) => return Err(ControlFlow::Continue(Undetermined)),
1250            }
1251        }
1252
1253        // No resolution and no one else can define the name - determinate error.
1254        Err(ControlFlow::Continue(Determined))
1255    }
1256
1257    fn finalize_module_binding(
1258        &mut self,
1259        ident: IdentKey,
1260        orig_ident_span: Span,
1261        binding: Option<Decl<'ra>>,
1262        parent_scope: &ParentScope<'ra>,
1263        module: Module<'ra>,
1264        finalize: Finalize,
1265        shadowing: Shadowing,
1266    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1267        let Finalize { path_span, report_private, used, root_span, .. } = finalize;
1268
1269        let Some(binding) = binding else {
1270            return Err(ControlFlow::Continue(Determined));
1271        };
1272
1273        let ident = ident.orig(orig_ident_span);
1274        if !self.is_accessible_from(binding.vis(), parent_scope.module) {
1275            if report_private {
1276                self.privacy_errors.push(PrivacyError {
1277                    ident,
1278                    decl: binding,
1279                    dedup_span: path_span,
1280                    outermost_res: None,
1281                    source: None,
1282                    parent_scope: *parent_scope,
1283                    single_nested: path_span != root_span,
1284                });
1285            } else {
1286                return Err(ControlFlow::Break(Determined));
1287            }
1288        }
1289
1290        if shadowing == Shadowing::Unrestricted
1291            && binding.expansion != LocalExpnId::ROOT
1292            && let DeclKind::Import { import, .. } = binding.kind
1293            && #[allow(non_exhaustive_omitted_patterns)] match import.kind {
    ImportKind::MacroExport => true,
    _ => false,
}matches!(import.kind, ImportKind::MacroExport)
1294        {
1295            self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
1296        }
1297
1298        // If we encounter a re-export for a type with private fields, it will not be able to
1299        // be constructed through this re-export. We track that case here to expand later
1300        // privacy errors with appropriate information.
1301        if let Res::Def(_, def_id) = binding.res() {
1302            let struct_ctor = match def_id.as_local() {
1303                Some(def_id) => self.struct_constructors.get(&def_id).cloned(),
1304                None => {
1305                    let ctor = self.cstore().ctor_untracked(self.tcx(), def_id);
1306                    ctor.map(|(ctor_kind, ctor_def_id)| {
1307                        let ctor_res = Res::Def(
1308                            DefKind::Ctor(rustc_hir::def::CtorOf::Struct, ctor_kind),
1309                            ctor_def_id,
1310                        );
1311                        let ctor_vis = self.tcx.visibility(ctor_def_id);
1312                        let field_visibilities = self
1313                            .tcx
1314                            .associated_item_def_ids(def_id)
1315                            .iter()
1316                            .map(|&field_id| self.tcx.visibility(field_id))
1317                            .collect();
1318                        (ctor_res, ctor_vis, field_visibilities)
1319                    })
1320                }
1321            };
1322            if let Some((_, _, fields)) = struct_ctor
1323                && fields.iter().any(|vis| !self.is_accessible_from(*vis, module))
1324            {
1325                self.inaccessible_ctor_reexport.insert(path_span, binding.span);
1326            }
1327        }
1328
1329        self.record_use(ident, binding, used);
1330        return Ok(binding);
1331    }
1332
1333    // Checks if a single import can define the `Ident` corresponding to `binding`.
1334    // This is used to check whether we can definitively accept a glob as a resolution.
1335    fn single_import_can_define_name<'r>(
1336        mut self: CmResolver<'r, 'ra, 'tcx>,
1337        resolution: &NameResolution<'ra>,
1338        binding: Option<Decl<'ra>>,
1339        ns: Namespace,
1340        ignore_import: Option<Import<'ra>>,
1341        ignore_decl: Option<Decl<'ra>>,
1342        parent_scope: &ParentScope<'ra>,
1343    ) -> bool {
1344        for single_import in &resolution.single_imports {
1345            if let Some(decl) = resolution.non_glob_decl
1346                && let DeclKind::Import { import, .. } = decl.kind
1347                && import == *single_import
1348            {
1349                // Single import has already defined the name and we are aware of it,
1350                // no need to block the globs.
1351                continue;
1352            }
1353            if ignore_import == Some(*single_import) {
1354                continue;
1355            }
1356            if !self.is_accessible_from(single_import.vis, parent_scope.module) {
1357                continue;
1358            }
1359            if let Some(ignored) = ignore_decl
1360                && let DeclKind::Import { import, .. } = ignored.kind
1361                && import == *single_import
1362            {
1363                continue;
1364            }
1365
1366            let Some(module) = single_import.imported_module.get() else {
1367                return true;
1368            };
1369            let ImportKind::Single { source, target, decls, .. } = &single_import.kind else {
1370                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1371            };
1372            if source != target {
1373                if decls.iter().all(|d| d.get().decl().is_none()) {
1374                    return true;
1375                } else if decls[ns].get().decl().is_none() && binding.is_some() {
1376                    return true;
1377                }
1378            }
1379
1380            match self.reborrow().resolve_ident_in_module(
1381                module,
1382                *source,
1383                ns,
1384                &single_import.parent_scope,
1385                None,
1386                ignore_decl,
1387                None,
1388            ) {
1389                Err(Determined) => continue,
1390                Ok(binding)
1391                    if !self
1392                        .is_accessible_from(binding.vis(), single_import.parent_scope.module) =>
1393                {
1394                    continue;
1395                }
1396                Ok(_) | Err(Undetermined) => return true,
1397            }
1398        }
1399
1400        false
1401    }
1402
1403    /// Validate a local resolution (from ribs).
1404    #[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(1404u32),
                                    ::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:1415",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1415u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("validate_res_from_ribs({0:?})",
                                                                res) as &dyn Value))])
                        });
                } else { ; }
            };
            let ribs = &all_ribs[rib_index + 1..];
            if let RibKind::ForwardGenericParamBan(reason) =
                    all_ribs[rib_index].kind {
                if let Some(span) = finalize {
                    let res_error =
                        if rib_ident.name == kw::SelfUpper {
                            ResolutionError::ForwardDeclaredSelf(reason)
                        } else {
                            ResolutionError::ForwardDeclaredGenericParam(rib_ident.name,
                                reason)
                        };
                    self.report_error(span, res_error);
                }
                match (&res, &Res::Err) {
                    (left_val, right_val) => {
                        if !(*left_val == *right_val) {
                            let kind = ::core::panicking::AssertKind::Eq;
                            ::core::panicking::assert_failed(kind, &*left_val,
                                &*right_val, ::core::option::Option::None);
                        }
                    }
                };
                return Res::Err;
            }
            match res {
                Res::Local(_) => {
                    use ResolutionError::*;
                    let mut res_err = None;
                    for rib in ribs {
                        match rib.kind {
                            RibKind::Normal | RibKind::Block(..) |
                                RibKind::FnOrCoroutine | RibKind::Module(..) |
                                RibKind::MacroDefinition(..) |
                                RibKind::ForwardGenericParamBan(_) => {}
                            RibKind::Item(..) | RibKind::AssocItem => {
                                if let Some(span) = finalize {
                                    res_err =
                                        Some((span, CannotCaptureDynamicEnvironmentInFnItem));
                                }
                            }
                            RibKind::ConstantItem(_, item) => {
                                if let Some(span) = finalize {
                                    let (span, resolution_error) =
                                        match item {
                                            None if rib_ident.name == kw::SelfLower => {
                                                (span, LowercaseSelf)
                                            }
                                            None => {
                                                let sm = self.tcx.sess.source_map();
                                                let type_span =
                                                    match sm.span_followed_by(original_rib_ident_def.span, ":")
                                                        {
                                                        None => { Some(original_rib_ident_def.span.shrink_to_hi()) }
                                                        Some(_) => None,
                                                    };
                                                (rib_ident.span,
                                                    AttemptToUseNonConstantValueInConstant {
                                                        ident: original_rib_ident_def,
                                                        suggestion: "const",
                                                        current: "let",
                                                        type_span,
                                                    })
                                            }
                                            Some((ident, kind)) =>
                                                (span,
                                                    AttemptToUseNonConstantValueInConstant {
                                                        ident,
                                                        suggestion: "let",
                                                        current: kind.as_str(),
                                                        type_span: None,
                                                    }),
                                        };
                                    self.report_error(span, resolution_error);
                                }
                                return Res::Err;
                            }
                            RibKind::ConstParamTy => {
                                if let Some(span) = finalize {
                                    self.report_error(span,
                                        ParamInTyOfConstParam { name: rib_ident.name });
                                }
                                return Res::Err;
                            }
                            RibKind::InlineAsmSym => {
                                if let Some(span) = finalize {
                                    self.report_error(span, InvalidAsmSym);
                                }
                                return Res::Err;
                            }
                        }
                    }
                    if let Some((span, res_err)) = res_err {
                        self.report_error(span, res_err);
                        return Res::Err;
                    }
                }
                Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } |
                    Res::SelfTyAlias { .. } => {
                    for rib in ribs {
                        let (has_generic_params, def_kind) =
                            match rib.kind {
                                RibKind::Normal | RibKind::Block(..) |
                                    RibKind::FnOrCoroutine | RibKind::Module(..) |
                                    RibKind::MacroDefinition(..) | RibKind::InlineAsmSym |
                                    RibKind::AssocItem | RibKind::ForwardGenericParamBan(_) => {
                                    continue;
                                }
                                RibKind::ConstParamTy => {
                                    if !self.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_gca: self.tcx.features().generic_const_args(),
                                                            name: rib_ident.name,
                                                            param_kind: ParamKindInNonTrivialAnonConst::Type,
                                                        }
                                                    }
                                                };
                                            let _: ErrorGuaranteed = self.report_error(span, error);
                                        }
                                        return Res::Err;
                                    }
                                    continue;
                                }
                                RibKind::Item(has_generic_params, def_kind) => {
                                    (has_generic_params, def_kind)
                                }
                            };
                        if let Some(span) = finalize {
                            let item =
                                if let Some(diag_metadata) = diag_metadata &&
                                        let Some(current_item) = diag_metadata.current_item {
                                    let 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_gca: self.tcx.features().generic_const_args(),
                                                            name: rib_ident.name,
                                                            param_kind: ParamKindInNonTrivialAnonConst::Const {
                                                                name: rib_ident.name,
                                                            },
                                                        }
                                                    }
                                                };
                                            self.report_error(span, error);
                                        }
                                        return Res::Err;
                                    }
                                    continue;
                                }
                                RibKind::Item(has_generic_params, def_kind) => {
                                    (has_generic_params, def_kind)
                                }
                            };
                        if let Some(span) = finalize {
                            let item =
                                if let Some(diag_metadata) = diag_metadata &&
                                        let Some(current_item) = diag_metadata.current_item {
                                    let 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))]
1405    fn validate_res_from_ribs(
1406        &mut self,
1407        rib_index: usize,
1408        rib_ident: Ident,
1409        res: Res,
1410        finalize: Option<Span>,
1411        original_rib_ident_def: Ident,
1412        all_ribs: &[Rib<'ra>],
1413        diag_metadata: Option<&DiagMetadata<'_>>,
1414    ) -> Res {
1415        debug!("validate_res_from_ribs({:?})", res);
1416        let ribs = &all_ribs[rib_index + 1..];
1417
1418        // An invalid forward use of a generic parameter from a previous default
1419        // or in a const param ty.
1420        if let RibKind::ForwardGenericParamBan(reason) = all_ribs[rib_index].kind {
1421            if let Some(span) = finalize {
1422                let res_error = if rib_ident.name == kw::SelfUpper {
1423                    ResolutionError::ForwardDeclaredSelf(reason)
1424                } else {
1425                    ResolutionError::ForwardDeclaredGenericParam(rib_ident.name, reason)
1426                };
1427                self.report_error(span, res_error);
1428            }
1429            assert_eq!(res, Res::Err);
1430            return Res::Err;
1431        }
1432
1433        match res {
1434            Res::Local(_) => {
1435                use ResolutionError::*;
1436                let mut res_err = None;
1437
1438                for rib in ribs {
1439                    match rib.kind {
1440                        RibKind::Normal
1441                        | RibKind::Block(..)
1442                        | RibKind::FnOrCoroutine
1443                        | RibKind::Module(..)
1444                        | RibKind::MacroDefinition(..)
1445                        | RibKind::ForwardGenericParamBan(_) => {
1446                            // Nothing to do. Continue.
1447                        }
1448                        RibKind::Item(..) | RibKind::AssocItem => {
1449                            // This was an attempt to access an upvar inside a
1450                            // named function item. This is not allowed, so we
1451                            // report an error.
1452                            if let Some(span) = finalize {
1453                                // We don't immediately trigger a resolve error, because
1454                                // we want certain other resolution errors (namely those
1455                                // emitted for `ConstantItemRibKind` below) to take
1456                                // precedence.
1457                                res_err = Some((span, CannotCaptureDynamicEnvironmentInFnItem));
1458                            }
1459                        }
1460                        RibKind::ConstantItem(_, item) => {
1461                            // Still doesn't deal with upvars
1462                            if let Some(span) = finalize {
1463                                let (span, resolution_error) = match item {
1464                                    None if rib_ident.name == kw::SelfLower => {
1465                                        (span, LowercaseSelf)
1466                                    }
1467                                    None => {
1468                                        // If we have a `let name = expr;`, we have the span for
1469                                        // `name` and use that to see if it is followed by a type
1470                                        // specifier. If not, then we know we need to suggest
1471                                        // `const name: Ty = expr;`. This is a heuristic, it will
1472                                        // break down in the presence of macros.
1473                                        let sm = self.tcx.sess.source_map();
1474                                        let type_span = match sm
1475                                            .span_followed_by(original_rib_ident_def.span, ":")
1476                                        {
1477                                            None => {
1478                                                Some(original_rib_ident_def.span.shrink_to_hi())
1479                                            }
1480                                            Some(_) => None,
1481                                        };
1482                                        (
1483                                            rib_ident.span,
1484                                            AttemptToUseNonConstantValueInConstant {
1485                                                ident: original_rib_ident_def,
1486                                                suggestion: "const",
1487                                                current: "let",
1488                                                type_span,
1489                                            },
1490                                        )
1491                                    }
1492                                    Some((ident, kind)) => (
1493                                        span,
1494                                        AttemptToUseNonConstantValueInConstant {
1495                                            ident,
1496                                            suggestion: "let",
1497                                            current: kind.as_str(),
1498                                            type_span: None,
1499                                        },
1500                                    ),
1501                                };
1502                                self.report_error(span, resolution_error);
1503                            }
1504                            return Res::Err;
1505                        }
1506                        RibKind::ConstParamTy => {
1507                            if let Some(span) = finalize {
1508                                self.report_error(
1509                                    span,
1510                                    ParamInTyOfConstParam { name: rib_ident.name },
1511                                );
1512                            }
1513                            return Res::Err;
1514                        }
1515                        RibKind::InlineAsmSym => {
1516                            if let Some(span) = finalize {
1517                                self.report_error(span, InvalidAsmSym);
1518                            }
1519                            return Res::Err;
1520                        }
1521                    }
1522                }
1523                if let Some((span, res_err)) = res_err {
1524                    self.report_error(span, res_err);
1525                    return Res::Err;
1526                }
1527            }
1528            Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {
1529                for rib in ribs {
1530                    let (has_generic_params, def_kind) = match rib.kind {
1531                        RibKind::Normal
1532                        | RibKind::Block(..)
1533                        | RibKind::FnOrCoroutine
1534                        | RibKind::Module(..)
1535                        | RibKind::MacroDefinition(..)
1536                        | RibKind::InlineAsmSym
1537                        | RibKind::AssocItem
1538                        | RibKind::ForwardGenericParamBan(_) => {
1539                            // Nothing to do. Continue.
1540                            continue;
1541                        }
1542
1543                        RibKind::ConstParamTy => {
1544                            if !self.tcx.features().generic_const_parameter_types() {
1545                                if let Some(span) = finalize {
1546                                    self.report_error(
1547                                        span,
1548                                        ResolutionError::ParamInTyOfConstParam {
1549                                            name: rib_ident.name,
1550                                        },
1551                                    );
1552                                }
1553                                return Res::Err;
1554                            } else {
1555                                continue;
1556                            }
1557                        }
1558
1559                        RibKind::ConstantItem(trivial, _) => {
1560                            if let ConstantHasGenerics::No(cause) = trivial
1561                                && !matches!(res, Res::SelfTyAlias { .. })
1562                            {
1563                                if let Some(span) = finalize {
1564                                    let error = match cause {
1565                                        NoConstantGenericsReason::IsEnumDiscriminant => {
1566                                            ResolutionError::ParamInEnumDiscriminant {
1567                                                name: rib_ident.name,
1568                                                param_kind: ParamKindInEnumDiscriminant::Type,
1569                                            }
1570                                        }
1571                                        NoConstantGenericsReason::NonTrivialConstArg => {
1572                                            ResolutionError::ParamInNonTrivialAnonConst {
1573                                                is_gca: self.tcx.features().generic_const_args(),
1574                                                name: rib_ident.name,
1575                                                param_kind: ParamKindInNonTrivialAnonConst::Type,
1576                                            }
1577                                        }
1578                                    };
1579                                    let _: ErrorGuaranteed = self.report_error(span, error);
1580                                }
1581
1582                                return Res::Err;
1583                            }
1584
1585                            continue;
1586                        }
1587
1588                        // This was an attempt to use a type parameter outside its scope.
1589                        RibKind::Item(has_generic_params, def_kind) => {
1590                            (has_generic_params, def_kind)
1591                        }
1592                    };
1593
1594                    if let Some(span) = finalize {
1595                        let item = if let Some(diag_metadata) = diag_metadata
1596                            && let Some(current_item) = diag_metadata.current_item
1597                        {
1598                            let span = current_item
1599                                .kind
1600                                .ident()
1601                                .map(|i| i.span)
1602                                .unwrap_or(current_item.span);
1603                            Some((span, current_item.kind.clone()))
1604                        } else {
1605                            None
1606                        };
1607                        self.report_error(
1608                            span,
1609                            ResolutionError::GenericParamsFromOuterItem {
1610                                outer_res: res,
1611                                has_generic_params,
1612                                def_kind,
1613                                inner_item: item,
1614                                current_self_ty: diag_metadata
1615                                    .and_then(|m| m.current_self_type.as_ref())
1616                                    .and_then(|ty| {
1617                                        self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1618                                    }),
1619                            },
1620                        );
1621                    }
1622                    return Res::Err;
1623                }
1624            }
1625            Res::Def(DefKind::ConstParam, _) => {
1626                for rib in ribs {
1627                    let (has_generic_params, def_kind) = match rib.kind {
1628                        RibKind::Normal
1629                        | RibKind::Block(..)
1630                        | RibKind::FnOrCoroutine
1631                        | RibKind::Module(..)
1632                        | RibKind::MacroDefinition(..)
1633                        | RibKind::InlineAsmSym
1634                        | RibKind::AssocItem
1635                        | RibKind::ForwardGenericParamBan(_) => continue,
1636
1637                        RibKind::ConstParamTy => {
1638                            if !self.tcx.features().generic_const_parameter_types() {
1639                                if let Some(span) = finalize {
1640                                    self.report_error(
1641                                        span,
1642                                        ResolutionError::ParamInTyOfConstParam {
1643                                            name: rib_ident.name,
1644                                        },
1645                                    );
1646                                }
1647                                return Res::Err;
1648                            } else {
1649                                continue;
1650                            }
1651                        }
1652
1653                        RibKind::ConstantItem(trivial, _) => {
1654                            if let ConstantHasGenerics::No(cause) = trivial {
1655                                if let Some(span) = finalize {
1656                                    let error = match cause {
1657                                        NoConstantGenericsReason::IsEnumDiscriminant => {
1658                                            ResolutionError::ParamInEnumDiscriminant {
1659                                                name: rib_ident.name,
1660                                                param_kind: ParamKindInEnumDiscriminant::Const,
1661                                            }
1662                                        }
1663                                        NoConstantGenericsReason::NonTrivialConstArg => {
1664                                            ResolutionError::ParamInNonTrivialAnonConst {
1665                                                is_gca: self.tcx.features().generic_const_args(),
1666                                                name: rib_ident.name,
1667                                                param_kind: ParamKindInNonTrivialAnonConst::Const {
1668                                                    name: rib_ident.name,
1669                                                },
1670                                            }
1671                                        }
1672                                    };
1673                                    self.report_error(span, error);
1674                                }
1675
1676                                return Res::Err;
1677                            }
1678
1679                            continue;
1680                        }
1681
1682                        RibKind::Item(has_generic_params, def_kind) => {
1683                            (has_generic_params, def_kind)
1684                        }
1685                    };
1686
1687                    // This was an attempt to use a const parameter outside its scope.
1688                    if let Some(span) = finalize {
1689                        let item = if let Some(diag_metadata) = diag_metadata
1690                            && let Some(current_item) = diag_metadata.current_item
1691                        {
1692                            let span = current_item
1693                                .kind
1694                                .ident()
1695                                .map(|i| i.span)
1696                                .unwrap_or(current_item.span);
1697                            Some((span, current_item.kind.clone()))
1698                        } else {
1699                            None
1700                        };
1701                        self.report_error(
1702                            span,
1703                            ResolutionError::GenericParamsFromOuterItem {
1704                                outer_res: res,
1705                                has_generic_params,
1706                                def_kind,
1707                                inner_item: item,
1708                                current_self_ty: diag_metadata
1709                                    .and_then(|m| m.current_self_type.as_ref())
1710                                    .and_then(|ty| {
1711                                        self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1712                                    }),
1713                            },
1714                        );
1715                    }
1716                    return Res::Err;
1717                }
1718            }
1719            _ => {}
1720        }
1721
1722        res
1723    }
1724
1725    #[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(1725u32),
                                    ::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))]
1726    pub(crate) fn maybe_resolve_path<'r>(
1727        self: CmResolver<'r, 'ra, 'tcx>,
1728        path: &[Segment],
1729        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1730        parent_scope: &ParentScope<'ra>,
1731        ignore_import: Option<Import<'ra>>,
1732    ) -> PathResult<'ra> {
1733        self.resolve_path_with_ribs(
1734            path,
1735            opt_ns,
1736            parent_scope,
1737            None,
1738            None,
1739            None,
1740            None,
1741            ignore_import,
1742            None,
1743        )
1744    }
1745    #[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(1745u32),
                                    ::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))]
1746    pub(crate) fn resolve_path<'r>(
1747        self: CmResolver<'r, 'ra, 'tcx>,
1748        path: &[Segment],
1749        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1750        parent_scope: &ParentScope<'ra>,
1751        finalize: Option<Finalize>,
1752        ignore_decl: Option<Decl<'ra>>,
1753        ignore_import: Option<Import<'ra>>,
1754    ) -> PathResult<'ra> {
1755        self.resolve_path_with_ribs(
1756            path,
1757            opt_ns,
1758            parent_scope,
1759            None,
1760            finalize,
1761            None,
1762            ignore_decl,
1763            ignore_import,
1764            None,
1765        )
1766    }
1767
1768    pub(crate) fn resolve_path_with_ribs<'r>(
1769        mut self: CmResolver<'r, 'ra, 'tcx>,
1770        path: &[Segment],
1771        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1772        parent_scope: &ParentScope<'ra>,
1773        source: Option<PathSource<'_, '_, '_>>,
1774        finalize: Option<Finalize>,
1775        ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
1776        ignore_decl: Option<Decl<'ra>>,
1777        ignore_import: Option<Import<'ra>>,
1778        diag_metadata: Option<&DiagMetadata<'_>>,
1779    ) -> PathResult<'ra> {
1780        let mut module = None;
1781        let mut module_had_parse_errors = !self.mods_with_parse_errors.is_empty()
1782            && self.mods_with_parse_errors.contains(&parent_scope.module.nearest_parent_mod());
1783        let mut allow_super = true;
1784        let mut second_binding = None;
1785
1786        // We'll provide more context to the privacy errors later, up to `len`.
1787        let privacy_errors_len = self.privacy_errors.len();
1788        fn record_segment_res<'r, 'ra, 'tcx>(
1789            mut this: CmResolver<'r, 'ra, 'tcx>,
1790            finalize: Option<Finalize>,
1791            res: Res,
1792            id: Option<NodeId>,
1793        ) {
1794            if finalize.is_some()
1795                && let Some(id) = id
1796                && !this.partial_res_map.contains_key(&id)
1797            {
1798                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");
1799                this.get_mut().record_partial_res(id, PartialRes::new(res));
1800            }
1801        }
1802
1803        for (segment_idx, &Segment { ident, id, .. }) in path.iter().enumerate() {
1804            {
    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:1804",
                        "rustc_resolve::ident", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                        ::tracing_core::__macro_support::Option::Some(1804u32),
                        ::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);
1805
1806            let is_last = segment_idx + 1 == path.len();
1807            let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1808            let name = ident.name;
1809
1810            allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super);
1811
1812            if ns == TypeNS {
1813                if allow_super && name == kw::Super {
1814                    let parent = if segment_idx == 0 {
1815                        self.resolve_super_in_module(ident, None, parent_scope)
1816                    } else if let Some(ModuleOrUniformRoot::Module(module)) = module {
1817                        self.resolve_super_in_module(ident, Some(module), parent_scope)
1818                    } else {
1819                        None
1820                    };
1821                    if let Some(parent) = parent {
1822                        module = Some(ModuleOrUniformRoot::Module(parent));
1823                        continue;
1824                    }
1825                    return PathResult::failed(
1826                        ident,
1827                        false,
1828                        finalize.is_some(),
1829                        module_had_parse_errors,
1830                        module,
1831                        || {
1832                            (
1833                                "too many leading `super` keywords".to_string(),
1834                                "there are too many leading `super` keywords".to_string(),
1835                                None,
1836                            )
1837                        },
1838                    );
1839                }
1840                if segment_idx == 0 {
1841                    if name == kw::SelfLower {
1842                        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1843                        let self_mod = self.resolve_self(&mut ctxt, parent_scope.module);
1844                        if let Some(res) = self_mod.res() {
1845                            record_segment_res(self.reborrow(), finalize, res, id);
1846                        }
1847                        module = Some(ModuleOrUniformRoot::Module(self_mod));
1848                        continue;
1849                    }
1850                    if name == kw::PathRoot && ident.span.at_least_rust_2018() {
1851                        module = Some(ModuleOrUniformRoot::ExternPrelude);
1852                        continue;
1853                    }
1854                    if name == kw::PathRoot
1855                        && ident.span.is_rust_2015()
1856                        && self.tcx.sess.at_least_rust_2018()
1857                    {
1858                        // `::a::b` from 2015 macro on 2018 global edition
1859                        let crate_root = self.resolve_crate_root(ident);
1860                        module = Some(ModuleOrUniformRoot::ModuleAndExternPrelude(crate_root));
1861                        continue;
1862                    }
1863                    if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate {
1864                        // `::a::b`, `crate::a::b` or `$crate::a::b`
1865                        let crate_root = self.resolve_crate_root(ident);
1866                        if let Some(res) = crate_root.res() {
1867                            record_segment_res(self.reborrow(), finalize, res, id);
1868                        }
1869                        module = Some(ModuleOrUniformRoot::Module(crate_root));
1870                        continue;
1871                    }
1872                }
1873            }
1874
1875            // Report special messages for path segment keywords in wrong positions.
1876            if ident.is_path_segment_keyword() && segment_idx != 0 {
1877                return PathResult::failed(
1878                    ident,
1879                    false,
1880                    finalize.is_some(),
1881                    module_had_parse_errors,
1882                    module,
1883                    || {
1884                        let name_str = if name == kw::PathRoot {
1885                            "the crate root".to_string()
1886                        } else {
1887                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", name))
    })format!("`{name}`")
1888                        };
1889                        let (message, label) = if segment_idx == 1
1890                            && path[0].ident.name == kw::PathRoot
1891                        {
1892                            (
1893                                ::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}"),
1894                                "cannot start with this".to_string(),
1895                            )
1896                        } else {
1897                            (
1898                                ::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"),
1899                                "can only be used in path start position".to_string(),
1900                            )
1901                        };
1902                        (message, label, None)
1903                    },
1904                );
1905            }
1906
1907            let binding = if let Some(module) = module {
1908                self.reborrow().resolve_ident_in_module(
1909                    module,
1910                    ident,
1911                    ns,
1912                    parent_scope,
1913                    finalize,
1914                    ignore_decl,
1915                    ignore_import,
1916                )
1917            } else if let Some(ribs) = ribs
1918                && let Some(TypeNS | ValueNS) = opt_ns
1919            {
1920                if !ignore_import.is_none() {
    ::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
1921                match self.get_mut().resolve_ident_in_lexical_scope(
1922                    ident,
1923                    ns,
1924                    parent_scope,
1925                    finalize,
1926                    &ribs[ns],
1927                    ignore_decl,
1928                    diag_metadata,
1929                ) {
1930                    // we found a locally-imported or available item/module
1931                    Some(LateDecl::Decl(binding)) => Ok(binding),
1932                    // we found a local variable or type param
1933                    Some(LateDecl::RibDef(res)) => {
1934                        record_segment_res(self.reborrow(), finalize, res, id);
1935                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
1936                            res,
1937                            path.len() - 1,
1938                        ));
1939                    }
1940                    _ => Err(Determinacy::determined(finalize.is_some())),
1941                }
1942            } else {
1943                self.reborrow().resolve_ident_in_scope_set(
1944                    ident,
1945                    ScopeSet::All(ns),
1946                    parent_scope,
1947                    finalize,
1948                    ignore_decl,
1949                    ignore_import,
1950                )
1951            };
1952
1953            match binding {
1954                Ok(binding) => {
1955                    if segment_idx == 1 {
1956                        second_binding = Some(binding);
1957                    }
1958                    let res = binding.res();
1959
1960                    // Mark every privacy error in this path with the res to the last element. This allows us
1961                    // to detect the item the user cares about and either find an alternative import, or tell
1962                    // the user it is not accessible.
1963                    if finalize.is_some() {
1964                        for error in &mut self.get_mut().privacy_errors[privacy_errors_len..] {
1965                            error.outermost_res = Some((res, ident));
1966                            error.source = match source {
1967                                Some(PathSource::Struct(Some(expr)))
1968                                | Some(PathSource::Expr(Some(expr))) => Some(expr.clone()),
1969                                _ => None,
1970                            };
1971                        }
1972                    }
1973
1974                    let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
1975                    if let Res::OpenMod(sym) = binding.res() {
1976                        module = Some(ModuleOrUniformRoot::OpenModule(sym));
1977                        record_segment_res(self.reborrow(), finalize, res, id);
1978                    } else if let Some(def_id) = binding.res().module_like_def_id() {
1979                        if self.mods_with_parse_errors.contains(&def_id) {
1980                            module_had_parse_errors = true;
1981                        }
1982                        module = Some(ModuleOrUniformRoot::Module(self.expect_module(def_id)));
1983                        record_segment_res(self.reborrow(), finalize, res, id);
1984                    } else if res == Res::ToolMod && !is_last && opt_ns.is_some() {
1985                        if binding.is_import() {
1986                            self.dcx().emit_err(errors::ToolModuleImported {
1987                                span: ident.span,
1988                                import: binding.span,
1989                            });
1990                        }
1991                        let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1992                        return PathResult::NonModule(PartialRes::new(res));
1993                    } else if res == Res::Err {
1994                        return PathResult::NonModule(PartialRes::new(Res::Err));
1995                    } else if opt_ns.is_some() && (is_last || maybe_assoc) {
1996                        if let Some(finalize) = finalize {
1997                            self.get_mut().lint_if_path_starts_with_module(
1998                                finalize,
1999                                path,
2000                                second_binding,
2001                            );
2002                        }
2003                        record_segment_res(self.reborrow(), finalize, res, id);
2004                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
2005                            res,
2006                            path.len() - segment_idx - 1,
2007                        ));
2008                    } else {
2009                        return PathResult::failed(
2010                            ident,
2011                            is_last,
2012                            finalize.is_some(),
2013                            module_had_parse_errors,
2014                            module,
2015                            || {
2016                                let label = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{2}` is {0} {1}, not a module",
                res.article(), res.descr(), ident))
    })format!(
2017                                    "`{ident}` is {} {}, not a module",
2018                                    res.article(),
2019                                    res.descr()
2020                                );
2021                                let scope = match &path[..segment_idx] {
2022                                    [.., prev] => {
2023                                        if prev.ident.name == kw::PathRoot {
2024                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the crate root"))
    })format!("the crate root")
2025                                        } else {
2026                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", prev.ident))
    })format!("`{}`", prev.ident)
2027                                        }
2028                                    }
2029                                    _ => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this scope"))
    })format!("this scope"),
2030                                };
2031                                // FIXME: reword, as the reason we expected a module is because of
2032                                // the following path segment.
2033                                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}");
2034                                (message, label, None)
2035                            },
2036                        );
2037                    }
2038                }
2039                Err(Undetermined) if finalize.is_none() => return PathResult::Indeterminate,
2040                Err(Determined | Undetermined) => {
2041                    if let Some(ModuleOrUniformRoot::Module(module)) = module
2042                        && opt_ns.is_some()
2043                        && !module.is_normal()
2044                    {
2045                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
2046                            module.res().unwrap(),
2047                            path.len() - segment_idx,
2048                        ));
2049                    }
2050
2051                    let mut this = self.reborrow();
2052                    return PathResult::failed(
2053                        ident,
2054                        is_last,
2055                        finalize.is_some(),
2056                        module_had_parse_errors,
2057                        module,
2058                        || {
2059                            this.get_mut().report_path_resolution_error(
2060                                path,
2061                                opt_ns,
2062                                parent_scope,
2063                                ribs,
2064                                ignore_decl,
2065                                ignore_import,
2066                                module,
2067                                segment_idx,
2068                                ident,
2069                                diag_metadata,
2070                            )
2071                        },
2072                    );
2073                }
2074            }
2075        }
2076
2077        if let Some(finalize) = finalize {
2078            self.get_mut().lint_if_path_starts_with_module(finalize, path, second_binding);
2079        }
2080
2081        PathResult::Module(match module {
2082            Some(module) => module,
2083            None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
2084            _ => ::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),
2085        })
2086    }
2087}