Skip to main content

rustc_resolve/
late.rs

1// ignore-tidy-filelength
2//! "Late resolution" is the pass that resolves most of names in a crate beside imports and macros.
3//! It runs when the crate is fully expanded and its module structure is fully built.
4//! So it just walks through the crate and resolves all the expressions, types, etc.
5//!
6//! If you wonder why there's no `early.rs`, that's because it's split into three files -
7//! `build_reduced_graph.rs`, `macros.rs` and `imports.rs`.
8
9use std::borrow::Cow;
10use std::collections::hash_map::Entry;
11use std::debug_assert_matches;
12use std::mem::{replace, swap, take};
13use std::ops::{ControlFlow, Range};
14
15use rustc_ast::visit::{
16    AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor, try_visit, visit_opt, walk_list,
17};
18use rustc_ast::*;
19use rustc_data_structures::either::Either;
20use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
21use rustc_data_structures::unord::{UnordMap, UnordSet};
22use rustc_errors::codes::*;
23use rustc_errors::{
24    Applicability, Diag, DiagArgValue, Diagnostic, ErrorGuaranteed, IntoDiagArg, MultiSpan,
25    StashKey, Suggestions, elided_lifetime_in_path_suggestion, pluralize,
26};
27use rustc_hir::def::Namespace::{self, *};
28use rustc_hir::def::{CtorKind, DefKind, LifetimeRes, NonMacroAttrKind, PartialRes, PerNS};
29use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE, LocalDefId};
30use rustc_hir::{MissingLifetimeKind, PrimTy, TraitCandidate};
31use rustc_middle::middle::resolve_bound_vars::Set1;
32use rustc_middle::ty::{AssocTag, DelegationInfo, Visibility};
33use rustc_middle::{bug, span_bug};
34use rustc_session::config::{CrateType, ResolveDocLinks};
35use rustc_session::errors::feature_err;
36use rustc_session::lint;
37use rustc_span::{BytePos, DUMMY_SP, Ident, Span, Spanned, Symbol, kw, respan, sym};
38use smallvec::{SmallVec, smallvec};
39use thin_vec::ThinVec;
40use tracing::{debug, instrument, trace};
41
42use crate::{
43    BindingError, BindingKey, Decl, DelegationFnSig, Finalize, IdentKey, LateDecl, LocalModule,
44    Module, ModuleOrUniformRoot, ParentScope, PathResult, Res, ResolutionError, Resolver, Segment,
45    Stage, TyCtxt, UseError, Used, errors, path_names_to_string, rustdoc, with_owner,
46};
47
48mod diagnostics;
49
50use diagnostics::{ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime};
51
52#[derive(#[automatically_derived]
impl ::core::marker::Copy for BindingInfo { }Copy, #[automatically_derived]
impl ::core::clone::Clone for BindingInfo {
    #[inline]
    fn clone(&self) -> BindingInfo {
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<BindingMode>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for BindingInfo {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "BindingInfo",
            "span", &self.span, "annotation", &&self.annotation)
    }
}Debug)]
53struct BindingInfo {
54    span: Span,
55    annotation: BindingMode,
56}
57
58#[derive(#[automatically_derived]
impl ::core::marker::Copy for PatternSource { }Copy, #[automatically_derived]
impl ::core::clone::Clone for PatternSource {
    #[inline]
    fn clone(&self) -> PatternSource { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for PatternSource {
    #[inline]
    fn eq(&self, other: &PatternSource) -> 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::cmp::Eq for PatternSource {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for PatternSource {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                PatternSource::Match => "Match",
                PatternSource::Let => "Let",
                PatternSource::For => "For",
                PatternSource::FnParam => "FnParam",
            })
    }
}Debug)]
59pub(crate) enum PatternSource {
60    Match,
61    Let,
62    For,
63    FnParam,
64}
65
66#[derive(#[automatically_derived]
impl ::core::marker::Copy for IsRepeatExpr { }Copy, #[automatically_derived]
impl ::core::clone::Clone for IsRepeatExpr {
    #[inline]
    fn clone(&self) -> IsRepeatExpr { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for IsRepeatExpr {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                IsRepeatExpr::No => "No",
                IsRepeatExpr::Yes => "Yes",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for IsRepeatExpr {
    #[inline]
    fn eq(&self, other: &IsRepeatExpr) -> 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::cmp::Eq for IsRepeatExpr {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
67enum IsRepeatExpr {
68    No,
69    Yes,
70}
71
72struct IsNeverPattern;
73
74/// Describes whether an `AnonConst` is a type level const arg or
75/// some other form of anon const (i.e. inline consts or enum discriminants)
76#[derive(#[automatically_derived]
impl ::core::marker::Copy for AnonConstKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AnonConstKind {
    #[inline]
    fn clone(&self) -> AnonConstKind {
        let _: ::core::clone::AssertParamIsClone<IsRepeatExpr>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for AnonConstKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            AnonConstKind::EnumDiscriminant =>
                ::core::fmt::Formatter::write_str(f, "EnumDiscriminant"),
            AnonConstKind::FieldDefaultValue =>
                ::core::fmt::Formatter::write_str(f, "FieldDefaultValue"),
            AnonConstKind::InlineConst =>
                ::core::fmt::Formatter::write_str(f, "InlineConst"),
            AnonConstKind::ConstArg(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ConstArg", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for AnonConstKind {
    #[inline]
    fn eq(&self, other: &AnonConstKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (AnonConstKind::ConstArg(__self_0),
                    AnonConstKind::ConstArg(__arg1_0)) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AnonConstKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<IsRepeatExpr>;
    }
}Eq)]
77enum AnonConstKind {
78    EnumDiscriminant,
79    FieldDefaultValue,
80    InlineConst,
81    ConstArg(IsRepeatExpr),
82}
83
84impl PatternSource {
85    fn descr(self) -> &'static str {
86        match self {
87            PatternSource::Match => "match binding",
88            PatternSource::Let => "let binding",
89            PatternSource::For => "for binding",
90            PatternSource::FnParam => "function parameter",
91        }
92    }
93}
94
95impl IntoDiagArg for PatternSource {
96    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
97        DiagArgValue::Str(Cow::Borrowed(self.descr()))
98    }
99}
100
101/// Denotes whether the context for the set of already bound bindings is a `Product`
102/// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
103/// See those functions for more information.
104#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for PatBoundCtx {
    #[inline]
    fn eq(&self, other: &PatBoundCtx) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
105enum PatBoundCtx {
106    /// A product pattern context, e.g., `Variant(a, b)`.
107    Product,
108    /// An or-pattern context, e.g., `p_0 | ... | p_n`.
109    Or,
110}
111
112/// Tracks bindings resolved within a pattern. This serves two purposes:
113///
114/// - This tracks when identifiers are bound multiple times within a pattern. In a product context,
115///   this is an error. In an or-pattern, this lets us reuse the same resolution for each instance.
116///   See `fresh_binding` and `resolve_pattern_inner` for more information.
117///
118/// - The guard expression of a guard pattern may use bindings from within the guard pattern, but
119///   not from elsewhere in the pattern containing it. This allows us to isolate the bindings in the
120///   subpattern to construct the scope for the guard.
121///
122/// Each identifier must map to at most one distinct [`Res`].
123type PatternBindings = SmallVec<[(PatBoundCtx, FxIndexMap<Ident, Res>); 1]>;
124
125/// Does this the item (from the item rib scope) allow generic parameters?
126#[derive(#[automatically_derived]
impl ::core::marker::Copy for HasGenericParams { }Copy, #[automatically_derived]
impl ::core::clone::Clone for HasGenericParams {
    #[inline]
    fn clone(&self) -> HasGenericParams {
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for HasGenericParams {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            HasGenericParams::Yes(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Yes",
                    &__self_0),
            HasGenericParams::No =>
                ::core::fmt::Formatter::write_str(f, "No"),
        }
    }
}Debug)]
127pub(crate) enum HasGenericParams {
128    Yes(Span),
129    No,
130}
131
132/// May this constant have generics?
133#[derive(#[automatically_derived]
impl ::core::marker::Copy for ConstantHasGenerics { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ConstantHasGenerics {
    #[inline]
    fn clone(&self) -> ConstantHasGenerics {
        let _: ::core::clone::AssertParamIsClone<NoConstantGenericsReason>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ConstantHasGenerics {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ConstantHasGenerics::Yes =>
                ::core::fmt::Formatter::write_str(f, "Yes"),
            ConstantHasGenerics::No(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "No",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for ConstantHasGenerics {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NoConstantGenericsReason>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for ConstantHasGenerics {
    #[inline]
    fn eq(&self, other: &ConstantHasGenerics) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (ConstantHasGenerics::No(__self_0),
                    ConstantHasGenerics::No(__arg1_0)) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
134pub(crate) enum ConstantHasGenerics {
135    Yes,
136    No(NoConstantGenericsReason),
137}
138
139impl ConstantHasGenerics {
140    fn force_yes_if(self, b: bool) -> Self {
141        if b { Self::Yes } else { self }
142    }
143}
144
145/// Reason for why an anon const is not allowed to reference generic parameters
146#[derive(#[automatically_derived]
impl ::core::marker::Copy for NoConstantGenericsReason { }Copy, #[automatically_derived]
impl ::core::clone::Clone for NoConstantGenericsReason {
    #[inline]
    fn clone(&self) -> NoConstantGenericsReason { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for NoConstantGenericsReason {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                NoConstantGenericsReason::NonTrivialConstArg =>
                    "NonTrivialConstArg",
                NoConstantGenericsReason::IsEnumDiscriminant =>
                    "IsEnumDiscriminant",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for NoConstantGenericsReason {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for NoConstantGenericsReason {
    #[inline]
    fn eq(&self, other: &NoConstantGenericsReason) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
147pub(crate) enum NoConstantGenericsReason {
148    /// Const arguments are only allowed to use generic parameters when:
149    /// - `feature(generic_const_exprs)` is enabled
150    /// or
151    /// - the const argument is a sole const generic parameter, i.e. `foo::<{ N }>()`
152    ///
153    /// If neither of the above are true then this is used as the cause.
154    NonTrivialConstArg,
155    /// Enum discriminants are not allowed to reference generic parameters ever, this
156    /// is used when an anon const is in the following position:
157    ///
158    /// ```rust,compile_fail
159    /// enum Foo<const N: isize> {
160    ///     Variant = { N }, // this anon const is not allowed to use generics
161    /// }
162    /// ```
163    IsEnumDiscriminant,
164}
165
166#[derive(#[automatically_derived]
impl ::core::marker::Copy for ConstantItemKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ConstantItemKind {
    #[inline]
    fn clone(&self) -> ConstantItemKind { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ConstantItemKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ConstantItemKind::Const => "Const",
                ConstantItemKind::Static => "Static",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for ConstantItemKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for ConstantItemKind {
    #[inline]
    fn eq(&self, other: &ConstantItemKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
167pub(crate) enum ConstantItemKind {
168    Const,
169    Static,
170}
171
172impl ConstantItemKind {
173    pub(crate) fn as_str(&self) -> &'static str {
174        match self {
175            Self::Const => "const",
176            Self::Static => "static",
177        }
178    }
179}
180
181#[derive(#[automatically_derived]
impl ::core::fmt::Debug for RecordPartialRes {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                RecordPartialRes::Yes => "Yes",
                RecordPartialRes::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for RecordPartialRes { }Copy, #[automatically_derived]
impl ::core::clone::Clone for RecordPartialRes {
    #[inline]
    fn clone(&self) -> RecordPartialRes { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for RecordPartialRes {
    #[inline]
    fn eq(&self, other: &RecordPartialRes) -> 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::cmp::Eq for RecordPartialRes {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
182enum RecordPartialRes {
183    Yes,
184    No,
185}
186
187/// The rib kind restricts certain accesses,
188/// e.g. to a `Res::Local` of an outer item.
189#[derive(#[automatically_derived]
impl<'ra> ::core::marker::Copy for RibKind<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::clone::Clone for RibKind<'ra> {
    #[inline]
    fn clone(&self) -> RibKind<'ra> {
        let _: ::core::clone::AssertParamIsClone<Option<LocalModule<'ra>>>;
        let _: ::core::clone::AssertParamIsClone<HasGenericParams>;
        let _: ::core::clone::AssertParamIsClone<DefKind>;
        let _: ::core::clone::AssertParamIsClone<ConstantHasGenerics>;
        let _:
                ::core::clone::AssertParamIsClone<Option<(Ident,
                ConstantItemKind)>>;
        let _: ::core::clone::AssertParamIsClone<LocalModule<'ra>>;
        let _: ::core::clone::AssertParamIsClone<DefId>;
        let _:
                ::core::clone::AssertParamIsClone<ForwardGenericParamBanReason>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for RibKind<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            RibKind::Normal => ::core::fmt::Formatter::write_str(f, "Normal"),
            RibKind::Block(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Block",
                    &__self_0),
            RibKind::AssocItem =>
                ::core::fmt::Formatter::write_str(f, "AssocItem"),
            RibKind::FnOrCoroutine =>
                ::core::fmt::Formatter::write_str(f, "FnOrCoroutine"),
            RibKind::Item(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Item",
                    __self_0, &__self_1),
            RibKind::ConstantItem(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "ConstantItem", __self_0, &__self_1),
            RibKind::Module(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Module",
                    &__self_0),
            RibKind::MacroDefinition(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "MacroDefinition", &__self_0),
            RibKind::ForwardGenericParamBan(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ForwardGenericParamBan", &__self_0),
            RibKind::ConstParamTy =>
                ::core::fmt::Formatter::write_str(f, "ConstParamTy"),
            RibKind::InlineAsmSym =>
                ::core::fmt::Formatter::write_str(f, "InlineAsmSym"),
        }
    }
}Debug)]
190pub(crate) enum RibKind<'ra> {
191    /// No restriction needs to be applied.
192    Normal,
193
194    /// We passed through an `ast::Block`.
195    /// Behaves like `Normal`, but also partially like `Module` if the block contains items.
196    /// `Block(None)` must be always processed in the same way as `Block(Some(module))`
197    /// with empty `module`. The module can be `None` only because creation of some definitely
198    /// empty modules is skipped as an optimization.
199    Block(Option<LocalModule<'ra>>),
200
201    /// We passed through an impl or trait and are now in one of its
202    /// methods or associated types. Allow references to ty params that impl or trait
203    /// binds. Disallow any other upvars (including other ty params that are
204    /// upvars).
205    AssocItem,
206
207    /// We passed through a function, closure or coroutine signature. Disallow labels.
208    FnOrCoroutine,
209
210    /// We passed through an item scope. Disallow upvars.
211    Item(HasGenericParams, DefKind),
212
213    /// We're in a constant item. Can't refer to dynamic stuff.
214    ///
215    /// The item may reference generic parameters in trivial constant expressions.
216    /// All other constants aren't allowed to use generic params at all.
217    ConstantItem(ConstantHasGenerics, Option<(Ident, ConstantItemKind)>),
218
219    /// We passed through a module item.
220    Module(LocalModule<'ra>),
221
222    /// We passed through a `macro_rules!` statement
223    MacroDefinition(DefId),
224
225    /// All bindings in this rib are generic parameters that can't be used
226    /// from the default of a generic parameter because they're not declared
227    /// before said generic parameter. Also see the `visit_generics` override.
228    ForwardGenericParamBan(ForwardGenericParamBanReason),
229
230    /// We are inside of the type of a const parameter. Can't refer to any
231    /// parameters.
232    ConstParamTy,
233
234    /// We are inside a `sym` inline assembly operand. Can only refer to
235    /// globals.
236    InlineAsmSym,
237}
238
239#[derive(#[automatically_derived]
impl ::core::marker::Copy for ForwardGenericParamBanReason { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ForwardGenericParamBanReason {
    #[inline]
    fn clone(&self) -> ForwardGenericParamBanReason { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ForwardGenericParamBanReason {
    #[inline]
    fn eq(&self, other: &ForwardGenericParamBanReason) -> 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::cmp::Eq for ForwardGenericParamBanReason {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for ForwardGenericParamBanReason {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ForwardGenericParamBanReason::Default => "Default",
                ForwardGenericParamBanReason::ConstParamTy => "ConstParamTy",
            })
    }
}Debug)]
240pub(crate) enum ForwardGenericParamBanReason {
241    Default,
242    ConstParamTy,
243}
244
245impl RibKind<'_> {
246    /// Whether this rib kind contains generic parameters, as opposed to local
247    /// variables.
248    pub(crate) fn contains_params(&self) -> bool {
249        match self {
250            RibKind::Normal
251            | RibKind::Block(..)
252            | RibKind::FnOrCoroutine
253            | RibKind::ConstantItem(..)
254            | RibKind::Module(_)
255            | RibKind::MacroDefinition(_)
256            | RibKind::InlineAsmSym => false,
257            RibKind::ConstParamTy
258            | RibKind::AssocItem
259            | RibKind::Item(..)
260            | RibKind::ForwardGenericParamBan(_) => true,
261        }
262    }
263
264    /// This rib forbids referring to labels defined in upwards ribs.
265    fn is_label_barrier(self) -> bool {
266        match self {
267            RibKind::Normal | RibKind::MacroDefinition(..) => false,
268            RibKind::FnOrCoroutine | RibKind::ConstantItem(..) => true,
269            kind => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected rib kind: {0:?}",
        kind))bug!("unexpected rib kind: {kind:?}"),
270        }
271    }
272}
273
274/// A single local scope.
275///
276/// A rib represents a scope names can live in. Note that these appear in many places, not just
277/// around braces. At any place where the list of accessible names (of the given namespace)
278/// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
279/// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
280/// etc.
281///
282/// Different [rib kinds](enum@RibKind) are transparent for different names.
283///
284/// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
285/// resolving, the name is looked up from inside out.
286#[derive(#[automatically_derived]
impl<'ra, R: ::core::fmt::Debug> ::core::fmt::Debug for Rib<'ra, R> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "Rib",
            "bindings", &self.bindings, "patterns_with_skipped_bindings",
            &self.patterns_with_skipped_bindings, "kind", &&self.kind)
    }
}Debug)]
287pub(crate) struct Rib<'ra, R = Res> {
288    pub bindings: FxIndexMap<Ident, R>,
289    pub patterns_with_skipped_bindings: UnordMap<DefId, Vec<(Span, Result<(), ErrorGuaranteed>)>>,
290    pub kind: RibKind<'ra>,
291}
292
293impl<'ra, R> Rib<'ra, R> {
294    fn new(kind: RibKind<'ra>) -> Rib<'ra, R> {
295        Rib {
296            bindings: Default::default(),
297            patterns_with_skipped_bindings: Default::default(),
298            kind,
299        }
300    }
301}
302
303#[derive(#[automatically_derived]
impl ::core::clone::Clone for LifetimeUseSet {
    #[inline]
    fn clone(&self) -> LifetimeUseSet {
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<visit::LifetimeCtxt>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for LifetimeUseSet { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for LifetimeUseSet {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LifetimeUseSet::One { use_span: __self_0, use_ctxt: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f, "One",
                    "use_span", __self_0, "use_ctxt", &__self_1),
            LifetimeUseSet::Many =>
                ::core::fmt::Formatter::write_str(f, "Many"),
        }
    }
}Debug)]
304enum LifetimeUseSet {
305    One { use_span: Span, use_ctxt: visit::LifetimeCtxt },
306    Many,
307}
308
309#[derive(#[automatically_derived]
impl ::core::marker::Copy for LifetimeRibKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for LifetimeRibKind {
    #[inline]
    fn clone(&self) -> LifetimeRibKind {
        let _: ::core::clone::AssertParamIsClone<NodeId>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<LifetimeBinderKind>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<LifetimeRes>;
        let _: ::core::clone::AssertParamIsClone<NoConstantGenericsReason>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for LifetimeRibKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LifetimeRibKind::Generics {
                binder: __self_0, span: __self_1, kind: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "Generics", "binder", __self_0, "span", __self_1, "kind",
                    &__self_2),
            LifetimeRibKind::AnonymousCreateParameter {
                binder: __self_0, report_in_path: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "AnonymousCreateParameter", "binder", __self_0,
                    "report_in_path", &__self_1),
            LifetimeRibKind::Elided(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Elided",
                    &__self_0),
            LifetimeRibKind::AnonymousReportError =>
                ::core::fmt::Formatter::write_str(f, "AnonymousReportError"),
            LifetimeRibKind::StaticIfNoLifetimeInScope {
                lint_id: __self_0, emit_lint: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "StaticIfNoLifetimeInScope", "lint_id", __self_0,
                    "emit_lint", &__self_1),
            LifetimeRibKind::ElisionFailure =>
                ::core::fmt::Formatter::write_str(f, "ElisionFailure"),
            LifetimeRibKind::ConstParamTy =>
                ::core::fmt::Formatter::write_str(f, "ConstParamTy"),
            LifetimeRibKind::ConcreteAnonConst(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ConcreteAnonConst", &__self_0),
            LifetimeRibKind::Item =>
                ::core::fmt::Formatter::write_str(f, "Item"),
            LifetimeRibKind::ImplTrait =>
                ::core::fmt::Formatter::write_str(f, "ImplTrait"),
        }
    }
}Debug)]
310enum LifetimeRibKind {
311    // -- Ribs introducing named lifetimes
312    //
313    /// This rib declares generic parameters.
314    /// Only for this kind the `LifetimeRib::bindings` field can be non-empty.
315    Generics { binder: NodeId, span: Span, kind: LifetimeBinderKind },
316
317    // -- Ribs introducing unnamed lifetimes
318    //
319    /// Create a new anonymous lifetime parameter and reference it.
320    ///
321    /// If `report_in_path`, report an error when encountering lifetime elision in a path:
322    /// ```compile_fail
323    /// struct Foo<'a> { x: &'a () }
324    /// async fn foo(x: Foo) {}
325    /// ```
326    ///
327    /// Note: the error should not trigger when the elided lifetime is in a pattern or
328    /// expression-position path:
329    /// ```
330    /// struct Foo<'a> { x: &'a () }
331    /// async fn foo(Foo { x: _ }: Foo<'_>) {}
332    /// ```
333    AnonymousCreateParameter { binder: NodeId, report_in_path: bool },
334
335    /// Replace all anonymous lifetimes by provided lifetime.
336    Elided(LifetimeRes),
337
338    // -- Barrier ribs that stop lifetime lookup, or continue it but produce an error later.
339    //
340    /// Give a hard error when either `&` or `'_` is written. Used to
341    /// rule out things like `where T: Foo<'_>`. Does not imply an
342    /// error on default object bounds (e.g., `Box<dyn Foo>`).
343    AnonymousReportError,
344
345    /// Resolves elided lifetimes to `'static` if there are no other lifetimes in scope,
346    /// otherwise give a warning that the previous behavior of introducing a new early-bound
347    /// lifetime is a bug and will be removed (if `emit_lint` is enabled).
348    StaticIfNoLifetimeInScope { lint_id: NodeId, emit_lint: bool },
349
350    /// Signal we cannot find which should be the anonymous lifetime.
351    ElisionFailure,
352
353    /// This rib forbids usage of generic parameters inside of const parameter types.
354    ///
355    /// While this is desirable to support eventually, it is difficult to do and so is
356    /// currently forbidden. See rust-lang/project-const-generics#28 for more info.
357    ConstParamTy,
358
359    /// Usage of generic parameters is forbidden in various positions for anon consts:
360    /// - const arguments when `generic_const_exprs` is not enabled
361    /// - enum discriminant values
362    ///
363    /// This rib emits an error when a lifetime would resolve to a lifetime parameter.
364    ConcreteAnonConst(NoConstantGenericsReason),
365
366    /// This rib acts as a barrier to forbid reference to lifetimes of a parent item.
367    Item,
368
369    /// Lifetimes cannot be elided in `impl Trait` types without `#![feature(anonymous_lifetime_in_impl_trait)]`.
370    ImplTrait,
371}
372
373#[derive(#[automatically_derived]
impl ::core::marker::Copy for LifetimeBinderKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for LifetimeBinderKind {
    #[inline]
    fn clone(&self) -> LifetimeBinderKind { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for LifetimeBinderKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                LifetimeBinderKind::FnPtrType => "FnPtrType",
                LifetimeBinderKind::PolyTrait => "PolyTrait",
                LifetimeBinderKind::WhereBound => "WhereBound",
                LifetimeBinderKind::Item => "Item",
                LifetimeBinderKind::ConstItem => "ConstItem",
                LifetimeBinderKind::Function => "Function",
                LifetimeBinderKind::Closure => "Closure",
                LifetimeBinderKind::ImplBlock => "ImplBlock",
                LifetimeBinderKind::ImplAssocType => "ImplAssocType",
            })
    }
}Debug)]
374enum LifetimeBinderKind {
375    FnPtrType,
376    PolyTrait,
377    WhereBound,
378    // Item covers foreign items, ADTs, type aliases, trait associated items and
379    // trait alias associated items.
380    Item,
381    ConstItem,
382    Function,
383    Closure,
384    ImplBlock,
385    // Covers only `impl` associated types.
386    ImplAssocType,
387}
388
389impl LifetimeBinderKind {
390    fn descr(self) -> &'static str {
391        use LifetimeBinderKind::*;
392        match self {
393            FnPtrType => "type",
394            PolyTrait => "bound",
395            WhereBound => "bound",
396            Item | ConstItem => "item",
397            ImplAssocType => "associated type",
398            ImplBlock => "impl block",
399            Function => "function",
400            Closure => "closure",
401        }
402    }
403}
404
405#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LifetimeRib {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "LifetimeRib",
            "kind", &self.kind, "bindings", &&self.bindings)
    }
}Debug)]
406struct LifetimeRib {
407    kind: LifetimeRibKind,
408    // We need to preserve insertion order for async fns.
409    bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
410}
411
412impl LifetimeRib {
413    fn new(kind: LifetimeRibKind) -> LifetimeRib {
414        LifetimeRib { bindings: Default::default(), kind }
415    }
416}
417
418#[derive(#[automatically_derived]
impl ::core::marker::Copy for AliasPossibility { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AliasPossibility {
    #[inline]
    fn clone(&self) -> AliasPossibility { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for AliasPossibility {
    #[inline]
    fn eq(&self, other: &AliasPossibility) -> 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::cmp::Eq for AliasPossibility {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for AliasPossibility {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                AliasPossibility::No => "No",
                AliasPossibility::Maybe => "Maybe",
            })
    }
}Debug)]
419pub(crate) enum AliasPossibility {
420    No,
421    Maybe,
422}
423
424#[derive(#[automatically_derived]
impl<'a, 'ast, 'ra> ::core::marker::Copy for PathSource<'a, 'ast, 'ra> { }Copy, #[automatically_derived]
impl<'a, 'ast, 'ra> ::core::clone::Clone for PathSource<'a, 'ast, 'ra> {
    #[inline]
    fn clone(&self) -> PathSource<'a, 'ast, 'ra> {
        let _: ::core::clone::AssertParamIsClone<AliasPossibility>;
        let _: ::core::clone::AssertParamIsClone<Option<&'ast Expr>>;
        let _: ::core::clone::AssertParamIsClone<Option<&'a Expr>>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<&'ra [Span]>;
        let _: ::core::clone::AssertParamIsClone<Namespace>;
        let _:
                ::core::clone::AssertParamIsClone<&'a PathSource<'a, 'ast,
                'ra>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'a, 'ast, 'ra> ::core::fmt::Debug for PathSource<'a, 'ast, 'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            PathSource::Type => ::core::fmt::Formatter::write_str(f, "Type"),
            PathSource::Trait(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Trait",
                    &__self_0),
            PathSource::Expr(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Expr",
                    &__self_0),
            PathSource::Pat => ::core::fmt::Formatter::write_str(f, "Pat"),
            PathSource::Struct(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Struct",
                    &__self_0),
            PathSource::TupleStruct(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "TupleStruct", __self_0, &__self_1),
            PathSource::TraitItem(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "TraitItem", __self_0, &__self_1),
            PathSource::Delegation =>
                ::core::fmt::Formatter::write_str(f, "Delegation"),
            PathSource::ExternItemImpl =>
                ::core::fmt::Formatter::write_str(f, "ExternItemImpl"),
            PathSource::PreciseCapturingArg(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "PreciseCapturingArg", &__self_0),
            PathSource::ReturnTypeNotation =>
                ::core::fmt::Formatter::write_str(f, "ReturnTypeNotation"),
            PathSource::DefineOpaques =>
                ::core::fmt::Formatter::write_str(f, "DefineOpaques"),
            PathSource::Macro =>
                ::core::fmt::Formatter::write_str(f, "Macro"),
            PathSource::Module =>
                ::core::fmt::Formatter::write_str(f, "Module"),
        }
    }
}Debug)]
425pub(crate) enum PathSource<'a, 'ast, 'ra> {
426    /// Type paths `Path`.
427    Type,
428    /// Trait paths in bounds or impls.
429    Trait(AliasPossibility),
430    /// Expression paths `path`, with optional parent context.
431    Expr(Option<&'ast Expr>),
432    /// Paths in path patterns `Path`.
433    Pat,
434    /// Paths in struct expressions and patterns `Path { .. }`.
435    Struct(Option<&'a Expr>),
436    /// Paths in tuple struct patterns `Path(..)`.
437    TupleStruct(Span, &'ra [Span]),
438    /// `m::A::B` in `<T as m::A>::B::C`.
439    ///
440    /// Second field holds the "cause" of this one, i.e. the context within
441    /// which the trait item is resolved. Used for diagnostics.
442    TraitItem(Namespace, &'a PathSource<'a, 'ast, 'ra>),
443    /// Paths in delegation item
444    Delegation,
445    /// Paths in externally implementable item declarations.
446    ExternItemImpl,
447    /// An arg in a `use<'a, N>` precise-capturing bound.
448    PreciseCapturingArg(Namespace),
449    /// Paths that end with `(..)`, for return type notation.
450    ReturnTypeNotation,
451    /// Paths from `#[define_opaque]` attributes
452    DefineOpaques,
453    /// Resolving a macro
454    Macro,
455    /// Paths for module or crate root. Used for restrictions.
456    Module,
457}
458
459impl PathSource<'_, '_, '_> {
460    fn namespace(self) -> Namespace {
461        match self {
462            PathSource::Type
463            | PathSource::Trait(_)
464            | PathSource::Struct(_)
465            | PathSource::DefineOpaques
466            | PathSource::Module => TypeNS,
467            PathSource::Expr(..)
468            | PathSource::Pat
469            | PathSource::TupleStruct(..)
470            | PathSource::Delegation
471            | PathSource::ExternItemImpl
472            | PathSource::ReturnTypeNotation => ValueNS,
473            PathSource::TraitItem(ns, _) => ns,
474            PathSource::PreciseCapturingArg(ns) => ns,
475            PathSource::Macro => MacroNS,
476        }
477    }
478
479    fn defer_to_typeck(self) -> bool {
480        match self {
481            PathSource::Type
482            | PathSource::Expr(..)
483            | PathSource::Pat
484            | PathSource::Struct(_)
485            | PathSource::TupleStruct(..)
486            | PathSource::ReturnTypeNotation => true,
487            PathSource::Trait(_)
488            | PathSource::TraitItem(..)
489            | PathSource::DefineOpaques
490            | PathSource::Delegation
491            | PathSource::ExternItemImpl
492            | PathSource::PreciseCapturingArg(..)
493            | PathSource::Macro
494            | PathSource::Module => false,
495        }
496    }
497
498    fn descr_expected(self) -> &'static str {
499        match &self {
500            PathSource::DefineOpaques => "type alias or associated type with opaqaue types",
501            PathSource::Type => "type",
502            PathSource::Trait(_) => "trait",
503            PathSource::Pat => "unit struct, unit variant or constant",
504            PathSource::Struct(_) => "struct, variant or union type",
505            PathSource::TraitItem(ValueNS, PathSource::TupleStruct(..))
506            | PathSource::TupleStruct(..) => "tuple struct or tuple variant",
507            PathSource::TraitItem(ns, _) => match ns {
508                TypeNS => "associated type",
509                ValueNS => "method or associated constant",
510                MacroNS => ::rustc_middle::util::bug::bug_fmt(format_args!("associated macro"))bug!("associated macro"),
511            },
512            PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
513                // "function" here means "anything callable" rather than `DefKind::Fn`,
514                // this is not precise but usually more helpful than just "value".
515                Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
516                    // the case of `::some_crate()`
517                    ExprKind::Path(_, path)
518                        if let [segment, _] = path.segments.as_slice()
519                            && segment.ident.name == kw::PathRoot =>
520                    {
521                        "external crate"
522                    }
523                    ExprKind::Path(_, path)
524                        if let Some(segment) = path.segments.last()
525                            && let Some(c) = segment.ident.to_string().chars().next()
526                            && c.is_uppercase() =>
527                    {
528                        "function, tuple struct or tuple variant"
529                    }
530                    _ => "function",
531                },
532                _ => "value",
533            },
534            PathSource::ReturnTypeNotation | PathSource::Delegation => "function",
535            PathSource::ExternItemImpl => "function or static",
536            PathSource::PreciseCapturingArg(..) => "type or const parameter",
537            PathSource::Macro => "macro",
538            PathSource::Module => "module",
539        }
540    }
541
542    fn is_call(self) -> bool {
543        #[allow(non_exhaustive_omitted_patterns)] match self {
    PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })) => true,
    _ => false,
}matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
544    }
545
546    pub(crate) fn is_expected(self, res: Res) -> bool {
547        match self {
548            PathSource::DefineOpaques => {
549                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum |
        DefKind::TyAlias | DefKind::AssocTy, _) | Res::SelfTyAlias { .. } =>
        true,
    _ => false,
}matches!(
550                    res,
551                    Res::Def(
552                        DefKind::Struct
553                            | DefKind::Union
554                            | DefKind::Enum
555                            | DefKind::TyAlias
556                            | DefKind::AssocTy,
557                        _
558                    ) | Res::SelfTyAlias { .. }
559                )
560            }
561            PathSource::Type => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::Trait
        | DefKind::TraitAlias | DefKind::TyAlias | DefKind::AssocTy |
        DefKind::TyParam | DefKind::OpaqueTy | DefKind::ForeignTy, _) |
        Res::PrimTy(..) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } =>
        true,
    _ => false,
}matches!(
562                res,
563                Res::Def(
564                    DefKind::Struct
565                        | DefKind::Union
566                        | DefKind::Enum
567                        | DefKind::Trait
568                        | DefKind::TraitAlias
569                        | DefKind::TyAlias
570                        | DefKind::AssocTy
571                        | DefKind::TyParam
572                        | DefKind::OpaqueTy
573                        | DefKind::ForeignTy,
574                    _,
575                ) | Res::PrimTy(..)
576                    | Res::SelfTyParam { .. }
577                    | Res::SelfTyAlias { .. }
578            ),
579            PathSource::Trait(AliasPossibility::No) => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Trait, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Trait, _)),
580            PathSource::Trait(AliasPossibility::Maybe) => {
581                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
582            }
583            PathSource::Expr(..) => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn) |
        DefKind::Const { .. } | DefKind::Static { .. } | DefKind::Fn |
        DefKind::AssocFn | DefKind::AssocConst { .. } | DefKind::ConstParam,
        _) | Res::Local(..) | Res::SelfCtor(..) => true,
    _ => false,
}matches!(
584                res,
585                Res::Def(
586                    DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
587                        | DefKind::Const { .. }
588                        | DefKind::Static { .. }
589                        | DefKind::Fn
590                        | DefKind::AssocFn
591                        | DefKind::AssocConst { .. }
592                        | DefKind::ConstParam,
593                    _,
594                ) | Res::Local(..)
595                    | Res::SelfCtor(..)
596            ),
597            PathSource::Pat => {
598                res.expected_in_unit_struct_pat()
599                    || #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Const { .. } | DefKind::AssocConst { .. }, _) => true,
    _ => false,
}matches!(
600                        res,
601                        Res::Def(DefKind::Const { .. } | DefKind::AssocConst { .. }, _)
602                    )
603            }
604            PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
605            PathSource::Struct(_) => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Variant |
        DefKind::TyAlias | DefKind::AssocTy, _) | Res::SelfTyParam { .. } |
        Res::SelfTyAlias { .. } => true,
    _ => false,
}matches!(
606                res,
607                Res::Def(
608                    DefKind::Struct
609                        | DefKind::Union
610                        | DefKind::Variant
611                        | DefKind::TyAlias
612                        | DefKind::AssocTy,
613                    _,
614                ) | Res::SelfTyParam { .. }
615                    | Res::SelfTyAlias { .. }
616            ),
617            PathSource::TraitItem(ns, _) => match res {
618                Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn, _) if ns == ValueNS => true,
619                Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
620                _ => false,
621            },
622            PathSource::ReturnTypeNotation => match res {
623                Res::Def(DefKind::AssocFn, _) => true,
624                _ => false,
625            },
626            PathSource::Delegation => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Fn | DefKind::AssocFn, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Fn | DefKind::AssocFn, _)),
627            PathSource::ExternItemImpl => {
628                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) |
        DefKind::Static { .. }, _) => true,
    _ => false,
}matches!(
629                    res,
630                    Res::Def(
631                        DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::Static { .. },
632                        _
633                    )
634                )
635            }
636            PathSource::PreciseCapturingArg(ValueNS) => {
637                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::ConstParam, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::ConstParam, _))
638            }
639            // We allow `SelfTyAlias` here so we can give a more descriptive error later.
640            PathSource::PreciseCapturingArg(TypeNS) => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } |
        Res::SelfTyAlias { .. } => true,
    _ => false,
}matches!(
641                res,
642                Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }
643            ),
644            PathSource::PreciseCapturingArg(MacroNS) => false,
645            PathSource::Macro => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Macro(_), _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Macro(_), _)),
646            PathSource::Module => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Mod, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Mod, _)),
647        }
648    }
649
650    fn error_code(self, has_unexpected_resolution: bool) -> ErrCode {
651        match (self, has_unexpected_resolution) {
652            (PathSource::Trait(_), true) => E0404,
653            (PathSource::Trait(_), false) => E0405,
654            (PathSource::Type | PathSource::DefineOpaques, true) => E0573,
655            (PathSource::Type | PathSource::DefineOpaques, false) => E0425,
656            (PathSource::Struct(_), true) => E0574,
657            (PathSource::Struct(_), false) => E0422,
658            (PathSource::Expr(..), true)
659            | (PathSource::Delegation, true)
660            | (PathSource::ExternItemImpl, true) => E0423,
661            (PathSource::Expr(..), false)
662            | (PathSource::Delegation, false)
663            | (PathSource::ExternItemImpl, false) => E0425,
664            (PathSource::Pat | PathSource::TupleStruct(..), true) => E0532,
665            (PathSource::Pat | PathSource::TupleStruct(..), false) => E0531,
666            (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, true) => E0575,
667            (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, false) => E0576,
668            (PathSource::PreciseCapturingArg(..), true) => E0799,
669            (PathSource::PreciseCapturingArg(..), false) => E0800,
670            (PathSource::Macro, _) => E0425,
671            // FIXME: There is no dedicated error code for this case yet.
672            // E0577 already covers the same situation for visibilities,
673            // so we reuse it here for now. It may make sense to generalize
674            // it for restrictions in the future.
675            (PathSource::Module, true) => E0577,
676            (PathSource::Module, false) => E0433,
677        }
678    }
679}
680
681/// At this point for most items we can answer whether that item is exported or not,
682/// but some items like impls require type information to determine exported-ness, so we make a
683/// conservative estimate for them (e.g. based on nominal visibility).
684#[derive(#[automatically_derived]
impl<'a> ::core::clone::Clone for MaybeExported<'a> {
    #[inline]
    fn clone(&self) -> MaybeExported<'a> {
        let _: ::core::clone::AssertParamIsClone<NodeId>;
        let _: ::core::clone::AssertParamIsClone<Option<DefId>>;
        let _:
                ::core::clone::AssertParamIsClone<Result<DefId,
                &'a ast::Visibility>>;
        let _: ::core::clone::AssertParamIsClone<&'a ast::Visibility>;
        *self
    }
}Clone, #[automatically_derived]
impl<'a> ::core::marker::Copy for MaybeExported<'a> { }Copy)]
685enum MaybeExported<'a> {
686    Ok(NodeId),
687    Impl(Option<DefId>),
688    ImplItem(Result<DefId, &'a ast::Visibility>),
689    NestedUse(&'a ast::Visibility),
690}
691
692impl MaybeExported<'_> {
693    fn eval(self, r: &Resolver<'_, '_>) -> bool {
694        let def_id = match self {
695            MaybeExported::Ok(node_id) => Some(if r.current_owner.id == node_id {
696                r.current_owner.def_id
697            } else {
698                r.current_owner.node_id_to_def_id[&node_id]
699            }),
700            MaybeExported::Impl(Some(trait_def_id)) | MaybeExported::ImplItem(Ok(trait_def_id)) => {
701                trait_def_id.as_local()
702            }
703            MaybeExported::Impl(None) => return true,
704            MaybeExported::ImplItem(Err(vis)) | MaybeExported::NestedUse(vis) => {
705                return vis.kind.is_pub();
706            }
707        };
708        def_id.is_none_or(|def_id| r.effective_visibilities.is_exported(def_id))
709    }
710}
711
712/// Used for recording UnnecessaryQualification.
713#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for UnnecessaryQualification<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "UnnecessaryQualification", "decl", &self.decl, "node_id",
            &self.node_id, "path_span", &self.path_span, "removal_span",
            &&self.removal_span)
    }
}Debug)]
714pub(crate) struct UnnecessaryQualification<'ra> {
715    pub decl: LateDecl<'ra>,
716    pub node_id: NodeId,
717    pub path_span: Span,
718    pub removal_span: Span,
719}
720
721#[derive(#[automatically_derived]
impl<'ast> ::core::default::Default for DiagMetadata<'ast> {
    #[inline]
    fn default() -> DiagMetadata<'ast> {
        DiagMetadata {
            current_trait_assoc_items: ::core::default::Default::default(),
            current_self_type: ::core::default::Default::default(),
            current_self_item: ::core::default::Default::default(),
            current_item: ::core::default::Default::default(),
            currently_processing_generic_args: ::core::default::Default::default(),
            current_function: ::core::default::Default::default(),
            unused_labels: ::core::default::Default::default(),
            current_let_binding: ::core::default::Default::default(),
            current_pat: ::core::default::Default::default(),
            in_if_condition: ::core::default::Default::default(),
            in_assignment: ::core::default::Default::default(),
            is_assign_rhs: ::core::default::Default::default(),
            in_non_gat_assoc_type: ::core::default::Default::default(),
            in_range: ::core::default::Default::default(),
            current_trait_object: ::core::default::Default::default(),
            current_where_predicate: ::core::default::Default::default(),
            current_type_path: ::core::default::Default::default(),
            current_impl_items: ::core::default::Default::default(),
            current_impl_item: ::core::default::Default::default(),
            currently_processing_impl_trait: ::core::default::Default::default(),
            current_elision_failures: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]
impl<'ast> ::core::fmt::Debug for DiagMetadata<'ast> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["current_trait_assoc_items", "current_self_type",
                        "current_self_item", "current_item",
                        "currently_processing_generic_args", "current_function",
                        "unused_labels", "current_let_binding", "current_pat",
                        "in_if_condition", "in_assignment", "is_assign_rhs",
                        "in_non_gat_assoc_type", "in_range", "current_trait_object",
                        "current_where_predicate", "current_type_path",
                        "current_impl_items", "current_impl_item",
                        "currently_processing_impl_trait",
                        "current_elision_failures"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.current_trait_assoc_items, &self.current_self_type,
                        &self.current_self_item, &self.current_item,
                        &self.currently_processing_generic_args,
                        &self.current_function, &self.unused_labels,
                        &self.current_let_binding, &self.current_pat,
                        &self.in_if_condition, &self.in_assignment,
                        &self.is_assign_rhs, &self.in_non_gat_assoc_type,
                        &self.in_range, &self.current_trait_object,
                        &self.current_where_predicate, &self.current_type_path,
                        &self.current_impl_items, &self.current_impl_item,
                        &self.currently_processing_impl_trait,
                        &&self.current_elision_failures];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "DiagMetadata",
            names, values)
    }
}Debug)]
722pub(crate) struct DiagMetadata<'ast> {
723    /// The current trait's associated items' ident, used for diagnostic suggestions.
724    current_trait_assoc_items: Option<&'ast [Box<AssocItem>]>,
725
726    /// The current self type if inside an impl (used for better errors).
727    pub(crate) current_self_type: Option<Ty>,
728
729    /// The current self item if inside an ADT (used for better errors).
730    current_self_item: Option<NodeId>,
731
732    /// The current item being evaluated (used for suggestions and more detail in errors).
733    pub(crate) current_item: Option<&'ast Item>,
734
735    /// When processing generic arguments and encountering an unresolved ident not found,
736    /// suggest introducing a type or const param depending on the context.
737    currently_processing_generic_args: bool,
738
739    /// The current enclosing (non-closure) function (used for better errors).
740    current_function: Option<(FnKind<'ast>, Span)>,
741
742    /// A list of labels as of yet unused. Labels will be removed from this map when
743    /// they are used (in a `break` or `continue` statement)
744    unused_labels: FxIndexMap<NodeId, Span>,
745
746    /// Only used for better errors on `let <pat>: <expr, not type>;`.
747    current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
748
749    current_pat: Option<&'ast Pat>,
750
751    /// Used to detect possible `if let` written without `let` and to provide structured suggestion.
752    in_if_condition: Option<&'ast Expr>,
753
754    /// Used to detect possible new binding written without `let` and to provide structured suggestion.
755    in_assignment: Option<&'ast Expr>,
756    is_assign_rhs: bool,
757
758    /// If we are setting an associated type in trait impl, is it a non-GAT type?
759    in_non_gat_assoc_type: Option<bool>,
760
761    /// Used to detect possible `.` -> `..` typo when calling methods.
762    in_range: Option<(&'ast Expr, &'ast Expr)>,
763
764    /// If we are currently in a trait object definition. Used to point at the bounds when
765    /// encountering a struct or enum.
766    current_trait_object: Option<&'ast [ast::GenericBound]>,
767
768    /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
769    current_where_predicate: Option<&'ast WherePredicate>,
770
771    current_type_path: Option<&'ast Ty>,
772
773    /// The current impl items (used to suggest).
774    current_impl_items: Option<&'ast [Box<AssocItem>]>,
775
776    /// The current impl items (used to suggest).
777    current_impl_item: Option<&'ast AssocItem>,
778
779    /// When processing impl trait
780    currently_processing_impl_trait: Option<(TraitRef, Ty)>,
781
782    /// Accumulate the errors due to missed lifetime elision,
783    /// and report them all at once for each function.
784    current_elision_failures:
785        Vec<(MissingLifetime, LifetimeElisionCandidate, Either<NodeId, Range<NodeId>>)>,
786}
787
788struct LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
789    r: &'a mut Resolver<'ra, 'tcx>,
790
791    /// The module that represents the current item scope.
792    parent_scope: ParentScope<'ra>,
793
794    /// The current set of local scopes for types and values.
795    ribs: PerNS<Vec<Rib<'ra>>>,
796
797    /// Previous popped `rib`, only used for diagnostic.
798    last_block_rib: Option<Rib<'ra>>,
799
800    /// The current set of local scopes, for labels.
801    label_ribs: Vec<Rib<'ra, NodeId>>,
802
803    /// The current set of local scopes for lifetimes.
804    lifetime_ribs: Vec<LifetimeRib>,
805
806    /// We are looking for lifetimes in an elision context.
807    /// The set contains all the resolutions that we encountered so far.
808    /// They will be used to determine the correct lifetime for the fn return type.
809    /// The `LifetimeElisionCandidate` is used for diagnostics, to suggest introducing named
810    /// lifetimes.
811    lifetime_elision_candidates: Option<Vec<(LifetimeRes, LifetimeElisionCandidate)>>,
812
813    /// The trait that the current context can refer to.
814    current_trait_ref: Option<(Module<'ra>, TraitRef)>,
815
816    /// Fields used to add information to diagnostic errors.
817    diag_metadata: Box<DiagMetadata<'ast>>,
818
819    /// State used to know whether to ignore resolution errors for function bodies.
820    ///
821    /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
822    /// In most cases this will be `None`, in which case errors will always be reported.
823    /// If it is `true`, then it will be updated when entering a nested function or trait body.
824    in_func_body: bool,
825
826    /// Count the number of places a lifetime is used.
827    lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
828}
829
830impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for LateResolutionVisitor<'_, '_, 'ra, 'tcx> {
831    fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
832        &self.r
833    }
834}
835impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for LateResolutionVisitor<'_, '_, 'ra, 'tcx> {
836    fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
837        &mut self.r
838    }
839}
840
841/// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
842impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
843    fn visit_attribute(&mut self, _: &'ast Attribute) {
844        // We do not want to resolve expressions that appear in attributes,
845        // as they do not correspond to actual code.
846    }
847    fn visit_item(&mut self, item: &'ast Item) {
848        let prev = replace(&mut self.diag_metadata.current_item, Some(item));
849        // Always report errors in items we just entered.
850        let old_ignore = replace(&mut self.in_func_body, false);
851        with_owner(self, item.id, |this| {
852            this.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item))
853        });
854        self.in_func_body = old_ignore;
855        self.diag_metadata.current_item = prev;
856    }
857    fn visit_arm(&mut self, arm: &'ast Arm) {
858        self.resolve_arm(arm);
859    }
860    fn visit_block(&mut self, block: &'ast Block) {
861        let old_macro_rules = self.parent_scope.macro_rules;
862        self.resolve_block(block);
863        self.parent_scope.macro_rules = old_macro_rules;
864    }
865    fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
866        ::rustc_middle::util::bug::bug_fmt(format_args!("encountered anon const without a manual call to `resolve_anon_const`: {0:#?}",
        constant));bug!("encountered anon const without a manual call to `resolve_anon_const`: {constant:#?}");
