Skip to main content

rustc_resolve/
ident.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<Decl<'ra>, Determinacy> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.resolve_ident_in_module(module, ident, ns, parent_scope,
                None, None, ignore_import)
        }
    }
}#[instrument(level = "debug", skip(self))]
915    pub(crate) fn maybe_resolve_ident_in_module<'r>(
916        self: CmResolver<'r, 'ra, 'tcx>,
917        module: ModuleOrUniformRoot<'ra>,
918        ident: Ident,
919        ns: Namespace,
920        parent_scope: &ParentScope<'ra>,
921        ignore_import: Option<Import<'ra>>,
922    ) -> Result<Decl<'ra>, Determinacy> {
923        self.resolve_ident_in_module(module, ident, ns, parent_scope, None, None, ignore_import)
924    }
925
926    #[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(926u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["module", "ident",
                                                    "ns", "parent_scope", "finalize", "ignore_decl",
                                                    "ignore_import"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&module)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ns)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_decl)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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