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    fn resolve_super_in_module(
927        &self,
928        ident: Ident,
929        module: Option<Module<'ra>>,
930        parent_scope: &ParentScope<'ra>,
931    ) -> Option<Module<'ra>> {
932        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
933        module
934            .unwrap_or_else(|| self.resolve_self(&mut ctxt, parent_scope.module))
935            .parent
936            .map(|parent| self.resolve_self(&mut ctxt, parent))
937    }
938
939    pub(crate) fn path_root_is_crate_root(&self, ident: Ident) -> bool {
940        ident.name == kw::PathRoot && ident.span.is_rust_2015() && self.tcx.sess.is_rust_2015()
941    }
942
943    #[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(943u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::ident"),
                                    ::tracing_core::field::FieldSet::new(&["module", "ident",
                                                    "ns", "parent_scope", "finalize", "ignore_decl",
                                                    "ignore_import"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&module)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ns)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_scope)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&finalize)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_decl)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ignore_import)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<Decl<'ra>, Determinacy> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            match module {
                ModuleOrUniformRoot::Module(module) => {
                    if ns == TypeNS && ident.name == kw::Super &&
                            let Some(module) =
                                self.resolve_super_in_module(ident, Some(module),
                                    parent_scope) {
                        return Ok(module.self_decl.unwrap());
                    }
                    let (ident_key, def) =
                        IdentKey::new_adjusted(ident, module.expansion);
                    let adjusted_parent_scope =
                        match def {
                            Some(def) =>
                                ParentScope {
                                    module: self.expn_def_scope(def),
                                    ..*parent_scope
                                },
                            None => *parent_scope,
                        };
                    self.resolve_ident_in_scope_set_inner(ident_key, ident.span,
                        ScopeSet::Module(ns, module), &adjusted_parent_scope,
                        finalize, ignore_decl, ignore_import)
                }
                ModuleOrUniformRoot::ModuleAndExternPrelude(module) =>
                    self.resolve_ident_in_scope_set(ident,
                        ScopeSet::ModuleAndExternPrelude(ns, module), parent_scope,
                        finalize, ignore_decl, ignore_import),
                ModuleOrUniformRoot::ExternPrelude => {
                    if ns != TypeNS {
                        Err(Determined)
                    } else {
                        self.resolve_ident_in_scope_set_inner(IdentKey::new_adjusted(ident,
                                    ExpnId::root()).0, ident.span, ScopeSet::ExternPrelude,
                            parent_scope, finalize, ignore_decl, ignore_import)
                    }
                }
                ModuleOrUniformRoot::CurrentScope => {
                    if ns == TypeNS {
                        if ident.name == kw::SelfLower {
                            let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
                            let module =
                                self.resolve_self(&mut ctxt, parent_scope.module);
                            return Ok(module.self_decl.unwrap());
                        }
                        if ident.name == kw::Super &&
                                let Some(module) =
                                    self.resolve_super_in_module(ident, None, parent_scope) {
                            return Ok(module.self_decl.unwrap());
                        }
                        if ident.name == kw::Crate || ident.name == kw::DollarCrate
                                || self.path_root_is_crate_root(ident) {
                            let module = self.resolve_crate_root(ident);
                            return Ok(module.self_decl.unwrap());
                        } else if ident.name == kw::Super ||
                                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))]