867    }
868    fn visit_expr(&mut self, expr: &'ast Expr) {
869        self.resolve_expr(expr, None);
870    }
871    fn visit_pat(&mut self, p: &'ast Pat) {
872        let prev = self.diag_metadata.current_pat;
873        self.diag_metadata.current_pat = Some(p);
874
875        if let PatKind::Guard(subpat, _) = &p.kind {
876            // We walk the guard expression in `resolve_pattern_inner`. Don't resolve it twice.
877            self.visit_pat(subpat);
878        } else {
879            visit::walk_pat(self, p);
880        }
881
882        self.diag_metadata.current_pat = prev;
883    }
884    fn visit_local(&mut self, local: &'ast Local) {
885        let local_spans = match local.pat.kind {
886            // We check for this to avoid tuple struct fields.
887            PatKind::Wild => None,
888            _ => Some((
889                local.pat.span,
890                local.ty.as_ref().map(|ty| ty.span),
891                local.kind.init().map(|init| init.span),
892            )),
893        };
894        let original = replace(&mut self.diag_metadata.current_let_binding, local_spans);
895        self.resolve_local(local);
896        self.diag_metadata.current_let_binding = original;
897    }
898    fn visit_ty(&mut self, ty: &'ast Ty) {
899        let prev = self.diag_metadata.current_trait_object;
900        let prev_ty = self.diag_metadata.current_type_path;
901        match &ty.kind {
902            TyKind::Ref(None, _) | TyKind::PinnedRef(None, _) => {
903                // Elided lifetime in reference: we resolve as if there was some lifetime `'_` with
904                // NodeId `ty.id`.
905                // This span will be used in case of elision failure.
906                let span = self.r.tcx.sess.source_map().start_point(ty.span);
907                self.resolve_elided_lifetime(ty.id, span);
908                visit::walk_ty(self, ty);
909            }
910            TyKind::Path(qself, path) => {
911                self.diag_metadata.current_type_path = Some(ty);
912
913                // If we have a path that ends with `(..)`, then it must be
914                // return type notation. Resolve that path in the *value*
915                // namespace.
916                let source = if let Some(seg) = path.segments.last()
917                    && let Some(args) = &seg.args
918                    && #[allow(non_exhaustive_omitted_patterns)] match **args {
    GenericArgs::ParenthesizedElided(..) => true,
    _ => false,
}matches!(**args, GenericArgs::ParenthesizedElided(..))
919                {
920                    PathSource::ReturnTypeNotation
921                } else {
922                    PathSource::Type
923                };
924
925                self.smart_resolve_path(ty.id, qself, path, source);
926
927                // Check whether we should interpret this as a bare trait object.
928                if qself.is_none()
929                    && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
930                    && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) =
931                        partial_res.full_res()
932                {
933                    // This path is actually a bare trait object. In case of a bare `Fn`-trait
934                    // object with anonymous lifetimes, we need this rib to correctly place the
935                    // synthetic lifetimes.
936                    let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
937                    self.with_generic_param_rib(
938                        &[],
939                        RibKind::Normal,
940                        ty.id,
941                        LifetimeBinderKind::PolyTrait,
942                        span,
943                        |this| this.visit_path(path),
944                    );
945                } else {
946                    visit::walk_ty(self, ty)
947                }
948            }
949            TyKind::ImplicitSelf => {
950                let self_ty = Ident::with_dummy_span(kw::SelfUpper);
951                let res = self
952                    .resolve_ident_in_lexical_scope(
953                        self_ty,
954                        TypeNS,
955                        Some(Finalize::new(ty.id, ty.span)),
956                        None,
957                    )
958                    .map_or(Res::Err, |d| d.res());
959                self.r.record_partial_res(ty.id, PartialRes::new(res));
960                visit::walk_ty(self, ty)
961            }
962            TyKind::ImplTrait(..) => {
963                let candidates = self.lifetime_elision_candidates.take();
964                self.with_lifetime_rib(LifetimeRibKind::ImplTrait, |this| visit::walk_ty(this, ty));
965                self.lifetime_elision_candidates = candidates;
966            }
967            TyKind::TraitObject(bounds, ..) => {
968                self.diag_metadata.current_trait_object = Some(&bounds[..]);
969                visit::walk_ty(self, ty)
970            }
971            TyKind::FnPtr(fn_ptr) => {
972                let span = ty.span.shrink_to_lo().to(fn_ptr.decl_span.shrink_to_lo());
973                self.with_generic_param_rib(
974                    &fn_ptr.generic_params,
975                    RibKind::Normal,
976                    ty.id,
977                    LifetimeBinderKind::FnPtrType,
978                    span,
979                    |this| {
980                        this.visit_generic_params(&fn_ptr.generic_params, false);
981                        this.resolve_fn_signature(
982                            ty.id,
983                            false,
984                            // We don't need to deal with patterns in parameters, because
985                            // they are not possible for foreign or bodiless functions.
986                            fn_ptr.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
987                            &fn_ptr.decl.output,
988                            false,
989                        )
990                    },
991                )
992            }
993            TyKind::UnsafeBinder(unsafe_binder) => {
994                let span = ty.span.shrink_to_lo().to(unsafe_binder.inner_ty.span.shrink_to_lo());
995                self.with_generic_param_rib(
996                    &unsafe_binder.generic_params,
997                    RibKind::Normal,
998                    ty.id,
999                    LifetimeBinderKind::FnPtrType,
1000                    span,
1001                    |this| {
1002                        this.visit_generic_params(&unsafe_binder.generic_params, false);
1003                        this.with_lifetime_rib(
1004                            // We don't allow anonymous `unsafe &'_ ()` binders,
1005                            // although I guess we could.
1006                            LifetimeRibKind::AnonymousReportError,
1007                            |this| this.visit_ty(&unsafe_binder.inner_ty),
1008                        );
1009                    },
1010                )
1011            }
1012            TyKind::Array(element_ty, length) => {
1013                self.visit_ty(element_ty);
1014                self.resolve_anon_const(length, AnonConstKind::ConstArg(IsRepeatExpr::No));
1015            }
1016            _ => visit::walk_ty(self, ty),
1017        }
1018        self.diag_metadata.current_trait_object = prev;
1019        self.diag_metadata.current_type_path = prev_ty;
1020    }
1021
1022    fn visit_ty_pat(&mut self, t: &'ast TyPat) -> Self::Result {
1023        match &t.kind {
1024            TyPatKind::Range(start, end, _) => {
1025                if let Some(start) = start {
1026                    self.resolve_anon_const(start, AnonConstKind::ConstArg(IsRepeatExpr::No));
1027                }
1028                if let Some(end) = end {
1029                    self.resolve_anon_const(end, AnonConstKind::ConstArg(IsRepeatExpr::No));
1030                }
1031            }
1032            TyPatKind::Or(patterns) => {
1033                for pat in patterns {
1034                    self.visit_ty_pat(pat)
1035                }
1036            }
1037            TyPatKind::NotNull | TyPatKind::Err(_) => {}
1038        }
1039    }
1040
1041    fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
1042        let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
1043        self.with_generic_param_rib(
1044            &tref.bound_generic_params,
1045            RibKind::Normal,
1046            tref.trait_ref.ref_id,
1047            LifetimeBinderKind::PolyTrait,
1048            span,
1049            |this| {
1050                this.visit_generic_params(&tref.bound_generic_params, false);
1051                this.smart_resolve_path(
1052                    tref.trait_ref.ref_id,
1053                    &None,
1054                    &tref.trait_ref.path,
1055                    PathSource::Trait(AliasPossibility::Maybe),
1056                );
1057                this.visit_trait_ref(&tref.trait_ref);
1058            },
1059        );
1060    }
1061    fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
1062        with_owner(self, foreign_item.id, |this| {
1063            this.resolve_doc_links(&foreign_item.attrs, MaybeExported::Ok(foreign_item.id));
1064            let def_kind = this.r.tcx.def_kind(this.r.current_owner.def_id);
1065            match foreign_item.kind {
1066                ForeignItemKind::TyAlias(TyAlias { ref generics, .. }) => {
1067                    this.with_generic_param_rib(
1068                        &generics.params,
1069                        RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1070                        foreign_item.id,
1071                        LifetimeBinderKind::Item,
1072                        generics.span,
1073                        |this| visit::walk_item(this, foreign_item),
1074                    );
1075                }
1076                ForeignItemKind::Fn(Fn { ref generics, .. }) => {
1077                    this.with_generic_param_rib(
1078                        &generics.params,
1079                        RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1080                        foreign_item.id,
1081                        LifetimeBinderKind::Function,
1082                        generics.span,
1083                        |this| visit::walk_item(this, foreign_item),
1084                    );
1085                }
1086                ForeignItemKind::Static(..) => {
1087                    this.with_static_rib(def_kind, |this| visit::walk_item(this, foreign_item))
1088                }
1089                ForeignItemKind::MacCall(..) => {
1090                    {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
1091                }
1092            }
1093        })
1094    }
1095    fn visit_fn(&mut self, fn_kind: FnKind<'ast>, _: &AttrVec, sp: Span, fn_id: NodeId) {
1096        let previous_value = self.diag_metadata.current_function;
1097        match fn_kind {
1098            // Bail if the function is foreign, and thus cannot validly have
1099            // a body, or if there's no body for some other reason.
1100            FnKind::Fn(FnCtxt::Foreign, _, Fn { sig, ident, generics, .. })
1101            | FnKind::Fn(_, _, Fn { sig, ident, generics, body: None, .. }) => {
1102                self.visit_fn_header(&sig.header);
1103                self.visit_ident(ident);
1104                self.visit_generics(generics);
1105                self.resolve_fn_signature(
1106                    fn_id,
1107                    sig.decl.has_self(),
1108                    sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1109                    &sig.decl.output,
1110                    false,
1111                );
1112                return;
1113            }
1114            FnKind::Fn(..) => {
1115                self.diag_metadata.current_function = Some((fn_kind, sp));
1116            }
1117            // Do not update `current_function` for closures: it suggests `self` parameters.
1118            FnKind::Closure(..) => {}
1119        };
1120        {
    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/late.rs:1120",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1120u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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!("(resolving function) entering function")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("(resolving function) entering function");
1121
1122        if let FnKind::Fn(_, _, f) = fn_kind {
1123            self.resolve_eii(&f.eii_impls);
1124        }
1125
1126        // Create a value rib for the function.
1127        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
1128            // Create a label rib for the function.
1129            this.with_label_rib(RibKind::FnOrCoroutine, |this| {
1130                match fn_kind {
1131                    FnKind::Fn(_, _, Fn { sig, generics, contract, body, .. }) => {
1132                        this.visit_generics(generics);
1133
1134                        let declaration = &sig.decl;
1135                        let coro_node_id = sig
1136                            .header
1137                            .coroutine_kind
1138                            .map(|coroutine_kind| coroutine_kind.return_id());
1139
1140                        this.resolve_fn_signature(
1141                            fn_id,
1142                            declaration.has_self(),
1143                            declaration
1144                                .inputs
1145                                .iter()
1146                                .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
1147                            &declaration.output,
1148                            coro_node_id.is_some(),
1149                        );
1150
1151                        if let Some(contract) = contract {
1152                            this.visit_contract(contract);
1153                        }
1154
1155                        if let Some(body) = body {
1156                            // Ignore errors in function bodies if this is rustdoc
1157                            // Be sure not to set this until the function signature has been resolved.
1158                            let previous_state = replace(&mut this.in_func_body, true);
1159                            // We only care block in the same function
1160                            this.last_block_rib = None;
1161                            // Resolve the function body, potentially inside the body of an async closure
1162                            this.with_lifetime_rib(
1163                                LifetimeRibKind::Elided(LifetimeRes::Infer),
1164                                |this| this.visit_block(body),
1165                            );
1166
1167                            {
    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/late.rs:1167",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1167u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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!("(resolving function) leaving function")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("(resolving function) leaving function");
1168                            this.in_func_body = previous_state;
1169                        }
1170                    }
1171                    FnKind::Closure(binder, _, declaration, body) => {
1172                        this.visit_closure_binder(binder);
1173
1174                        this.with_lifetime_rib(
1175                            match binder {
1176                                // We do not have any explicit generic lifetime parameter.
1177                                ClosureBinder::NotPresent => {
1178                                    LifetimeRibKind::AnonymousCreateParameter {
1179                                        binder: fn_id,
1180                                        report_in_path: false,
1181                                    }
1182                                }
1183                                ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1184                            },
1185                            // Add each argument to the rib.
1186                            |this| this.resolve_params(&declaration.inputs),
1187                        );
1188                        this.with_lifetime_rib(
1189                            match binder {
1190                                ClosureBinder::NotPresent => {
1191                                    LifetimeRibKind::Elided(LifetimeRes::Infer)
1192                                }
1193                                ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1194                            },
1195                            |this| visit::walk_fn_ret_ty(this, &declaration.output),
1196                        );
1197
1198                        // Ignore errors in function bodies if this is rustdoc
1199                        // Be sure not to set this until the function signature has been resolved.
1200                        let previous_state = replace(&mut this.in_func_body, true);
1201                        // Resolve the function body, potentially inside the body of an async closure
1202                        this.with_lifetime_rib(
1203                            LifetimeRibKind::Elided(LifetimeRes::Infer),
1204                            |this| this.visit_expr(body),
1205                        );
1206
1207                        {
    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/late.rs:1207",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1207u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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!("(resolving function) leaving function")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("(resolving function) leaving function");
1208                        this.in_func_body = previous_state;
1209                    }
1210                }
1211            })
1212        });
1213        self.diag_metadata.current_function = previous_value;
1214    }
1215
1216    fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1217        self.resolve_lifetime(lifetime, use_ctxt)
1218    }
1219
1220    fn visit_precise_capturing_arg(&mut self, arg: &'ast PreciseCapturingArg) {
1221        match arg {
1222            // Lower the lifetime regularly; we'll resolve the lifetime and check
1223            // it's a parameter later on in HIR lowering.
1224            PreciseCapturingArg::Lifetime(_) => {}
1225
1226            PreciseCapturingArg::Arg(path, id) => {
1227                // we want `impl use<C>` to try to resolve `C` as both a type parameter or
1228                // a const parameter. Since the resolver specifically doesn't allow having
1229                // two generic params with the same name, even if they're a different namespace,
1230                // it doesn't really matter which we try resolving first, but just like
1231                // `Ty::Param` we just fall back to the value namespace only if it's missing
1232                // from the type namespace.
1233                let mut check_ns = |ns| {
1234                    self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns).is_some()
1235                };
1236                // Like `Ty::Param`, we try resolving this as both a const and a type.
1237                if !check_ns(TypeNS) && check_ns(ValueNS) {
1238                    self.smart_resolve_path(
1239                        *id,
1240                        &None,
1241                        path,
1242                        PathSource::PreciseCapturingArg(ValueNS),
1243                    );
1244                } else {
1245                    self.smart_resolve_path(
1246                        *id,
1247                        &None,
1248                        path,
1249                        PathSource::PreciseCapturingArg(TypeNS),
1250                    );
1251                }
1252            }
1253        }
1254
1255        visit::walk_precise_capturing_arg(self, arg)
1256    }
1257
1258    fn visit_generics(&mut self, generics: &'ast Generics) {
1259        self.visit_generic_params(&generics.params, self.diag_metadata.current_self_item.is_some());
1260        for p in &generics.where_clause.predicates {
1261            self.visit_where_predicate(p);
1262        }
1263    }
1264
1265    fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
1266        match b {
1267            ClosureBinder::NotPresent => {}
1268            ClosureBinder::For { generic_params, .. } => {
1269                self.visit_generic_params(
1270                    generic_params,
1271                    self.diag_metadata.current_self_item.is_some(),
1272                );
1273            }
1274        }
1275    }
1276
1277    fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
1278        {
    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/late.rs:1278",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1278u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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!("visit_generic_arg({0:?})",
                                                    arg) as &dyn Value))])
            });
    } else { ; }
};debug!("visit_generic_arg({:?})", arg);
1279        let prev = replace(&mut self.diag_metadata.currently_processing_generic_args, true);
1280        match arg {
1281            GenericArg::Type(ty) => {
1282                // We parse const arguments as path types as we cannot distinguish them during
1283                // parsing. We try to resolve that ambiguity by attempting resolution the type
1284                // namespace first, and if that fails we try again in the value namespace. If
1285                // resolution in the value namespace succeeds, we have an generic const argument on
1286                // our hands.
1287                if let TyKind::Path(None, ref path) = ty.kind
1288                    // We cannot disambiguate multi-segment paths right now as that requires type
1289                    // checking.
1290                    && path.is_potential_trivial_const_arg()
1291                {
1292                    let mut check_ns = |ns| {
1293                        self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
1294                            .is_some()
1295                    };
1296                    if !check_ns(TypeNS) && check_ns(ValueNS) {
1297                        self.resolve_anon_const_manual(
1298                            true,
1299                            AnonConstKind::ConstArg(IsRepeatExpr::No),
1300                            |this| {
1301                                this.smart_resolve_path(ty.id, &None, path, PathSource::Expr(None));
1302                                this.visit_path(path);
1303                            },
1304                        );
1305
1306                        self.diag_metadata.currently_processing_generic_args = prev;
1307                        return;
1308                    }
1309                }
1310
1311                self.visit_ty(ty);
1312            }
1313            GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1314            GenericArg::Const(ct) => {
1315                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
1316            }
1317        }
1318        self.diag_metadata.currently_processing_generic_args = prev;
1319    }
1320
1321    fn visit_assoc_item_constraint(&mut self, constraint: &'ast AssocItemConstraint) {
1322        self.visit_ident(&constraint.ident);
1323        if let Some(ref gen_args) = constraint.gen_args {
1324            // Forbid anonymous lifetimes in GAT parameters until proper semantics are decided.
1325            self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1326                this.visit_generic_args(gen_args)
1327            });
1328        }
1329        match constraint.kind {
1330            AssocItemConstraintKind::Equality { ref term } => match term {
1331                Term::Ty(ty) => self.visit_ty(ty),
1332                Term::Const(c) => {
1333                    self.resolve_anon_const(c, AnonConstKind::ConstArg(IsRepeatExpr::No))
1334                }
1335            },
1336            AssocItemConstraintKind::Bound { ref bounds } => {
1337                for elem in bounds {
    match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_param_bound(elem,
                BoundKind::Bound)) {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(self, visit_param_bound, bounds, BoundKind::Bound);
1338            }
1339        }
1340    }
1341
1342    fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1343        let Some(ref args) = path_segment.args else {
1344            return;
1345        };
1346
1347        match &**args {
1348            GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1349            GenericArgs::Parenthesized(p_args) => {
1350                // Probe the lifetime ribs to know how to behave.
1351                for rib in self.lifetime_ribs.iter().rev() {
1352                    match rib.kind {
1353                        // We are inside a `PolyTraitRef`. The lifetimes are
1354                        // to be introduced in that (maybe implicit) `for<>` binder.
1355                        LifetimeRibKind::Generics {
1356                            binder,
1357                            kind: LifetimeBinderKind::PolyTrait,
1358                            ..
1359                        } => {
1360                            self.resolve_fn_signature(
1361                                binder,
1362                                false,
1363                                p_args.inputs.iter().map(|ty| (None, &**ty)),
1364                                &p_args.output,
1365                                false,
1366                            );
1367                            break;
1368                        }
1369                        // We have nowhere to introduce generics. Code is malformed,
1370                        // so use regular lifetime resolution to avoid spurious errors.
1371                        LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1372                            visit::walk_generic_args(self, args);
1373                            break;
1374                        }
1375                        LifetimeRibKind::AnonymousCreateParameter { .. }
1376                        | LifetimeRibKind::AnonymousReportError
1377                        | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1378                        | LifetimeRibKind::ImplTrait
1379                        | LifetimeRibKind::Elided(_)
1380                        | LifetimeRibKind::ElisionFailure
1381                        | LifetimeRibKind::ConcreteAnonConst(_)
1382                        | LifetimeRibKind::ConstParamTy => {}
1383                    }
1384                }
1385            }
1386            GenericArgs::ParenthesizedElided(_) => {}
1387        }
1388    }
1389
1390    fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1391        {
    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/late.rs:1391",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1391u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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!("visit_where_predicate {0:?}",
                                                    p) as &dyn Value))])
            });
    } else { ; }
};debug!("visit_where_predicate {:?}", p);
1392        let previous_value = replace(&mut self.diag_metadata.current_where_predicate, Some(p));
1393        self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1394            if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1395                bounded_ty,
1396                bounds,
1397                bound_generic_params,
1398                ..
1399            }) = &p.kind
1400            {
1401                let span = p.span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1402                this.with_generic_param_rib(
1403                    bound_generic_params,
1404                    RibKind::Normal,
1405                    bounded_ty.id,
1406                    LifetimeBinderKind::WhereBound,
1407                    span,
1408                    |this| {
1409                        this.visit_generic_params(bound_generic_params, false);
1410                        this.visit_ty(bounded_ty);
1411                        for bound in bounds {
1412                            this.visit_param_bound(bound, BoundKind::Bound)
1413                        }
1414                    },
1415                );
1416            } else {
1417                visit::walk_where_predicate(this, p);
1418            }
1419        });
1420        self.diag_metadata.current_where_predicate = previous_value;
1421    }
1422
1423    fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1424        for (op, _) in &asm.operands {
1425            match op {
1426                InlineAsmOperand::In { expr, .. }
1427                | InlineAsmOperand::Out { expr: Some(expr), .. }
1428                | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1429                InlineAsmOperand::Out { expr: None, .. } => {}
1430                InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1431                    self.visit_expr(in_expr);
1432                    if let Some(out_expr) = out_expr {
1433                        self.visit_expr(out_expr);
1434                    }
1435                }
1436                InlineAsmOperand::Const { anon_const, .. } => {
1437                    // Although this is `DefKind::AnonConst`, it is allowed to reference outer
1438                    // generic parameters like an inline const.
1439                    self.resolve_anon_const(anon_const, AnonConstKind::InlineConst);
1440                }
1441                InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1442                InlineAsmOperand::Label { block } => self.visit_block(block),
1443            }
1444        }
1445    }
1446
1447    fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1448        // This is similar to the code for AnonConst.
1449        self.with_rib(ValueNS, RibKind::InlineAsmSym, |this| {
1450            this.with_rib(TypeNS, RibKind::InlineAsmSym, |this| {
1451                this.with_label_rib(RibKind::InlineAsmSym, |this| {
1452                    this.smart_resolve_path(sym.id, &sym.qself, &sym.path, PathSource::Expr(None));
1453                    visit::walk_inline_asm_sym(this, sym);
1454                });
1455            })
1456        });
1457    }
1458
1459    fn visit_variant(&mut self, v: &'ast Variant) {
1460        self.resolve_doc_links(&v.attrs, MaybeExported::Ok(v.id));
1461        self.visit_id(v.id);
1462        for elem in &v.attrs {
    match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_attribute(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(self, visit_attribute, &v.attrs);
1463        self.visit_vis(&v.vis);
1464        self.visit_ident(&v.ident);
1465        self.visit_variant_data(&v.data);
1466        if let Some(discr) = &v.disr_expr {
1467            self.resolve_anon_const(discr, AnonConstKind::EnumDiscriminant);
1468        }
1469    }
1470
1471    fn visit_field_def(&mut self, f: &'ast FieldDef) {
1472        self.resolve_doc_links(&f.attrs, MaybeExported::Ok(f.id));
1473        let FieldDef {
1474            attrs,
1475            id: _,
1476            span: _,
1477            vis,
1478            ident,
1479            ty,
1480            is_placeholder: _,
1481            default,
1482            safety: _,
1483        } = f;
1484        for elem in attrs {
    match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_attribute(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(self, visit_attribute, attrs);
1485        match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_vis(vis)) {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(self.visit_vis(vis));
1486        if let Some(x) = ident {
    match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_ident(x)) {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};visit_opt!(self, visit_ident, ident);
1487        match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_ty(ty)) {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(self.visit_ty(ty));
1488        if let Some(v) = &default {
1489            self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);
1490        }
1491    }
1492}
1493
1494impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1495    fn new(resolver: &'a mut Resolver<'ra, 'tcx>) -> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1496        // During late resolution we only track the module component of the parent scope,
1497        // although it may be useful to track other components as well for diagnostics.
1498        let graph_root = resolver.graph_root;
1499        let parent_scope = ParentScope::module(graph_root, resolver.arenas);
1500        let start_rib_kind = RibKind::Module(graph_root);
1501        LateResolutionVisitor {
1502            r: resolver,
1503            parent_scope,
1504            ribs: PerNS {
1505                value_ns: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Rib::new(start_rib_kind)]))vec![Rib::new(start_rib_kind)],
1506                type_ns: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Rib::new(start_rib_kind)]))vec![Rib::new(start_rib_kind)],
1507                macro_ns: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Rib::new(start_rib_kind)]))vec![Rib::new(start_rib_kind)],
1508            },
1509            last_block_rib: None,
1510            label_ribs: Vec::new(),
1511            lifetime_ribs: Vec::new(),
1512            lifetime_elision_candidates: None,
1513            current_trait_ref: None,
1514            diag_metadata: Default::default(),
1515            // errors at module scope should always be reported
1516            in_func_body: false,
1517            lifetime_uses: Default::default(),
1518        }
1519    }
1520
1521    fn maybe_resolve_ident_in_lexical_scope(
1522        &mut self,
1523        ident: Ident,
1524        ns: Namespace,
1525    ) -> Option<LateDecl<'ra>> {
1526        self.r.resolve_ident_in_lexical_scope(
1527            ident,
1528            ns,
1529            &self.parent_scope,
1530            None,
1531            &self.ribs[ns],
1532            None,
1533            Some(&self.diag_metadata),
1534        )
1535    }
1536
1537    fn resolve_ident_in_lexical_scope(
1538        &mut self,
1539        ident: Ident,
1540        ns: Namespace,
1541        finalize: Option<Finalize>,
1542        ignore_decl: Option<Decl<'ra>>,
1543    ) -> Option<LateDecl<'ra>> {
1544        self.r.resolve_ident_in_lexical_scope(
1545            ident,
1546            ns,
1547            &self.parent_scope,
1548            finalize,
1549            &self.ribs[ns],
1550            ignore_decl,
1551            Some(&self.diag_metadata),
1552        )
1553    }
1554
1555    fn resolve_path(
1556        &mut self,
1557        path: &[Segment],
1558        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1559        finalize: Option<Finalize>,
1560        source: PathSource<'_, 'ast, 'ra>,
1561    ) -> PathResult<'ra> {
1562        self.r.cm().resolve_path_with_ribs(
1563            path,
1564            opt_ns,
1565            &self.parent_scope,
1566            Some(source),
1567            finalize.map(|finalize| Finalize { stage: Stage::Late, ..finalize }),
1568            Some(&self.ribs),
1569            None,
1570            None,
1571            Some(&self.diag_metadata),
1572        )
1573    }
1574
1575    // AST resolution
1576    //
1577    // We maintain a list of value ribs and type ribs.
1578    //
1579    // Simultaneously, we keep track of the current position in the module
1580    // graph in the `parent_scope.module` pointer. When we go to resolve a name in
1581    // the value or type namespaces, we first look through all the ribs and
1582    // then query the module graph. When we resolve a name in the module
1583    // namespace, we can skip all the ribs (since nested modules are not
1584    // allowed within blocks in Rust) and jump straight to the current module
1585    // graph node.
1586    //
1587    // Named implementations are handled separately. When we find a method
1588    // call, we consult the module node to find all of the implementations in
1589    // scope. This information is lazily cached in the module node. We then
1590    // generate a fake "implementation scope" containing all the
1591    // implementations thus found, for compatibility with old resolve pass.
1592
1593    /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
1594    fn with_rib<T>(
1595        &mut self,
1596        ns: Namespace,
1597        kind: RibKind<'ra>,
1598        work: impl FnOnce(&mut Self) -> T,
1599    ) -> T {
1600        self.ribs[ns].push(Rib::new(kind));
1601        let ret = work(self);
1602        self.ribs[ns].pop();
1603        ret
1604    }
1605
1606    fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1607        // For type parameter defaults, we have to ban access
1608        // to following type parameters, as the GenericArgs can only
1609        // provide previous type parameters as they're built. We
1610        // put all the parameters on the ban list and then remove
1611        // them one by one as they are processed and become available.
1612        let mut forward_ty_ban_rib =
1613            Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1614        let mut forward_const_ban_rib =
1615            Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1616        for param in params.iter() {
1617            match param.kind {
1618                GenericParamKind::Type { .. } => {
1619                    forward_ty_ban_rib
1620                        .bindings
1621                        .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1622                }
1623                GenericParamKind::Const { .. } => {
1624                    forward_const_ban_rib
1625                        .bindings
1626                        .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1627                }
1628                GenericParamKind::Lifetime => {}
1629            }
1630        }
1631
1632        // rust-lang/rust#61631: The type `Self` is essentially
1633        // another type parameter. For ADTs, we consider it
1634        // well-defined only after all of the ADT type parameters have
1635        // been provided. Therefore, we do not allow use of `Self`
1636        // anywhere in ADT type parameter defaults.
1637        //
1638        // (We however cannot ban `Self` for defaults on *all* generic
1639        // lists; e.g. trait generics can usefully refer to `Self`,
1640        // such as in the case of `trait Add<Rhs = Self>`.)
1641        if add_self_upper {
1642            // (`Some` if + only if we are in ADT's generics.)
1643            forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1644        }
1645
1646        // NOTE: We use different ribs here not for a technical reason, but just
1647        // for better diagnostics.
1648        let mut forward_ty_ban_rib_const_param_ty = Rib {
1649            bindings: forward_ty_ban_rib.bindings.clone(),
1650            patterns_with_skipped_bindings: Default::default(),
1651            kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1652        };
1653        let mut forward_const_ban_rib_const_param_ty = Rib {
1654            bindings: forward_const_ban_rib.bindings.clone(),
1655            patterns_with_skipped_bindings: Default::default(),
1656            kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1657        };
1658        // We'll ban these with a `ConstParamTy` rib, so just clear these ribs for better
1659        // diagnostics, so we don't mention anything about const param tys having generics at all.
1660        if !self.r.tcx.features().generic_const_parameter_types() {
1661            forward_ty_ban_rib_const_param_ty.bindings.clear();
1662            forward_const_ban_rib_const_param_ty.bindings.clear();
1663        }
1664
1665        self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1666            for param in params {
1667                match param.kind {
1668                    GenericParamKind::Lifetime => {
1669                        for bound in &param.bounds {
1670                            this.visit_param_bound(bound, BoundKind::Bound);
1671                        }
1672                    }
1673                    GenericParamKind::Type { ref default } => {
1674                        for bound in &param.bounds {
1675                            this.visit_param_bound(bound, BoundKind::Bound);
1676                        }
1677
1678                        if let Some(ty) = default {
1679                            this.ribs[TypeNS].push(forward_ty_ban_rib);
1680                            this.ribs[ValueNS].push(forward_const_ban_rib);
1681                            this.visit_ty(ty);
1682                            forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1683                            forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1684                        }
1685
1686                        // Allow all following defaults to refer to this type parameter.
1687                        let i = &Ident::with_dummy_span(param.ident.name);
1688                        forward_ty_ban_rib.bindings.swap_remove(i);
1689                        forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);
1690                    }
1691                    GenericParamKind::Const { ref ty, span: _, ref default } => {
1692                        // Const parameters can't have param bounds.
1693                        if !param.bounds.is_empty() {
    ::core::panicking::panic("assertion failed: param.bounds.is_empty()")
};assert!(param.bounds.is_empty());
1694
1695                        this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);
1696                        this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);
1697                        if this.r.tcx.features().generic_const_parameter_types() {
1698                            this.visit_ty(ty)
1699                        } else {
1700                            this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));
1701                            this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));
1702                            this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {
1703                                this.visit_ty(ty)
1704                            });
1705                            this.ribs[TypeNS].pop().unwrap();
1706                            this.ribs[ValueNS].pop().unwrap();
1707                        }
1708                        forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();
1709                        forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();
1710
1711                        if let Some(expr) = default {
1712                            this.ribs[TypeNS].push(forward_ty_ban_rib);
1713                            this.ribs[ValueNS].push(forward_const_ban_rib);
1714                            this.resolve_anon_const(
1715                                expr,
1716                                AnonConstKind::ConstArg(IsRepeatExpr::No),
1717                            );
1718                            forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1719                            forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1720                        }
1721
1722                        // Allow all following defaults to refer to this const parameter.
1723                        let i = &Ident::with_dummy_span(param.ident.name);
1724                        forward_const_ban_rib.bindings.swap_remove(i);
1725                        forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);
1726                    }
1727                }
1728            }
1729        })
1730    }
1731
1732    #[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("with_lifetime_rib",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1732u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["kind"],
                                        ::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(&kind)
                                                            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: T = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.lifetime_ribs.push(LifetimeRib::new(kind));
            let outer_elision_candidates =
                self.lifetime_elision_candidates.take();
            let ret = work(self);
            self.lifetime_elision_candidates = outer_elision_candidates;
            self.lifetime_ribs.pop();
            ret
        }
    }
}#[instrument(level = "debug", skip(self, work))]
1733    fn with_lifetime_rib<T>(
1734        &mut self,
1735        kind: LifetimeRibKind,
1736        work: impl FnOnce(&mut Self) -> T,
1737    ) -> T {
1738        self.lifetime_ribs.push(LifetimeRib::new(kind));
1739        let outer_elision_candidates = self.lifetime_elision_candidates.take();
1740        let ret = work(self);
1741        self.lifetime_elision_candidates = outer_elision_candidates;
1742        self.lifetime_ribs.pop();
1743        ret
1744    }
1745
1746    #[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_lifetime",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1746u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["lifetime",
                                                    "use_ctxt"],
                                        ::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(&lifetime)
                                                            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(&use_ctxt)
                                                            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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ident = lifetime.ident;
            if ident.name == kw::StaticLifetime {
                self.record_lifetime_res(lifetime.id, LifetimeRes::Static,
                    LifetimeElisionCandidate::Named);
                return;
            }
            if ident.name == kw::UnderscoreLifetime {
                return self.resolve_anonymous_lifetime(lifetime, lifetime.id,
                        false);
            }
            let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
            while let Some(rib) = lifetime_rib_iter.next() {
                let normalized_ident = ident.normalize_to_macros_2_0();
                if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
                    self.record_lifetime_res(lifetime.id, res,
                        LifetimeElisionCandidate::Named);
                    if let LifetimeRes::Param { param, binder } = res {
                        match self.lifetime_uses.entry(param) {
                            Entry::Vacant(v) => {
                                {
                                    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/late.rs:1772",
                                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1772u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                                        ::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!("First use of {0:?} at {1:?}",
                                                                                    res, ident.span) as &dyn Value))])
                                            });
                                    } else { ; }
                                };
                                let use_set =
                                    self.lifetime_ribs.iter().rev().find_map(|rib|
                                                match rib.kind {
                                                    LifetimeRibKind::Item |
                                                        LifetimeRibKind::AnonymousReportError |
                                                        LifetimeRibKind::StaticIfNoLifetimeInScope { .. } |
                                                        LifetimeRibKind::ElisionFailure =>
                                                        Some(LifetimeUseSet::Many),
                                                    LifetimeRibKind::AnonymousCreateParameter {
                                                        binder: anon_binder, .. } =>
                                                        Some(if binder == anon_binder {
                                                                LifetimeUseSet::One { use_span: ident.span, use_ctxt }
                                                            } else { LifetimeUseSet::Many }),
                                                    LifetimeRibKind::Elided(r) =>
                                                        Some(if res == r {
                                                                LifetimeUseSet::One { use_span: ident.span, use_ctxt }
                                                            } else { LifetimeUseSet::Many }),
                                                    LifetimeRibKind::Generics { .. } |
                                                        LifetimeRibKind::ConstParamTy => None,
                                                    LifetimeRibKind::ConcreteAnonConst(_) => {
                                                        ::rustc_middle::util::bug::span_bug_fmt(ident.span,
                                                            format_args!("unexpected rib kind: {0:?}", rib.kind))
                                                    }
                                                    LifetimeRibKind::ImplTrait => {
                                                        if self.r.tcx.features().anonymous_lifetime_in_impl_trait()
                                                            {
                                                            None
                                                        } else { Some(LifetimeUseSet::Many) }
                                                    }
                                                }).unwrap_or(LifetimeUseSet::Many);
                                {
                                    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/late.rs:1817",
                                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1817u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                                        ::tracing_core::field::FieldSet::new(&["use_ctxt",
                                                                        "use_set"],
                                                            ::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(&debug(&use_ctxt)
                                                                            as &dyn Value)),
                                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&debug(&use_set) as
                                                                            &dyn Value))])
                                            });
                                    } else { ; }
                                };
                                v.insert(use_set);
                            }
                            Entry::Occupied(mut o) => {
                                {
                                    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/late.rs:1821",
                                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1821u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                                        ::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!("Many uses of {0:?} at {1:?}",
                                                                                    res, ident.span) as &dyn Value))])
                                            });
                                    } else { ; }
                                };
                                *o.get_mut() = LifetimeUseSet::Many;
                            }
                        }
                    }
                    return;
                }
                match rib.kind {
                    LifetimeRibKind::Item => break,
                    LifetimeRibKind::ConstParamTy => {
                        let guar =
                            self.emit_non_static_lt_in_const_param_ty_error(lifetime);
                        self.record_lifetime_res(lifetime.id,
                            LifetimeRes::Error(guar), LifetimeElisionCandidate::Ignore);
                        return;
                    }
                    LifetimeRibKind::ConcreteAnonConst(cause) => {
                        let guar =
                            self.emit_forbidden_non_static_lifetime_error(cause,
                                lifetime);
                        self.record_lifetime_res(lifetime.id,
                            LifetimeRes::Error(guar), LifetimeElisionCandidate::Ignore);
                        return;
                    }
                    LifetimeRibKind::AnonymousCreateParameter { .. } |
                        LifetimeRibKind::Elided(_) | LifetimeRibKind::Generics { ..
                        } | LifetimeRibKind::ElisionFailure |
                        LifetimeRibKind::AnonymousReportError |
                        LifetimeRibKind::ImplTrait |
                        LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {}
                }
            }
            let normalized_ident = ident.normalize_to_macros_2_0();
            let outer_res =
                lifetime_rib_iter.find_map(|rib|
                        rib.bindings.get_key_value(&normalized_ident).map(|(&outer,
                                    _)| outer));
            let guar =
                self.emit_undeclared_lifetime_error(lifetime, outer_res);
            self.record_lifetime_res(lifetime.id, LifetimeRes::Error(guar),
                LifetimeElisionCandidate::Named);
        }
    }
}#[instrument(level = "debug", skip(self))]
1747    fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1748        let ident = lifetime.ident;
1749
1750        if ident.name == kw::StaticLifetime {
1751            self.record_lifetime_res(
1752                lifetime.id,
1753                LifetimeRes::Static,
1754                LifetimeElisionCandidate::Named,
1755            );
1756            return;
1757        }
1758
1759        if ident.name == kw::UnderscoreLifetime {
1760            return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1761        }
1762
1763        let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1764        while let Some(rib) = lifetime_rib_iter.next() {
1765            let normalized_ident = ident.normalize_to_macros_2_0();
1766            if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1767                self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
1768
1769                if let LifetimeRes::Param { param, binder } = res {
1770                    match self.lifetime_uses.entry(param) {
1771                        Entry::Vacant(v) => {
1772                            debug!("First use of {:?} at {:?}", res, ident.span);
1773                            let use_set = self
1774                                .lifetime_ribs
1775                                .iter()
1776                                .rev()
1777                                .find_map(|rib| match rib.kind {
1778                                    // Do not suggest eliding a lifetime where an anonymous
1779                                    // lifetime would be illegal.
1780                                    LifetimeRibKind::Item
1781                                    | LifetimeRibKind::AnonymousReportError
1782                                    | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1783                                    | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1784                                    // An anonymous lifetime is legal here, and bound to the right
1785                                    // place, go ahead.
1786                                    LifetimeRibKind::AnonymousCreateParameter {
1787                                        binder: anon_binder,
1788                                        ..
1789                                    } => Some(if binder == anon_binder {
1790                                        LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1791                                    } else {
1792                                        LifetimeUseSet::Many
1793                                    }),
1794                                    // Only report if eliding the lifetime would have the same
1795                                    // semantics.
1796                                    LifetimeRibKind::Elided(r) => Some(if res == r {
1797                                        LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1798                                    } else {
1799                                        LifetimeUseSet::Many
1800                                    }),
1801                                    LifetimeRibKind::Generics { .. }
1802                                    | LifetimeRibKind::ConstParamTy => None,
1803                                    LifetimeRibKind::ConcreteAnonConst(_) => {
1804                                        span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1805                                    }
1806
1807                                    LifetimeRibKind::ImplTrait => {
1808                                        if self.r.tcx.features().anonymous_lifetime_in_impl_trait()
1809                                        {
1810                                            None
1811                                        } else {
1812                                            Some(LifetimeUseSet::Many)
1813                                        }
1814                                    }
1815                                })
1816                                .unwrap_or(LifetimeUseSet::Many);
1817                            debug!(?use_ctxt, ?use_set);
1818                            v.insert(use_set);
1819                        }
1820                        Entry::Occupied(mut o) => {
1821                            debug!("Many uses of {:?} at {:?}", res, ident.span);
1822                            *o.get_mut() = LifetimeUseSet::Many;
1823                        }
1824                    }
1825                }
1826                return;
1827            }
1828
1829            match rib.kind {
1830                LifetimeRibKind::Item => break,
1831                LifetimeRibKind::ConstParamTy => {
1832                    let guar = self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1833                    self.record_lifetime_res(
1834                        lifetime.id,
1835                        LifetimeRes::Error(guar),
1836                        LifetimeElisionCandidate::Ignore,
1837                    );
1838                    return;
1839                }
1840                LifetimeRibKind::ConcreteAnonConst(cause) => {
1841                    let guar = self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1842                    self.record_lifetime_res(
1843                        lifetime.id,
1844                        LifetimeRes::Error(guar),
1845                        LifetimeElisionCandidate::Ignore,
1846                    );
1847                    return;
1848                }
1849                LifetimeRibKind::AnonymousCreateParameter { .. }
1850                | LifetimeRibKind::Elided(_)
1851                | LifetimeRibKind::Generics { .. }
1852                | LifetimeRibKind::ElisionFailure
1853                | LifetimeRibKind::AnonymousReportError
1854                | LifetimeRibKind::ImplTrait
1855                | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {}
1856            }
1857        }
1858
1859        let normalized_ident = ident.normalize_to_macros_2_0();
1860        let outer_res = lifetime_rib_iter
1861            .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1862
1863        let guar = self.emit_undeclared_lifetime_error(lifetime, outer_res);
1864        self.record_lifetime_res(
1865            lifetime.id,
1866            LifetimeRes::Error(guar),
1867            LifetimeElisionCandidate::Named,
1868        );
1869    }
1870
1871    #[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_anonymous_lifetime",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1871u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["lifetime",
                                                    "id_for_lint", "elided"],
                                        ::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(&lifetime)
                                                            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(&id_for_lint)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&elided 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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if true {
                match (&lifetime.ident.name, &kw::UnderscoreLifetime) {
                    (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);
                        }
                    }
                };
            };
            let kind =
                if elided {
                    MissingLifetimeKind::Ampersand
                } else { MissingLifetimeKind::Underscore };
            let missing_lifetime =
                MissingLifetime {
                    id: lifetime.id,
                    span: lifetime.ident.span,
                    kind,
                    count: 1,
                    id_for_lint,
                };
            let elision_candidate =
                LifetimeElisionCandidate::Missing(missing_lifetime);
            for (i, rib) in self.lifetime_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/late.rs:1891",
                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1891u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                        ::tracing_core::field::FieldSet::new(&["rib.kind"],
                                            ::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(&debug(&rib.kind)
                                                            as &dyn Value))])
                            });
                    } else { ; }
                };
                match rib.kind {
                    LifetimeRibKind::AnonymousCreateParameter { binder, .. } =>
                        {
                        let res =
                            self.create_fresh_lifetime(lifetime.ident, binder, kind);
                        self.record_lifetime_res(lifetime.id, res,
                            elision_candidate);
                        return;
                    }
                    LifetimeRibKind::StaticIfNoLifetimeInScope {
                        lint_id: node_id, emit_lint } => {
                        let mut lifetimes_in_scope = ::alloc::vec::Vec::new();
                        for rib in self.lifetime_ribs[..i].iter().rev() {
                            lifetimes_in_scope.extend(rib.bindings.iter().map(|(ident,
                                            _)| ident.span));
                            if let LifetimeRibKind::AnonymousCreateParameter { binder,
                                        .. } = rib.kind &&
                                    let Some(extra) =
                                        self.r.extra_lifetime_params_map.get(&binder) {
                                lifetimes_in_scope.extend(extra.iter().map(|(ident, _, _)|
                                            ident.span));
                            }
                            if let LifetimeRibKind::Item = rib.kind { break; }
                        }
                        if lifetimes_in_scope.is_empty() {
                            self.record_lifetime_res(lifetime.id, LifetimeRes::Static,
                                elision_candidate);
                            return;
                        } else if emit_lint {
                            let lt_span =
                                if elided {
                                    lifetime.ident.span.shrink_to_hi()
                                } else { lifetime.ident.span };
                            let code = if elided { "'static " } else { "'static" };
                            self.r.lint_buffer.buffer_lint(lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
                                node_id, lifetime.ident.span,
                                crate::errors::AssociatedConstElidedLifetime {
                                    elided,
                                    code,
                                    span: lt_span,
                                    lifetimes_in_scope: lifetimes_in_scope.into(),
                                });
                        }
                    }
                    LifetimeRibKind::AnonymousReportError => {
                        let guar =
                            if elided {
                                let suggestion =
                                    self.lifetime_ribs[i..].iter().rev().find_map(|rib|
                                            {
                                                if let LifetimeRibKind::Generics {
                                                        span,
                                                        kind: LifetimeBinderKind::PolyTrait |
                                                            LifetimeBinderKind::WhereBound, .. } = rib.kind {
                                                    Some(errors::ElidedAnonymousLifetimeReportErrorSuggestion {
                                                            lo: span.shrink_to_lo(),
                                                            hi: lifetime.ident.span.shrink_to_hi(),
                                                        })
                                                } else { None }
                                            });
                                if !self.in_func_body &&
                                                    let Some((module, _)) = &self.current_trait_ref &&
                                                let Some(ty) = &self.diag_metadata.current_self_type &&
                                            Some(true) == self.diag_metadata.in_non_gat_assoc_type &&
                                        let crate::ModuleKind::Def(DefKind::Trait, trait_id, _, _) =
                                            module.kind {
                                    if def_id_matches_path(self.r.tcx, trait_id,
                                            &["core", "iter", "traits", "iterator", "Iterator"]) {
                                        self.r.dcx().emit_err(errors::LendingIteratorReportError {
                                                lifetime: lifetime.ident.span,
                                                ty: ty.span,
                                            })
                                    } else {
                                        let decl =
                                            if !trait_id.is_local() &&
                                                                    let Some(assoc) = self.diag_metadata.current_impl_item &&
                                                                let AssocItemKind::Type(_) = assoc.kind &&
                                                            let assocs = self.r.tcx.associated_items(trait_id) &&
                                                        let Some(ident) = assoc.kind.ident() &&
                                                    let Some(assoc) =
                                                        assocs.find_by_ident_and_kind(self.r.tcx, ident,
                                                            AssocTag::Type, trait_id) {
                                                let mut decl: MultiSpan =
                                                    self.r.tcx.def_span(assoc.def_id).into();
                                                decl.push_span_label(self.r.tcx.def_span(trait_id),
                                                    String::new());
                                                decl
                                            } else { DUMMY_SP.into() };
                                        let mut err =
                                            self.r.dcx().create_err(errors::AnonymousLifetimeNonGatReportError {
                                                    lifetime: lifetime.ident.span,
                                                    decl,
                                                });
                                        self.point_at_impl_lifetimes(&mut err, i,
                                            lifetime.ident.span);
                                        err.emit()
                                    }
                                } else {
                                    self.r.dcx().emit_err(errors::ElidedAnonymousLifetimeReportError {
                                            span: lifetime.ident.span,
                                            suggestion,
                                        })
                                }
                            } else {
                                self.r.dcx().emit_err(errors::ExplicitAnonymousLifetimeReportError {
                                        span: lifetime.ident.span,
                                    })
                            };
                        self.record_lifetime_res(lifetime.id,
                            LifetimeRes::Error(guar), elision_candidate);
                        return;
                    }
                    LifetimeRibKind::Elided(res) => {
                        self.record_lifetime_res(lifetime.id, res,
                            elision_candidate);
                        return;
                    }
                    LifetimeRibKind::ElisionFailure => {
                        self.diag_metadata.current_elision_failures.push((missing_lifetime,
                                elision_candidate, Either::Left(lifetime.id)));
                        return;
                    }
                    LifetimeRibKind::Item => break,
                    LifetimeRibKind::Generics { .. } |
                        LifetimeRibKind::ConstParamTy | LifetimeRibKind::ImplTrait
                        => {}
                    LifetimeRibKind::ConcreteAnonConst(_) => {
                        ::rustc_middle::util::bug::span_bug_fmt(lifetime.ident.span,
                            format_args!("unexpected rib kind: {0:?}", rib.kind))
                    }
                }
            }
            let guar =
                self.report_missing_lifetime_specifiers([&missing_lifetime],
                    None);
            self.record_lifetime_res(lifetime.id, LifetimeRes::Error(guar),
                elision_candidate);
        }
    }
}#[instrument(level = "debug", skip(self))]
1872    fn resolve_anonymous_lifetime(
1873        &mut self,
1874        lifetime: &Lifetime,
1875        id_for_lint: NodeId,
1876        elided: bool,
1877    ) {
1878        debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1879
1880        let kind =
1881            if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1882        let missing_lifetime = MissingLifetime {
1883            id: lifetime.id,
1884            span: lifetime.ident.span,
1885            kind,
1886            count: 1,
1887            id_for_lint,
1888        };
1889        let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1890        for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1891            debug!(?rib.kind);
1892            match rib.kind {
1893                LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1894                    let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1895                    self.record_lifetime_res(lifetime.id, res, elision_candidate);
1896                    return;
1897                }
1898                LifetimeRibKind::StaticIfNoLifetimeInScope { lint_id: node_id, emit_lint } => {
1899                    let mut lifetimes_in_scope = vec![];
1900                    for rib in self.lifetime_ribs[..i].iter().rev() {
1901                        lifetimes_in_scope.extend(rib.bindings.iter().map(|(ident, _)| ident.span));
1902                        // Consider any anonymous lifetimes, too
1903                        if let LifetimeRibKind::AnonymousCreateParameter { binder, .. } = rib.kind
1904                            && let Some(extra) = self.r.extra_lifetime_params_map.get(&binder)
1905                        {
1906                            lifetimes_in_scope.extend(extra.iter().map(|(ident, _, _)| ident.span));
1907                        }
1908                        if let LifetimeRibKind::Item = rib.kind {
1909                            break;
1910                        }
1911                    }
1912                    if lifetimes_in_scope.is_empty() {
1913                        self.record_lifetime_res(
1914                            lifetime.id,
1915                            LifetimeRes::Static,
1916                            elision_candidate,
1917                        );
1918                        return;
1919                    } else if emit_lint {
1920                        let lt_span = if elided {
1921                            lifetime.ident.span.shrink_to_hi()
1922                        } else {
1923                            lifetime.ident.span
1924                        };
1925                        let code = if elided { "'static " } else { "'static" };
1926
1927                        self.r.lint_buffer.buffer_lint(
1928                            lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
1929                            node_id,
1930                            lifetime.ident.span,
1931                            crate::errors::AssociatedConstElidedLifetime {
1932                                elided,
1933                                code,
1934                                span: lt_span,
1935                                lifetimes_in_scope: lifetimes_in_scope.into(),
1936                            },
1937                        );
1938                    }
1939                }
1940                LifetimeRibKind::AnonymousReportError => {
1941                    let guar = if elided {
1942                        let suggestion = self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1943                            if let LifetimeRibKind::Generics {
1944                                span,
1945                                kind: LifetimeBinderKind::PolyTrait | LifetimeBinderKind::WhereBound,
1946                                ..
1947                            } = rib.kind
1948                            {
1949                                Some(errors::ElidedAnonymousLifetimeReportErrorSuggestion {
1950                                    lo: span.shrink_to_lo(),
1951                                    hi: lifetime.ident.span.shrink_to_hi(),
1952                                })
1953                            } else {
1954                                None
1955                            }
1956                        });
1957                        // are we trying to use an anonymous lifetime
1958                        // on a non GAT associated trait type?
1959                        if !self.in_func_body
1960                            && let Some((module, _)) = &self.current_trait_ref
1961                            && let Some(ty) = &self.diag_metadata.current_self_type
1962                            && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1963                            && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _, _) =
1964                                module.kind
1965                        {
1966                            if def_id_matches_path(
1967                                self.r.tcx,
1968                                trait_id,
1969                                &["core", "iter", "traits", "iterator", "Iterator"],
1970                            ) {
1971                                self.r.dcx().emit_err(errors::LendingIteratorReportError {
1972                                    lifetime: lifetime.ident.span,
1973                                    ty: ty.span,
1974                                })
1975                            } else {
1976                                let decl = if !trait_id.is_local()
1977                                    && let Some(assoc) = self.diag_metadata.current_impl_item
1978                                    && let AssocItemKind::Type(_) = assoc.kind
1979                                    && let assocs = self.r.tcx.associated_items(trait_id)
1980                                    && let Some(ident) = assoc.kind.ident()
1981                                    && let Some(assoc) = assocs.find_by_ident_and_kind(
1982                                        self.r.tcx,
1983                                        ident,
1984                                        AssocTag::Type,
1985                                        trait_id,
1986                                    ) {
1987                                    let mut decl: MultiSpan =
1988                                        self.r.tcx.def_span(assoc.def_id).into();
1989                                    decl.push_span_label(
1990                                        self.r.tcx.def_span(trait_id),
1991                                        String::new(),
1992                                    );
1993                                    decl
1994                                } else {
1995                                    DUMMY_SP.into()
1996                                };
1997                                let mut err = self.r.dcx().create_err(
1998                                    errors::AnonymousLifetimeNonGatReportError {
1999                                        lifetime: lifetime.ident.span,
2000                                        decl,
2001                                    },
2002                                );
2003                                self.point_at_impl_lifetimes(&mut err, i, lifetime.ident.span);
2004                                err.emit()
2005                            }
2006                        } else {
2007                            self.r.dcx().emit_err(errors::ElidedAnonymousLifetimeReportError {
2008                                span: lifetime.ident.span,
2009                                suggestion,
2010                            })
2011                        }
2012                    } else {
2013                        self.r.dcx().emit_err(errors::ExplicitAnonymousLifetimeReportError {
2014                            span: lifetime.ident.span,
2015                        })
2016                    };
2017                    self.record_lifetime_res(
2018                        lifetime.id,
2019                        LifetimeRes::Error(guar),
2020                        elision_candidate,
2021                    );
2022                    return;
2023                }
2024                LifetimeRibKind::Elided(res) => {
2025                    self.record_lifetime_res(lifetime.id, res, elision_candidate);
2026                    return;
2027                }
2028                LifetimeRibKind::ElisionFailure => {
2029                    self.diag_metadata.current_elision_failures.push((
2030                        missing_lifetime,
2031                        elision_candidate,
2032                        Either::Left(lifetime.id),
2033                    ));
2034                    return;
2035                }
2036                LifetimeRibKind::Item => break,
2037                LifetimeRibKind::Generics { .. }
2038                | LifetimeRibKind::ConstParamTy
2039                | LifetimeRibKind::ImplTrait => {}
2040                LifetimeRibKind::ConcreteAnonConst(_) => {
2041                    // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
2042                    span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
2043                }
2044            }
2045        }
2046        let guar = self.report_missing_lifetime_specifiers([&missing_lifetime], None);
2047        self.record_lifetime_res(lifetime.id, LifetimeRes::Error(guar), elision_candidate);
2048    }
2049
2050    fn point_at_impl_lifetimes(&mut self, err: &mut Diag<'_>, i: usize, lifetime: Span) {
2051        let Some((rib, span)) =
2052            self.lifetime_ribs[..i].iter().rev().find_map(|rib| match rib.kind {
2053                LifetimeRibKind::Generics { span, kind: LifetimeBinderKind::ImplBlock, .. } => {
2054                    Some((rib, span))
2055                }
2056                _ => None,
2057            })
2058        else {
2059            return;
2060        };
2061        if !rib.bindings.is_empty() {
2062            err.span_label(
2063                span,
2064                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("there {0} named lifetime{1} specified on the impl block you could use",
                if rib.bindings.len() == 1 { "is a" } else { "are" },
                if rib.bindings.len() == 1 { "" } else { "s" }))
    })format!(
2065                    "there {} named lifetime{} specified on the impl block you could use",
2066                    if rib.bindings.len() == 1 { "is a" } else { "are" },
2067                    pluralize!(rib.bindings.len()),
2068                ),
2069            );
2070            if rib.bindings.len() == 1 {
2071                err.span_suggestion_verbose(
2072                    lifetime.shrink_to_hi(),
2073                    "consider using the lifetime from the impl block",
2074                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ",
                rib.bindings.keys().next().unwrap()))
    })format!("{} ", rib.bindings.keys().next().unwrap()),
