Skip to main content

rustc_resolve/
ident.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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