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