2075                    Applicability::MaybeIncorrect,
2076                );
2077            }
2078        } else {
2079            struct AnonRefFinder;
2080            impl<'ast> Visitor<'ast> for AnonRefFinder {
2081                type Result = ControlFlow<Span>;
2082
2083                fn visit_ty(&mut self, ty: &'ast ast::Ty) -> Self::Result {
2084                    if let ast::TyKind::Ref(None, mut_ty) = &ty.kind {
2085                        return ControlFlow::Break(mut_ty.ty.span.shrink_to_lo());
2086                    }
2087                    visit::walk_ty(self, ty)
2088                }
2089
2090                fn visit_lifetime(
2091                    &mut self,
2092                    lt: &'ast ast::Lifetime,
2093                    _cx: visit::LifetimeCtxt,
2094                ) -> Self::Result {
2095                    if lt.ident.name == kw::UnderscoreLifetime {
2096                        return ControlFlow::Break(lt.ident.span);
2097                    }
2098                    visit::walk_lifetime(self, lt)
2099                }
2100            }
2101
2102            if let Some(ty) = &self.diag_metadata.current_self_type
2103                && let ControlFlow::Break(sp) = AnonRefFinder.visit_ty(ty)
2104            {
2105                err.multipart_suggestion(
2106                    "add a lifetime to the impl block and use it in the self type and associated \
2107                     type",
2108                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span, "<'a>".to_string()), (sp, "'a ".to_string()),
                (lifetime.shrink_to_hi(), "'a ".to_string())]))vec![
2109                        (span, "<'a>".to_string()),
2110                        (sp, "'a ".to_string()),
2111                        (lifetime.shrink_to_hi(), "'a ".to_string()),
2112                    ],
2113                    Applicability::MaybeIncorrect,
2114                );
2115            } else if let Some(item) = &self.diag_metadata.current_item
2116                && let ItemKind::Impl(impl_) = &item.kind
2117                && let Some(of_trait) = &impl_.of_trait
2118                && let ControlFlow::Break(sp) = AnonRefFinder.visit_trait_ref(&of_trait.trait_ref)
2119            {
2120                err.multipart_suggestion(
2121                    "add a lifetime to the impl block and use it in the trait and associated type",
2122                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span, "<'a>".to_string()), (sp, "'a".to_string()),
                (lifetime.shrink_to_hi(), "'a ".to_string())]))vec![
2123                        (span, "<'a>".to_string()),
2124                        (sp, "'a".to_string()),
2125                        (lifetime.shrink_to_hi(), "'a ".to_string()),
2126                    ],
2127                    Applicability::MaybeIncorrect,
2128                );
2129            } else {
2130                err.span_label(
2131                    span,
2132                    "you could add a lifetime on the impl block, if the trait or the self type \
2133                     could have one",
2134                );
2135            }
2136        }
2137    }
2138
2139    #[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_elided_lifetime",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2139u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["anchor_id", "span"],
                                        ::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(&anchor_id)
                                                            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(&span)
                                                            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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let id = self.r.next_node_id();
            let lt =
                Lifetime {
                    id,
                    ident: Ident::new(kw::UnderscoreLifetime, span),
                };
            self.record_lifetime_res(anchor_id,
                LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
                LifetimeElisionCandidate::Ignore);
            self.resolve_anonymous_lifetime(&lt, anchor_id, true);
        }
    }
}#[instrument(level = "debug", skip(self))]
2140    fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
2141        let id = self.r.next_node_id();
2142        let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
2143
2144        self.record_lifetime_res(
2145            anchor_id,
2146            LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
2147            LifetimeElisionCandidate::Ignore,
2148        );
2149        self.resolve_anonymous_lifetime(&lt, anchor_id, true);
2150    }
2151
2152    #[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("create_fresh_lifetime",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2152u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["ident", "binder",
                                                    "kind"], ::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(&binder)
                                                            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(&kind)
                                                            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: LifetimeRes = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if true {
                match (&ident.name, &kw::UnderscoreLifetime) {
                    (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);
                        }
                    }
                };
            };
            {
                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/late.rs:2160",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2160u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["ident.span"],
                                        ::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(&debug(&ident.span)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let param = self.r.next_node_id();
            let res = LifetimeRes::Fresh { param, binder, kind };
            self.record_lifetime_param(param, res);
            self.r.extra_lifetime_params_map.entry(binder).or_insert_with(Vec::new).push((ident,
                    param, res));
            res
        }
    }
}#[instrument(level = "debug", skip(self))]
2153    fn create_fresh_lifetime(
2154        &mut self,
2155        ident: Ident,
2156        binder: NodeId,
2157        kind: MissingLifetimeKind,
2158    ) -> LifetimeRes {
2159        debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
2160        debug!(?ident.span);
2161
2162        // Leave the responsibility to create the `LocalDefId` to lowering.
2163        let param = self.r.next_node_id();
2164        let res = LifetimeRes::Fresh { param, binder, kind };
2165        self.record_lifetime_param(param, res);
2166
2167        // Record the created lifetime parameter so lowering can pick it up and add it to HIR.
2168        self.r
2169            .extra_lifetime_params_map
2170            .entry(binder)
2171            .or_insert_with(Vec::new)
2172            .push((ident, param, res));
2173        res
2174    }
2175
2176    #[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_elided_lifetimes_in_path",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2176u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["partial_res",
                                                    "path", "source", "path_span"],
                                        ::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(&partial_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(&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(&source)
                                                            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(&path_span)
                                                            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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let proj_start = path.len() - partial_res.unresolved_segments();
            for (i, segment) in path.iter().enumerate() {
                if segment.has_lifetime_args { continue; }
                let Some(segment_id) = segment.id else { continue; };
                let type_def_id =
                    match partial_res.base_res() {
                        Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start =>
                            {
                            self.r.tcx.parent(def_id)
                        }
                        Res::Def(DefKind::Variant, def_id) if
                            i + 2 == proj_start && segment.has_generic_args => {
                            self.r.tcx.parent(def_id)
                        }
                        Res::Def(DefKind::Variant, def_id) if
                            i + 1 == proj_start &&
                                !i.checked_sub(1).is_some_and(|i| path[i].has_generic_args)
                            => {
                            self.r.tcx.parent(def_id)
                        }
                        Res::Def(DefKind::Struct, def_id) |
                            Res::Def(DefKind::Union, def_id) |
                            Res::Def(DefKind::Enum, def_id) |
                            Res::Def(DefKind::TyAlias, def_id) |
                            Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start => {
                            def_id
                        }
                        _ => continue,
                    };
                let expected_lifetimes =
                    self.r.item_generics_num_lifetimes(type_def_id);
                if expected_lifetimes == 0 { continue; }
                let node_ids = self.r.next_node_ids(expected_lifetimes);
                self.record_lifetime_res(segment_id,
                    LifetimeRes::ElidedAnchor {
                        start: node_ids.start,
                        end: node_ids.end,
                    }, LifetimeElisionCandidate::Ignore);
                let inferred =
                    match source {
                        PathSource::Trait(..) | PathSource::TraitItem(..) |
                            PathSource::Type | PathSource::PreciseCapturingArg(..) |
                            PathSource::ReturnTypeNotation | PathSource::Macro |
                            PathSource::Module => false,
                        PathSource::Expr(..) | PathSource::Pat |
                            PathSource::Struct(_) | PathSource::TupleStruct(..) |
                            PathSource::DefineOpaques | PathSource::Delegation |
                            PathSource::ExternItemImpl => true,
                    };
                if inferred {
                    for id in node_ids {
                        self.record_lifetime_res(id, LifetimeRes::Infer,
                            LifetimeElisionCandidate::Named);
                    }
                    continue;
                }
                let elided_lifetime_span =
                    if segment.has_generic_args {
                        segment.args_span.with_hi(segment.args_span.lo() +
                                BytePos(1))
                    } else {
                        segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
                    };
                let ident =
                    Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
                let kind =
                    if segment.has_generic_args {
                        MissingLifetimeKind::Comma
                    } else { MissingLifetimeKind::Brackets };
                let missing_lifetime =
                    MissingLifetime {
                        id: node_ids.start,
                        id_for_lint: segment_id,
                        span: elided_lifetime_span,
                        kind,
                        count: expected_lifetimes,
                    };
                let mut should_lint = true;
                for rib in self.lifetime_ribs.iter().rev() {
                    match rib.kind {
                        LifetimeRibKind::AnonymousCreateParameter {
                            report_in_path: true, .. } |
                            LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {
                            let sess = self.r.tcx.sess;
                            let subdiag =
                                elided_lifetime_in_path_suggestion(sess.source_map(),
                                    expected_lifetimes, path_span, !segment.has_generic_args,
                                    elided_lifetime_span);
                            let guar =
                                self.r.dcx().emit_err(errors::ImplicitElidedLifetimeNotAllowedHere {
                                        span: path_span,
                                        subdiag,
                                    });
                            should_lint = false;
                            for id in node_ids {
                                self.record_lifetime_res(id, LifetimeRes::Error(guar),
                                    LifetimeElisionCandidate::Named);
                            }
                            break;
                        }
                        LifetimeRibKind::AnonymousCreateParameter { binder, .. } =>
                            {
                            let mut candidate =
                                LifetimeElisionCandidate::Missing(missing_lifetime);
                            for id in node_ids {
                                let res = self.create_fresh_lifetime(ident, binder, kind);
                                self.record_lifetime_res(id, res,
                                    replace(&mut candidate, LifetimeElisionCandidate::Named));
                            }
                            break;
                        }
                        LifetimeRibKind::Elided(res) => {
                            let mut candidate =
                                LifetimeElisionCandidate::Missing(missing_lifetime);
                            for id in node_ids {
                                self.record_lifetime_res(id, res,
                                    replace(&mut candidate, LifetimeElisionCandidate::Ignore));
                            }
                            break;
                        }
                        LifetimeRibKind::ElisionFailure => {
                            self.diag_metadata.current_elision_failures.push((missing_lifetime,
                                    LifetimeElisionCandidate::Ignore, Either::Right(node_ids)));
                            break;
                        }
                        LifetimeRibKind::AnonymousReportError |
                            LifetimeRibKind::Item => {
                            let guar =
                                self.report_missing_lifetime_specifiers([&missing_lifetime],
                                    None);
                            for id in node_ids {
                                self.record_lifetime_res(id, LifetimeRes::Error(guar),
                                    LifetimeElisionCandidate::Ignore);
                            }
                            break;
                        }
                        LifetimeRibKind::Generics { .. } |
                            LifetimeRibKind::ConstParamTy | LifetimeRibKind::ImplTrait
                            => {}
                        LifetimeRibKind::ConcreteAnonConst(_) => {
                            ::rustc_middle::util::bug::span_bug_fmt(elided_lifetime_span,
                                format_args!("unexpected rib kind: {0:?}", rib.kind))
                        }
                    }
                }
                if should_lint {
                    let include_angle_bracket = !segment.has_generic_args;
                    self.r.lint_buffer.dyn_buffer_lint_any(lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
                        segment_id, elided_lifetime_span,
                        move |dcx, level, sess|
                            {
                                let source_map =
                                    sess.downcast_ref::<rustc_session::Session>().expect("expected a `Session`").source_map();
                                errors::ElidedLifetimesInPaths {
                                        subdiag: elided_lifetime_in_path_suggestion(source_map,
                                            expected_lifetimes, path_span, include_angle_bracket,
                                            elided_lifetime_span),
                                    }.into_diag(dcx, level)
                            });
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2177    fn resolve_elided_lifetimes_in_path(
2178        &mut self,
2179        partial_res: PartialRes,
2180        path: &[Segment],
2181        source: PathSource<'_, 'ast, 'ra>,
2182        path_span: Span,
2183    ) {
2184        let proj_start = path.len() - partial_res.unresolved_segments();
2185        for (i, segment) in path.iter().enumerate() {
2186            if segment.has_lifetime_args {
2187                continue;
2188            }
2189            let Some(segment_id) = segment.id else {
2190                continue;
2191            };
2192
2193            // Figure out if this is a type/trait segment,
2194            // which may need lifetime elision performed.
2195            let type_def_id = match partial_res.base_res() {
2196                Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2197                    self.r.tcx.parent(def_id)
2198                }
2199                Res::Def(DefKind::Variant, def_id)
2200                    if i + 2 == proj_start && segment.has_generic_args =>
2201                {
2202                    self.r.tcx.parent(def_id)
2203                }
2204                Res::Def(DefKind::Variant, def_id)
2205                    if i + 1 == proj_start
2206                        && !i.checked_sub(1).is_some_and(|i| path[i].has_generic_args) =>
2207                {
2208                    self.r.tcx.parent(def_id)
2209                }
2210                Res::Def(DefKind::Struct, def_id)
2211                | Res::Def(DefKind::Union, def_id)
2212                | Res::Def(DefKind::Enum, def_id)
2213                | Res::Def(DefKind::TyAlias, def_id)
2214                | Res::Def(DefKind::Trait, def_id)
2215                    if i + 1 == proj_start =>
2216                {
2217                    def_id
2218                }
2219                _ => continue,
2220            };
2221
2222            let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2223            if expected_lifetimes == 0 {
2224                continue;
2225            }
2226
2227            let node_ids = self.r.next_node_ids(expected_lifetimes);
2228            self.record_lifetime_res(
2229                segment_id,
2230                LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2231                LifetimeElisionCandidate::Ignore,
2232            );
2233
2234            let inferred = match source {
2235                PathSource::Trait(..)
2236                | PathSource::TraitItem(..)
2237                | PathSource::Type
2238                | PathSource::PreciseCapturingArg(..)
2239                | PathSource::ReturnTypeNotation
2240                | PathSource::Macro
2241                | PathSource::Module => false,
2242                PathSource::Expr(..)
2243                | PathSource::Pat
2244                | PathSource::Struct(_)
2245                | PathSource::TupleStruct(..)
2246                | PathSource::DefineOpaques
2247                | PathSource::Delegation
2248                | PathSource::ExternItemImpl => true,
2249            };
2250            if inferred {
2251                // Do not create a parameter for patterns and expressions: type checking can infer
2252                // the appropriate lifetime for us.
2253                for id in node_ids {
2254                    self.record_lifetime_res(
2255                        id,
2256                        LifetimeRes::Infer,
2257                        LifetimeElisionCandidate::Named,
2258                    );
2259                }
2260                continue;
2261            }
2262
2263            let elided_lifetime_span = if segment.has_generic_args {
2264                // If there are brackets, but not generic arguments, then use the opening bracket
2265                segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2266            } else {
2267                // If there are no brackets, use the identifier span.
2268                // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
2269                // originating from macros, since the segment's span might be from a macro arg.
2270                segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2271            };
2272            let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2273
2274            let kind = if segment.has_generic_args {
2275                MissingLifetimeKind::Comma
2276            } else {
2277                MissingLifetimeKind::Brackets
2278            };
2279            let missing_lifetime = MissingLifetime {
2280                id: node_ids.start,
2281                id_for_lint: segment_id,
2282                span: elided_lifetime_span,
2283                kind,
2284                count: expected_lifetimes,
2285            };
2286            let mut should_lint = true;
2287            for rib in self.lifetime_ribs.iter().rev() {
2288                match rib.kind {
2289                    // In create-parameter mode we error here because we don't want to support
2290                    // deprecated impl elision in new features like impl elision and `async fn`,
2291                    // both of which work using the `CreateParameter` mode:
2292                    //
2293                    //     impl Foo for std::cell::Ref<u32> // note lack of '_
2294                    //     async fn foo(_: std::cell::Ref<u32>) { ... }
2295                    LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2296                    | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {
2297                        let sess = self.r.tcx.sess;
2298                        let subdiag = elided_lifetime_in_path_suggestion(
2299                            sess.source_map(),
2300                            expected_lifetimes,
2301                            path_span,
2302                            !segment.has_generic_args,
2303                            elided_lifetime_span,
2304                        );
2305                        let guar =
2306                            self.r.dcx().emit_err(errors::ImplicitElidedLifetimeNotAllowedHere {
2307                                span: path_span,
2308                                subdiag,
2309                            });
2310                        should_lint = false;
2311
2312                        for id in node_ids {
2313                            self.record_lifetime_res(
2314                                id,
2315                                LifetimeRes::Error(guar),
2316                                LifetimeElisionCandidate::Named,
2317                            );
2318                        }
2319                        break;
2320                    }
2321                    // Do not create a parameter for patterns and expressions.
2322                    LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2323                        // Group all suggestions into the first record.
2324                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2325                        for id in node_ids {
2326                            let res = self.create_fresh_lifetime(ident, binder, kind);
2327                            self.record_lifetime_res(
2328                                id,
2329                                res,
2330                                replace(&mut candidate, LifetimeElisionCandidate::Named),
2331                            );
2332                        }
2333                        break;
2334                    }
2335                    LifetimeRibKind::Elided(res) => {
2336                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2337                        for id in node_ids {
2338                            self.record_lifetime_res(
2339                                id,
2340                                res,
2341                                replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2342                            );
2343                        }
2344                        break;
2345                    }
2346                    LifetimeRibKind::ElisionFailure => {
2347                        self.diag_metadata.current_elision_failures.push((
2348                            missing_lifetime,
2349                            LifetimeElisionCandidate::Ignore,
2350                            Either::Right(node_ids),
2351                        ));
2352                        break;
2353                    }
2354                    // `LifetimeRes::Error`, which would usually be used in the case of
2355                    // `ReportError`, is unsuitable here, as we don't emit an error yet. Instead,
2356                    // we simply resolve to an implicit lifetime, which will be checked later, at
2357                    // which point a suitable error will be emitted.
2358                    LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2359                        let guar =
2360                            self.report_missing_lifetime_specifiers([&missing_lifetime], None);
2361                        for id in node_ids {
2362                            self.record_lifetime_res(
2363                                id,
2364                                LifetimeRes::Error(guar),
2365                                LifetimeElisionCandidate::Ignore,
2366                            );
2367                        }
2368                        break;
2369                    }
2370                    LifetimeRibKind::Generics { .. }
2371                    | LifetimeRibKind::ConstParamTy
2372                    | LifetimeRibKind::ImplTrait => {}
2373                    LifetimeRibKind::ConcreteAnonConst(_) => {
2374                        // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
2375                        span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2376                    }
2377                }
2378            }
2379
2380            if should_lint {
2381                let include_angle_bracket = !segment.has_generic_args;
2382                self.r.lint_buffer.dyn_buffer_lint_any(
2383                    lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2384                    segment_id,
2385                    elided_lifetime_span,
2386                    move |dcx, level, sess| {
2387                        let source_map = sess
2388                            .downcast_ref::<rustc_session::Session>()
2389                            .expect("expected a `Session`")
2390                            .source_map();
2391                        errors::ElidedLifetimesInPaths {
2392                            subdiag: elided_lifetime_in_path_suggestion(
2393                                source_map,
2394                                expected_lifetimes,
2395                                path_span,
2396                                include_angle_bracket,
2397                                elided_lifetime_span,
2398                            ),
2399                        }
2400                        .into_diag(dcx, level)
2401                    },
2402                );
2403            }
2404        }
2405    }
2406
2407    #[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("record_lifetime_res",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2407u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["id", "res",
                                                    "candidate"],
                                        ::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(&id)
                                                            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(&candidate)
                                                            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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
                {
                    ::core::panicking::panic_fmt(format_args!("lifetime {0:?} resolved multiple times ({1:?} before, {2:?} now)",
                            id, prev_res, res));
                }
            }
            match res {
                LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } |
                    LifetimeRes::Static { .. } => {
                    if let Some(ref mut candidates) =
                            self.lifetime_elision_candidates {
                        candidates.push((res, candidate));
                    }
                }
                LifetimeRes::Infer | LifetimeRes::Error(..) |
                    LifetimeRes::ElidedAnchor { .. } => {}
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2408    fn record_lifetime_res(
2409        &mut self,
2410        id: NodeId,
2411        res: LifetimeRes,
2412        candidate: LifetimeElisionCandidate,
2413    ) {
2414        if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2415            panic!("lifetime {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)")
2416        }
2417
2418        match res {
2419            LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2420                if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2421                    candidates.push((res, candidate));
2422                }
2423            }
2424            LifetimeRes::Infer | LifetimeRes::Error(..) | LifetimeRes::ElidedAnchor { .. } => {}
2425        }
2426    }
2427
2428    #[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("record_lifetime_param",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2428u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["id", "res"],
                                        ::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(&id)
                                                            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))])
                            })
                } 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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
                {
                    ::core::panicking::panic_fmt(format_args!("lifetime parameter {0:?} resolved multiple times ({1:?} before, {2:?} now)",
                            id, prev_res, res));
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2429    fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
2430        if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2431            panic!(
2432                "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2433            )
2434        }
2435    }
2436
2437    /// Perform resolution of a function signature, accounting for lifetime elision.
2438    #[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_fn_signature",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2438u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["fn_id", "has_self",
                                                    "output_ty", "report_elided_lifetimes_in_path"],
                                        ::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(&fn_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&has_self 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(&output_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&report_elided_lifetimes_in_path
                                                            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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let rib =
                LifetimeRibKind::AnonymousCreateParameter {
                    binder: fn_id,
                    report_in_path: report_elided_lifetimes_in_path,
                };
            self.with_lifetime_rib(rib,
                |this|
                    {
                        let elision_lifetime =
                            this.resolve_fn_params(has_self, inputs);
                        {
                            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/late.rs:2454",
                                                "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                ::tracing_core::__macro_support::Option::Some(2454u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                                ::tracing_core::field::FieldSet::new(&["elision_lifetime"],
                                                    ::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(&debug(&elision_lifetime)
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        let outer_failures =
                            take(&mut this.diag_metadata.current_elision_failures);
                        let output_rib =
                            if let Ok(res) = elision_lifetime.as_ref() {
                                this.r.lifetime_elision_allowed.insert(fn_id);
                                LifetimeRibKind::Elided(*res)
                            } else { LifetimeRibKind::ElisionFailure };
                        this.with_lifetime_rib(output_rib,
                            |this| visit::walk_fn_ret_ty(this, output_ty));
                        let elision_failures =
                            replace(&mut this.diag_metadata.current_elision_failures,
                                outer_failures);
                        if !elision_failures.is_empty() {
                            let Err(failure_info) =
                                elision_lifetime else {
                                    ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
                                };
                            let guar =
                                this.report_missing_lifetime_specifiers(elision_failures.iter().map(|(missing_lifetime,
                                                ..)| missing_lifetime), Some(failure_info));
                            let mut record_res =
                                |lifetime, candidate|
                                    {
                                        this.record_lifetime_res(lifetime, LifetimeRes::Error(guar),
                                            candidate)
                                    };
                            for (_, candidate, nodes) in elision_failures {
                                match nodes {
                                    Either::Left(node_id) => record_res(node_id, candidate),
                                    Either::Right(node_ids) => {
                                        for lifetime in node_ids { record_res(lifetime, candidate) }
                                    }
                                }
                            }
                        }
                    });
        }
    }
}#[instrument(level = "debug", skip(self, inputs))]
2439    fn resolve_fn_signature(
2440        &mut self,
2441        fn_id: NodeId,
2442        has_self: bool,
2443        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2444        output_ty: &'ast FnRetTy,
2445        report_elided_lifetimes_in_path: bool,
2446    ) {
2447        let rib = LifetimeRibKind::AnonymousCreateParameter {
2448            binder: fn_id,
2449            report_in_path: report_elided_lifetimes_in_path,
2450        };
2451        self.with_lifetime_rib(rib, |this| {
2452            // Add each argument to the rib.
2453            let elision_lifetime = this.resolve_fn_params(has_self, inputs);
2454            debug!(?elision_lifetime);
2455
2456            let outer_failures = take(&mut this.diag_metadata.current_elision_failures);
2457            let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2458                this.r.lifetime_elision_allowed.insert(fn_id);
2459                LifetimeRibKind::Elided(*res)
2460            } else {
2461                LifetimeRibKind::ElisionFailure
2462            };
2463            this.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2464            let elision_failures =
2465                replace(&mut this.diag_metadata.current_elision_failures, outer_failures);
2466            if !elision_failures.is_empty() {
2467                let Err(failure_info) = elision_lifetime else { bug!() };
2468                let guar = this.report_missing_lifetime_specifiers(
2469                    elision_failures.iter().map(|(missing_lifetime, ..)| missing_lifetime),
2470                    Some(failure_info),
2471                );
2472                let mut record_res = |lifetime, candidate| {
2473                    this.record_lifetime_res(lifetime, LifetimeRes::Error(guar), candidate)
2474                };
2475                for (_, candidate, nodes) in elision_failures {
2476                    match nodes {
2477                        Either::Left(node_id) => record_res(node_id, candidate),
2478                        Either::Right(node_ids) => {
2479                            for lifetime in node_ids {
2480                                record_res(lifetime, candidate)
2481                            }
2482                        }
2483                    }
2484                }
2485            }
2486        });
2487    }
2488
2489    /// Resolve inside function parameters and parameter types.
2490    /// Returns the lifetime for elision in fn return type,
2491    /// or diagnostic information in case of elision failure.
2492    fn resolve_fn_params(
2493        &mut self,
2494        has_self: bool,
2495        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2496    ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2497        enum Elision {
2498            /// We have not found any candidate.
2499            None,
2500            /// We have a candidate bound to `self`.
2501            Self_(LifetimeRes),
2502            /// We have a candidate bound to a parameter.
2503            Param(LifetimeRes),
2504            /// We failed elision.
2505            Err,
2506        }
2507
2508        // Save elision state to reinstate it later.
2509        let outer_candidates = self.lifetime_elision_candidates.take();
2510
2511        // Result of elision.
2512        let mut elision_lifetime = Elision::None;
2513        // Information for diagnostics.
2514        let mut parameter_info = Vec::new();
2515        let mut all_candidates = Vec::new();
2516
2517        // Resolve and apply bindings first so diagnostics can see if they're used in types.
2518        let mut bindings = {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push((PatBoundCtx::Product, Default::default()));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [(PatBoundCtx::Product, Default::default())])))
    }
}smallvec![(PatBoundCtx::Product, Default::default())];
2519        for (pat, _) in inputs.clone() {
2520            {
    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/late.rs:2520",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2520u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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!("resolving bindings in pat = {0:?}",
                                                    pat) as &dyn Value))])
            });
    } else { ; }
};debug!("resolving bindings in pat = {pat:?}");
2521            self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2522                if let Some(pat) = pat {
2523                    this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2524                }
2525            });
2526        }
2527        self.apply_pattern_bindings(bindings);
2528
2529        for (index, (pat, ty)) in inputs.enumerate() {
2530            {
    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/late.rs:2530",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2530u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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!("resolving type for pat = {0:?}, ty = {1:?}",
                                                    pat, ty) as &dyn Value))])
            });
    } else { ; }
};debug!("resolving type for pat = {pat:?}, ty = {ty:?}");
2531            // Record elision candidates only for this parameter.
2532            if true {
    {
        match self.lifetime_elision_candidates {
            None => {}
            ref left_val => {
                ::core::panicking::assert_matches_failed(left_val, "None",
                    ::core::option::Option::None);
            }
        }
    };
};debug_assert_matches!(self.lifetime_elision_candidates, None);
2533            self.lifetime_elision_candidates = Some(Default::default());
2534            self.visit_ty(ty);
2535            let local_candidates = self.lifetime_elision_candidates.take();
2536
2537            if let Some(candidates) = local_candidates {
2538                let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2539                let lifetime_count = distinct.len();
2540                if lifetime_count != 0 {
2541                    parameter_info.push(ElisionFnParameter {
2542                        index,
2543                        ident: if let Some(pat) = pat
2544                            && let PatKind::Ident(_, ident, _) = pat.kind
2545                        {
2546                            Some(ident)
2547                        } else {
2548                            None
2549                        },
2550                        lifetime_count,
2551                        span: ty.span,
2552                    });
2553                    all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2554                        match candidate {
2555                            LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {
2556                                None
2557                            }
2558                            LifetimeElisionCandidate::Missing(missing) => Some(missing),
2559                        }
2560                    }));
2561                }
2562                if !distinct.is_empty() {
2563                    match elision_lifetime {
2564                        // We are the first parameter to bind lifetimes.
2565                        Elision::None => {
2566                            if let Some(res) = distinct.get_only() {
2567                                // We have a single lifetime => success.
2568                                elision_lifetime = Elision::Param(*res)
2569                            } else {
2570                                // We have multiple lifetimes => error.
2571                                elision_lifetime = Elision::Err;
2572                            }
2573                        }
2574                        // We have 2 parameters that bind lifetimes => error.
2575                        Elision::Param(_) => elision_lifetime = Elision::Err,
2576                        // `self` elision takes precedence over everything else.
2577                        Elision::Self_(_) | Elision::Err => {}
2578                    }
2579                }
2580            }
2581
2582            // Handle `self` specially.
2583            if index == 0 && has_self {
2584                let self_lifetime = self.find_lifetime_for_self(ty);
2585                elision_lifetime = match self_lifetime {
2586                    // We found `self` elision.
2587                    Set1::One(lifetime) => Elision::Self_(lifetime),
2588                    // `self` itself had ambiguous lifetimes, e.g.
2589                    // &Box<&Self>. In this case we won't consider
2590                    // taking an alternative parameter lifetime; just avoid elision
2591                    // entirely.
2592                    Set1::Many => Elision::Err,
2593                    // We do not have `self` elision: disregard the `Elision::Param` that we may
2594                    // have found.
2595                    Set1::Empty => Elision::None,
2596                }
2597            }
2598            {
    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/late.rs:2598",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2598u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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!("(resolving function / closure) recorded parameter")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("(resolving function / closure) recorded parameter");
2599        }
2600
2601        // Reinstate elision state.
2602        if true {
    {
        match self.lifetime_elision_candidates {
            None => {}
            ref left_val => {
                ::core::panicking::assert_matches_failed(left_val, "None",
                    ::core::option::Option::None);
            }
        }
    };
};debug_assert_matches!(self.lifetime_elision_candidates, None);
2603        self.lifetime_elision_candidates = outer_candidates;
2604
2605        if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2606            return Ok(res);
2607        }
2608
2609        // We do not have a candidate.
2610        Err((all_candidates, parameter_info))
2611    }
2612
2613    /// List all the lifetimes that appear in the provided type.
2614    fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2615        /// Visits a type to find all the &references, and determines the
2616        /// set of lifetimes for all of those references where the referent
2617        /// contains Self.
2618        struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2619            r: &'a Resolver<'ra, 'tcx>,
2620            impl_self: Option<Res>,
2621            lifetime: Set1<LifetimeRes>,
2622        }
2623
2624        impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2625            fn visit_ty(&mut self, ty: &'ra Ty) {
2626                {
    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/late.rs:2626",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2626u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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!("FindReferenceVisitor considering ty={0:?}",
                                                    ty) as &dyn Value))])
            });
    } else { ; }
};trace!("FindReferenceVisitor considering ty={:?}", ty);
2627                if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2628                    // See if anything inside the &thing contains Self
2629                    let mut visitor =
2630                        SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2631                    visitor.visit_ty(ty);
2632                    {
    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/late.rs:2632",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2632u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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!("FindReferenceVisitor: SelfVisitor self_found={0:?}",
                                                    visitor.self_found) as &dyn Value))])
            });
    } else { ; }
};trace!("FindReferenceVisitor: SelfVisitor self_found={:?}", visitor.self_found);
2633                    if visitor.self_found {
2634                        let lt_id = if let Some(lt) = lt {
2635                            lt.id
2636                        } else {
2637                            let res = self.r.lifetimes_res_map[&ty.id];
2638                            let LifetimeRes::ElidedAnchor { start, .. } = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2639                            start
2640                        };
2641                        let lt_res = self.r.lifetimes_res_map[&lt_id];
2642                        {
    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/late.rs:2642",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2642u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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!("FindReferenceVisitor inserting res={0:?}",
                                                    lt_res) as &dyn Value))])
            });
    } else { ; }
};trace!("FindReferenceVisitor inserting res={:?}", lt_res);
2643                        self.lifetime.insert(lt_res);
2644                    }
2645                }
2646                visit::walk_ty(self, ty)
2647            }
2648
2649            // A type may have an expression as a const generic argument.
2650            // We do not want to recurse into those.
2651            fn visit_expr(&mut self, _: &'ra Expr) {}
2652        }
2653
2654        /// Visitor which checks the referent of a &Thing to see if the
2655        /// Thing contains Self
2656        struct SelfVisitor<'a, 'ra, 'tcx> {
2657            r: &'a Resolver<'ra, 'tcx>,
2658            impl_self: Option<Res>,
2659            self_found: bool,
2660        }
2661
2662        impl SelfVisitor<'_, '_, '_> {
2663            // Look for `self: &'a Self` - also desugared from `&'a self`
2664            fn is_self_ty(&self, ty: &Ty) -> bool {
2665                match ty.kind {
2666                    TyKind::ImplicitSelf => true,
2667                    TyKind::Path(None, _) => {
2668                        let path_res = self.r.partial_res_map[&ty.id].full_res();
2669                        if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2670                            return true;
2671                        }
2672                        self.impl_self.is_some() && path_res == self.impl_self
2673                    }
2674                    _ => false,
2675                }
2676            }
2677        }
2678
2679        impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2680            fn visit_ty(&mut self, ty: &'ra Ty) {
2681                {
    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/late.rs:2681",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2681u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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!("SelfVisitor considering ty={0:?}",
                                                    ty) as &dyn Value))])
            });
    } else { ; }
};trace!("SelfVisitor considering ty={:?}", ty);
2682                if self.is_self_ty(ty) {
2683                    {
    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/late.rs:2683",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2683u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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!("SelfVisitor found Self")
                                            as &dyn Value))])
            });
    } else { ; }
};trace!("SelfVisitor found Self");
2684                    self.self_found = true;
2685                }
2686                visit::walk_ty(self, ty)
2687            }
2688
2689            // A type may have an expression as a const generic argument.
2690            // We do not want to recurse into those.
2691            fn visit_expr(&mut self, _: &'ra Expr) {}
2692        }
2693
2694        let impl_self = self
2695            .diag_metadata
2696            .current_self_type
2697            .as_ref()
2698            .and_then(|ty| {
2699                if let TyKind::Path(None, _) = ty.kind {
2700                    self.r.partial_res_map.get(&ty.id)
2701                } else {
2702                    None
2703                }
2704            })
2705            .and_then(|res| res.full_res())
2706            .filter(|res| {
2707                // Permit the types that unambiguously always
2708                // result in the same type constructor being used
2709                // (it can't differ between `Self` and `self`).
2710                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _) |
        Res::PrimTy(_) => true,
    _ => false,
}matches!(
2711                    res,
2712                    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2713                )
2714            });
2715        let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2716        visitor.visit_ty(ty);
2717        {
    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/late.rs:2717",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2717u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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!("FindReferenceVisitor found={0:?}",
                                                    visitor.lifetime) as &dyn Value))])
            });
    } else { ; }
};trace!("FindReferenceVisitor found={:?}", visitor.lifetime);
2718        visitor.lifetime
2719    }
2720
2721    /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
2722    /// label and reports an error if the label is not found or is unreachable.
2723    fn resolve_label(&self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2724        let mut suggestion = None;
2725
2726        for i in (0..self.label_ribs.len()).rev() {
2727            let rib = &self.label_ribs[i];
2728
2729            if let RibKind::MacroDefinition(def) = rib.kind
2730                // If an invocation of this macro created `ident`, give up on `ident`
2731                // and switch to `ident`'s source from the macro definition.
2732                && def == self.r.macro_def(label.span.ctxt())
2733            {
2734                label.span.remove_mark();
2735            }
2736
2737            let ident = label.normalize_to_macro_rules();
2738            if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2739                let definition_span = ident.span;
2740                return if self.is_label_valid_from_rib(i) {
2741                    Ok((*id, definition_span))
2742                } else {
2743                    Err(ResolutionError::UnreachableLabel {
2744                        name: label.name,
2745                        definition_span,
2746                        suggestion,
2747                    })
2748                };
2749            }
2750
2751            // Diagnostics: Check if this rib contains a label with a similar name, keep track of
2752            // the first such label that is encountered.
2753            suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2754        }
2755
2756        Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2757    }
2758
2759    /// Determine whether or not a label from the `rib_index`th label rib is reachable.
2760    fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2761        let ribs = &self.label_ribs[rib_index + 1..];
2762        ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2763    }
2764
2765    fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2766        {
    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/late.rs:2766",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2766u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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_adt")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_adt");