944    pub(crate) fn resolve_ident_in_module<'r>(
945        self: CmResolver<'r, 'ra, 'tcx>,
946        module: ModuleOrUniformRoot<'ra>,
947        ident: Ident,
948        ns: Namespace,
949        parent_scope: &ParentScope<'ra>,
950        finalize: Option<Finalize>,
951        ignore_decl: Option<Decl<'ra>>,
952        ignore_import: Option<Import<'ra>>,
953    ) -> Result<Decl<'ra>, Determinacy> {
954        match module {
955            ModuleOrUniformRoot::Module(module) => {
956                if ns == TypeNS
957                    && ident.name == kw::Super
958                    && let Some(module) =
959                        self.resolve_super_in_module(ident, Some(module), parent_scope)
960                {
961                    return Ok(module.self_decl.unwrap());
962                }
963
964                let (ident_key, def) = IdentKey::new_adjusted(ident, module.expansion);
965                let adjusted_parent_scope = match def {
966                    Some(def) => ParentScope { module: self.expn_def_scope(def), ..*parent_scope },
967                    None => *parent_scope,
968                };
969                self.resolve_ident_in_scope_set_inner(
970                    ident_key,
971                    ident.span,
972                    ScopeSet::Module(ns, module),
973                    &adjusted_parent_scope,
974                    finalize,
975                    ignore_decl,
976                    ignore_import,
977                )
978            }
979            ModuleOrUniformRoot::ModuleAndExternPrelude(module) => self.resolve_ident_in_scope_set(
980                ident,
981                ScopeSet::ModuleAndExternPrelude(ns, module),
982                parent_scope,
983                finalize,
984                ignore_decl,
985                ignore_import,
986            ),
987            ModuleOrUniformRoot::ExternPrelude => {
988                if ns != TypeNS {
989                    Err(Determined)
990                } else {
991                    self.resolve_ident_in_scope_set_inner(
992                        IdentKey::new_adjusted(ident, ExpnId::root()).0,
993                        ident.span,
994                        ScopeSet::ExternPrelude,
995                        parent_scope,
996                        finalize,
997                        ignore_decl,
998                        ignore_import,
999                    )
1000                }
1001            }
1002            ModuleOrUniformRoot::CurrentScope => {
1003                if ns == TypeNS {
1004                    if ident.name == kw::SelfLower {
1005                        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1006                        let module = self.resolve_self(&mut ctxt, parent_scope.module);
1007                        return Ok(module.self_decl.unwrap());
1008                    }
1009                    if ident.name == kw::Super
1010                        && let Some(module) =
1011                            self.resolve_super_in_module(ident, None, parent_scope)
1012                    {
1013                        return Ok(module.self_decl.unwrap());
1014                    }
1015                    if ident.name == kw::Crate
1016                        || ident.name == kw::DollarCrate
1017                        || self.path_root_is_crate_root(ident)
1018                    {
1019                        let module = self.resolve_crate_root(ident);
1020                        return Ok(module.self_decl.unwrap());
1021                    } else if ident.name == kw::Super || ident.name == kw::SelfLower {
1022                        // FIXME: Implement these with renaming requirements so that e.g.
1023                        // `use super;` doesn't work, but `use super as name;` does.
1024                        // Fall through here to get an error from `early_resolve_...`.
1025                    }
1026                }
1027
1028                self.resolve_ident_in_scope_set(
1029                    ident,
1030                    ScopeSet::All(ns),
1031                    parent_scope,
1032                    finalize,
1033                    ignore_decl,
1034                    ignore_import,
1035                )
1036            }
1037        }
1038    }
1039
1040    /// Attempts to resolve `ident` in namespace `ns` of non-glob bindings in `module`.
1041    fn resolve_ident_in_module_non_globs_unadjusted<'r>(
1042        mut self: CmResolver<'r, 'ra, 'tcx>,
1043        module: Module<'ra>,
1044        ident: IdentKey,
1045        orig_ident_span: Span,
1046        ns: Namespace,
1047        parent_scope: &ParentScope<'ra>,
1048        shadowing: Shadowing,
1049        finalize: Option<Finalize>,
1050        // This binding should be ignored during in-module resolution, so that we don't get
1051        // "self-confirming" import resolutions during import validation and checking.
1052        ignore_decl: Option<Decl<'ra>>,
1053        ignore_import: Option<Import<'ra>>,
1054    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1055        let key = BindingKey::new(ident, ns);
1056        // `try_borrow_mut` is required to ensure exclusive access, even if the resulting binding
1057        // doesn't need to be mutable. It will fail when there is a cycle of imports, and without
1058        // the exclusive access infinite recursion will crash the compiler with stack overflow.
1059        let resolution = &*self
1060            .resolution_or_default(module, key, orig_ident_span)
1061            .try_borrow_mut_unchecked()
1062            .map_err(|_| ControlFlow::Continue(Determined))?;
1063
1064        let binding = resolution.non_glob_decl.filter(|b| Some(*b) != ignore_decl);
1065
1066        if let Some(finalize) = finalize {
1067            return self.get_mut().finalize_module_binding(
1068                ident,
1069                orig_ident_span,
1070                binding,
1071                parent_scope,
1072                module,
1073                finalize,
1074                shadowing,
1075            );
1076        }
1077
1078        // Items and single imports are not shadowable, if we have one, then it's determined.
1079        if let Some(binding) = binding {
1080            let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1081            return if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) };
1082        }
1083
1084        // Check if one of single imports can still define the name, block if it can.
1085        if self.reborrow().single_import_can_define_name(
1086            &resolution,
1087            None,
1088            ns,
1089            ignore_import,
1090            ignore_decl,
1091            parent_scope,
1092        ) {
1093            return Err(ControlFlow::Break(Undetermined));
1094        }
1095
1096        // Check if one of unexpanded macros can still define the name.
1097        if !module.unexpanded_invocations.borrow().is_empty() {
1098            return Err(ControlFlow::Continue(Undetermined));
1099        }
1100
1101        // No resolution and no one else can define the name - determinate error.
1102        Err(ControlFlow::Continue(Determined))
1103    }
1104
1105    /// Attempts to resolve `ident` in namespace `ns` of glob bindings in `module`.
1106    fn resolve_ident_in_module_globs_unadjusted<'r>(
1107        mut self: CmResolver<'r, 'ra, 'tcx>,
1108        module: Module<'ra>,
1109        ident: IdentKey,
1110        orig_ident_span: Span,
1111        ns: Namespace,
1112        parent_scope: &ParentScope<'ra>,
1113        shadowing: Shadowing,
1114        finalize: Option<Finalize>,
1115        ignore_decl: Option<Decl<'ra>>,
1116        ignore_import: Option<Import<'ra>>,
1117    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1118        let key = BindingKey::new(ident, ns);
1119        // `try_borrow_mut` is required to ensure exclusive access, even if the resulting binding
1120        // doesn't need to be mutable. It will fail when there is a cycle of imports, and without
1121        // the exclusive access infinite recursion will crash the compiler with stack overflow.
1122        let resolution = &*self
1123            .resolution_or_default(module, key, orig_ident_span)
1124            .try_borrow_mut_unchecked()
1125            .map_err(|_| ControlFlow::Continue(Determined))?;
1126
1127        let binding = resolution.glob_decl.filter(|b| Some(*b) != ignore_decl);
1128
1129        if let Some(finalize) = finalize {
1130            return self.get_mut().finalize_module_binding(
1131                ident,
1132                orig_ident_span,
1133                binding,
1134                parent_scope,
1135                module,
1136                finalize,
1137                shadowing,
1138            );
1139        }
1140
1141        // Check if one of single imports can still define the name,
1142        // if it can then our result is not determined and can be invalidated.
1143        if self.reborrow().single_import_can_define_name(
1144            &resolution,
1145            binding,
1146            ns,
1147            ignore_import,
1148            ignore_decl,
1149            parent_scope,
1150        ) {
1151            return Err(ControlFlow::Break(Undetermined));
1152        }
1153
1154        // So we have a resolution that's from a glob import. This resolution is determined
1155        // if it cannot be shadowed by some new item/import expanded from a macro.
1156        // This happens either if there are no unexpanded macros, or expanded names cannot
1157        // shadow globs (that happens in macro namespace or with restricted shadowing).
1158        //
1159        // Additionally, any macro in any module can plant names in the root module if it creates
1160        // `macro_export` macros, so the root module effectively has unresolved invocations if any
1161        // module has unresolved invocations.
1162        // However, it causes resolution/expansion to stuck too often (#53144), so, to make
1163        // progress, we have to ignore those potential unresolved invocations from other modules
1164        // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
1165        // shadowing is enabled, see `macro_expanded_macro_export_errors`).
1166        if let Some(binding) = binding {
1167            return if binding.determined() || ns == MacroNS || shadowing == Shadowing::Restricted {
1168                let accessible = self.is_accessible_from(binding.vis(), parent_scope.module);
1169                if accessible { Ok(binding) } else { Err(ControlFlow::Break(Determined)) }
1170            } else {
1171                Err(ControlFlow::Break(Undetermined))
1172            };
1173        }
1174
1175        // Now we are in situation when new item/import can appear only from a glob or a macro
1176        // expansion. With restricted shadowing names from globs and macro expansions cannot
1177        // shadow names from outer scopes, so we can freely fallback from module search to search
1178        // in outer scopes. For `resolve_ident_in_scope_set` to continue search in outer
1179        // scopes we return `Undetermined` with `ControlFlow::Continue`.
1180        // Check if one of unexpanded macros can still define the name,
1181        // if it can then our "no resolution" result is not determined and can be invalidated.
1182        if !module.unexpanded_invocations.borrow().is_empty() {
1183            return Err(ControlFlow::Continue(Undetermined));
1184        }
1185
1186        // Check if one of glob imports can still define the name,
1187        // if it can then our "no resolution" result is not determined and can be invalidated.
1188        for glob_import in module.globs.borrow().iter() {
1189            if ignore_import == Some(*glob_import) {
1190                continue;
1191            }
1192            if !self.is_accessible_from(glob_import.vis, parent_scope.module) {
1193                continue;
1194            }
1195            let module = match glob_import.imported_module.get() {
1196                Some(ModuleOrUniformRoot::Module(module)) => module,
1197                Some(_) => continue,
1198                None => return Err(ControlFlow::Continue(Undetermined)),
1199            };
1200            let tmp_parent_scope;
1201            let (mut adjusted_parent_scope, mut adjusted_ident) = (parent_scope, ident);
1202            match adjusted_ident
1203                .ctxt
1204                .update_unchecked(|ctxt| ctxt.glob_adjust(module.expansion, glob_import.span))
1205            {
1206                Some(Some(def)) => {
1207                    tmp_parent_scope =
1208                        ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
1209                    adjusted_parent_scope = &tmp_parent_scope;
1210                }
1211                Some(None) => {}
1212                None => continue,
1213            };
1214            let result = self.reborrow().resolve_ident_in_scope_set_inner(
1215                adjusted_ident,
1216                orig_ident_span,
1217                ScopeSet::Module(ns, module),
1218                adjusted_parent_scope,
1219                None,
1220                ignore_decl,
1221                ignore_import,
1222            );
1223
1224            match result {
1225                Err(Determined) => continue,
1226                Ok(binding)
1227                    if !self.is_accessible_from(binding.vis(), glob_import.parent_scope.module) =>
1228                {
1229                    continue;
1230                }
1231                Ok(_) | Err(Undetermined) => return Err(ControlFlow::Continue(Undetermined)),
1232            }
1233        }
1234
1235        // No resolution and no one else can define the name - determinate error.
1236        Err(ControlFlow::Continue(Determined))
1237    }
1238
1239    fn finalize_module_binding(
1240        &mut self,
1241        ident: IdentKey,
1242        orig_ident_span: Span,
1243        binding: Option<Decl<'ra>>,
1244        parent_scope: &ParentScope<'ra>,
1245        module: Module<'ra>,
1246        finalize: Finalize,
1247        shadowing: Shadowing,
1248    ) -> Result<Decl<'ra>, ControlFlow<Determinacy, Determinacy>> {
1249        let Finalize { path_span, report_private, used, root_span, .. } = finalize;
1250
1251        let Some(binding) = binding else {
1252            return Err(ControlFlow::Continue(Determined));
1253        };
1254
1255        let ident = ident.orig(orig_ident_span);
1256        if !self.is_accessible_from(binding.vis(), parent_scope.module) {
1257            if report_private {
1258                self.privacy_errors.push(PrivacyError {
1259                    ident,
1260                    decl: binding,
1261                    dedup_span: path_span,
1262                    outermost_res: None,
1263                    source: None,
1264                    parent_scope: *parent_scope,
1265                    single_nested: path_span != root_span,
1266                });
1267            } else {
1268                return Err(ControlFlow::Break(Determined));
1269            }
1270        }
1271
1272        if shadowing == Shadowing::Unrestricted
1273            && binding.expansion != LocalExpnId::ROOT
1274            && let DeclKind::Import { import, .. } = binding.kind
1275            && #[allow(non_exhaustive_omitted_patterns)] match import.kind {
    ImportKind::MacroExport => true,
    _ => false,
}matches!(import.kind, ImportKind::MacroExport)
1276        {
1277            self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
1278        }
1279
1280        // If we encounter a re-export for a type with private fields, it will not be able to
1281        // be constructed through this re-export. We track that case here to expand later
1282        // privacy errors with appropriate information.
1283        if let Res::Def(_, def_id) = binding.res() {
1284            let struct_ctor = match def_id.as_local() {
1285                Some(def_id) => self.struct_constructors.get(&def_id).cloned(),
1286                None => {
1287                    let ctor = self.cstore().ctor_untracked(self.tcx(), def_id);
1288                    ctor.map(|(ctor_kind, ctor_def_id)| {
1289                        let ctor_res = Res::Def(
1290                            DefKind::Ctor(rustc_hir::def::CtorOf::Struct, ctor_kind),
1291                            ctor_def_id,
1292                        );
1293                        let ctor_vis = self.tcx.visibility(ctor_def_id);
1294                        let field_visibilities = self
1295                            .tcx
1296                            .associated_item_def_ids(def_id)
1297                            .iter()
1298                            .map(|&field_id| self.tcx.visibility(field_id))
1299                            .collect();
1300                        (ctor_res, ctor_vis, field_visibilities)
1301                    })
1302                }
1303            };
1304            if let Some((_, _, fields)) = struct_ctor
1305                && fields.iter().any(|vis| !self.is_accessible_from(*vis, module))
1306            {
1307                self.inaccessible_ctor_reexport.insert(path_span, binding.span);
1308            }
1309        }
1310
1311        self.record_use(ident, binding, used);
1312        return Ok(binding);
1313    }
1314
1315    // Checks if a single import can define the `Ident` corresponding to `binding`.
1316    // This is used to check whether we can definitively accept a glob as a resolution.
1317    fn single_import_can_define_name<'r>(
1318        mut self: CmResolver<'r, 'ra, 'tcx>,
1319        resolution: &NameResolution<'ra>,
1320        binding: Option<Decl<'ra>>,
1321        ns: Namespace,
1322        ignore_import: Option<Import<'ra>>,
1323        ignore_decl: Option<Decl<'ra>>,
1324        parent_scope: &ParentScope<'ra>,
1325    ) -> bool {
1326        for single_import in &resolution.single_imports {
1327            if let Some(decl) = resolution.non_glob_decl
1328                && let DeclKind::Import { import, .. } = decl.kind
1329                && import == *single_import
1330            {
1331                // Single import has already defined the name and we are aware of it,
1332                // no need to block the globs.
1333                continue;
1334            }
1335            if ignore_import == Some(*single_import) {
1336                continue;
1337            }
1338            if !self.is_accessible_from(single_import.vis, parent_scope.module) {
1339                continue;
1340            }
1341            if let Some(ignored) = ignore_decl
1342                && let DeclKind::Import { import, .. } = ignored.kind
1343                && import == *single_import
1344            {
1345                continue;
1346            }
1347
1348            let Some(module) = single_import.imported_module.get() else {
1349                return true;
1350            };
1351            let ImportKind::Single { source, target, decls, .. } = &single_import.kind else {
1352                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1353            };
1354            if source != target {
1355                if decls.iter().all(|d| d.get().decl().is_none()) {
1356                    return true;
1357                } else if decls[ns].get().decl().is_none() && binding.is_some() {
1358                    return true;
1359                }
1360            }
1361
1362            match self.reborrow().resolve_ident_in_module(
1363                module,
1364                *source,
1365                ns,
1366                &single_import.parent_scope,
1367                None,
1368                ignore_decl,
1369                ignore_import,
1370            ) {
1371                Err(Determined) => continue,
1372                Ok(binding)
1373                    if !self
1374                        .is_accessible_from(binding.vis(), single_import.parent_scope.module) =>
1375                {
1376                    continue;
1377                }
1378                Ok(_) | Err(Undetermined) => return true,
1379            }
1380        }
1381
1382        false
1383    }
1384
1385    /// Validate a local resolution (from ribs).
1386    #[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(1386u32),
                                    ::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:1397",
                                    "rustc_resolve::ident", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1397u32),
                                    ::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 {
                                                            is_ogca: self.tcx.features().opaque_generic_const_args(),
                                                            name: rib_ident.name,
                                                            param_kind: ParamKindInNonTrivialAnonConst::Type,
                                                        }
                                                    }
                                                };
                                            let _: ErrorGuaranteed = self.report_error(span, error);
                                        }
                                        return Res::Err;
                                    }
                                    continue;
                                }
                                RibKind::Item(has_generic_params, def_kind) => {
                                    (has_generic_params, def_kind)
                                }
                            };
                        if let Some(span) = finalize {
                            let item =
                                if let Some(diag_metadata) = diag_metadata &&
                                        let Some(current_item) = diag_metadata.current_item {
                                    let span =
                                        current_item.kind.ident().map(|i|
                                                    i.span).unwrap_or(current_item.span);
                                    Some((span, current_item.kind.clone()))
                                } else { None };
                            self.report_error(span,
                                ResolutionError::GenericParamsFromOuterItem {
                                    outer_res: res,
                                    has_generic_params,
                                    def_kind,
                                    inner_item: item,
                                    current_self_ty: diag_metadata.and_then(|m|
                                                m.current_self_type.as_ref()).and_then(|ty|
                                            {
                                                self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
                                            }),
                                });
                        }
                        return Res::Err;
                    }
                }
                Res::Def(DefKind::ConstParam, _) => {
                    for rib in ribs {
                        let (has_generic_params, def_kind) =
                            match rib.kind {
                                RibKind::Normal | RibKind::Block(..) |
                                    RibKind::FnOrCoroutine | RibKind::Module(..) |
                                    RibKind::MacroDefinition(..) | RibKind::InlineAsmSym |
                                    RibKind::AssocItem | RibKind::ForwardGenericParamBan(_) =>
                                    continue,
                                RibKind::ConstParamTy => {
                                    if !self.tcx.features().generic_const_parameter_types() {
                                        if let Some(span) = finalize {
                                            self.report_error(span,
                                                ResolutionError::ParamInTyOfConstParam {
                                                    name: rib_ident.name,
                                                });
                                        }
                                        return Res::Err;
                                    } else { continue; }
                                }
                                RibKind::ConstantItem(trivial, _) => {
                                    if let ConstantHasGenerics::No(cause) = trivial {
                                        if let Some(span) = finalize {
                                            let error =
                                                match cause {
                                                    NoConstantGenericsReason::IsEnumDiscriminant => {
                                                        ResolutionError::ParamInEnumDiscriminant {
                                                            name: rib_ident.name,
                                                            param_kind: ParamKindInEnumDiscriminant::Const,
                                                        }
                                                    }
                                                    NoConstantGenericsReason::NonTrivialConstArg => {
                                                        ResolutionError::ParamInNonTrivialAnonConst {
                                                            is_ogca: self.tcx.features().opaque_generic_const_args(),
                                                            name: rib_ident.name,
                                                            param_kind: ParamKindInNonTrivialAnonConst::Const {
                                                                name: rib_ident.name,
                                                            },
                                                        }
                                                    }
                                                };
                                            self.report_error(span, error);
                                        }
                                        return Res::Err;
                                    }
                                    continue;
                                }
                                RibKind::Item(has_generic_params, def_kind) => {
                                    (has_generic_params, def_kind)
                                }
                            };
                        if let Some(span) = finalize {
                            let item =
                                if let Some(diag_metadata) = diag_metadata &&
                                        let Some(current_item) = diag_metadata.current_item {
                                    let span =
                                        current_item.kind.ident().map(|i|
                                                    i.span).unwrap_or(current_item.span);
                                    Some((span, current_item.kind.clone()))
                                } else { None };
                            self.report_error(span,
                                ResolutionError::GenericParamsFromOuterItem {
                                    outer_res: res,
                                    has_generic_params,
                                    def_kind,
                                    inner_item: item,
                                    current_self_ty: diag_metadata.and_then(|m|
                                                m.current_self_type.as_ref()).and_then(|ty|
                                            {
                                                self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
                                            }),
                                });
                        }
                        return Res::Err;
                    }
                }
                _ => {}
            }
            res
        }
    }
}#[instrument(level = "debug", skip(self, all_ribs))]
1387    fn validate_res_from_ribs(
1388        &mut self,
1389        rib_index: usize,
1390        rib_ident: Ident,
1391        res: Res,
1392        finalize: Option<Span>,
1393        original_rib_ident_def: Ident,
1394        all_ribs: &[Rib<'ra>],
1395        diag_metadata: Option<&DiagMetadata<'_>>,
1396    ) -> Res {
1397        debug!("validate_res_from_ribs({:?})", res);
1398        let ribs = &all_ribs[rib_index + 1..];
1399
1400        // An invalid forward use of a generic parameter from a previous default
1401        // or in a const param ty.
1402        if let RibKind::ForwardGenericParamBan(reason) = all_ribs[rib_index].kind {
1403            if let Some(span) = finalize {
1404                let res_error = if rib_ident.name == kw::SelfUpper {
1405                    ResolutionError::ForwardDeclaredSelf(reason)
1406                } else {
1407                    ResolutionError::ForwardDeclaredGenericParam(rib_ident.name, reason)
1408                };
1409                self.report_error(span, res_error);
1410            }
1411            assert_eq!(res, Res::Err);
1412            return Res::Err;
1413        }
1414
1415        match res {
1416            Res::Local(_) => {
1417                use ResolutionError::*;
1418                let mut res_err = None;
1419
1420                for rib in ribs {
1421                    match rib.kind {
1422                        RibKind::Normal
1423                        | RibKind::Block(..)
1424                        | RibKind::FnOrCoroutine
1425                        | RibKind::Module(..)
1426                        | RibKind::MacroDefinition(..)
1427                        | RibKind::ForwardGenericParamBan(_) => {
1428                            // Nothing to do. Continue.
1429                        }
1430                        RibKind::Item(..) | RibKind::AssocItem => {
1431                            // This was an attempt to access an upvar inside a
1432                            // named function item. This is not allowed, so we
1433                            // report an error.
1434                            if let Some(span) = finalize {
1435                                // We don't immediately trigger a resolve error, because
1436                                // we want certain other resolution errors (namely those
1437                                // emitted for `ConstantItemRibKind` below) to take
1438                                // precedence.
1439                                res_err = Some((span, CannotCaptureDynamicEnvironmentInFnItem));
1440                            }
1441                        }
1442                        RibKind::ConstantItem(_, item) => {
1443                            // Still doesn't deal with upvars
1444                            if let Some(span) = finalize {
1445                                let (span, resolution_error) = match item {
1446                                    None if rib_ident.name == kw::SelfLower => {
1447                                        (span, LowercaseSelf)
1448                                    }
1449                                    None => {
1450                                        // If we have a `let name = expr;`, we have the span for
1451                                        // `name` and use that to see if it is followed by a type
1452                                        // specifier. If not, then we know we need to suggest
1453                                        // `const name: Ty = expr;`. This is a heuristic, it will
1454                                        // break down in the presence of macros.
1455                                        let sm = self.tcx.sess.source_map();
1456                                        let type_span = match sm.span_look_ahead(
1457                                            original_rib_ident_def.span,
1458                                            ":",
1459                                            None,
1460                                        ) {
1461                                            None => {
1462                                                Some(original_rib_ident_def.span.shrink_to_hi())
1463                                            }
1464                                            Some(_) => None,
1465                                        };
1466                                        (
1467                                            rib_ident.span,
1468                                            AttemptToUseNonConstantValueInConstant {
1469                                                ident: original_rib_ident_def,
1470                                                suggestion: "const",
1471                                                current: "let",
1472                                                type_span,
1473                                            },
1474                                        )
1475                                    }
1476                                    Some((ident, kind)) => (
1477                                        span,
1478                                        AttemptToUseNonConstantValueInConstant {
1479                                            ident,
1480                                            suggestion: "let",
1481                                            current: kind.as_str(),
1482                                            type_span: None,
1483                                        },
1484                                    ),
1485                                };
1486                                self.report_error(span, resolution_error);
1487                            }
1488                            return Res::Err;
1489                        }
1490                        RibKind::ConstParamTy => {
1491                            if let Some(span) = finalize {
1492                                self.report_error(
1493                                    span,
1494                                    ParamInTyOfConstParam { name: rib_ident.name },
1495                                );
1496                            }
1497                            return Res::Err;
1498                        }
1499                        RibKind::InlineAsmSym => {
1500                            if let Some(span) = finalize {
1501                                self.report_error(span, InvalidAsmSym);
1502                            }
1503                            return Res::Err;
1504                        }
1505                    }
1506                }
1507                if let Some((span, res_err)) = res_err {
1508                    self.report_error(span, res_err);
1509                    return Res::Err;
1510                }
1511            }
1512            Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {
1513                for rib in ribs {
1514                    let (has_generic_params, def_kind) = match rib.kind {
1515                        RibKind::Normal
1516                        | RibKind::Block(..)
1517                        | RibKind::FnOrCoroutine
1518                        | RibKind::Module(..)
1519                        | RibKind::MacroDefinition(..)
1520                        | RibKind::InlineAsmSym
1521                        | RibKind::AssocItem
1522                        | RibKind::ForwardGenericParamBan(_) => {
1523                            // Nothing to do. Continue.
1524                            continue;
1525                        }
1526
1527                        RibKind::ConstParamTy => {
1528                            if !self.tcx.features().generic_const_parameter_types() {
1529                                if let Some(span) = finalize {
1530                                    self.report_error(
1531                                        span,
1532                                        ResolutionError::ParamInTyOfConstParam {
1533                                            name: rib_ident.name,
1534                                        },
1535                                    );
1536                                }
1537                                return Res::Err;
1538                            } else {
1539                                continue;
1540                            }
1541                        }
1542
1543                        RibKind::ConstantItem(trivial, _) => {
1544                            if let ConstantHasGenerics::No(cause) = trivial
1545                                && !matches!(res, Res::SelfTyAlias { .. })
1546                            {
1547                                if let Some(span) = finalize {
1548                                    let error = match cause {
1549                                        NoConstantGenericsReason::IsEnumDiscriminant => {
1550                                            ResolutionError::ParamInEnumDiscriminant {
1551                                                name: rib_ident.name,
1552                                                param_kind: ParamKindInEnumDiscriminant::Type,
1553                                            }
1554                                        }
1555                                        NoConstantGenericsReason::NonTrivialConstArg => {
1556                                            ResolutionError::ParamInNonTrivialAnonConst {
1557                                                is_ogca: self
1558                                                    .tcx
1559                                                    .features()
1560                                                    .opaque_generic_const_args(),
1561                                                name: rib_ident.name,
1562                                                param_kind: ParamKindInNonTrivialAnonConst::Type,
1563                                            }
1564                                        }
1565                                    };
1566                                    let _: ErrorGuaranteed = self.report_error(span, error);
1567                                }
1568
1569                                return Res::Err;
1570                            }
1571
1572                            continue;
1573                        }
1574
1575                        // This was an attempt to use a type parameter outside its scope.
1576                        RibKind::Item(has_generic_params, def_kind) => {
1577                            (has_generic_params, def_kind)
1578                        }
1579                    };
1580
1581                    if let Some(span) = finalize {
1582                        let item = if let Some(diag_metadata) = diag_metadata
1583                            && let Some(current_item) = diag_metadata.current_item
1584                        {
1585                            let span = current_item
1586                                .kind
1587                                .ident()
1588                                .map(|i| i.span)
1589                                .unwrap_or(current_item.span);
1590                            Some((span, current_item.kind.clone()))
1591                        } else {
1592                            None
1593                        };
1594                        self.report_error(
1595                            span,
1596                            ResolutionError::GenericParamsFromOuterItem {
1597                                outer_res: res,
1598                                has_generic_params,
1599                                def_kind,
1600                                inner_item: item,
1601                                current_self_ty: diag_metadata
1602                                    .and_then(|m| m.current_self_type.as_ref())
1603                                    .and_then(|ty| {
1604                                        self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1605                                    }),
1606                            },
1607                        );
1608                    }
1609                    return Res::Err;
1610                }
1611            }
1612            Res::Def(DefKind::ConstParam, _) => {
1613                for rib in ribs {
1614                    let (has_generic_params, def_kind) = match rib.kind {
1615                        RibKind::Normal
1616                        | RibKind::Block(..)
1617                        | RibKind::FnOrCoroutine
1618                        | RibKind::Module(..)
1619                        | RibKind::MacroDefinition(..)
1620                        | RibKind::InlineAsmSym
1621                        | RibKind::AssocItem
1622                        | RibKind::ForwardGenericParamBan(_) => continue,
1623
1624                        RibKind::ConstParamTy => {
1625                            if !self.tcx.features().generic_const_parameter_types() {
1626                                if let Some(span) = finalize {
1627                                    self.report_error(
1628                                        span,
1629                                        ResolutionError::ParamInTyOfConstParam {
1630                                            name: rib_ident.name,
1631                                        },
1632                                    );
1633                                }
1634                                return Res::Err;
1635                            } else {
1636                                continue;
1637                            }
1638                        }
1639
1640                        RibKind::ConstantItem(trivial, _) => {
1641                            if let ConstantHasGenerics::No(cause) = trivial {
1642                                if let Some(span) = finalize {
1643                                    let error = match cause {
1644                                        NoConstantGenericsReason::IsEnumDiscriminant => {
1645                                            ResolutionError::ParamInEnumDiscriminant {
1646                                                name: rib_ident.name,
1647                                                param_kind: ParamKindInEnumDiscriminant::Const,
1648                                            }
1649                                        }
1650                                        NoConstantGenericsReason::NonTrivialConstArg => {
1651                                            ResolutionError::ParamInNonTrivialAnonConst {
1652                                                is_ogca: self
1653                                                    .tcx
1654                                                    .features()
1655                                                    .opaque_generic_const_args(),
1656                                                name: rib_ident.name,
1657                                                param_kind: ParamKindInNonTrivialAnonConst::Const {
1658                                                    name: rib_ident.name,
1659                                                },
1660                                            }
1661                                        }
1662                                    };
1663                                    self.report_error(span, error);
1664                                }
1665
1666                                return Res::Err;
1667                            }
1668
1669                            continue;
1670                        }
1671
1672                        RibKind::Item(has_generic_params, def_kind) => {
1673                            (has_generic_params, def_kind)
1674                        }
1675                    };
1676
1677                    // This was an attempt to use a const parameter outside its scope.
1678                    if let Some(span) = finalize {
1679                        let item = if let Some(diag_metadata) = diag_metadata
1680                            && let Some(current_item) = diag_metadata.current_item
1681                        {
1682                            let span = current_item
1683                                .kind
1684                                .ident()
1685                                .map(|i| i.span)
1686                                .unwrap_or(current_item.span);
1687                            Some((span, current_item.kind.clone()))
1688                        } else {
1689                            None
1690                        };
1691                        self.report_error(
1692                            span,
1693                            ResolutionError::GenericParamsFromOuterItem {
1694                                outer_res: res,
1695                                has_generic_params,
1696                                def_kind,
1697                                inner_item: item,
1698                                current_self_ty: diag_metadata
1699                                    .and_then(|m| m.current_self_type.as_ref())
1700                                    .and_then(|ty| {
1701                                        self.tcx.sess.source_map().span_to_snippet(ty.span).ok()
1702                                    }),
1703                            },
1704                        );
1705                    }
1706                    return Res::Err;
1707                }
1708            }
1709            _ => {}
1710        }
1711
1712        res
1713    }
1714
1715    #[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(1715u32),
                                    ::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))]
