rustc_resolve/
ident.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<LateDecl<'ra>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let orig_ident = ident;
            let (general_span, normalized_span) =
                if ident.name == kw::SelfUpper {
                    let empty_span =
                        ident.span.with_ctxt(SyntaxContext::root());
                    (empty_span, empty_span)
                } else if ns == TypeNS {
                    let normalized_span = ident.span.normalize_to_macros_2_0();
                    (normalized_span, normalized_span)
                } else {
                    (ident.span.normalize_to_macro_rules(),
                        ident.span.normalize_to_macros_2_0())
                };
            ident.span = general_span;
            let normalized_ident = Ident { span: normalized_span, ..ident };
            for (i, rib) in ribs.iter().enumerate().rev() {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/ident.rs:331",
                                        "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                        ::tracing_core::__macro_support::Option::Some(331u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("walk rib\n{0:?}",
                                                                    rib.bindings) as &dyn Value))])
                            });
                    } else { ; }
                };
                let rib_ident =
                    if rib.kind.contains_params() {
                        normalized_ident
                    } else { ident };
                if let Some((original_rib_ident_def, res)) =
                        rib.bindings.get_key_value(&rib_ident) {
                    return Some(LateDecl::RibDef(self.validate_res_from_ribs(i,
                                    rib_ident, *res, finalize.map(|_| general_span),
                                    *original_rib_ident_def, ribs, diag_metadata)));
                } else if let RibKind::Block(Some(module)) = rib.kind &&
                        let Ok(binding) =
                            self.cm().resolve_ident_in_scope_set(ident,
                                ScopeSet::Module(ns, module), parent_scope,
                                finalize.map(|finalize|
                                        Finalize { used: Used::Scope, ..finalize }),
                                finalize.is_some(), ignore_decl, None) {
                    return Some(LateDecl::Decl(binding));
                } else if let RibKind::Module(module) = rib.kind {
                    let parent_scope = &ParentScope { module, ..*parent_scope };
                    let finalize =
                        finalize.map(|f| Finalize { stage: Stage::Late, ..f });
                    return self.cm().resolve_ident_in_scope_set(orig_ident,
                                    ScopeSet::All(ns), parent_scope, finalize,
                                    finalize.is_some(), ignore_decl,
                                    None).ok().map(LateDecl::Decl);
                }
                if let RibKind::MacroDefinition(def) = rib.kind &&
                        def == self.macro_def(ident.span.ctxt()) {
                    ident.span.remove_mark();
                }
            }
            ::core::panicking::panic("internal error: entered unreachable code")
        }
    }
}#[instrument(level = "debug", skip(self, ribs))]
305    pub(crate) fn resolve_ident_in_lexical_scope(
306        &mut self,
307        mut ident: Ident,
308        ns: Namespace,
309        parent_scope: &ParentScope<'ra>,
310        finalize: Option<Finalize>,
311        ribs: &[Rib<'ra>],
312        ignore_decl: Option<Decl<'ra>>,
313        diag_metadata: Option<&DiagMetadata<'_>>,
314    ) -> Option<LateDecl<'ra>> {
315        let orig_ident = ident;
316        let (general_span, normalized_span) = if ident.name == kw::SelfUpper {
317            // FIXME(jseyfried) improve `Self` hygiene
318            let empty_span = ident.span.with_ctxt(SyntaxContext::root());
319            (empty_span, empty_span)
320        } else if ns == TypeNS {
321            let normalized_span = ident.span.normalize_to_macros_2_0();
322            (normalized_span, normalized_span)
323        } else {
324            (ident.span.normalize_to_macro_rules(), ident.span.normalize_to_macros_2_0())
325        };
326        ident.span = general_span;
327        let normalized_ident = Ident { span: normalized_span, ..ident };
328
329        // Walk backwards up the ribs in scope.
330        for (i, rib) in ribs.iter().enumerate().rev() {
331            debug!("walk rib\n{:?}", rib.bindings);
332            // Use the rib kind to determine whether we are resolving parameters
333            // (macro 2.0 hygiene) or local variables (`macro_rules` hygiene).
334            let rib_ident = if rib.kind.contains_params() { normalized_ident } else { ident };
335            if let Some((original_rib_ident_def, res)) = rib.bindings.get_key_value(&rib_ident) {
336                // The ident resolves to a type parameter or local variable.
337                return Some(LateDecl::RibDef(self.validate_res_from_ribs(
338                    i,
339                    rib_ident,
340                    *res,
341                    finalize.map(|_| general_span),
342                    *original_rib_ident_def,
343                    ribs,
344                    diag_metadata,
345                )));
346            } else if let RibKind::Block(Some(module)) = rib.kind
347                && let Ok(binding) = self.cm().resolve_ident_in_scope_set(
348                    ident,
349                    ScopeSet::Module(ns, module),
350                    parent_scope,
351                    finalize.map(|finalize| Finalize { used: Used::Scope, ..finalize }),
352                    finalize.is_some(),
353                    ignore_decl,
354                    None,
355                )
356            {
357                // The ident resolves to an item in a block.
358                return Some(LateDecl::Decl(binding));
359            } else if let RibKind::Module(module) = rib.kind {
360                // Encountered a module item, abandon ribs and look into that module and preludes.
361                let parent_scope = &ParentScope { module, ..*parent_scope };
362                let finalize = finalize.map(|f| Finalize { stage: Stage::Late, ..f });
363                return self
364                    .cm()
365                    .resolve_ident_in_scope_set(
366                        orig_ident,
367                        ScopeSet::All(ns),
368                        parent_scope,
369                        finalize,
370                        finalize.is_some(),
371                        ignore_decl,
372                        None,
373                    )
374                    .ok()
375                    .map(LateDecl::Decl);
376            }
377
378            if let RibKind::MacroDefinition(def) = rib.kind
379                && def == self.macro_def(ident.span.ctxt())
380            {
381                // If an invocation of this macro created `ident`, give up on `ident`
382                // and switch to `ident`'s source from the macro definition.
383                ident.span.remove_mark();
384            }
385        }
386
387        unreachable!()
388    }
389
390    /// Resolve an identifier in the specified set of scopes.
391    #[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_scope_set",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(391u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["orig_ident",
                                                    "scope_set", "parent_scope", "finalize", "force",
                                                    "ignore_decl", "ignore_import"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&orig_ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scope_set)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&force as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_decl)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<Decl<'ra>, Determinacy> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !(force || finalize.is_none()) {
                ::core::panicking::panic("assertion failed: force || finalize.is_none()")
            };
            if !#[allow(non_exhaustive_omitted_patterns)] match scope_set {
                            ScopeSet::Module(..) => true,
                            _ => false,
                        } && orig_ident.is_path_segment_keyword() {
                return Err(Determinacy::Determined);
            }
            let (ns, macro_kind) =
                match scope_set {
                    ScopeSet::All(ns) | ScopeSet::Module(ns, _) |
                        ScopeSet::ModuleAndExternPrelude(ns, _) => (ns, None),
                    ScopeSet::ExternPrelude => (TypeNS, None),
                    ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind)),
                };
            let derive_fallback_lint_id =
                match finalize {
                    Some(Finalize { node_id, stage: Stage::Late, .. }) =>
                        Some(node_id),
                    _ => None,
                };
            let mut innermost_results: SmallVec<[(Decl<'_>, Scope<'_>); 2]> =
                SmallVec::new();
            let mut determinacy = Determinacy::Determined;
            let break_result =
                self.visit_scopes(scope_set, parent_scope, orig_ident.span,
                    derive_fallback_lint_id,
                    |this, scope, use_prelude, ctxt|
                        {
                            let ident = Ident::new(orig_ident.name, ctxt);
                            let ident = Macros20NormalizedIdent(ident);
                            let res =
                                match this.reborrow().resolve_ident_in_scope(ident, ns,
                                        scope, use_prelude, scope_set, parent_scope,
                                        if innermost_results.is_empty() { finalize } else { None },
                                        force, ignore_decl, ignore_import) {
                                    Ok(decl) => Ok(decl),
                                    Err(ControlFlow::Break(determinacy)) if
                                        innermost_results.is_empty() => {
                                        return ControlFlow::Break(Err(determinacy));
                                    }
                                    Err(determinacy) => Err(determinacy.into_value()),
                                };
                            match res {
                                Ok(decl) if
                                    sub_namespace_match(decl.macro_kinds(), macro_kind) => {
                                    if #[allow(non_exhaustive_omitted_patterns)] match finalize
                                            {
                                            None | Some(Finalize { stage: Stage::Late, .. }) => true,
                                            _ => false,
                                        } {
                                        return ControlFlow::Break(Ok(decl));
                                    }
                                    if let Some(&(innermost_decl, _)) =
                                            innermost_results.first() {
                                        if this.get_mut().maybe_push_ambiguity(orig_ident, ns,
                                                scope_set, parent_scope, decl, scope, &innermost_results) {
                                            return ControlFlow::Break(Ok(innermost_decl));
                                        }
                                    }
                                    innermost_results.push((decl, scope));
                                }
                                Ok(_) | Err(Determinacy::Determined) => {}
                                Err(Determinacy::Undetermined) =>
                                    determinacy = Determinacy::Undetermined,
                            }
                            ControlFlow::Continue(())
                        });
            if let Some(break_result) = break_result { return break_result; }
            match innermost_results.first() {
                Some(&(decl, ..)) => Ok(decl),
                None =>
                    Err(Determinacy::determined(determinacy ==
                                    Determinacy::Determined || force)),
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
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        force: bool,
399        ignore_decl: Option<Decl<'ra>>,
400        ignore_import: Option<Import<'ra>>,
401    ) -> Result<Decl<'ra>, Determinacy> {
402        assert!(force || finalize.is_none()); // `finalize` implies `force`
403
404        // Make sure `self`, `super` etc produce an error when passed to here.
405        if !matches!(scope_set, ScopeSet::Module(..)) && orig_ident.is_path_segment_keyword() {
406            return Err(Determinacy::Determined);
407        }
408
409        let (ns, macro_kind) = match scope_set {
410            ScopeSet::All(ns)
411            | ScopeSet::Module(ns, _)
412            | ScopeSet::ModuleAndExternPrelude(ns, _) => (ns, None),
413            ScopeSet::ExternPrelude => (TypeNS, None),
414            ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind)),
415        };
416        let derive_fallback_lint_id = match finalize {
417            Some(Finalize { node_id, stage: Stage::Late, .. }) => Some(node_id),
418            _ => None,
419        };
420
421        // This is *the* result, resolution from the scope closest to the resolved identifier.
422        // However, sometimes this result is "weak" because it comes from a glob import or
423        // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
424        // mod m { ... } // solution in outer scope
425        // {
426        //     use prefix::*; // imports another `m` - innermost solution
427        //                    // weak, cannot shadow the outer `m`, need to report ambiguity error
428        //     m::mac!();
429        // }
430        // So we have to save the innermost solution and continue searching in outer scopes
431        // to detect potential ambiguities.
432        let mut innermost_results: SmallVec<[(Decl<'_>, Scope<'_>); 2]> = SmallVec::new();
433        let mut determinacy = Determinacy::Determined;
434
435        // Go through all the scopes and try to resolve the name.
436        let break_result = self.visit_scopes(
437            scope_set,
438            parent_scope,
439            orig_ident.span,
440            derive_fallback_lint_id,
441            |this, scope, use_prelude, ctxt| {
442                let ident = Ident::new(orig_ident.name, ctxt);
443                // The passed `ctxt` is already normalized, so avoid expensive double normalization.
444                let ident = Macros20NormalizedIdent(ident);
445                let res = match this.reborrow().resolve_ident_in_scope(
446                    ident,
447                    ns,
448                    scope,
449                    use_prelude,
450                    scope_set,
451                    parent_scope,
452                    // Shadowed decls don't need to be marked as used or non-speculatively loaded.
453                    if innermost_results.is_empty() { finalize } else { None },
454                    force,
455                    ignore_decl,
456                    ignore_import,
457                ) {
458                    Ok(decl) => Ok(decl),
459                    // We can break with an error at this step, it means we cannot determine the
460                    // resolution right now, but we must block and wait until we can, instead of
461                    // considering outer scopes. Although there's no need to do that if we already
462                    // have a better solution.
463                    Err(ControlFlow::Break(determinacy)) if innermost_results.is_empty() => {
464                        return ControlFlow::Break(Err(determinacy));
465                    }
466                    Err(determinacy) => Err(determinacy.into_value()),
467                };
468                match res {
469                    Ok(decl) if sub_namespace_match(decl.macro_kinds(), macro_kind) => {
470                        // Below we report various ambiguity errors.
471                        // We do not need to report them if we are either in speculative resolution,
472                        // or in late resolution when everything is already imported and expanded
473                        // and no ambiguities exist.
474                        if matches!(finalize, None | Some(Finalize { stage: Stage::Late, .. })) {
475                            return ControlFlow::Break(Ok(decl));
476                        }
477
478                        if let Some(&(innermost_decl, _)) = innermost_results.first() {
479                            // Found another solution, if the first one was "weak", report an error.
480                            if this.get_mut().maybe_push_ambiguity(
481                                orig_ident,
482                                ns,
483                                scope_set,
484                                parent_scope,
485                                decl,
486                                scope,
487                                &innermost_results,
488                            ) {
489                                // No need to search for more potential ambiguities, one is enough.
490                                return ControlFlow::Break(Ok(innermost_decl));
491                            }
492                        }
493
494                        innermost_results.push((decl, scope));
495                    }
496                    Ok(_) | Err(Determinacy::Determined) => {}
497                    Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
498                }
499
500                ControlFlow::Continue(())
501            },
502        );
503
504        // Scope visiting returned some result early.
505        if let Some(break_result) = break_result {
506            return break_result;
507        }
508
509        // Scope visiting walked all the scopes and maybe found something in one of them.
510        match innermost_results.first() {
511            Some(&(decl, ..)) => Ok(decl),
512            None => Err(Determinacy::determined(determinacy == Determinacy::Determined || force)),
513        }
514    }
515
516    fn resolve_ident_in_scope<'r>(
517        mut self: CmResolver<'r, 'ra, 'tcx>,
518        ident: Macros20NormalizedIdent,
519        ns: Namespace,
520        scope: Scope<'ra>,
521        use_prelude: UsePrelude,
522        scope_set: ScopeSet<'ra>,
523        parent_scope: &ParentScope<'ra>,
524        finalize: Option<Finalize>,
525        force: bool,
526        ignore_decl: Option<Decl<'ra>>,
527        ignore_import: Option<Import<'ra>>,
528    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
529        let ret = match scope {
530            Scope::DeriveHelpers(expn_id) => {
531                if let Some(decl) = self
532                    .helper_attrs
533                    .get(&expn_id)
534                    .and_then(|attrs| attrs.iter().rfind(|(i, _)| ident == *i).map(|(_, d)| *d))
535                {
536                    Ok(decl)
537                } else {
538                    Err(Determinacy::Determined)
539                }
540            }
541            Scope::DeriveHelpersCompat => {
542                let mut result = Err(Determinacy::Determined);
543                for derive in parent_scope.derives {
544                    let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
545                    match self.reborrow().resolve_derive_macro_path(
546                        derive,
547                        parent_scope,
548                        force,
549                        ignore_import,
550                    ) {
551                        Ok((Some(ext), _)) => {
552                            if ext.helper_attrs.contains(&ident.name) {
553                                let decl = self.arenas.new_pub_def_decl(
554                                    Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat),
555                                    derive.span,
556                                    LocalExpnId::ROOT,
557                                );
558                                result = Ok(decl);
559                                break;
560                            }
561                        }
562                        Ok(_) | Err(Determinacy::Determined) => {}
563                        Err(Determinacy::Undetermined) => result = Err(Determinacy::Undetermined),
564                    }
565                }
566                result
567            }
568            Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
569                MacroRulesScope::Def(macro_rules_def) if ident == macro_rules_def.ident => {
570                    Ok(macro_rules_def.decl)
571                }
572                MacroRulesScope::Invocation(_) => Err(Determinacy::Undetermined),
573                _ => Err(Determinacy::Determined),
574            },
575            Scope::ModuleNonGlobs(module, derive_fallback_lint_id) => {
576                let (adjusted_parent_scope, adjusted_finalize) = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..) => true,
    _ => false,
}matches!(
577                    scope_set,
578                    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..)
579                ) {
580                    (parent_scope, finalize)
581                } else {
582                    (
583                        &ParentScope { module, ..*parent_scope },
584                        finalize.map(|f| Finalize { used: Used::Scope, ..f }),
585                    )
586                };
587                let decl = self.reborrow().resolve_ident_in_module_non_globs_unadjusted(
588                    module,
589                    ident,
590                    ns,
591                    adjusted_parent_scope,
592                    if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..)) {
593                        Shadowing::Unrestricted
594                    } else {
595                        Shadowing::Restricted
596                    },
597                    adjusted_finalize,
598                    ignore_decl,
599                    ignore_import,
600                );
601                match decl {
602                    Ok(decl) => {
603                        if let Some(lint_id) = derive_fallback_lint_id {
604                            self.get_mut().lint_buffer.buffer_lint(
605                                PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
606                                lint_id,
607                                ident.span,
608                                errors::ProcMacroDeriveResolutionFallback {
609                                    span: ident.span,
610                                    ns_descr: ns.descr(),
611                                    ident: ident.0,
612                                },
613                            );
614                        }
615                        Ok(decl)
616                    }
617                    Err(ControlFlow::Continue(determinacy)) => Err(determinacy),
618                    Err(ControlFlow::Break(determinacy)) => {
619                        return Err(ControlFlow::Break(Determinacy::determined(
620                            determinacy == Determinacy::Determined || force,
621                        )));
622                    }
623                }
624            }
625            Scope::ModuleGlobs(module, derive_fallback_lint_id) => {
626                let (adjusted_parent_scope, adjusted_finalize) = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..) => true,
    _ => false,
}matches!(
627                    scope_set,
628                    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..)
629                ) {
630                    (parent_scope, finalize)
631                } else {
632                    (
633                        &ParentScope { module, ..*parent_scope },
634                        finalize.map(|f| Finalize { used: Used::Scope, ..f }),
635                    )
636                };
637                let binding = self.reborrow().resolve_ident_in_module_globs_unadjusted(
638                    module,
639                    ident,
640                    ns,
641                    adjusted_parent_scope,
642                    if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..)) {
643                        Shadowing::Unrestricted
644                    } else {
645                        Shadowing::Restricted
646                    },
647                    adjusted_finalize,
648                    ignore_decl,
649                    ignore_import,
650                );
651                match binding {
652                    Ok(binding) => {
653                        if let Some(lint_id) = derive_fallback_lint_id {
654                            self.get_mut().lint_buffer.buffer_lint(
655                                PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
656                                lint_id,
657                                ident.span,
658                                errors::ProcMacroDeriveResolutionFallback {
659                                    span: ident.span,
660                                    ns_descr: ns.descr(),
661                                    ident: ident.0,
662                                },
663                            );
664                        }
665                        Ok(binding)
666                    }
667                    Err(ControlFlow::Continue(determinacy)) => Err(determinacy),
668                    Err(ControlFlow::Break(determinacy)) => {
669                        return Err(ControlFlow::Break(Determinacy::determined(
670                            determinacy == Determinacy::Determined || force,
671                        )));
672                    }
673                }
674            }
675            Scope::MacroUsePrelude => match self.macro_use_prelude.get(&ident.name).cloned() {
676                Some(decl) => Ok(decl),
677                None => Err(Determinacy::determined(
678                    self.graph_root.unexpanded_invocations.borrow().is_empty(),
679                )),
680            },
681            Scope::BuiltinAttrs => match self.builtin_attr_decls.get(&ident.name) {
682                Some(decl) => Ok(*decl),
683                None => Err(Determinacy::Determined),
684            },
685            Scope::ExternPreludeItems => {
686                match self.reborrow().extern_prelude_get_item(ident, finalize.is_some()) {
687                    Some(decl) => Ok(decl),
688                    None => Err(Determinacy::determined(
689                        self.graph_root.unexpanded_invocations.borrow().is_empty(),
690                    )),
691                }
692            }
693            Scope::ExternPreludeFlags => {
694                match self.extern_prelude_get_flag(ident, finalize.is_some()) {
695                    Some(decl) => Ok(decl),
696                    None => Err(Determinacy::Determined),
697                }
698            }
699            Scope::ToolPrelude => match self.registered_tool_decls.get(&ident) {
700                Some(decl) => Ok(*decl),
701                None => Err(Determinacy::Determined),
702            },
703            Scope::StdLibPrelude => {
704                let mut result = Err(Determinacy::Determined);
705                if let Some(prelude) = self.prelude
706                    && let Ok(decl) = self.reborrow().resolve_ident_in_scope_set(
707                        ident.0,
708                        ScopeSet::Module(ns, prelude),
709                        parent_scope,
710                        None,
711                        false,
712                        ignore_decl,
713                        ignore_import,
714                    )
715                    && (#[allow(non_exhaustive_omitted_patterns)] match use_prelude {
    UsePrelude::Yes => true,
    _ => false,
}matches!(use_prelude, UsePrelude::Yes) || self.is_builtin_macro(decl.res()))
716                {
717                    result = Ok(decl)
718                }
719
720                result
721            }
722            Scope::BuiltinTypes => match self.builtin_type_decls.get(&ident.name) {
723                Some(decl) => {
724                    if #[allow(non_exhaustive_omitted_patterns)] match ident.name {
    sym::f16 => true,
    _ => false,
}matches!(ident.name, sym::f16)
725                        && !self.tcx.features().f16()
726                        && !ident.span.allows_unstable(sym::f16)
727                        && finalize.is_some()
728                    {
729                        feature_err(
730                            self.tcx.sess,
731                            sym::f16,
732                            ident.span,
733                            "the type `f16` is unstable",
734                        )
735                        .emit();
736                    }
737                    if #[allow(non_exhaustive_omitted_patterns)] match ident.name {
    sym::f128 => true,
    _ => false,
}matches!(ident.name, sym::f128)
738                        && !self.tcx.features().f128()
739                        && !ident.span.allows_unstable(sym::f128)
740                        && finalize.is_some()
741                    {
742                        feature_err(
743                            self.tcx.sess,
744                            sym::f128,
745                            ident.span,
746                            "the type `f128` is unstable",
747                        )
748                        .emit();
749                    }
750                    Ok(*decl)
751                }
752                None => Err(Determinacy::Determined),
753            },
754        };
755
756        ret.map_err(ControlFlow::Continue)
757    }
758
759    fn maybe_push_ambiguity(
760        &mut self,
761        orig_ident: Ident,
762        ns: Namespace,
763        scope_set: ScopeSet<'ra>,
764        parent_scope: &ParentScope<'ra>,
765        decl: Decl<'ra>,
766        scope: Scope<'ra>,
767        innermost_results: &[(Decl<'ra>, Scope<'ra>)],
768    ) -> bool {
769        let (innermost_decl, innermost_scope) = innermost_results[0];
770        let (res, innermost_res) = (decl.res(), innermost_decl.res());
771        if res == innermost_res {
772            return false;
773        }
774
775        // FIXME: Use `scope` instead of `res` to detect built-in attrs and derive helpers,
776        // it will exclude imports, make slightly more code legal, and will require lang approval.
777        let module_only = #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..));
778        let is_builtin = |res| #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)) => true,
    _ => false,
}matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)));
779        let derive_helper = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
780        let derive_helper_compat = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
781
782        let ambiguity_error_kind = if is_builtin(innermost_res) || is_builtin(res) {
783            Some(AmbiguityKind::BuiltinAttr)
784        } else if innermost_res == derive_helper_compat {
785            Some(AmbiguityKind::DeriveHelper)
786        } else if res == derive_helper_compat && innermost_res != derive_helper {
787            ::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")
788        } else if #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
    Scope::MacroRules(_) => true,
    _ => false,
}matches!(innermost_scope, Scope::MacroRules(_))
789            && #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..) => true,
    _ => false,
}matches!(scope, Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..))
790            && !self.disambiguate_macro_rules_vs_modularized(innermost_decl, decl)
791        {
792            Some(AmbiguityKind::MacroRulesVsModularized)
793        } else if #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::MacroRules(_) => true,
    _ => false,
}matches!(scope, Scope::MacroRules(_))
794            && #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
    Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..) => true,
    _ => false,
}matches!(innermost_scope, Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..))
795        {
796            // should be impossible because of visitation order in
797            // visit_scopes
798            //
799            // we visit all macro_rules scopes (e.g. textual scope macros)
800            // before we visit any modules (e.g. path-based scope macros)
801            ::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!(
802                orig_ident.span,
803                "ambiguous scoped macro resolutions with path-based \
804                                        scope resolution as first candidate"
805            )
806        } else if innermost_decl.is_glob_import() {
807            Some(AmbiguityKind::GlobVsOuter)
808        } else if !module_only && innermost_decl.may_appear_after(parent_scope.expansion, decl) {
809            Some(AmbiguityKind::MoreExpandedVsOuter)
810        } else if innermost_decl.expansion != LocalExpnId::ROOT
811            && (!module_only || ns == MacroNS)
812            && let Scope::ModuleGlobs(m1, _) = scope
813            && let Scope::ModuleNonGlobs(m2, _) = innermost_scope
814            && m1 == m2
815        {
816            // FIXME: this error is too conservative and technically unnecessary now when module
817            // scope is split into two scopes, at least when not resolving in `ScopeSet::Module`,
818            // remove it with lang team approval.
819            Some(AmbiguityKind::GlobVsExpanded)
820        } else {
821            None
822        };
823
824        if let Some(kind) = ambiguity_error_kind {
825            // Skip ambiguity errors for extern flag bindings "overridden"
826            // by extern item bindings.
827            // FIXME: Remove with lang team approval.
828            let issue_145575_hack = #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::ExternPreludeFlags => true,
    _ => false,
}matches!(scope, Scope::ExternPreludeFlags)
829                && innermost_results[1..]
830                    .iter()
831                    .any(|(b, s)| #[allow(non_exhaustive_omitted_patterns)] match s {
    Scope::ExternPreludeItems => true,
    _ => false,
}matches!(s, Scope::ExternPreludeItems) && *b != innermost_decl);
832            // Skip ambiguity errors for nonglob module bindings "overridden"
833            // by glob module bindings in the same module.
834            // FIXME: Remove with lang team approval.
835            let issue_149681_hack = match scope {
836                Scope::ModuleGlobs(m1, _)
837                    if innermost_results[1..]
838                        .iter()
839                        .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)) =>
840                {
841                    true
842                }
843                _ => false,
844            };
845
846            if issue_145575_hack || issue_149681_hack {
847                self.issue_145575_hack_applied = true;
848            } else {
849                // Turn ambiguity errors for core vs std panic into warnings.
850                // FIXME: Remove with lang team approval.
851                let is_issue_147319_hack = orig_ident.span.edition() <= Edition::Edition2024
852                    && #[allow(non_exhaustive_omitted_patterns)] match orig_ident.name {
    sym::panic => true,
    _ => false,
}matches!(orig_ident.name, sym::panic)
853                    && #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::StdLibPrelude => true,
    _ => false,
}matches!(scope, Scope::StdLibPrelude)
854                    && #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
    Scope::ModuleGlobs(_, _) => true,
    _ => false,
}matches!(innermost_scope, Scope::ModuleGlobs(_, _))
855                    && ((self.is_specific_builtin_macro(res, sym::std_panic)
856                        && self.is_specific_builtin_macro(innermost_res, sym::core_panic))
857                        || (self.is_specific_builtin_macro(res, sym::core_panic)
858                            && self.is_specific_builtin_macro(innermost_res, sym::std_panic)));
859
860                let warning = is_issue_147319_hack.then_some(AmbiguityWarning::PanicImport);
861
862                self.ambiguity_errors.push(AmbiguityError {
863                    kind,
864                    ident: orig_ident,
865                    b1: innermost_decl,
866                    b2: decl,
867                    scope1: innermost_scope,
868                    scope2: scope,
869                    warning,
870                });
871                return true;
872            }
873        }
874
875        false
876    }
877
878    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("maybe_resolve_ident_in_module",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(878u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["module", "ident",
                                                    "ns", "parent_scope", "ignore_import"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&module)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ns)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<Decl<'ra>, Determinacy> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.resolve_ident_in_module(module, ident, ns, parent_scope,
                None, None, ignore_import)
        }
    }
}#[instrument(level = "debug", skip(self))]
879    pub(crate) fn maybe_resolve_ident_in_module<'r>(
880        self: CmResolver<'r, 'ra, 'tcx>,
881        module: ModuleOrUniformRoot<'ra>,
882        ident: Ident,
883        ns: Namespace,
884        parent_scope: &ParentScope<'ra>,
885        ignore_import: Option<Import<'ra>>,
886    ) -> Result<Decl<'ra>, Determinacy> {
887        self.resolve_ident_in_module(module, ident, ns, parent_scope, None, None, ignore_import)
888    }
889
890    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("resolve_ident_in_module",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(890u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["module", "ident",
                                                    "ns", "parent_scope", "finalize", "ignore_decl",
                                                    "ignore_import"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&module)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ns)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_decl)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<Decl<'ra>, Determinacy> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tmp_parent_scope;
            let mut adjusted_parent_scope = parent_scope;
            match module {
                ModuleOrUniformRoot::Module(m) => {
                    if let Some(def) =
                            ident.span.normalize_to_macros_2_0_and_adjust(m.expansion) {
                        tmp_parent_scope =
                            ParentScope {
                                module: self.expn_def_scope(def),
                                ..*parent_scope
                            };
                        adjusted_parent_scope = &tmp_parent_scope;
                    }
                }
                ModuleOrUniformRoot::ExternPrelude => {
                    ident.span.normalize_to_macros_2_0_and_adjust(ExpnId::root());
                }
                ModuleOrUniformRoot::ModuleAndExternPrelude(..) |
                    ModuleOrUniformRoot::CurrentScope => {}
            }
            self.resolve_ident_in_virt_module_unadjusted(module, ident, ns,
                adjusted_parent_scope, finalize, ignore_decl, ignore_import)
        }
    }
}#[instrument(level = "debug", skip(self))]
891    pub(crate) fn resolve_ident_in_module<'r>(
892        self: CmResolver<'r, 'ra, 'tcx>,
893        module: ModuleOrUniformRoot<'ra>,
894        mut ident: Ident,
895        ns: Namespace,
896        parent_scope: &ParentScope<'ra>,
897        finalize: Option<Finalize>,
898        ignore_decl: Option<Decl<'ra>>,
899        ignore_import: Option<Import<'ra>>,
900    ) -> Result<Decl<'ra>, Determinacy> {
901        let tmp_parent_scope;
902        let mut adjusted_parent_scope = parent_scope;
903        match module {
904            ModuleOrUniformRoot::Module(m) => {
905                if let Some(def) = ident.span.normalize_to_macros_2_0_and_adjust(m.expansion) {
906                    tmp_parent_scope =
907                        ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
908                    adjusted_parent_scope = &tmp_parent_scope;
909                }
910            }
911            ModuleOrUniformRoot::ExternPrelude => {
912                ident.span.normalize_to_macros_2_0_and_adjust(ExpnId::root());
913            }
914            ModuleOrUniformRoot::ModuleAndExternPrelude(..) | ModuleOrUniformRoot::CurrentScope => {
915                // No adjustments
916            }
917        }
918        self.resolve_ident_in_virt_module_unadjusted(
919            module,
920            ident,
921            ns,
922            adjusted_parent_scope,
923            finalize,
924            ignore_decl,
925            ignore_import,
926        )
927    }
928
929    /// Attempts to resolve `ident` in namespace `ns` of `module`.
930    #[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_virt_module_unadjusted",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(930u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["module", "ident",
                                                    "ns", "parent_scope", "finalize", "ignore_decl",
                                                    "ignore_import"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&module)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ns)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_decl)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<Decl<'ra>, Determinacy> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            match module {
                ModuleOrUniformRoot::Module(module) =>
                    self.resolve_ident_in_scope_set(ident,
                        ScopeSet::Module(ns, module), parent_scope, finalize,
                        finalize.is_some(), ignore_decl, ignore_import),
                ModuleOrUniformRoot::ModuleAndExternPrelude(module) =>
                    self.resolve_ident_in_scope_set(ident,
                        ScopeSet::ModuleAndExternPrelude(ns, module), parent_scope,
                        finalize, finalize.is_some(), ignore_decl, ignore_import),
                ModuleOrUniformRoot::ExternPrelude => {
                    if ns != TypeNS {
                        Err(Determined)
                    } else {
                        self.resolve_ident_in_scope_set(ident,
                            ScopeSet::ExternPrelude, parent_scope, finalize,
                            finalize.is_some(), ignore_decl, ignore_import)
                    }
                }
                ModuleOrUniformRoot::CurrentScope => {
                    if ns == TypeNS {
                        if ident.name == kw::Crate || ident.name == kw::DollarCrate
                            {
                            let module = self.resolve_crate_root(ident);
                            return Ok(module.self_decl.unwrap());
                        } else if ident.name == kw::Super ||
                                ident.name == kw::SelfLower {}
                    }
                    self.resolve_ident_in_scope_set(ident, ScopeSet::All(ns),
                        parent_scope, finalize, finalize.is_some(), ignore_decl,
                        ignore_import)
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
931    fn resolve_ident_in_virt_module_unadjusted<'r>(
932        self: CmResolver<'r, 'ra, 'tcx>,
933        module: ModuleOrUniformRoot<'ra>,
934        ident: Ident,
935        ns: Namespace,
936        parent_scope: &ParentScope<'ra>,
937        finalize: Option<Finalize>,
938        ignore_decl: Option<Decl<'ra>>,
939        ignore_import: Option<Import<'ra>>,
940    ) -> Result<Decl<'ra>, Determinacy> {
941        match module {
942            ModuleOrUniformRoot::Module(module) => self.resolve_ident_in_scope_set(
943                ident,
944                ScopeSet::Module(ns, module),
945                parent_scope,
946                finalize,
947                finalize.is_some(),
948                ignore_decl,
949                ignore_import,
950            ),
951            ModuleOrUniformRoot::ModuleAndExternPrelude(module) => self.resolve_ident_in_scope_set(
952                ident,
953                ScopeSet::ModuleAndExternPrelude(ns, module),
954                parent_scope,
955                finalize,
956                finalize.is_some(),
957                ignore_decl,
958                ignore_import,
959            ),
960            ModuleOrUniformRoot::ExternPrelude => {
961                if ns != TypeNS {
962                    Err(Determined)
963                } else {
964                    self.resolve_ident_in_scope_set(
965                        ident,
966                        ScopeSet::ExternPrelude,
967                        parent_scope,
968                        finalize,
969                        finalize.is_some(),
970                        ignore_decl,
971                        ignore_import,
972                    )
973                }
974            }
975            ModuleOrUniformRoot::CurrentScope => {
976                if ns == TypeNS {
977                    if ident.name == kw::Crate || ident.name == kw::DollarCrate {
978                        let module = self.resolve_crate_root(ident);
979                        return Ok(module.self_decl.unwrap());
980                    } else if ident.name == kw::Super || ident.name == kw::SelfLower {
981                        // FIXME: Implement these with renaming requirements so that e.g.
982                        // `use super;` doesn't work, but `use super as name;` does.
983                        // Fall through here to get an error from `early_resolve_...`.
984                    }
985                }
986
987                self.resolve_ident_in_scope_set(
988                    ident,
989                    ScopeSet::All(ns),
990                    parent_scope,
991                    finalize,
992                    finalize.is_some(),
993                    ignore_decl,
994                    ignore_import,
995                )
996            }
997        }
998    }
999
1000    /// Attempts to resolve `ident` in namespace `ns` of non-glob bindings in `module`.
1001    fn resolve_ident_in_module_non_globs_unadjusted<'r>(
1002        mut self: CmResolver<'r, 'ra, 'tcx>,
1003        module: Module<'ra>,
1004        ident: Macros20NormalizedIdent,
1005        ns: Namespace,
1006        parent_scope: &ParentScope<'ra>,
1007        shadowing: Shadowing,
1008        finalize: Option<Finalize>,
1009        // This binding should be ignored during in-module resolution, so that we don't get
1010        // "self-confirming" import resolutions during import validation and checking.
1011        ignore_decl: Option<Decl<'ra>>,
1012        ignore_import: Option<Import<'ra>>,
1013    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1014        let key = BindingKey::new(ident, ns);
1015        // `try_borrow_mut` is required to ensure exclusive access, even if the resulting binding
1016        // doesn't need to be mutable. It will fail when there is a cycle of imports, and without
1017        // the exclusive access infinite recursion will crash the compiler with stack overflow.
1018        let resolution = &*self
1019            .resolution_or_default(module, key)
1020            .try_borrow_mut_unchecked()
1021            .map_err(|_| ControlFlow::Continue(Determined))?;
1022
1023        let binding = resolution.non_glob_decl.filter(|b| Some(*b) != ignore_decl);
1024
1025        if let Some(finalize) = finalize {
1026            return self.get_mut().finalize_module_binding(
1027                ident.0,
1028                binding,
1029                parent_scope,
1030                module,
1031                finalize,
1032                shadowing,
1033            );
1034        }
1035
1036        // Items and single imports are not shadowable, if we have one, then it's determined.
1037        if let Some(binding) = binding {
1038            let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1039            return if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) };
1040        }
1041
1042        // Check if one of single imports can still define the name, block if it can.
1043        if self.reborrow().single_import_can_define_name(
1044            &resolution,
1045            None,
1046            ns,
1047            ignore_import,
1048            ignore_decl,
1049            parent_scope,
1050        ) {
1051            return Err(ControlFlow::Break(Undetermined));
1052        }
1053
1054        // Check if one of unexpanded macros can still define the name.
1055        if !module.unexpanded_invocations.borrow().is_empty() {
1056            return Err(ControlFlow::Continue(Undetermined));
1057        }
1058
1059        // No resolution and no one else can define the name - determinate error.
1060        Err(ControlFlow::Continue(Determined))
1061    }
1062
1063    /// Attempts to resolve `ident` in namespace `ns` of glob bindings in `module`.
1064    fn resolve_ident_in_module_globs_unadjusted<'r>(
1065        mut self: CmResolver<'r, 'ra, 'tcx>,
1066        module: Module<'ra>,
1067        ident: Macros20NormalizedIdent,
1068        ns: Namespace,
1069        parent_scope: &ParentScope<'ra>,
1070        shadowing: Shadowing,
1071        finalize: Option<Finalize>,
1072        ignore_decl: Option<Decl<'ra>>,
1073        ignore_import: Option<Import<'ra>>,
1074    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1075        let key = BindingKey::new(ident, ns);
1076        // `try_borrow_mut` is required to ensure exclusive access, even if the resulting binding
1077        // doesn't need to be mutable. It will fail when there is a cycle of imports, and without
1078        // the exclusive access infinite recursion will crash the compiler with stack overflow.
1079        let resolution = &*self
1080            .resolution_or_default(module, key)
1081            .try_borrow_mut_unchecked()
1082            .map_err(|_| ControlFlow::Continue(Determined))?;
1083
1084        let binding = resolution.glob_decl.filter(|b| Some(*b) != ignore_decl);
1085
1086        if let Some(finalize) = finalize {
1087            return self.get_mut().finalize_module_binding(
1088                ident.0,
1089                binding,
1090                parent_scope,
1091                module,
1092                finalize,
1093                shadowing,
1094            );
1095        }
1096
1097        // Check if one of single imports can still define the name,
1098        // if it can then our result is not determined and can be invalidated.
1099        if self.reborrow().single_import_can_define_name(
1100            &resolution,
1101            binding,
1102            ns,
1103            ignore_import,
1104            ignore_decl,
1105            parent_scope,
1106        ) {
1107            return Err(ControlFlow::Break(Undetermined));
1108        }
1109
1110        // So we have a resolution that's from a glob import. This resolution is determined
1111        // if it cannot be shadowed by some new item/import expanded from a macro.
1112        // This happens either if there are no unexpanded macros, or expanded names cannot
1113        // shadow globs (that happens in macro namespace or with restricted shadowing).
1114        //
1115        // Additionally, any macro in any module can plant names in the root module if it creates
1116        // `macro_export` macros, so the root module effectively has unresolved invocations if any
1117        // module has unresolved invocations.
1118        // However, it causes resolution/expansion to stuck too often (#53144), so, to make
1119        // progress, we have to ignore those potential unresolved invocations from other modules
1120        // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
1121        // shadowing is enabled, see `macro_expanded_macro_export_errors`).
1122        if let Some(binding) = binding {
1123            return if binding.determined() || ns == MacroNS || shadowing == Shadowing::Restricted {
1124                let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1125                if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) }
1126            } else {
1127                Err(ControlFlow::Break(Undetermined))
1128            };
1129        }
1130
1131        // Now we are in situation when new item/import can appear only from a glob or a macro
1132        // expansion. With restricted shadowing names from globs and macro expansions cannot
1133        // shadow names from outer scopes, so we can freely fallback from module search to search
1134        // in outer scopes. For `resolve_ident_in_scope_set` to continue search in outer
1135        // scopes we return `Undetermined` with `ControlFlow::Continue`.
1136        // Check if one of unexpanded macros can still define the name,
1137        // if it can then our "no resolution" result is not determined and can be invalidated.
1138        if !module.unexpanded_invocations.borrow().is_empty() {
1139            return Err(ControlFlow::Continue(Undetermined));
1140        }
1141
1142        // Check if one of glob imports can still define the name,
1143        // if it can then our "no resolution" result is not determined and can be invalidated.
1144        for glob_import in module.globs.borrow().iter() {
1145            if ignore_import == Some(*glob_import) {
1146                continue;
1147            }
1148            if !self.is_accessible_from(glob_import.vis, parent_scope.module) {
1149                continue;
1150            }
1151            let module = match glob_import.imported_module.get() {
1152                Some(ModuleOrUniformRoot::Module(module)) => module,
1153                Some(_) => continue,
1154                None => return Err(ControlFlow::Continue(Undetermined)),
1155            };
1156            let tmp_parent_scope;
1157            let (mut adjusted_parent_scope, mut ident) = (parent_scope, ident);
1158            match ident.0.span.glob_adjust(module.expansion, glob_import.span) {
1159                Some(Some(def)) => {
1160                    tmp_parent_scope =
1161                        ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
1162                    adjusted_parent_scope = &tmp_parent_scope;
1163                }
1164                Some(None) => {}
1165                None => continue,
1166            };
1167            let result = self.reborrow().resolve_ident_in_scope_set(
1168                ident.0,
1169                ScopeSet::Module(ns, module),
1170                adjusted_parent_scope,
1171                None,
1172                false,
1173                ignore_decl,
1174                ignore_import,
1175            );
1176
1177            match result {
1178                Err(Determined) => continue,
1179                Ok(binding)
1180                    if !self.is_accessible_from(binding.vis(), glob_import.parent_scope.module) =>
1181                {
1182                    continue;
1183                }
1184                Ok(_) | Err(Undetermined) => return Err(ControlFlow::Continue(Undetermined)),
1185            }
1186        }
1187
1188        // No resolution and no one else can define the name - determinate error.
1189        Err(ControlFlow::Continue(Determined))
1190    }
1191
1192    fn finalize_module_binding(
1193        &mut self,
1194        ident: Ident,
1195        binding: Option<Decl<'ra>>,
1196        parent_scope: &ParentScope<'ra>,
1197        module: Module<'ra>,
1198        finalize: Finalize,
1199        shadowing: Shadowing,
1200    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1201        let Finalize { path_span, report_private, used, root_span, .. } = finalize;
1202
1203        let Some(binding) = binding else {
1204            return Err(ControlFlow::Continue(Determined));
1205        };
1206
1207        if !self.is_accessible_from(binding.vis(), parent_scope.module) {
1208            if report_private {
1209                self.privacy_errors.push(PrivacyError {
1210                    ident,
1211                    decl: binding,
1212                    dedup_span: path_span,
1213                    outermost_res: None,
1214                    source: None,
1215                    parent_scope: *parent_scope,
1216                    single_nested: path_span != root_span,
1217                });
1218            } else {
1219                return Err(ControlFlow::Break(Determined));
1220            }
1221        }
1222
1223        if shadowing == Shadowing::Unrestricted
1224            && binding.expansion != LocalExpnId::ROOT
1225            && let DeclKind::Import { import, .. } = binding.kind
1226            && #[allow(non_exhaustive_omitted_patterns)] match import.kind {
    ImportKind::MacroExport => true,
    _ => false,
}matches!(import.kind, ImportKind::MacroExport)
1227        {
1228            self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
1229        }
1230
1231        // If we encounter a re-export for a type with private fields, it will not be able to
1232        // be constructed through this re-export. We track that case here to expand later
1233        // privacy errors with appropriate information.
1234        if let Res::Def(_, def_id) = binding.res() {
1235            let struct_ctor = match def_id.as_local() {
1236                Some(def_id) => self.struct_constructors.get(&def_id).cloned(),
1237                None => {
1238                    let ctor = self.cstore().ctor_untracked(self.tcx(), def_id);
1239                    ctor.map(|(ctor_kind, ctor_def_id)| {
1240                        let ctor_res = Res::Def(
1241                            DefKind::Ctor(rustc_hir::def::CtorOf::Struct, ctor_kind),
1242                            ctor_def_id,
1243                        );
1244                        let ctor_vis = self.tcx.visibility(ctor_def_id);
1245                        let field_visibilities = self
1246                            .tcx
1247                            .associated_item_def_ids(def_id)
1248                            .iter()
1249                            .map(|field_id| self.tcx.visibility(field_id))
1250                            .collect();
1251                        (ctor_res, ctor_vis, field_visibilities)
1252                    })
1253                }
1254            };
1255            if let Some((_, _, fields)) = struct_ctor
1256                && fields.iter().any(|vis| !self.is_accessible_from(*vis, module))
1257            {
1258                self.inaccessible_ctor_reexport.insert(path_span, binding.span);
1259            }
1260        }
1261
1262        self.record_use(ident, binding, used);
1263        return Ok(binding);
1264    }
1265
1266    // Checks if a single import can define the `Ident` corresponding to `binding`.
1267    // This is used to check whether we can definitively accept a glob as a resolution.
1268    fn single_import_can_define_name<'r>(
1269        mut self: CmResolver<'r, 'ra, 'tcx>,
1270        resolution: &NameResolution<'ra>,
1271        binding: Option<Decl<'ra>>,
1272        ns: Namespace,
1273        ignore_import: Option<Import<'ra>>,
1274        ignore_decl: Option<Decl<'ra>>,
1275        parent_scope: &ParentScope<'ra>,
1276    ) -> bool {
1277        for single_import in &resolution.single_imports {
1278            if let Some(decl) = resolution.non_glob_decl
1279                && let DeclKind::Import { import, .. } = decl.kind
1280                && import == *single_import
1281            {
1282                // Single import has already defined the name and we are aware of it,
1283                // no need to block the globs.
1284                continue;
1285            }
1286            if ignore_import == Some(*single_import) {
1287                continue;
1288            }
1289            if !self.is_accessible_from(single_import.vis, parent_scope.module) {
1290                continue;
1291            }
1292            if let Some(ignored) = ignore_decl
1293                && let DeclKind::Import { import, .. } = ignored.kind
1294                && import == *single_import
1295            {
1296                continue;
1297            }
1298
1299            let Some(module) = single_import.imported_module.get() else {
1300                return true;
1301            };
1302            let ImportKind::Single { source, target, decls, .. } = &single_import.kind else {
1303                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1304            };
1305            if source != target {
1306                if decls.iter().all(|d| d.get().decl().is_none()) {
1307                    return true;
1308                } else if decls[ns].get().decl().is_none() && binding.is_some() {
1309                    return true;
1310                }
1311            }
1312
1313            match self.reborrow().resolve_ident_in_module(
1314                module,
1315                *source,
1316                ns,
1317                &single_import.parent_scope,
1318                None,
1319                ignore_decl,
1320                ignore_import,
1321            ) {
1322                Err(Determined) => continue,
1323                Ok(binding)
1324                    if !self
1325                        .is_accessible_from(binding.vis(), single_import.parent_scope.module) =>
1326                {
1327                    continue;
1328                }
1329                Ok(_) | Err(Undetermined) => return true,
1330            }
1331        }
1332
1333        false
1334    }
1335
1336    /// Validate a local resolution (from ribs).
1337    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("validate_res_from_ribs",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1337u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["rib_index",
                                                    "rib_ident", "res", "finalize", "original_rib_ident_def",
                                                    "diag_metadata"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&rib_index as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rib_ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&original_rib_ident_def)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_metadata)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Res = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/ident.rs:1348",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1348u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("validate_res_from_ribs({0:?})",
                                                                res) as &dyn Value))])
                        });
                } else { ; }
            };
            let ribs = &all_ribs[rib_index + 1..];
            if let RibKind::ForwardGenericParamBan(reason) =
                    all_ribs[rib_index].kind {
                if let Some(span) = finalize {
                    let res_error =
                        if rib_ident.name == kw::SelfUpper {
                            ResolutionError::ForwardDeclaredSelf(reason)
                        } else {
                            ResolutionError::ForwardDeclaredGenericParam(rib_ident.name,
                                reason)
                        };
                    self.report_error(span, res_error);
                }
                match (&res, &Res::Err) {
                    (left_val, right_val) => {
                        if !(*left_val == *right_val) {
                            let kind = ::core::panicking::AssertKind::Eq;
                            ::core::panicking::assert_failed(kind, &*left_val,
                                &*right_val, ::core::option::Option::None);
                        }
                    }
                };
                return Res::Err;
            }
            match res {
                Res::Local(_) => {
                    use ResolutionError::*;
                    let mut res_err = None;
                    for rib in ribs {
                        match rib.kind {
                            RibKind::Normal | RibKind::Block(..) |
                                RibKind::FnOrCoroutine | RibKind::Module(..) |
                                RibKind::MacroDefinition(..) |
                                RibKind::ForwardGenericParamBan(_) => {}
                            RibKind::Item(..) | RibKind::AssocItem => {
                                if let Some(span) = finalize {
                                    res_err =
                                        Some((span, CannotCaptureDynamicEnvironmentInFnItem));
                                }
                            }
                            RibKind::ConstantItem(_, item) => {
                                if let Some(span) = finalize {
                                    let (span, resolution_error) =
                                        match item {
                                            None if rib_ident.name == kw::SelfLower => {
                                                (span, LowercaseSelf)
                                            }
                                            None => {
                                                let sm = self.tcx.sess.source_map();
                                                let type_span =
                                                    match sm.span_look_ahead(original_rib_ident_def.span, ":",
                                                            None) {
                                                        None => { Some(original_rib_ident_def.span.shrink_to_hi()) }
                                                        Some(_) => None,
                                                    };
                                                (rib_ident.span,
                                                    AttemptToUseNonConstantValueInConstant {
                                                        ident: original_rib_ident_def,
                                                        suggestion: "const",
                                                        current: "let",
                                                        type_span,
                                                    })
                                            }
                                            Some((ident, kind)) =>
                                                (span,
                                                    AttemptToUseNonConstantValueInConstant {
                                                        ident,
                                                        suggestion: "let",
                                                        current: kind.as_str(),
                                                        type_span: None,
                                                    }),
                                        };
                                    self.report_error(span, resolution_error);
                                }
                                return Res::Err;
                            }
                            RibKind::ConstParamTy => {
                                if let Some(span) = finalize {
                                    self.report_error(span,
                                        ParamInTyOfConstParam { name: rib_ident.name });
                                }
                                return Res::Err;
                            }
                            RibKind::InlineAsmSym => {
                                if let Some(span) = finalize {
                                    self.report_error(span, InvalidAsmSym);
                                }
                                return Res::Err;
                            }
                        }
                    }
                    if let Some((span, res_err)) = res_err {
                        self.report_error(span, res_err);
                        return Res::Err;
                    }
                }
                Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } |
                    Res::SelfTyAlias { .. } => {
                    for rib in ribs {
                        let (has_generic_params, def_kind) =
                            match rib.kind {
                                RibKind::Normal | RibKind::Block(..) |
                                    RibKind::FnOrCoroutine | RibKind::Module(..) |
                                    RibKind::MacroDefinition(..) | RibKind::InlineAsmSym |
                                    RibKind::AssocItem | RibKind::ForwardGenericParamBan(_) => {
                                    continue;
                                }
                                RibKind::ConstParamTy => {
                                    if !self.tcx.features().generic_const_parameter_types() {
                                        if let Some(span) = finalize {
                                            self.report_error(span,
                                                ResolutionError::ParamInTyOfConstParam {
                                                    name: rib_ident.name,
                                                });
                                        }
                                        return Res::Err;
                                    } else { continue; }
                                }
                                RibKind::ConstantItem(trivial, _) => {
                                    if let ConstantHasGenerics::No(cause) = trivial &&
                                            !#[allow(non_exhaustive_omitted_patterns)] match res {
                                                    Res::SelfTyAlias { .. } => true,
                                                    _ => false,
                                                } {
                                        if let Some(span) = finalize {
                                            let error =
                                                match cause {
                                                    NoConstantGenericsReason::IsEnumDiscriminant => {
                                                        ResolutionError::ParamInEnumDiscriminant {
                                                            name: rib_ident.name,
                                                            param_kind: ParamKindInEnumDiscriminant::Type,
                                                        }
                                                    }
                                                    NoConstantGenericsReason::NonTrivialConstArg => {
                                                        ResolutionError::ParamInNonTrivialAnonConst {
                                                            name: rib_ident.name,
                                                            param_kind: ParamKindInNonTrivialAnonConst::Type,
                                                        }
                                                    }
                                                };
                                            let _: ErrorGuaranteed = self.report_error(span, error);
                                        }
                                        return Res::Err;
                                    }
                                    continue;
                                }
                                RibKind::Item(has_generic_params, def_kind) => {
                                    (has_generic_params, def_kind)
                                }
                            };
                        if let Some(span) = finalize {
                            let item =
                                if let Some(diag_metadata) = diag_metadata &&
                                        let Some(current_item) = diag_metadata.current_item {
                                    let span =
                                        current_item.kind.ident().map(|i|
                                                    i.span).unwrap_or(current_item.span);
                                    Some((span, current_item.kind.clone()))
                                } else { None };
                            self.report_error(span,
                                ResolutionError::GenericParamsFromOuterItem {
                                    outer_res: res,
                                    has_generic_params,
                                    def_kind,
                                    inner_item: item,
                                    current_self_ty: diag_metadata.and_then(|m|
                                                m.current_self_type.as_ref()).and_then(|ty|
                                            {
                                                self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
                                            }),
                                });
                        }
                        return Res::Err;
                    }
                }
                Res::Def(DefKind::ConstParam, _) => {
                    for rib in ribs {
                        let (has_generic_params, def_kind) =
                            match rib.kind {
                                RibKind::Normal | RibKind::Block(..) |
                                    RibKind::FnOrCoroutine | RibKind::Module(..) |
                                    RibKind::MacroDefinition(..) | RibKind::InlineAsmSym |
                                    RibKind::AssocItem | RibKind::ForwardGenericParamBan(_) =>
                                    continue,
                                RibKind::ConstParamTy => {
                                    if !self.tcx.features().generic_const_parameter_types() {
                                        if let Some(span) = finalize {
                                            self.report_error(span,
                                                ResolutionError::ParamInTyOfConstParam {
                                                    name: rib_ident.name,
                                                });
                                        }
                                        return Res::Err;
                                    } else { continue; }
                                }
                                RibKind::ConstantItem(trivial, _) => {
                                    if let ConstantHasGenerics::No(cause) = trivial {
                                        if let Some(span) = finalize {
                                            let error =
                                                match cause {
                                                    NoConstantGenericsReason::IsEnumDiscriminant => {
                                                        ResolutionError::ParamInEnumDiscriminant {
                                                            name: rib_ident.name,
                                                            param_kind: ParamKindInEnumDiscriminant::Const,
                                                        }
                                                    }
                                                    NoConstantGenericsReason::NonTrivialConstArg => {
                                                        ResolutionError::ParamInNonTrivialAnonConst {
                                                            name: rib_ident.name,
                                                            param_kind: ParamKindInNonTrivialAnonConst::Const {
                                                                name: rib_ident.name,
                                                            },
                                                        }
                                                    }
                                                };
                                            self.report_error(span, error);
                                        }
                                        return Res::Err;
                                    }
                                    continue;
                                }
                                RibKind::Item(has_generic_params, def_kind) => {
                                    (has_generic_params, def_kind)
                                }
                            };
                        if let Some(span) = finalize {
                            let item =
                                if let Some(diag_metadata) = diag_metadata &&
                                        let Some(current_item) = diag_metadata.current_item {
                                    let span =
                                        current_item.kind.ident().map(|i|
                                                    i.span).unwrap_or(current_item.span);
                                    Some((span, current_item.kind.clone()))
                                } else { None };
                            self.report_error(span,
                                ResolutionError::GenericParamsFromOuterItem {
                                    outer_res: res,
                                    has_generic_params,
                                    def_kind,
                                    inner_item: item,
                                    current_self_ty: diag_metadata.and_then(|m|
                                                m.current_self_type.as_ref()).and_then(|ty|
                                            {
                                                self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
                                            }),
                                });
                        }
                        return Res::Err;
                    }
                }
                _ => {}
            }
            res
        }
    }
}#[instrument(level = "debug", skip(self, all_ribs))]
1338    fn validate_res_from_ribs(
1339        &mut self,
1340        rib_index: usize,
1341        rib_ident: Ident,
1342        res: Res,
1343        finalize: Option<Span>,
1344        original_rib_ident_def: Ident,
1345        all_ribs: &[Rib<'ra>],
1346        diag_metadata: Option<&DiagMetadata<'_>>,
1347    ) -> Res {
1348        debug!("validate_res_from_ribs({:?})", res);
1349        let ribs = &all_ribs[rib_index + 1..];
1350
1351        // An invalid forward use of a generic parameter from a previous default
1352        // or in a const param ty.
1353        if let RibKind::ForwardGenericParamBan(reason) = all_ribs[rib_index].kind {
1354            if let Some(span) = finalize {
1355                let res_error = if rib_ident.name == kw::SelfUpper {
1356                    ResolutionError::ForwardDeclaredSelf(reason)
1357                } else {
1358                    ResolutionError::ForwardDeclaredGenericParam(rib_ident.name, reason)
1359                };
1360                self.report_error(span, res_error);
1361            }
1362            assert_eq!(res, Res::Err);
1363            return Res::Err;
1364        }
1365
1366        match res {
1367            Res::Local(_) => {
1368                use ResolutionError::*;
1369                let mut res_err = None;
1370
1371                for rib in ribs {
1372                    match rib.kind {
1373                        RibKind::Normal
1374                        | RibKind::Block(..)
1375                        | RibKind::FnOrCoroutine
1376                        | RibKind::Module(..)
1377                        | RibKind::MacroDefinition(..)
1378                        | RibKind::ForwardGenericParamBan(_) => {
1379                            // Nothing to do. Continue.
1380                        }
1381                        RibKind::Item(..) | RibKind::AssocItem => {
1382                            // This was an attempt to access an upvar inside a
1383                            // named function item. This is not allowed, so we
1384                            // report an error.
1385                            if let Some(span) = finalize {
1386                                // We don't immediately trigger a resolve error, because
1387                                // we want certain other resolution errors (namely those
1388                                // emitted for `ConstantItemRibKind` below) to take
1389                                // precedence.
1390                                res_err = Some((span, CannotCaptureDynamicEnvironmentInFnItem));
1391                            }
1392                        }
1393                        RibKind::ConstantItem(_, item) => {
1394                            // Still doesn't deal with upvars
1395                            if let Some(span) = finalize {
1396                                let (span, resolution_error) = match item {
1397                                    None if rib_ident.name == kw::SelfLower => {
1398                                        (span, LowercaseSelf)
1399                                    }
1400                                    None => {
1401                                        // If we have a `let name = expr;`, we have the span for
1402                                        // `name` and use that to see if it is followed by a type
1403                                        // specifier. If not, then we know we need to suggest
1404                                        // `const name: Ty = expr;`. This is a heuristic, it will
1405                                        // break down in the presence of macros.
1406                                        let sm = self.tcx.sess.source_map();
1407                                        let type_span = match sm.span_look_ahead(
1408                                            original_rib_ident_def.span,
1409                                            ":",
1410                                            None,
1411                                        ) {
1412                                            None => {
1413                                                Some(original_rib_ident_def.span.shrink_to_hi())
1414                                            }
1415                                            Some(_) => None,
1416                                        };
1417                                        (
1418                                            rib_ident.span,
1419                                            AttemptToUseNonConstantValueInConstant {
1420                                                ident: original_rib_ident_def,
1421                                                suggestion: "const",
1422                                                current: "let",
1423                                                type_span,
1424                                            },
1425                                        )
1426                                    }
1427                                    Some((ident, kind)) => (
1428                                        span,
1429                                        AttemptToUseNonConstantValueInConstant {
1430                                            ident,
1431                                            suggestion: "let",
1432                                            current: kind.as_str(),
1433                                            type_span: None,
1434                                        },
1435                                    ),
1436                                };
1437                                self.report_error(span, resolution_error);
1438                            }
1439                            return Res::Err;
1440                        }
1441                        RibKind::ConstParamTy => {
1442                            if let Some(span) = finalize {
1443                                self.report_error(
1444                                    span,
1445                                    ParamInTyOfConstParam { name: rib_ident.name },
1446                                );
1447                            }
1448                            return Res::Err;
1449                        }
1450                        RibKind::InlineAsmSym => {
1451                            if let Some(span) = finalize {
1452                                self.report_error(span, InvalidAsmSym);
1453                            }
1454                            return Res::Err;
1455                        }
1456                    }
1457                }
1458                if let Some((span, res_err)) = res_err {
1459                    self.report_error(span, res_err);
1460                    return Res::Err;
1461                }
1462            }
1463            Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {
1464                for rib in ribs {
1465                    let (has_generic_params, def_kind) = match rib.kind {
1466                        RibKind::Normal
1467                        | RibKind::Block(..)
1468                        | RibKind::FnOrCoroutine
1469                        | RibKind::Module(..)
1470                        | RibKind::MacroDefinition(..)
1471                        | RibKind::InlineAsmSym
1472                        | RibKind::AssocItem
1473                        | RibKind::ForwardGenericParamBan(_) => {
1474                            // Nothing to do. Continue.
1475                            continue;
1476                        }
1477
1478                        RibKind::ConstParamTy => {
1479                            if !self.tcx.features().generic_const_parameter_types() {
1480                                if let Some(span) = finalize {
1481                                    self.report_error(
1482                                        span,
1483                                        ResolutionError::ParamInTyOfConstParam {
1484                                            name: rib_ident.name,
1485                                        },
1486                                    );
1487                                }
1488                                return Res::Err;
1489                            } else {
1490                                continue;
1491                            }
1492                        }
1493
1494                        RibKind::ConstantItem(trivial, _) => {
1495                            if let ConstantHasGenerics::No(cause) = trivial
1496                                && !matches!(res, Res::SelfTyAlias { .. })
1497                            {
1498                                if let Some(span) = finalize {
1499                                    let error = match cause {
1500                                        NoConstantGenericsReason::IsEnumDiscriminant => {
1501                                            ResolutionError::ParamInEnumDiscriminant {
1502                                                name: rib_ident.name,
1503                                                param_kind: ParamKindInEnumDiscriminant::Type,
1504                                            }
1505                                        }
1506                                        NoConstantGenericsReason::NonTrivialConstArg => {
1507                                            ResolutionError::ParamInNonTrivialAnonConst {
1508                                                name: rib_ident.name,
1509                                                param_kind: ParamKindInNonTrivialAnonConst::Type,
1510                                            }
1511                                        }
1512                                    };
1513                                    let _: ErrorGuaranteed = self.report_error(span, error);
1514                                }
1515
1516                                return Res::Err;
1517                            }
1518
1519                            continue;
1520                        }
1521
1522                        // This was an attempt to use a type parameter outside its scope.
1523                        RibKind::Item(has_generic_params, def_kind) => {
1524                            (has_generic_params, def_kind)
1525                        }
1526                    };
1527
1528                    if let Some(span) = finalize {
1529                        let item = if let Some(diag_metadata) = diag_metadata
1530                            && let Some(current_item) = diag_metadata.current_item
1531                        {
1532                            let span = current_item
1533                                .kind
1534                                .ident()
1535                                .map(|i| i.span)
1536                                .unwrap_or(current_item.span);
1537                            Some((span, current_item.kind.clone()))
1538                        } else {
1539                            None
1540                        };
1541                        self.report_error(
1542                            span,
1543                            ResolutionError::GenericParamsFromOuterItem {
1544                                outer_res: res,
1545                                has_generic_params,
1546                                def_kind,
1547                                inner_item: item,
1548                                current_self_ty: diag_metadata
1549                                    .and_then(|m| m.current_self_type.as_ref())
1550                                    .and_then(|ty| {
1551                                        self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1552                                    }),
1553                            },
1554                        );
1555                    }
1556                    return Res::Err;
1557                }
1558            }
1559            Res::Def(DefKind::ConstParam, _) => {
1560                for rib in ribs {
1561                    let (has_generic_params, def_kind) = match rib.kind {
1562                        RibKind::Normal
1563                        | RibKind::Block(..)
1564                        | RibKind::FnOrCoroutine
1565                        | RibKind::Module(..)
1566                        | RibKind::MacroDefinition(..)
1567                        | RibKind::InlineAsmSym
1568                        | RibKind::AssocItem
1569                        | RibKind::ForwardGenericParamBan(_) => continue,
1570
1571                        RibKind::ConstParamTy => {
1572                            if !self.tcx.features().generic_const_parameter_types() {
1573                                if let Some(span) = finalize {
1574                                    self.report_error(
1575                                        span,
1576                                        ResolutionError::ParamInTyOfConstParam {
1577                                            name: rib_ident.name,
1578                                        },
1579                                    );
1580                                }
1581                                return Res::Err;
1582                            } else {
1583                                continue;
1584                            }
1585                        }
1586
1587                        RibKind::ConstantItem(trivial, _) => {
1588                            if let ConstantHasGenerics::No(cause) = trivial {
1589                                if let Some(span) = finalize {
1590                                    let error = match cause {
1591                                        NoConstantGenericsReason::IsEnumDiscriminant => {
1592                                            ResolutionError::ParamInEnumDiscriminant {
1593                                                name: rib_ident.name,
1594                                                param_kind: ParamKindInEnumDiscriminant::Const,
1595                                            }
1596                                        }
1597                                        NoConstantGenericsReason::NonTrivialConstArg => {
1598                                            ResolutionError::ParamInNonTrivialAnonConst {
1599                                                name: rib_ident.name,
1600                                                param_kind: ParamKindInNonTrivialAnonConst::Const {
1601                                                    name: rib_ident.name,
1602                                                },
1603                                            }
1604                                        }
1605                                    };
1606                                    self.report_error(span, error);
1607                                }
1608
1609                                return Res::Err;
1610                            }
1611
1612                            continue;
1613                        }
1614
1615                        RibKind::Item(has_generic_params, def_kind) => {
1616                            (has_generic_params, def_kind)
1617                        }
1618                    };
1619
1620                    // This was an attempt to use a const parameter outside its scope.
1621                    if let Some(span) = finalize {
1622                        let item = if let Some(diag_metadata) = diag_metadata
1623                            && let Some(current_item) = diag_metadata.current_item
1624                        {
1625                            let span = current_item
1626                                .kind
1627                                .ident()
1628                                .map(|i| i.span)
1629                                .unwrap_or(current_item.span);
1630                            Some((span, current_item.kind.clone()))
1631                        } else {
1632                            None
1633                        };
1634                        self.report_error(
1635                            span,
1636                            ResolutionError::GenericParamsFromOuterItem {
1637                                outer_res: res,
1638                                has_generic_params,
1639                                def_kind,
1640                                inner_item: item,
1641                                current_self_ty: diag_metadata
1642                                    .and_then(|m| m.current_self_type.as_ref())
1643                                    .and_then(|ty| {
1644                                        self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1645                                    }),
1646                            },
1647                        );
1648                    }
1649                    return Res::Err;
1650                }
1651            }
1652            _ => {}
1653        }
1654
1655        res
1656    }
1657
1658    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("maybe_resolve_path",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1658u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["path", "opt_ns",
                                                    "parent_scope", "ignore_import"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&opt_ns)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: PathResult<'ra> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.resolve_path_with_ribs(path, opt_ns, parent_scope, None,
                None, None, None, ignore_import, None)
        }
    }
}#[instrument(level = "debug", skip(self))]
1659    pub(crate) fn maybe_resolve_path<'r>(
1660        self: CmResolver<'r, 'ra, 'tcx>,
1661        path: &[Segment],
1662        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1663        parent_scope: &ParentScope<'ra>,
1664        ignore_import: Option<Import<'ra>>,
1665    ) -> PathResult<'ra> {
1666        self.resolve_path_with_ribs(
1667            path,
1668            opt_ns,
1669            parent_scope,
1670            None,
1671            None,
1672            None,
1673            None,
1674            ignore_import,
1675            None,
1676        )
1677    }
1678    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("resolve_path",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1678u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["path", "opt_ns",
                                                    "parent_scope", "finalize", "ignore_decl", "ignore_import"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&opt_ns)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_decl)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: PathResult<'ra> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.resolve_path_with_ribs(path, opt_ns, parent_scope, None,
                finalize, None, ignore_decl, ignore_import, None)
        }
    }
}#[instrument(level = "debug", skip(self))]
1679    pub(crate) fn resolve_path<'r>(
1680        self: CmResolver<'r, 'ra, 'tcx>,
1681        path: &[Segment],
1682        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1683        parent_scope: &ParentScope<'ra>,
1684        finalize: Option<Finalize>,
1685        ignore_decl: Option<Decl<'ra>>,
1686        ignore_import: Option<Import<'ra>>,
1687    ) -> PathResult<'ra> {
1688        self.resolve_path_with_ribs(
1689            path,
1690            opt_ns,
1691            parent_scope,
1692            None,
1693            finalize,
1694            None,
1695            ignore_decl,
1696            ignore_import,
1697            None,
1698        )
1699    }
1700
1701    pub(crate) fn resolve_path_with_ribs<'r>(
1702        mut self: CmResolver<'r, 'ra, 'tcx>,
1703        path: &[Segment],
1704        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1705        parent_scope: &ParentScope<'ra>,
1706        source: Option<PathSource<'_, '_, '_>>,
1707        finalize: Option<Finalize>,
1708        ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
1709        ignore_decl: Option<Decl<'ra>>,
1710        ignore_import: Option<Import<'ra>>,
1711        diag_metadata: Option<&DiagMetadata<'_>>,
1712    ) -> PathResult<'ra> {
1713        let mut module = None;
1714        let mut module_had_parse_errors = false;
1715        let mut allow_super = true;
1716        let mut second_binding = None;
1717
1718        // We'll provide more context to the privacy errors later, up to `len`.
1719        let privacy_errors_len = self.privacy_errors.len();
1720        fn record_segment_res<'r, 'ra, 'tcx>(
1721            mut this: CmResolver<'r, 'ra, 'tcx>,
1722            finalize: Option<Finalize>,
1723            res: Res,
1724            id: Option<NodeId>,
1725        ) {
1726            if finalize.is_some()
1727                && let Some(id) = id
1728                && !this.partial_res_map.contains_key(&id)
1729            {
1730                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");
1731                this.get_mut().record_partial_res(id, PartialRes::new(res));
1732            }
1733        }
1734
1735        for (segment_idx, &Segment { ident, id, .. }) in path.iter().enumerate() {
1736            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/ident.rs:1736",
                        "rustc_resolve::ident", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                        ::tracing_core::__macro_support::Option::Some(1736u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_path ident {0} {1:?} {2:?}",
                                                    segment_idx, ident, id) as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_path ident {} {:?} {:?}", segment_idx, ident, id);
1737
1738            let is_last = segment_idx + 1 == path.len();
1739            let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1740            let name = ident.name;
1741
1742            allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super);
1743
1744            if ns == TypeNS {
1745                if allow_super && name == kw::Super {
1746                    let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1747                    let self_module = match segment_idx {
1748                        0 => Some(self.resolve_self(&mut ctxt, parent_scope.module)),
1749                        _ => match module {
1750                            Some(ModuleOrUniformRoot::Module(module)) => Some(module),
1751                            _ => None,
1752                        },
1753                    };
1754                    if let Some(self_module) = self_module
1755                        && let Some(parent) = self_module.parent
1756                    {
1757                        module =
1758                            Some(ModuleOrUniformRoot::Module(self.resolve_self(&mut ctxt, parent)));
1759                        continue;
1760                    }
1761                    return PathResult::failed(
1762                        ident,
1763                        false,
1764                        finalize.is_some(),
1765                        module_had_parse_errors,
1766                        module,
1767                        || ("there are too many leading `super` keywords".to_string(), None),
1768                    );
1769                }
1770                if segment_idx == 0 {
1771                    if name == kw::SelfLower {
1772                        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1773                        let self_mod = self.resolve_self(&mut ctxt, parent_scope.module);
1774                        if let Some(res) = self_mod.res() {
1775                            record_segment_res(self.reborrow(), finalize, res, id);
1776                        }
1777                        module = Some(ModuleOrUniformRoot::Module(self_mod));
1778                        continue;
1779                    }
1780                    if name == kw::PathRoot && ident.span.at_least_rust_2018() {
1781                        module = Some(ModuleOrUniformRoot::ExternPrelude);
1782                        continue;
1783                    }
1784                    if name == kw::PathRoot
1785                        && ident.span.is_rust_2015()
1786                        && self.tcx.sess.at_least_rust_2018()
1787                    {
1788                        // `::a::b` from 2015 macro on 2018 global edition
1789                        let crate_root = self.resolve_crate_root(ident);
1790                        module = Some(ModuleOrUniformRoot::ModuleAndExternPrelude(crate_root));
1791                        continue;
1792                    }
1793                    if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate {
1794                        // `::a::b`, `crate::a::b` or `$crate::a::b`
1795                        let crate_root = self.resolve_crate_root(ident);
1796                        if let Some(res) = crate_root.res() {
1797                            record_segment_res(self.reborrow(), finalize, res, id);
1798                        }
1799                        module = Some(ModuleOrUniformRoot::Module(crate_root));
1800                        continue;
1801                    }
1802                }
1803            }
1804
1805            // Report special messages for path segment keywords in wrong positions.
1806            if ident.is_path_segment_keyword() && segment_idx != 0 {
1807                return PathResult::failed(
1808                    ident,
1809                    false,
1810                    finalize.is_some(),
1811                    module_had_parse_errors,
1812                    module,
1813                    || {
1814                        let name_str = if name == kw::PathRoot {
1815                            "crate root".to_string()
1816                        } else {
1817                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", name))
    })format!("`{name}`")
1818                        };
1819                        let label = if segment_idx == 1 && path[0].ident.name == kw::PathRoot {
1820                            ::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}")
1821                        } else {
1822                            ::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")
1823                        };
1824                        (label, None)
1825                    },
1826                );
1827            }
1828
1829            let binding = if let Some(module) = module {
1830                self.reborrow().resolve_ident_in_module(
1831                    module,
1832                    ident,
1833                    ns,
1834                    parent_scope,
1835                    finalize,
1836                    ignore_decl,
1837                    ignore_import,
1838                )
1839            } else if let Some(ribs) = ribs
1840                && let Some(TypeNS | ValueNS) = opt_ns
1841            {
1842                if !ignore_import.is_none() {
    ::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
1843                match self.get_mut().resolve_ident_in_lexical_scope(
1844                    ident,
1845                    ns,
1846                    parent_scope,
1847                    finalize,
1848                    &ribs[ns],
1849                    ignore_decl,
1850                    diag_metadata,
1851                ) {
1852                    // we found a locally-imported or available item/module
1853                    Some(LateDecl::Decl(binding)) => Ok(binding),
1854                    // we found a local variable or type param
1855                    Some(LateDecl::RibDef(res)) => {
1856                        record_segment_res(self.reborrow(), finalize, res, id);
1857                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
1858                            res,
1859                            path.len() - 1,
1860                        ));
1861                    }
1862                    _ => Err(Determinacy::determined(finalize.is_some())),
1863                }
1864            } else {
1865                self.reborrow().resolve_ident_in_scope_set(
1866                    ident,
1867                    ScopeSet::All(ns),
1868                    parent_scope,
1869                    finalize,
1870                    finalize.is_some(),
1871                    ignore_decl,
1872                    ignore_import,
1873                )
1874            };
1875
1876            match binding {
1877                Ok(binding) => {
1878                    if segment_idx == 1 {
1879                        second_binding = Some(binding);
1880                    }
1881                    let res = binding.res();
1882
1883                    // Mark every privacy error in this path with the res to the last element. This allows us
1884                    // to detect the item the user cares about and either find an alternative import, or tell
1885                    // the user it is not accessible.
1886                    if finalize.is_some() {
1887                        for error in &mut self.get_mut().privacy_errors[privacy_errors_len..] {
1888                            error.outermost_res = Some((res, ident));
1889                            error.source = match source {
1890                                Some(PathSource::Struct(Some(expr)))
1891                                | Some(PathSource::Expr(Some(expr))) => Some(expr.clone()),
1892                                _ => None,
1893                            };
1894                        }
1895                    }
1896
1897                    let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
1898                    if let Some(def_id) = binding.res().module_like_def_id() {
1899                        if self.mods_with_parse_errors.contains(&def_id) {
1900                            module_had_parse_errors = true;
1901                        }
1902                        module = Some(ModuleOrUniformRoot::Module(self.expect_module(def_id)));
1903                        record_segment_res(self.reborrow(), finalize, res, id);
1904                    } else if res == Res::ToolMod && !is_last && opt_ns.is_some() {
1905                        if binding.is_import() {
1906                            self.dcx().emit_err(errors::ToolModuleImported {
1907                                span: ident.span,
1908                                import: binding.span,
1909                            });
1910                        }
1911                        let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1912                        return PathResult::NonModule(PartialRes::new(res));
1913                    } else if res == Res::Err {
1914                        return PathResult::NonModule(PartialRes::new(Res::Err));
1915                    } else if opt_ns.is_some() && (is_last || maybe_assoc) {
1916                        if let Some(finalize) = finalize {
1917                            self.get_mut().lint_if_path_starts_with_module(
1918                                finalize,
1919                                path,
1920                                second_binding,
1921                            );
1922                        }
1923                        record_segment_res(self.reborrow(), finalize, res, id);
1924                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
1925                            res,
1926                            path.len() - segment_idx - 1,
1927                        ));
1928                    } else {
1929                        return PathResult::failed(
1930                            ident,
1931                            is_last,
1932                            finalize.is_some(),
1933                            module_had_parse_errors,
1934                            module,
1935                            || {
1936                                let label = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{2}` is {0} {1}, not a module",
                res.article(), res.descr(), ident))
    })format!(
1937                                    "`{ident}` is {} {}, not a module",
1938                                    res.article(),
1939                                    res.descr()
1940                                );
1941                                (label, None)
1942                            },
1943                        );
1944                    }
1945                }
1946                Err(Undetermined) => return PathResult::Indeterminate,
1947                Err(Determined) => {
1948                    if let Some(ModuleOrUniformRoot::Module(module)) = module
1949                        && opt_ns.is_some()
1950                        && !module.is_normal()
1951                    {
1952                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
1953                            module.res().unwrap(),
1954                            path.len() - segment_idx,
1955                        ));
1956                    }
1957
1958                    let mut this = self.reborrow();
1959                    return PathResult::failed(
1960                        ident,
1961                        is_last,
1962                        finalize.is_some(),
1963                        module_had_parse_errors,
1964                        module,
1965                        || {
1966                            this.get_mut().report_path_resolution_error(
1967                                path,
1968                                opt_ns,
1969                                parent_scope,
1970                                ribs,
1971                                ignore_decl,
1972                                ignore_import,
1973                                module,
1974                                segment_idx,
1975                                ident,
1976                                diag_metadata,
1977                            )
1978                        },
1979                    );
1980                }
1981            }
1982        }
1983
1984        if let Some(finalize) = finalize {
1985            self.get_mut().lint_if_path_starts_with_module(finalize, path, second_binding);
1986        }
1987
1988        PathResult::Module(match module {
1989            Some(module) => module,
1990            None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
1991            _ => ::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),
1992        })
1993    }
1994}