2767        let kind = self.r.tcx.def_kind(self.r.current_owner.def_id);
2768        self.with_current_self_item(item, |this| {
2769            this.with_generic_param_rib(
2770                &generics.params,
2771                RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2772                item.id,
2773                LifetimeBinderKind::Item,
2774                generics.span,
2775                |this| {
2776                    let item_def_id = this.r.current_owner.def_id.to_def_id();
2777                    this.with_self_rib(
2778                        Res::SelfTyAlias { alias_to: item_def_id, is_trait_impl: false },
2779                        |this| {
2780                            visit::walk_item(this, item);
2781                        },
2782                    );
2783                },
2784            );
2785        });
2786    }
2787
2788    fn future_proof_import(&mut self, use_tree: &UseTree) {
2789        if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2790            let ident = segment.ident;
2791            if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2792                return;
2793            }
2794
2795            let nss = match use_tree.kind {
2796                UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2797                _ => &[TypeNS],
2798            };
2799            let report_error = |this: &Self, ns| {
2800                if this.should_report_errs() {
2801                    let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2802                    this.r.dcx().emit_err(errors::ImportsCannotReferTo { span: ident.span, what });
2803                }
2804            };
2805
2806            for &ns in nss {
2807                match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2808                    Some(LateDecl::RibDef(..)) => {
2809                        report_error(self, ns);
2810                    }
2811                    Some(LateDecl::Decl(binding)) => {
2812                        if let Some(LateDecl::RibDef(..)) =
2813                            self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2814                        {
2815                            report_error(self, ns);
2816                        }
2817                    }
2818                    None => {}
2819                }
2820            }
2821        } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2822            for (use_tree, _) in items {
2823                self.future_proof_import(use_tree);
2824            }
2825        }
2826    }
2827
2828    fn resolve_item(&mut self, item: &'ast Item) {
2829        let mod_inner_docs =
2830            #[allow(non_exhaustive_omitted_patterns)] match item.kind {
    ItemKind::Mod(..) => true,
    _ => false,
}matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2831        if !mod_inner_docs && !#[allow(non_exhaustive_omitted_patterns)] match item.kind {
    ItemKind::Impl(..) | ItemKind::Use(..) => true,
    _ => false,
}matches!(item.kind, ItemKind::Impl(..) | ItemKind::Use(..)) {
2832            self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2833        }
2834
2835        {
    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/late.rs:2835",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2835u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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!("(resolving item) resolving {0:?} ({1:?})",
                                                    item.kind.ident(), item.kind) as &dyn Value))])
            });
    } else { ; }
};debug!("(resolving item) resolving {:?} ({:?})", item.kind.ident(), item.kind);
2836
2837        let def_kind = self.r.tcx.def_kind(self.r.current_owner.def_id);
2838        match &item.kind {
2839            ItemKind::TyAlias(TyAlias { generics, .. }) => {
2840                self.with_generic_param_rib(
2841                    &generics.params,
2842                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2843                    item.id,
2844                    LifetimeBinderKind::Item,
2845                    generics.span,
2846                    |this| visit::walk_item(this, item),
2847                );
2848            }
2849
2850            ItemKind::Fn(Fn { generics, define_opaque, .. }) => {
2851                self.with_generic_param_rib(
2852                    &generics.params,
2853                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2854                    item.id,
2855                    LifetimeBinderKind::Function,
2856                    generics.span,
2857                    |this| visit::walk_item(this, item),
2858                );
2859                self.resolve_define_opaques(define_opaque);
2860            }
2861
2862            ItemKind::Enum(_, generics, _)
2863            | ItemKind::Struct(_, generics, _)
2864            | ItemKind::Union(_, generics, _) => {
2865                self.resolve_adt(item, generics);
2866            }
2867
2868            ItemKind::Impl(Impl { generics, of_trait, self_ty, items: impl_items, .. }) => {
2869                self.diag_metadata.current_impl_items = Some(impl_items);
2870                self.resolve_implementation(
2871                    &item.attrs,
2872                    generics,
2873                    of_trait.as_deref(),
2874                    self_ty,
2875                    item.id,
2876                    impl_items,
2877                );
2878                self.diag_metadata.current_impl_items = None;
2879            }
2880
2881            ItemKind::Trait(Trait { generics, bounds, items, impl_restriction, .. }) => {
2882                // resolve paths for `impl` restrictions
2883                self.resolve_impl_restriction_path(impl_restriction);
2884
2885                // Create a new rib for the trait-wide type parameters.
2886                self.with_generic_param_rib(
2887                    &generics.params,
2888                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2889                    item.id,
2890                    LifetimeBinderKind::Item,
2891                    generics.span,
2892                    |this| {
2893                        let local_def_id = this.r.current_owner.def_id.to_def_id();
2894                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2895                            this.visit_generics(generics);
2896                            for elem in bounds {
    match ::rustc_ast_ir::visit::VisitorResult::branch(this.visit_param_bound(elem,
                BoundKind::SuperTraits)) {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2897                            this.resolve_trait_items(items);
2898                        });
2899                    },
2900                );
2901            }
2902
2903            ItemKind::TraitAlias(TraitAlias { generics, bounds, .. }) => {
2904                // Create a new rib for the trait-wide type parameters.
2905                self.with_generic_param_rib(
2906                    &generics.params,
2907                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2908                    item.id,
2909                    LifetimeBinderKind::Item,
2910                    generics.span,
2911                    |this| {
2912                        let local_def_id = this.r.current_owner.def_id.to_def_id();
2913                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2914                            this.visit_generics(generics);
2915                            for elem in bounds {
    match ::rustc_ast_ir::visit::VisitorResult::branch(this.visit_param_bound(elem,
                BoundKind::Bound)) {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2916                        });
2917                    },
2918                );
2919            }
2920
2921            ItemKind::Mod(..) => {
2922                let module = self.r.expect_module(self.r.current_owner.def_id.to_def_id());
2923                let orig_module = replace(&mut self.parent_scope.module, module);
2924                self.with_rib(ValueNS, RibKind::Module(module.expect_local()), |this| {
2925                    this.with_rib(TypeNS, RibKind::Module(module.expect_local()), |this| {
2926                        if mod_inner_docs {
2927                            this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2928                        }
2929                        let old_macro_rules = this.parent_scope.macro_rules;
2930                        visit::walk_item(this, item);
2931                        // Maintain macro_rules scopes in the same way as during early resolution
2932                        // for diagnostics and doc links.
2933                        if item.attrs.iter().all(|attr| {
2934                            !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2935                        }) {
2936                            this.parent_scope.macro_rules = old_macro_rules;
2937                        }
2938                    })
2939                });
2940                self.parent_scope.module = orig_module;
2941            }
2942
2943            ItemKind::Static(ast::StaticItem {
2944                ident, ty, expr, define_opaque, eii_impls, ..
2945            }) => {
2946                self.with_static_rib(def_kind, |this| {
2947                    this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2948                        this.visit_ty(ty);
2949                    });
2950                    if let Some(expr) = expr {
2951                        // We already forbid generic params because of the above item rib,
2952                        // so it doesn't matter whether this is a trivial constant.
2953                        this.resolve_static_body(expr, Some((*ident, ConstantItemKind::Static)));
2954                    }
2955                });
2956                self.resolve_define_opaques(define_opaque);
2957                self.resolve_eii(&eii_impls);
2958            }
2959
2960            ItemKind::Const(ast::ConstItem {
2961                ident,
2962                generics,
2963                ty,
2964                rhs_kind,
2965                define_opaque,
2966                defaultness: _,
2967            }) => {
2968                self.with_generic_param_rib(
2969                    &generics.params,
2970                    RibKind::Item(
2971                        if self.r.tcx.features().generic_const_items() {
2972                            HasGenericParams::Yes(generics.span)
2973                        } else {
2974                            HasGenericParams::No
2975                        },
2976                        def_kind,
2977                    ),
2978                    item.id,
2979                    LifetimeBinderKind::ConstItem,
2980                    generics.span,
2981                    |this| {
2982                        this.visit_generics(generics);
2983
2984                        this.with_lifetime_rib(
2985                            LifetimeRibKind::Elided(LifetimeRes::Static),
2986                            |this| {
2987                                if rhs_kind.is_type_const()
2988                                    && !this.r.tcx.features().generic_const_parameter_types()
2989                                {
2990                                    this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
2991                                        this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
2992                                            this.with_lifetime_rib(
2993                                                LifetimeRibKind::ConstParamTy,
2994                                                |this| this.visit_ty(ty),
2995                                            )
2996                                        })
2997                                    });
2998                                } else {
2999                                    this.visit_ty(ty);
3000                                }
3001                            },
3002                        );
3003
3004                        this.resolve_const_item_rhs(
3005                            rhs_kind,
3006                            Some((*ident, ConstantItemKind::Const)),
3007                        );
3008                    },
3009                );
3010                self.resolve_define_opaques(define_opaque);
3011            }
3012            ItemKind::ConstBlock(ConstBlockItem { id: _, span: _, block }) => self
3013                .with_generic_param_rib(
3014                    &[],
3015                    RibKind::Item(HasGenericParams::No, def_kind),
3016                    item.id,
3017                    LifetimeBinderKind::ConstItem,
3018                    DUMMY_SP,
3019                    |this| {
3020                        this.with_lifetime_rib(
3021                            LifetimeRibKind::Elided(LifetimeRes::Infer),
3022                            |this| {
3023                                this.with_constant_rib(
3024                                    IsRepeatExpr::No,
3025                                    ConstantHasGenerics::Yes,
3026                                    Some((ConstBlockItem::IDENT, ConstantItemKind::Const)),
3027                                    |this| this.resolve_labeled_block(None, block.id, block),
3028                                )
3029                            },
3030                        );
3031                    },
3032                ),
3033
3034            ItemKind::Use(use_tree) => {
3035                let maybe_exported = match use_tree.kind {
3036                    UseTreeKind::Simple(_) | UseTreeKind::Glob(_) => MaybeExported::Ok(item.id),
3037                    UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
3038                };
3039                self.resolve_doc_links(&item.attrs, maybe_exported);
3040
3041                self.future_proof_import(use_tree);
3042            }
3043
3044            ItemKind::MacroDef(_, macro_def) => {
3045                // Maintain macro_rules scopes in the same way as during early resolution
3046                // for diagnostics and doc links.
3047                if macro_def.macro_rules {
3048                    let def_id = self.r.current_owner.def_id;
3049                    self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
3050                }
3051
3052                if let Some(EiiDecl { foreign_item: extern_item_path, impl_unsafe: _ }) =
3053                    &macro_def.eii_declaration
3054                {
3055                    self.smart_resolve_path(
3056                        item.id,
3057                        &None,
3058                        extern_item_path,
3059                        PathSource::ExternItemImpl,
3060                    );
3061                }
3062            }
3063
3064            ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
3065                visit::walk_item(self, item);
3066            }
3067
3068            ItemKind::Delegation(delegation) => {
3069                let span = delegation.path.segments.last().unwrap().ident.span;
3070                self.with_generic_param_rib(
3071                    &[],
3072                    RibKind::Item(HasGenericParams::Yes(span), def_kind),
3073                    item.id,
3074                    LifetimeBinderKind::Function,
3075                    span,
3076                    |this| this.resolve_delegation(delegation, item.id, false),
3077                );
3078            }
3079
3080            ItemKind::ExternCrate(..) => {}
3081
3082            ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
3083                {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3084            }
3085        }
3086    }
3087
3088    fn with_generic_param_rib<F>(
3089        &mut self,
3090        params: &[GenericParam],
3091        kind: RibKind<'ra>,
3092        binder: NodeId,
3093        generics_kind: LifetimeBinderKind,
3094        generics_span: Span,
3095        f: F,
3096    ) where
3097        F: FnOnce(&mut Self),
3098    {
3099        {
    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/late.rs:3099",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3099u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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!("with_generic_param_rib")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("with_generic_param_rib");
3100        let lifetime_kind =
3101            LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind };
3102
3103        let mut function_type_rib = Rib::new(kind);
3104        let mut function_value_rib = Rib::new(kind);
3105        let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
3106
3107        // Only check for shadowed bindings if we're declaring new params.
3108        if !params.is_empty() {
3109            let mut seen_bindings = FxHashMap::default();
3110            // Store all seen lifetimes names from outer scopes.
3111            let mut seen_lifetimes = FxHashSet::default();
3112
3113            // We also can't shadow bindings from associated parent items.
3114            for ns in [ValueNS, TypeNS] {
3115                for parent_rib in self.ribs[ns].iter().rev() {
3116                    // Break at module or block level, to account for nested items which are
3117                    // allowed to shadow generic param names.
3118                    if #[allow(non_exhaustive_omitted_patterns)] match parent_rib.kind {
    RibKind::Module(..) | RibKind::Block(..) => true,
    _ => false,
}matches!(parent_rib.kind, RibKind::Module(..) | RibKind::Block(..)) {
3119                        break;
3120                    }
3121
3122                    seen_bindings
3123                        .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
3124                }
3125            }
3126
3127            // Forbid shadowing lifetime bindings
3128            for rib in self.lifetime_ribs.iter().rev() {
3129                seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
3130                if let LifetimeRibKind::Item = rib.kind {
3131                    break;
3132                }
3133            }
3134
3135            for param in params {
3136                let ident = param.ident.normalize_to_macros_2_0();
3137                {
    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/late.rs:3137",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3137u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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!("with_generic_param_rib: {0}",
                                                    param.id) as &dyn Value))])
            });
    } else { ; }
};debug!("with_generic_param_rib: {}", param.id);
3138
3139                if let GenericParamKind::Lifetime = param.kind
3140                    && let Some(&original) = seen_lifetimes.get(&ident)
3141                {
3142                    let guar = diagnostics::signal_lifetime_shadowing(
3143                        self.r.tcx.sess,
3144                        original,
3145                        param.ident,
3146                    );
3147                    // Record lifetime res, so lowering knows there is something fishy.
3148                    self.record_lifetime_param(param.id, LifetimeRes::Error(guar));
3149                    continue;
3150                }
3151
3152                match seen_bindings.entry(ident) {
3153                    Entry::Occupied(entry) => {
3154                        let span = *entry.get();
3155                        let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
3156                        let guar = self.r.report_error(param.ident.span, err);
3157                        let rib = match param.kind {
3158                            GenericParamKind::Lifetime => {
3159                                // Record lifetime res, so lowering knows there is something fishy.
3160                                self.record_lifetime_param(param.id, LifetimeRes::Error(guar));
3161                                continue;
3162                            }
3163                            GenericParamKind::Type { .. } => &mut function_type_rib,
3164                            GenericParamKind::Const { .. } => &mut function_value_rib,
3165                        };
3166
3167                        // Taint the resolution in case of errors to prevent follow up errors in typeck
3168                        self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
3169                        rib.bindings.insert(ident, Res::Err);
3170                        continue;
3171                    }
3172                    Entry::Vacant(entry) => {
3173                        entry.insert(param.ident.span);
3174                    }
3175                }
3176
3177                if param.ident.name == kw::UnderscoreLifetime {
3178                    // To avoid emitting two similar errors,
3179                    // we need to check if the span is a raw underscore lifetime, see issue #143152
3180                    let is_raw_underscore_lifetime = self
3181                        .r
3182                        .tcx
3183                        .sess
3184                        .psess
3185                        .raw_identifier_spans
3186                        .iter()
3187                        .any(|span| span == param.span());
3188
3189                    let guar = self
3190                        .r
3191                        .dcx()
3192                        .create_err(errors::UnderscoreLifetimeIsReserved { span: param.ident.span })
3193                        .emit_unless_delay(is_raw_underscore_lifetime);
3194                    // Record lifetime res, so lowering knows there is something fishy.
3195                    self.record_lifetime_param(param.id, LifetimeRes::Error(guar));
3196                    continue;
3197                }
3198
3199                if param.ident.name == kw::StaticLifetime {
3200                    let guar = self.r.dcx().emit_err(errors::StaticLifetimeIsReserved {
3201                        span: param.ident.span,
3202                        lifetime: param.ident,
3203                    });
3204                    // Record lifetime res, so lowering knows there is something fishy.
3205                    self.record_lifetime_param(param.id, LifetimeRes::Error(guar));
3206                    continue;
3207                }
3208
3209                let def_id = self.r.local_def_id(param.id);
3210
3211                // Plain insert (no renaming).
3212                let (rib, def_kind) = match param.kind {
3213                    GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
3214                    GenericParamKind::Const { .. } => {
3215                        (&mut function_value_rib, DefKind::ConstParam)
3216                    }
3217                    GenericParamKind::Lifetime => {
3218                        let res = LifetimeRes::Param { param: def_id, binder };
3219                        self.record_lifetime_param(param.id, res);
3220                        function_lifetime_rib.bindings.insert(ident, (param.id, res));
3221                        continue;
3222                    }
3223                };
3224
3225                let res = match kind {
3226                    RibKind::Item(..) | RibKind::AssocItem => {
3227                        Res::Def(def_kind, def_id.to_def_id())
3228                    }
3229                    RibKind::Normal => {
3230                        // FIXME(non_lifetime_binders): Stop special-casing
3231                        // const params to error out here.
3232                        if self.r.tcx.features().non_lifetime_binders()
3233                            && #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    GenericParamKind::Type { .. } => true,
    _ => false,
}matches!(param.kind, GenericParamKind::Type { .. })
3234                        {
3235                            Res::Def(def_kind, def_id.to_def_id())
3236                        } else {
3237                            Res::Err
3238                        }
3239                    }
3240                    _ => ::rustc_middle::util::bug::span_bug_fmt(param.ident.span,
    format_args!("Unexpected rib kind {0:?}", kind))span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