1716    pub(crate) fn maybe_resolve_path<'r>(
1717        self: CmResolver<'r, 'ra, 'tcx>,
1718        path: &[Segment],
1719        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1720        parent_scope: &ParentScope<'ra>,
1721        ignore_import: Option<Import<'ra>>,
1722    ) -> PathResult<'ra> {
1723        self.resolve_path_with_ribs(
1724            path,
1725            opt_ns,
1726            parent_scope,
1727            None,
1728            None,
1729            None,
1730            None,
1731            ignore_import,
1732            None,
1733        )
1734    }
1735    #[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(1735u32),
                                    ::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))]
1736    pub(crate) fn resolve_path<'r>(
1737        self: CmResolver<'r, 'ra, 'tcx>,
1738        path: &[Segment],
1739        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1740        parent_scope: &ParentScope<'ra>,
1741        finalize: Option<Finalize>,
1742        ignore_decl: Option<Decl<'ra>>,
1743        ignore_import: Option<Import<'ra>>,
1744    ) -> PathResult<'ra> {
1745        self.resolve_path_with_ribs(
1746            path,
1747            opt_ns,
1748            parent_scope,
1749            None,
1750            finalize,
1751            None,
1752            ignore_decl,
1753            ignore_import,
1754            None,
1755        )
1756    }
1757
1758    pub(crate) fn resolve_path_with_ribs<'r>(
1759        mut self: CmResolver<'r, 'ra, 'tcx>,
1760        path: &[Segment],
1761        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1762        parent_scope: &ParentScope<'ra>,
1763        source: Option<PathSource<'_, '_, '_>>,
1764        finalize: Option<Finalize>,
1765        ribs: Option<&PerNS<Vec<Rib<'ra>>>>,
1766        ignore_decl: Option<Decl<'ra>>,
1767        ignore_import: Option<Import<'ra>>,
1768        diag_metadata: Option<&DiagMetadata<'_>>,
1769    ) -> PathResult<'ra> {
1770        let mut module = None;
1771        let mut module_had_parse_errors = !self.mods_with_parse_errors.is_empty()
1772            && self.mods_with_parse_errors.contains(&parent_scope.module.nearest_parent_mod());
1773        let mut allow_super = true;
1774        let mut second_binding = None;
1775
1776        // We'll provide more context to the privacy errors later, up to `len`.
1777        let privacy_errors_len = self.privacy_errors.len();
1778        fn record_segment_res<'r, 'ra, 'tcx>(
1779            mut this: CmResolver<'r, 'ra, 'tcx>,
1780            finalize: Option<Finalize>,
1781            res: Res,
1782            id: Option<NodeId>,
1783        ) {
1784            if finalize.is_some()
1785                && let Some(id) = id
1786                && !this.partial_res_map.contains_key(&id)
1787            {
1788                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");
1789                this.get_mut().record_partial_res(id, PartialRes::new(res));
1790            }
1791        }
1792
1793        for (segment_idx, &Segment { ident, id, .. }) in path.iter().enumerate() {
1794            {
    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:1794",
                        "rustc_resolve::ident", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/ident.rs"),
                        ::tracing_core::__macro_support::Option::Some(1794u32),
                        ::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);
1795
1796            let is_last = segment_idx + 1 == path.len();
1797            let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS };
1798            let name = ident.name;
1799
1800            allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super);
1801
1802            if ns == TypeNS {
1803                if allow_super && name == kw::Super {
1804                    let parent = if segment_idx == 0 {
1805                        self.resolve_super_in_module(ident, None, parent_scope)
1806                    } else if let Some(ModuleOrUniformRoot::Module(module)) = module {
1807                        self.resolve_super_in_module(ident, Some(module), parent_scope)
1808                    } else {
1809                        None
1810                    };
1811                    if let Some(parent) = parent {
1812                        module = Some(ModuleOrUniformRoot::Module(parent));
1813                        continue;
1814                    }
1815                    return PathResult::failed(
1816                        ident,
1817                        false,
1818                        finalize.is_some(),
1819                        module_had_parse_errors,
1820                        module,
1821                        || {
1822                            (
1823                                "too many leading `super` keywords".to_string(),
1824                                "there are too many leading `super` keywords".to_string(),
1825                                None,
1826                            )
1827                        },
1828                    );
1829                }
1830                if segment_idx == 0 {
1831                    if name == kw::SelfLower {
1832                        let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
1833                        let self_mod = self.resolve_self(&mut ctxt, parent_scope.module);
1834                        if let Some(res) = self_mod.res() {
1835                            record_segment_res(self.reborrow(), finalize, res, id);
1836                        }
1837                        module = Some(ModuleOrUniformRoot::Module(self_mod));
1838                        continue;
1839                    }
1840                    if name == kw::PathRoot && ident.span.at_least_rust_2018() {
1841                        module = Some(ModuleOrUniformRoot::ExternPrelude);
1842                        continue;
1843                    }
1844                    if name == kw::PathRoot
1845                        && ident.span.is_rust_2015()
1846                        && self.tcx.sess.at_least_rust_2018()
1847                    {
1848                        // `::a::b` from 2015 macro on 2018 global edition
1849                        let crate_root = self.resolve_crate_root(ident);
1850                        module = Some(ModuleOrUniformRoot::ModuleAndExternPrelude(crate_root));
1851                        continue;
1852                    }
1853                    if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate {
1854                        // `::a::b`, `crate::a::b` or `$crate::a::b`
1855                        let crate_root = self.resolve_crate_root(ident);
1856                        if let Some(res) = crate_root.res() {
1857                            record_segment_res(self.reborrow(), finalize, res, id);
1858                        }
1859                        module = Some(ModuleOrUniformRoot::Module(crate_root));
1860                        continue;
1861                    }
1862                }
1863            }
1864
1865            // Report special messages for path segment keywords in wrong positions.
1866            if ident.is_path_segment_keyword() && segment_idx != 0 {
1867                return PathResult::failed(
1868                    ident,
1869                    false,
1870                    finalize.is_some(),
1871                    module_had_parse_errors,
1872                    module,
1873                    || {
1874                        let name_str = if name == kw::PathRoot {
1875                            "the crate root".to_string()
1876                        } else {
1877                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", name))
    })format!("`{name}`")
1878                        };
1879                        let (message, label) = if segment_idx == 1
1880                            && path[0].ident.name == kw::PathRoot
1881                        {
1882                            (
1883                                ::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}"),
1884                                "cannot start with this".to_string(),
1885                            )
1886                        } else {
1887                            (
1888                                ::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"),
1889                                "can only be used in path start position".to_string(),
1890                            )
1891                        };
1892                        (message, label, None)
1893                    },
1894                );
1895            }
1896
1897            let binding = if let Some(module) = module {
1898                self.reborrow().resolve_ident_in_module(
1899                    module,
1900                    ident,
1901                    ns,
1902                    parent_scope,
1903                    finalize,
1904                    ignore_decl,
1905                    ignore_import,
1906                )
1907            } else if let Some(ribs) = ribs
1908                && let Some(TypeNS | ValueNS) = opt_ns
1909            {
1910                if !ignore_import.is_none() {
    ::core::panicking::panic("assertion failed: ignore_import.is_none()")
};assert!(ignore_import.is_none());
1911                match self.get_mut().resolve_ident_in_lexical_scope(
1912                    ident,
1913                    ns,
1914                    parent_scope,
1915                    finalize,
1916                    &ribs[ns],
1917                    ignore_decl,
1918                    diag_metadata,
1919                ) {
1920                    // we found a locally-imported or available item/module
1921                    Some(LateDecl::Decl(binding)) => Ok(binding),
1922                    // we found a local variable or type param
1923                    Some(LateDecl::RibDef(res)) => {
1924                        record_segment_res(self.reborrow(), finalize, res, id);
1925                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
1926                            res,
1927                            path.len() - 1,
1928                        ));
1929                    }
1930                    _ => Err(Determinacy::determined(finalize.is_some())),
1931                }
1932            } else {
1933                self.reborrow().resolve_ident_in_scope_set(
1934                    ident,
1935                    ScopeSet::All(ns),
1936                    parent_scope,
1937                    finalize,
1938                    ignore_decl,
1939                    ignore_import,
1940                )
1941            };
1942
1943            match binding {
1944                Ok(binding) => {
1945                    if segment_idx == 1 {
1946                        second_binding = Some(binding);
1947                    }
1948                    let res = binding.res();
1949
1950                    // Mark every privacy error in this path with the res to the last element. This allows us
1951                    // to detect the item the user cares about and either find an alternative import, or tell
1952                    // the user it is not accessible.
1953                    if finalize.is_some() {
1954                        for error in &mut self.get_mut().privacy_errors[privacy_errors_len..] {
1955                            error.outermost_res = Some((res, ident));
1956                            error.source = match source {
1957                                Some(PathSource::Struct(Some(expr)))
1958                                | Some(PathSource::Expr(Some(expr))) => Some(expr.clone()),
1959                                _ => None,
1960                            };
1961                        }
1962                    }
1963
1964                    let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
1965                    if let Some(def_id) = binding.res().module_like_def_id() {
1966                        if self.mods_with_parse_errors.contains(&def_id) {
1967                            module_had_parse_errors = true;
1968                        }
1969                        module = Some(ModuleOrUniformRoot::Module(self.expect_module(def_id)));
1970                        record_segment_res(self.reborrow(), finalize, res, id);
1971                    } else if res == Res::ToolMod && !is_last && opt_ns.is_some() {
1972                        if binding.is_import() {
1973                            self.dcx().emit_err(errors::ToolModuleImported {
1974                                span: ident.span,
1975                                import: binding.span,
1976                            });
1977                        }
1978                        let res = Res::NonMacroAttr(NonMacroAttrKind::Tool);
1979                        return PathResult::NonModule(PartialRes::new(res));
1980                    } else if res == Res::Err {
1981                        return PathResult::NonModule(PartialRes::new(Res::Err));
1982                    } else if opt_ns.is_some() && (is_last || maybe_assoc) {
1983                        if let Some(finalize) = finalize {
1984                            self.get_mut().lint_if_path_starts_with_module(
1985                                finalize,
1986                                path,
1987                                second_binding,
1988                            );
1989                        }
1990                        record_segment_res(self.reborrow(), finalize, res, id);
1991                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
1992                            res,
1993                            path.len() - segment_idx - 1,
1994                        ));
1995                    } else {
1996                        return PathResult::failed(
1997                            ident,
1998                            is_last,
1999                            finalize.is_some(),
2000                            module_had_parse_errors,
2001                            module,
2002                            || {
2003                                let label = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{2}` is {0} {1}, not a module",
                res.article(), res.descr(), ident))
    })format!(
2004                                    "`{ident}` is {} {}, not a module",
2005                                    res.article(),
2006                                    res.descr()
2007                                );
2008                                let scope = match &path[..segment_idx] {
2009                                    [.., prev] => {
2010                                        if prev.ident.name == kw::PathRoot {
2011                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the crate root"))
    })format!("the crate root")
2012                                        } else {
2013                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", prev.ident))
    })format!("`{}`", prev.ident)
2014                                        }
2015                                    }
2016                                    _ => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this scope"))
    })format!("this scope"),
2017                                };
2018                                // FIXME: reword, as the reason we expected a module is because of
2019                                // the following path segment.
2020                                let message = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot find module `{0}` in {1}",
                ident, scope))
    })format!("cannot find module `{ident}` in {scope}");
2021                                (message, label, None)
2022                            },
2023                        );
2024                    }
2025                }
2026                Err(Undetermined) if finalize.is_none() => return PathResult::Indeterminate,
2027                Err(Determined | Undetermined) => {
2028                    if let Some(ModuleOrUniformRoot::Module(module)) = module
2029                        && opt_ns.is_some()
2030                        && !module.is_normal()
2031                    {
2032                        return PathResult::NonModule(PartialRes::with_unresolved_segments(
2033                            module.res().unwrap(),
2034                            path.len() - segment_idx,
2035                        ));
2036                    }
2037
2038                    let mut this = self.reborrow();
2039                    return PathResult::failed(
2040                        ident,
2041                        is_last,
2042                        finalize.is_some(),
2043                        module_had_parse_errors,
2044                        module,
2045                        || {
2046                            this.get_mut().report_path_resolution_error(
2047                                path,
2048                                opt_ns,
2049                                parent_scope,
2050                                ribs,
2051                                ignore_decl,
2052                                ignore_import,
2053                                module,
2054                                segment_idx,
2055                                ident,
2056                                diag_metadata,
2057                            )
2058                        },
2059                    );
2060                }
2061            }
2062        }
2063
2064        if let Some(finalize) = finalize {
2065            self.get_mut().lint_if_path_starts_with_module(finalize, path, second_binding);
2066        }
2067
2068        PathResult::Module(match module {
2069            Some(module) => module,
2070            None if path.is_empty() => ModuleOrUniformRoot::CurrentScope,
2071            _ => ::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),
2072        })
2073    }
2074}