Skip to main content

rustc_resolve/
ident.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<LateDecl<'ra>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let orig_ident = ident;
            let (general_span, normalized_span) =
                if ident.name == kw::SelfUpper {
                    let empty_span =
                        ident.span.with_ctxt(SyntaxContext::root());
                    (empty_span, empty_span)
                } else if ns == TypeNS {
                    let normalized_span = ident.span.normalize_to_macros_2_0();
                    (normalized_span, normalized_span)
                } else {
                    (ident.span.normalize_to_macro_rules(),
                        ident.span.normalize_to_macros_2_0())
                };
            ident.span = general_span;
            let normalized_ident = Ident { span: normalized_span, ..ident };
            for (i, rib) in ribs.iter().enumerate().rev() {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/ident.rs:333",
                                        "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                        ::tracing_core::__macro_support::Option::Some(333u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("walk rib\n{0:?}",
                                                                    rib.bindings) as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                let rib_ident =
                    if rib.kind.contains_params() {
                        normalized_ident
                    } else { ident };
                if let Some((original_rib_ident_def, res)) =
                        rib.bindings.get_key_value(&rib_ident) {
                    return Some(LateDecl::RibDef(self.validate_res_from_ribs(i,
                                    rib_ident, *res, finalize.map(|_| general_span),
                                    *original_rib_ident_def, ribs, diag_metadata)));
                } else if let RibKind::Block(Some(module)) = rib.kind &&
                        let Ok(binding) =
                            self.cm().resolve_ident_in_scope_set(ident,
                                ScopeSet::Module(ns, module.to_module()), parent_scope,
                                finalize.map(|finalize|
                                        Finalize { used: Used::Scope, ..finalize }), ignore_decl,
                                None) {
                    return Some(LateDecl::Decl(binding));
                } else if let RibKind::Module(module) = rib.kind {
                    let parent_scope =
                        &ParentScope {
                                module: module.to_module(),
                                ..*parent_scope
                            };
                    let finalize =
                        finalize.map(|f| Finalize { stage: Stage::Late, ..f });
                    return self.cm().resolve_ident_in_scope_set(orig_ident,
                                    ScopeSet::All(ns), parent_scope, finalize, ignore_decl,
                                    None).ok().map(LateDecl::Decl);
                }
                if let RibKind::MacroDefinition(def) = rib.kind &&
                        def == self.macro_def(ident.span.ctxt()) {
                    ident.span.remove_mark();
                }
            }
            ::core::panicking::panic("internal error: entered unreachable code")
        }
    }
}#[instrument(level = "debug", skip(self, ribs))]
307    pub(crate) fn resolve_ident_in_lexical_scope(
308        &mut self,
309        mut ident: Ident,
310        ns: Namespace,
311        parent_scope: &ParentScope<'ra>,
312        finalize: Option<Finalize>,
313        ribs: &[Rib<'ra>],
314        ignore_decl: Option<Decl<'ra>>,
315        diag_metadata: Option<&DiagMetadata<'_>>,
316    ) -> Option<LateDecl<'ra>> {
317        let orig_ident = ident;
318        let (general_span, normalized_span) = if ident.name == kw::SelfUpper {
319            // FIXME(jseyfried) improve `Self` hygiene
320            let empty_span = ident.span.with_ctxt(SyntaxContext::root());
321            (empty_span, empty_span)
322        } else if ns == TypeNS {
323            let normalized_span = ident.span.normalize_to_macros_2_0();
324            (normalized_span, normalized_span)
325        } else {
326            (ident.span.normalize_to_macro_rules(), ident.span.normalize_to_macros_2_0())
327        };
328        ident.span = general_span;
329        let normalized_ident = Ident { span: normalized_span, ..ident };
330
331        // Walk backwards up the ribs in scope.
332        for (i, rib) in ribs.iter().enumerate().rev() {
333            debug!("walk rib\n{:?}", rib.bindings);
334            // Use the rib kind to determine whether we are resolving parameters
335            // (macro 2.0 hygiene) or local variables (`macro_rules` hygiene).
336            let rib_ident = if rib.kind.contains_params() { normalized_ident } else { ident };
337            if let Some((original_rib_ident_def, res)) = rib.bindings.get_key_value(&rib_ident) {
338                // The ident resolves to a type parameter or local variable.
339                return Some(LateDecl::RibDef(self.validate_res_from_ribs(
340                    i,
341                    rib_ident,
342                    *res,
343                    finalize.map(|_| general_span),
344                    *original_rib_ident_def,
345                    ribs,
346                    diag_metadata,
347                )));
348            } else if let RibKind::Block(Some(module)) = rib.kind
349                && let Ok(binding) = self.cm().resolve_ident_in_scope_set(
350                    ident,
351                    ScopeSet::Module(ns, module.to_module()),
352                    parent_scope,
353                    finalize.map(|finalize| Finalize { used: Used::Scope, ..finalize }),
354                    ignore_decl,
355                    None,
356                )
357            {
358                // The ident resolves to an item in a block.
359                return Some(LateDecl::Decl(binding));
360            } else if let RibKind::Module(module) = rib.kind {
361                // Encountered a module item, abandon ribs and look into that module and preludes.
362                let parent_scope = &ParentScope { module: module.to_module(), ..*parent_scope };
363                let finalize = finalize.map(|f| Finalize { stage: Stage::Late, ..f });
364                return self
365                    .cm()
366                    .resolve_ident_in_scope_set(
367                        orig_ident,
368                        ScopeSet::All(ns),
369                        parent_scope,
370                        finalize,
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    pub(crate) fn resolve_ident_in_scope_set<'r>(
392        self: CmResolver<'r, 'ra, 'tcx>,
393        orig_ident: Ident,
394        scope_set: ScopeSet<'ra>,
395        parent_scope: &ParentScope<'ra>,
396        finalize: Option<Finalize>,
397        ignore_decl: Option<Decl<'ra>>,
398        ignore_import: Option<Import<'ra>>,
399    ) -> Result<Decl<'ra>, Determinacy> {
400        self.resolve_ident_in_scope_set_inner(
401            IdentKey::new(orig_ident),
402            orig_ident.span,
403            scope_set,
404            parent_scope,
405            finalize,
406            ignore_decl,
407            ignore_import,
408        )
409    }
410
411    fn resolve_ident_in_scope_set_inner<'r>(
412        self: CmResolver<'r, 'ra, 'tcx>,
413        ident: IdentKey,
414        orig_ident_span: Span,
415        scope_set: ScopeSet<'ra>,
416        parent_scope: &ParentScope<'ra>,
417        finalize: Option<Finalize>,
418        ignore_decl: Option<Decl<'ra>>,
419        ignore_import: Option<Import<'ra>>,
420    ) -> Result<Decl<'ra>, Determinacy> {
421        // Make sure `self`, `super` etc produce an error when passed to here.
422        if !#[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..)) && ident.name.is_path_segment_keyword() {
423            return Err(Determinacy::Determined);
424        }
425
426        let (ns, macro_kind) = match scope_set {
427            ScopeSet::All(ns)
428            | ScopeSet::Module(ns, _)
429            | ScopeSet::ModuleAndExternPrelude(ns, _) => (ns, None),
430            ScopeSet::ExternPrelude => (TypeNS, None),
431            ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind)),
432        };
433        let derive_fallback_lint_id = match finalize {
434            Some(Finalize { node_id, stage: Stage::Late, .. }) => Some(node_id),
435            _ => None,
436        };
437
438        // This is *the* result, resolution from the scope closest to the resolved identifier.
439        // However, sometimes this result is "weak" because it comes from a glob import or
440        // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
441        // mod m { ... } // solution in outer scope
442        // {
443        //     use prefix::*; // imports another `m` - innermost solution
444        //                    // weak, cannot shadow the outer `m`, need to report ambiguity error
445        //     m::mac!();
446        // }
447        // So we have to save the innermost solution and continue searching in outer scopes
448        // to detect potential ambiguities.
449        let mut innermost_results: SmallVec<[(Decl<'_>, Scope<'_>); 2]> = SmallVec::new();
450        let mut determinacy = Determinacy::Determined;
451
452        // Go through all the scopes and try to resolve the name.
453        let break_result = self.visit_scopes(
454            scope_set,
455            parent_scope,
456            ident.ctxt,
457            orig_ident_span,
458            derive_fallback_lint_id,
459            |mut this, scope, use_prelude, ctxt| {
460                let ident = IdentKey { name: ident.name, ctxt };
461                let res = match this.reborrow().resolve_ident_in_scope(
462                    ident,
463                    orig_ident_span,
464                    ns,
465                    scope,
466                    use_prelude,
467                    scope_set,
468                    parent_scope,
469                    // Shadowed decls don't need to be marked as used or non-speculatively loaded.
470                    if innermost_results.is_empty() { finalize } else { None },
471                    ignore_decl,
472                    ignore_import,
473                ) {
474                    Ok(decl) => Ok(decl),
475                    // We can break with an error at this step, it means we cannot determine the
476                    // resolution right now, but we must block and wait until we can, instead of
477                    // considering outer scopes. Although there's no need to do that if we already
478                    // have a better solution.
479                    Err(ControlFlow::Break(determinacy)) if innermost_results.is_empty() => {
480                        return ControlFlow::Break(Err(determinacy));
481                    }
482                    Err(determinacy) => Err(determinacy.into_value()),
483                };
484                match res {
485                    Ok(decl) if sub_namespace_match(decl.macro_kinds(), macro_kind) => {
486                        // Below we report various ambiguity errors.
487                        // We do not need to report them if we are either in speculative resolution,
488                        // or in late resolution when everything is already imported and expanded
489                        // and no ambiguities exist.
490                        let import = match finalize {
491                            None | Some(Finalize { stage: Stage::Late, .. }) => {
492                                return ControlFlow::Break(Ok(decl));
493                            }
494                            Some(Finalize { import, .. }) => import,
495                        };
496                        this.get_mut().maybe_push_glob_vs_glob_vis_ambiguity(
497                            ident,
498                            orig_ident_span,
499                            decl,
500                            import,
501                        );
502
503                        if let Some(&(innermost_decl, _)) = innermost_results.first() {
504                            // Found another solution, if the first one was "weak", report an error.
505                            if this.get_mut().maybe_push_ambiguity(
506                                ident,
507                                orig_ident_span,
508                                ns,
509                                scope_set,
510                                parent_scope,
511                                decl,
512                                scope,
513                                &innermost_results,
514                                import,
515                            ) {
516                                // No need to search for more potential ambiguities, one is enough.
517                                return ControlFlow::Break(Ok(innermost_decl));
518                            }
519                        }
520
521                        innermost_results.push((decl, scope));
522                    }
523                    Ok(_) | Err(Determinacy::Determined) => {}
524                    Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
525                }
526
527                ControlFlow::Continue(())
528            },
529        );
530
531        // Scope visiting returned some result early.
532        if let Some(break_result) = break_result {
533            return break_result;
534        }
535
536        // Scope visiting walked all the scopes and maybe found something in one of them.
537        match innermost_results.first() {
538            Some(&(decl, ..)) => Ok(decl),
539            None => Err(determinacy),
540        }
541    }
542
543    fn resolve_ident_in_scope<'r>(
544        mut self: CmResolver<'r, 'ra, 'tcx>,
545        ident: IdentKey,
546        orig_ident_span: Span,
547        ns: Namespace,
548        scope: Scope<'ra>,
549        use_prelude: UsePrelude,
550        scope_set: ScopeSet<'ra>,
551        parent_scope: &ParentScope<'ra>,
552        finalize: Option<Finalize>,
553        ignore_decl: Option<Decl<'ra>>,
554        ignore_import: Option<Import<'ra>>,
555    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
556        let ret = match scope {
557            Scope::DeriveHelpers(expn_id) => {
558                if let Some(decl) = self
559                    .helper_attrs
560                    .get(&expn_id)
561                    .and_then(|attrs| attrs.iter().rfind(|(i, ..)| ident == *i).map(|(.., d)| *d))
562                {
563                    Ok(decl)
564                } else {
565                    Err(Determinacy::Determined)
566                }
567            }
568            Scope::DeriveHelpersCompat => {
569                let mut result = Err(Determinacy::Determined);
570                for derive in parent_scope.derives {
571                    let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
572                    match self.reborrow().resolve_derive_macro_path(
573                        derive,
574                        parent_scope,
575                        false,
576                        ignore_import,
577                    ) {
578                        Ok((Some(ext), _)) => {
579                            if ext.helper_attrs.contains(&ident.name) {
580                                let decl = self.arenas.new_pub_def_decl(
581                                    Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat),
582                                    derive.span,
583                                    LocalExpnId::ROOT,
584                                );
585                                result = Ok(decl);
586                                break;
587                            }
588                        }
589                        Ok(_) | Err(Determinacy::Determined) => {}
590                        Err(Determinacy::Undetermined) => result = Err(Determinacy::Undetermined),
591                    }
592                }
593                result
594            }
595            Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
596                MacroRulesScope::Def(macro_rules_def) if ident == macro_rules_def.ident => {
597                    Ok(macro_rules_def.decl)
598                }
599                MacroRulesScope::Invocation(_) => Err(Determinacy::Undetermined),
600                _ => Err(Determinacy::Determined),
601            },
602            Scope::ModuleNonGlobs(module, derive_fallback_lint_id) => {
603                let (adjusted_parent_scope, adjusted_finalize) = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..) => true,
    _ => false,
}matches!(
604                    scope_set,
605                    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..)
606                ) {
607                    (parent_scope, finalize)
608                } else {
609                    (
610                        &ParentScope { module, ..*parent_scope },
611                        finalize.map(|f| Finalize { used: Used::Scope, ..f }),
612                    )
613                };
614                let shadowing = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..)) {
615                    Shadowing::Unrestricted
616                } else {
617                    Shadowing::Restricted
618                };
619                let decl = if module.is_local() {
620                    self.reborrow().resolve_ident_in_local_module_non_globs_unadjusted(
621                        module.expect_local(),
622                        ident,
623                        orig_ident_span,
624                        ns,
625                        adjusted_parent_scope,
626                        shadowing,
627                        adjusted_finalize,
628                        ignore_decl,
629                        ignore_import,
630                    )
631                } else {
632                    self.reborrow().resolve_ident_in_extern_module_non_globs_unadjusted(
633                        module.expect_extern(),
634                        ident,
635                        orig_ident_span,
636                        ns,
637                        adjusted_parent_scope,
638                        shadowing,
639                        adjusted_finalize,
640                        ignore_decl,
641                    )
642                };
643
644                match decl {
645                    Ok(decl) => {
646                        if let Some(lint_id) = derive_fallback_lint_id {
647                            self.get_mut().lint_buffer.buffer_lint(
648                                PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
649                                lint_id,
650                                orig_ident_span,
651                                diagnostics::ProcMacroDeriveResolutionFallback {
652                                    span: orig_ident_span,
653                                    ns_descr: ns.descr(),
654                                    ident: ident.name,
655                                },
656                            );
657                        }
658                        Ok(decl)
659                    }
660                    Err(ControlFlow::Continue(determinacy)) => Err(determinacy),
661                    Err(ControlFlow::Break(..)) => return decl,
662                }
663            }
664            Scope::ModuleGlobs(module, _) if !module.is_local() => {
665                // Fast path: external module decoding only creates non-glob declarations.
666                Err(Determined)
667            }
668            Scope::ModuleGlobs(module, derive_fallback_lint_id) => {
669                let (adjusted_parent_scope, adjusted_finalize) = if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..) => true,
    _ => false,
}matches!(
670                    scope_set,
671                    ScopeSet::Module(..) | ScopeSet::ModuleAndExternPrelude(..)
672                ) {
673                    (parent_scope, finalize)
674                } else {
675                    (
676                        &ParentScope { module, ..*parent_scope },
677                        finalize.map(|f| Finalize { used: Used::Scope, ..f }),
678                    )
679                };
680                let binding = self.reborrow().resolve_ident_in_module_globs_unadjusted(
681                    module.expect_local(),
682                    ident,
683                    orig_ident_span,
684                    ns,
685                    adjusted_parent_scope,
686                    if #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..)) {
687                        Shadowing::Unrestricted
688                    } else {
689                        Shadowing::Restricted
690                    },
691                    adjusted_finalize,
692                    ignore_decl,
693                    ignore_import,
694                );
695                match binding {
696                    Ok(binding) => {
697                        if let Some(lint_id) = derive_fallback_lint_id {
698                            self.get_mut().lint_buffer.buffer_lint(
699                                PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
700                                lint_id,
701                                orig_ident_span,
702                                diagnostics::ProcMacroDeriveResolutionFallback {
703                                    span: orig_ident_span,
704                                    ns_descr: ns.descr(),
705                                    ident: ident.name,
706                                },
707                            );
708                        }
709                        Ok(binding)
710                    }
711                    Err(ControlFlow::Continue(determinacy)) => Err(determinacy),
712                    Err(ControlFlow::Break(..)) => return binding,
713                }
714            }
715            Scope::MacroUsePrelude => match self.macro_use_prelude.get(&ident.name).cloned() {
716                Some(decl) => Ok(decl),
717                None => Err(Determinacy::determined(!self.graph_root.has_unexpanded_invocations())),
718            },
719            Scope::BuiltinAttrs => match self.builtin_attr_decls.get(&ident.name) {
720                Some(decl) => Ok(*decl),
721                None => Err(Determinacy::Determined),
722            },
723            Scope::ExternPreludeItems => {
724                match self.reborrow().extern_prelude_get_item(
725                    ident,
726                    orig_ident_span,
727                    finalize.is_some(),
728                ) {
729                    Some(decl) => Ok(decl),
730                    None => {
731                        Err(Determinacy::determined(!self.graph_root.has_unexpanded_invocations()))
732                    }
733                }
734            }
735            Scope::ExternPreludeFlags => {
736                match self.extern_prelude_get_flag(ident, orig_ident_span, finalize.is_some()) {
737                    Some(decl) => Ok(decl),
738                    None => Err(Determinacy::Determined),
739                }
740            }
741            Scope::ToolAttributePrelude => match self.registered_attr_tool_decls.get(&ident) {
742                Some(decl) => Ok(*decl),
743                None => Err(Determinacy::Determined),
744            },
745            Scope::StdLibPrelude => {
746                let mut result = Err(Determinacy::Determined);
747                if let Some(prelude) = self.prelude
748                    && let Ok(decl) = self.reborrow().resolve_ident_in_scope_set_inner(
749                        ident,
750                        orig_ident_span,
751                        ScopeSet::Module(ns, prelude),
752                        parent_scope,
753                        None,
754                        ignore_decl,
755                        ignore_import,
756                    )
757                    && (#[allow(non_exhaustive_omitted_patterns)] match use_prelude {
    UsePrelude::Yes => true,
    _ => false,
}matches!(use_prelude, UsePrelude::Yes) || self.is_builtin_macro(decl.res()))
758                {
759                    result = Ok(decl)
760                }
761
762                result
763            }
764            Scope::BuiltinTypes => match self.builtin_type_decls.get(&ident.name) {
765                Some(decl) => {
766                    if #[allow(non_exhaustive_omitted_patterns)] match ident.name {
    sym::f16 => true,
    _ => false,
}matches!(ident.name, sym::f16)
767                        && !self.features.f16()
768                        && !orig_ident_span.allows_unstable(sym::f16)
769                        && finalize.is_some()
770                    {
771                        feature_err(
772                            self.tcx.sess,
773                            sym::f16,
774                            orig_ident_span,
775                            "the type `f16` is unstable",
776                        )
777                        .emit();
778                    }
779                    if #[allow(non_exhaustive_omitted_patterns)] match ident.name {
    sym::f128 => true,
    _ => false,
}matches!(ident.name, sym::f128)
780                        && !self.features.f128()
781                        && !orig_ident_span.allows_unstable(sym::f128)
782                        && finalize.is_some()
783                    {
784                        feature_err(
785                            self.tcx.sess,
786                            sym::f128,
787                            orig_ident_span,
788                            "the type `f128` is unstable",
789                        )
790                        .emit();
791                    }
792                    Ok(*decl)
793                }
794                None => Err(Determinacy::Determined),
795            },
796        };
797
798        ret.map_err(ControlFlow::Continue)
799    }
800
801    fn maybe_push_glob_vs_glob_vis_ambiguity(
802        &mut self,
803        ident: IdentKey,
804        orig_ident_span: Span,
805        decl: Decl<'ra>,
806        import: Option<ImportSummary>,
807    ) {
808        let Some(import) = import else { return };
809        let vis1 = self.import_decl_vis(decl, import);
810        let vis2 = self.import_decl_vis_ext(decl, import, true);
811        if vis1 != vis2 {
812            self.ambiguity_errors.push(AmbiguityError {
813                kind: AmbiguityKind::GlobVsGlob,
814                ambig_vis: Some((vis1, vis2)),
815                ident: ident.orig(orig_ident_span),
816                b1: decl.ambiguity_vis_max.get().unwrap_or(decl),
817                b2: decl.ambiguity_vis_min.get().unwrap_or(decl),
818                scope1: Scope::ModuleGlobs(decl.parent_module.unwrap(), None),
819                scope2: Scope::ModuleGlobs(decl.parent_module.unwrap(), None),
820                warning: Some(AmbiguityWarning::GlobImport),
821            });
822        }
823    }
824
825    fn maybe_push_ambiguity(
826        &mut self,
827        ident: IdentKey,
828        orig_ident_span: Span,
829        ns: Namespace,
830        scope_set: ScopeSet<'ra>,
831        parent_scope: &ParentScope<'ra>,
832        decl: Decl<'ra>,
833        scope: Scope<'ra>,
834        innermost_results: &[(Decl<'ra>, Scope<'ra>)],
835        import: Option<ImportSummary>,
836    ) -> bool {
837        let (innermost_decl, innermost_scope) = innermost_results[0];
838        let (res, innermost_res) = (decl.res(), innermost_decl.res());
839        let ambig_vis = if res != innermost_res {
840            None
841        } else if let Some(import) = import
842            && let vis1 = self.import_decl_vis(decl, import)
843            && let vis2 = self.import_decl_vis(innermost_decl, import)
844            && vis1 != vis2
845        {
846            Some((vis1, vis2))
847        } else {
848            return false;
849        };
850
851        // FIXME: Use `scope` instead of `res` to detect built-in attrs and derive helpers,
852        // it will exclude imports, make slightly more code legal, and will require lang approval.
853        let module_only = #[allow(non_exhaustive_omitted_patterns)] match scope_set {
    ScopeSet::Module(..) => true,
    _ => false,
}matches!(scope_set, ScopeSet::Module(..));
854        let is_builtin = |res| #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)) => true,
    _ => false,
}matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)));
855        let derive_helper = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
856        let derive_helper_compat = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
857
858        let ambiguity_error_kind = if is_builtin(innermost_res) || is_builtin(res) {
859            Some(AmbiguityKind::BuiltinAttr)
860        } else if innermost_res == derive_helper_compat {
861            Some(AmbiguityKind::DeriveHelper)
862        } else if res == derive_helper_compat && innermost_res != derive_helper {
863            ::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")
864        } else if #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
    Scope::MacroRules(_) => true,
    _ => false,
}matches!(innermost_scope, Scope::MacroRules(_))
865            && #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..) => true,
    _ => false,
}matches!(scope, Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..))
866            && !self.disambiguate_macro_rules_vs_modularized(innermost_decl, decl)
867        {
868            Some(AmbiguityKind::MacroRulesVsModularized)
869        } else if #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::MacroRules(_) => true,
    _ => false,
}matches!(scope, Scope::MacroRules(_))
870            && #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
    Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..) => true,
    _ => false,
}matches!(innermost_scope, Scope::ModuleNonGlobs(..) | Scope::ModuleGlobs(..))
871        {
872            // should be impossible because of visitation order in
873            // visit_scopes
874            //
875            // we visit all macro_rules scopes (e.g. textual scope macros)
876            // before we visit any modules (e.g. path-based scope macros)
877            ::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!(
878                orig_ident_span,
879                "ambiguous scoped macro resolutions with path-based \
880                                        scope resolution as first candidate"
881            )
882        } else if innermost_decl.is_glob_import() {
883            Some(AmbiguityKind::GlobVsOuter)
884        } else if !module_only && innermost_decl.may_appear_after(parent_scope.expansion, decl) {
885            Some(AmbiguityKind::MoreExpandedVsOuter)
886        } else if innermost_decl.expansion != LocalExpnId::ROOT
887            && (!module_only || ns == MacroNS)
888            && let Scope::ModuleGlobs(m1, _) = scope
889            && let Scope::ModuleNonGlobs(m2, _) = innermost_scope
890            && m1 == m2
891        {
892            // FIXME: this error is too conservative and technically unnecessary now when module
893            // scope is split into two scopes, at least when not resolving in `ScopeSet::Module`,
894            // remove it with lang team approval.
895            Some(AmbiguityKind::GlobVsExpanded)
896        } else {
897            None
898        };
899
900        if let Some(kind) = ambiguity_error_kind {
901            // Skip ambiguity errors for extern flag bindings "overridden"
902            // by extern item bindings.
903            // FIXME: Remove with lang team approval.
904            let issue_145575_hack = #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::ExternPreludeFlags => true,
    _ => false,
}matches!(scope, Scope::ExternPreludeFlags)
905                && innermost_results[1..]
906                    .iter()
907                    .any(|(b, s)| #[allow(non_exhaustive_omitted_patterns)] match s {
    Scope::ExternPreludeItems => true,
    _ => false,
}matches!(s, Scope::ExternPreludeItems) && *b != innermost_decl);
908            // Skip ambiguity errors for nonglob module bindings "overridden"
909            // by glob module bindings in the same module.
910            // FIXME: Remove with lang team approval.
911            let issue_149681_hack = match scope {
912                Scope::ModuleGlobs(m1, _)
913                    if innermost_results[1..]
914                        .iter()
915                        .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)) =>
916                {
917                    true
918                }
919                _ => false,
920            };
921
922            if issue_145575_hack || issue_149681_hack {
923                self.issue_145575_hack_applied = true;
924            } else {
925                // Turn ambiguity errors for core vs std panic into warnings.
926                // FIXME: Remove with lang team approval.
927                let is_issue_147319_hack = orig_ident_span.edition() <= Edition::Edition2024
928                    && #[allow(non_exhaustive_omitted_patterns)] match ident.name {
    sym::panic => true,
    _ => false,
}matches!(ident.name, sym::panic)
929                    && #[allow(non_exhaustive_omitted_patterns)] match scope {
    Scope::StdLibPrelude => true,
    _ => false,
}matches!(scope, Scope::StdLibPrelude)
930                    && #[allow(non_exhaustive_omitted_patterns)] match innermost_scope {
    Scope::ModuleGlobs(_, _) => true,
    _ => false,
}matches!(innermost_scope, Scope::ModuleGlobs(_, _))
931                    && ((self.is_specific_builtin_macro(res, sym::std_panic)
932                        && self.is_specific_builtin_macro(innermost_res, sym::core_panic))
933                        || (self.is_specific_builtin_macro(res, sym::core_panic)
934                            && self.is_specific_builtin_macro(innermost_res, sym::std_panic)));
935
936                let warning = if ambig_vis.is_some() {
937                    Some(AmbiguityWarning::GlobImport)
938                } else if is_issue_147319_hack {
939                    Some(AmbiguityWarning::PanicImport)
940                } else {
941                    None
942                };
943
944                self.ambiguity_errors.push(AmbiguityError {
945                    kind,
946                    ambig_vis,
947                    ident: ident.orig(orig_ident_span),
948                    b1: innermost_decl,
949                    b2: decl,
950                    scope1: innermost_scope,
951                    scope2: scope,
952                    warning,
953                });
954                return true;
955            }
956        }
957
958        false
959    }
960
961    #[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(961u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("module")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("module");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ident")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ident");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ns")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ns");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("parent_scope")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("parent_scope");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ignore_import")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ignore_import");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&module)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ns)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<Decl<'ra>, Determinacy> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.resolve_ident_in_module(module, ident, ns, parent_scope,
                None, None, ignore_import)
        }
    }
}#[instrument(level = "debug", skip(self))]
962    pub(crate) fn maybe_resolve_ident_in_module<'r>(
963        self: CmResolver<'r, 'ra, 'tcx>,
964        module: ModuleOrUniformRoot<'ra>,
965        ident: Ident,
966        ns: Namespace,
967        parent_scope: &ParentScope<'ra>,
968        ignore_import: Option<Import<'ra>>,
969    ) -> Result<Decl<'ra>, Determinacy> {
970        self.resolve_ident_in_module(module, ident, ns, parent_scope, None, None, ignore_import)
971    }
972
973    fn resolve_super_in_module(
974        &self,
975        ident: Ident,
976        module: Option<Module<'ra>>,
977        parent_scope: &ParentScope<'ra>,
978    ) -> Option<Module<'ra>> {
979        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
980        module
981            .unwrap_or_else(|| self.resolve_self(&mut ctxt, parent_scope.module))
982            .parent
983            .map(|parent| self.resolve_self(&mut ctxt, parent))
984    }
985
986    pub(crate) fn path_root_is_crate_root(&self, ident: Ident) -> bool {
987        ident.name == kw::PathRoot && ident.span.is_rust_2015() && self.tcx.sess.is_rust_2015()
988    }
989
990    #[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(990u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("module")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("module");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ident")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ident");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ns")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ns");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("parent_scope")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("parent_scope");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("finalize")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("finalize");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ignore_decl")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ignore_decl");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ignore_import")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ignore_import");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&module)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ns)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_decl)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<Decl<'ra>, Determinacy> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            match module {
                ModuleOrUniformRoot::Module(module) => {
                    if ns == TypeNS {
                        if ident.name == kw::SelfLower {
                            return Ok(module.self_decl.unwrap());
                        }
                        if ident.name == kw::Super &&
                                let Some(module) =
                                    self.resolve_super_in_module(ident, Some(module),
                                        parent_scope) {
                            return Ok(module.self_decl.unwrap());
                        }
                    }
                    let (ident_key, def) =
                        IdentKey::new_adjusted(ident, module.expansion);
                    let adjusted_parent_scope =
                        match def {
                            Some(def) =>
                                ParentScope {
                                    module: self.expn_def_scope(def),
                                    ..*parent_scope
                                },
                            None => *parent_scope,
                        };
                    self.resolve_ident_in_scope_set_inner(ident_key, ident.span,
                        ScopeSet::Module(ns, module), &adjusted_parent_scope,
                        finalize, ignore_decl, ignore_import)
                }
                ModuleOrUniformRoot::OpenModule(sym) => {
                    let open_ns_name =
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("{0}::{1}", sym.as_str(),
                                        ident.name))
                            });
                    let ns_ident =
                        IdentKey::with_root_ctxt(Symbol::intern(&open_ns_name));
                    match self.extern_prelude_get_flag(ns_ident, ident.span,
                            finalize.is_some()) {
                        Some(decl) => Ok(decl),
                        None => Err(Determinacy::Determined),
                    }
                }
                ModuleOrUniformRoot::ModuleAndExternPrelude(module) =>
                    self.resolve_ident_in_scope_set(ident,
                        ScopeSet::ModuleAndExternPrelude(ns, module), parent_scope,
                        finalize, ignore_decl, ignore_import),
                ModuleOrUniformRoot::ExternPrelude => {
                    if ns != TypeNS {
                        Err(Determined)
                    } else {
                        self.resolve_ident_in_scope_set_inner(IdentKey::new_adjusted(ident,
                                    ExpnId::root()).0, ident.span, ScopeSet::ExternPrelude,
                            parent_scope, finalize, ignore_decl, ignore_import)
                    }
                }
                ModuleOrUniformRoot::CurrentScope => {
                    if ns == TypeNS {
                        if ident.name == kw::SelfLower {
                            let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
                            let module =
                                self.resolve_self(&mut ctxt, parent_scope.module);
                            return Ok(module.self_decl.unwrap());
                        }
                        if ident.name == kw::Super &&
                                let Some(module) =
                                    self.resolve_super_in_module(ident, None, parent_scope) {
                            return Ok(module.self_decl.unwrap());
                        }
                        if ident.name == kw::Crate || ident.name == kw::DollarCrate
                                || self.path_root_is_crate_root(ident) {
                            let module = self.resolve_crate_root(ident);
                            return Ok(module.self_decl.unwrap());
                        } else if ident.name == kw::Super {}
                    }
                    self.resolve_ident_in_scope_set(ident, ScopeSet::All(ns),
                        parent_scope, finalize, ignore_decl, ignore_import)
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
991    pub(crate) fn resolve_ident_in_module<'r>(
992        self: CmResolver<'r, 'ra, 'tcx>,
993        module: ModuleOrUniformRoot<'ra>,
994        ident: Ident,
995        ns: Namespace,
996        parent_scope: &ParentScope<'ra>,
997        finalize: Option<Finalize>,
998        ignore_decl: Option<Decl<'ra>>,
999        ignore_import: Option<Import<'ra>>,
1000    ) -> Result<Decl<'ra>, Determinacy> {
1001        match module {
1002            ModuleOrUniformRoot::Module(module) => {
1003                if ns == TypeNS {
1004                    if ident.name == kw::SelfLower {
1005                        return Ok(module.self_decl.unwrap());
1006                    }
1007                    if ident.name == kw::Super
1008                        && let Some(module) =
1009                            self.resolve_super_in_module(ident, Some(module), parent_scope)
1010                    {
1011                        return Ok(module.self_decl.unwrap());
1012                    }
1013                }
1014
1015                let (ident_key, def) = IdentKey::new_adjusted(ident, module.expansion);
1016                let adjusted_parent_scope = match def {
1017                    Some(def) => ParentScope { module: self.expn_def_scope(def), ..*parent_scope },
1018                    None => *parent_scope,
1019                };
1020                self.resolve_ident_in_scope_set_inner(
1021                    ident_key,
1022                    ident.span,
1023                    ScopeSet::Module(ns, module),
1024                    &adjusted_parent_scope,
1025                    finalize,
1026                    ignore_decl,
1027                    ignore_import,
1028                )
1029            }
1030            ModuleOrUniformRoot::OpenModule(sym) => {
1031                let open_ns_name = format!("{}::{}", sym.as_str(), ident.name);
1032                let ns_ident = IdentKey::with_root_ctxt(Symbol::intern(&open_ns_name));
1033                match self.extern_prelude_get_flag(ns_ident, ident.span, finalize.is_some()) {
1034                    Some(decl) => Ok(decl),
1035                    None => Err(Determinacy::Determined),
1036                }
1037            }
1038            ModuleOrUniformRoot::ModuleAndExternPrelude(module) => self.resolve_ident_in_scope_set(
1039                ident,
1040                ScopeSet::ModuleAndExternPrelude(ns, module),
1041                parent_scope,
1042                finalize,
1043                ignore_decl,
1044                ignore_import,
1045            ),
1046            ModuleOrUniformRoot::ExternPrelude => {
1047                if ns != TypeNS {
1048                    Err(Determined)
1049                } else {
1050                    self.resolve_ident_in_scope_set_inner(
1051                        IdentKey::new_adjusted(ident, ExpnId::root()).0,
1052                        ident.span,
1053                        ScopeSet::ExternPrelude,
1054                        parent_scope,
1055                        finalize,
1056                        ignore_decl,
1057                        ignore_import,
1058                    )
1059                }
1060            }
1061            ModuleOrUniformRoot::CurrentScope => {
1062                if ns == TypeNS {
1063                    if ident.name == kw::SelfLower {
1064                        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1065                        let module = self.resolve_self(&mut ctxt, parent_scope.module);
1066                        return Ok(module.self_decl.unwrap());
1067                    }
1068                    if ident.name == kw::Super
1069                        && let Some(module) =
1070                            self.resolve_super_in_module(ident, None, parent_scope)
1071                    {
1072                        return Ok(module.self_decl.unwrap());
1073                    }
1074                    if ident.name == kw::Crate
1075                        || ident.name == kw::DollarCrate
1076                        || self.path_root_is_crate_root(ident)
1077                    {
1078                        let module = self.resolve_crate_root(ident);
1079                        return Ok(module.self_decl.unwrap());
1080                    } else if ident.name == kw::Super {
1081                        // FIXME: Implement these with renaming requirements so that e.g.
1082                        // `use super;` doesn't work, but `use super as name;` does.
1083                        // Fall through here to get an error from `early_resolve_...`.
1084                    }
1085                }
1086
1087                self.resolve_ident_in_scope_set(
1088                    ident,
1089                    ScopeSet::All(ns),
1090                    parent_scope,
1091                    finalize,
1092                    ignore_decl,
1093                    ignore_import,
1094                )
1095            }
1096        }
1097    }
1098
1099    /// Attempts to resolve `ident` in namespace `ns` of non-glob bindings in an external `module`.
1100    fn resolve_ident_in_extern_module_non_globs_unadjusted<'r>(
1101        mut self: CmResolver<'r, 'ra, 'tcx>,
1102        module: ExternModule<'ra>,
1103        ident: IdentKey,
1104        orig_ident_span: Span,
1105        ns: Namespace,
1106        parent_scope: &ParentScope<'ra>,
1107        shadowing: Shadowing,
1108        finalize: Option<Finalize>,
1109        // This binding should be ignored during in-module resolution, so that we don't get
1110        // "self-confirming" import resolutions during import validation and checking.
1111        ignore_decl: Option<Decl<'ra>>,
1112    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1113        let key = BindingKey::new(ident, ns);
1114        let resolution =
1115            &*self.resolution(module.to_module(), key).ok_or(ControlFlow::Continue(Determined))?;
1116
1117        let binding = resolution.non_glob_decl.filter(|b| Some(*b) != ignore_decl);
1118
1119        if let Some(finalize) = finalize {
1120            return self.get_mut().finalize_module_binding(
1121                ident,
1122                orig_ident_span,
1123                binding,
1124                parent_scope,
1125                finalize,
1126                shadowing,
1127            );
1128        }
1129
1130        // Items and single imports are not shadowable, if we have one, then it's determined.
1131        if let Some(binding) = binding {
1132            let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1133            return if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) };
1134        }
1135        Err(ControlFlow::Continue(Determined))
1136    }
1137
1138    /// Attempts to resolve `ident` in namespace `ns` of non-glob bindings in a local `module`.
1139    fn resolve_ident_in_local_module_non_globs_unadjusted<'r>(
1140        mut self: CmResolver<'r, 'ra, 'tcx>,
1141        module: LocalModule<'ra>,
1142        ident: IdentKey,
1143        orig_ident_span: Span,
1144        ns: Namespace,
1145        parent_scope: &ParentScope<'ra>,
1146        shadowing: Shadowing,
1147        finalize: Option<Finalize>,
1148        // This binding should be ignored during in-module resolution, so that we don't get
1149        // "self-confirming" import resolutions during import validation and checking.
1150        ignore_decl: Option<Decl<'ra>>,
1151        ignore_import: Option<Import<'ra>>,
1152    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1153        let key = BindingKey::new(ident, ns);
1154        let resolution = self.resolution(module.to_module(), key);
1155
1156        let binding =
1157            resolution.as_ref().and_then(|r| r.non_glob_decl).filter(|b| Some(*b) != ignore_decl);
1158
1159        if let Some(finalize) = finalize {
1160            // finalize implies that the module is fully expanded
1161            if !!module.has_unexpanded_invocations() {
    ::core::panicking::panic("assertion failed: !module.has_unexpanded_invocations()")
};assert!(!module.has_unexpanded_invocations());
1162            return self.get_mut().finalize_module_binding(
1163                ident,
1164                orig_ident_span,
1165                binding,
1166                parent_scope,
1167                finalize,
1168                shadowing,
1169            );
1170        }
1171
1172        // Items and single imports are not shadowable, if we have one, then it's determined.
1173        if let Some(binding) = binding {
1174            let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1175            return if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) };
1176        }
1177
1178        if let Some(resolution) = resolution {
1179            // We need to detect resolution cycles to avoid infinite recursion. The guard ensures
1180            // the resolution is removed when this resolve call ends.
1181            let _cycle_guard = cycle_detection::enter_cycle_detector(module, key)
1182                .map_err(|_| ControlFlow::Continue(Determined))?;
1183
1184            // Check if one of single imports can still define the name, block if it can.
1185            if self.reborrow().single_import_can_define_name(
1186                &resolution,
1187                None,
1188                ns,
1189                ignore_import,
1190                ignore_decl,
1191                parent_scope,
1192            ) {
1193                return Err(ControlFlow::Break(Undetermined));
1194            }
1195        }
1196
1197        // Check if one of unexpanded macros can still define the name.
1198        if module.has_unexpanded_invocations() {
1199            return Err(ControlFlow::Continue(Undetermined));
1200        }
1201
1202        // No resolution and no one else can define the name - determinate error.
1203        Err(ControlFlow::Continue(Determined))
1204    }
1205
1206    /// Attempts to resolve `ident` in namespace `ns` of glob bindings in `module`.
1207    fn resolve_ident_in_module_globs_unadjusted<'r>(
1208        mut self: CmResolver<'r, 'ra, 'tcx>,
1209        module: LocalModule<'ra>,
1210        ident: IdentKey,
1211        orig_ident_span: Span,
1212        ns: Namespace,
1213        parent_scope: &ParentScope<'ra>,
1214        shadowing: Shadowing,
1215        finalize: Option<Finalize>,
1216        ignore_decl: Option<Decl<'ra>>,
1217        ignore_import: Option<Import<'ra>>,
1218    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1219        let key = BindingKey::new(ident, ns);
1220        let resolution = self.resolution(module.to_module(), key);
1221
1222        let binding =
1223            resolution.as_ref().and_then(|r| r.glob_decl).filter(|b| Some(*b) != ignore_decl);
1224
1225        if let Some(finalize) = finalize {
1226            // finalize implies that the module is fully expanded
1227            if !!module.has_unexpanded_invocations() {
    ::core::panicking::panic("assertion failed: !module.has_unexpanded_invocations()")
};assert!(!module.has_unexpanded_invocations());
1228            return self.get_mut().finalize_module_binding(
1229                ident,
1230                orig_ident_span,
1231                binding,
1232                parent_scope,
1233                finalize,
1234                shadowing,
1235            );
1236        }
1237
1238        // We need to detect resolution cycles to avoid infinite recursion. The guard ensures
1239        // the resolution is removed when this resolve call ends.
1240        let _cycle_guard = cycle_detection::enter_cycle_detector(module, key)
1241            .map_err(|_| ControlFlow::Continue(Determined))?;
1242
1243        // Check if one of single imports can still define the name,
1244        // if it can then our result is not determined and can be invalidated.
1245        if let Some(resolution) = resolution {
1246            if self.reborrow().single_import_can_define_name(
1247                &resolution,
1248                binding,
1249                ns,
1250                ignore_import,
1251                ignore_decl,
1252                parent_scope,
1253            ) {
1254                return Err(ControlFlow::Break(Undetermined));
1255            }
1256        }
1257
1258        // So we have a resolution that's from a glob import. This resolution is determined
1259        // if it cannot be shadowed by some new item/import expanded from a macro.
1260        // This happens either if there are no unexpanded macros, or expanded names cannot
1261        // shadow globs (that happens in macro namespace or with restricted shadowing).
1262        //
1263        // Additionally, any macro in any module can plant names in the root module if it creates
1264        // `macro_export` macros, so the root module effectively has unresolved invocations if any
1265        // module has unresolved invocations.
1266        // However, it causes resolution/expansion to stuck too often (#53144), so, to make
1267        // progress, we have to ignore those potential unresolved invocations from other modules
1268        // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
1269        // shadowing is enabled, see `macro_expanded_macro_export_errors`).
1270        if let Some(binding) = binding {
1271            return if binding.determined() || ns == MacroNS || shadowing == Shadowing::Restricted {
1272                let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1273                if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) }
1274            } else {
1275                Err(ControlFlow::Break(Undetermined))
1276            };
1277        }
1278
1279        // Now we are in situation when new item/import can appear only from a glob or a macro
1280        // expansion. With restricted shadowing names from globs and macro expansions cannot
1281        // shadow names from outer scopes, so we can freely fallback from module search to search
1282        // in outer scopes. For `resolve_ident_in_scope_set` to continue search in outer
1283        // scopes we return `Undetermined` with `ControlFlow::Continue`.
1284        // Check if one of unexpanded macros can still define the name,
1285        // if it can then our "no resolution" result is not determined and can be invalidated.
1286        if module.has_unexpanded_invocations() {
1287            return Err(ControlFlow::Continue(Undetermined));
1288        }
1289
1290        // Check if one of glob imports can still define the name,
1291        // if it can then our "no resolution" result is not determined and can be invalidated.
1292        for glob_import in module.globs.borrow().iter() {
1293            if ignore_import == Some(*glob_import) {
1294                continue;
1295            }
1296            if !self.is_accessible_from(glob_import.vis, parent_scope.module) {
1297                continue;
1298            }
1299            let module = match glob_import.imported_module.get() {
1300                Some(ModuleOrUniformRoot::Module(module)) => module,
1301                Some(_) => continue,
1302                None => return Err(ControlFlow::Continue(Undetermined)),
1303            };
1304            let tmp_parent_scope;
1305            let (mut adjusted_parent_scope, mut adjusted_ident) = (parent_scope, ident);
1306            match adjusted_ident
1307                .ctxt
1308                .update_unchecked(|ctxt| ctxt.glob_adjust(module.expansion, glob_import.span))
1309            {
1310                Some(Some(def)) => {
1311                    tmp_parent_scope =
1312                        ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
1313                    adjusted_parent_scope = &tmp_parent_scope;
1314                }
1315                Some(None) => {}
1316                None => continue,
1317            };
1318            let result = self.reborrow().resolve_ident_in_scope_set_inner(
1319                adjusted_ident,
1320                orig_ident_span,
1321                ScopeSet::Module(ns, module),
1322                adjusted_parent_scope,
1323                None,
1324                ignore_decl,
1325                ignore_import,
1326            );
1327
1328            match result {
1329                Err(Determined) => continue,
1330                Ok(binding)
1331                    if !self.is_accessible_from(binding.vis(), glob_import.parent_scope.module) =>
1332                {
1333                    continue;
1334                }
1335                Ok(_) | Err(Undetermined) => return Err(ControlFlow::Continue(Undetermined)),
1336            }
1337        }
1338
1339        // No resolution and no one else can define the name - determinate error.
1340        Err(ControlFlow::Continue(Determined))
1341    }
1342
1343    fn finalize_module_binding(
1344        &mut self,
1345        ident: IdentKey,
1346        orig_ident_span: Span,
1347        binding: Option<Decl<'ra>>,
1348        parent_scope: &ParentScope<'ra>,
1349        finalize: Finalize,
1350        shadowing: Shadowing,
1351    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1352        let Finalize { path_span, report_private, used, root_span, .. } = finalize;
1353
1354        let Some(binding) = binding else {
1355            return Err(ControlFlow::Continue(Determined));
1356        };
1357
1358        let ident = ident.orig(orig_ident_span);
1359        if !self.is_accessible_from(binding.vis(), parent_scope.module) {
1360            if report_private {
1361                self.privacy_errors.push(PrivacyError {
1362                    ident,
1363                    decl: binding,
1364                    dedup_span: path_span,
1365                    outermost_res: None,
1366                    source: None,
1367                    parent_scope: *parent_scope,
1368                    single_nested: path_span != root_span,
1369                });
1370            } else {
1371                return Err(ControlFlow::Break(Determined));
1372            }
1373        }
1374
1375        if shadowing == Shadowing::Unrestricted
1376            && binding.expansion != LocalExpnId::ROOT
1377            && let DeclKind::Import { import, .. } = binding.kind
1378            && #[allow(non_exhaustive_omitted_patterns)] match import.kind {
    ImportKind::MacroExport => true,
    _ => false,
}matches!(import.kind, ImportKind::MacroExport)
1379        {
1380            self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
1381        }
1382
1383        self.record_use(ident, binding, used);
1384        return Ok(binding);
1385    }
1386
1387    // Checks if a single import can define the `Ident` corresponding to `binding`.
1388    // This is used to check whether we can definitively accept a glob as a resolution.
1389    fn single_import_can_define_name<'r>(
1390        mut self: CmResolver<'r, 'ra, 'tcx>,
1391        resolution: &NameResolution<'ra>,
1392        binding: Option<Decl<'ra>>,
1393        ns: Namespace,
1394        ignore_import: Option<Import<'ra>>,
1395        ignore_decl: Option<Decl<'ra>>,
1396        parent_scope: &ParentScope<'ra>,
1397    ) -> bool {
1398        for single_import in &resolution.single_imports {
1399            if let Some(decl) = resolution.non_glob_decl
1400                && let DeclKind::Import { import, .. } = decl.kind
1401                && import == *single_import
1402            {
1403                // Single import has already defined the name and we are aware of it,
1404                // no need to block the globs.
1405                continue;
1406            }
1407            if ignore_import == Some(*single_import) {
1408                continue;
1409            }
1410            if !self.is_accessible_from(single_import.vis, parent_scope.module) {
1411                continue;
1412            }
1413            if let Some(ignored) = ignore_decl
1414                && let DeclKind::Import { import, .. } = ignored.kind
1415                && import == *single_import
1416            {
1417                continue;
1418            }
1419
1420            let Some(module) = single_import.imported_module.get() else {
1421                return true;
1422            };
1423            let ImportKind::Single { source, target, decls, .. } = &single_import.kind else {
1424                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1425            };
1426            if source != target {
1427                if decls.iter().all(|d| d.get().decl().is_none()) {
1428                    return true;
1429                } else if decls[ns].get().decl().is_none() && binding.is_some() {
1430                    return true;
1431                }
1432            }
1433
1434            match self.reborrow().resolve_ident_in_module(
1435                module,
1436                *source,
1437                ns,
1438                &single_import.parent_scope,
1439                None,
1440                ignore_decl,
1441                None,
1442            ) {
1443                Err(Determined) => continue,
1444                Ok(binding)
1445                    if !self
1446                        .is_accessible_from(binding.vis(), single_import.parent_scope.module) =>
1447                {
1448                    continue;
1449                }
1450                Ok(_) | Err(Undetermined) => return true,
1451            }
1452        }
1453
1454        false
1455    }
1456
1457    /// Validate a local resolution (from ribs).
1458    #[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(1458u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("rib_index")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("rib_index");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("rib_ident")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("rib_ident");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("res")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("res");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("finalize")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("finalize");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("original_rib_ident_def")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("original_rib_ident_def");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("diag_metadata")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("diag_metadata");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&rib_index
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rib_ident)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&original_rib_ident_def)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_metadata)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Res = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/ident.rs:1469",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1469u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("validate_res_from_ribs({0:?})",
                                                                res) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let ribs = &all_ribs[rib_index + 1..];
            if let RibKind::ForwardGenericParamBan(reason) =
                    all_ribs[rib_index].kind {
                if let Some(span) = finalize {
                    let res_error =
                        if rib_ident.name == kw::SelfUpper {
                            ResolutionError::ForwardDeclaredSelf(reason)
                        } else {
                            ResolutionError::ForwardDeclaredGenericParam(rib_ident.name,
                                reason)
                        };
                    self.report_error(span, res_error);
                }
                {
                    match (&res, &Res::Err) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    }
                };
                return Res::Err;
            }
            match res {
                Res::Local(_) => {
                    use ResolutionError::*;
                    let mut res_err = None;
                    for rib in ribs {
                        match rib.kind {
                            RibKind::Normal | RibKind::Block(..) |
                                RibKind::FnOrCoroutine | RibKind::Module(..) |
                                RibKind::MacroDefinition(..) |
                                RibKind::ForwardGenericParamBan(_) => {}
                            RibKind::Item(..) | RibKind::AssocItem => {
                                if let Some(span) = finalize {
                                    res_err =
                                        Some((span, CannotCaptureDynamicEnvironmentInFnItem));
                                }
                            }
                            RibKind::ConstantItem(_, item) => {
                                if let Some(span) = finalize {
                                    let (span, resolution_error) =
                                        match item {
                                            None if rib_ident.name == kw::SelfLower => {
                                                (span, LowercaseSelf)
                                            }
                                            None => {
                                                let sm = self.tcx.sess.source_map();
                                                let type_span =
                                                    match sm.span_followed_by(original_rib_ident_def.span, ":")
                                                        {
                                                        None => { Some(original_rib_ident_def.span.shrink_to_hi()) }
                                                        Some(_) => None,
                                                    };
                                                (rib_ident.span,
                                                    AttemptToUseNonConstantValueInConstant {
                                                        ident: original_rib_ident_def,
                                                        suggestion: "const",
                                                        current: "let",
                                                        type_span,
                                                    })
                                            }
                                            Some((ident, kind)) =>
                                                (span,
                                                    AttemptToUseNonConstantValueInConstant {
                                                        ident,
                                                        suggestion: "let",
                                                        current: kind.as_str(),
                                                        type_span: None,
                                                    }),
                                        };
                                    self.report_error(span, resolution_error);
                                }
                                return Res::Err;
                            }
                            RibKind::ConstParamTy => {
                                if let Some(span) = finalize {
                                    self.report_error(span,
                                        ParamInTyOfConstParam { name: rib_ident.name });
                                }
                                return Res::Err;
                            }
                            RibKind::InlineAsmSym => {
                                if let Some(span) = finalize {
                                    self.report_error(span, InvalidAsmSym);
                                }
                                return Res::Err;
                            }
                        }
                    }
                    if let Some((span, res_err)) = res_err {
                        self.report_error(span, res_err);
                        return Res::Err;
                    }
                }
                Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } |
                    Res::SelfTyAlias { .. } => {
                    for rib in ribs {
                        let (has_generic_params, def_kind) =
                            match rib.kind {
                                RibKind::Normal | RibKind::Block(..) |
                                    RibKind::FnOrCoroutine | RibKind::Module(..) |
                                    RibKind::MacroDefinition(..) | RibKind::InlineAsmSym |
                                    RibKind::AssocItem | RibKind::ForwardGenericParamBan(_) => {
                                    continue;
                                }
                                RibKind::ConstParamTy => {
                                    if !self.features.generic_const_parameter_types() {
                                        if let Some(span) = finalize {
                                            self.report_error(span,
                                                ResolutionError::ParamInTyOfConstParam {
                                                    name: rib_ident.name,
                                                });
                                        }
                                        return Res::Err;
                                    } else { continue; }
                                }
                                RibKind::ConstantItem(trivial, _) => {
                                    if let ConstantHasGenerics::No(cause) = trivial &&
                                            !#[allow(non_exhaustive_omitted_patterns)] match res {
                                                    Res::SelfTyAlias { .. } => true,
                                                    _ => false,
                                                } {
                                        if let Some(span) = finalize {
                                            let error =
                                                match cause {
                                                    NoConstantGenericsReason::IsEnumDiscriminant => {
                                                        ResolutionError::ParamInEnumDiscriminant {
                                                            name: rib_ident.name,
                                                            param_kind: ParamKindInEnumDiscriminant::Type,
                                                        }
                                                    }
                                                    NoConstantGenericsReason::NonTrivialConstArg => {
                                                        ResolutionError::ParamInNonTrivialAnonConst {
                                                            is_gca: self.features.generic_const_args(),
                                                            name: rib_ident.name,
                                                            param_kind: ParamKindInNonTrivialAnonConst::Type,
                                                        }
                                                    }
                                                };
                                            let _: ErrorGuaranteed = self.report_error(span, error);
                                        }
                                        return Res::Err;
                                    }
                                    continue;
                                }
                                RibKind::Item(has_generic_params, def_kind) => {
                                    (has_generic_params, def_kind)
                                }
                            };
                        if let Some(span) = finalize {
                            let item =
                                if let Some(diag_metadata) = diag_metadata &&
                                        let Some(current_item) = diag_metadata.current_item {
                                    let label_span =
                                        current_item.kind.ident().map(|i|
                                                    i.span).unwrap_or(current_item.span);
                                    Some((label_span, current_item.span,
                                            current_item.kind.clone()))
                                } else { None };
                            self.report_error(span,
                                ResolutionError::GenericParamsFromOuterItem {
                                    outer_res: res,
                                    has_generic_params,
                                    def_kind,
                                    inner_item: item,
                                    current_self_ty: diag_metadata.and_then(|m|
                                                m.current_self_type.as_ref()).and_then(|ty|
                                            {
                                                self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
                                            }),
                                });
                        }
                        return Res::Err;
                    }
                }
                Res::Def(DefKind::ConstParam, _) => {
                    for rib in ribs {
                        let (has_generic_params, def_kind) =
                            match rib.kind {
                                RibKind::Normal | RibKind::Block(..) |
                                    RibKind::FnOrCoroutine | RibKind::Module(..) |
                                    RibKind::MacroDefinition(..) | RibKind::InlineAsmSym |
                                    RibKind::AssocItem | RibKind::ForwardGenericParamBan(_) =>
                                    continue,
                                RibKind::ConstParamTy => {
                                    if !self.features.generic_const_parameter_types() {
                                        if let Some(span) = finalize {
                                            self.report_error(span,
                                                ResolutionError::ParamInTyOfConstParam {
                                                    name: rib_ident.name,
                                                });
                                        }
                                        return Res::Err;
                                    } else { continue; }
                                }
                                RibKind::ConstantItem(trivial, _) => {
                                    if let ConstantHasGenerics::No(cause) = trivial {
                                        if let Some(span) = finalize {
                                            let error =
                                                match cause {
                                                    NoConstantGenericsReason::IsEnumDiscriminant => {
                                                        ResolutionError::ParamInEnumDiscriminant {
                                                            name: rib_ident.name,
                                                            param_kind: ParamKindInEnumDiscriminant::Const,
                                                        }
                                                    }
                                                    NoConstantGenericsReason::NonTrivialConstArg => {
                                                        ResolutionError::ParamInNonTrivialAnonConst {
                                                            is_gca: self.features.generic_const_args(),
                                                            name: rib_ident.name,
                                                            param_kind: ParamKindInNonTrivialAnonConst::Const {
                                                                name: rib_ident.name,
                                                            },
                                                        }
                                                    }
                                                };
                                            self.report_error(span, error);
                                        }
                                        return Res::Err;
                                    }
                                    continue;
                                }
                                RibKind::Item(has_generic_params, def_kind) => {
                                    (has_generic_params, def_kind)
                                }
                            };
                        if let Some(span) = finalize {
                            let item =
                                if let Some(diag_metadata) = diag_metadata &&
                                        let Some(current_item) = diag_metadata.current_item {
                                    let label_span =
                                        current_item.kind.ident().map(|i|
                                                    i.span).unwrap_or(current_item.span);
                                    Some((label_span, current_item.span,
                                            current_item.kind.clone()))
                                } else { None };
                            self.report_error(span,
                                ResolutionError::GenericParamsFromOuterItem {
                                    outer_res: res,
                                    has_generic_params,
                                    def_kind,
                                    inner_item: item,
                                    current_self_ty: diag_metadata.and_then(|m|
                                                m.current_self_type.as_ref()).and_then(|ty|
                                            {
                                                self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
                                            }),
                                });
                        }
                        return Res::Err;
                    }
                }
                _ => {}
            }
            res
        }
    }
}#[instrument(level = "debug", skip(self, all_ribs))]
1459    fn validate_res_from_ribs(
1460        &mut self,
1461        rib_index: usize,
1462        rib_ident: Ident,
1463        res: Res,
1464        finalize: Option<Span>,
1465        original_rib_ident_def: Ident,
1466        all_ribs: &[Rib<'ra>],
1467        diag_metadata: Option<&DiagMetadata<'_>>,
1468    ) -> Res {
1469        debug!("validate_res_from_ribs({:?})", res);
1470        let ribs = &all_ribs[rib_index + 1..];
1471
1472        // An invalid forward use of a generic parameter from a previous default
1473        // or in a const param ty.
1474        if let RibKind::ForwardGenericParamBan(reason) = all_ribs[rib_index].kind {
1475            if let Some(span) = finalize {
1476                let res_error = if rib_ident.name == kw::SelfUpper {
1477                    ResolutionError::ForwardDeclaredSelf(reason)
1478                } else {
1479                    ResolutionError::ForwardDeclaredGenericParam(rib_ident.name, reason)
1480                };
1481                self.report_error(span, res_error);
1482            }
1483            assert_eq!(res, Res::Err);
1484            return Res::Err;
1485        }
1486
1487        match res {
1488            Res::Local(_) => {
1489                use ResolutionError::*;
1490                let mut res_err = None;
1491
1492                for rib in ribs {
1493                    match rib.kind {
1494                        RibKind::Normal
1495                        | RibKind::Block(..)
1496                        | RibKind::FnOrCoroutine
1497                        | RibKind::Module(..)
1498                        | RibKind::MacroDefinition(..)
1499                        | RibKind::ForwardGenericParamBan(_) => {
1500                            // Nothing to do. Continue.
1501                        }
1502                        RibKind::Item(..) | RibKind::AssocItem => {
1503                            // This was an attempt to access an upvar inside a
1504                            // named function item. This is not allowed, so we
1505                            // report an error.
1506                            if let Some(span) = finalize {
1507                                // We don't immediately trigger a resolve error, because
1508                                // we want certain other resolution errors (namely those
1509                                // emitted for `ConstantItemRibKind` below) to take
1510                                // precedence.
1511                                res_err = Some((span, CannotCaptureDynamicEnvironmentInFnItem));
1512                            }
1513                        }
1514                        RibKind::ConstantItem(_, item) => {
1515                            // Still doesn't deal with upvars
1516                            if let Some(span) = finalize {
1517                                let (span, resolution_error) = match item {
1518                                    None if rib_ident.name == kw::SelfLower => {
1519                                        (span, LowercaseSelf)
1520                                    }
1521                                    None => {
1522                                        // If we have a `let name = expr;`, we have the span for
1523                                        // `name` and use that to see if it is followed by a type
1524                                        // specifier. If not, then we know we need to suggest
1525                                        // `const name: Ty = expr;`. This is a heuristic, it will
1526                                        // break down in the presence of macros.
1527                                        let sm = self.tcx.sess.source_map();
1528                                        let type_span = match sm
1529                                            .span_followed_by(original_rib_ident_def.span, ":")
1530                                        {
1531                                            None => {
1532                                                Some(original_rib_ident_def.span.shrink_to_hi())
1533                                            }
1534                                            Some(_) => None,
1535                                        };
1536                                        (
1537                                            rib_ident.span,
1538                                            AttemptToUseNonConstantValueInConstant {
1539                                                ident: original_rib_ident_def,
1540                                                suggestion: "const",
1541                                                current: "let",
1542                                                type_span,
1543                                            },
1544                                        )
1545                                    }
1546                                    Some((ident, kind)) => (
1547                                        span,
1548                                        AttemptToUseNonConstantValueInConstant {
1549                                            ident,
1550                                            suggestion: "let",
1551                                            current: kind.as_str(),
1552                                            type_span: None,
1553                                        },
1554                                    ),
1555                                };
1556                                self.report_error(span, resolution_error);
1557                            }
1558                            return Res::Err;
1559                        }
1560                        RibKind::ConstParamTy => {
1561                            if let Some(span) = finalize {
1562                                self.report_error(
1563                                    span,
1564                                    ParamInTyOfConstParam { name: rib_ident.name },
1565                                );
1566                            }
1567                            return Res::Err;
1568                        }
1569                        RibKind::InlineAsmSym => {
1570                            if let Some(span) = finalize {
1571                                self.report_error(span, InvalidAsmSym);
1572                            }
1573                            return Res::Err;
1574                        }
1575                    }
1576                }
1577                if let Some((span, res_err)) = res_err {
1578                    self.report_error(span, res_err);
1579                    return Res::Err;
1580                }
1581            }
1582            Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {
1583                for rib in ribs {
1584                    let (has_generic_params, def_kind) = match rib.kind {
1585                        RibKind::Normal
1586                        | RibKind::Block(..)
1587                        | RibKind::FnOrCoroutine
1588                        | RibKind::Module(..)
1589                        | RibKind::MacroDefinition(..)
1590                        | RibKind::InlineAsmSym
1591                        | RibKind::AssocItem
1592                        | RibKind::ForwardGenericParamBan(_) => {
1593                            // Nothing to do. Continue.
1594                            continue;
1595                        }
1596
1597                        RibKind::ConstParamTy => {
1598                            if !self.features.generic_const_parameter_types() {
1599                                if let Some(span) = finalize {
1600                                    self.report_error(
1601                                        span,
1602                                        ResolutionError::ParamInTyOfConstParam {
1603                                            name: rib_ident.name,
1604                                        },
1605                                    );
1606                                }
1607                                return Res::Err;
1608                            } else {
1609                                continue;
1610                            }
1611                        }
1612
1613                        RibKind::ConstantItem(trivial, _) => {
1614                            if let ConstantHasGenerics::No(cause) = trivial
1615                                && !matches!(res, Res::SelfTyAlias { .. })
1616                            {
1617                                if let Some(span) = finalize {
1618                                    let error = match cause {
1619                                        NoConstantGenericsReason::IsEnumDiscriminant => {
1620                                            ResolutionError::ParamInEnumDiscriminant {
1621                                                name: rib_ident.name,
1622                                                param_kind: ParamKindInEnumDiscriminant::Type,
1623                                            }
1624                                        }
1625                                        NoConstantGenericsReason::NonTrivialConstArg => {
1626                                            ResolutionError::ParamInNonTrivialAnonConst {
1627                                                is_gca: self.features.generic_const_args(),
1628                                                name: rib_ident.name,
1629                                                param_kind: ParamKindInNonTrivialAnonConst::Type,
1630                                            }
1631                                        }
1632                                    };
1633                                    let _: ErrorGuaranteed = self.report_error(span, error);
1634                                }
1635
1636                                return Res::Err;
1637                            }
1638
1639                            continue;
1640                        }
1641
1642                        // This was an attempt to use a type parameter outside its scope.
1643                        RibKind::Item(has_generic_params, def_kind) => {
1644                            (has_generic_params, def_kind)
1645                        }
1646                    };
1647
1648                    if let Some(span) = finalize {
1649                        let item = if let Some(diag_metadata) = diag_metadata
1650                            && let Some(current_item) = diag_metadata.current_item
1651                        {
1652                            let label_span = current_item
1653                                .kind
1654                                .ident()
1655                                .map(|i| i.span)
1656                                .unwrap_or(current_item.span);
1657                            Some((label_span, current_item.span, current_item.kind.clone()))
1658                        } else {
1659                            None
1660                        };
1661                        self.report_error(
1662                            span,
1663                            ResolutionError::GenericParamsFromOuterItem {
1664                                outer_res: res,
1665                                has_generic_params,
1666                                def_kind,
1667                                inner_item: item,
1668                                current_self_ty: diag_metadata
1669                                    .and_then(|m| m.current_self_type.as_ref())
1670                                    .and_then(|ty| {
1671                                        self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1672                                    }),
1673                            },
1674                        );
1675                    }
1676                    return Res::Err;
1677                }
1678            }
1679            Res::Def(DefKind::ConstParam, _) => {
1680                for rib in ribs {
1681                    let (has_generic_params, def_kind) = match rib.kind {
1682                        RibKind::Normal
1683                        | RibKind::Block(..)
1684                        | RibKind::FnOrCoroutine
1685                        | RibKind::Module(..)
1686                        | RibKind::MacroDefinition(..)
1687                        | RibKind::InlineAsmSym
1688                        | RibKind::AssocItem
1689                        | RibKind::ForwardGenericParamBan(_) => continue,
1690
1691                        RibKind::ConstParamTy => {
1692                            if !self.features.generic_const_parameter_types() {
1693                                if let Some(span) = finalize {
1694                                    self.report_error(
1695                                        span,
1696                                        ResolutionError::ParamInTyOfConstParam {
1697                                            name: rib_ident.name,
1698                                        },
1699                                    );
1700                                }
1701                                return Res::Err;
1702                            } else {
1703                                continue;
1704                            }
1705                        }
1706
1707                        RibKind::ConstantItem(trivial, _) => {
1708                            if let ConstantHasGenerics::No(cause) = trivial {
1709                                if let Some(span) = finalize {
1710                                    let error = match cause {
1711                                        NoConstantGenericsReason::IsEnumDiscriminant => {
1712                                            ResolutionError::ParamInEnumDiscriminant {
1713                                                name: rib_ident.name,
1714                                                param_kind: ParamKindInEnumDiscriminant::Const,
1715                                            }
1716                                        }
1717                                        NoConstantGenericsReason::NonTrivialConstArg => {
1718                                            ResolutionError::ParamInNonTrivialAnonConst {
1719                                                is_gca: self.features.generic_const_args(),
1720                                                name: rib_ident.name,
1721                                                param_kind: ParamKindInNonTrivialAnonConst::Const {
1722                                                    name: rib_ident.name,
1723                                                },
1724                                            }
1725                                        }
1726                                    };
1727                                    self.report_error(span, error);
1728                                }
1729
1730                                return Res::Err;
1731                            }
1732
1733                            continue;
1734                        }
1735
1736                        RibKind::Item(has_generic_params, def_kind) => {
1737                            (has_generic_params, def_kind)
1738                        }
1739                    };
1740
1741                    // This was an attempt to use a const parameter outside its scope.
1742                    if let Some(span) = finalize {
1743                        let item = if let Some(diag_metadata) = diag_metadata
1744                            && let Some(current_item) = diag_metadata.current_item
1745                        {
1746                            let label_span = current_item
1747                                .kind
1748                                .ident()
1749                                .map(|i| i.span)
1750                                .unwrap_or(current_item.span);
1751                            Some((label_span, current_item.span, current_item.kind.clone()))
1752                        } else {
1753                            None
1754                        };
1755                        self.report_error(
1756                            span,
1757                            ResolutionError::GenericParamsFromOuterItem {
1758                                outer_res: res,
1759                                has_generic_params,
1760                                def_kind,
1761                                inner_item: item,
1762                                current_self_ty: diag_metadata
1763                                    .and_then(|m| m.current_self_type.as_ref())
1764                                    .and_then(|ty| {
1765                                        self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1766                                    }),
1767                            },
1768                        );
1769                    }
1770                    return Res::Err;
1771                }
1772            }
1773            _ => {}
1774        }
1775
1776        res
1777    }
1778
1779    #[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(1779u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("opt_ns")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("opt_ns");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("parent_scope")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("parent_scope");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ignore_import")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ignore_import");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&opt_ns)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: PathResult<'ra> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.resolve_path_with_ribs(path, opt_ns, parent_scope, None,
                None, None, None, ignore_import, None)
        }
    }
}#[instrument(level = "debug", skip(self))]
1780    pub(crate) fn maybe_resolve_path<'r>(
1781        self: CmResolver<'r, 'ra, 'tcx>,
1782        path: &[Segment],
1783        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1784        parent_scope: &ParentScope<'ra>,
1785        ignore_import: Option<Import<'ra>>,
1786    ) -> PathResult<'ra> {
1787        self.resolve_path_with_ribs(
1788            path,
1789            opt_ns,
1790            parent_scope,
1791            None,
1792            None,
1793            None,
1794            None,
1795            ignore_import,
1796            None,
1797        )
1798    }
1799    #[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(1799u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("opt_ns")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("opt_ns");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("parent_scope")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("parent_scope");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("finalize")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("finalize");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ignore_decl")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ignore_decl");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ignore_import")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ignore_import");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&opt_ns)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_decl)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: PathResult<'ra> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.resolve_path_with_ribs(path, opt_ns, parent_scope, None,
                finalize, None, ignore_decl, ignore_import, None)
        }
    }
}#[instrument(level = "debug", skip(self))]
1800    pub(crate) fn resolve_path<'r>(
1801        self: CmResolver<'r, 'ra, 'tcx>,
1802        path: &[Segment],
1803        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1804        parent_scope: &ParentScope<'ra>,
1805        finalize: Option<Finalize>,
1806        ignore_decl: Option<Decl<'ra>>,
1807        ignore_import: Option<Import<'ra>>,
1808    ) -> PathResult<'ra> {
1809        self.resolve_path_with_ribs(
1810            path,
1811            opt_ns,
1812            parent_scope,
1813            None,
1814            finalize,
1815            None,
1816            ignore_decl,
1817            ignore_import,
1818            None,
1819        )
1820    }
1821
1822    pub(crate) fn resolve_path_with_ribs<'r>(
1823        mut self: CmResolver<'r, 'ra, 'tcx>,
1824        path: &[Segment],
1825        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1826        parent_scope: &ParentScope<'ra>,
1827        source: Option<PathSource<'_, '_, '_>>,
1828        finalize: Option<Finalize>,
1829        ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
1830        ignore_decl: Option<Decl<'ra>>,
1831        ignore_import: Option<Import<'ra>>,
1832        diag_metadata: Option<&DiagMetadata<'_>>,
1833    ) -> PathResult<'ra> {
1834        let mut module = None;
1835        let mut module_had_parse_errors = !self.mods_with_parse_errors.is_empty()
1836            && self
1837                .mods_with_parse_errors
1838                .contains(&parent_scope.module.nearest_parent_mod().to_def_id());
1839        let mut allow_super = true;
1840        let mut second_binding = None;
1841
1842        // We'll provide more context to the privacy errors later, up to `len`.
1843        let privacy_errors_len = self.privacy_errors.len();
1844        fn record_segment_res<'r, 'ra, 'tcx>(
1845            mut this: CmResolver<'r, 'ra, 'tcx>,
1846            finalize: Option<Finalize>,
1847            res: Res,
1848            id: Option<NodeId>,
1849        ) {
1850            if finalize.is_some()
1851                && let Some(id) = id
1852                && !this.partial_res_map.contains_key(&id)
1853            {
1854                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");
1855                this.get_mut().record_partial_res(id, PartialRes::new(res));
1856            }
1857        }
1858
1859        for (segment_idx, &Segment { ident, id, .. }) in path.iter().enumerate() {
1860            {
    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:1860",
                        "rustc_resolve::ident", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                        ::tracing_core::__macro_support::Option::Some(1860u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_path ident {0} {1:?} {2:?}",
                                                    segment_idx, ident, id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolve_path ident {} {:?} {:?}", segment_idx, ident, id);
1861
1862            let is_last = segment_idx + 1 == path.len();
1863            let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1864            let name = ident.name;
1865
1866            allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super);
1867
1868            if ns == TypeNS {
1869                if allow_super && name == kw::Super {
1870                    let parent = if segment_idx == 0 {
1871                        self.resolve_super_in_module(ident, None, parent_scope)
1872                    } else if let Some(ModuleOrUniformRoot::Module(module)) = module {
1873                        self.resolve_super_in_module(ident, Some(module), parent_scope)
1874                    } else {
1875                        None
1876                    };
1877                    if let Some(parent) = parent {
1878                        module = Some(ModuleOrUniformRoot::Module(parent));
1879                        continue;
1880                    }
1881                    let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1882                    let current_module = self.resolve_self(&mut ctxt, parent_scope.module);
1883                    let current_module_path = module_to_string(current_module)
1884                        .map_or_else(|| "crate".to_string(), |path| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("crate::{0}", path))
    })format!("crate::{path}"));
1885                    return PathResult::failed(
1886                        ident,
1887                        false,
1888                        finalize.is_some(),
1889                        module_had_parse_errors,
1890                        module,
1891                        || {
1892                            (
1893                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("too many leading `super` keywords within `{0}`",
                current_module_path))
    })format!(
1894                                    "too many leading `super` keywords within `{current_module_path}`"
1895                                ),
1896                                "this `super` would go above the crate root".to_string(),
1897                                None,
1898                                None,
1899                            )
1900                        },
1901                    );
1902                }
1903                if segment_idx == 0 {
1904                    if name == kw::SelfLower {
1905                        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1906                        let self_mod = self.resolve_self(&mut ctxt, parent_scope.module);
1907                        if let Some(res) = self_mod.res() {
1908                            record_segment_res(self.reborrow(), finalize, res, id);
1909                        }
1910                        module = Some(ModuleOrUniformRoot::Module(self_mod));
1911                        continue;
1912                    }
1913                    if name == kw::PathRoot && ident.span.at_least_rust_2018() {
1914                        module = Some(ModuleOrUniformRoot::ExternPrelude);
1915                        continue;
1916                    }
1917                    if name == kw::PathRoot
1918                        && ident.span.is_rust_2015()
1919                        && self.tcx.sess.at_least_rust_2018()
1920                    {
1921                        // `::a::b` from 2015 macro on 2018 global edition
1922                        let crate_root = self.resolve_crate_root(ident);
1923                        module = Some(ModuleOrUniformRoot::ModuleAndExternPrelude(crate_root));
1924                        continue;
1925                    }
1926                    if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate {
1927                        // `::a::b`, `crate::a::b` or `$crate::a::b`
1928                        let crate_root = self.resolve_crate_root(ident);
1929                        if let Some(res) = crate_root.res() {
1930                            record_segment_res(self.reborrow(), finalize, res, id);
1931                        }
1932                        module = Some(ModuleOrUniformRoot::Module(crate_root));
1933                        continue;
1934                    }
1935                }
1936            }
1937
1938            let allow_trailing_self = is_last && name == kw::SelfLower;
1939
1940            // Report special messages for path segment keywords in wrong positions.
1941            if ident.is_path_segment_keyword() && segment_idx != 0 && !allow_trailing_self {
1942                return PathResult::failed(
1943                    ident,
1944                    false,
1945                    finalize.is_some(),
1946                    module_had_parse_errors,
1947                    module,
1948                    || {
1949                        let name_str = if name == kw::PathRoot {
1950                            "the crate root".to_string()
1951                        } else {
1952                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", name))
    })format!("`{name}`")
1953                        };
1954                        let (message, label) = if segment_idx == 1
1955                            && path[0].ident.name == kw::PathRoot
1956                        {
1957                            (
1958                                ::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}"),
1959                                "cannot start with this".to_string(),
1960                            )
1961                        } else if name == kw::SelfLower {
1962                            (
1963                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`self` in paths can only be used in start position or last position"))
    })format!(
1964                                    "`self` in paths can only be used in start position or last position"
1965                                ),
1966                                "can only be used in path start position or last position"
1967                                    .to_string(),
1968                            )
1969                        } else {
1970                            (
1971                                ::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"),
1972                                "can only be used in path start position".to_string(),
1973                            )
1974                        };
1975                        (message, label, None, None)
1976                    },
1977                );
1978            }
1979
1980            let binding = if let Some(module) = module {
1981                self.reborrow().resolve_ident_in_module(
1982                    module,
1983                    ident,
1984                    ns,
1985                    parent_scope,
1986                    finalize,
1987                    ignore_decl,
1988                    ignore_import,
1989                )
1990            } else if let Some(ribs) = ribs
1991                && let Some(TypeNS | ValueNS) = opt_ns
1992            {
1993                if !ignore_import.is_none() {
    ::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
1994                match self.get_mut().resolve_ident_in_lexical_scope(
1995                    ident,
1996                    ns,
1997                    parent_scope,
1998                    finalize,
1999                    &ribs[ns],
2000                    ignore_decl,
2001                    diag_metadata,
2002                ) {
2003                    // we found a locally-imported or available item/module
2004                    Some(LateDecl::Decl(binding)) => Ok(binding),
2005                    // we found a local variable or type param
2006                    Some(LateDecl::RibDef(res)) => {
2007                        record_segment_res(self.reborrow(), finalize, res, id);
2008                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
2009                            res,
2010                            path.len() - 1,
2011                        ));
2012                    }
2013                    _ => Err(Determinacy::determined(finalize.is_some())),
2014                }
2015            } else {
2016                self.reborrow().resolve_ident_in_scope_set(
2017                    ident,
2018                    ScopeSet::All(ns),
2019                    parent_scope,
2020                    finalize,
2021                    ignore_decl,
2022                    ignore_import,
2023                )
2024            };
2025
2026            match binding {
2027                Ok(binding) => {
2028                    if segment_idx == 1 {
2029                        second_binding = Some(binding);
2030                    }
2031                    let res = binding.res();
2032
2033                    // Mark every privacy error in this path with the res to the last element. This allows us
2034                    // to detect the item the user cares about and either find an alternative import, or tell
2035                    // the user it is not accessible.
2036                    if finalize.is_some() {
2037                        for error in &mut self.get_mut().privacy_errors[privacy_errors_len..] {
2038                            error.outermost_res = Some((res, ident));
2039                            error.source = match source {
2040                                Some(PathSource::Struct(Some(expr)))
2041                                | Some(PathSource::Expr(Some(expr))) => Some(expr.clone()),
2042                                _ => None,
2043                            };
2044                        }
2045                    }
2046
2047                    let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
2048                    if let Res::OpenMod(sym) = binding.res() {
2049                        module = Some(ModuleOrUniformRoot::OpenModule(sym));
2050                        record_segment_res(self.reborrow(), finalize, res, id);
2051                    } else if let Some(def_id) = binding.res().module_like_def_id() {
2052                        if self.mods_with_parse_errors.contains(&def_id) {
2053                            module_had_parse_errors = true;
2054                        }
2055                        module = Some(ModuleOrUniformRoot::Module(self.expect_module(def_id)));
2056                        record_segment_res(self.reborrow(), finalize, res, id);
2057                    } else if res == Res::ToolMod && !is_last && opt_ns.is_some() {
2058                        if binding.is_import() {
2059                            self.dcx().emit_err(diagnostics::ToolModuleImported {
2060                                span: ident.span,
2061                                import: binding.span,
2062                            });
2063                        }
2064                        let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
2065                        return PathResult::NonModule(PartialRes::new(res));
2066                    } else if res == Res::Err {
2067                        return PathResult::NonModule(PartialRes::new(Res::Err));
2068                    } else if opt_ns.is_some() && (is_last || maybe_assoc) {
2069                        if let Some(finalize) = finalize {
2070                            self.get_mut().lint_if_path_starts_with_module(
2071                                finalize,
2072                                path,
2073                                second_binding,
2074                            );
2075                        }
2076                        record_segment_res(self.reborrow(), finalize, res, id);
2077                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
2078                            res,
2079                            path.len() - segment_idx - 1,
2080                        ));
2081                    } else {
2082                        return PathResult::failed(
2083                            ident,
2084                            is_last,
2085                            finalize.is_some(),
2086                            module_had_parse_errors,
2087                            module,
2088                            || {
2089                                let import_inherent_item_error_flag =
2090                                    self.features.import_trait_associated_functions()
2091                                        && #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union |
        DefKind::ForeignTy, _) => true,
    _ => false,
}matches!(
2092                                            res,
2093                                            Res::Def(
2094                                                DefKind::Struct
2095                                                    | DefKind::Enum
2096                                                    | DefKind::Union
2097                                                    | DefKind::ForeignTy,
2098                                                _
2099                                            )
2100                                        );
2101                                // Show a different error message for items that can have associated items.
2102                                let label = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{3}` is {0} {1}, not a module{2}",
                res.article(), res.descr(),
                if import_inherent_item_error_flag {
                    " or a trait"
                } else { "" }, ident))
    })format!(
2103                                    "`{ident}` is {} {}, not a module{}",
2104                                    res.article(),
2105                                    res.descr(),
2106                                    if import_inherent_item_error_flag {
2107                                        " or a trait"
2108                                    } else {
2109                                        ""
2110                                    }
2111                                );
2112                                let scope = match &path[..segment_idx] {
2113                                    [.., prev] => {
2114                                        if prev.ident.name == kw::PathRoot {
2115                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the crate root"))
    })format!("the crate root")
2116                                        } else {
2117                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", prev.ident))
    })format!("`{}`", prev.ident)
2118                                        }
2119                                    }
2120                                    _ => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this scope"))
    })format!("this scope"),
2121                                };
2122                                // FIXME: reword, as the reason we expected a module is because of
2123                                // the following path segment.
2124                                let message = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot find module `{0}` in {1}",
                ident, scope))
    })format!("cannot find module `{ident}` in {scope}");
2125                                let note = if import_inherent_item_error_flag {
2126                                    Some(
2127                                        "cannot import inherent associated items, only trait associated items".to_string(),
2128                                    )
2129                                } else {
2130                                    None
2131                                };
2132                                (message, label, None, note)
2133                            },
2134                        );
2135                    }
2136                }
2137                Err(Undetermined) if finalize.is_none() => return PathResult::Indeterminate,
2138                Err(Determined | Undetermined) => {
2139                    if let Some(ModuleOrUniformRoot::Module(module)) = module
2140                        && opt_ns.is_some()
2141                        && !module.is_normal()
2142                    {
2143                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
2144                            module.res().unwrap(),
2145                            path.len() - segment_idx,
2146                        ));
2147                    }
2148
2149                    let mut this = self.reborrow();
2150                    return PathResult::failed(
2151                        ident,
2152                        is_last,
2153                        finalize.is_some(),
2154                        module_had_parse_errors,
2155                        module,
2156                        || {
2157                            let (message, label, suggestion) =
2158                                this.get_mut().report_path_resolution_error(
2159                                    path,
2160                                    opt_ns,
2161                                    parent_scope,
2162                                    ribs,
2163                                    ignore_decl,
2164                                    ignore_import,
2165                                    module,
2166                                    segment_idx,
2167                                    ident,
2168                                    diag_metadata,
2169                                );
2170                            (message, label, suggestion, None)
2171                        },
2172                    );
2173                }
2174            }
2175        }
2176
2177        if let Some(finalize) = finalize {
2178            self.get_mut().lint_if_path_starts_with_module(finalize, path, second_binding);
2179        }
2180
2181        PathResult::Module(match module {
2182            Some(module) => module,
2183            None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
2184            _ => ::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),
2185        })
2186    }
2187}