3241                };
3242                self.r.record_partial_res(param.id, PartialRes::new(res));
3243                rib.bindings.insert(ident, res);
3244            }
3245        }
3246
3247        self.lifetime_ribs.push(function_lifetime_rib);
3248        self.ribs[ValueNS].push(function_value_rib);
3249        self.ribs[TypeNS].push(function_type_rib);
3250
3251        f(self);
3252
3253        self.ribs[TypeNS].pop();
3254        self.ribs[ValueNS].pop();
3255        let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
3256
3257        // Do not account for the parameters we just bound for function lifetime elision.
3258        if let Some(ref mut candidates) = self.lifetime_elision_candidates {
3259            for (_, res) in function_lifetime_rib.bindings.values() {
3260                candidates.retain(|(r, _)| r != res);
3261            }
3262        }
3263
3264        if let LifetimeBinderKind::FnPtrType
3265        | LifetimeBinderKind::WhereBound
3266        | LifetimeBinderKind::Function
3267        | LifetimeBinderKind::ImplBlock = generics_kind
3268        {
3269            self.maybe_report_lifetime_uses(generics_span, params)
3270        }
3271    }
3272
3273    fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
3274        self.label_ribs.push(Rib::new(kind));
3275        f(self);
3276        self.label_ribs.pop();
3277    }
3278
3279    fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
3280        let kind = RibKind::Item(HasGenericParams::No, def_kind);
3281        self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
3282    }
3283
3284    // HACK(min_const_generics, generic_const_exprs): We
3285    // want to keep allowing `[0; size_of::<*mut T>()]`
3286    // with a future compat lint for now. We do this by adding an
3287    // additional special case for repeat expressions.
3288    //
3289    // Note that we intentionally still forbid `[0; N + 1]` during
3290    // name resolution so that we don't extend the future
3291    // compat lint to new cases.
3292    #[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("with_constant_rib",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3292u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["is_repeat",
                                                    "may_use_generics", "item"],
                                        ::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(&is_repeat)
                                                            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(&may_use_generics)
                                                            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(&item)
                                                            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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let f =
                |this: &mut Self|
                    {
                        this.with_rib(ValueNS,
                            RibKind::ConstantItem(may_use_generics, item),
                            |this|
                                {
                                    this.with_rib(TypeNS,
                                        RibKind::ConstantItem(may_use_generics.force_yes_if(is_repeat
                                                    == IsRepeatExpr::Yes), item),
                                        |this|
                                            {
                                                this.with_label_rib(RibKind::ConstantItem(may_use_generics,
                                                        item), f);
                                            })
                                })
                    };
            if let ConstantHasGenerics::No(cause) = may_use_generics {
                self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause),
                    f)
            } else { f(self) }
        }
    }
}#[instrument(level = "debug", skip(self, f))]
3293    fn with_constant_rib(
3294        &mut self,
3295        is_repeat: IsRepeatExpr,
3296        may_use_generics: ConstantHasGenerics,
3297        item: Option<(Ident, ConstantItemKind)>,
3298        f: impl FnOnce(&mut Self),
3299    ) {
3300        let f = |this: &mut Self| {
3301            this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3302                this.with_rib(
3303                    TypeNS,
3304                    RibKind::ConstantItem(
3305                        may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3306                        item,
3307                    ),
3308                    |this| {
3309                        this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3310                    },
3311                )
3312            })
3313        };
3314
3315        if let ConstantHasGenerics::No(cause) = may_use_generics {
3316            self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3317        } else {
3318            f(self)
3319        }
3320    }
3321
3322    fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
3323        // Handle nested impls (inside fn bodies)
3324        let previous_value =
3325            replace(&mut self.diag_metadata.current_self_type, Some(self_type.clone()));
3326        let result = f(self);
3327        self.diag_metadata.current_self_type = previous_value;
3328        result
3329    }
3330
3331    fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3332        let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3333        let result = f(self);
3334        self.diag_metadata.current_self_item = previous_value;
3335        result
3336    }
3337
3338    /// When evaluating a `trait` use its associated types' idents for suggestions in E0425.
3339    fn resolve_trait_items(&mut self, trait_items: &'ast [Box<AssocItem>]) {
3340        let trait_assoc_items =
3341            replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3342
3343        for item in trait_items {
3344            with_owner(self, item.id, |this| this.resolve_trait_item(item));
3345        }
3346
3347        self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3348    }
3349
3350    fn resolve_trait_item(&mut self, item: &'ast Item<AssocItemKind>) {
3351        let walk_assoc_item =
3352            |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3353                this.with_generic_param_rib(
3354                    &generics.params,
3355                    RibKind::AssocItem,
3356                    item.id,
3357                    kind,
3358                    generics.span,
3359                    |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3360                );
3361            };
3362
3363        self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3364        match &item.kind {
3365            AssocItemKind::Const(ast::ConstItem {
3366                generics, ty, rhs_kind, define_opaque, ..
3367            }) => {
3368                self.with_generic_param_rib(
3369                    &generics.params,
3370                    RibKind::AssocItem,
3371                    item.id,
3372                    LifetimeBinderKind::ConstItem,
3373                    generics.span,
3374                    |this| {
3375                        this.with_lifetime_rib(
3376                            LifetimeRibKind::StaticIfNoLifetimeInScope {
3377                                lint_id: item.id,
3378                                emit_lint: false,
3379                            },
3380                            |this| {
3381                                this.visit_generics(generics);
3382                                if rhs_kind.is_type_const()
3383                                    && !this.r.tcx.features().generic_const_parameter_types()
3384                                {
3385                                    this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3386                                        this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
3387                                            this.with_lifetime_rib(
3388                                                LifetimeRibKind::ConstParamTy,
3389                                                |this| this.visit_ty(ty),
3390                                            )
3391                                        })
3392                                    });
3393                                } else {
3394                                    this.visit_ty(ty);
3395                                }
3396
3397                                // Only impose the restrictions of `ConstRibKind` for an
3398                                // actual constant expression in a provided default.
3399                                //
3400                                // We allow arbitrary const expressions inside of associated consts,
3401                                // even if they are potentially not const evaluatable.
3402                                //
3403                                // Type parameters can already be used and as associated consts are
3404                                // not used as part of the type system, this is far less surprising.
3405                                this.resolve_const_item_rhs(rhs_kind, None);
3406                            },
3407                        )
3408                    },
3409                );
3410
3411                self.resolve_define_opaques(define_opaque);
3412            }
3413            AssocItemKind::Fn(Fn { generics, define_opaque, .. }) => {
3414                walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3415
3416                self.resolve_define_opaques(define_opaque);
3417            }
3418            AssocItemKind::Delegation(delegation) => {
3419                self.with_generic_param_rib(
3420                    &[],
3421                    RibKind::AssocItem,
3422                    item.id,
3423                    LifetimeBinderKind::Function,
3424                    delegation.path.segments.last().unwrap().ident.span,
3425                    |this| this.resolve_delegation(delegation, item.id, false),
3426                );
3427            }
3428            AssocItemKind::Type(TyAlias { generics, .. }) => self
3429                .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3430                    walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3431                }),
3432            AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3433                {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3434            }
3435        };
3436    }
3437
3438    /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
3439    fn with_optional_trait_ref<T>(
3440        &mut self,
3441        opt_trait_ref: Option<&TraitRef>,
3442        self_type: &'ast Ty,
3443        f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3444    ) -> T {
3445        let mut new_val = None;
3446        let mut new_id = None;
3447        if let Some(trait_ref) = opt_trait_ref {
3448            let path: Vec<_> = Segment::from_path(&trait_ref.path);
3449            self.diag_metadata.currently_processing_impl_trait =
3450                Some((trait_ref.clone(), self_type.clone()));
3451            let res = self.smart_resolve_path_fragment(
3452                &None,
3453                &path,
3454                PathSource::Trait(AliasPossibility::No),
3455                Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3456                RecordPartialRes::Yes,
3457                None,
3458            );
3459            self.diag_metadata.currently_processing_impl_trait = None;
3460            if let Some(def_id) = res.expect_full_res().opt_def_id() {
3461                new_id = Some(def_id);
3462                new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3463            }
3464        }
3465        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3466        let result = f(self, new_id);
3467        self.current_trait_ref = original_trait_ref;
3468        result
3469    }
3470
3471    fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3472        let mut self_type_rib = Rib::new(RibKind::Normal);
3473
3474        // Plain insert (no renaming, since types are not currently hygienic)
3475        self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3476        self.ribs[ns].push(self_type_rib);
3477        f(self);
3478        self.ribs[ns].pop();
3479    }
3480
3481    fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3482        self.with_self_rib_ns(TypeNS, self_res, f)
3483    }
3484
3485    fn resolve_implementation(
3486        &mut self,
3487        attrs: &[ast::Attribute],
3488        generics: &'ast Generics,
3489        of_trait: Option<&'ast ast::TraitImplHeader>,
3490        self_type: &'ast Ty,
3491        item_id: NodeId,
3492        impl_items: &'ast [Box<AssocItem>],
3493    ) {
3494        {
    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/late.rs:3494",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3494u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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_implementation")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_implementation");
3495        // If applicable, create a rib for the type parameters.
3496        self.with_generic_param_rib(
3497            &generics.params,
3498            RibKind::Item(HasGenericParams::Yes(generics.span), self.r.tcx.def_kind(self.r.current_owner.def_id)),
3499            item_id,
3500            LifetimeBinderKind::ImplBlock,
3501            generics.span,
3502            |this| {
3503                // Dummy self type for better errors if `Self` is used in the trait path.
3504                this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3505                    this.with_lifetime_rib(
3506                        LifetimeRibKind::AnonymousCreateParameter {
3507                            binder: item_id,
3508                            report_in_path: true
3509                        },
3510                        |this| {
3511                            // Resolve the trait reference, if necessary.
3512                            this.with_optional_trait_ref(
3513                                of_trait.map(|t| &t.trait_ref),
3514                                self_type,
3515                                |this, trait_id| {
3516                                    this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3517
3518                                    let item_def_id = this.r.current_owner.def_id;
3519
3520                                    // Register the trait definitions from here.
3521                                    if let Some(trait_id) = trait_id {
3522                                        this.r
3523                                            .trait_impls
3524                                            .entry(trait_id)
3525                                            .or_default()
3526                                            .push(item_def_id);
3527                                    }
3528
3529                                    let item_def_id = item_def_id.to_def_id();
3530                                    let res = Res::SelfTyAlias {
3531                                        alias_to: item_def_id,
3532                                        is_trait_impl: trait_id.is_some(),
3533                                    };
3534                                    this.with_self_rib(res, |this| {
3535                                        if let Some(of_trait) = of_trait {
3536                                            // Resolve type arguments in the trait path.
3537                                            visit::walk_trait_ref(this, &of_trait.trait_ref);
3538                                        }
3539                                        // Resolve the self type.
3540                                        this.visit_ty(self_type);
3541                                        // Resolve the generic parameters.
3542                                        this.visit_generics(generics);
3543
3544                                        // Resolve the items within the impl.
3545                                        this.with_current_self_type(self_type, |this| {
3546                                            this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3547                                                {
    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/late.rs:3547",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3547u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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_implementation with_self_rib_ns(ValueNS, ...)")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
3548                                                let mut seen_trait_items = Default::default();
3549                                                for item in impl_items {
3550                                                    with_owner(this, item.id, |this| {
3551                                                        this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id, of_trait.is_some());
3552                                                    })
3553                                                }
3554                                            });
3555                                        });
3556                                    });
3557                                },
3558                            )
3559                        },
3560                    );
3561                });
3562            },
3563        );
3564    }
3565
3566    fn resolve_impl_item(
3567        &mut self,
3568        item: &'ast AssocItem,
3569        seen_trait_items: &mut FxHashMap<DefId, Span>,
3570        trait_id: Option<DefId>,
3571        is_in_trait_impl: bool,
3572    ) {
3573        use crate::ResolutionError::*;
3574        self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3575        let prev = self.diag_metadata.current_impl_item.take();
3576        self.diag_metadata.current_impl_item = Some(&item);
3577        match &item.kind {
3578            AssocItemKind::Const(ast::ConstItem {
3579                ident,
3580                generics,
3581                ty,
3582                rhs_kind,
3583                define_opaque,
3584                ..
3585            }) => {
3586                {
    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/late.rs:3586",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3586u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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_implementation AssocItemKind::Const")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_implementation AssocItemKind::Const");
3587                self.with_generic_param_rib(
3588                    &generics.params,
3589                    RibKind::AssocItem,
3590                    item.id,
3591                    LifetimeBinderKind::ConstItem,
3592                    generics.span,
3593                    |this| {
3594                        this.with_lifetime_rib(
3595                            // Until these are a hard error, we need to create them within the
3596                            // correct binder, Otherwise the lifetimes of this assoc const think
3597                            // they are lifetimes of the trait.
3598                            LifetimeRibKind::AnonymousCreateParameter {
3599                                binder: item.id,
3600                                report_in_path: true,
3601                            },
3602                            |this| {
3603                                this.with_lifetime_rib(
3604                                    LifetimeRibKind::StaticIfNoLifetimeInScope {
3605                                        lint_id: item.id,
3606                                        // In impls, it's not a hard error yet due to backcompat.
3607                                        emit_lint: true,
3608                                    },
3609                                    |this| {
3610                                        // If this is a trait impl, ensure the const
3611                                        // exists in trait
3612                                        this.check_trait_item(
3613                                            item.id,
3614                                            *ident,
3615                                            *ident,
3616                                            &item.kind,
3617                                            ValueNS,
3618                                            item.span,
3619                                            seen_trait_items,
3620                                            |i, s, c| ConstNotMemberOfTrait(i, s, c),
3621                                        );
3622
3623                                        this.visit_generics(generics);
3624                                        if rhs_kind.is_type_const()
3625                                            && !this
3626                                                .r
3627                                                .tcx
3628                                                .features()
3629                                                .generic_const_parameter_types()
3630                                        {
3631                                            this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3632                                                this.with_rib(
3633                                                    ValueNS,
3634                                                    RibKind::ConstParamTy,
3635                                                    |this| {
3636                                                        this.with_lifetime_rib(
3637                                                            LifetimeRibKind::ConstParamTy,
3638                                                            |this| this.visit_ty(ty),
3639                                                        )
3640                                                    },
3641                                                )
3642                                            });
3643                                        } else {
3644                                            this.visit_ty(ty);
3645                                        }
3646                                        // We allow arbitrary const expressions inside of associated consts,
3647                                        // even if they are potentially not const evaluatable.
3648                                        //
3649                                        // Type parameters can already be used and as associated consts are
3650                                        // not used as part of the type system, this is far less surprising.
3651                                        this.resolve_const_item_rhs(rhs_kind, None);
3652                                    },
3653                                )
3654                            },
3655                        );
3656                    },
3657                );
3658                self.resolve_define_opaques(define_opaque);
3659            }
3660            AssocItemKind::Fn(fn_kind @ Fn { ident, generics, define_opaque, .. }) => {
3661                {
    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/late.rs:3661",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3661u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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_implementation AssocItemKind::Fn")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_implementation AssocItemKind::Fn");
3662                // We also need a new scope for the impl item type parameters.
3663                self.with_generic_param_rib(
3664                    &generics.params,
3665                    RibKind::AssocItem,
3666                    item.id,
3667                    LifetimeBinderKind::Function,
3668                    generics.span,
3669                    |this| {
3670                        let effective_ident = if is_in_trait_impl && fn_kind.is_pin_drop_sugar() {
3671                            Ident::new(sym::pin_drop, ident.span)
3672                        } else {
3673                            *ident
3674                        };
3675                        // If this is a trait impl, ensure the method
3676                        // exists in trait
3677                        this.check_trait_item(
3678                            item.id,
3679                            effective_ident,
3680                            *ident,
3681                            &item.kind,
3682                            ValueNS,
3683                            item.span,
3684                            seen_trait_items,
3685                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3686                        );
3687
3688                        visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3689                    },
3690                );
3691
3692                self.resolve_define_opaques(define_opaque);
3693            }
3694            AssocItemKind::Type(TyAlias { ident, generics, .. }) => {
3695                self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3696                {
    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/late.rs:3696",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3696u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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_implementation AssocItemKind::Type")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_implementation AssocItemKind::Type");
3697                // We also need a new scope for the impl item type parameters.
3698                self.with_generic_param_rib(
3699                    &generics.params,
3700                    RibKind::AssocItem,
3701                    item.id,
3702                    LifetimeBinderKind::ImplAssocType,
3703                    generics.span,
3704                    |this| {
3705                        this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3706                            // If this is a trait impl, ensure the type
3707                            // exists in trait
3708                            this.check_trait_item(
3709                                item.id,
3710                                *ident,
3711                                *ident,
3712                                &item.kind,
3713                                TypeNS,
3714                                item.span,
3715                                seen_trait_items,
3716                                |i, s, c| TypeNotMemberOfTrait(i, s, c),
3717                            );
3718
3719                            visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3720                        });
3721                    },
3722                );
3723                self.diag_metadata.in_non_gat_assoc_type = None;
3724            }
3725            AssocItemKind::Delegation(delegation) => {
3726                {
    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/late.rs:3726",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3726u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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_implementation AssocItemKind::Delegation")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_implementation AssocItemKind::Delegation");
3727                self.with_generic_param_rib(
3728                    &[],
3729                    RibKind::AssocItem,
3730                    item.id,
3731                    LifetimeBinderKind::Function,
3732                    delegation.path.segments.last().unwrap().ident.span,
3733                    |this| {
3734                        this.check_trait_item(
3735                            item.id,
3736                            delegation.ident,
3737                            delegation.ident,
3738                            &item.kind,
3739                            ValueNS,
3740                            item.span,
3741                            seen_trait_items,
3742                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3743                        );
3744
3745                        // Here we don't use `trait_id`, as we can process unresolved trait, however
3746                        // in this case we are still in a trait impl, https://github.com/rust-lang/rust/issues/150152
3747                        this.resolve_delegation(delegation, item.id, is_in_trait_impl);
3748                    },
3749                );
3750            }
3751            AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3752                {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3753            }
3754        }
3755        self.diag_metadata.current_impl_item = prev;
3756    }
3757
3758    fn check_trait_item<F>(
3759        &mut self,
3760        id: NodeId,
3761        mut ident: Ident,
3762        mut reported_ident: Ident,
3763        kind: &AssocItemKind,
3764        ns: Namespace,
3765        span: Span,
3766        seen_trait_items: &mut FxHashMap<DefId, Span>,
3767        err: F,
3768    ) where
3769        F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3770    {
3771        // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3772        let Some((module, _)) = self.current_trait_ref else {
3773            return;
3774        };
3775        ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3776        reported_ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3777        let key = BindingKey::new(IdentKey::new(ident), ns);
3778        let mut decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3779        {
    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/late.rs:3779",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3779u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["decl"],
                            ::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(&debug(&decl) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?decl);
3780        if decl.is_none() {
3781            // We could not find the trait item in the correct namespace.
3782            // Check the other namespace to report an error.
3783            let ns = match ns {
3784                ValueNS => TypeNS,
3785                TypeNS => ValueNS,
3786                _ => ns,
3787            };
3788            let key = BindingKey::new(IdentKey::new(ident), ns);
3789            decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3790            {
    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/late.rs:3790",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3790u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["decl"],
                            ::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(&debug(&decl) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?decl);
3791        }
3792
3793        let feed_visibility = |this: &mut Self, def_id| {
3794            let vis = this.r.tcx.visibility(def_id);
3795            let vis = if vis.is_visible_locally() {
3796                vis.expect_local()
3797            } else {
3798                this.r.dcx().span_delayed_bug(
3799                    span,
3800                    "error should be emitted when an unexpected trait item is used",
3801                );
3802                Visibility::Public
3803            };
3804            // HACK: because we don't want to track the `TyCtxtFeed` through the resolver to here
3805            // in a hash-map, we instead conjure a `TyCtxtFeed` for any `DefId` here, but prevent
3806            // it from being used generally.
3807            this.r.tcx.feed_visibility_for_trait_impl_item(this.r.current_owner.def_id, vis);
3808        };
3809
3810        let Some(decl) = decl else {
3811            // We could not find the method: report an error.
3812            let candidate = self.find_similarly_named_assoc_item(reported_ident.name, kind);
3813            let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3814            let path_names = path_names_to_string(path);
3815            self.report_error(span, err(reported_ident, path_names, candidate));
3816            feed_visibility(self, module.def_id());
3817            return;
3818        };
3819
3820        let res = decl.res();
3821        let Res::Def(def_kind, id_in_trait) = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
3822        feed_visibility(self, id_in_trait);
3823
3824        match seen_trait_items.entry(id_in_trait) {
3825            Entry::Occupied(entry) => {
3826                self.report_error(
3827                    span,
3828                    ResolutionError::TraitImplDuplicate {
3829                        name: ident,
3830                        old_span: *entry.get(),
3831                        trait_item_span: decl.span,
3832                    },
3833                );
3834                return;
3835            }
3836            Entry::Vacant(entry) => {
3837                entry.insert(span);
3838            }
3839        };
3840
3841        match (def_kind, kind) {
3842            (DefKind::AssocTy, AssocItemKind::Type(..))
3843            | (DefKind::AssocFn, AssocItemKind::Fn(..))
3844            | (DefKind::AssocConst { .. }, AssocItemKind::Const(..))
3845            | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3846                self.r.record_partial_res(id, PartialRes::new(res));
3847                return;
3848            }
3849            _ => {}
3850        }
3851
3852        // The method kind does not correspond to what appeared in the trait, report.
3853        let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3854        let (code, kind) = match kind {
3855            AssocItemKind::Const(..) => (E0323, "const"),
3856            AssocItemKind::Fn(..) => (E0324, "method"),
3857            AssocItemKind::Type(..) => (E0325, "type"),
3858            AssocItemKind::Delegation(..) => (E0324, "method"),
3859            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3860                ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("unexpanded macro"))span_bug!(span, "unexpanded macro")
3861            }
3862        };
3863        let trait_path = path_names_to_string(path);
3864        self.report_error(
3865            span,
3866            ResolutionError::TraitImplMismatch {
3867                name: ident,
3868                kind,
3869                code,
3870                trait_path,
3871                trait_item_span: decl.span,
3872            },
3873        );
3874    }
3875
3876    fn resolve_static_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3877        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3878            this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3879                this.visit_expr(expr)
3880            });
3881        })
3882    }
3883
3884    fn resolve_const_item_rhs(
3885        &mut self,
3886        rhs_kind: &'ast ConstItemRhsKind,
3887        item: Option<(Ident, ConstantItemKind)>,
3888    ) {
3889        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| match rhs_kind {
3890            ConstItemRhsKind::TypeConst { rhs: Some(anon_const) } => {
3891                this.resolve_anon_const(anon_const, AnonConstKind::ConstArg(IsRepeatExpr::No));
3892            }
3893            ConstItemRhsKind::Body { rhs: Some(expr) } => {
3894                this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3895                    this.visit_expr(expr)
3896                });
3897            }
3898            _ => (),
3899        })
3900    }
3901
3902    fn resolve_delegation(
3903        &mut self,
3904        delegation: &'ast Delegation,
3905        item_id: NodeId,
3906        is_in_trait_impl: bool,
3907    ) {
3908        self.smart_resolve_path(
3909            delegation.id,
3910            &delegation.qself,
3911            &delegation.path,
3912            PathSource::Delegation,
3913        );
3914
3915        // Create lifetimes not with `LifetimeRibKind::Generics` but with `LifetimeRibKind::Elided`,
3916        // as we are not processing generic params but generic args in a future call (#156342, #156758).
3917        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3918            if let Some(qself) = &delegation.qself {
3919                this.visit_ty(&qself.ty);
3920            }
3921
3922            this.visit_path(&delegation.path);
3923        });
3924
3925        self.r.delegation_infos.insert(
3926            self.r.current_owner.def_id,
3927            DelegationInfo {
3928                resolution_node: if is_in_trait_impl { item_id } else { delegation.id },
3929            },
3930        );
3931
3932        let Some(body) = &delegation.body else { return };
3933        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3934            let ident = Ident::new(kw::SelfLower, body.span.normalize_to_macro_rules());
3935            let res = Res::Local(delegation.id);
3936            this.innermost_rib_bindings(ValueNS).insert(ident, res);
3937
3938            //As we lower target_expr_template body to a body of a function we need a label rib (#148889)
3939            this.with_label_rib(RibKind::FnOrCoroutine, |this| {
3940                this.visit_block(body);
3941            });
3942        });
3943    }
3944
3945    fn resolve_params(&mut self, params: &'ast [Param]) {
3946        let mut bindings = {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push((PatBoundCtx::Product, Default::default()));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [(PatBoundCtx::Product, Default::default())])))
    }
}smallvec![(PatBoundCtx::Product, Default::default())];
3947        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3948            for Param { pat, .. } in params {
3949                this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3950            }
3951            this.apply_pattern_bindings(bindings);
3952        });
3953        for Param { ty, .. } in params {
3954            self.visit_ty(ty);
3955        }
3956    }
3957
3958    fn resolve_local(&mut self, local: &'ast Local) {
3959        {
    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/late.rs:3959",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3959u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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!("resolving local ({0:?})",
                                                    local) as &dyn Value))])
            });
    } else { ; }
};debug!("resolving local ({:?})", local);
3960        // Resolve the type.
3961        if let Some(x) = &local.ty {
    match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_ty(x)) {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};visit_opt!(self, visit_ty, &local.ty);
