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