3962
3963        // Resolve the initializer.
3964        if let Some((init, els)) = local.kind.init_else_opt() {
3965            self.visit_expr(init);
3966
3967            // Resolve the `else` block
3968            if let Some(els) = els {
3969                self.visit_block(els);
3970            }
3971        }
3972
3973        // Resolve the pattern.
3974        self.resolve_pattern_top(&local.pat, PatternSource::Let);
3975    }
3976
3977    /// Build a map from pattern identifiers to binding-info's, and check the bindings are
3978    /// consistent when encountering or-patterns and never patterns.
3979    /// This is done hygienically: this could arise for a macro that expands into an or-pattern
3980    /// where one 'x' was from the user and one 'x' came from the macro.
3981    ///
3982    /// A never pattern by definition indicates an unreachable case. For example, matching on
3983    /// `Result<T, &!>` could look like:
3984    /// ```rust
3985    /// # #![feature(never_type)]
3986    /// # #![feature(never_patterns)]
3987    /// # fn bar(_x: u32) {}
3988    /// let foo: Result<u32, &!> = Ok(0);
3989    /// match foo {
3990    ///     Ok(x) => bar(x),
3991    ///     Err(&!),
3992    /// }
3993    /// ```
3994    /// This extends to product types: `(x, !)` is likewise unreachable. So it doesn't make sense to
3995    /// have a binding here, and we tell the user to use `_` instead.
3996    fn compute_and_check_binding_map(
3997        &mut self,
3998        pat: &Pat,
3999    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
4000        let mut binding_map = FxIndexMap::default();
4001        let mut is_never_pat = false;
4002
4003        pat.walk(&mut |pat| {
4004            match pat.kind {
4005                PatKind::Ident(annotation, ident, ref sub_pat)
4006                    if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
4007                {
4008                    binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
4009                }
4010                PatKind::Or(ref ps) => {
4011                    // Check the consistency of this or-pattern and
4012                    // then add all bindings to the larger map.
4013                    match self.compute_and_check_or_pat_binding_map(ps) {
4014                        Ok(bm) => binding_map.extend(bm),
4015                        Err(IsNeverPattern) => is_never_pat = true,
4016                    }
4017                    return false;
4018                }
4019                PatKind::Never => is_never_pat = true,
4020                _ => {}
4021            }
4022
4023            true
4024        });
4025
4026        if is_never_pat {
4027            for (_, binding) in binding_map {
4028                self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
4029            }
4030            Err(IsNeverPattern)
4031        } else {
4032            Ok(binding_map)
4033        }
4034    }
4035
4036    fn is_base_res_local(&self, nid: NodeId) -> bool {
4037        #[allow(non_exhaustive_omitted_patterns)] match self.r.partial_res_map.get(&nid).map(|res|
            res.expect_full_res()) {
    Some(Res::Local(..)) => true,
    _ => false,
}matches!(
4038            self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
4039            Some(Res::Local(..))
4040        )
4041    }
4042
4043    /// Compute the binding map for an or-pattern. Checks that all of the arms in the or-pattern
4044    /// have exactly the same set of bindings, with the same binding modes for each.
4045    /// Returns the computed binding map and a boolean indicating whether the pattern is a never
4046    /// pattern.
4047    ///
4048    /// A never pattern by definition indicates an unreachable case. For example, destructuring a
4049    /// `Result<T, &!>` could look like:
4050    /// ```rust
4051    /// # #![feature(never_type)]
4052    /// # #![feature(never_patterns)]
4053    /// # fn foo() -> Result<bool, &'static !> { Ok(true) }
4054    /// let (Ok(x) | Err(&!)) = foo();
4055    /// # let _ = x;
4056    /// ```
4057    /// Because the `Err(&!)` branch is never reached, it does not need to have the same bindings as
4058    /// the other branches of the or-pattern. So we must ignore never pattern when checking the
4059    /// bindings of an or-pattern.
4060    /// Moreover, if all the subpatterns are never patterns (e.g. `Ok(!) | Err(!)`), then the
4061    /// pattern as a whole counts as a never pattern (since it's definitionallly unreachable).
4062    fn compute_and_check_or_pat_binding_map(
4063        &mut self,
4064        pats: &[Pat],
4065    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
4066        let mut missing_vars = FxIndexMap::default();
4067        let mut inconsistent_vars = FxIndexMap::default();
4068
4069        // 1) Compute the binding maps of all arms; we must ignore never patterns here.
4070        let not_never_pats = pats
4071            .iter()
4072            .filter_map(|pat| {
4073                let binding_map = self.compute_and_check_binding_map(pat).ok()?;
4074                Some((binding_map, pat))
4075            })
4076            .collect::<Vec<_>>();
4077
4078        // 2) Record any missing bindings or binding mode inconsistencies.
4079        for &(ref map_outer, pat_outer) in not_never_pats.iter() {
4080            // Check against all arms except for the same pattern which is always self-consistent.
4081            let inners = not_never_pats.iter().filter(|(_, pat)| pat.id != pat_outer.id);
4082
4083            for &(ref map, pat) in inners {
4084                for (&name, binding_inner) in map {
4085                    match map_outer.get(&name) {
4086                        None => {
4087                            // The inner binding is missing in the outer.
4088                            let binding_error =
4089                                missing_vars.entry(name).or_insert_with(|| BindingError {
4090                                    name,
4091                                    origin: Default::default(),
4092                                    target: Default::default(),
4093                                    could_be_path: name.as_str().starts_with(char::is_uppercase),
4094                                });
4095                            binding_error.origin.push((binding_inner.span, pat.clone()));
4096                            binding_error.target.push(pat_outer.clone());
4097                        }
4098                        Some(binding_outer) => {
4099                            if binding_outer.annotation != binding_inner.annotation {
4100                                // The binding modes in the outer and inner bindings differ.
4101                                inconsistent_vars
4102                                    .entry(name)
4103                                    .or_insert((binding_inner.span, binding_outer.span));
4104                            }
4105                        }
4106                    }
4107                }
4108            }
4109        }
4110
4111        // 3) Report all missing variables we found.
4112        for (name, mut v) in missing_vars {
4113            if inconsistent_vars.contains_key(&name) {
4114                v.could_be_path = false;
4115            }
4116            self.report_error(
4117                v.origin.iter().next().unwrap().0,
4118                ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
4119            );
4120        }
4121
4122        // 4) Report all inconsistencies in binding modes we found.
4123        for (name, v) in inconsistent_vars {
4124            self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
4125        }
4126
4127        // 5) Bubble up the final binding map.
4128        if not_never_pats.is_empty() {
4129            // All the patterns are never patterns, so the whole or-pattern is one too.
4130            Err(IsNeverPattern)
4131        } else {
4132            let mut binding_map = FxIndexMap::default();
4133            for (bm, _) in not_never_pats {
4134                binding_map.extend(bm);
4135            }
4136            Ok(binding_map)
4137        }
4138    }
4139
4140    /// Check the consistency of bindings wrt or-patterns and never patterns.
4141    fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
4142        let mut is_or_or_never = false;
4143        pat.walk(&mut |pat| match pat.kind {
4144            PatKind::Or(..) | PatKind::Never => {
4145                is_or_or_never = true;
4146                false
4147            }
4148            _ => true,
4149        });
4150        if is_or_or_never {
4151            let _ = self.compute_and_check_binding_map(pat);
4152        }
4153    }
4154
4155    fn resolve_arm(&mut self, arm: &'ast Arm) {
4156        self.with_rib(ValueNS, RibKind::Normal, |this| {
4157            this.resolve_pattern_top(&arm.pat, PatternSource::Match);
4158            if let Some(x) = arm.guard.as_ref().map(|g| &g.cond) {
    match ::rustc_ast_ir::visit::VisitorResult::branch(this.visit_expr(x)) {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};visit_opt!(this, visit_expr, arm.guard.as_ref().map(|g| &g.cond));
4159            if let Some(x) = &arm.body {
    match ::rustc_ast_ir::visit::VisitorResult::branch(this.visit_expr(x)) {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};visit_opt!(this, visit_expr, &arm.body);
4160        });
4161    }
4162
4163    /// Arising from `source`, resolve a top level pattern.
4164    fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
4165        let mut bindings = {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push((PatBoundCtx::Product, Default::default()));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [(PatBoundCtx::Product, Default::default())])))
    }
}smallvec![(PatBoundCtx::Product, Default::default())];
4166        self.resolve_pattern(pat, pat_src, &mut bindings);
4167        self.apply_pattern_bindings(bindings);
4168    }
4169
4170    /// Apply the bindings from a pattern to the innermost rib of the current scope.
4171    fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
4172        let rib_bindings = self.innermost_rib_bindings(ValueNS);
4173        let Some((_, pat_bindings)) = pat_bindings.pop() else {
4174            ::rustc_middle::util::bug::bug_fmt(format_args!("tried applying nonexistent bindings from pattern"));bug!("tried applying nonexistent bindings from pattern");
4175        };
4176
4177        if rib_bindings.is_empty() {
4178            // Often, such as for match arms, the bindings are introduced into a new rib.
4179            // In this case, we can move the bindings over directly.
4180            *rib_bindings = pat_bindings;
4181        } else {
4182            rib_bindings.extend(pat_bindings);
4183        }
4184    }
4185
4186    /// Resolve bindings in a pattern. `apply_pattern_bindings` must be called after to introduce
4187    /// the bindings into scope.
4188    fn resolve_pattern(
4189        &mut self,
4190        pat: &'ast Pat,
4191        pat_src: PatternSource,
4192        bindings: &mut PatternBindings,
4193    ) {
4194        // We walk the pattern before declaring the pattern's inner bindings,
4195        // so that we avoid resolving a literal expression to a binding defined
4196        // by the pattern.
4197        // NB: `Self::visit_pat` must be used rather than `visit::walk_pat` to avoid resolving guard
4198        // patterns' guard expressions multiple times (#141265).
4199        self.visit_pat(pat);
4200        self.resolve_pattern_inner(pat, pat_src, bindings);
4201        // This has to happen *after* we determine which pat_idents are variants:
4202        self.check_consistent_bindings(pat);
4203    }
4204
4205    /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
4206    ///
4207    /// ### `bindings`
4208    ///
4209    /// A stack of sets of bindings accumulated.
4210    ///
4211    /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
4212    /// be interpreted as re-binding an already bound binding. This results in an error.
4213    /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
4214    /// in reusing this binding rather than creating a fresh one.
4215    ///
4216    /// When called at the top level, the stack must have a single element
4217    /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
4218    /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
4219    /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
4220    /// When each `p_i` has been dealt with, the top set is merged with its parent.
4221    /// When a whole or-pattern has been dealt with, the thing happens.
4222    ///
4223    /// See the implementation and `fresh_binding` for more details.
4224    #[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_pattern_inner",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(4224u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["pat", "pat_src"],
                                        ::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(&pat)
                                                            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(&pat_src)
                                                            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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            pat.walk(&mut |pat|
                        {
                            match pat.kind {
                                PatKind::Ident(bmode, ident, ref sub) => {
                                    let has_sub = sub.is_some();
                                    let res =
                                        self.try_resolve_as_non_binding(pat_src, bmode, ident,
                                                has_sub).unwrap_or_else(||
                                                self.fresh_binding(ident, pat.id, pat_src, bindings));
                                    self.r.record_partial_res(pat.id, PartialRes::new(res));
                                    self.r.record_pat_span(pat.id, pat.span);
                                }
                                PatKind::TupleStruct(ref qself, ref path, ref sub_patterns)
                                    => {
                                    self.smart_resolve_path(pat.id, qself, path,
                                        PathSource::TupleStruct(pat.span,
                                            self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p|
                                                        p.span))));
                                }
                                PatKind::Path(ref qself, ref path) => {
                                    self.smart_resolve_path(pat.id, qself, path,
                                        PathSource::Pat);
                                }
                                PatKind::Struct(ref qself, ref path, ref _fields, ref rest)
                                    => {
                                    self.smart_resolve_path(pat.id, qself, path,
                                        PathSource::Struct(None));
                                    self.record_patterns_with_skipped_bindings(pat, rest);
                                }
                                PatKind::Or(ref ps) => {
                                    bindings.push((PatBoundCtx::Or, Default::default()));
                                    for p in ps {
                                        bindings.push((PatBoundCtx::Product, Default::default()));
                                        self.resolve_pattern_inner(p, pat_src, bindings);
                                        let collected = bindings.pop().unwrap().1;
                                        bindings.last_mut().unwrap().1.extend(collected);
                                    }
                                    let collected = bindings.pop().unwrap().1;
                                    bindings.last_mut().unwrap().1.extend(collected);
                                    return false;
                                }
                                PatKind::Guard(ref subpat, ref guard) => {
                                    bindings.push((PatBoundCtx::Product, Default::default()));
                                    let binding_ctx_stack_len = bindings.len();
                                    self.resolve_pattern_inner(subpat, pat_src, bindings);
                                    match (&bindings.len(), &binding_ctx_stack_len) {
                                        (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);
                                            }
                                        }
                                    };
                                    let subpat_bindings = bindings.pop().unwrap().1;
                                    self.with_rib(ValueNS, RibKind::Normal,
                                        |this|
                                            {
                                                *this.innermost_rib_bindings(ValueNS) =
                                                    subpat_bindings.clone();
                                                this.resolve_expr(&guard.cond, None);
                                            });
                                    bindings.last_mut().unwrap().1.extend(subpat_bindings);
                                    return false;
                                }
                                _ => {}
                            }
                            true
                        });
        }
    }
}#[tracing::instrument(skip(self, bindings), level = "debug")]
4225    fn resolve_pattern_inner(
4226        &mut self,
4227        pat: &'ast Pat,
4228        pat_src: PatternSource,
4229        bindings: &mut PatternBindings,
4230    ) {
4231        // Visit all direct subpatterns of this pattern.
4232        pat.walk(&mut |pat| {
4233            match pat.kind {
4234                PatKind::Ident(bmode, ident, ref sub) => {
4235                    // First try to resolve the identifier as some existing entity,
4236                    // then fall back to a fresh binding.
4237                    let has_sub = sub.is_some();
4238                    let res = self
4239                        .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
4240                        .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
4241                    self.r.record_partial_res(pat.id, PartialRes::new(res));
4242                    self.r.record_pat_span(pat.id, pat.span);
4243                }
4244                PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
4245                    self.smart_resolve_path(
4246                        pat.id,
4247                        qself,
4248                        path,
4249                        PathSource::TupleStruct(
4250                            pat.span,
4251                            self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
4252                        ),
4253                    );
4254                }
4255                PatKind::Path(ref qself, ref path) => {
4256                    self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
4257                }
4258                PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
4259                    self.smart_resolve_path(pat.id, qself, path, PathSource::Struct(None));
4260                    self.record_patterns_with_skipped_bindings(pat, rest);
4261                }
4262                PatKind::Or(ref ps) => {
4263                    // Add a new set of bindings to the stack. `Or` here records that when a
4264                    // binding already exists in this set, it should not result in an error because
4265                    // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
4266                    bindings.push((PatBoundCtx::Or, Default::default()));
4267                    for p in ps {
4268                        // Now we need to switch back to a product context so that each
4269                        // part of the or-pattern internally rejects already bound names.
4270                        // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
4271                        bindings.push((PatBoundCtx::Product, Default::default()));
4272                        self.resolve_pattern_inner(p, pat_src, bindings);
4273                        // Move up the non-overlapping bindings to the or-pattern.
4274                        // Existing bindings just get "merged".
4275                        let collected = bindings.pop().unwrap().1;
4276                        bindings.last_mut().unwrap().1.extend(collected);
4277                    }
4278                    // This or-pattern itself can itself be part of a product,
4279                    // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
4280                    // Both cases bind `a` again in a product pattern and must be rejected.
4281                    let collected = bindings.pop().unwrap().1;
4282                    bindings.last_mut().unwrap().1.extend(collected);
4283
4284                    // Prevent visiting `ps` as we've already done so above.
4285                    return false;
4286                }
4287                PatKind::Guard(ref subpat, ref guard) => {
4288                    // Add a new set of bindings to the stack to collect bindings in `subpat`.
4289                    bindings.push((PatBoundCtx::Product, Default::default()));
4290                    // Resolving `subpat` adds bindings onto the newly-pushed context. After, the
4291                    // total number of contexts on the stack should be the same as before.
4292                    let binding_ctx_stack_len = bindings.len();
4293                    self.resolve_pattern_inner(subpat, pat_src, bindings);
4294                    assert_eq!(bindings.len(), binding_ctx_stack_len);
4295                    // These bindings, but none from the surrounding pattern, are visible in the
4296                    // guard; put them in scope and resolve `guard`.
4297                    let subpat_bindings = bindings.pop().unwrap().1;
4298                    self.with_rib(ValueNS, RibKind::Normal, |this| {
4299                        *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
4300                        this.resolve_expr(&guard.cond, None);
4301                    });
4302                    // Propagate the subpattern's bindings upwards.
4303                    // FIXME(guard_patterns): For `if let` guards, we'll also need to get the
4304                    // bindings introduced by the guard from its rib and propagate them upwards.
4305                    // This will require checking the identifiers for overlaps with `bindings`, like
4306                    // what `fresh_binding` does (ideally sharing its logic). To keep them separate
4307                    // from `subpat_bindings`, we can introduce a fresh rib for the guard.
4308                    bindings.last_mut().unwrap().1.extend(subpat_bindings);
4309                    // Prevent visiting `subpat` as we've already done so above.
4310                    return false;
4311                }
4312                _ => {}
4313            }
4314            true
4315        });
4316    }
4317
4318    fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
4319        match rest {
4320            ast::PatFieldsRest::Rest(_) | ast::PatFieldsRest::Recovered(_) => {
4321                // Record that the pattern doesn't introduce all the bindings it could.
4322                if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
4323                    && let Some(res) = partial_res.full_res()
4324                    && let Some(def_id) = res.opt_def_id()
4325                {
4326                    self.ribs[ValueNS]
4327                        .last_mut()
4328                        .unwrap()
4329                        .patterns_with_skipped_bindings
4330                        .entry(def_id)
4331                        .or_default()
4332                        .push((
4333                            pat.span,
4334                            match rest {
4335                                ast::PatFieldsRest::Recovered(guar) => Err(*guar),
4336                                _ => Ok(()),
4337                            },
4338                        ));
4339                }
4340            }
4341            ast::PatFieldsRest::None => {}
4342        }
4343    }
4344
4345    fn fresh_binding(
4346        &mut self,
4347        ident: Ident,
4348        pat_id: NodeId,
4349        pat_src: PatternSource,
4350        bindings: &mut PatternBindings,
4351    ) -> Res {
4352        // Add the binding to the bindings map, if it doesn't already exist.
4353        // (We must not add it if it's in the bindings map because that breaks the assumptions
4354        // later passes make about or-patterns.)
4355        let ident = ident.normalize_to_macro_rules();
4356
4357        // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
4358        let already_bound_and = bindings
4359            .iter()
4360            .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
4361        if already_bound_and {
4362            // Overlap in a product pattern somewhere; report an error.
4363            use ResolutionError::*;
4364            let error = match pat_src {
4365                // `fn f(a: u8, a: u8)`:
4366                PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
4367                // `Variant(a, a)`:
4368                _ => IdentifierBoundMoreThanOnceInSamePattern,
4369            };
4370            self.report_error(ident.span, error(ident));
4371        }
4372
4373        // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
4374        // This is *required* for consistency which is checked later.
4375        let already_bound_or = bindings
4376            .iter()
4377            .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
4378        let res = if let Some(&res) = already_bound_or {
4379            // `Variant1(a) | Variant2(a)`, ok
4380            // Reuse definition from the first `a`.
4381            res
4382        } else {
4383            // A completely fresh binding is added to the map.
4384            Res::Local(pat_id)
4385        };
4386
4387        // Record as bound.
4388        bindings.last_mut().unwrap().1.insert(ident, res);
4389        res
4390    }
4391
4392    fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4393        &mut self.ribs[ns].last_mut().unwrap().bindings
4394    }
4395
4396    fn try_resolve_as_non_binding(
4397        &mut self,
4398        pat_src: PatternSource,
4399        ann: BindingMode,
4400        ident: Ident,
4401        has_sub: bool,
4402    ) -> Option<Res> {
4403        // An immutable (no `mut`) by-value (no `ref`) binding pattern without
4404        // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
4405        // also be interpreted as a path to e.g. a constant, variant, etc.
4406        let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4407
4408        let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4409        let (res, binding) = match ls_binding {
4410            LateDecl::Decl(binding)
4411                if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4412            {
4413                // For ambiguous bindings we don't know all their definitions and cannot check
4414                // whether they can be shadowed by fresh bindings or not, so force an error.
4415                // issues/33118#issuecomment-233962221 (see below) still applies here,
4416                // but we have to ignore it for backward compatibility.
4417                self.r.record_use(ident, binding, Used::Other);
4418                return None;
4419            }
4420            LateDecl::Decl(binding) => (binding.res(), Some(binding)),
4421            LateDecl::RibDef(res) => (res, None),
4422        };
4423
4424        match res {
4425            Res::SelfCtor(_) // See #70549.
4426            | Res::Def(
4427                DefKind::Ctor(_, CtorKind::Const) | DefKind::Const { .. } | DefKind::AssocConst { .. } | DefKind::ConstParam,
4428                _,
4429            ) if is_syntactic_ambiguity => {
4430                // Disambiguate in favor of a unit struct/variant or constant pattern.
4431                if let Some(binding) = binding {
4432                    self.r.record_use(ident, binding, Used::Other);
4433                }
4434                Some(res)
4435            }
4436            Res::Def(
4437                DefKind::Ctor(..)
4438                | DefKind::Const { .. }
4439                | DefKind::AssocConst { .. }
4440                | DefKind::Static { .. },
4441                _,
4442            ) => {
4443                // This is unambiguously a fresh binding, either syntactically
4444                // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
4445                // to something unusable as a pattern (e.g., constructor function),
4446                // but we still conservatively report an error, see
4447                // issues/33118#issuecomment-233962221 for one reason why.
4448                let binding = binding.expect("no binding for a ctor or static");
4449                self.report_error(
4450                    ident.span,
4451                    ResolutionError::BindingShadowsSomethingUnacceptable {
4452                        shadowing_binding: pat_src,
4453                        name: ident.name,
4454                        participle: if binding.is_import() { "imported" } else { "defined" },
4455                        article: binding.res().article(),
4456                        shadowed_binding: binding.res(),
4457                        shadowed_binding_span: binding.span,
4458                    },
4459                );
4460                None
4461            }
4462            Res::Def(DefKind::ConstParam, def_id) => {
4463                // Same as for DefKind::Const { .. } above, but here, `binding` is `None`, so we
4464                // have to construct the error differently
4465                self.report_error(
4466                    ident.span,
4467                    ResolutionError::BindingShadowsSomethingUnacceptable {
4468                        shadowing_binding: pat_src,
4469                        name: ident.name,
4470                        participle: "defined",
4471                        article: res.article(),
4472                        shadowed_binding: res,
4473                        shadowed_binding_span: self.r.def_span(def_id),
4474                    },
4475                );
4476                None
4477            }
4478            Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4479                // These entities are explicitly allowed to be shadowed by fresh bindings.
4480                None
4481            }
4482            Res::SelfCtor(_) => {
4483                // We resolve `Self` in pattern position as an ident sometimes during recovery,
4484                // so delay a bug instead of ICEing.
4485                self.r.dcx().span_delayed_bug(
4486                    ident.span,
4487                    "unexpected `SelfCtor` in pattern, expected identifier",
4488                );
4489                None
4490            }
4491            _ => ::rustc_middle::util::bug::span_bug_fmt(ident.span,
    format_args!("unexpected resolution for an identifier in pattern: {0:?}",
        res))span_bug!(
4492                ident.span,
4493                "unexpected resolution for an identifier in pattern: {:?}",
4494                res,
4495            ),
4496        }
4497    }
4498
4499    fn resolve_impl_restriction_path(&mut self, restriction: &'ast ast::ImplRestriction) {
4500        match &restriction.kind {
4501            ast::RestrictionKind::Unrestricted => (),
4502            ast::RestrictionKind::Restricted { path, id, shorthand: _ } => {
4503                self.smart_resolve_path(*id, &None, path, PathSource::Module);
4504                if let Some(res) = self.r.partial_res_map[&id].full_res()
4505                    && let Some(def_id) = res.opt_def_id()
4506                {
4507                    if !self.r.is_accessible_from(
4508                        Visibility::Restricted(def_id),
4509                        self.parent_scope.module,
4510                    ) {
4511                        self.r.dcx().create_err(errors::RestrictionAncestorOnly(path.span)).emit();
4512                    }
4513                }
4514            }
4515        }
4516    }
4517
4518    // High-level and context dependent path resolution routine.
4519    // Resolves the path and records the resolution into definition map.
4520    // If resolution fails tries several techniques to find likely
4521    // resolution candidates, suggest imports or other help, and report
4522    // errors in user friendly way.
4523    fn smart_resolve_path(
4524        &mut self,
4525        id: NodeId,
4526        qself: &Option<Box<QSelf>>,
4527        path: &Path,
4528        source: PathSource<'_, 'ast, 'ra>,
4529    ) {
4530        self.smart_resolve_path_fragment(
4531            qself,
4532            &Segment::from_path(path),
4533            source,
4534            Finalize::new(id, path.span),
4535            RecordPartialRes::Yes,
4536            None,
4537        );
4538    }
4539
4540    fn smart_resolve_path_fragment(
4541        &mut self,
4542        qself: &Option<Box<QSelf>>,
4543        path: &[Segment],
4544        source: PathSource<'_, 'ast, 'ra>,
4545        finalize: Finalize,
4546        record_partial_res: RecordPartialRes,
4547        parent_qself: Option<&QSelf>,
4548    ) -> PartialRes {
4549        let ns = source.namespace();
4550
4551        let Finalize { node_id, path_span, .. } = finalize;
4552        let report_errors = |this: &mut Self, res: Option<Res>| {
4553            if this.should_report_errs() {
4554                let (mut err, candidates) = this.smart_resolve_report_errors(
4555                    path,
4556                    None,
4557                    path_span,
4558                    source,
4559                    res,
4560                    parent_qself,
4561                );
4562
4563                let node_id = this.parent_scope.module.nearest_parent_mod_node_id();
4564                let instead = res.is_some();
4565                let (suggestion, const_err) = if let Some((start, end)) =
4566                    this.diag_metadata.in_range
4567                    && path[0].ident.span.lo() == end.span.lo()
4568                    && !#[allow(non_exhaustive_omitted_patterns)] match start.kind {
    ExprKind::Lit(_) => true,
    _ => false,
}matches!(start.kind, ExprKind::Lit(_))
4569                {
4570                    let mut sugg = ".";
4571                    let mut span = start.span.between(end.span);
4572                    if span.lo() + BytePos(2) == span.hi() {
4573                        // There's no space between the start, the range op and the end, suggest
4574                        // removal which will look better.
4575                        span = span.with_lo(span.lo() + BytePos(1));
4576                        sugg = "";
4577                    }
4578                    (
4579                        Some((
4580                            span,
4581                            "you might have meant to write `.` instead of `..`",
4582                            sugg.to_string(),
4583                            Applicability::MaybeIncorrect,
4584                        )),
4585                        None,
4586                    )
4587                } else if res.is_none()
4588                    && let PathSource::Type
4589                    | PathSource::Expr(_)
4590                    | PathSource::PreciseCapturingArg(..) = source
4591                {
4592                    this.suggest_adding_generic_parameter(path, source)
4593                } else {
4594                    (None, None)
4595                };
4596
4597                if let Some(const_err) = const_err {
4598                    err.cancel();
4599                    err = const_err;
4600                }
4601
4602                let ue = UseError {
4603                    err,
4604                    candidates,
4605                    node_id,
4606                    instead,
4607                    suggestion,
4608                    path: path.into(),
4609                    is_call: source.is_call(),
4610                };
4611
4612                this.r.use_injections.push(ue);
4613            }
4614
4615            PartialRes::new(Res::Err)
4616        };
4617
4618        // For paths originating from calls (like in `HashMap::new()`), tries
4619        // to enrich the plain `failed to resolve: ...` message with hints
4620        // about possible missing imports.
4621        //
4622        // Similar thing, for types, happens in `report_errors` above.
4623        let report_errors_for_call =
4624            |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4625                // Before we start looking for candidates, we have to get our hands
4626                // on the type user is trying to perform invocation on; basically:
4627                // we're transforming `HashMap::new` into just `HashMap`.
4628                let (following_seg, prefix_path) = match path.split_last() {
4629                    Some((last, path)) if !path.is_empty() => (Some(last), path),
4630                    _ => return Some(parent_err),
4631                };
4632
4633                let (mut err, candidates) = this.smart_resolve_report_errors(
4634                    prefix_path,
4635                    following_seg,
4636                    path_span,
4637                    PathSource::Type,
4638                    None,
4639                    parent_qself,
4640                );
4641
4642                // There are two different error messages user might receive at
4643                // this point:
4644                // - E0425 cannot find type `{}` in this scope
4645                // - E0433 failed to resolve: use of undeclared type or module `{}`
4646                //
4647                // The first one is emitted for paths in type-position, and the
4648                // latter one - for paths in expression-position.
4649                //
4650                // Thus (since we're in expression-position at this point), not to
4651                // confuse the user, we want to keep the *message* from E0433 (so
4652                // `parent_err`), but we want *hints* from E0425 (so `err`).
4653                //
4654                // And that's what happens below - we're just mixing both messages
4655                // into a single one.
4656                let failed_to_resolve = match parent_err.node {
4657                    ResolutionError::FailedToResolve { .. } => true,
4658                    _ => false,
4659                };
4660                let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4661
4662                // overwrite all properties with the parent's error message
4663                err.messages = take(&mut parent_err.messages);
4664                err.code = take(&mut parent_err.code);
4665                swap(&mut err.span, &mut parent_err.span);
4666                if failed_to_resolve {
4667                    err.children = take(&mut parent_err.children);
4668                } else {
4669                    err.children.append(&mut parent_err.children);
4670                }
4671                err.sort_span = parent_err.sort_span;
4672                err.is_lint = parent_err.is_lint.clone();
4673
4674                // merge the parent_err's suggestions with the typo (err's) suggestions
4675                match &mut err.suggestions {
4676                    Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4677                        Suggestions::Enabled(parent_suggestions) => {
4678                            // If both suggestions are enabled, append parent_err's suggestions to err's suggestions.
4679                            typo_suggestions.append(parent_suggestions)
4680                        }
4681                        Suggestions::Sealed(_) | Suggestions::Disabled => {
4682                            // If the parent's suggestions are either sealed or disabled, it signifies that
4683                            // new suggestions cannot be added or removed from the diagnostic. Therefore,
4684                            // we assign both types of suggestions to err's suggestions and discard the
4685                            // existing suggestions in err.
4686                            err.suggestions = std::mem::take(&mut parent_err.suggestions);
4687                        }
4688                    },
4689                    Suggestions::Sealed(_) | Suggestions::Disabled => (),
4690                }
4691
4692                parent_err.cancel();
4693
4694                let node_id = this.parent_scope.module.nearest_parent_mod_node_id();
4695
4696                if this.should_report_errs() {
4697                    if candidates.is_empty() {
4698                        if path.len() == 2
4699                            && let [segment] = prefix_path
4700                        {
4701                            // Delay to check whether method name is an associated function or not
4702                            // ```
4703                            // let foo = Foo {};
4704                            // foo::bar(); // possibly suggest to foo.bar();
4705                            //```
4706                            err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4707                        } else {
4708                            // When there is no suggested imports, we can just emit the error
4709                            // and suggestions immediately. Note that we bypass the usually error
4710                            // reporting routine (ie via `self.r.report_error`) because we need
4711                            // to post-process the `ResolutionError` above.
4712                            err.emit();
4713                        }
4714                    } else {
4715                        // If there are suggested imports, the error reporting is delayed
4716                        this.r.use_injections.push(UseError {
4717                            err,
4718                            candidates,
4719                            node_id,
4720                            instead: false,
4721                            suggestion: None,
4722                            path: prefix_path.into(),
4723                            is_call: source.is_call(),
4724                        });
4725                    }
4726                } else {
4727                    err.cancel();
4728                }
4729
4730                // We don't return `Some(parent_err)` here, because the error will
4731                // be already printed either immediately or as part of the `use` injections
4732                None
4733            };
4734
4735        let partial_res = match self.resolve_qpath_anywhere(
4736            qself,
4737            path,
4738            ns,
4739            source.defer_to_typeck(),
4740            finalize,
4741            source,
4742        ) {
4743            Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4744                // if we also have an associated type that matches the ident, stash a suggestion
4745                if let Some(items) = self.diag_metadata.current_trait_assoc_items
4746                    && let [Segment { ident, .. }] = path
4747                    && items.iter().any(|item| {
4748                        if let AssocItemKind::Type(alias) = &item.kind
4749                            && alias.ident == *ident
4750                        {
4751                            true
4752                        } else {
4753                            false
4754                        }
4755                    })
4756                {
4757                    let mut diag = self.r.tcx.dcx().struct_allow("");
4758                    diag.span_suggestion_verbose(
4759                        path_span.shrink_to_lo(),
4760                        "there is an associated type with the same name",
4761                        "Self::",
4762                        Applicability::MaybeIncorrect,
4763                    );
4764                    diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4765                }
4766
4767                if source.is_expected(res) || res == Res::Err {
4768                    partial_res
4769                } else {
4770                    report_errors(self, Some(res))
4771                }
4772            }
4773
4774            Ok(Some(partial_res)) if source.defer_to_typeck() => {
4775                // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
4776                // or `<T>::A::B`. If `B` should be resolved in value namespace then
4777                // it needs to be added to the trait map.
4778                if ns == ValueNS {
4779                    let item_name = path.last().unwrap().ident;
4780                    let traits = self.traits_in_scope(item_name, ns);
4781                    self.r.trait_map.insert(node_id, traits);
4782                }
4783
4784                if PrimTy::from_name(path[0].ident.name).is_some() {
4785                    let mut std_path = Vec::with_capacity(1 + path.len());
4786
4787                    std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4788                    std_path.extend(path);
4789                    if let PathResult::Module(_) | PathResult::NonModule(_) =
4790                        self.resolve_path(&std_path, Some(ns), None, source)
4791                    {
4792                        // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
4793                        let item_span =
4794                            path.iter().last().map_or(path_span, |segment| segment.ident.span);
4795
4796                        self.r.confused_type_with_std_module.insert(item_span, path_span);
4797                        self.r.confused_type_with_std_module.insert(path_span, path_span);
4798                    }
4799                }
4800
4801                partial_res
4802            }
4803
4804            Err(err) => {
4805                if let Some(err) = report_errors_for_call(self, err) {
4806                    self.report_error(err.span, err.node);
4807                }
4808
4809                PartialRes::new(Res::Err)
4810            }
4811
4812            _ => report_errors(self, None),
4813        };
4814
4815        if record_partial_res == RecordPartialRes::Yes {
4816            // Avoid recording definition of `A::B` in `<T as A>::B::C`.
4817            self.r.record_partial_res(node_id, partial_res);
4818            self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4819            self.lint_unused_qualifications(path, ns, finalize);
4820        }
4821
4822        partial_res
4823    }
4824
4825    fn self_type_is_available(&mut self) -> bool {
4826        let binding = self
4827            .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4828        if let Some(LateDecl::RibDef(res)) = binding { res != Res::Err } else { false }
4829    }
4830
4831    fn self_value_is_available(&mut self, self_span: Span) -> bool {
4832        let ident = Ident::new(kw::SelfLower, self_span);
4833        let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4834        if let Some(LateDecl::RibDef(res)) = binding { res != Res::Err } else { false }
4835    }
4836
4837    /// A wrapper around [`Resolver::report_error`].
4838    ///
4839    /// This doesn't emit errors for function bodies if this is rustdoc.
4840    fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4841        if self.should_report_errs() {
4842            self.r.report_error(span, resolution_error);
4843        }
4844    }
4845
4846    #[inline]
4847    /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items or
4848    // an invalid `use foo::*;` was found, which can cause unbounded amounts of "item not found"
4849    // errors. We silence them all.
4850    fn should_report_errs(&self) -> bool {
4851        !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4852            && !self.r.glob_error.is_some()
4853    }
4854
4855    // Resolve in alternative namespaces if resolution in the primary namespace fails.
4856    fn resolve_qpath_anywhere(
4857        &mut self,
4858        qself: &Option<Box<QSelf>>,
4859        path: &[Segment],
4860        primary_ns: Namespace,
4861        defer_to_typeck: bool,
4862        finalize: Finalize,
4863        source: PathSource<'_, 'ast, 'ra>,
4864    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4865        let mut fin_res = None;
4866
4867        for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4868            if i == 0 || ns != primary_ns {
4869                match self.resolve_qpath(qself, path, ns, finalize, source)? {
4870                    Some(partial_res)
4871                        if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4872                    {
4873                        return Ok(Some(partial_res));
4874                    }
4875                    partial_res => {
4876                        if fin_res.is_none() {
4877                            fin_res = partial_res;
4878                        }
4879                    }
4880                }
4881            }
4882        }
4883
4884        if !(primary_ns != MacroNS) {
    ::core::panicking::panic("assertion failed: primary_ns != MacroNS")
};assert!(primary_ns != MacroNS);
4885        if qself.is_none()
4886            && let PathResult::NonModule(res) =
4887                self.r.cm().maybe_resolve_path(path, Some(MacroNS), &self.parent_scope, None)
4888        {
4889            return Ok(Some(res));
4890        }
4891
4892        Ok(fin_res)
4893    }
4894
4895    /// Handles paths that may refer to associated items.
4896    fn resolve_qpath(
4897        &mut self,
4898        qself: &Option<Box<QSelf>>,
4899        path: &[Segment],
4900        ns: Namespace,
4901        finalize: Finalize,
4902        source: PathSource<'_, 'ast, 'ra>,
4903    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4904        {
    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/late.rs:4904",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(4904u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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_qpath(qself={0:?}, path={1:?}, ns={2:?}, finalize={3:?})",
                                                    qself, path, ns, finalize) as &dyn Value))])
            });
    } else { ; }
};debug!(
4905            "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4906            qself, path, ns, finalize,
4907        );
4908
4909        if let Some(qself) = qself {
4910            if qself.position == 0 {
4911                // This is a case like `<T>::B`, where there is no
4912                // trait to resolve. In that case, we leave the `B`
4913                // segment to be resolved by type-check.
4914                return Ok(Some(PartialRes::with_unresolved_segments(
4915                    Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4916                    path.len(),
4917                )));
4918            }
4919
4920            let num_privacy_errors = self.r.privacy_errors.len();
4921            // Make sure that `A` in `<T as A>::B::C` is a trait.
4922            let trait_res = self.smart_resolve_path_fragment(
4923                &None,
4924                &path[..qself.position],
4925                PathSource::Trait(AliasPossibility::No),
4926                Finalize::new(finalize.node_id, qself.path_span),
4927                RecordPartialRes::No,
4928                Some(&qself),
4929            );
4930
4931            if trait_res.expect_full_res() == Res::Err {
4932                return Ok(Some(trait_res));
4933            }
4934
4935            // Truncate additional privacy errors reported above,
4936            // because they'll be recomputed below.
4937            self.r.privacy_errors.truncate(num_privacy_errors);
4938
4939            // Make sure `A::B` in `<T as A>::B::C` is a trait item.
4940            //
4941            // Currently, `path` names the full item (`A::B::C`, in
4942            // our example). so we extract the prefix of that that is
4943            // the trait (the slice upto and including
4944            // `qself.position`). And then we recursively resolve that,
4945            // but with `qself` set to `None`.
4946            let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4947            let partial_res = self.smart_resolve_path_fragment(
4948                &None,
4949                &path[..=qself.position],
4950                PathSource::TraitItem(ns, &source),
4951                Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4952                RecordPartialRes::No,
4953                Some(&qself),
4954            );
4955
4956            // The remaining segments (the `C` in our example) will
4957            // have to be resolved by type-check, since that requires doing
4958            // trait resolution.
4959            return Ok(Some(PartialRes::with_unresolved_segments(
4960                partial_res.base_res(),
4961                partial_res.unresolved_segments() + path.len() - qself.position - 1,
4962            )));
4963        }
4964
4965        let result = match self.resolve_path(path, Some(ns), Some(finalize), source) {
4966            PathResult::NonModule(path_res) => path_res,
4967            PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4968                PartialRes::new(module.res().unwrap())
4969            }
4970            // A part of this path references a `mod` that had a parse error. To avoid resolution
4971            // errors for each reference to that module, we don't emit an error for them until the
4972            // `mod` is fixed. this can have a significant cascade effect.
4973            PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4974                PartialRes::new(Res::Err)
4975            }
4976            // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
4977            // don't report an error right away, but try to fallback to a primitive type.
4978            // So, we are still able to successfully resolve something like
4979            //
4980            // use std::u8; // bring module u8 in scope
4981            // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
4982            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
4983            //                     // not to nonexistent std::u8::max_value
4984            // }
4985            //
4986            // Such behavior is required for backward compatibility.
4987            // The same fallback is used when `a` resolves to nothing.
4988            PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4989                if (ns == TypeNS || path.len() > 1)
4990                    && PrimTy::from_name(path[0].ident.name).is_some() =>
4991            {
4992                let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4993                let tcx = self.r.tcx();
4994
4995                let gate_err_sym_msg = match prim {
4996                    PrimTy::Float(FloatTy::F16) if !tcx.features().f16() => {
4997                        Some((sym::f16, "the type `f16` is unstable"))
4998                    }
4999                    PrimTy::Float(FloatTy::F128) if !tcx.features().f128() => {
5000                        Some((sym::f128, "the type `f128` is unstable"))
5001                    }
5002                    _ => None,
5003                };
5004
5005                if let Some((sym, msg)) = gate_err_sym_msg {
5006                    let span = path[0].ident.span;
5007                    if !span.allows_unstable(sym) {
5008                        feature_err(tcx.sess, sym, span, msg).emit();
5009                    }
5010                };
5011
5012                // Fix up partial res of segment from `resolve_path` call.
5013                if let Some(id) = path[0].id {
5014                    self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
5015                }
5016
5017                PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
5018            }
5019            PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
5020                PartialRes::new(module.res().unwrap())
5021            }
5022            PathResult::Failed {
5023                is_error_from_last_segment: false,
5024                span,
5025                label,
5026                suggestion,
5027                module,
5028                segment_name,
5029                error_implied_by_parse_error: _,
5030                message,
5031                note: _,
5032            } => {
5033                return Err(respan(
5034                    span,
5035                    ResolutionError::FailedToResolve {
5036                        segment: segment_name,
5037                        label,
5038                        suggestion,
5039                        module,
5040                        message,
5041                    },
5042                ));
5043            }
5044            PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
5045            PathResult::Indeterminate => ::rustc_middle::util::bug::bug_fmt(format_args!("indeterminate path result in resolve_qpath"))bug!("indeterminate path result in resolve_qpath"),
5046        };
5047
5048        Ok(Some(result))
5049    }
5050
5051    fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
5052        if let Some(label) = label {
5053            if label.ident.as_str().as_bytes()[1] != b'_' {
5054                self.diag_metadata.unused_labels.insert(id, label.ident.span);
5055            }
5056
5057            if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
5058                diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
5059            }
5060
5061            self.with_label_rib(RibKind::Normal, |this| {
5062                let ident = label.ident.normalize_to_macro_rules();
5063                this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
5064                f(this);
5065            });
5066        } else {
5067            f(self);
5068        }
5069    }
5070
5071    fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
5072        self.with_resolved_label(label, id, |this| this.visit_block(block));
5073    }
5074
5075    fn resolve_block(&mut self, block: &'ast Block) {
5076        {
    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/late.rs:5076",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5076u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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!("(resolving block) entering block")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("(resolving block) entering block");
5077        // Move down in the graph, if there's an anonymous module rooted here.
5078        let orig_module = self.parent_scope.module;
5079        let anonymous_module = self.r.block_map.get(&block.id).copied();
5080
5081        let mut num_macro_definition_ribs = 0;
5082        if let Some(anonymous_module) = anonymous_module {
5083            {
    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/late.rs:5083",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5083u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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!("(resolving block) found anonymous module, moving down")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("(resolving block) found anonymous module, moving down");
5084            self.ribs[ValueNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
5085            self.ribs[TypeNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
5086            self.parent_scope.module = anonymous_module.to_module();
5087        } else {
5088            self.ribs[ValueNS].push(Rib::new(RibKind::Block(None)));
5089        }
5090
5091        // Descend into the block.
5092        for stmt in &block.stmts {
5093            if let StmtKind::Item(ref item) = stmt.kind
5094                && let ItemKind::MacroDef(..) = item.kind
5095            {
5096                num_macro_definition_ribs += 1;
5097                let res = self.r.owner_def_id(item.id).to_def_id();
5098                self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
5099                self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
5100            }
5101
5102            self.visit_stmt(stmt);
5103        }
5104
5105        // Move back up.
5106        self.parent_scope.module = orig_module;
5107        for _ in 0..num_macro_definition_ribs {
5108            self.ribs[ValueNS].pop();
5109            self.label_ribs.pop();
5110        }
5111        self.last_block_rib = self.ribs[ValueNS].pop();
5112        if anonymous_module.is_some() {
5113            self.ribs[TypeNS].pop();
5114        }
5115        {
    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/late.rs:5115",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5115u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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!("(resolving block) leaving block")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("(resolving block) leaving block");
5116    }
5117
5118    fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
5119        {
    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/late.rs:5119",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5119u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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_anon_const(constant: {0:?}, anon_const_kind: {1:?})",
                                                    constant, anon_const_kind) as &dyn Value))])
            });
    } else { ; }
};debug!(
5120            "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
5121            constant, anon_const_kind
5122        );
5123
5124        let is_trivial_const_arg = constant.value.is_potential_trivial_const_arg();
5125        self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
5126            this.resolve_expr(&constant.value, None)
5127        })
5128    }
5129
5130    /// There are a few places that we need to resolve an anon const but we did not parse an
5131    /// anon const so cannot provide an `&'ast AnonConst`. Right now this is just unbraced
5132    /// const arguments that were parsed as type arguments, and `legacy_const_generics` which
5133    /// parse as normal function argument expressions. To avoid duplicating the code for resolving
5134    /// an anon const we have this function which lets the caller manually call `resolve_expr` or
5135    /// `smart_resolve_path`.
5136    fn resolve_anon_const_manual(
5137        &mut self,
5138        is_trivial_const_arg: bool,
5139        anon_const_kind: AnonConstKind,
5140        resolve_expr: impl FnOnce(&mut Self),
5141    ) {
5142        let is_repeat_expr = match anon_const_kind {
5143            AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
5144            _ => IsRepeatExpr::No,
5145        };
5146
5147        let may_use_generics = match anon_const_kind {
5148            AnonConstKind::EnumDiscriminant => {
5149                ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
5150            }
5151            AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
5152            AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
5153            AnonConstKind::ConstArg(_) => {
5154                if self.r.tcx.features().generic_const_exprs()
5155                    || self.r.tcx.features().min_generic_const_args()
5156                    || is_trivial_const_arg
5157                {
5158                    ConstantHasGenerics::Yes
5159                } else {
5160                    ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
5161                }
5162            }
5163        };
5164
5165        self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
5166            this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
5167                resolve_expr(this);
5168            });
5169        });
5170    }
5171
5172    fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
5173        self.resolve_expr(&f.expr, Some(e));
5174        self.visit_ident(&f.ident);
5175        for elem in f.attrs.iter() {
    match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_attribute(elem))
        {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(self, visit_attribute, f.attrs.iter());
5176    }
5177
5178    fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
5179        // First, record candidate traits for this expression if it could
5180        // result in the invocation of a method call.
5181
5182        self.record_candidate_traits_for_expr_if_necessary(expr);
5183
5184        // Next, resolve the node.
5185        match expr.kind {
5186            ExprKind::Path(ref qself, ref path) => {
5187                self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
5188                visit::walk_expr(self, expr);
5189            }
5190
5191            ExprKind::Struct(ref se) => {
5192                self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct(parent));
5193                // This is the same as `visit::walk_expr(self, expr);`, but we want to pass the
5194                // parent in for accurate suggestions when encountering `Foo { bar }` that should
5195                // have been `Foo { bar: self.bar }`.
5196                if let Some(qself) = &se.qself {
5197                    self.visit_ty(&qself.ty);
5198                }
5199                self.visit_path(&se.path);
5200                for elem in &se.fields {
    match ::rustc_ast_ir::visit::VisitorResult::branch(self.resolve_expr_field(elem,
                expr)) {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};walk_list!(self, resolve_expr_field, &se.fields, expr);
5201                match &se.rest {
5202                    StructRest::Base(expr) => self.visit_expr(expr),
5203                    StructRest::Rest(_span) => {}
5204                    StructRest::None | StructRest::NoneWithError(_) => {}
5205                }
5206            }
5207
5208            ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
5209                match self.resolve_label(label.ident) {
5210                    Ok((node_id, _)) => {
5211                        // Since this res is a label, it is never read.
5212                        self.r.label_res_map.insert(expr.id, node_id);
5213                        self.diag_metadata.unused_labels.swap_remove(&node_id);
5214                    }
5215                    Err(error) => {
5216                        self.report_error(label.ident.span, error);
5217                    }
5218                }
5219
5220                // visit `break` argument if any
5221                visit::walk_expr(self, expr);
5222            }
5223
5224            ExprKind::Break(None, Some(ref e)) => {
5225                // We use this instead of `visit::walk_expr` to keep the parent expr around for
5226                // better diagnostics.
5227                self.resolve_expr(e, Some(expr));
5228            }
5229
5230            ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
5231                self.visit_expr(scrutinee);
5232                self.resolve_pattern_top(pat, PatternSource::Let);
5233            }
5234
5235            ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
5236                self.visit_expr(scrutinee);
5237                // This is basically a tweaked, inlined `resolve_pattern_top`.
5238                let mut bindings = {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push((PatBoundCtx::Product, Default::default()));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [(PatBoundCtx::Product, Default::default())])))
    }
}smallvec![(PatBoundCtx::Product, Default::default())];
5239                self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
5240                // We still collect the bindings in this `let` expression which is in
5241                // an invalid position (and therefore shouldn't declare variables into
5242                // its parent scope). To avoid unnecessary errors though, we do just
5243                // reassign the resolutions to `Res::Err`.
5244                for (_, bindings) in &mut bindings {
5245                    for (_, binding) in bindings {
5246                        *binding = Res::Err;
5247                    }
5248                }
5249                self.apply_pattern_bindings(bindings);
5250            }
5251
5252            ExprKind::If(ref cond, ref then, ref opt_else) => {
5253                self.with_rib(ValueNS, RibKind::Normal, |this| {
5254                    let old = this.diag_metadata.in_if_condition.replace(cond);
5255                    this.visit_expr(cond);
5256                    this.diag_metadata.in_if_condition = old;
5257                    this.visit_block(then);
5258                });
5259                if let Some(expr) = opt_else {
5260                    self.visit_expr(expr);
5261                }
5262            }
5263
5264            ExprKind::Loop(ref block, label, _) => {
5265                self.resolve_labeled_block(label, expr.id, block)
5266            }
5267
5268            ExprKind::While(ref cond, ref block, label) => {
5269                self.with_resolved_label(label, expr.id, |this| {
5270                    this.with_rib(ValueNS, RibKind::Normal, |this| {
5271                        let old = this.diag_metadata.in_if_condition.replace(cond);
5272                        this.visit_expr(cond);
5273                        this.diag_metadata.in_if_condition = old;
5274                        this.visit_block(block);
5275                    })
5276                });
5277            }
5278
5279            ExprKind::ForLoop { ref pat, ref iter, ref body, label, kind: _ } => {
5280                self.visit_expr(iter);
5281                self.with_rib(ValueNS, RibKind::Normal, |this| {
5282                    this.resolve_pattern_top(pat, PatternSource::For);
5283                    this.resolve_labeled_block(label, expr.id, body);
5284                });
5285            }
5286
5287            ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
5288
5289            // Equivalent to `visit::walk_expr` + passing some context to children.
5290            ExprKind::Field(ref subexpression, _) => {
5291                self.resolve_expr(subexpression, Some(expr));
5292            }
5293            ExprKind::MethodCall(MethodCall { ref seg, ref receiver, ref args, .. }) => {
5294                self.resolve_expr(receiver, Some(expr));
5295                for arg in args {
5296                    self.resolve_expr(arg, None);
5297                }
5298                self.visit_path_segment(seg);
5299            }
5300
5301            ExprKind::Call(ref callee, ref arguments) => {
5302                self.resolve_expr(callee, Some(expr));
5303                let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
5304                for (idx, argument) in arguments.iter().enumerate() {
5305                    // Constant arguments need to be treated as AnonConst since
5306                    // that is how they will be later lowered to HIR.
5307                    if const_args.contains(&idx) {
5308                        // FIXME(mgca): legacy const generics doesn't support mgca but maybe
5309                        // that's okay.
5310                        let is_trivial_const_arg = argument.is_potential_trivial_const_arg();
5311                        self.resolve_anon_const_manual(
5312                            is_trivial_const_arg,
5313                            AnonConstKind::ConstArg(IsRepeatExpr::No),
5314                            |this| this.resolve_expr(argument, None),
5315                        );
5316                    } else {
5317                        self.resolve_expr(argument, None);
5318                    }
5319                }
5320            }
5321            ExprKind::Type(ref _type_expr, ref _ty) => {
5322                visit::walk_expr(self, expr);
5323            }
5324            // For closures, RibKind::FnOrCoroutine is added in visit_fn
5325            ExprKind::Closure(ast::Closure {
5326                binder: ClosureBinder::For { ref generic_params, span },
5327                ..
5328            }) => {
5329                self.with_generic_param_rib(
5330                    generic_params,
5331                    RibKind::Normal,
5332                    expr.id,
5333                    LifetimeBinderKind::Closure,
5334                    span,
5335                    |this| visit::walk_expr(this, expr),
5336                );
5337            }
5338            ExprKind::Closure(..) => visit::walk_expr(self, expr),
5339            ExprKind::Gen(..) => {
5340                self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
5341            }
5342            ExprKind::Repeat(ref elem, ref ct) => {
5343                self.visit_expr(elem);
5344                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
5345            }
5346            ExprKind::ConstBlock(ref ct) => {
5347                self.resolve_anon_const(ct, AnonConstKind::InlineConst);
5348            }
5349            ExprKind::Index(ref elem, ref idx, _) => {
5350                self.resolve_expr(elem, Some(expr));
5351                self.visit_expr(idx);
5352            }
5353            ExprKind::Assign(ref lhs, ref rhs, _) => {
5354                if !self.diag_metadata.is_assign_rhs {
5355                    self.diag_metadata.in_assignment = Some(expr);
5356                }
5357                self.visit_expr(lhs);
5358                self.diag_metadata.is_assign_rhs = true;
5359                self.diag_metadata.in_assignment = None;
5360                self.visit_expr(rhs);
5361                self.diag_metadata.is_assign_rhs = false;
5362            }
5363            ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
5364                self.diag_metadata.in_range = Some((start, end));
5365                self.resolve_expr(start, Some(expr));
5366                self.resolve_expr(end, Some(expr));
5367                self.diag_metadata.in_range = None;
5368            }
5369            _ => {
5370                visit::walk_expr(self, expr);
5371            }
5372        }
5373    }
5374
5375    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
5376        match expr.kind {
5377            ExprKind::Field(_, ident) => {
5378                // #6890: Even though you can't treat a method like a field,
5379                // we need to add any trait methods we find that match the
5380                // field name so that we can do some nice error reporting
5381                // later on in typeck.
5382                let traits = self.traits_in_scope(ident, ValueNS);
5383                self.r.trait_map.insert(expr.id, traits);
5384            }
5385            ExprKind::MethodCall(ref call) => {
5386                {
    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/late.rs:5386",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5386u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::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!("(recording candidate traits for expr) recording traits for {0}",
                                                    expr.id) as &dyn Value))])
            });
    } else { ; }
};debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
5387                let traits = self.traits_in_scope(call.seg.ident, ValueNS);
5388                self.r.trait_map.insert(expr.id, traits);
5389            }
5390            _ => {
5391                // Nothing to do.
5392            }
5393        }
5394    }
5395
5396    fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> &'tcx [TraitCandidate<'tcx>] {
5397        self.r.traits_in_scope(
5398            self.current_trait_ref.as_ref().map(|(module, _)| *module),
5399            &self.parent_scope,
5400            ident.span,
5401            Some((ident.name, ns)),
5402        )
5403    }
5404
5405    fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
5406        // FIXME: This caching may be incorrect in case of multiple `macro_rules`
5407        // items with the same name in the same module.
5408        // Also hygiene is not considered.
5409        let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
5410        let res = *doc_link_resolutions
5411            .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5412            .or_default()
5413            .entry((Symbol::intern(path_str), ns))
5414            .or_insert_with_key(|(path, ns)| {
5415                let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
5416                if let Some(res) = res
5417                    && let Some(def_id) = res.opt_def_id()
5418                    && self.is_invalid_proc_macro_item_for_doc(def_id)
5419                {
5420                    // Encoding def ids in proc macro crate metadata will ICE,
5421                    // because it will only store proc macros for it.
5422                    return None;
5423                }
5424                res
5425            });
5426        self.r.doc_link_resolutions = doc_link_resolutions;
5427        res
5428    }
5429
5430    fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5431        if !#[allow(non_exhaustive_omitted_patterns)] match self.r.tcx.sess.opts.resolve_doc_links
    {
    ResolveDocLinks::ExportedMetadata => true,
    _ => false,
}matches!(self.r.tcx.sess.opts.resolve_doc_links, ResolveDocLinks::ExportedMetadata)
5432            || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5433        {
5434            return false;
5435        }
5436        let Some(local_did) = did.as_local() else { return true };
5437        !self.r.proc_macros.contains(&local_did)
5438    }
5439
5440    fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5441        match self.r.tcx.sess.opts.resolve_doc_links {
5442            ResolveDocLinks::None => return,
5443            ResolveDocLinks::ExportedMetadata
5444                if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5445                    || !maybe_exported.eval(self.r) =>
5446            {
5447                return;
5448            }
5449            ResolveDocLinks::Exported
5450                if !maybe_exported.eval(self.r)
5451                    && !rustdoc::has_primitive_or_keyword_or_attribute_docs(attrs) =>
5452            {
5453                return;
5454            }
5455            ResolveDocLinks::ExportedMetadata
5456            | ResolveDocLinks::Exported
5457            | ResolveDocLinks::All => {}
5458        }
5459
5460        if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5461            return;
5462        }
5463
5464        let mut need_traits_in_scope = false;
5465        for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5466            // Resolve all namespaces due to no disambiguator or for diagnostics.
5467            let mut any_resolved = false;
5468            let mut need_assoc = false;
5469            for ns in [TypeNS, ValueNS, MacroNS] {
5470                if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5471                    // Rustdoc ignores tool attribute resolutions and attempts
5472                    // to resolve their prefixes for diagnostics.
5473                    any_resolved = !#[allow(non_exhaustive_omitted_patterns)] match res {
    Res::NonMacroAttr(NonMacroAttrKind::Tool) => true,
    _ => false,
}matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5474                } else if ns != MacroNS {
5475                    need_assoc = true;
5476                }
5477            }
5478
5479            // Resolve all prefixes for type-relative resolution or for diagnostics.
5480            if need_assoc || !any_resolved {
5481                let mut path = &path_str[..];
5482                while let Some(idx) = path.rfind("::") {
5483                    path = &path[..idx];
5484                    need_traits_in_scope = true;
5485                    for ns in [TypeNS, ValueNS, MacroNS] {
5486                        self.resolve_and_cache_rustdoc_path(path, ns);
5487                    }
5488                }
5489            }
5490        }
5491
5492        if need_traits_in_scope {
5493            // FIXME: hygiene is not considered.
5494            let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5495            doc_link_traits_in_scope
5496                .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5497                .or_insert_with(|| {
5498                    self.r
5499                        .traits_in_scope(None, &self.parent_scope, DUMMY_SP, None)
5500                        .into_iter()
5501                        .filter_map(|tr| {
5502                            if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5503                                // Encoding def ids in proc macro crate metadata will ICE.
5504                                // because it will only store proc macros for it.
5505                                return None;
5506                            }
5507                            Some(tr.def_id)
5508                        })
5509                        .collect()
5510                });
5511            self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5512        }
5513    }
5514
5515    fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5516        // Don't lint on global paths because the user explicitly wrote out the full path.
5517        if let Some(seg) = path.first()
5518            && seg.ident.name == kw::PathRoot
5519        {
5520            return;
5521        }
5522
5523        if finalize.path_span.from_expansion()
5524            || path.iter().any(|seg| seg.ident.span.from_expansion())
5525        {
5526            return;
5527        }
5528
5529        let end_pos =
5530            path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5531        let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5532            // Preserve the current namespace for the final path segment, but use the type
5533            // namespace for all preceding segments
5534            //
5535            // e.g. for `std::env::args` check the `ValueNS` for `args` but the `TypeNS` for
5536            // `std` and `env`
5537            //
5538            // If the final path segment is beyond `end_pos` all the segments to check will
5539            // use the type namespace
5540            let ns = if i + 1 == path.len() { ns } else { TypeNS };
5541            let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5542            let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5543            (res == binding.res()).then_some((seg, binding))
5544        });
5545
5546        if let Some((seg, decl)) = unqualified {
5547            self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5548                decl,
5549                node_id: finalize.node_id,
5550                path_span: finalize.path_span,
5551                removal_span: path[0].ident.span.until(seg.ident.span),
5552            });
5553        }
5554    }
5555
5556    fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5557        if let Some(define_opaque) = define_opaque {
5558            for (id, path) in define_opaque {
5559                self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5560            }
5561        }
5562    }
5563
5564    fn resolve_eii(&mut self, eii_impls: &[EiiImpl]) {
5565        for EiiImpl { node_id, eii_macro_path, known_eii_macro_resolution, .. } in eii_impls {
5566            // See docs on the `known_eii_macro_resolution` field:
5567            // if we already know the resolution statically, don't bother resolving it.
5568            if let Some(target) = known_eii_macro_resolution {
5569                self.smart_resolve_path(
5570                    *node_id,
5571                    &None,
5572                    &target.foreign_item,
5573                    PathSource::ExternItemImpl,
5574                );
5575            } else {
5576                self.smart_resolve_path(*node_id, &None, &eii_macro_path, PathSource::Macro);
5577            }
5578        }
5579    }
5580}
5581
5582/// Walks the whole crate in DFS order, visiting each item, counting the declared number of
5583/// lifetime generic parameters and function parameters.
5584struct ItemInfoCollector<'a, 'ra, 'tcx> {
5585    r: &'a mut Resolver<'ra, 'tcx>,
5586}
5587
5588impl ItemInfoCollector<'_, '_, '_> {
5589    fn collect_fn_info(&mut self, decl: &FnDecl, id: NodeId) {
5590        self.r
5591            .delegation_fn_sigs
5592            .insert(self.r.owner_def_id(id), DelegationFnSig { has_self: decl.has_self() });
5593    }
5594}
5595
5596fn required_generic_args_suggestion(generics: &ast::Generics) -> Option<String> {
5597    let required = generics
5598        .params
5599        .iter()
5600        .filter_map(|param| match &param.kind {
5601            ast::GenericParamKind::Lifetime => Some("'_"),
5602            ast::GenericParamKind::Type { default } => {
5603                if default.is_none() {
5604                    Some("_")
5605                } else {
5606                    None
5607                }
5608            }
5609            ast::GenericParamKind::Const { default, .. } => {
5610                if default.is_none() {
5611                    Some("_")
5612                } else {
5613                    None
5614                }
5615            }
5616        })
5617        .collect::<Vec<_>>();
5618
5619    if required.is_empty() { None } else { Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>", required.join(", ")))
    })format!("<{}>", required.join(", "))) }
5620}
5621
5622impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
5623    fn visit_item(&mut self, item: &'ast Item) {
5624        match &item.kind {
5625            ItemKind::TyAlias(TyAlias { generics, .. })
5626            | ItemKind::Const(ConstItem { generics, .. })
5627            | ItemKind::Fn(Fn { generics, .. })
5628            | ItemKind::Enum(_, generics, _)
5629            | ItemKind::Struct(_, generics, _)
5630            | ItemKind::Union(_, generics, _)
5631            | ItemKind::Impl(Impl { generics, .. })
5632            | ItemKind::Trait(Trait { generics, .. })
5633            | ItemKind::TraitAlias(TraitAlias { generics, .. }) => {
5634                if let ItemKind::Fn(Fn { sig, .. }) = &item.kind {
5635                    self.collect_fn_info(&sig.decl, item.id);
5636                }
5637
5638                let def_id = self.r.owner_def_id(item.id);
5639                let count = generics
5640                    .params
5641                    .iter()
5642                    .filter(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    ast::GenericParamKind::Lifetime { .. } => true,
    _ => false,
}matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5643                    .count();
5644                self.r.item_generics_num_lifetimes.insert(def_id, count);
5645            }
5646
5647            ItemKind::ForeignMod(ForeignMod { items, .. }) => {
5648                for foreign_item in items {
5649                    if let ForeignItemKind::Fn(Fn { sig, .. }) = &foreign_item.kind {
5650                        self.collect_fn_info(&sig.decl, foreign_item.id);
5651                    }
5652                }
5653            }
5654
5655            ItemKind::Mod(..)
5656            | ItemKind::Static(..)
5657            | ItemKind::ConstBlock(..)
5658            | ItemKind::Use(..)
5659            | ItemKind::ExternCrate(..)
5660            | ItemKind::MacroDef(..)
5661            | ItemKind::GlobalAsm(..)
5662            | ItemKind::MacCall(..)
5663            | ItemKind::DelegationMac(..) => {}
5664            ItemKind::Delegation(..) => {
5665                // Delegated functions have lifetimes, their count is not necessarily zero.
5666                // But skipping the delegation items here doesn't mean that the count will be considered zero,
5667                // it means there will be a panic when retrieving the count,
5668                // but for delegation items we are never actually retrieving that count in practice.
5669            }
5670        }
5671        visit::walk_item(self, item)
5672    }
5673
5674    fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5675        if let AssocItemKind::Fn(Fn { sig, .. }) = &item.kind {
5676            self.collect_fn_info(&sig.decl, item.id);
5677        }
5678
5679        if let AssocItemKind::Type(ast::TyAlias { generics, .. }) = &item.kind {
5680            let def_id = self.r.owner_def_id(item.id);
5681            if let Some(suggestion) = required_generic_args_suggestion(generics) {
5682                self.r.item_required_generic_args_suggestions.insert(def_id, suggestion);
5683            }
5684        }
5685        visit::walk_assoc_item(self, item, ctxt);
5686    }
5687}
5688
5689impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5690    pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
5691        with_owner(self, CRATE_NODE_ID, |this| {
5692            visit::walk_crate(&mut ItemInfoCollector { r: this }, krate);
5693            let mut late_resolution_visitor = LateResolutionVisitor::new(this);
5694            late_resolution_visitor
5695                .resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5696            visit::walk_crate(&mut late_resolution_visitor, krate);
5697            for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
5698                this.lint_buffer.buffer_lint(
5699                    lint::builtin::UNUSED_LABELS,
5700                    *id,
5701                    *span,
5702                    errors::UnusedLabel,
5703                );
5704            }
5705        })
5706    }
5707}
5708
5709/// Check if definition matches a path
5710fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5711    let mut path = expected_path.iter().rev();
5712    while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5713        if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5714            return false;
5715        }
5716        def_id = parent;
5717    }
5718    true
5719}