Skip to main content

rustc_resolve/
late.rs

1// ignore-tidy-file-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::diagnostics::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 { res: __self_0, error_in_path: __self_1 }
                =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Elided", "res", __self_0, "error_in_path", &__self_1),
            LifetimeRibKind::AnonymousReportError =>
                ::core::fmt::Formatter::write_str(f, "AnonymousReportError"),
            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 {
337        res: LifetimeRes,
338        /// Always report those lifetimes as an error if in a path
339        error_in_path: bool,
340    },
341
342    // -- Barrier ribs that stop lifetime lookup, or continue it but produce an error later.
343    //
344    /// Give a hard error when either `&` or `'_` is written. Used to
345    /// rule out things like `where T: Foo<'_>`. Does not imply an
346    /// error on default object bounds (e.g., `Box<dyn Foo>`).
347    AnonymousReportError,
348
349    /// Signal we cannot find which should be the anonymous lifetime.
350    ElisionFailure,
351
352    /// This rib forbids usage of generic parameters inside of const parameter types.
353    ///
354    /// While this is desirable to support eventually, it is difficult to do and so is
355    /// currently forbidden. See rust-lang/project-const-generics#28 for more info.
356    ConstParamTy,
357
358    /// Usage of generic parameters is forbidden in various positions for anon consts:
359    /// - const arguments when `generic_const_exprs` is not enabled
360    /// - enum discriminant values
361    ///
362    /// This rib emits an error when a lifetime would resolve to a lifetime parameter.
363    ConcreteAnonConst(NoConstantGenericsReason),
364
365    /// This rib acts as a barrier to forbid reference to lifetimes of a parent item.
366    Item,
367
368    /// Lifetimes cannot be elided in `impl Trait` types without `#![feature(anonymous_lifetime_in_impl_trait)]`.
369    ImplTrait,
370}
371impl LifetimeRibKind {
372    /// Convenience function for creating non-erroring `Elided` variants.
373    fn elided(res: LifetimeRes) -> LifetimeRibKind {
374        LifetimeRibKind::Elided { res, error_in_path: false }
375    }
376}
377
378#[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)]
379enum LifetimeBinderKind {
380    FnPtrType,
381    PolyTrait,
382    WhereBound,
383    // Item covers foreign items, ADTs, type aliases, trait associated items and
384    // trait alias associated items.
385    Item,
386    ConstItem,
387    Function,
388    Closure,
389    ImplBlock,
390    // Covers only `impl` associated types.
391    ImplAssocType,
392}
393
394impl LifetimeBinderKind {
395    fn descr(self) -> &'static str {
396        use LifetimeBinderKind::*;
397        match self {
398            FnPtrType => "type",
399            PolyTrait => "bound",
400            WhereBound => "bound",
401            Item | ConstItem => "item",
402            ImplAssocType => "associated type",
403            ImplBlock => "impl block",
404            Function => "function",
405            Closure => "closure",
406        }
407    }
408}
409
410#[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)]
411struct LifetimeRib {
412    kind: LifetimeRibKind,
413    // We need to preserve insertion order for async fns.
414    bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
415}
416
417impl LifetimeRib {
418    fn new(kind: LifetimeRibKind) -> LifetimeRib {
419        LifetimeRib { bindings: Default::default(), kind }
420    }
421}
422
423#[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)]
424pub(crate) enum AliasPossibility {
425    No,
426    Maybe,
427}
428
429#[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)]
430pub(crate) enum PathSource<'a, 'ast, 'ra> {
431    /// Type paths `Path`.
432    Type,
433    /// Trait paths in bounds or impls.
434    Trait(AliasPossibility),
435    /// Expression paths `path`, with optional parent context.
436    Expr(Option<&'ast Expr>),
437    /// Paths in path patterns `Path`.
438    Pat,
439    /// Paths in struct expressions and patterns `Path { .. }`.
440    Struct(Option<&'a Expr>),
441    /// Paths in tuple struct patterns `Path(..)`.
442    TupleStruct(Span, &'ra [Span]),
443    /// `m::A::B` in `<T as m::A>::B::C`.
444    ///
445    /// Second field holds the "cause" of this one, i.e. the context within
446    /// which the trait item is resolved. Used for diagnostics.
447    TraitItem(Namespace, &'a PathSource<'a, 'ast, 'ra>),
448    /// Paths in delegation item
449    Delegation,
450    /// Paths in externally implementable item declarations.
451    ExternItemImpl,
452    /// An arg in a `use<'a, N>` precise-capturing bound.
453    PreciseCapturingArg(Namespace),
454    /// Paths that end with `(..)`, for return type notation.
455    ReturnTypeNotation,
456    /// Paths from `#[define_opaque]` attributes
457    DefineOpaques,
458    /// Resolving a macro
459    Macro,
460    /// Paths for module or crate root. Used for restrictions.
461    Module,
462}
463
464impl PathSource<'_, '_, '_> {
465    fn namespace(self) -> Namespace {
466        match self {
467            PathSource::Type
468            | PathSource::Trait(_)
469            | PathSource::Struct(_)
470            | PathSource::DefineOpaques
471            | PathSource::Module => TypeNS,
472            PathSource::Expr(..)
473            | PathSource::Pat
474            | PathSource::TupleStruct(..)
475            | PathSource::Delegation
476            | PathSource::ExternItemImpl
477            | PathSource::ReturnTypeNotation => ValueNS,
478            PathSource::TraitItem(ns, _) => ns,
479            PathSource::PreciseCapturingArg(ns) => ns,
480            PathSource::Macro => MacroNS,
481        }
482    }
483
484    fn defer_to_typeck(self) -> bool {
485        match self {
486            PathSource::Type
487            | PathSource::Expr(..)
488            | PathSource::Pat
489            | PathSource::Struct(_)
490            | PathSource::TupleStruct(..)
491            | PathSource::ReturnTypeNotation => true,
492            PathSource::Trait(_)
493            | PathSource::TraitItem(..)
494            | PathSource::DefineOpaques
495            | PathSource::Delegation
496            | PathSource::ExternItemImpl
497            | PathSource::PreciseCapturingArg(..)
498            | PathSource::Macro
499            | PathSource::Module => false,
500        }
501    }
502
503    fn descr_expected(self) -> &'static str {
504        match &self {
505            PathSource::DefineOpaques => "type alias or associated type with opaqaue types",
506            PathSource::Type => "type",
507            PathSource::Trait(_) => "trait",
508            PathSource::Pat => "unit struct, unit variant or constant",
509            PathSource::Struct(_) => "struct, variant or union type",
510            PathSource::TraitItem(ValueNS, PathSource::TupleStruct(..))
511            | PathSource::TupleStruct(..) => "tuple struct or tuple variant",
512            PathSource::TraitItem(ns, _) => match ns {
513                TypeNS => "associated type",
514                ValueNS => "method or associated constant",
515                MacroNS => ::rustc_middle::util::bug::bug_fmt(format_args!("associated macro"))bug!("associated macro"),
516            },
517            PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
518                // "function" here means "anything callable" rather than `DefKind::Fn`,
519                // this is not precise but usually more helpful than just "value".
520                Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
521                    // the case of `::some_crate()`
522                    ExprKind::Path(_, path)
523                        if let [segment, _] = path.segments.as_slice()
524                            && segment.ident.name == kw::PathRoot =>
525                    {
526                        "external crate"
527                    }
528                    ExprKind::Path(_, path)
529                        if let Some(segment) = path.segments.last()
530                            && let Some(c) = segment.ident.to_string().chars().next()
531                            && c.is_uppercase() =>
532                    {
533                        "function, tuple struct or tuple variant"
534                    }
535                    _ => "function",
536                },
537                _ => "value",
538            },
539            PathSource::ReturnTypeNotation | PathSource::Delegation => "function",
540            PathSource::ExternItemImpl => "function or static",
541            PathSource::PreciseCapturingArg(..) => "type or const parameter",
542            PathSource::Macro => "macro",
543            PathSource::Module => "module",
544        }
545    }
546
547    fn is_call(self) -> bool {
548        #[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(..), .. })))
549    }
550
551    pub(crate) fn is_expected(self, res: Res) -> bool {
552        match self {
553            PathSource::DefineOpaques => {
554                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum |
        DefKind::TyAlias | DefKind::AssocTy, _) | Res::SelfTyAlias { .. } =>
        true,
    _ => false,
}matches!(
555                    res,
556                    Res::Def(
557                        DefKind::Struct
558                            | DefKind::Union
559                            | DefKind::Enum
560                            | DefKind::TyAlias
561                            | DefKind::AssocTy,
562                        _
563                    ) | Res::SelfTyAlias { .. }
564                )
565            }
566            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!(
567                res,
568                Res::Def(
569                    DefKind::Struct
570                        | DefKind::Union
571                        | DefKind::Enum
572                        | DefKind::Trait
573                        | DefKind::TraitAlias
574                        | DefKind::TyAlias
575                        | DefKind::AssocTy
576                        | DefKind::TyParam
577                        | DefKind::OpaqueTy
578                        | DefKind::ForeignTy,
579                    _,
580                ) | Res::PrimTy(..)
581                    | Res::SelfTyParam { .. }
582                    | Res::SelfTyAlias { .. }
583            ),
584            PathSource::Trait(AliasPossibility::No) => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Trait, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Trait, _)),
585            PathSource::Trait(AliasPossibility::Maybe) => {
586                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
587            }
588            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!(
589                res,
590                Res::Def(
591                    DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
592                        | DefKind::Const { .. }
593                        | DefKind::Static { .. }
594                        | DefKind::Fn
595                        | DefKind::AssocFn
596                        | DefKind::AssocConst { .. }
597                        | DefKind::ConstParam,
598                    _,
599                ) | Res::Local(..)
600                    | Res::SelfCtor(..)
601            ),
602            PathSource::Pat => {
603                res.expected_in_unit_struct_pat()
604                    || #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Const { .. } | DefKind::AssocConst { .. }, _) => true,
    _ => false,
}matches!(
605                        res,
606                        Res::Def(DefKind::Const { .. } | DefKind::AssocConst { .. }, _)
607                    )
608            }
609            PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
610            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!(
611                res,
612                Res::Def(
613                    DefKind::Struct
614                        | DefKind::Union
615                        | DefKind::Variant
616                        | DefKind::TyAlias
617                        | DefKind::AssocTy,
618                    _,
619                ) | Res::SelfTyParam { .. }
620                    | Res::SelfTyAlias { .. }
621            ),
622            PathSource::TraitItem(ns, _) => match res {
623                Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn, _) if ns == ValueNS => true,
624                Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
625                _ => false,
626            },
627            PathSource::ReturnTypeNotation => match res {
628                Res::Def(DefKind::AssocFn, _) => true,
629                _ => false,
630            },
631            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, _)),
632            PathSource::ExternItemImpl => {
633                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) |
        DefKind::Static { .. }, _) => true,
    _ => false,
}matches!(
634                    res,
635                    Res::Def(
636                        DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::Static { .. },
637                        _
638                    )
639                )
640            }
641            PathSource::PreciseCapturingArg(ValueNS) => {
642                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::ConstParam, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::ConstParam, _))
643            }
644            // We allow `SelfTyAlias` here so we can give a more descriptive error later.
645            PathSource::PreciseCapturingArg(TypeNS) => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } |
        Res::SelfTyAlias { .. } => true,
    _ => false,
}matches!(
646                res,
647                Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }
648            ),
649            PathSource::PreciseCapturingArg(MacroNS) => false,
650            PathSource::Macro => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Macro(_), _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Macro(_), _)),
651            PathSource::Module => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Mod, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Mod, _)),
652        }
653    }
654
655    fn error_code(self, has_unexpected_resolution: bool) -> ErrCode {
656        match (self, has_unexpected_resolution) {
657            (PathSource::Trait(_), true) => E0404,
658            (PathSource::Trait(_), false) => E0405,
659            (PathSource::Type | PathSource::DefineOpaques, true) => E0573,
660            (PathSource::Type | PathSource::DefineOpaques, false) => E0425,
661            (PathSource::Struct(_), true) => E0574,
662            (PathSource::Struct(_), false) => E0422,
663            (PathSource::Expr(..), true)
664            | (PathSource::Delegation, true)
665            | (PathSource::ExternItemImpl, true) => E0423,
666            (PathSource::Expr(..), false)
667            | (PathSource::Delegation, false)
668            | (PathSource::ExternItemImpl, false) => E0425,
669            (PathSource::Pat | PathSource::TupleStruct(..), true) => E0532,
670            (PathSource::Pat | PathSource::TupleStruct(..), false) => E0531,
671            (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, true) => E0575,
672            (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, false) => E0576,
673            (PathSource::PreciseCapturingArg(..), true) => E0799,
674            (PathSource::PreciseCapturingArg(..), false) => E0800,
675            (PathSource::Macro, _) => E0425,
676            // FIXME: There is no dedicated error code for this case yet.
677            // E0577 already covers the same situation for visibilities,
678            // so we reuse it here for now. It may make sense to generalize
679            // it for restrictions in the future.
680            (PathSource::Module, true) => E0577,
681            (PathSource::Module, false) => E0433,
682        }
683    }
684}
685
686/// At this point for most items we can answer whether that item is exported or not,
687/// but some items like impls require type information to determine exported-ness, so we make a
688/// conservative estimate for them (e.g. based on nominal visibility).
689#[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)]
690enum MaybeExported<'a> {
691    Ok(NodeId),
692    Impl(Option<DefId>),
693    ImplItem(Result<DefId, &'a ast::Visibility>),
694    NestedUse(&'a ast::Visibility),
695}
696
697impl MaybeExported<'_> {
698    fn eval(self, r: &Resolver<'_, '_>) -> bool {
699        let def_id = match self {
700            MaybeExported::Ok(node_id) => Some(if r.current_owner.id == node_id {
701                r.current_owner.def_id
702            } else {
703                r.current_owner.node_id_to_def_id[&node_id]
704            }),
705            MaybeExported::Impl(Some(trait_def_id)) | MaybeExported::ImplItem(Ok(trait_def_id)) => {
706                trait_def_id.as_local()
707            }
708            MaybeExported::Impl(None) => return true,
709            MaybeExported::ImplItem(Err(vis)) | MaybeExported::NestedUse(vis) => {
710                return vis.kind.is_pub();
711            }
712        };
713        def_id.is_none_or(|def_id| r.effective_visibilities.is_exported(def_id))
714    }
715}
716
717/// Used for recording UnnecessaryQualification.
718#[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)]
719pub(crate) struct UnnecessaryQualification<'ra> {
720    pub decl: LateDecl<'ra>,
721    pub node_id: NodeId,
722    pub path_span: Span,
723    pub removal_span: Span,
724}
725
726#[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(),
            in_assoc_ty_binding: ::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", "in_assoc_ty_binding",
                        "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.in_assoc_ty_binding,
                        &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)]
727pub(crate) struct DiagMetadata<'ast> {
728    /// The current trait's associated items' ident, used for diagnostic suggestions.
729    current_trait_assoc_items: Option<&'ast [Box<AssocItem>]>,
730
731    /// The current self type if inside an impl (used for better errors).
732    pub(crate) current_self_type: Option<&'ast Ty>,
733
734    /// The current self item if inside an ADT (used for better errors).
735    current_self_item: Option<NodeId>,
736
737    /// The current item being evaluated (used for suggestions and more detail in errors).
738    pub(crate) current_item: Option<&'ast Item>,
739
740    /// When processing generic arguments and encountering an unresolved ident not found,
741    /// suggest introducing a type or const param depending on the context.
742    currently_processing_generic_args: bool,
743
744    /// The current enclosing (non-closure) function (used for better errors).
745    current_function: Option<(FnKind<'ast>, Span)>,
746
747    /// A list of labels as of yet unused. Labels will be removed from this map when
748    /// they are used (in a `break` or `continue` statement)
749    unused_labels: FxIndexMap<NodeId, Span>,
750
751    /// Only used for better errors on `let <pat>: <expr, not type>;`.
752    current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
753
754    current_pat: Option<&'ast Pat>,
755
756    /// Used to detect possible `if let` written without `let` and to provide structured suggestion.
757    in_if_condition: Option<&'ast Expr>,
758
759    /// Used to detect possible new binding written without `let` and to provide structured suggestion.
760    in_assignment: Option<&'ast Expr>,
761    is_assign_rhs: bool,
762
763    /// If we are setting an associated type in trait impl, is it a non-GAT type?
764    in_non_gat_assoc_type: Option<bool>,
765
766    /// Used to detect possible `.` -> `..` typo when calling methods.
767    in_range: Option<(&'ast Expr, &'ast Expr)>,
768
769    /// If we are currently in a trait object definition. Used to point at the bounds when
770    /// encountering a struct or enum.
771    current_trait_object: Option<&'ast [ast::GenericBound]>,
772
773    /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
774    current_where_predicate: Option<&'ast WherePredicate>,
775
776    /// Whether we are visiting an associated type equality binding like `Trait<Assoc = &T>`.
777    in_assoc_ty_binding: bool,
778
779    current_type_path: Option<&'ast Ty>,
780
781    /// The current impl items (used to suggest).
782    current_impl_items: Option<&'ast [Box<AssocItem>]>,
783
784    /// The current impl items (used to suggest).
785    current_impl_item: Option<&'ast AssocItem>,
786
787    /// When processing impl trait
788    currently_processing_impl_trait: Option<(TraitRef, Ty)>,
789
790    /// Accumulate the errors due to missed lifetime elision,
791    /// and report them all at once for each function.
792    current_elision_failures: Vec<(MissingLifetime, Either<NodeId, Range<NodeId>>)>,
793}
794
795struct LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
796    r: &'a mut Resolver<'ra, 'tcx>,
797
798    /// The module that represents the current item scope.
799    parent_scope: ParentScope<'ra>,
800
801    /// The current set of local scopes for types and values.
802    ribs: PerNS<Vec<Rib<'ra>>>,
803
804    /// Previous popped `rib`, only used for diagnostic.
805    last_block_rib: Option<Rib<'ra>>,
806
807    /// The current set of local scopes, for labels.
808    label_ribs: Vec<Rib<'ra, NodeId>>,
809
810    /// The current set of local scopes for lifetimes.
811    lifetime_ribs: Vec<LifetimeRib>,
812
813    /// We are looking for lifetimes in an elision context.
814    /// The set contains all the resolutions that we encountered so far.
815    /// They will be used to determine the correct lifetime for the fn return type.
816    /// The `LifetimeElisionCandidate` is used for diagnostics, to suggest introducing named
817    /// lifetimes.
818    lifetime_elision_candidates: Option<Vec<(LifetimeRes, LifetimeElisionCandidate)>>,
819
820    /// The trait that the current context can refer to.
821    current_trait_ref: Option<(Module<'ra>, TraitRef)>,
822
823    /// Fields used to add information to diagnostic errors.
824    diag_metadata: Box<DiagMetadata<'ast>>,
825
826    /// State used to know whether to ignore resolution errors for function bodies.
827    ///
828    /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
829    /// In most cases this will be `None`, in which case errors will always be reported.
830    /// If it is `true`, then it will be updated when entering a nested function or trait body.
831    in_func_body: bool,
832
833    /// Count the number of places a lifetime is used.
834    lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
835
836    /// `use` injections are delayed for better placement and deduplication.
837    use_injections: Vec<UseError<'tcx>>,
838}
839
840impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for LateResolutionVisitor<'_, '_, 'ra, 'tcx> {
841    fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
842        &self.r
843    }
844}
845impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for LateResolutionVisitor<'_, '_, 'ra, 'tcx> {
846    fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
847        &mut self.r
848    }
849}
850
851/// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
852impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
853    fn visit_attribute(&mut self, _: &'ast Attribute) {
854        // We do not want to resolve expressions that appear in attributes,
855        // as they do not correspond to actual code.
856    }
857    fn visit_item(&mut self, item: &'ast Item) {
858        let prev = replace(&mut self.diag_metadata.current_item, Some(item));
859        // Always report errors in items we just entered.
860        let old_ignore = replace(&mut self.in_func_body, false);
861        with_owner(self, item.id, |this| {
862            this.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item))
863        });
864        self.in_func_body = old_ignore;
865        self.diag_metadata.current_item = prev;
866    }
867    fn visit_arm(&mut self, arm: &'ast Arm) {
868        self.resolve_arm(arm);
869    }
870    fn visit_block(&mut self, block: &'ast Block) {
871        let old_macro_rules = self.parent_scope.macro_rules;
872        self.resolve_block(block);
873        self.parent_scope.macro_rules = old_macro_rules;
874    }
875    fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
876        ::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:#?}");
877    }
878    fn visit_expr(&mut self, expr: &'ast Expr) {
879        self.resolve_expr(expr, None);
880    }
881    fn visit_pat(&mut self, p: &'ast Pat) {
882        let prev = self.diag_metadata.current_pat;
883        self.diag_metadata.current_pat = Some(p);
884
885        if let PatKind::Guard(subpat, _) = &p.kind {
886            // We walk the guard expression in `resolve_pattern_inner`. Don't resolve it twice.
887            self.visit_pat(subpat);
888        } else {
889            visit::walk_pat(self, p);
890        }
891
892        self.diag_metadata.current_pat = prev;
893    }
894    fn visit_local(&mut self, local: &'ast Local) {
895        let local_spans = match local.pat.kind {
896            // We check for this to avoid tuple struct fields.
897            PatKind::Wild => None,
898            _ => Some((
899                local.pat.span,
900                local.ty.as_ref().map(|ty| ty.span),
901                local.kind.init().map(|init| init.span),
902            )),
903        };
904        let original = replace(&mut self.diag_metadata.current_let_binding, local_spans);
905        self.resolve_local(local);
906        self.diag_metadata.current_let_binding = original;
907    }
908    fn visit_ty(&mut self, ty: &'ast Ty) {
909        let prev = self.diag_metadata.current_trait_object;
910        let prev_ty = self.diag_metadata.current_type_path;
911        match &ty.kind {
912            TyKind::Ref(None, _) | TyKind::PinnedRef(None, _) => {
913                // Elided lifetime in reference: we resolve as if there was some lifetime `'_` with
914                // NodeId `ty.id`.
915                // This span will be used in case of elision failure.
916                let span = self.r.tcx.sess.source_map().start_point(ty.span);
917                self.resolve_elided_lifetime(ty.id, span);
918                visit::walk_ty(self, ty);
919            }
920            TyKind::Path(qself, path) => {
921                self.diag_metadata.current_type_path = Some(ty);
922
923                // If we have a path that ends with `(..)`, then it must be
924                // return type notation. Resolve that path in the *value*
925                // namespace.
926                let source = if let Some(seg) = path.segments.last()
927                    && let Some(args) = &seg.args
928                    && #[allow(non_exhaustive_omitted_patterns)] match **args {
    GenericArgs::ParenthesizedElided(..) => true,
    _ => false,
}matches!(**args, GenericArgs::ParenthesizedElided(..))
929                {
930                    PathSource::ReturnTypeNotation
931                } else {
932                    PathSource::Type
933                };
934
935                self.smart_resolve_path(ty.id, qself, path, source);
936
937                // Check whether we should interpret this as a bare trait object.
938                if qself.is_none()
939                    && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
940                    && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) =
941                        partial_res.full_res()
942                {
943                    // This path is actually a bare trait object. In case of a bare `Fn`-trait
944                    // object with anonymous lifetimes, we need this rib to correctly place the
945                    // synthetic lifetimes.
946                    let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
947                    self.with_generic_param_rib(
948                        &[],
949                        RibKind::Normal,
950                        ty.id,
951                        LifetimeBinderKind::PolyTrait,
952                        span,
953                        |this| this.visit_path(path),
954                    );
955                } else {
956                    visit::walk_ty(self, ty)
957                }
958            }
959            TyKind::ImplicitSelf => {
960                let self_ty = Ident::with_dummy_span(kw::SelfUpper);
961                let res = self
962                    .resolve_ident_in_lexical_scope(
963                        self_ty,
964                        TypeNS,
965                        Some(Finalize::new(ty.id, ty.span)),
966                        None,
967                    )
968                    .map_or(Res::Err, |d| d.res());
969                self.r.record_partial_res(ty.id, PartialRes::new(res));
970                visit::walk_ty(self, ty)
971            }
972            TyKind::ImplTrait(..) => {
973                let candidates = self.lifetime_elision_candidates.take();
974                self.with_lifetime_rib(LifetimeRibKind::ImplTrait, |this| visit::walk_ty(this, ty));
975                self.lifetime_elision_candidates = candidates;
976            }
977            TyKind::TraitObject(bounds, ..) => {
978                self.diag_metadata.current_trait_object = Some(&bounds[..]);
979                visit::walk_ty(self, ty)
980            }
981            TyKind::FnPtr(fn_ptr) => {
982                let span = ty.span.shrink_to_lo().to(fn_ptr.decl_span.shrink_to_lo());
983                self.with_generic_param_rib(
984                    &fn_ptr.generic_params,
985                    RibKind::Normal,
986                    ty.id,
987                    LifetimeBinderKind::FnPtrType,
988                    span,
989                    |this| {
990                        this.visit_generic_params(&fn_ptr.generic_params, false);
991                        this.resolve_fn_signature(
992                            ty.id,
993                            false,
994                            // We don't need to deal with patterns in parameters, because
995                            // they are not possible for foreign or bodiless functions.
996                            fn_ptr.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
997                            &fn_ptr.decl.output,
998                            false,
999                        )
1000                    },
1001                )
1002            }
1003            TyKind::UnsafeBinder(unsafe_binder) => {
1004                let span = ty.span.shrink_to_lo().to(unsafe_binder.inner_ty.span.shrink_to_lo());
1005                self.with_generic_param_rib(
1006                    &unsafe_binder.generic_params,
1007                    RibKind::Normal,
1008                    ty.id,
1009                    LifetimeBinderKind::FnPtrType,
1010                    span,
1011                    |this| {
1012                        this.visit_generic_params(&unsafe_binder.generic_params, false);
1013                        this.with_lifetime_rib(
1014                            // We don't allow anonymous `unsafe &'_ ()` binders,
1015                            // although I guess we could.
1016                            LifetimeRibKind::AnonymousReportError,
1017                            |this| this.visit_ty(&unsafe_binder.inner_ty),
1018                        );
1019                    },
1020                )
1021            }
1022            TyKind::Array(element_ty, length) => {
1023                self.visit_ty(element_ty);
1024                self.resolve_anon_const(length, AnonConstKind::ConstArg(IsRepeatExpr::No));
1025            }
1026            TyKind::DirectConstArg(expr) => self.resolve_anon_const_manual(
1027                true,
1028                AnonConstKind::ConstArg(IsRepeatExpr::No),
1029                |this| this.resolve_expr(expr, None),
1030            ),
1031            _ => visit::walk_ty(self, ty),
1032        }
1033        self.diag_metadata.current_trait_object = prev;
1034        self.diag_metadata.current_type_path = prev_ty;
1035    }
1036
1037    fn visit_ty_pat(&mut self, t: &'ast TyPat) -> Self::Result {
1038        match &t.kind {
1039            TyPatKind::Range(start, end, _) => {
1040                if let Some(start) = start {
1041                    self.resolve_anon_const(start, AnonConstKind::ConstArg(IsRepeatExpr::No));
1042                }
1043                if let Some(end) = end {
1044                    self.resolve_anon_const(end, AnonConstKind::ConstArg(IsRepeatExpr::No));
1045                }
1046            }
1047            TyPatKind::Or(patterns) => {
1048                for pat in patterns {
1049                    self.visit_ty_pat(pat)
1050                }
1051            }
1052            TyPatKind::NotNull | TyPatKind::Err(_) => {}
1053        }
1054    }
1055
1056    fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
1057        let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
1058        self.with_generic_param_rib(
1059            &tref.bound_generic_params,
1060            RibKind::Normal,
1061            tref.trait_ref.ref_id,
1062            LifetimeBinderKind::PolyTrait,
1063            span,
1064            |this| {
1065                this.visit_generic_params(&tref.bound_generic_params, false);
1066                this.smart_resolve_path(
1067                    tref.trait_ref.ref_id,
1068                    &None,
1069                    &tref.trait_ref.path,
1070                    PathSource::Trait(AliasPossibility::Maybe),
1071                );
1072                this.visit_trait_ref(&tref.trait_ref);
1073            },
1074        );
1075    }
1076    fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
1077        with_owner(self, foreign_item.id, |this| {
1078            this.resolve_doc_links(&foreign_item.attrs, MaybeExported::Ok(foreign_item.id));
1079            let def_kind = this.r.tcx.def_kind(this.r.current_owner.def_id);
1080            match foreign_item.kind {
1081                ForeignItemKind::TyAlias(TyAlias { ref generics, .. }) => {
1082                    this.with_generic_param_rib(
1083                        &generics.params,
1084                        RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1085                        foreign_item.id,
1086                        LifetimeBinderKind::Item,
1087                        generics.span,
1088                        |this| visit::walk_item(this, foreign_item),
1089                    );
1090                }
1091                ForeignItemKind::Fn(Fn { ref generics, .. }) => {
1092                    this.with_generic_param_rib(
1093                        &generics.params,
1094                        RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1095                        foreign_item.id,
1096                        LifetimeBinderKind::Function,
1097                        generics.span,
1098                        |this| visit::walk_item(this, foreign_item),
1099                    );
1100                }
1101                ForeignItemKind::Static(..) => {
1102                    this.with_static_rib(def_kind, |this| visit::walk_item(this, foreign_item))
1103                }
1104                ForeignItemKind::MacCall(..) => {
1105                    {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
1106                }
1107            }
1108        })
1109    }
1110    fn visit_fn(&mut self, fn_kind: FnKind<'ast>, _: &AttrVec, sp: Span, fn_id: NodeId) {
1111        let previous_value = self.diag_metadata.current_function;
1112        match fn_kind {
1113            // Bail if the function is foreign, and thus cannot validly have
1114            // a body, or if there's no body for some other reason.
1115            FnKind::Fn(FnCtxt::Foreign, _, Fn { sig, ident, generics, .. })
1116            | FnKind::Fn(_, _, Fn { sig, ident, generics, body: None, .. }) => {
1117                self.visit_fn_header(&sig.header);
1118                self.visit_ident(ident);
1119                self.visit_generics(generics);
1120                self.resolve_fn_signature(
1121                    fn_id,
1122                    sig.decl.has_self(),
1123                    sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1124                    &sig.decl.output,
1125                    false,
1126                );
1127                return;
1128            }
1129            FnKind::Fn(..) => {
1130                self.diag_metadata.current_function = Some((fn_kind, sp));
1131            }
1132            // Do not update `current_function` for closures: it suggests `self` parameters.
1133            FnKind::Closure(..) => {}
1134        };
1135        {
    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:1135",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1135u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("(resolving function) entering function")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("(resolving function) entering function");
1136
1137        if let FnKind::Fn(_, _, f) = fn_kind {
1138            self.resolve_eii(f.eii_impl.as_deref());
1139        }
1140
1141        // Create a value rib for the function.
1142        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
1143            // Create a label rib for the function.
1144            this.with_label_rib(RibKind::FnOrCoroutine, |this| {
1145                match fn_kind {
1146                    FnKind::Fn(_, _, Fn { sig, generics, contract, body, .. }) => {
1147                        this.visit_generics(generics);
1148
1149                        let declaration = &sig.decl;
1150                        let coro_node_id = sig
1151                            .header
1152                            .coroutine_kind
1153                            .map(|coroutine_kind| coroutine_kind.return_id());
1154
1155                        this.resolve_fn_signature(
1156                            fn_id,
1157                            declaration.has_self(),
1158                            declaration
1159                                .inputs
1160                                .iter()
1161                                .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
1162                            &declaration.output,
1163                            coro_node_id.is_some(),
1164                        );
1165
1166                        if let Some(contract) = contract {
1167                            this.visit_contract(contract);
1168                        }
1169
1170                        if let Some(body) = body {
1171                            // Ignore errors in function bodies if this is rustdoc
1172                            // Be sure not to set this until the function signature has been resolved.
1173                            let previous_state = replace(&mut this.in_func_body, true);
1174                            // We only care block in the same function
1175                            this.last_block_rib = None;
1176                            // Resolve the function body, potentially inside the body of an async closure
1177                            this.with_lifetime_rib(
1178                                LifetimeRibKind::elided(LifetimeRes::Infer),
1179                                |this| this.visit_block(body),
1180                            );
1181
1182                            {
    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:1182",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1182u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("(resolving function) leaving function")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("(resolving function) leaving function");
1183                            this.in_func_body = previous_state;
1184                        }
1185                    }
1186                    FnKind::Closure(binder, _, declaration, body) => {
1187                        this.visit_closure_binder(binder);
1188
1189                        this.with_lifetime_rib(
1190                            match binder {
1191                                // We do not have any explicit generic lifetime parameter.
1192                                ClosureBinder::NotPresent => {
1193                                    LifetimeRibKind::AnonymousCreateParameter {
1194                                        binder: fn_id,
1195                                        report_in_path: false,
1196                                    }
1197                                }
1198                                ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1199                            },
1200                            // Add each argument to the rib.
1201                            |this| this.resolve_params(&declaration.inputs),
1202                        );
1203                        this.with_lifetime_rib(
1204                            match binder {
1205                                ClosureBinder::NotPresent => {
1206                                    LifetimeRibKind::elided(LifetimeRes::Infer)
1207                                }
1208                                ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1209                            },
1210                            |this| visit::walk_fn_ret_ty(this, &declaration.output),
1211                        );
1212
1213                        // Ignore errors in function bodies if this is rustdoc
1214                        // Be sure not to set this until the function signature has been resolved.
1215                        let previous_state = replace(&mut this.in_func_body, true);
1216                        // Resolve the function body, potentially inside the body of an async closure
1217                        this.with_lifetime_rib(
1218                            LifetimeRibKind::elided(LifetimeRes::Infer),
1219                            |this| this.visit_expr(body),
1220                        );
1221
1222                        {
    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:1222",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1222u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("(resolving function) leaving function")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("(resolving function) leaving function");
1223                        this.in_func_body = previous_state;
1224                    }
1225                }
1226            })
1227        });
1228        self.diag_metadata.current_function = previous_value;
1229    }
1230
1231    fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1232        self.resolve_lifetime(lifetime, use_ctxt)
1233    }
1234
1235    fn visit_precise_capturing_arg(&mut self, arg: &'ast PreciseCapturingArg) {
1236        match arg {
1237            // Lower the lifetime regularly; we'll resolve the lifetime and check
1238            // it's a parameter later on in HIR lowering.
1239            PreciseCapturingArg::Lifetime(_) => {}
1240
1241            PreciseCapturingArg::Arg(path, id) => {
1242                // we want `impl use<C>` to try to resolve `C` as both a type parameter or
1243                // a const parameter. Since the resolver specifically doesn't allow having
1244                // two generic params with the same name, even if they're a different namespace,
1245                // it doesn't really matter which we try resolving first, but just like
1246                // `Ty::Param` we just fall back to the value namespace only if it's missing
1247                // from the type namespace.
1248                let mut check_ns = |ns| {
1249                    self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns).is_some()
1250                };
1251                // Like `Ty::Param`, we try resolving this as both a const and a type.
1252                if !check_ns(TypeNS) && check_ns(ValueNS) {
1253                    self.smart_resolve_path(
1254                        *id,
1255                        &None,
1256                        path,
1257                        PathSource::PreciseCapturingArg(ValueNS),
1258                    );
1259                } else {
1260                    self.smart_resolve_path(
1261                        *id,
1262                        &None,
1263                        path,
1264                        PathSource::PreciseCapturingArg(TypeNS),
1265                    );
1266                }
1267            }
1268        }
1269
1270        visit::walk_precise_capturing_arg(self, arg)
1271    }
1272
1273    fn visit_generics(&mut self, generics: &'ast Generics) {
1274        self.visit_generic_params(&generics.params, self.diag_metadata.current_self_item.is_some());
1275        for p in &generics.where_clause.predicates {
1276            self.visit_where_predicate(p);
1277        }
1278    }
1279
1280    fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
1281        match b {
1282            ClosureBinder::NotPresent => {}
1283            ClosureBinder::For { generic_params, .. } => {
1284                self.visit_generic_params(
1285                    generic_params,
1286                    self.diag_metadata.current_self_item.is_some(),
1287                );
1288            }
1289        }
1290    }
1291
1292    #[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("visit_generic_arg",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1292u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("arg")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("arg");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arg)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let prev =
                replace(&mut self.diag_metadata.currently_processing_generic_args,
                    true);
            match arg {
                GenericArg::Type(ty) => {
                    if let TyKind::Path(None, ref path) = ty.kind &&
                                    let Some(ident) = path.as_single_argless_ident() &&
                                self.maybe_resolve_ident_in_lexical_scope(ident,
                                        TypeNS).is_none() &&
                            self.maybe_resolve_ident_in_lexical_scope(ident,
                                    ValueNS).is_some() {
                        self.resolve_anon_const_manual(true,
                            AnonConstKind::ConstArg(IsRepeatExpr::No),
                            |this|
                                {
                                    this.smart_resolve_path(ty.id, &None, path,
                                        PathSource::Expr(None));
                                    this.visit_path(path);
                                })
                    } else { self.visit_ty(ty) }
                }
                GenericArg::Lifetime(lt) =>
                    self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
                GenericArg::Const(ct) => {
                    self.resolve_anon_const(ct,
                        AnonConstKind::ConstArg(IsRepeatExpr::No))
                }
            }
            self.diag_metadata.currently_processing_generic_args = prev;
        }
    }
}#[instrument(level = "debug", skip(self))]
1293    fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
1294        let prev = replace(&mut self.diag_metadata.currently_processing_generic_args, true);
1295        match arg {
1296            GenericArg::Type(ty) => {
1297                // We parse const arguments as path types as we cannot distinguish them during
1298                // parsing. We try to resolve that ambiguity by attempting resolution the type
1299                // namespace first, and if that fails we try again in the value namespace. If
1300                // resolution in the value namespace succeeds, we have an generic const argument on
1301                // our hands.
1302                //
1303                // We cannot disambiguate multi-segment paths right now as that requires type
1304                // checking.
1305                if let TyKind::Path(None, ref path) = ty.kind
1306                    && let Some(ident) = path.as_single_argless_ident()
1307                    && self.maybe_resolve_ident_in_lexical_scope(ident, TypeNS).is_none()
1308                    && self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS).is_some()
1309                {
1310                    self.resolve_anon_const_manual(
1311                        true,
1312                        AnonConstKind::ConstArg(IsRepeatExpr::No),
1313                        |this| {
1314                            this.smart_resolve_path(ty.id, &None, path, PathSource::Expr(None));
1315                            this.visit_path(path);
1316                        },
1317                    )
1318                } else {
1319                    self.visit_ty(ty)
1320                }
1321            }
1322            GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1323            GenericArg::Const(ct) => {
1324                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
1325            }
1326        }
1327        self.diag_metadata.currently_processing_generic_args = prev;
1328    }
1329
1330    fn visit_assoc_item_constraint(&mut self, constraint: &'ast AssocItemConstraint) {
1331        self.visit_ident(&constraint.ident);
1332        if let Some(ref gen_args) = constraint.gen_args {
1333            // Forbid anonymous lifetimes in GAT parameters until proper semantics are decided.
1334            self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1335                this.visit_generic_args(gen_args)
1336            });
1337        }
1338        match constraint.kind {
1339            AssocItemConstraintKind::Equality { ref term } => match term {
1340                Term::Ty(ty) => {
1341                    let prev = replace(&mut self.diag_metadata.in_assoc_ty_binding, true);
1342                    self.visit_ty(ty);
1343                    self.diag_metadata.in_assoc_ty_binding = prev;
1344                }
1345                Term::Const(c) => {
1346                    self.resolve_anon_const(c, AnonConstKind::ConstArg(IsRepeatExpr::No))
1347                }
1348            },
1349            AssocItemConstraintKind::Bound { ref bounds } => {
1350                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);
1351            }
1352        }
1353    }
1354
1355    fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1356        let Some(ref args) = path_segment.args else {
1357            return;
1358        };
1359
1360        match &**args {
1361            GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1362            GenericArgs::Parenthesized(p_args) => {
1363                // Probe the lifetime ribs to know how to behave.
1364                for rib in self.lifetime_ribs.iter().rev() {
1365                    match rib.kind {
1366                        // We are inside a `PolyTraitRef`. The lifetimes are
1367                        // to be introduced in that (maybe implicit) `for<>` binder.
1368                        LifetimeRibKind::Generics {
1369                            binder,
1370                            kind: LifetimeBinderKind::PolyTrait,
1371                            ..
1372                        } => {
1373                            self.resolve_fn_signature(
1374                                binder,
1375                                false,
1376                                p_args.inputs.iter().map(|param| (None, &*param.ty)),
1377                                &p_args.output,
1378                                false,
1379                            );
1380                            break;
1381                        }
1382                        // We have nowhere to introduce generics. Code is malformed,
1383                        // so use regular lifetime resolution to avoid spurious errors.
1384                        LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1385                            visit::walk_generic_args(self, args);
1386                            break;
1387                        }
1388                        LifetimeRibKind::AnonymousCreateParameter { .. }
1389                        | LifetimeRibKind::AnonymousReportError
1390                        | LifetimeRibKind::ImplTrait
1391                        | LifetimeRibKind::Elided { .. }
1392                        | LifetimeRibKind::ElisionFailure
1393                        | LifetimeRibKind::ConcreteAnonConst(_)
1394                        | LifetimeRibKind::ConstParamTy => {}
1395                    }
1396                }
1397            }
1398            GenericArgs::ParenthesizedElided(_) => {}
1399        }
1400    }
1401
1402    fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1403        {
    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:1403",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1403u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_where_predicate {0:?}",
                                                    p) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("visit_where_predicate {:?}", p);
1404        let previous_value = replace(&mut self.diag_metadata.current_where_predicate, Some(p));
1405        self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1406            if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1407                bounded_ty,
1408                bounds,
1409                bound_generic_params,
1410                ..
1411            }) = &p.kind
1412            {
1413                let span = p.span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1414                this.with_generic_param_rib(
1415                    bound_generic_params,
1416                    RibKind::Normal,
1417                    bounded_ty.id,
1418                    LifetimeBinderKind::WhereBound,
1419                    span,
1420                    |this| {
1421                        this.visit_generic_params(bound_generic_params, false);
1422                        this.visit_ty(bounded_ty);
1423                        for bound in bounds {
1424                            this.visit_param_bound(bound, BoundKind::Bound)
1425                        }
1426                    },
1427                );
1428            } else {
1429                visit::walk_where_predicate(this, p);
1430            }
1431        });
1432        self.diag_metadata.current_where_predicate = previous_value;
1433    }
1434
1435    fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1436        for (op, _) in &asm.operands {
1437            match op {
1438                InlineAsmOperand::In { expr, .. }
1439                | InlineAsmOperand::Out { expr: Some(expr), .. }
1440                | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1441                InlineAsmOperand::Out { expr: None, .. } => {}
1442                InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1443                    self.visit_expr(in_expr);
1444                    if let Some(out_expr) = out_expr {
1445                        self.visit_expr(out_expr);
1446                    }
1447                }
1448                InlineAsmOperand::Const { anon_const, .. } => {
1449                    // Although this is `DefKind::AnonConst`, it is allowed to reference outer
1450                    // generic parameters like an inline const.
1451                    self.resolve_anon_const(anon_const, AnonConstKind::InlineConst);
1452                }
1453                InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1454                InlineAsmOperand::Label { block } => self.visit_block(block),
1455            }
1456        }
1457    }
1458
1459    fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1460        // This is similar to the code for AnonConst.
1461        self.with_rib(ValueNS, RibKind::InlineAsmSym, |this| {
1462            this.with_rib(TypeNS, RibKind::InlineAsmSym, |this| {
1463                this.with_label_rib(RibKind::InlineAsmSym, |this| {
1464                    this.smart_resolve_path(sym.id, &sym.qself, &sym.path, PathSource::Expr(None));
1465                    visit::walk_inline_asm_sym(this, sym);
1466                });
1467            })
1468        });
1469    }
1470
1471    fn visit_variant(&mut self, v: &'ast Variant) {
1472        self.resolve_doc_links(&v.attrs, MaybeExported::Ok(v.id));
1473        self.visit_id(v.id);
1474        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);
1475        self.visit_vis(&v.vis);
1476        self.visit_ident(&v.ident);
1477        self.visit_variant_data(&v.data);
1478        if let Some(discr) = &v.disr_expr {
1479            self.resolve_anon_const(discr, AnonConstKind::EnumDiscriminant);
1480        }
1481    }
1482
1483    fn visit_field_def(&mut self, f: &'ast FieldDef) {
1484        self.resolve_doc_links(&f.attrs, MaybeExported::Ok(f.id));
1485        let FieldDef { attrs, id: _, span: _, vis, ident, ty, is_placeholder: _, extras: _ } = f;
1486        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);
1487        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));
1488        self.resolve_restriction_path(&f.mut_restriction().kind);
1489        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);
1490        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));
1491        if let Some(v) = f.default_value() {
1492            self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);
1493        }
1494    }
1495}
1496
1497impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1498    fn new(resolver: &'a mut Resolver<'ra, 'tcx>) -> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1499        // During late resolution we only track the module component of the parent scope,
1500        // although it may be useful to track other components as well for diagnostics.
1501        let graph_root = resolver.graph_root;
1502        let parent_scope = ParentScope::module(graph_root, resolver.arenas);
1503        let start_rib_kind = RibKind::Module(graph_root);
1504        LateResolutionVisitor {
1505            r: resolver,
1506            parent_scope,
1507            ribs: PerNS {
1508                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)],
1509                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)],
1510                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)],
1511            },
1512            last_block_rib: None,
1513            label_ribs: Vec::new(),
1514            lifetime_ribs: Vec::new(),
1515            lifetime_elision_candidates: None,
1516            current_trait_ref: None,
1517            diag_metadata: Default::default(),
1518            // errors at module scope should always be reported
1519            in_func_body: false,
1520            lifetime_uses: Default::default(),
1521            use_injections: Vec::new(),
1522        }
1523    }
1524
1525    fn maybe_resolve_ident_in_lexical_scope(
1526        &mut self,
1527        ident: Ident,
1528        ns: Namespace,
1529    ) -> Option<LateDecl<'ra>> {
1530        self.r.resolve_ident_in_lexical_scope(
1531            ident,
1532            ns,
1533            &self.parent_scope,
1534            None,
1535            &self.ribs[ns],
1536            None,
1537            Some(&self.diag_metadata),
1538        )
1539    }
1540
1541    fn resolve_ident_in_lexical_scope(
1542        &mut self,
1543        ident: Ident,
1544        ns: Namespace,
1545        finalize: Option<Finalize>,
1546        ignore_decl: Option<Decl<'ra>>,
1547    ) -> Option<LateDecl<'ra>> {
1548        self.r.resolve_ident_in_lexical_scope(
1549            ident,
1550            ns,
1551            &self.parent_scope,
1552            finalize,
1553            &self.ribs[ns],
1554            ignore_decl,
1555            Some(&self.diag_metadata),
1556        )
1557    }
1558
1559    fn resolve_path(
1560        &mut self,
1561        path: &[Segment],
1562        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1563        finalize: Option<Finalize>,
1564        source: PathSource<'_, 'ast, 'ra>,
1565    ) -> PathResult<'ra> {
1566        self.r.cm_mut().resolve_path_with_ribs(
1567            path,
1568            opt_ns,
1569            &self.parent_scope,
1570            Some(source),
1571            finalize.map(|finalize| Finalize { stage: Stage::Late, ..finalize }),
1572            Some(&self.ribs),
1573            None,
1574            None,
1575            Some(&self.diag_metadata),
1576        )
1577    }
1578
1579    // AST resolution
1580    //
1581    // We maintain a list of value ribs and type ribs.
1582    //
1583    // Simultaneously, we keep track of the current position in the module
1584    // graph in the `parent_scope.module` pointer. When we go to resolve a name in
1585    // the value or type namespaces, we first look through all the ribs and
1586    // then query the module graph. When we resolve a name in the module
1587    // namespace, we can skip all the ribs (since nested modules are not
1588    // allowed within blocks in Rust) and jump straight to the current module
1589    // graph node.
1590    //
1591    // Named implementations are handled separately. When we find a method
1592    // call, we consult the module node to find all of the implementations in
1593    // scope. This information is lazily cached in the module node. We then
1594    // generate a fake "implementation scope" containing all the
1595    // implementations thus found, for compatibility with old resolve pass.
1596
1597    /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
1598    fn with_rib<T>(
1599        &mut self,
1600        ns: Namespace,
1601        kind: RibKind<'ra>,
1602        work: impl FnOnce(&mut Self) -> T,
1603    ) -> T {
1604        self.ribs[ns].push(Rib::new(kind));
1605        let ret = work(self);
1606        self.ribs[ns].pop();
1607        ret
1608    }
1609
1610    fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1611        // For type parameter defaults, we have to ban access
1612        // to following type parameters, as the GenericArgs can only
1613        // provide previous type parameters as they're built. We
1614        // put all the parameters on the ban list and then remove
1615        // them one by one as they are processed and become available.
1616        let mut forward_ty_ban_rib =
1617            Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1618        let mut forward_const_ban_rib =
1619            Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1620        for param in params.iter() {
1621            match param.kind {
1622                GenericParamKind::Type { .. } => {
1623                    forward_ty_ban_rib
1624                        .bindings
1625                        .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1626                }
1627                GenericParamKind::Const { .. } => {
1628                    forward_const_ban_rib
1629                        .bindings
1630                        .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1631                }
1632                GenericParamKind::Lifetime => {}
1633            }
1634        }
1635
1636        // rust-lang/rust#61631: The type `Self` is essentially
1637        // another type parameter. For ADTs, we consider it
1638        // well-defined only after all of the ADT type parameters have
1639        // been provided. Therefore, we do not allow use of `Self`
1640        // anywhere in ADT type parameter defaults.
1641        //
1642        // (We however cannot ban `Self` for defaults on *all* generic
1643        // lists; e.g. trait generics can usefully refer to `Self`,
1644        // such as in the case of `trait Add<Rhs = Self>`.)
1645        if add_self_upper {
1646            // (`Some` if + only if we are in ADT's generics.)
1647            forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1648        }
1649
1650        // NOTE: We use different ribs here not for a technical reason, but just
1651        // for better diagnostics.
1652        let mut forward_ty_ban_rib_const_param_ty = Rib {
1653            bindings: forward_ty_ban_rib.bindings.clone(),
1654            patterns_with_skipped_bindings: Default::default(),
1655            kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1656        };
1657        let mut forward_const_ban_rib_const_param_ty = Rib {
1658            bindings: forward_const_ban_rib.bindings.clone(),
1659            patterns_with_skipped_bindings: Default::default(),
1660            kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1661        };
1662        // We'll ban these with a `ConstParamTy` rib, so just clear these ribs for better
1663        // diagnostics, so we don't mention anything about const param tys having generics at all.
1664        if !self.r.features.generic_const_parameter_types() {
1665            forward_ty_ban_rib_const_param_ty.bindings.clear();
1666            forward_const_ban_rib_const_param_ty.bindings.clear();
1667        }
1668
1669        self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1670            for param in params {
1671                match param.kind {
1672                    GenericParamKind::Lifetime => {
1673                        for bound in &param.bounds {
1674                            this.visit_param_bound(bound, BoundKind::Bound);
1675                        }
1676                    }
1677                    GenericParamKind::Type { ref default } => {
1678                        for bound in &param.bounds {
1679                            this.visit_param_bound(bound, BoundKind::Bound);
1680                        }
1681
1682                        if let Some(ty) = default {
1683                            this.ribs[TypeNS].push(forward_ty_ban_rib);
1684                            this.ribs[ValueNS].push(forward_const_ban_rib);
1685                            this.visit_ty(ty);
1686                            forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1687                            forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1688                        }
1689
1690                        // Allow all following defaults to refer to this type parameter.
1691                        let i = &Ident::with_dummy_span(param.ident.name);
1692                        forward_ty_ban_rib.bindings.swap_remove(i);
1693                        forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);
1694                    }
1695                    GenericParamKind::Const { ref ty, span: _, ref default } => {
1696                        // Const parameters can't have param bounds.
1697                        if !param.bounds.is_empty() {
    ::core::panicking::panic("assertion failed: param.bounds.is_empty()")
};assert!(param.bounds.is_empty());
1698
1699                        this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);
1700                        this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);
1701                        if this.r.features.generic_const_parameter_types() {
1702                            this.visit_ty(ty)
1703                        } else {
1704                            this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));
1705                            this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));
1706                            this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {
1707                                this.visit_ty(ty)
1708                            });
1709                            this.ribs[TypeNS].pop().unwrap();
1710                            this.ribs[ValueNS].pop().unwrap();
1711                        }
1712                        forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();
1713                        forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();
1714
1715                        if let Some(expr) = default {
1716                            this.ribs[TypeNS].push(forward_ty_ban_rib);
1717                            this.ribs[ValueNS].push(forward_const_ban_rib);
1718                            this.resolve_anon_const(
1719                                expr,
1720                                AnonConstKind::ConstArg(IsRepeatExpr::No),
1721                            );
1722                            forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1723                            forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1724                        }
1725
1726                        // Allow all following defaults to refer to this const parameter.
1727                        let i = &Ident::with_dummy_span(param.ident.name);
1728                        forward_const_ban_rib.bindings.swap_remove(i);
1729                        forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);
1730                    }
1731                }
1732            }
1733        })
1734    }
1735
1736    #[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(1736u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("kind")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("kind");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: 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))]
1737    fn with_lifetime_rib<T>(
1738        &mut self,
1739        kind: LifetimeRibKind,
1740        work: impl FnOnce(&mut Self) -> T,
1741    ) -> T {
1742        self.lifetime_ribs.push(LifetimeRib::new(kind));
1743        let outer_elision_candidates = self.lifetime_elision_candidates.take();
1744        let ret = work(self);
1745        self.lifetime_elision_candidates = outer_elision_candidates;
1746        self.lifetime_ribs.pop();
1747        ret
1748    }
1749
1750    #[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(1750u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("lifetime")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("lifetime");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("use_ctxt")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("use_ctxt");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_ctxt)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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:1776",
                                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1776u32),
                                                        ::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};
                                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("First use of {0:?} at {1:?}",
                                                                                    res, ident.span) as &dyn ::tracing::field::Value))])
                                            });
                                    } else { ; }
                                };
                                let use_set =
                                    self.lifetime_ribs.iter().rev().find_map(|rib|
                                                match rib.kind {
                                                    LifetimeRibKind::Item |
                                                        LifetimeRibKind::AnonymousReportError |
                                                        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 { res: r, error_in_path } => {
                                                        Some(if res == r && !error_in_path {
                                                                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.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: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(&[{
                                                                            const NAME:
                                                                                ::tracing::__macro_support::FieldName<{
                                                                                    ::tracing::__macro_support::FieldName::len("use_ctxt")
                                                                                }> =
                                                                                ::tracing::__macro_support::FieldName::new("use_ctxt");
                                                                            NAME.as_str()
                                                                        },
                                                                        {
                                                                            const NAME:
                                                                                ::tracing::__macro_support::FieldName<{
                                                                                    ::tracing::__macro_support::FieldName::len("use_set")
                                                                                }> =
                                                                                ::tracing::__macro_support::FieldName::new("use_set");
                                                                            NAME.as_str()
                                                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                        ::tracing::metadata::Kind::EVENT)
                                                };
                                            ::tracing::callsite::DefaultCallsite::new(&META)
                                        };
                                    let enabled =
                                        ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            {
                                                let interest = __CALLSITE.interest();
                                                !interest.is_never() &&
                                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                        interest)
                                            };
                                    if enabled {
                                        (|value_set: ::tracing::field::ValueSet|
                                                    {
                                                        let meta = __CALLSITE.metadata();
                                                        ::tracing::Event::dispatch(meta, &value_set);
                                                        ;
                                                    })({
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_ctxt)
                                                                            as &dyn ::tracing::field::Value)),
                                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_set)
                                                                            as &dyn ::tracing::field::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:1825",
                                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1825u32),
                                                        ::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};
                                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Many uses of {0:?} at {1:?}",
                                                                                    res, ident.span) as &dyn ::tracing::field::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 => {}
                }
            }
            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))]
1751    fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1752        let ident = lifetime.ident;
1753
1754        if ident.name == kw::StaticLifetime {
1755            self.record_lifetime_use(
1756                lifetime.id,
1757                LifetimeRes::Static,
1758                LifetimeElisionCandidate::Ignore,
1759            );
1760            return;
1761        }
1762
1763        if ident.name == kw::UnderscoreLifetime {
1764            return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1765        }
1766
1767        let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1768        while let Some(rib) = lifetime_rib_iter.next() {
1769            let normalized_ident = ident.normalize_to_macros_2_0();
1770            if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1771                self.record_lifetime_use(lifetime.id, res, LifetimeElisionCandidate::Ignore);
1772
1773                if let LifetimeRes::Param { param, binder } = res {
1774                    match self.lifetime_uses.entry(param) {
1775                        Entry::Vacant(v) => {
1776                            debug!("First use of {:?} at {:?}", res, ident.span);
1777                            let use_set = self
1778                                .lifetime_ribs
1779                                .iter()
1780                                .rev()
1781                                .find_map(|rib| match rib.kind {
1782                                    // Do not suggest eliding a lifetime where an anonymous
1783                                    // lifetime would be illegal.
1784                                    LifetimeRibKind::Item
1785                                    | LifetimeRibKind::AnonymousReportError
1786                                    | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1787                                    // An anonymous lifetime is legal here, and bound to the right
1788                                    // place, go ahead.
1789                                    LifetimeRibKind::AnonymousCreateParameter {
1790                                        binder: anon_binder,
1791                                        ..
1792                                    } => Some(if binder == anon_binder {
1793                                        LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1794                                    } else {
1795                                        LifetimeUseSet::Many
1796                                    }),
1797                                    // Only report if eliding the lifetime would have the same
1798                                    // semantics.
1799                                    LifetimeRibKind::Elided { res: r, error_in_path } => {
1800                                        Some(if res == r && !error_in_path {
1801                                            LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1802                                        } else {
1803                                            LifetimeUseSet::Many
1804                                        })
1805                                    }
1806                                    LifetimeRibKind::Generics { .. }
1807                                    | LifetimeRibKind::ConstParamTy => None,
1808                                    LifetimeRibKind::ConcreteAnonConst(_) => {
1809                                        span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1810                                    }
1811
1812                                    LifetimeRibKind::ImplTrait => {
1813                                        if self.r.features.anonymous_lifetime_in_impl_trait() {
1814                                            None
1815                                        } else {
1816                                            Some(LifetimeUseSet::Many)
1817                                        }
1818                                    }
1819                                })
1820                                .unwrap_or(LifetimeUseSet::Many);
1821                            debug!(?use_ctxt, ?use_set);
1822                            v.insert(use_set);
1823                        }
1824                        Entry::Occupied(mut o) => {
1825                            debug!("Many uses of {:?} at {:?}", res, ident.span);
1826                            *o.get_mut() = LifetimeUseSet::Many;
1827                        }
1828                    }
1829                }
1830                return;
1831            }
1832
1833            match rib.kind {
1834                LifetimeRibKind::Item => break,
1835                LifetimeRibKind::ConstParamTy => {
1836                    let guar = self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1837                    self.record_lifetime_err(lifetime.id, guar);
1838                    return;
1839                }
1840                LifetimeRibKind::ConcreteAnonConst(cause) => {
1841                    let guar = self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1842                    self.record_lifetime_err(lifetime.id, guar);
1843                    return;
1844                }
1845                LifetimeRibKind::AnonymousCreateParameter { .. }
1846                | LifetimeRibKind::Elided { .. }
1847                | LifetimeRibKind::Generics { .. }
1848                | LifetimeRibKind::ElisionFailure
1849                | LifetimeRibKind::AnonymousReportError
1850                | LifetimeRibKind::ImplTrait => {}
1851            }
1852        }
1853
1854        let normalized_ident = ident.normalize_to_macros_2_0();
1855        let outer_res = lifetime_rib_iter
1856            .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1857
1858        let guar = self.emit_undeclared_lifetime_error(lifetime, outer_res);
1859        self.record_lifetime_err(lifetime.id, guar);
1860    }
1861
1862    #[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(1862u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("lifetime")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("lifetime");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("id_for_lint")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("id_for_lint");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("elided")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("elided");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id_for_lint)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&elided as
                                                            &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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:1882",
                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1882u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                        ::tracing_core::field::FieldSet::new(&[{
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("rib.kind")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("rib.kind");
                                                            NAME.as_str()
                                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rib.kind)
                                                            as &dyn ::tracing::field::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::AnonymousReportError => {
                        let guar =
                            if elided {
                                let suggestion =
                                    if self.diag_metadata.in_assoc_ty_binding {
                                        None
                                    } else {
                                        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 if self.diag_metadata.in_assoc_ty_binding {
                                    let mut err =
                                        self.r.dcx().create_err(crate::diagnostics::ElidedAnonymousLifetimeReportError {
                                                span: lifetime.ident.span,
                                                suggestion,
                                            });
                                    self.suggest_introducing_lifetime_for_assoc_ty_binding(&mut err,
                                        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))]
1863    fn resolve_anonymous_lifetime(
1864        &mut self,
1865        lifetime: &Lifetime,
1866        id_for_lint: NodeId,
1867        elided: bool,
1868    ) {
1869        debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1870
1871        let kind =
1872            if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1873        let missing_lifetime = MissingLifetime {
1874            id: lifetime.id,
1875            span: lifetime.ident.span,
1876            kind,
1877            count: 1,
1878            id_for_lint,
1879        };
1880        let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1881        for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1882            debug!(?rib.kind);
1883            match rib.kind {
1884                LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1885                    let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1886                    self.record_lifetime_use(lifetime.id, res, elision_candidate);
1887                    return;
1888                }
1889                LifetimeRibKind::AnonymousReportError => {
1890                    let guar = if elided {
1891                        let suggestion = if self.diag_metadata.in_assoc_ty_binding {
1892                            // In an associated type binding like `I: IntoIterator<Item = &T>`,
1893                            // introducing the lifetime on the trait ref would produce
1894                            // `I: for<'a> IntoIterator<Item = &'a T>`. Prefer a named lifetime
1895                            // from an enclosing item instead, so the assoc-ty-binding-specific path
1896                            // below builds that suggestion.
1897                            None
1898                        } else {
1899                            self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1900                                // Look for a `Generics` rib that represents a trait or where-bound
1901                                // binder (`T: Trait<&U>` or `where T: Trait<&U>`), since that is
1902                                // where the generic E0637 diagnostic can insert `for<'a>`.
1903                                if let LifetimeRibKind::Generics {
1904                                    span,
1905                                    kind:
1906                                        LifetimeBinderKind::PolyTrait
1907                                        | LifetimeBinderKind::WhereBound,
1908                                    ..
1909                                } = rib.kind
1910                                {
1911                                    Some(crate::diagnostics::ElidedAnonymousLifetimeReportErrorSuggestion {
1912                                        lo: span.shrink_to_lo(),
1913                                        hi: lifetime.ident.span.shrink_to_hi(),
1914                                    })
1915                                } else {
1916                                    None
1917                                }
1918                            })
1919                        };
1920                        // are we trying to use an anonymous lifetime
1921                        // on a non GAT associated trait type?
1922                        if !self.in_func_body
1923                            && let Some((module, _)) = &self.current_trait_ref
1924                            && let Some(ty) = &self.diag_metadata.current_self_type
1925                            && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1926                            && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _, _) =
1927                                module.kind
1928                        {
1929                            if def_id_matches_path(
1930                                self.r.tcx,
1931                                trait_id,
1932                                &["core", "iter", "traits", "iterator", "Iterator"],
1933                            ) {
1934                                self.r.dcx().emit_err(
1935                                    crate::diagnostics::LendingIteratorReportError {
1936                                        lifetime: lifetime.ident.span,
1937                                        ty: ty.span,
1938                                    },
1939                                )
1940                            } else {
1941                                let decl = if !trait_id.is_local()
1942                                    && let Some(assoc) = self.diag_metadata.current_impl_item
1943                                    && let AssocItemKind::Type(_) = assoc.kind
1944                                    && let assocs = self.r.tcx.associated_items(trait_id)
1945                                    && let Some(ident) = assoc.kind.ident()
1946                                    && let Some(assoc) = assocs.find_by_ident_and_kind(
1947                                        self.r.tcx,
1948                                        ident,
1949                                        AssocTag::Type,
1950                                        trait_id,
1951                                    ) {
1952                                    let mut decl: MultiSpan =
1953                                        self.r.tcx.def_span(assoc.def_id).into();
1954                                    decl.push_span_label(
1955                                        self.r.tcx.def_span(trait_id),
1956                                        String::new(),
1957                                    );
1958                                    decl
1959                                } else {
1960                                    DUMMY_SP.into()
1961                                };
1962                                let mut err = self.r.dcx().create_err(
1963                                    crate::diagnostics::AnonymousLifetimeNonGatReportError {
1964                                        lifetime: lifetime.ident.span,
1965                                        decl,
1966                                    },
1967                                );
1968                                self.point_at_impl_lifetimes(&mut err, i, lifetime.ident.span);
1969                                err.emit()
1970                            }
1971                        } else if self.diag_metadata.in_assoc_ty_binding {
1972                            // For associated type bindings, e.g.
1973                            // `fn f<I: IntoIterator<Item = &T>>()`, introduce a named lifetime
1974                            // on an enclosing generics binder instead:
1975                            // `fn f<'a, I: IntoIterator<Item = &'a T>>()`.
1976                            let mut err = self.r.dcx().create_err(
1977                                crate::diagnostics::ElidedAnonymousLifetimeReportError {
1978                                    span: lifetime.ident.span,
1979                                    suggestion,
1980                                },
1981                            );
1982                            self.suggest_introducing_lifetime_for_assoc_ty_binding(
1983                                &mut err,
1984                                lifetime.ident.span,
1985                            );
1986                            err.emit()
1987                        } else {
1988                            self.r.dcx().emit_err(
1989                                crate::diagnostics::ElidedAnonymousLifetimeReportError {
1990                                    span: lifetime.ident.span,
1991                                    suggestion,
1992                                },
1993                            )
1994                        }
1995                    } else {
1996                        self.r.dcx().emit_err(
1997                            crate::diagnostics::ExplicitAnonymousLifetimeReportError {
1998                                span: lifetime.ident.span,
1999                            },
2000                        )
2001                    };
2002                    self.record_lifetime_err(lifetime.id, guar);
2003                    return;
2004                }
2005                LifetimeRibKind::Elided { res, .. } => {
2006                    self.record_lifetime_use(lifetime.id, res, elision_candidate);
2007                    return;
2008                }
2009                LifetimeRibKind::ElisionFailure => {
2010                    self.diag_metadata
2011                        .current_elision_failures
2012                        .push((missing_lifetime, Either::Left(lifetime.id)));
2013                    return;
2014                }
2015                LifetimeRibKind::Item => break,
2016                LifetimeRibKind::Generics { .. }
2017                | LifetimeRibKind::ConstParamTy
2018                | LifetimeRibKind::ImplTrait => {}
2019                LifetimeRibKind::ConcreteAnonConst(_) => {
2020                    // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
2021                    span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
2022                }
2023            }
2024        }
2025        let guar = self.report_missing_lifetime_specifiers([&missing_lifetime], None);
2026        self.record_lifetime_err(lifetime.id, guar);
2027    }
2028
2029    fn point_at_impl_lifetimes(&mut self, err: &mut Diag<'_>, i: usize, lifetime: Span) {
2030        let Some((rib, span)) =
2031            self.lifetime_ribs[..i].iter().rev().find_map(|rib| match rib.kind {
2032                LifetimeRibKind::Generics { span, kind: LifetimeBinderKind::ImplBlock, .. } => {
2033                    Some((rib, span))
2034                }
2035                _ => None,
2036            })
2037        else {
2038            return;
2039        };
2040        if !rib.bindings.is_empty() {
2041            err.span_label(
2042                span,
2043                ::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!(
2044                    "there {} named lifetime{} specified on the impl block you could use",
2045                    if rib.bindings.len() == 1 { "is a" } else { "are" },
2046                    pluralize!(rib.bindings.len()),
2047                ),
2048            );
2049            if rib.bindings.len() == 1 {
2050                err.span_suggestion_verbose(
2051                    lifetime.shrink_to_hi(),
2052                    "consider using the lifetime from the impl block",
2053                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ",
                rib.bindings.keys().next().unwrap()))
    })format!("{} ", rib.bindings.keys().next().unwrap()),
2054                    Applicability::MaybeIncorrect,
2055                );
2056            }
2057        } else {
2058            struct AnonRefFinder;
2059            impl<'ast> Visitor<'ast> for AnonRefFinder {
2060                type Result = ControlFlow<Span>;
2061
2062                fn visit_ty(&mut self, ty: &'ast ast::Ty) -> Self::Result {
2063                    if let ast::TyKind::Ref(None, mut_ty) = &ty.kind {
2064                        return ControlFlow::Break(mut_ty.ty.span.shrink_to_lo());
2065                    }
2066                    visit::walk_ty(self, ty)
2067                }
2068
2069                fn visit_lifetime(
2070                    &mut self,
2071                    lt: &'ast ast::Lifetime,
2072                    _cx: visit::LifetimeCtxt,
2073                ) -> Self::Result {
2074                    if lt.ident.name == kw::UnderscoreLifetime {
2075                        return ControlFlow::Break(lt.ident.span);
2076                    }
2077                    visit::walk_lifetime(self, lt)
2078                }
2079            }
2080
2081            if let Some(ty) = &self.diag_metadata.current_self_type
2082                && let ControlFlow::Break(sp) = AnonRefFinder.visit_ty(ty)
2083            {
2084                err.multipart_suggestion(
2085                    "add a lifetime to the impl block and use it in the self type and associated \
2086                     type",
2087                    ::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![
2088                        (span, "<'a>".to_string()),
2089                        (sp, "'a ".to_string()),
2090                        (lifetime.shrink_to_hi(), "'a ".to_string()),
2091                    ],
2092                    Applicability::MaybeIncorrect,
2093                );
2094            } else if let Some(item) = &self.diag_metadata.current_item
2095                && let ItemKind::Impl(impl_) = &item.kind
2096                && let Some(of_trait) = &impl_.of_trait
2097                && let ControlFlow::Break(sp) = AnonRefFinder.visit_trait_ref(&of_trait.trait_ref)
2098            {
2099                err.multipart_suggestion(
2100                    "add a lifetime to the impl block and use it in the trait and associated type",
2101                    ::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![
2102                        (span, "<'a>".to_string()),
2103                        (sp, "'a".to_string()),
2104                        (lifetime.shrink_to_hi(), "'a ".to_string()),
2105                    ],
2106                    Applicability::MaybeIncorrect,
2107                );
2108            } else {
2109                err.span_label(
2110                    span,
2111                    "you could add a lifetime on the impl block, if the trait or the self type \
2112                     could have one",
2113                );
2114            }
2115        }
2116    }
2117
2118    #[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(2118u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("anchor_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("anchor_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&anchor_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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))]
2119    fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
2120        let id = self.r.next_node_id();
2121        let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
2122
2123        self.record_lifetime_use(
2124            anchor_id,
2125            LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
2126            LifetimeElisionCandidate::Ignore,
2127        );
2128        self.resolve_anonymous_lifetime(&lt, anchor_id, true);
2129    }
2130
2131    #[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(2131u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ident")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ident");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("binder")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("binder");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("kind")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("kind");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&binder)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: 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:2139",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2139u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ident.span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ident.span");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident.span)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let param = self.r.next_node_id();
            let res = LifetimeRes::Fresh { param, kind };
            self.record_lifetime_def(param, res);
            self.r.current_owner.extra_lifetime_params_map.entry(binder).or_insert_with(Vec::new).push((ident,
                    param, kind));
            res
        }
    }
}#[instrument(level = "debug", skip(self))]
2132    fn create_fresh_lifetime(
2133        &mut self,
2134        ident: Ident,
2135        binder: NodeId,
2136        kind: MissingLifetimeKind,
2137    ) -> LifetimeRes {
2138        debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
2139        debug!(?ident.span);
2140
2141        // Leave the responsibility to create the `LocalDefId` to lowering.
2142        let param = self.r.next_node_id();
2143        let res = LifetimeRes::Fresh { param, kind };
2144        self.record_lifetime_def(param, res);
2145
2146        // Record the created lifetime parameter so lowering can pick it up and add it to HIR.
2147        self.r
2148            .current_owner
2149            .extra_lifetime_params_map
2150            .entry(binder)
2151            .or_insert_with(Vec::new)
2152            .push((ident, param, kind));
2153        res
2154    }
2155
2156    #[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(2156u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("partial_res")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("partial_res");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path_span");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&partial_res)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path_span)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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::Elided {
                            error_in_path: true, .. } => {
                            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, error_in_path: false } => {
                            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))]
2157    fn resolve_elided_lifetimes_in_path(
2158        &mut self,
2159        partial_res: PartialRes,
2160        path: &[Segment],
2161        source: PathSource<'_, 'ast, 'ra>,
2162        path_span: Span,
2163    ) {
2164        let proj_start = path.len() - partial_res.unresolved_segments();
2165        for (i, segment) in path.iter().enumerate() {
2166            if segment.has_lifetime_args {
2167                continue;
2168            }
2169            let Some(segment_id) = segment.id else {
2170                continue;
2171            };
2172
2173            // Figure out if this is a type/trait segment,
2174            // which may need lifetime elision performed.
2175            let type_def_id = match partial_res.base_res() {
2176                Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2177                    self.r.tcx.parent(def_id)
2178                }
2179                Res::Def(DefKind::Variant, def_id)
2180                    if i + 2 == proj_start && segment.has_generic_args =>
2181                {
2182                    self.r.tcx.parent(def_id)
2183                }
2184                Res::Def(DefKind::Variant, def_id)
2185                    if i + 1 == proj_start
2186                        && !i.checked_sub(1).is_some_and(|i| path[i].has_generic_args) =>
2187                {
2188                    self.r.tcx.parent(def_id)
2189                }
2190                Res::Def(DefKind::Struct, def_id)
2191                | Res::Def(DefKind::Union, def_id)
2192                | Res::Def(DefKind::Enum, def_id)
2193                | Res::Def(DefKind::TyAlias, def_id)
2194                | Res::Def(DefKind::Trait, def_id)
2195                    if i + 1 == proj_start =>
2196                {
2197                    def_id
2198                }
2199                _ => continue,
2200            };
2201
2202            let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2203            if expected_lifetimes == 0 {
2204                continue;
2205            }
2206
2207            let node_ids = self.r.next_node_ids(expected_lifetimes);
2208            self.record_lifetime_use(
2209                segment_id,
2210                LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2211                LifetimeElisionCandidate::Ignore,
2212            );
2213
2214            let inferred = match source {
2215                PathSource::Trait(..)
2216                | PathSource::TraitItem(..)
2217                | PathSource::Type
2218                | PathSource::PreciseCapturingArg(..)
2219                | PathSource::ReturnTypeNotation
2220                | PathSource::Macro
2221                | PathSource::Module => false,
2222                PathSource::Expr(..)
2223                | PathSource::Pat
2224                | PathSource::Struct(_)
2225                | PathSource::TupleStruct(..)
2226                | PathSource::DefineOpaques
2227                | PathSource::Delegation
2228                | PathSource::ExternItemImpl => true,
2229            };
2230            if inferred {
2231                // Do not create a parameter for patterns and expressions: type checking can infer
2232                // the appropriate lifetime for us.
2233                for id in node_ids {
2234                    self.record_lifetime_use(
2235                        id,
2236                        LifetimeRes::Infer,
2237                        LifetimeElisionCandidate::Ignore,
2238                    );
2239                }
2240                continue;
2241            }
2242
2243            let elided_lifetime_span = if segment.has_generic_args {
2244                // If there are brackets, but not generic arguments, then use the opening bracket
2245                segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2246            } else {
2247                // If there are no brackets, use the identifier span.
2248                // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
2249                // originating from macros, since the segment's span might be from a macro arg.
2250                segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2251            };
2252            let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2253
2254            let kind = if segment.has_generic_args {
2255                MissingLifetimeKind::Comma
2256            } else {
2257                MissingLifetimeKind::Brackets
2258            };
2259            let missing_lifetime = MissingLifetime {
2260                id: node_ids.start,
2261                id_for_lint: segment_id,
2262                span: elided_lifetime_span,
2263                kind,
2264                count: expected_lifetimes,
2265            };
2266            let mut should_lint = true;
2267            for rib in self.lifetime_ribs.iter().rev() {
2268                match rib.kind {
2269                    // In create-parameter mode we error here because we don't want to support
2270                    // deprecated impl elision in new features like impl elision and `async fn`,
2271                    // both of which work using the `CreateParameter` mode:
2272                    //
2273                    //     impl Foo for std::cell::Ref<u32> // note lack of '_
2274                    //     async fn foo(_: std::cell::Ref<u32>) { ... }
2275                    LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2276                    | LifetimeRibKind::Elided { error_in_path: true, .. } => {
2277                        let sess = self.r.tcx.sess;
2278                        let subdiag = elided_lifetime_in_path_suggestion(
2279                            sess.source_map(),
2280                            expected_lifetimes,
2281                            path_span,
2282                            !segment.has_generic_args,
2283                            elided_lifetime_span,
2284                        );
2285                        let guar = self.r.dcx().emit_err(
2286                            crate::diagnostics::ImplicitElidedLifetimeNotAllowedHere {
2287                                span: path_span,
2288                                subdiag,
2289                            },
2290                        );
2291                        should_lint = false;
2292
2293                        for id in node_ids {
2294                            self.record_lifetime_err(id, guar);
2295                        }
2296                        break;
2297                    }
2298                    // Do not create a parameter for patterns and expressions.
2299                    LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2300                        // Group all suggestions into the first record.
2301                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2302                        for id in node_ids {
2303                            let res = self.create_fresh_lifetime(ident, binder, kind);
2304                            self.record_lifetime_use(
2305                                id,
2306                                res,
2307                                replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2308                            );
2309                        }
2310                        break;
2311                    }
2312                    LifetimeRibKind::Elided { res, error_in_path: false } => {
2313                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2314                        for id in node_ids {
2315                            self.record_lifetime_use(
2316                                id,
2317                                res,
2318                                replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2319                            );
2320                        }
2321                        break;
2322                    }
2323                    LifetimeRibKind::ElisionFailure => {
2324                        self.diag_metadata
2325                            .current_elision_failures
2326                            .push((missing_lifetime, Either::Right(node_ids)));
2327                        break;
2328                    }
2329                    // `LifetimeRes::Error`, which would usually be used in the case of
2330                    // `ReportError`, is unsuitable here, as we don't emit an error yet. Instead,
2331                    // we simply resolve to an implicit lifetime, which will be checked later, at
2332                    // which point a suitable error will be emitted.
2333                    LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2334                        let guar =
2335                            self.report_missing_lifetime_specifiers([&missing_lifetime], None);
2336                        for id in node_ids {
2337                            self.record_lifetime_err(id, guar);
2338                        }
2339                        break;
2340                    }
2341                    LifetimeRibKind::Generics { .. }
2342                    | LifetimeRibKind::ConstParamTy
2343                    | LifetimeRibKind::ImplTrait => {}
2344                    LifetimeRibKind::ConcreteAnonConst(_) => {
2345                        // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
2346                        span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2347                    }
2348                }
2349            }
2350
2351            if should_lint {
2352                let include_angle_bracket = !segment.has_generic_args;
2353                self.r.lint_buffer.dyn_buffer_lint_any(
2354                    lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2355                    segment_id,
2356                    elided_lifetime_span,
2357                    move |dcx, level, sess| {
2358                        let source_map = sess
2359                            .downcast_ref::<rustc_session::Session>()
2360                            .expect("expected a `Session`")
2361                            .source_map();
2362                        crate::diagnostics::ElidedLifetimesInPaths {
2363                            subdiag: elided_lifetime_in_path_suggestion(
2364                                source_map,
2365                                expected_lifetimes,
2366                                path_span,
2367                                include_angle_bracket,
2368                                elided_lifetime_span,
2369                            ),
2370                        }
2371                        .into_diag(dcx, level)
2372                    },
2373                );
2374            }
2375        }
2376    }
2377
2378    /// Register a use of an already defined lifetime.
2379    #[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(2379u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("res")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("res");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("candidate")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("candidate");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidate)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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))]
2380    fn record_lifetime_use(
2381        &mut self,
2382        id: NodeId,
2383        res: LifetimeRes,
2384        candidate: LifetimeElisionCandidate,
2385    ) {
2386        self.record_lifetime_def(id, res);
2387
2388        match res {
2389            LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2390                if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2391                    candidates.push((res, candidate));
2392                }
2393            }
2394            LifetimeRes::Infer | LifetimeRes::Error(..) | LifetimeRes::ElidedAnchor { .. } => {}
2395        }
2396    }
2397
2398    /// Can be used for both definitions and uses of lifetimes, as an error
2399    /// has already been reported.
2400    #[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(2400u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("guar")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("guar");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&guar)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        { self.record_lifetime_def(id, LifetimeRes::Error(guar)); }
    }
}#[instrument(level = "debug", skip(self))]
2401    fn record_lifetime_err(&mut self, id: NodeId, guar: ErrorGuaranteed) {
2402        self.record_lifetime_def(id, LifetimeRes::Error(guar));
2403    }
2404
2405    /// Define a new lifetime (e.g. in generics)
2406    #[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(2406u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("res")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("res");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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))]
2407    fn record_lifetime_def(&mut self, id: NodeId, res: LifetimeRes) {
2408        if let Some(prev_res) = self.r.current_owner.lifetimes_res_map.insert(id, res) {
2409            panic!(
2410                "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2411            )
2412        }
2413    }
2414
2415    /// Perform resolution of a function signature, accounting for lifetime elision.
2416    #[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(2416u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("has_self")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("has_self");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("output_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("output_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("report_elided_lifetimes_in_path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("report_elided_lifetimes_in_path");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&has_self as
                                                            &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&output_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&report_elided_lifetimes_in_path
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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:2432",
                                                "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                ::tracing_core::__macro_support::Option::Some(2432u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("elision_lifetime")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("elision_lifetime");
                                                                    NAME.as_str()
                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&elision_lifetime)
                                                                    as &dyn ::tracing::field::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))]
2417    fn resolve_fn_signature(
2418        &mut self,
2419        fn_id: NodeId,
2420        has_self: bool,
2421        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2422        output_ty: &'ast FnRetTy,
2423        report_elided_lifetimes_in_path: bool,
2424    ) {
2425        let rib = LifetimeRibKind::AnonymousCreateParameter {
2426            binder: fn_id,
2427            report_in_path: report_elided_lifetimes_in_path,
2428        };
2429        self.with_lifetime_rib(rib, |this| {
2430            // Add each argument to the rib.
2431            let elision_lifetime = this.resolve_fn_params(has_self, inputs);
2432            debug!(?elision_lifetime);
2433
2434            let outer_failures = take(&mut this.diag_metadata.current_elision_failures);
2435            let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2436                if fn_id == this.r.current_owner.id {
2437                    this.r.current_owner.lifetime_elision_allowed = true;
2438                }
2439                LifetimeRibKind::elided(*res)
2440            } else {
2441                LifetimeRibKind::ElisionFailure
2442            };
2443            this.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2444            let elision_failures =
2445                replace(&mut this.diag_metadata.current_elision_failures, outer_failures);
2446            if !elision_failures.is_empty() {
2447                let Err(failure_info) = elision_lifetime else { bug!() };
2448                let guar = this.report_missing_lifetime_specifiers(
2449                    elision_failures.iter().map(|(missing_lifetime, ..)| missing_lifetime),
2450                    Some(failure_info),
2451                );
2452                let mut record_res = |lifetime| this.record_lifetime_err(lifetime, guar);
2453                for (_, nodes) in elision_failures {
2454                    match nodes {
2455                        Either::Left(node_id) => record_res(node_id),
2456                        Either::Right(node_ids) => {
2457                            for lifetime in node_ids {
2458                                record_res(lifetime)
2459                            }
2460                        }
2461                    }
2462                }
2463            }
2464        });
2465    }
2466
2467    /// Resolve inside function parameters and parameter types.
2468    /// Returns the lifetime for elision in fn return type,
2469    /// or diagnostic information in case of elision failure.
2470    fn resolve_fn_params(
2471        &mut self,
2472        has_self: bool,
2473        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2474    ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2475        enum Elision {
2476            /// We have not found any candidate.
2477            None,
2478            /// We have a candidate bound to `self`.
2479            Self_(LifetimeRes),
2480            /// We have a candidate bound to a parameter.
2481            Param(LifetimeRes),
2482            /// We failed elision.
2483            Err,
2484        }
2485
2486        // Save elision state to reinstate it later.
2487        let outer_candidates = self.lifetime_elision_candidates.take();
2488
2489        // Result of elision.
2490        let mut elision_lifetime = Elision::None;
2491        // Information for diagnostics.
2492        let mut parameter_info = Vec::new();
2493        let mut all_candidates = Vec::new();
2494
2495        // Resolve and apply bindings first so diagnostics can see if they're used in types.
2496        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())];
2497        for (pat, _) in inputs.clone() {
2498            {
    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:2498",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2498u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolving bindings in pat = {0:?}",
                                                    pat) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolving bindings in pat = {pat:?}");
2499            self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
2500                if let Some(pat) = pat {
2501                    this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2502                }
2503            });
2504        }
2505        self.apply_pattern_bindings(bindings);
2506
2507        for (index, (pat, ty)) in inputs.enumerate() {
2508            {
    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:2508",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2508u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolving type for pat = {0:?}, ty = {1:?}",
                                                    pat, ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolving type for pat = {pat:?}, ty = {ty:?}");
2509            // Record elision candidates only for this parameter.
2510            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);
2511            self.lifetime_elision_candidates = Some(Default::default());
2512            self.visit_ty(ty);
2513            let local_candidates = self.lifetime_elision_candidates.take();
2514
2515            if let Some(candidates) = local_candidates {
2516                let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2517                let lifetime_count = distinct.len();
2518                if lifetime_count != 0 {
2519                    parameter_info.push(ElisionFnParameter {
2520                        index,
2521                        ident: if let Some(pat) = pat
2522                            && let PatKind::Ident(_, ident, _) = pat.kind
2523                        {
2524                            Some(ident)
2525                        } else {
2526                            None
2527                        },
2528                        lifetime_count,
2529                        span: ty.span,
2530                    });
2531                    all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2532                        match candidate {
2533                            LifetimeElisionCandidate::Ignore => None,
2534                            LifetimeElisionCandidate::Missing(missing) => Some(missing),
2535                        }
2536                    }));
2537                }
2538                if !distinct.is_empty() {
2539                    match elision_lifetime {
2540                        // We are the first parameter to bind lifetimes.
2541                        Elision::None => {
2542                            if let Some(res) = distinct.get_only() {
2543                                // We have a single lifetime => success.
2544                                elision_lifetime = Elision::Param(*res)
2545                            } else {
2546                                // We have multiple lifetimes => error.
2547                                elision_lifetime = Elision::Err;
2548                            }
2549                        }
2550                        // We have 2 parameters that bind lifetimes => error.
2551                        Elision::Param(_) => elision_lifetime = Elision::Err,
2552                        // `self` elision takes precedence over everything else.
2553                        Elision::Self_(_) | Elision::Err => {}
2554                    }
2555                }
2556            }
2557
2558            // Handle `self` specially.
2559            if index == 0 && has_self {
2560                let self_lifetime = self.find_lifetime_for_self(ty);
2561                elision_lifetime = match self_lifetime {
2562                    // We found `self` elision.
2563                    Set1::One(lifetime) => Elision::Self_(lifetime),
2564                    // `self` itself had ambiguous lifetimes, e.g.
2565                    // &Box<&Self>. In this case we won't consider
2566                    // taking an alternative parameter lifetime; just avoid elision
2567                    // entirely.
2568                    Set1::Many => Elision::Err,
2569                    // We do not have `self` elision: disregard the `Elision::Param` that we may
2570                    // have found.
2571                    Set1::Empty => Elision::None,
2572                }
2573            }
2574            {
    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:2574",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2574u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("(resolving function / closure) recorded parameter")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("(resolving function / closure) recorded parameter");
2575        }
2576
2577        // Reinstate elision state.
2578        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);
2579        self.lifetime_elision_candidates = outer_candidates;
2580
2581        if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2582            return Ok(res);
2583        }
2584
2585        // We do not have a candidate.
2586        Err((all_candidates, parameter_info))
2587    }
2588
2589    /// List all the lifetimes that appear in the provided type.
2590    fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2591        /// Visits a type to find all the &references, and determines the
2592        /// set of lifetimes for all of those references where the referent
2593        /// contains Self.
2594        struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2595            r: &'a Resolver<'ra, 'tcx>,
2596            impl_self: Option<Res>,
2597            lifetime: Set1<LifetimeRes>,
2598        }
2599
2600        impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2601            fn visit_ty(&mut self, ty: &'ra Ty) {
2602                {
    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:2602",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2602u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("FindReferenceVisitor considering ty={0:?}",
                                                    ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("FindReferenceVisitor considering ty={:?}", ty);
2603                if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2604                    // See if anything inside the &thing contains Self
2605                    let mut visitor =
2606                        SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2607                    visitor.visit_ty(ty);
2608                    {
    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:2608",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2608u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("FindReferenceVisitor: SelfVisitor self_found={0:?}",
                                                    visitor.self_found) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("FindReferenceVisitor: SelfVisitor self_found={:?}", visitor.self_found);
2609                    if visitor.self_found {
2610                        let lt_id = if let Some(lt) = lt {
2611                            lt.id
2612                        } else {
2613                            let res = self.r.current_owner.lifetimes_res_map[&ty.id];
2614                            let LifetimeRes::ElidedAnchor { start, .. } = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2615                            start
2616                        };
2617                        let lt_res = self.r.current_owner.lifetimes_res_map[&lt_id];
2618                        {
    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:2618",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2618u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("FindReferenceVisitor inserting res={0:?}",
                                                    lt_res) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("FindReferenceVisitor inserting res={:?}", lt_res);
2619                        self.lifetime.insert(lt_res);
2620                    }
2621                }
2622                visit::walk_ty(self, ty)
2623            }
2624
2625            // A type may have an expression as a const generic argument.
2626            // We do not want to recurse into those.
2627            fn visit_expr(&mut self, _: &'ra Expr) {}
2628        }
2629
2630        /// Visitor which checks the referent of a &Thing to see if the
2631        /// Thing contains Self
2632        struct SelfVisitor<'a, 'ra, 'tcx> {
2633            r: &'a Resolver<'ra, 'tcx>,
2634            impl_self: Option<Res>,
2635            self_found: bool,
2636        }
2637
2638        impl SelfVisitor<'_, '_, '_> {
2639            // Look for `self: &'a Self` - also desugared from `&'a self`
2640            fn is_self_ty(&self, ty: &Ty) -> bool {
2641                match ty.kind {
2642                    TyKind::ImplicitSelf => true,
2643                    TyKind::Path(None, _) => {
2644                        let path_res = self.r.partial_res_map[&ty.id].full_res();
2645                        if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2646                            return true;
2647                        }
2648                        self.impl_self.is_some() && path_res == self.impl_self
2649                    }
2650                    _ => false,
2651                }
2652            }
2653        }
2654
2655        impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2656            fn visit_ty(&mut self, ty: &'ra Ty) {
2657                {
    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:2657",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2657u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("SelfVisitor considering ty={0:?}",
                                                    ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("SelfVisitor considering ty={:?}", ty);
2658                if self.is_self_ty(ty) {
2659                    {
    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:2659",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2659u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("SelfVisitor found Self")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("SelfVisitor found Self");
2660                    self.self_found = true;
2661                }
2662                visit::walk_ty(self, ty)
2663            }
2664
2665            // A type may have an expression as a const generic argument.
2666            // We do not want to recurse into those.
2667            fn visit_expr(&mut self, _: &'ra Expr) {}
2668        }
2669
2670        let impl_self = self
2671            .diag_metadata
2672            .current_self_type
2673            .and_then(|ty| {
2674                if let TyKind::Path(None, _) = ty.kind {
2675                    self.r.partial_res_map.get(&ty.id)
2676                } else {
2677                    None
2678                }
2679            })
2680            .and_then(|res| res.full_res())
2681            .filter(|res| {
2682                // Permit the types that unambiguously always
2683                // result in the same type constructor being used
2684                // (it can't differ between `Self` and `self`).
2685                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _) |
        Res::PrimTy(_) => true,
    _ => false,
}matches!(
2686                    res,
2687                    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2688                )
2689            });
2690        let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2691        visitor.visit_ty(ty);
2692        {
    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:2692",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2692u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("FindReferenceVisitor found={0:?}",
                                                    visitor.lifetime) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("FindReferenceVisitor found={:?}", visitor.lifetime);
2693        visitor.lifetime
2694    }
2695
2696    /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
2697    /// label and reports an error if the label is not found or is unreachable.
2698    fn resolve_label(&self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2699        let mut suggestion = None;
2700
2701        for i in (0..self.label_ribs.len()).rev() {
2702            let rib = &self.label_ribs[i];
2703
2704            if let RibKind::MacroDefinition(def) = rib.kind
2705                // If an invocation of this macro created `ident`, give up on `ident`
2706                // and switch to `ident`'s source from the macro definition.
2707                && def == self.r.macro_def(label.span.ctxt())
2708            {
2709                label.span.remove_mark();
2710            }
2711
2712            let ident = label.normalize_to_macro_rules();
2713            if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2714                let definition_span = ident.span;
2715                return if self.is_label_valid_from_rib(i) {
2716                    Ok((*id, definition_span))
2717                } else {
2718                    Err(ResolutionError::UnreachableLabel {
2719                        name: label.name,
2720                        definition_span,
2721                        suggestion,
2722                    })
2723                };
2724            }
2725
2726            // Diagnostics: Check if this rib contains a label with a similar name, keep track of
2727            // the first such label that is encountered.
2728            suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2729        }
2730
2731        Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2732    }
2733
2734    /// Determine whether or not a label from the `rib_index`th label rib is reachable.
2735    fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2736        let ribs = &self.label_ribs[rib_index + 1..];
2737        ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2738    }
2739
2740    fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2741        {
    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:2741",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2741u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_adt")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolve_adt");
2742        let kind = self.r.tcx.def_kind(self.r.current_owner.def_id);
2743        self.with_current_self_item(item, |this| {
2744            this.with_generic_param_rib(
2745                &generics.params,
2746                RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2747                item.id,
2748                LifetimeBinderKind::Item,
2749                generics.span,
2750                |this| {
2751                    let item_def_id = this.r.current_owner.def_id.to_def_id();
2752                    this.with_self_rib(
2753                        Res::SelfTyAlias { alias_to: item_def_id, is_trait_impl: false },
2754                        |this| {
2755                            visit::walk_item(this, item);
2756                        },
2757                    );
2758                },
2759            );
2760        });
2761    }
2762
2763    fn future_proof_import(&mut self, use_tree: &UseTree) {
2764        if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2765            let ident = segment.ident;
2766            if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2767                return;
2768            }
2769
2770            let nss = match use_tree.kind {
2771                UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2772                _ => &[TypeNS],
2773            };
2774            let report_error = |this: &Self, ns| {
2775                if this.should_report_errs() {
2776                    let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2777                    this.r.dcx().emit_err(crate::diagnostics::ImportsCannotReferTo {
2778                        span: ident.span,
2779                        what,
2780                    });
2781                }
2782            };
2783
2784            for &ns in nss {
2785                match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2786                    Some(LateDecl::RibDef(..)) => {
2787                        report_error(self, ns);
2788                    }
2789                    Some(LateDecl::Decl(binding)) => {
2790                        if let Some(LateDecl::RibDef(..)) =
2791                            self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2792                        {
2793                            report_error(self, ns);
2794                        }
2795                    }
2796                    None => {}
2797                }
2798            }
2799        } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2800            for (use_tree, _) in items {
2801                self.future_proof_import(use_tree);
2802            }
2803        }
2804    }
2805
2806    fn resolve_item(&mut self, item: &'ast Item) {
2807        let mod_inner_docs =
2808            #[allow(non_exhaustive_omitted_patterns)] match item.kind {
    ItemKind::Mod(..) => true,
    _ => false,
}matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2809        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(..)) {
2810            self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2811        }
2812
2813        {
    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:2813",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2813u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("(resolving item) resolving {0:?} ({1:?})",
                                                    item.kind.ident(), item.kind) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("(resolving item) resolving {:?} ({:?})", item.kind.ident(), item.kind);
2814
2815        let def_kind = self.r.tcx.def_kind(self.r.current_owner.def_id);
2816        match &item.kind {
2817            ItemKind::TyAlias(TyAlias { generics, .. }) => {
2818                self.with_generic_param_rib(
2819                    &generics.params,
2820                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2821                    item.id,
2822                    LifetimeBinderKind::Item,
2823                    generics.span,
2824                    |this| visit::walk_item(this, item),
2825                );
2826            }
2827
2828            ItemKind::Fn(Fn { generics, define_opaque, .. }) => {
2829                self.with_generic_param_rib(
2830                    &generics.params,
2831                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2832                    item.id,
2833                    LifetimeBinderKind::Function,
2834                    generics.span,
2835                    |this| visit::walk_item(this, item),
2836                );
2837                self.resolve_define_opaques(define_opaque);
2838            }
2839
2840            ItemKind::Enum(_, generics, _)
2841            | ItemKind::Struct(_, generics, _)
2842            | ItemKind::Union(_, generics, _) => {
2843                self.resolve_adt(item, generics);
2844            }
2845
2846            ItemKind::Impl(Impl { generics, of_trait, self_ty, items: impl_items, .. }) => {
2847                self.diag_metadata.current_impl_items = Some(impl_items);
2848                self.resolve_implementation(
2849                    &item.attrs,
2850                    generics,
2851                    of_trait.as_deref(),
2852                    self_ty,
2853                    item.id,
2854                    impl_items,
2855                );
2856                self.diag_metadata.current_impl_items = None;
2857            }
2858
2859            ItemKind::Trait(Trait { generics, bounds, items, impl_restriction, .. }) => {
2860                // resolve paths for `impl` restrictions
2861                self.resolve_restriction_path(&impl_restriction.kind);
2862
2863                // Create a new rib for the trait-wide type parameters.
2864                self.with_generic_param_rib(
2865                    &generics.params,
2866                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2867                    item.id,
2868                    LifetimeBinderKind::Item,
2869                    generics.span,
2870                    |this| {
2871                        let local_def_id = this.r.current_owner.def_id.to_def_id();
2872                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2873                            this.visit_generics(generics);
2874                            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);
2875                            this.resolve_trait_items(items);
2876                        });
2877                    },
2878                );
2879            }
2880
2881            ItemKind::TraitAlias(TraitAlias { generics, bounds, .. }) => {
2882                // Create a new rib for the trait-wide type parameters.
2883                self.with_generic_param_rib(
2884                    &generics.params,
2885                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2886                    item.id,
2887                    LifetimeBinderKind::Item,
2888                    generics.span,
2889                    |this| {
2890                        let local_def_id = this.r.current_owner.def_id.to_def_id();
2891                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2892                            this.visit_generics(generics);
2893                            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);
2894                        });
2895                    },
2896                );
2897            }
2898
2899            ItemKind::Mod(..) => {
2900                let module = self.r.expect_module(self.r.current_owner.def_id.to_def_id());
2901                let orig_module = replace(&mut self.parent_scope.module, module);
2902                self.with_rib(ValueNS, RibKind::Module(module.expect_local()), |this| {
2903                    this.with_rib(TypeNS, RibKind::Module(module.expect_local()), |this| {
2904                        if mod_inner_docs {
2905                            this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2906                        }
2907                        let old_macro_rules = this.parent_scope.macro_rules;
2908                        visit::walk_item(this, item);
2909                        // Maintain macro_rules scopes in the same way as during early resolution
2910                        // for diagnostics and doc links.
2911                        if item.attrs.iter().all(|attr| {
2912                            !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2913                        }) {
2914                            this.parent_scope.macro_rules = old_macro_rules;
2915                        }
2916                    })
2917                });
2918                self.parent_scope.module = orig_module;
2919            }
2920
2921            ItemKind::Static(ast::StaticItem {
2922                ident, ty, expr, define_opaque, eii_impl, ..
2923            }) => {
2924                self.with_static_rib(def_kind, |this| {
2925                    this.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Static), |this| {
2926                        this.visit_ty(ty);
2927                    });
2928                    if let Some(expr) = expr {
2929                        // We already forbid generic params because of the above item rib,
2930                        // so it doesn't matter whether this is a trivial constant.
2931                        this.resolve_static_body(expr, Some((*ident, ConstantItemKind::Static)));
2932                    }
2933                });
2934                self.resolve_define_opaques(define_opaque);
2935                self.resolve_eii(eii_impl.as_deref());
2936            }
2937
2938            ItemKind::Const(ast::ConstItem {
2939                ident,
2940                generics,
2941                ty,
2942                body,
2943                kind,
2944                define_opaque,
2945                defaultness: _,
2946            }) => {
2947                self.with_generic_param_rib(
2948                    &generics.params,
2949                    RibKind::Item(
2950                        if self.r.features.generic_const_items() {
2951                            HasGenericParams::Yes(generics.span)
2952                        } else {
2953                            HasGenericParams::No
2954                        },
2955                        def_kind,
2956                    ),
2957                    item.id,
2958                    LifetimeBinderKind::ConstItem,
2959                    generics.span,
2960                    |this| {
2961                        this.visit_generics(generics);
2962
2963                        this.with_lifetime_rib(
2964                            LifetimeRibKind::elided(LifetimeRes::Static),
2965                            |this: &mut LateResolutionVisitor<'a, 'ast, 'ra, 'tcx>| {
2966                                if *kind == ast::ConstItemKind::TypeConst
2967                                    && !this.r.features.generic_const_parameter_types()
2968                                {
2969                                    this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
2970                                        this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
2971                                            this.with_lifetime_rib(
2972                                                LifetimeRibKind::ConstParamTy,
2973                                                |this| this.visit_ty(ty),
2974                                            )
2975                                        })
2976                                    });
2977                                } else {
2978                                    this.visit_ty(ty);
2979                                }
2980                            },
2981                        );
2982
2983                        this.resolve_const_item_rhs(body, Some((*ident, ConstantItemKind::Const)));
2984                    },
2985                );
2986                self.resolve_define_opaques(define_opaque);
2987            }
2988            ItemKind::ConstBlock(ConstBlockItem { id: _, span: _, block }) => self
2989                .with_generic_param_rib(
2990                    &[],
2991                    RibKind::Item(HasGenericParams::No, def_kind),
2992                    item.id,
2993                    LifetimeBinderKind::ConstItem,
2994                    DUMMY_SP,
2995                    |this| {
2996                        this.with_lifetime_rib(
2997                            LifetimeRibKind::elided(LifetimeRes::Infer),
2998                            |this| {
2999                                this.with_constant_rib(
3000                                    IsRepeatExpr::No,
3001                                    ConstantHasGenerics::Yes,
3002                                    Some((ConstBlockItem::IDENT, ConstantItemKind::Const)),
3003                                    |this| this.resolve_labeled_block(None, block.id, block),
3004                                )
3005                            },
3006                        );
3007                    },
3008                ),
3009
3010            ItemKind::Use(use_tree) => {
3011                let maybe_exported = match use_tree.kind {
3012                    UseTreeKind::Simple(_) | UseTreeKind::Glob(_) => MaybeExported::Ok(item.id),
3013                    UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
3014                };
3015                self.resolve_doc_links(&item.attrs, maybe_exported);
3016
3017                self.future_proof_import(use_tree);
3018            }
3019
3020            ItemKind::MacroDef(_, macro_def) => {
3021                // Maintain macro_rules scopes in the same way as during early resolution
3022                // for diagnostics and doc links.
3023                if macro_def.macro_rules {
3024                    let def_id = self.r.current_owner.def_id;
3025                    self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
3026                }
3027
3028                if let Some(EiiDecl { foreign_item: extern_item_path, impl_unsafe: _ }) =
3029                    &macro_def.eii_declaration
3030                {
3031                    self.smart_resolve_path(
3032                        item.id,
3033                        &None,
3034                        extern_item_path,
3035                        PathSource::ExternItemImpl,
3036                    );
3037                }
3038            }
3039
3040            ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
3041                visit::walk_item(self, item);
3042            }
3043
3044            ItemKind::Delegation(delegation) => {
3045                let span = delegation.path.segments.last().unwrap().ident.span;
3046                self.with_generic_param_rib(
3047                    &[],
3048                    RibKind::Item(HasGenericParams::Yes(span), def_kind),
3049                    item.id,
3050                    LifetimeBinderKind::Function,
3051                    span,
3052                    |this| this.resolve_delegation(delegation, item.id, false),
3053                );
3054            }
3055
3056            ItemKind::ExternCrate(..) => {}
3057
3058            ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
3059                {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3060            }
3061        }
3062    }
3063
3064    fn with_generic_param_rib<F>(
3065        &mut self,
3066        params: &[GenericParam],
3067        kind: RibKind<'ra>,
3068        binder: NodeId,
3069        generics_kind: LifetimeBinderKind,
3070        generics_span: Span,
3071        f: F,
3072    ) where
3073        F: FnOnce(&mut Self),
3074    {
3075        {
    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:3075",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3075u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("with_generic_param_rib")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("with_generic_param_rib");
3076        let lifetime_kind =
3077            LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind };
3078
3079        let mut function_type_rib = Rib::new(kind);
3080        let mut function_value_rib = Rib::new(kind);
3081        let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
3082
3083        // Only check for shadowed bindings if we're declaring new params.
3084        if !params.is_empty() {
3085            let mut seen_bindings = FxHashMap::default();
3086            // Store all seen lifetimes names from outer scopes.
3087            let mut seen_lifetimes = FxHashSet::default();
3088
3089            // We also can't shadow bindings from associated parent items.
3090            for ns in [ValueNS, TypeNS] {
3091                for parent_rib in self.ribs[ns].iter().rev() {
3092                    // Break at module or block level, to account for nested items which are
3093                    // allowed to shadow generic param names.
3094                    if #[allow(non_exhaustive_omitted_patterns)] match parent_rib.kind {
    RibKind::Module(..) | RibKind::Block(..) => true,
    _ => false,
}matches!(parent_rib.kind, RibKind::Module(..) | RibKind::Block(..)) {
3095                        break;
3096                    }
3097
3098                    seen_bindings
3099                        .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
3100                }
3101            }
3102
3103            // Forbid shadowing lifetime bindings
3104            for rib in self.lifetime_ribs.iter().rev() {
3105                seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
3106                if let LifetimeRibKind::Item = rib.kind {
3107                    break;
3108                }
3109            }
3110
3111            for param in params {
3112                let ident = param.ident.normalize_to_macros_2_0();
3113                {
    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:3113",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3113u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("with_generic_param_rib: {0}",
                                                    param.id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("with_generic_param_rib: {}", param.id);
3114
3115                if let GenericParamKind::Lifetime = param.kind
3116                    && let Some(&original) = seen_lifetimes.get(&ident)
3117                {
3118                    let guar = diagnostics::signal_lifetime_shadowing(
3119                        self.r.tcx.sess,
3120                        original,
3121                        param.ident,
3122                    );
3123                    // Record lifetime res, so lowering knows there is something fishy.
3124                    self.record_lifetime_err(param.id, guar);
3125                    continue;
3126                }
3127
3128                match seen_bindings.entry(ident) {
3129                    Entry::Occupied(entry) => {
3130                        let span = *entry.get();
3131                        let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
3132                        let guar = self.r.report_error(param.ident.span, err);
3133                        let rib = match param.kind {
3134                            GenericParamKind::Lifetime => {
3135                                // Record lifetime res, so lowering knows there is something fishy.
3136                                self.record_lifetime_err(param.id, guar);
3137                                continue;
3138                            }
3139                            GenericParamKind::Type { .. } => &mut function_type_rib,
3140                            GenericParamKind::Const { .. } => &mut function_value_rib,
3141                        };
3142
3143                        // Taint the resolution in case of errors to prevent follow up errors in typeck
3144                        self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
3145                        rib.bindings.insert(ident, Res::Err);
3146                        continue;
3147                    }
3148                    Entry::Vacant(entry) => {
3149                        entry.insert(param.ident.span);
3150                    }
3151                }
3152
3153                if param.ident.name == kw::UnderscoreLifetime {
3154                    // To avoid emitting two similar errors,
3155                    // we need to check if the span is a raw underscore lifetime, see issue #143152
3156                    let is_raw_underscore_lifetime = self
3157                        .r
3158                        .tcx
3159                        .sess
3160                        .psess
3161                        .raw_identifier_spans
3162                        .iter()
3163                        .any(|span| span == param.span());
3164
3165                    let guar = self
3166                        .r
3167                        .dcx()
3168                        .create_err(crate::diagnostics::UnderscoreLifetimeIsReserved {
3169                            span: param.ident.span,
3170                        })
3171                        .emit_unless_delay(is_raw_underscore_lifetime);
3172                    // Record lifetime res, so lowering knows there is something fishy.
3173                    self.record_lifetime_err(param.id, guar);
3174                    continue;
3175                }
3176
3177                if param.ident.name == kw::StaticLifetime {
3178                    let guar =
3179                        self.r.dcx().emit_err(crate::diagnostics::StaticLifetimeIsReserved {
3180                            span: param.ident.span,
3181                            lifetime: param.ident,
3182                        });
3183                    // Record lifetime res, so lowering knows there is something fishy.
3184                    self.record_lifetime_err(param.id, guar);
3185                    continue;
3186                }
3187
3188                let def_id = self.r.local_def_id(param.id);
3189
3190                // Plain insert (no renaming).
3191                let (rib, def_kind) = match param.kind {
3192                    GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
3193                    GenericParamKind::Const { .. } => {
3194                        (&mut function_value_rib, DefKind::ConstParam)
3195                    }
3196                    GenericParamKind::Lifetime => {
3197                        let res = LifetimeRes::Param { param: def_id, binder };
3198                        self.record_lifetime_def(param.id, res);
3199                        function_lifetime_rib.bindings.insert(ident, (param.id, res));
3200                        continue;
3201                    }
3202                };
3203
3204                let res = match kind {
3205                    RibKind::Item(..) | RibKind::AssocItem => {
3206                        Res::Def(def_kind, def_id.to_def_id())
3207                    }
3208                    RibKind::Normal => {
3209                        // FIXME(non_lifetime_binders): Stop special-casing
3210                        // const params to error out here.
3211                        if self.r.features.non_lifetime_binders()
3212                            && #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    GenericParamKind::Type { .. } => true,
    _ => false,
}matches!(param.kind, GenericParamKind::Type { .. })
3213                        {
3214                            Res::Def(def_kind, def_id.to_def_id())
3215                        } else {
3216                            Res::Err
3217                        }
3218                    }
3219                    _ => ::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),
3220                };
3221                self.r.record_partial_res(param.id, PartialRes::new(res));
3222                rib.bindings.insert(ident, res);
3223            }
3224        }
3225
3226        self.lifetime_ribs.push(function_lifetime_rib);
3227        self.ribs[ValueNS].push(function_value_rib);
3228        self.ribs[TypeNS].push(function_type_rib);
3229
3230        f(self);
3231
3232        self.ribs[TypeNS].pop();
3233        self.ribs[ValueNS].pop();
3234        let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
3235
3236        // Do not account for the parameters we just bound for function lifetime elision.
3237        if let Some(ref mut candidates) = self.lifetime_elision_candidates {
3238            for (_, res) in function_lifetime_rib.bindings.values() {
3239                candidates.retain(|(r, _)| r != res);
3240            }
3241        }
3242
3243        if let LifetimeBinderKind::FnPtrType
3244        | LifetimeBinderKind::WhereBound
3245        | LifetimeBinderKind::Function
3246        | LifetimeBinderKind::ImplBlock = generics_kind
3247        {
3248            self.maybe_report_lifetime_uses(generics_span, params)
3249        }
3250    }
3251
3252    fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
3253        self.label_ribs.push(Rib::new(kind));
3254        f(self);
3255        self.label_ribs.pop();
3256    }
3257
3258    fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
3259        let kind = RibKind::Item(HasGenericParams::No, def_kind);
3260        self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
3261    }
3262
3263    // HACK(min_const_generics, generic_const_exprs): We
3264    // want to keep allowing `[0; size_of::<*mut T>()]`
3265    // with a future compat lint for now. We do this by adding an
3266    // additional special case for repeat expressions.
3267    //
3268    // Note that we intentionally still forbid `[0; N + 1]` during
3269    // name resolution so that we don't extend the future
3270    // compat lint to new cases.
3271    #[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(3271u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("is_repeat")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("is_repeat");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("may_use_generics")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("may_use_generics");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("item")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("item");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&is_repeat)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&may_use_generics)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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))]
3272    fn with_constant_rib(
3273        &mut self,
3274        is_repeat: IsRepeatExpr,
3275        may_use_generics: ConstantHasGenerics,
3276        item: Option<(Ident, ConstantItemKind)>,
3277        f: impl FnOnce(&mut Self),
3278    ) {
3279        let f = |this: &mut Self| {
3280            this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3281                this.with_rib(
3282                    TypeNS,
3283                    RibKind::ConstantItem(
3284                        may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3285                        item,
3286                    ),
3287                    |this| {
3288                        this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3289                    },
3290                )
3291            })
3292        };
3293
3294        if let ConstantHasGenerics::No(cause) = may_use_generics {
3295            self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3296        } else {
3297            f(self)
3298        }
3299    }
3300
3301    fn with_current_self_type<T>(
3302        &mut self,
3303        self_type: &'ast Ty,
3304        f: impl FnOnce(&mut Self) -> T,
3305    ) -> T {
3306        // Handle nested impls (inside fn bodies)
3307        let previous_value = replace(&mut self.diag_metadata.current_self_type, Some(self_type));
3308        let result = f(self);
3309        self.diag_metadata.current_self_type = previous_value;
3310        result
3311    }
3312
3313    fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3314        let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3315        let result = f(self);
3316        self.diag_metadata.current_self_item = previous_value;
3317        result
3318    }
3319
3320    /// When evaluating a `trait` use its associated types' idents for suggestions in E0425.
3321    fn resolve_trait_items(&mut self, trait_items: &'ast [Box<AssocItem>]) {
3322        let trait_assoc_items =
3323            replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3324
3325        for item in trait_items {
3326            with_owner(self, item.id, |this| this.resolve_trait_item(item));
3327        }
3328
3329        self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3330    }
3331
3332    fn resolve_trait_item(&mut self, item: &'ast Item<AssocItemKind>) {
3333        let walk_assoc_item =
3334            |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3335                this.with_generic_param_rib(
3336                    &generics.params,
3337                    RibKind::AssocItem,
3338                    item.id,
3339                    kind,
3340                    generics.span,
3341                    |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3342                );
3343            };
3344
3345        self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3346        match &item.kind {
3347            AssocItemKind::Const(ast::ConstItem {
3348                generics,
3349                ty,
3350                body,
3351                kind,
3352                define_opaque,
3353                ..
3354            }) => {
3355                self.with_generic_param_rib(
3356                    &generics.params,
3357                    RibKind::AssocItem,
3358                    item.id,
3359                    LifetimeBinderKind::ConstItem,
3360                    generics.span,
3361                    |this| {
3362                        this.with_lifetime_rib(
3363                            LifetimeRibKind::Elided {
3364                                res: LifetimeRes::Static,
3365                                error_in_path: true,
3366                            },
3367                            |this| {
3368                                this.visit_generics(generics);
3369                                if *kind == ConstItemKind::TypeConst
3370                                    && !this.r.features.generic_const_parameter_types()
3371                                {
3372                                    this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3373                                        this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
3374                                            this.with_lifetime_rib(
3375                                                LifetimeRibKind::ConstParamTy,
3376                                                |this| this.visit_ty(ty),
3377                                            )
3378                                        })
3379                                    });
3380                                } else {
3381                                    this.visit_ty(ty);
3382                                }
3383
3384                                // Only impose the restrictions of `ConstRibKind` for an
3385                                // actual constant expression in a provided default.
3386                                //
3387                                // We allow arbitrary const expressions inside of associated consts,
3388                                // even if they are potentially not const evaluatable.
3389                                //
3390                                // Type parameters can already be used and as associated consts are
3391                                // not used as part of the type system, this is far less surprising.
3392                                this.resolve_const_item_rhs(body, None);
3393                            },
3394                        )
3395                    },
3396                );
3397
3398                self.resolve_define_opaques(define_opaque);
3399            }
3400            AssocItemKind::Fn(Fn { generics, define_opaque, .. }) => {
3401                walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3402
3403                self.resolve_define_opaques(define_opaque);
3404            }
3405            AssocItemKind::Delegation(delegation) => {
3406                self.with_generic_param_rib(
3407                    &[],
3408                    RibKind::AssocItem,
3409                    item.id,
3410                    LifetimeBinderKind::Function,
3411                    delegation.path.segments.last().unwrap().ident.span,
3412                    |this| this.resolve_delegation(delegation, item.id, false),
3413                );
3414            }
3415            AssocItemKind::Type(TyAlias { generics, .. }) => self
3416                .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3417                    walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3418                }),
3419            AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3420                {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3421            }
3422        };
3423    }
3424
3425    /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
3426    fn with_optional_trait_ref<T>(
3427        &mut self,
3428        opt_trait_ref: Option<&TraitRef>,
3429        self_type: &'ast Ty,
3430        f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3431    ) -> T {
3432        let mut new_val = None;
3433        let mut new_id = None;
3434        if let Some(trait_ref) = opt_trait_ref {
3435            let path: Vec<_> = Segment::from_path(&trait_ref.path);
3436            self.diag_metadata.currently_processing_impl_trait =
3437                Some((trait_ref.clone(), self_type.clone()));
3438            let res = self.smart_resolve_path_fragment(
3439                &None,
3440                &path,
3441                PathSource::Trait(AliasPossibility::No),
3442                Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3443                RecordPartialRes::Yes,
3444                None,
3445            );
3446            self.diag_metadata.currently_processing_impl_trait = None;
3447            if let Some(def_id) = res.expect_full_res().opt_def_id() {
3448                new_id = Some(def_id);
3449                new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3450            }
3451        }
3452        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3453        let result = f(self, new_id);
3454        self.current_trait_ref = original_trait_ref;
3455        result
3456    }
3457
3458    fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3459        let mut self_type_rib = Rib::new(RibKind::Normal);
3460
3461        // Plain insert (no renaming, since types are not currently hygienic)
3462        self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3463        self.ribs[ns].push(self_type_rib);
3464        f(self);
3465        self.ribs[ns].pop();
3466    }
3467
3468    fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3469        self.with_self_rib_ns(TypeNS, self_res, f)
3470    }
3471
3472    fn resolve_implementation(
3473        &mut self,
3474        attrs: &[ast::Attribute],
3475        generics: &'ast Generics,
3476        of_trait: Option<&'ast ast::TraitImplHeader>,
3477        self_type: &'ast Ty,
3478        item_id: NodeId,
3479        impl_items: &'ast [Box<AssocItem>],
3480    ) {
3481        {
    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:3481",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3481u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_implementation")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolve_implementation");
3482        // If applicable, create a rib for the type parameters.
3483        self.with_generic_param_rib(
3484            &generics.params,
3485            RibKind::Item(HasGenericParams::Yes(generics.span), self.r.tcx.def_kind(self.r.current_owner.def_id)),
3486            item_id,
3487            LifetimeBinderKind::ImplBlock,
3488            generics.span,
3489            |this| {
3490                // Dummy self type for better errors if `Self` is used in the trait path.
3491                this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3492                    this.with_lifetime_rib(
3493                        LifetimeRibKind::AnonymousCreateParameter {
3494                            binder: item_id,
3495                            report_in_path: true
3496                        },
3497                        |this| {
3498                            // Resolve the trait reference, if necessary.
3499                            this.with_optional_trait_ref(
3500                                of_trait.map(|t| &t.trait_ref),
3501                                self_type,
3502                                |this, trait_id| {
3503                                    this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3504
3505                                    let item_def_id = this.r.current_owner.def_id;
3506
3507                                    // Register the trait definitions from here.
3508                                    if let Some(trait_id) = trait_id {
3509                                        this.r
3510                                            .trait_impls
3511                                            .entry(trait_id)
3512                                            .or_default()
3513                                            .push(item_def_id);
3514                                    }
3515
3516                                    let item_def_id = item_def_id.to_def_id();
3517                                    let res = Res::SelfTyAlias {
3518                                        alias_to: item_def_id,
3519                                        is_trait_impl: trait_id.is_some(),
3520                                    };
3521                                    this.with_self_rib(res, |this| {
3522                                        if let Some(of_trait) = of_trait {
3523                                            // Resolve type arguments in the trait path.
3524                                            visit::walk_trait_ref(this, &of_trait.trait_ref);
3525                                        }
3526                                        // Resolve the self type.
3527                                        this.visit_ty(self_type);
3528                                        // Resolve the generic parameters.
3529                                        this.visit_generics(generics);
3530
3531                                        // Resolve the items within the impl.
3532                                        this.with_current_self_type(self_type, |this| {
3533                                            this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3534                                                {
    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:3534",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3534u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_implementation with_self_rib_ns(ValueNS, ...)")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
3535                                                let mut seen_trait_items = Default::default();
3536                                                for item in impl_items {
3537                                                    with_owner(this, item.id, |this| {
3538                                                        this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id, of_trait.is_some());
3539                                                    })
3540                                                }
3541                                            });
3542                                        });
3543                                    });
3544                                },
3545                            )
3546                        },
3547                    );
3548                });
3549            },
3550        );
3551    }
3552
3553    fn resolve_impl_item(
3554        &mut self,
3555        item: &'ast AssocItem,
3556        seen_trait_items: &mut FxHashMap<DefId, Span>,
3557        trait_id: Option<DefId>,
3558        is_in_trait_impl: bool,
3559    ) {
3560        use crate::ResolutionError::*;
3561        self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3562        let prev = self.diag_metadata.current_impl_item.take();
3563        self.diag_metadata.current_impl_item = Some(&item);
3564        match &item.kind {
3565            AssocItemKind::Const(ast::ConstItem {
3566                ident,
3567                generics,
3568                ty,
3569                body,
3570                kind,
3571                define_opaque,
3572                ..
3573            }) => {
3574                {
    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:3574",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3574u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_implementation AssocItemKind::Const")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolve_implementation AssocItemKind::Const");
3575                self.with_generic_param_rib(
3576                    &generics.params,
3577                    RibKind::AssocItem,
3578                    item.id,
3579                    LifetimeBinderKind::ConstItem,
3580                    generics.span,
3581                    |this| {
3582                        this.with_lifetime_rib(
3583                            LifetimeRibKind::Elided {
3584                                res: LifetimeRes::Static,
3585                                error_in_path: true,
3586                            },
3587                            |this| {
3588                                // If this is a trait impl, ensure the const
3589                                // exists in trait
3590                                this.check_trait_item(
3591                                    item.id,
3592                                    *ident,
3593                                    *ident,
3594                                    &item.kind,
3595                                    ValueNS,
3596                                    item.span,
3597                                    seen_trait_items,
3598                                    |i, s, c| ConstNotMemberOfTrait(i, s, c),
3599                                );
3600
3601                                this.visit_generics(generics);
3602                                if *kind == ConstItemKind::TypeConst
3603                                    && !this.r.tcx.features().generic_const_parameter_types()
3604                                {
3605                                    this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3606                                        this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
3607                                            this.with_lifetime_rib(
3608                                                LifetimeRibKind::ConstParamTy,
3609                                                |this| this.visit_ty(ty),
3610                                            )
3611                                        })
3612                                    });
3613                                } else {
3614                                    this.visit_ty(ty);
3615                                }
3616                                // We allow arbitrary const expressions inside of associated consts,
3617                                // even if they are potentially not const evaluatable.
3618                                //
3619                                // Type parameters can already be used and as associated consts are
3620                                // not used as part of the type system, this is far less surprising.
3621                                this.resolve_const_item_rhs(body, None);
3622                            },
3623                        )
3624                    },
3625                );
3626                self.resolve_define_opaques(define_opaque);
3627            }
3628            AssocItemKind::Fn(fn_kind @ Fn { ident, generics, define_opaque, .. }) => {
3629                {
    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:3629",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3629u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_implementation AssocItemKind::Fn")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolve_implementation AssocItemKind::Fn");
3630                // We also need a new scope for the impl item type parameters.
3631                self.with_generic_param_rib(
3632                    &generics.params,
3633                    RibKind::AssocItem,
3634                    item.id,
3635                    LifetimeBinderKind::Function,
3636                    generics.span,
3637                    |this| {
3638                        let effective_ident = if is_in_trait_impl && fn_kind.is_pin_drop_sugar() {
3639                            Ident::new(sym::pin_drop, ident.span)
3640                        } else {
3641                            *ident
3642                        };
3643                        // If this is a trait impl, ensure the method
3644                        // exists in trait
3645                        this.check_trait_item(
3646                            item.id,
3647                            effective_ident,
3648                            *ident,
3649                            &item.kind,
3650                            ValueNS,
3651                            item.span,
3652                            seen_trait_items,
3653                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3654                        );
3655
3656                        visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3657                    },
3658                );
3659
3660                self.resolve_define_opaques(define_opaque);
3661            }
3662            AssocItemKind::Type(TyAlias { ident, generics, .. }) => {
3663                self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3664                {
    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:3664",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3664u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_implementation AssocItemKind::Type")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolve_implementation AssocItemKind::Type");
3665                // We also need a new scope for the impl item type parameters.
3666                self.with_generic_param_rib(
3667                    &generics.params,
3668                    RibKind::AssocItem,
3669                    item.id,
3670                    LifetimeBinderKind::ImplAssocType,
3671                    generics.span,
3672                    |this| {
3673                        this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3674                            // If this is a trait impl, ensure the type
3675                            // exists in trait
3676                            this.check_trait_item(
3677                                item.id,
3678                                *ident,
3679                                *ident,
3680                                &item.kind,
3681                                TypeNS,
3682                                item.span,
3683                                seen_trait_items,
3684                                |i, s, c| TypeNotMemberOfTrait(i, s, c),
3685                            );
3686
3687                            visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3688                        });
3689                    },
3690                );
3691                self.diag_metadata.in_non_gat_assoc_type = None;
3692            }
3693            AssocItemKind::Delegation(delegation) => {
3694                {
    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:3694",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3694u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_implementation AssocItemKind::Delegation")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolve_implementation AssocItemKind::Delegation");
3695                self.with_generic_param_rib(
3696                    &[],
3697                    RibKind::AssocItem,
3698                    item.id,
3699                    LifetimeBinderKind::Function,
3700                    delegation.path.segments.last().unwrap().ident.span,
3701                    |this| {
3702                        this.check_trait_item(
3703                            item.id,
3704                            delegation.ident,
3705                            delegation.ident,
3706                            &item.kind,
3707                            ValueNS,
3708                            item.span,
3709                            seen_trait_items,
3710                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3711                        );
3712
3713                        // Here we don't use `trait_id`, as we can process unresolved trait, however
3714                        // in this case we are still in a trait impl, https://github.com/rust-lang/rust/issues/150152
3715                        this.resolve_delegation(delegation, item.id, is_in_trait_impl);
3716                    },
3717                );
3718            }
3719            AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3720                {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3721            }
3722        }
3723        self.diag_metadata.current_impl_item = prev;
3724    }
3725
3726    fn check_trait_item<F>(
3727        &mut self,
3728        id: NodeId,
3729        mut ident: Ident,
3730        mut reported_ident: Ident,
3731        kind: &AssocItemKind,
3732        ns: Namespace,
3733        span: Span,
3734        seen_trait_items: &mut FxHashMap<DefId, Span>,
3735        err: F,
3736    ) where
3737        F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3738    {
3739        // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3740        let Some((module, _)) = self.current_trait_ref else {
3741            return;
3742        };
3743        ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3744        reported_ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3745        let key = BindingKey::new(IdentKey::new(ident), ns);
3746        let mut decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3747        {
    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:3747",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3747u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("decl")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("decl");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&decl)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?decl);
3748        if decl.is_none() {
3749            // We could not find the trait item in the correct namespace.
3750            // Check the other namespace to report an error.
3751            let ns = match ns {
3752                ValueNS => TypeNS,
3753                TypeNS => ValueNS,
3754                _ => ns,
3755            };
3756            let key = BindingKey::new(IdentKey::new(ident), ns);
3757            decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3758            {
    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:3758",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3758u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("decl")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("decl");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&decl)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?decl);
3759        }
3760
3761        let feed_visibility = |this: &mut Self, def_id| {
3762            let vis = this.r.tcx.visibility(def_id);
3763            let vis = if vis.is_visible_locally() {
3764                vis.expect_local()
3765            } else {
3766                this.r.dcx().span_delayed_bug(
3767                    span,
3768                    "error should be emitted when an unexpected trait item is used",
3769                );
3770                Visibility::Public
3771            };
3772            // HACK: because we don't want to track the `TyCtxtFeed` through the resolver to here
3773            // in a hash-map, we instead conjure a `TyCtxtFeed` for any `DefId` here, but prevent
3774            // it from being used generally.
3775            this.r.tcx.feed_visibility_for_trait_impl_item(this.r.current_owner.def_id, vis);
3776        };
3777
3778        let Some(decl) = decl else {
3779            // We could not find the method: report an error.
3780            let candidate = self.find_similarly_named_assoc_item(reported_ident.name, kind);
3781            let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3782            let path_names = path_names_to_string(path);
3783            self.report_error(span, err(reported_ident, path_names, candidate));
3784            feed_visibility(self, module.def_id());
3785            return;
3786        };
3787
3788        let res = decl.res();
3789        let Res::Def(def_kind, id_in_trait) = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
3790        feed_visibility(self, id_in_trait);
3791
3792        match seen_trait_items.entry(id_in_trait) {
3793            Entry::Occupied(entry) => {
3794                self.report_error(
3795                    span,
3796                    ResolutionError::TraitImplDuplicate {
3797                        name: ident,
3798                        old_span: *entry.get(),
3799                        trait_item_span: decl.span,
3800                    },
3801                );
3802                return;
3803            }
3804            Entry::Vacant(entry) => {
3805                entry.insert(span);
3806            }
3807        };
3808
3809        match (def_kind, kind) {
3810            (DefKind::AssocTy, AssocItemKind::Type(..))
3811            | (DefKind::AssocFn, AssocItemKind::Fn(..))
3812            | (DefKind::AssocConst { .. }, AssocItemKind::Const(..))
3813            | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3814                self.r.record_partial_res(id, PartialRes::new(res));
3815                return;
3816            }
3817            _ => {}
3818        }
3819
3820        // The method kind does not correspond to what appeared in the trait, report.
3821        let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3822        let (code, kind) = match kind {
3823            AssocItemKind::Const(..) => (E0323, "const"),
3824            AssocItemKind::Fn(..) => (E0324, "method"),
3825            AssocItemKind::Type(..) => (E0325, "type"),
3826            AssocItemKind::Delegation(..) => (E0324, "method"),
3827            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3828                ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("unexpanded macro"))span_bug!(span, "unexpanded macro")
3829            }
3830        };
3831        let trait_path = path_names_to_string(path);
3832        self.report_error(
3833            span,
3834            ResolutionError::TraitImplMismatch {
3835                name: ident,
3836                kind,
3837                code,
3838                trait_path,
3839                trait_item_span: decl.span,
3840            },
3841        );
3842    }
3843
3844    fn resolve_static_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3845        self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3846            this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3847                this.visit_expr(expr)
3848            });
3849        })
3850    }
3851
3852    fn resolve_const_item_rhs(
3853        &mut self,
3854        body: &'ast Option<Box<Expr>>,
3855        item: Option<(Ident, ConstantItemKind)>,
3856    ) {
3857        if let Some(body) = body {
3858            self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3859                this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3860                    this.visit_expr(body)
3861                })
3862            })
3863        }
3864    }
3865
3866    fn resolve_delegation(
3867        &mut self,
3868        delegation: &'ast Delegation,
3869        item_id: NodeId,
3870        is_in_trait_impl: bool,
3871    ) {
3872        self.smart_resolve_path(
3873            delegation.id,
3874            &delegation.qself,
3875            &delegation.path,
3876            PathSource::Delegation,
3877        );
3878
3879        // Create lifetimes not with `LifetimeRibKind::Generics` but with `LifetimeRibKind::Elided`,
3880        // as we are not processing generic params but generic args in a future call (#156342, #156758).
3881        self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3882            if let Some(qself) = &delegation.qself {
3883                this.visit_ty(&qself.ty);
3884            }
3885
3886            this.visit_path(&delegation.path);
3887        });
3888
3889        let resolution_node_id = if is_in_trait_impl { item_id } else { delegation.id };
3890        let def_id = self
3891            .r
3892            .partial_res_map
3893            .get(&resolution_node_id)
3894            .and_then(|r| r.expect_full_res().opt_def_id());
3895
3896        let resolution_id = def_id.ok_or_else(|| {
3897            self.r.tcx.dcx().span_delayed_bug(
3898                delegation.path.span,
3899                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("LateResolutionVisitor: couldn\'t resolve node {0:?} in delegation item",
                resolution_node_id))
    })format!(
3900                    "LateResolutionVisitor: couldn't resolve node {resolution_node_id:?} in delegation item",
3901                ),
3902            )
3903        });
3904
3905        let info = DelegationInfo { resolution_id };
3906        self.r.delegation_infos.insert(self.r.current_owner.def_id, info);
3907
3908        let Some(body) = &delegation.body else { return };
3909        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3910            let ident = Ident::new(kw::SelfLower, body.span.normalize_to_macro_rules());
3911            let res = Res::Local(delegation.id);
3912            this.innermost_rib_bindings(ValueNS).insert(ident, res);
3913
3914            //As we lower target_expr_template body to a body of a function we need a label rib (#148889)
3915            this.with_label_rib(RibKind::FnOrCoroutine, |this| {
3916                this.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3917                    this.visit_block(body);
3918                });
3919            });
3920        });
3921    }
3922
3923    fn resolve_params(&mut self, params: &'ast [Param]) {
3924        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())];
3925        self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3926            for Param { pat, .. } in params {
3927                this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3928            }
3929            this.apply_pattern_bindings(bindings);
3930        });
3931        for Param { ty, .. } in params {
3932            self.visit_ty(ty);
3933        }
3934    }
3935
3936    fn resolve_local(&mut self, local: &'ast Local) {
3937        {
    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:3937",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3937u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolving local ({0:?})",
                                                    local) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("resolving local ({:?})", local);
3938        // Resolve the type.
3939        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);
3940
3941        // Resolve the initializer.
3942        if let Some((init, els)) = local.kind.init_else_opt() {
3943            self.visit_expr(init);
3944
3945            // Resolve the `else` block
3946            if let Some(els) = els {
3947                self.visit_block(els);
3948            }
3949        }
3950
3951        // Resolve the pattern.
3952        self.resolve_pattern_top(&local.pat, PatternSource::Let);
3953    }
3954
3955    /// Build a map from pattern identifiers to binding-info's, and check the bindings are
3956    /// consistent when encountering or-patterns and never patterns.
3957    /// This is done hygienically: this could arise for a macro that expands into an or-pattern
3958    /// where one 'x' was from the user and one 'x' came from the macro.
3959    ///
3960    /// A never pattern by definition indicates an unreachable case. For example, matching on
3961    /// `Result<T, &!>` could look like:
3962    /// ```rust
3963    /// # #![feature(never_type)]
3964    /// # #![feature(never_patterns)]
3965    /// # fn bar(_x: u32) {}
3966    /// let foo: Result<u32, &!> = Ok(0);
3967    /// match foo {
3968    ///     Ok(x) => bar(x),
3969    ///     Err(&!),
3970    /// }
3971    /// ```
3972    /// This extends to product types: `(x, !)` is likewise unreachable. So it doesn't make sense to
3973    /// have a binding here, and we tell the user to use `_` instead.
3974    fn compute_and_check_binding_map(
3975        &mut self,
3976        pat: &Pat,
3977    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3978        let mut binding_map = FxIndexMap::default();
3979        let mut is_never_pat = false;
3980
3981        pat.walk(&mut |pat| {
3982            match pat.kind {
3983                PatKind::Ident(annotation, ident, ref sub_pat)
3984                    if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3985                {
3986                    binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3987                }
3988                PatKind::Or(ref ps) => {
3989                    // Check the consistency of this or-pattern and
3990                    // then add all bindings to the larger map.
3991                    match self.compute_and_check_or_pat_binding_map(ps) {
3992                        Ok(bm) => binding_map.extend(bm),
3993                        Err(IsNeverPattern) => is_never_pat = true,
3994                    }
3995                    return false;
3996                }
3997                PatKind::Never => is_never_pat = true,
3998                _ => {}
3999            }
4000
4001            true
4002        });
4003
4004        if is_never_pat {
4005            for (_, binding) in binding_map {
4006                self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
4007            }
4008            Err(IsNeverPattern)
4009        } else {
4010            Ok(binding_map)
4011        }
4012    }
4013
4014    fn is_base_res_local(&self, nid: NodeId) -> bool {
4015        #[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!(
4016            self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
4017            Some(Res::Local(..))
4018        )
4019    }
4020
4021    /// Compute the binding map for an or-pattern. Checks that all of the arms in the or-pattern
4022    /// have exactly the same set of bindings, with the same binding modes for each.
4023    /// Returns the computed binding map and a boolean indicating whether the pattern is a never
4024    /// pattern.
4025    ///
4026    /// A never pattern by definition indicates an unreachable case. For example, destructuring a
4027    /// `Result<T, &!>` could look like:
4028    /// ```rust
4029    /// # #![feature(never_type)]
4030    /// # #![feature(never_patterns)]
4031    /// # fn foo() -> Result<bool, &'static !> { Ok(true) }
4032    /// let (Ok(x) | Err(&!)) = foo();
4033    /// # let _ = x;
4034    /// ```
4035    /// Because the `Err(&!)` branch is never reached, it does not need to have the same bindings as
4036    /// the other branches of the or-pattern. So we must ignore never pattern when checking the
4037    /// bindings of an or-pattern.
4038    /// Moreover, if all the subpatterns are never patterns (e.g. `Ok(!) | Err(!)`), then the
4039    /// pattern as a whole counts as a never pattern (since it's definitionallly unreachable).
4040    fn compute_and_check_or_pat_binding_map(
4041        &mut self,
4042        pats: &[Pat],
4043    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
4044        let mut missing_vars = FxIndexMap::default();
4045        let mut inconsistent_vars = FxIndexMap::default();
4046
4047        // 1) Compute the binding maps of all arms; we must ignore never patterns here.
4048        let not_never_pats = pats
4049            .iter()
4050            .filter_map(|pat| {
4051                let binding_map = self.compute_and_check_binding_map(pat).ok()?;
4052                Some((binding_map, pat))
4053            })
4054            .collect::<Vec<_>>();
4055
4056        // 2) Record any missing bindings or binding mode inconsistencies.
4057        for &(ref map_outer, pat_outer) in not_never_pats.iter() {
4058            // Check against all arms except for the same pattern which is always self-consistent.
4059            let inners = not_never_pats.iter().filter(|(_, pat)| pat.id != pat_outer.id);
4060
4061            for &(ref map, pat) in inners {
4062                for (&name, binding_inner) in map {
4063                    match map_outer.get(&name) {
4064                        None => {
4065                            // The inner binding is missing in the outer.
4066                            let binding_error =
4067                                missing_vars.entry(name).or_insert_with(|| BindingError {
4068                                    name,
4069                                    origin: Default::default(),
4070                                    target: Default::default(),
4071                                    could_be_path: name.as_str().starts_with(char::is_uppercase),
4072                                });
4073                            binding_error.origin.push((binding_inner.span, pat.clone()));
4074                            binding_error.target.push(pat_outer.clone());
4075                        }
4076                        Some(binding_outer) => {
4077                            if binding_outer.annotation != binding_inner.annotation {
4078                                // The binding modes in the outer and inner bindings differ.
4079                                inconsistent_vars
4080                                    .entry(name)
4081                                    .or_insert((binding_inner.span, binding_outer.span));
4082                            }
4083                        }
4084                    }
4085                }
4086            }
4087        }
4088
4089        // 3) Report all missing variables we found.
4090        for (name, mut v) in missing_vars {
4091            if inconsistent_vars.contains_key(&name) {
4092                v.could_be_path = false;
4093            }
4094            self.report_error(
4095                v.origin.iter().next().unwrap().0,
4096                ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
4097            );
4098        }
4099
4100        // 4) Report all inconsistencies in binding modes we found.
4101        for (name, v) in inconsistent_vars {
4102            self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
4103        }
4104
4105        // 5) Bubble up the final binding map.
4106        if not_never_pats.is_empty() {
4107            // All the patterns are never patterns, so the whole or-pattern is one too.
4108            Err(IsNeverPattern)
4109        } else {
4110            let mut binding_map = FxIndexMap::default();
4111            for (bm, _) in not_never_pats {
4112                binding_map.extend(bm);
4113            }
4114            Ok(binding_map)
4115        }
4116    }
4117
4118    /// Check the consistency of bindings wrt or-patterns and never patterns.
4119    fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
4120        let mut is_or_or_never = false;
4121        pat.walk(&mut |pat| match pat.kind {
4122            PatKind::Or(..) | PatKind::Never => {
4123                is_or_or_never = true;
4124                false
4125            }
4126            _ => true,
4127        });
4128        if is_or_or_never {
4129            let _ = self.compute_and_check_binding_map(pat);
4130        }
4131    }
4132
4133    fn resolve_arm(&mut self, arm: &'ast Arm) {
4134        self.with_rib(ValueNS, RibKind::Normal, |this| {
4135            this.resolve_pattern_top(&arm.pat, PatternSource::Match);
4136            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));
4137            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);
4138        });
4139    }
4140
4141    /// Arising from `source`, resolve a top level pattern.
4142    fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
4143        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())];
4144        self.resolve_pattern(pat, pat_src, &mut bindings);
4145        self.apply_pattern_bindings(bindings);
4146    }
4147
4148    /// Apply the bindings from a pattern to the innermost rib of the current scope.
4149    fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
4150        let rib_bindings = self.innermost_rib_bindings(ValueNS);
4151        let Some((_, pat_bindings)) = pat_bindings.pop() else {
4152            ::rustc_middle::util::bug::bug_fmt(format_args!("tried applying nonexistent bindings from pattern"));bug!("tried applying nonexistent bindings from pattern");
4153        };
4154
4155        if rib_bindings.is_empty() {
4156            // Often, such as for match arms, the bindings are introduced into a new rib.
4157            // In this case, we can move the bindings over directly.
4158            *rib_bindings = pat_bindings;
4159        } else {
4160            rib_bindings.extend(pat_bindings);
4161        }
4162    }
4163
4164    /// Resolve bindings in a pattern. `apply_pattern_bindings` must be called after to introduce
4165    /// the bindings into scope.
4166    fn resolve_pattern(
4167        &mut self,
4168        pat: &'ast Pat,
4169        pat_src: PatternSource,
4170        bindings: &mut PatternBindings,
4171    ) {
4172        // We walk the pattern before declaring the pattern's inner bindings,
4173        // so that we avoid resolving a literal expression to a binding defined
4174        // by the pattern.
4175        // NB: `Self::visit_pat` must be used rather than `visit::walk_pat` to avoid resolving guard
4176        // patterns' guard expressions multiple times (#141265).
4177        self.visit_pat(pat);
4178        self.resolve_pattern_inner(pat, pat_src, bindings);
4179        // This has to happen *after* we determine which pat_idents are variants:
4180        self.check_consistent_bindings(pat);
4181    }
4182
4183    /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
4184    ///
4185    /// ### `bindings`
4186    ///
4187    /// A stack of sets of bindings accumulated.
4188    ///
4189    /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
4190    /// be interpreted as re-binding an already bound binding. This results in an error.
4191    /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
4192    /// in reusing this binding rather than creating a fresh one.
4193    ///
4194    /// When called at the top level, the stack must have a single element
4195    /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
4196    /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
4197    /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
4198    /// When each `p_i` has been dealt with, the top set is merged with its parent.
4199    /// When a whole or-pattern has been dealt with, the thing happens.
4200    ///
4201    /// See the implementation and `fresh_binding` for more details.
4202    #[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(4202u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("pat")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("pat");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("pat_src")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("pat_src");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat_src)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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")]
4203    fn resolve_pattern_inner(
4204        &mut self,
4205        pat: &'ast Pat,
4206        pat_src: PatternSource,
4207        bindings: &mut PatternBindings,
4208    ) {
4209        // Visit all direct subpatterns of this pattern.
4210        pat.walk(&mut |pat| {
4211            match pat.kind {
4212                PatKind::Ident(bmode, ident, ref sub) => {
4213                    // First try to resolve the identifier as some existing entity,
4214                    // then fall back to a fresh binding.
4215                    let has_sub = sub.is_some();
4216                    let res = self
4217                        .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
4218                        .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
4219                    self.r.record_partial_res(pat.id, PartialRes::new(res));
4220                    self.r.record_pat_span(pat.id, pat.span);
4221                }
4222                PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
4223                    self.smart_resolve_path(
4224                        pat.id,
4225                        qself,
4226                        path,
4227                        PathSource::TupleStruct(
4228                            pat.span,
4229                            self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
4230                        ),
4231                    );
4232                }
4233                PatKind::Path(ref qself, ref path) => {
4234                    self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
4235                }
4236                PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
4237                    self.smart_resolve_path(pat.id, qself, path, PathSource::Struct(None));
4238                    self.record_patterns_with_skipped_bindings(pat, rest);
4239                }
4240                PatKind::Or(ref ps) => {
4241                    // Add a new set of bindings to the stack. `Or` here records that when a
4242                    // binding already exists in this set, it should not result in an error because
4243                    // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
4244                    bindings.push((PatBoundCtx::Or, Default::default()));
4245                    for p in ps {
4246                        // Now we need to switch back to a product context so that each
4247                        // part of the or-pattern internally rejects already bound names.
4248                        // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
4249                        bindings.push((PatBoundCtx::Product, Default::default()));
4250                        self.resolve_pattern_inner(p, pat_src, bindings);
4251                        // Move up the non-overlapping bindings to the or-pattern.
4252                        // Existing bindings just get "merged".
4253                        let collected = bindings.pop().unwrap().1;
4254                        bindings.last_mut().unwrap().1.extend(collected);
4255                    }
4256                    // This or-pattern itself can itself be part of a product,
4257                    // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
4258                    // Both cases bind `a` again in a product pattern and must be rejected.
4259                    let collected = bindings.pop().unwrap().1;
4260                    bindings.last_mut().unwrap().1.extend(collected);
4261
4262                    // Prevent visiting `ps` as we've already done so above.
4263                    return false;
4264                }
4265                PatKind::Guard(ref subpat, ref guard) => {
4266                    // Add a new set of bindings to the stack to collect bindings in `subpat`.
4267                    bindings.push((PatBoundCtx::Product, Default::default()));
4268                    // Resolving `subpat` adds bindings onto the newly-pushed context. After, the
4269                    // total number of contexts on the stack should be the same as before.
4270                    let binding_ctx_stack_len = bindings.len();
4271                    self.resolve_pattern_inner(subpat, pat_src, bindings);
4272                    assert_eq!(bindings.len(), binding_ctx_stack_len);
4273                    // These bindings, but none from the surrounding pattern, are visible in the
4274                    // guard; put them in scope and resolve `guard`.
4275                    let subpat_bindings = bindings.pop().unwrap().1;
4276                    self.with_rib(ValueNS, RibKind::Normal, |this| {
4277                        *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
4278                        this.resolve_expr(&guard.cond, None);
4279                    });
4280                    // Propagate the subpattern's bindings upwards.
4281                    // FIXME(guard_patterns): For `if let` guards, we'll also need to get the
4282                    // bindings introduced by the guard from its rib and propagate them upwards.
4283                    // This will require checking the identifiers for overlaps with `bindings`, like
4284                    // what `fresh_binding` does (ideally sharing its logic). To keep them separate
4285                    // from `subpat_bindings`, we can introduce a fresh rib for the guard.
4286                    bindings.last_mut().unwrap().1.extend(subpat_bindings);
4287                    // Prevent visiting `subpat` as we've already done so above.
4288                    return false;
4289                }
4290                _ => {}
4291            }
4292            true
4293        });
4294    }
4295
4296    fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
4297        match rest {
4298            ast::PatFieldsRest::Rest(_) | ast::PatFieldsRest::Recovered(_) => {
4299                // Record that the pattern doesn't introduce all the bindings it could.
4300                if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
4301                    && let Some(res) = partial_res.full_res()
4302                    && let Some(def_id) = res.opt_def_id()
4303                {
4304                    self.ribs[ValueNS]
4305                        .last_mut()
4306                        .unwrap()
4307                        .patterns_with_skipped_bindings
4308                        .entry(def_id)
4309                        .or_default()
4310                        .push((
4311                            pat.span,
4312                            match rest {
4313                                ast::PatFieldsRest::Recovered(guar) => Err(*guar),
4314                                _ => Ok(()),
4315                            },
4316                        ));
4317                }
4318            }
4319            ast::PatFieldsRest::None => {}
4320        }
4321    }
4322
4323    fn fresh_binding(
4324        &mut self,
4325        ident: Ident,
4326        pat_id: NodeId,
4327        pat_src: PatternSource,
4328        bindings: &mut PatternBindings,
4329    ) -> Res {
4330        // Add the binding to the bindings map, if it doesn't already exist.
4331        // (We must not add it if it's in the bindings map because that breaks the assumptions
4332        // later passes make about or-patterns.)
4333        let ident = ident.normalize_to_macro_rules();
4334
4335        // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
4336        let already_bound_and = bindings
4337            .iter()
4338            .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
4339        if already_bound_and {
4340            // Overlap in a product pattern somewhere; report an error.
4341            use ResolutionError::*;
4342            let error = match pat_src {
4343                // `fn f(a: u8, a: u8)`:
4344                PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
4345                // `Variant(a, a)`:
4346                _ => IdentifierBoundMoreThanOnceInSamePattern,
4347            };
4348            self.report_error(ident.span, error(ident));
4349        }
4350
4351        // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
4352        // This is *required* for consistency which is checked later.
4353        let already_bound_or = bindings
4354            .iter()
4355            .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
4356        let res = if let Some(&res) = already_bound_or {
4357            // `Variant1(a) | Variant2(a)`, ok
4358            // Reuse definition from the first `a`.
4359            res
4360        } else {
4361            // A completely fresh binding is added to the map.
4362            Res::Local(pat_id)
4363        };
4364
4365        // Record as bound.
4366        bindings.last_mut().unwrap().1.insert(ident, res);
4367        res
4368    }
4369
4370    fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4371        &mut self.ribs[ns].last_mut().unwrap().bindings
4372    }
4373
4374    fn try_resolve_as_non_binding(
4375        &mut self,
4376        pat_src: PatternSource,
4377        ann: BindingMode,
4378        ident: Ident,
4379        has_sub: bool,
4380    ) -> Option<Res> {
4381        // An immutable (no `mut`) by-value (no `ref`) binding pattern without
4382        // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
4383        // also be interpreted as a path to e.g. a constant, variant, etc.
4384        let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4385
4386        let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4387        let (res, binding) = match ls_binding {
4388            LateDecl::Decl(binding)
4389                if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4390            {
4391                // For ambiguous bindings we don't know all their definitions and cannot check
4392                // whether they can be shadowed by fresh bindings or not, so force an error.
4393                // issues/33118#issuecomment-233962221 (see below) still applies here,
4394                // but we have to ignore it for backward compatibility.
4395                self.r.record_use(ident, binding, Used::Other);
4396                return None;
4397            }
4398            LateDecl::Decl(binding) => (binding.res(), Some(binding)),
4399            LateDecl::RibDef(res) => (res, None),
4400        };
4401
4402        match res {
4403            Res::SelfCtor(_) // See #70549.
4404            | Res::Def(
4405                DefKind::Ctor(_, CtorKind::Const) | DefKind::Const { .. } | DefKind::AssocConst { .. } | DefKind::ConstParam,
4406                _,
4407            ) if is_syntactic_ambiguity => {
4408                // Disambiguate in favor of a unit struct/variant or constant pattern.
4409                if let Some(binding) = binding {
4410                    self.r.record_use(ident, binding, Used::Other);
4411                }
4412                Some(res)
4413            }
4414            Res::Def(
4415                DefKind::Ctor(..)
4416                | DefKind::Const { .. }
4417                | DefKind::AssocConst { .. }
4418                | DefKind::Static { .. },
4419                _,
4420            ) => {
4421                // This is unambiguously a fresh binding, either syntactically
4422                // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
4423                // to something unusable as a pattern (e.g., constructor function),
4424                // but we still conservatively report an error, see
4425                // issues/33118#issuecomment-233962221 for one reason why.
4426                let binding = binding.expect("no binding for a ctor or static");
4427                self.report_error(
4428                    ident.span,
4429                    ResolutionError::BindingShadowsSomethingUnacceptable {
4430                        shadowing_binding: pat_src,
4431                        name: ident.name,
4432                        participle: if binding.is_import() { "imported" } else { "defined" },
4433                        article: binding.res().article(),
4434                        shadowed_binding: binding.res(),
4435                        shadowed_binding_span: binding.span,
4436                    },
4437                );
4438                None
4439            }
4440            Res::Def(DefKind::ConstParam, def_id) => {
4441                // Same as for DefKind::Const { .. } above, but here, `binding` is `None`, so we
4442                // have to construct the error differently
4443                self.report_error(
4444                    ident.span,
4445                    ResolutionError::BindingShadowsSomethingUnacceptable {
4446                        shadowing_binding: pat_src,
4447                        name: ident.name,
4448                        participle: "defined",
4449                        article: res.article(),
4450                        shadowed_binding: res,
4451                        shadowed_binding_span: self.r.def_span(def_id),
4452                    },
4453                );
4454                None
4455            }
4456            Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4457                // These entities are explicitly allowed to be shadowed by fresh bindings.
4458                None
4459            }
4460            Res::SelfCtor(_) => {
4461                // We resolve `Self` in pattern position as an ident sometimes during recovery,
4462                // so delay a bug instead of ICEing.
4463                self.r.dcx().span_delayed_bug(
4464                    ident.span,
4465                    "unexpected `SelfCtor` in pattern, expected identifier",
4466                );
4467                None
4468            }
4469            _ => ::rustc_middle::util::bug::span_bug_fmt(ident.span,
    format_args!("unexpected resolution for an identifier in pattern: {0:?}",
        res))span_bug!(
4470                ident.span,
4471                "unexpected resolution for an identifier in pattern: {:?}",
4472                res,
4473            ),
4474        }
4475    }
4476
4477    fn resolve_restriction_path(&mut self, restriction: &'ast ast::RestrictionKind) {
4478        match &restriction {
4479            ast::RestrictionKind::Unrestricted => (),
4480            ast::RestrictionKind::Restricted { path, id, shorthand: _ } => {
4481                self.smart_resolve_path(*id, &None, path, PathSource::Module);
4482            }
4483        }
4484    }
4485
4486    // High-level and context dependent path resolution routine.
4487    // Resolves the path and records the resolution into definition map.
4488    // If resolution fails tries several techniques to find likely
4489    // resolution candidates, suggest imports or other help, and report
4490    // errors in user friendly way.
4491    fn smart_resolve_path(
4492        &mut self,
4493        id: NodeId,
4494        qself: &Option<Box<QSelf>>,
4495        path: &Path,
4496        source: PathSource<'_, 'ast, 'ra>,
4497    ) {
4498        self.smart_resolve_path_fragment(
4499            qself,
4500            &Segment::from_path(path),
4501            source,
4502            Finalize::new(id, path.span),
4503            RecordPartialRes::Yes,
4504            None,
4505        );
4506    }
4507
4508    fn smart_resolve_path_fragment(
4509        &mut self,
4510        qself: &Option<Box<QSelf>>,
4511        path: &[Segment],
4512        source: PathSource<'_, 'ast, 'ra>,
4513        finalize: Finalize,
4514        record_partial_res: RecordPartialRes,
4515        parent_qself: Option<&QSelf>,
4516    ) -> PartialRes {
4517        let ns = source.namespace();
4518
4519        let Finalize { node_id, path_span, .. } = finalize;
4520        let report_errors = |this: &mut Self, res: Option<Res>| {
4521            if this.should_report_errs() {
4522                let (mut err, candidates) = this.smart_resolve_report_errors(
4523                    path,
4524                    None,
4525                    path_span,
4526                    source,
4527                    res,
4528                    parent_qself,
4529                );
4530
4531                let node_id = this.parent_scope.module.nearest_parent_mod_node_id();
4532                let instead = res.is_some();
4533                let (suggestion, const_err) = if let Some((start, end)) =
4534                    this.diag_metadata.in_range
4535                    && path[0].ident.span.lo() == end.span.lo()
4536                    && !#[allow(non_exhaustive_omitted_patterns)] match start.kind {
    ExprKind::Lit(_) => true,
    _ => false,
}matches!(start.kind, ExprKind::Lit(_))
4537                {
4538                    let mut sugg = ".";
4539                    let mut span = start.span.between(end.span);
4540                    if span.lo() + BytePos(2) == span.hi() {
4541                        // There's no space between the start, the range op and the end, suggest
4542                        // removal which will look better.
4543                        span = span.with_lo(span.lo() + BytePos(1));
4544                        sugg = "";
4545                    }
4546                    (
4547                        Some((
4548                            span,
4549                            "you might have meant to write `.` instead of `..`",
4550                            sugg.to_string(),
4551                            Applicability::MaybeIncorrect,
4552                        )),
4553                        None,
4554                    )
4555                } else if res.is_none()
4556                    && let PathSource::Type
4557                    | PathSource::Expr(_)
4558                    | PathSource::PreciseCapturingArg(..) = source
4559                {
4560                    this.suggest_adding_generic_parameter(path, source)
4561                } else {
4562                    (None, None)
4563                };
4564
4565                if let Some(const_err) = const_err {
4566                    err.cancel();
4567                    err = const_err;
4568                }
4569
4570                let ue = UseError {
4571                    err,
4572                    candidates,
4573                    node_id,
4574                    instead,
4575                    suggestion,
4576                    path: path.into(),
4577                    is_call: source.is_call(),
4578                };
4579
4580                this.use_injections.push(ue);
4581            }
4582
4583            PartialRes::new(Res::Err)
4584        };
4585
4586        // For paths originating from calls (like in `HashMap::new()`), tries
4587        // to enrich the plain `failed to resolve: ...` message with hints
4588        // about possible missing imports.
4589        //
4590        // Similar thing, for types, happens in `report_errors` above.
4591        let report_errors_for_call =
4592            |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4593                // Before we start looking for candidates, we have to get our hands
4594                // on the type user is trying to perform invocation on; basically:
4595                // we're transforming `HashMap::new` into just `HashMap`.
4596                let (following_seg, prefix_path) = match path.split_last() {
4597                    Some((last, path)) if !path.is_empty() => (Some(last), path),
4598                    _ => return Some(parent_err),
4599                };
4600
4601                let (mut err, candidates) = this.smart_resolve_report_errors(
4602                    prefix_path,
4603                    following_seg,
4604                    path_span,
4605                    PathSource::Type,
4606                    None,
4607                    parent_qself,
4608                );
4609
4610                // There are two different error messages user might receive at
4611                // this point:
4612                // - E0425 cannot find type `{}` in this scope
4613                // - E0433 failed to resolve: use of undeclared type or module `{}`
4614                //
4615                // The first one is emitted for paths in type-position, and the
4616                // latter one - for paths in expression-position.
4617                //
4618                // Thus (since we're in expression-position at this point), not to
4619                // confuse the user, we want to keep the *message* from E0433 (so
4620                // `parent_err`), but we want *hints* from E0425 (so `err`).
4621                //
4622                // And that's what happens below - we're just mixing both messages
4623                // into a single one.
4624                let failed_to_resolve = match parent_err.node {
4625                    ResolutionError::FailedToResolve { .. } => true,
4626                    _ => false,
4627                };
4628                let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4629
4630                // overwrite all properties with the parent's error message
4631                err.messages = take(&mut parent_err.messages);
4632                err.code = take(&mut parent_err.code);
4633                swap(&mut err.span, &mut parent_err.span);
4634                if failed_to_resolve {
4635                    err.children = take(&mut parent_err.children);
4636                } else {
4637                    err.children.append(&mut parent_err.children);
4638                }
4639                err.sort_span = parent_err.sort_span;
4640                err.is_lint = parent_err.is_lint.clone();
4641
4642                // merge the parent_err's suggestions with the typo (err's) suggestions
4643                match &mut err.suggestions {
4644                    Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4645                        Suggestions::Enabled(parent_suggestions) => {
4646                            // If both suggestions are enabled, append parent_err's suggestions to err's suggestions.
4647                            typo_suggestions.append(parent_suggestions)
4648                        }
4649                        Suggestions::Sealed(_) | Suggestions::Disabled => {
4650                            // If the parent's suggestions are either sealed or disabled, it signifies that
4651                            // new suggestions cannot be added or removed from the diagnostic. Therefore,
4652                            // we assign both types of suggestions to err's suggestions and discard the
4653                            // existing suggestions in err.
4654                            err.suggestions = std::mem::take(&mut parent_err.suggestions);
4655                        }
4656                    },
4657                    Suggestions::Sealed(_) | Suggestions::Disabled => (),
4658                }
4659
4660                parent_err.cancel();
4661
4662                let node_id = this.parent_scope.module.nearest_parent_mod_node_id();
4663
4664                if this.should_report_errs() {
4665                    if candidates.is_empty() {
4666                        if path.len() == 2
4667                            && let [segment] = prefix_path
4668                        {
4669                            // Delay to check whether method name is an associated function or not
4670                            // ```
4671                            // let foo = Foo {};
4672                            // foo::bar(); // possibly suggest to foo.bar();
4673                            //```
4674                            err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4675                        } else {
4676                            // When there is no suggested imports, we can just emit the error
4677                            // and suggestions immediately. Note that we bypass the usually error
4678                            // reporting routine (ie via `self.r.report_error`) because we need
4679                            // to post-process the `ResolutionError` above.
4680                            err.emit();
4681                        }
4682                    } else {
4683                        // If there are suggested imports, the error reporting is delayed
4684                        this.use_injections.push(UseError {
4685                            err,
4686                            candidates,
4687                            node_id,
4688                            instead: false,
4689                            suggestion: None,
4690                            path: prefix_path.into(),
4691                            is_call: source.is_call(),
4692                        });
4693                    }
4694                } else {
4695                    err.cancel();
4696                }
4697
4698                // We don't return `Some(parent_err)` here, because the error will
4699                // be already printed either immediately or as part of the `use` injections
4700                None
4701            };
4702
4703        let partial_res = match self.resolve_qpath_anywhere(
4704            qself,
4705            path,
4706            ns,
4707            source.defer_to_typeck(),
4708            finalize,
4709            source,
4710        ) {
4711            Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4712                // if we also have an associated type that matches the ident, stash a suggestion
4713                if let Some(items) = self.diag_metadata.current_trait_assoc_items
4714                    && let [Segment { ident, .. }] = path
4715                    && items.iter().any(|item| {
4716                        if let AssocItemKind::Type(alias) = &item.kind
4717                            && alias.ident == *ident
4718                        {
4719                            true
4720                        } else {
4721                            false
4722                        }
4723                    })
4724                {
4725                    let mut diag = self.r.tcx.dcx().struct_allow("");
4726                    diag.span_suggestion_verbose(
4727                        path_span.shrink_to_lo(),
4728                        "there is an associated type with the same name",
4729                        "Self::",
4730                        Applicability::MaybeIncorrect,
4731                    );
4732                    diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4733                }
4734
4735                if source.is_expected(res) || res == Res::Err {
4736                    partial_res
4737                } else {
4738                    report_errors(self, Some(res))
4739                }
4740            }
4741
4742            Ok(Some(partial_res)) if source.defer_to_typeck() => {
4743                // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
4744                // or `<T>::A::B`. If `B` should be resolved in value namespace then
4745                // it needs to be added to the trait map.
4746                if ns == ValueNS {
4747                    let item_name = path.last().unwrap().ident;
4748                    self.record_traits_in_scope(node_id, item_name);
4749                }
4750
4751                if PrimTy::from_name(path[0].ident.name).is_some() {
4752                    let mut std_path = Vec::with_capacity(1 + path.len());
4753
4754                    std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4755                    std_path.extend(path);
4756                    if let PathResult::Module(_) | PathResult::NonModule(_) =
4757                        self.resolve_path(&std_path, Some(ns), None, source)
4758                    {
4759                        // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
4760                        let item_span =
4761                            path.iter().last().map_or(path_span, |segment| segment.ident.span);
4762
4763                        self.r.confused_type_with_std_module.insert(item_span, path_span);
4764                        self.r.confused_type_with_std_module.insert(path_span, path_span);
4765                    }
4766                }
4767
4768                partial_res
4769            }
4770
4771            Err(err) => {
4772                if let Some(err) = report_errors_for_call(self, err) {
4773                    self.report_error(err.span, err.node);
4774                }
4775
4776                PartialRes::new(Res::Err)
4777            }
4778
4779            _ => report_errors(self, None),
4780        };
4781
4782        if record_partial_res == RecordPartialRes::Yes {
4783            // Avoid recording definition of `A::B` in `<T as A>::B::C`.
4784            self.r.record_partial_res(node_id, partial_res);
4785            self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4786            self.lint_unused_qualifications(path, ns, finalize);
4787        }
4788
4789        partial_res
4790    }
4791
4792    fn self_type_is_available(&mut self) -> bool {
4793        let binding = self
4794            .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4795        if let Some(LateDecl::RibDef(res)) = binding { res != Res::Err } else { false }
4796    }
4797
4798    fn self_value_is_available(&mut self, self_span: Span) -> bool {
4799        let ident = Ident::new(kw::SelfLower, self_span);
4800        let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4801        if let Some(LateDecl::RibDef(res)) = binding { res != Res::Err } else { false }
4802    }
4803
4804    /// A wrapper around [`Resolver::report_error`].
4805    ///
4806    /// This doesn't emit errors for function bodies if this is rustdoc.
4807    fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4808        if self.should_report_errs() {
4809            self.r.report_error(span, resolution_error);
4810        }
4811    }
4812
4813    #[inline]
4814    /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items or
4815    // an invalid `use foo::*;` was found, which can cause unbounded amounts of "item not found"
4816    // errors. We silence them all.
4817    fn should_report_errs(&self) -> bool {
4818        !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4819            && !self.r.glob_error.is_some()
4820    }
4821
4822    // Resolve in alternative namespaces if resolution in the primary namespace fails.
4823    fn resolve_qpath_anywhere(
4824        &mut self,
4825        qself: &Option<Box<QSelf>>,
4826        path: &[Segment],
4827        primary_ns: Namespace,
4828        defer_to_typeck: bool,
4829        finalize: Finalize,
4830        source: PathSource<'_, 'ast, 'ra>,
4831    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4832        let mut fin_res = None;
4833
4834        for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4835            if i == 0 || ns != primary_ns {
4836                match self.resolve_qpath(qself, path, ns, finalize, source)? {
4837                    Some(partial_res)
4838                        if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4839                    {
4840                        return Ok(Some(partial_res));
4841                    }
4842                    partial_res => {
4843                        if fin_res.is_none() {
4844                            fin_res = partial_res;
4845                        }
4846                    }
4847                }
4848            }
4849        }
4850
4851        if !(primary_ns != MacroNS) {
    ::core::panicking::panic("assertion failed: primary_ns != MacroNS")
};assert!(primary_ns != MacroNS);
4852        if qself.is_none()
4853            && let PathResult::NonModule(res) =
4854                self.r.cm().maybe_resolve_path(path, Some(MacroNS), &self.parent_scope, None)
4855        {
4856            return Ok(Some(res));
4857        }
4858
4859        Ok(fin_res)
4860    }
4861
4862    /// Handles paths that may refer to associated items.
4863    fn resolve_qpath(
4864        &mut self,
4865        qself: &Option<Box<QSelf>>,
4866        path: &[Segment],
4867        ns: Namespace,
4868        finalize: Finalize,
4869        source: PathSource<'_, 'ast, 'ra>,
4870    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4871        {
    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:4871",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(4871u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_qpath(qself={0:?}, path={1:?}, ns={2:?}, finalize={3:?})",
                                                    qself, path, ns, finalize) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
4872            "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4873            qself, path, ns, finalize,
4874        );
4875
4876        if let Some(qself) = qself {
4877            if qself.position == 0 {
4878                // This is a case like `<T>::B`, where there is no
4879                // trait to resolve. In that case, we leave the `B`
4880                // segment to be resolved by type-check.
4881                return Ok(Some(PartialRes::with_unresolved_segments(
4882                    Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4883                    path.len(),
4884                )));
4885            }
4886
4887            let num_privacy_errors = self.r.privacy_errors.len();
4888            // Make sure that `A` in `<T as A>::B::C` is a trait.
4889            let trait_res = self.smart_resolve_path_fragment(
4890                &None,
4891                &path[..qself.position],
4892                PathSource::Trait(AliasPossibility::No),
4893                Finalize::new(finalize.node_id, qself.path_span),
4894                RecordPartialRes::No,
4895                Some(&qself),
4896            );
4897
4898            if trait_res.expect_full_res() == Res::Err {
4899                return Ok(Some(trait_res));
4900            }
4901
4902            // Truncate additional privacy errors reported above,
4903            // because they'll be recomputed below.
4904            self.r.privacy_errors.truncate(num_privacy_errors);
4905
4906            // Make sure `A::B` in `<T as A>::B::C` is a trait item.
4907            //
4908            // Currently, `path` names the full item (`A::B::C`, in
4909            // our example). so we extract the prefix of that that is
4910            // the trait (the slice upto and including
4911            // `qself.position`). And then we recursively resolve that,
4912            // but with `qself` set to `None`.
4913            let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4914            let partial_res = self.smart_resolve_path_fragment(
4915                &None,
4916                &path[..=qself.position],
4917                PathSource::TraitItem(ns, &source),
4918                Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4919                RecordPartialRes::No,
4920                Some(&qself),
4921            );
4922
4923            // The remaining segments (the `C` in our example) will
4924            // have to be resolved by type-check, since that requires doing
4925            // trait resolution.
4926            return Ok(Some(PartialRes::with_unresolved_segments(
4927                partial_res.base_res(),
4928                partial_res.unresolved_segments() + path.len() - qself.position - 1,
4929            )));
4930        }
4931
4932        let result = match self.resolve_path(path, Some(ns), Some(finalize), source) {
4933            PathResult::NonModule(path_res) => path_res,
4934            PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4935                PartialRes::new(module.res().unwrap())
4936            }
4937            // A part of this path references a `mod` that had a parse error. To avoid resolution
4938            // errors for each reference to that module, we don't emit an error for them until the
4939            // `mod` is fixed. this can have a significant cascade effect.
4940            PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4941                PartialRes::new(Res::Err)
4942            }
4943            // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
4944            // don't report an error right away, but try to fallback to a primitive type.
4945            // So, we are still able to successfully resolve something like
4946            //
4947            // use std::u8; // bring module u8 in scope
4948            // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
4949            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
4950            //                     // not to nonexistent std::u8::max_value
4951            // }
4952            //
4953            // Such behavior is required for backward compatibility.
4954            // The same fallback is used when `a` resolves to nothing.
4955            PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4956                if (ns == TypeNS || path.len() > 1)
4957                    && PrimTy::from_name(path[0].ident.name).is_some() =>
4958            {
4959                let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4960                let tcx = self.r.tcx();
4961
4962                let gate_err_sym_msg = match prim {
4963                    PrimTy::Float(FloatTy::F16) if !self.r.features.f16() => {
4964                        Some((sym::f16, "the type `f16` is unstable"))
4965                    }
4966                    PrimTy::Float(FloatTy::F128) if !self.r.features.f128() => {
4967                        Some((sym::f128, "the type `f128` is unstable"))
4968                    }
4969                    _ => None,
4970                };
4971
4972                if let Some((sym, msg)) = gate_err_sym_msg {
4973                    let span = path[0].ident.span;
4974                    if !span.allows_unstable(sym) {
4975                        feature_err(tcx.sess, sym, span, msg).emit();
4976                    }
4977                };
4978
4979                // Fix up partial res of segment from `resolve_path` call.
4980                if let Some(id) = path[0].id {
4981                    self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
4982                }
4983
4984                PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
4985            }
4986            PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4987                PartialRes::new(module.res().unwrap())
4988            }
4989            PathResult::Failed {
4990                is_error_from_last_segment: false,
4991                span,
4992                label,
4993                suggestion,
4994                module,
4995                segment,
4996                error_implied_by_parse_error: _,
4997                message,
4998                note: _,
4999            } => {
5000                return Err(respan(
5001                    span,
5002                    ResolutionError::FailedToResolve {
5003                        segment: segment.name,
5004                        label,
5005                        suggestion,
5006                        module,
5007                        message,
5008                    },
5009                ));
5010            }
5011            PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
5012            PathResult::Indeterminate => ::rustc_middle::util::bug::bug_fmt(format_args!("indeterminate path result in resolve_qpath"))bug!("indeterminate path result in resolve_qpath"),
5013        };
5014
5015        Ok(Some(result))
5016    }
5017
5018    fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
5019        if let Some(label) = label {
5020            if label.ident.as_str().as_bytes()[1] != b'_' {
5021                self.diag_metadata.unused_labels.insert(id, label.ident.span);
5022            }
5023
5024            if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
5025                diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
5026            }
5027
5028            self.with_label_rib(RibKind::Normal, |this| {
5029                let ident = label.ident.normalize_to_macro_rules();
5030                this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
5031                f(this);
5032            });
5033        } else {
5034            f(self);
5035        }
5036    }
5037
5038    fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
5039        self.with_resolved_label(label, id, |this| this.visit_block(block));
5040    }
5041
5042    fn resolve_block(&mut self, block: &'ast Block) {
5043        {
    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:5043",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5043u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("(resolving block) entering block")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("(resolving block) entering block");
5044        // Move down in the graph, if there's an anonymous module rooted here.
5045        let orig_module = self.parent_scope.module;
5046        let anonymous_module = self.r.block_map.get(&block.id).copied();
5047
5048        let mut num_macro_definition_ribs = 0;
5049        if let Some(anonymous_module) = anonymous_module {
5050            {
    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:5050",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5050u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("(resolving block) found anonymous module, moving down")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("(resolving block) found anonymous module, moving down");
5051            self.ribs[ValueNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
5052            self.ribs[TypeNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
5053            self.parent_scope.module = anonymous_module.to_module();
5054        } else {
5055            self.ribs[ValueNS].push(Rib::new(RibKind::Block(None)));
5056        }
5057
5058        // Descend into the block.
5059        for stmt in &block.stmts {
5060            if let StmtKind::Item(ref item) = stmt.kind
5061                && let ItemKind::MacroDef(..) = item.kind
5062            {
5063                num_macro_definition_ribs += 1;
5064                let res = self.r.owner_def_id(item.id).to_def_id();
5065                self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
5066                self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
5067            }
5068
5069            self.visit_stmt(stmt);
5070        }
5071
5072        // Move back up.
5073        self.parent_scope.module = orig_module;
5074        for _ in 0..num_macro_definition_ribs {
5075            self.ribs[ValueNS].pop();
5076            self.label_ribs.pop();
5077        }
5078        self.last_block_rib = self.ribs[ValueNS].pop();
5079        if anonymous_module.is_some() {
5080            self.ribs[TypeNS].pop();
5081        }
5082        {
    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:5082",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5082u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("(resolving block) leaving block")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("(resolving block) leaving block");
5083    }
5084
5085    fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
5086        {
    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:5086",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5086u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_anon_const(constant: {0:?}, anon_const_kind: {1:?})",
                                                    constant, anon_const_kind) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
5087            "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
5088            constant, anon_const_kind
5089        );
5090
5091        let is_trivial_const_arg = constant.value.is_potential_trivial_const_arg();
5092        self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
5093            this.resolve_expr(&constant.value, None)
5094        })
5095    }
5096
5097    /// There are a few places that we need to resolve an anon const but we did not parse an
5098    /// anon const so cannot provide an `&'ast AnonConst`. Right now this is just unbraced
5099    /// const arguments that were parsed as type arguments, and `legacy_const_generics` which
5100    /// parse as normal function argument expressions. To avoid duplicating the code for resolving
5101    /// an anon const we have this function which lets the caller manually call `resolve_expr` or
5102    /// `smart_resolve_path`.
5103    fn resolve_anon_const_manual(
5104        &mut self,
5105        is_trivial_const_arg: bool,
5106        anon_const_kind: AnonConstKind,
5107        resolve_expr: impl FnOnce(&mut Self),
5108    ) {
5109        let is_repeat_expr = match anon_const_kind {
5110            AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
5111            _ => IsRepeatExpr::No,
5112        };
5113
5114        let may_use_generics = match anon_const_kind {
5115            AnonConstKind::EnumDiscriminant => {
5116                ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
5117            }
5118            AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
5119            AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
5120            AnonConstKind::ConstArg(_) => {
5121                if self.r.features.generic_const_exprs()
5122                    || self.r.features.min_generic_const_args()
5123                    || is_trivial_const_arg
5124                {
5125                    ConstantHasGenerics::Yes
5126                } else {
5127                    ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
5128                }
5129            }
5130        };
5131
5132        self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
5133            this.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
5134                resolve_expr(this);
5135            });
5136        });
5137    }
5138
5139    fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
5140        self.resolve_expr(&f.expr, Some(e));
5141        self.visit_ident(&f.ident);
5142        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());
5143    }
5144
5145    fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
5146        // First, record candidate traits for this expression if it could
5147        // result in the invocation of a method call.
5148
5149        self.record_candidate_traits_for_expr_if_necessary(expr);
5150
5151        // Next, resolve the node.
5152        match expr.kind {
5153            ExprKind::Path(ref qself, ref path) => {
5154                self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
5155                visit::walk_expr(self, expr);
5156            }
5157
5158            ExprKind::Struct(ref se) => {
5159                self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct(parent));
5160                // This is the same as `visit::walk_expr(self, expr);`, but we want to pass the
5161                // parent in for accurate suggestions when encountering `Foo { bar }` that should
5162                // have been `Foo { bar: self.bar }`.
5163                if let Some(qself) = &se.qself {
5164                    self.visit_ty(&qself.ty);
5165                }
5166                self.visit_path(&se.path);
5167                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);
5168                match &se.rest {
5169                    StructRest::Base(expr) => self.visit_expr(expr),
5170                    StructRest::Rest(_span) => {}
5171                    StructRest::None | StructRest::NoneWithError(_) => {}
5172                }
5173            }
5174
5175            ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
5176                match self.resolve_label(label.ident) {
5177                    Ok((node_id, _)) => {
5178                        // Since this res is a label, it is never read.
5179                        self.r.current_owner.label_res_map.insert(expr.id, node_id);
5180                        self.diag_metadata.unused_labels.swap_remove(&node_id);
5181                    }
5182                    Err(error) => {
5183                        self.report_error(label.ident.span, error);
5184                    }
5185                }
5186
5187                // visit `break` argument if any
5188                visit::walk_expr(self, expr);
5189            }
5190
5191            ExprKind::Break(None, Some(ref e)) => {
5192                // We use this instead of `visit::walk_expr` to keep the parent expr around for
5193                // better diagnostics.
5194                self.resolve_expr(e, Some(expr));
5195            }
5196
5197            ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
5198                self.visit_expr(scrutinee);
5199                self.resolve_pattern_top(pat, PatternSource::Let);
5200            }
5201
5202            ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
5203                self.visit_expr(scrutinee);
5204                // This is basically a tweaked, inlined `resolve_pattern_top`.
5205                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())];
5206                self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
5207                // We still collect the bindings in this `let` expression which is in
5208                // an invalid position (and therefore shouldn't declare variables into
5209                // its parent scope). To avoid unnecessary errors though, we do just
5210                // reassign the resolutions to `Res::Err`.
5211                for (_, bindings) in &mut bindings {
5212                    for (_, binding) in bindings {
5213                        *binding = Res::Err;
5214                    }
5215                }
5216                self.apply_pattern_bindings(bindings);
5217            }
5218
5219            ExprKind::If(ref cond, ref then, ref opt_else) => {
5220                self.with_rib(ValueNS, RibKind::Normal, |this| {
5221                    let old = this.diag_metadata.in_if_condition.replace(cond);
5222                    this.visit_expr(cond);
5223                    this.diag_metadata.in_if_condition = old;
5224                    this.visit_block(then);
5225                });
5226                if let Some(expr) = opt_else {
5227                    self.visit_expr(expr);
5228                }
5229            }
5230
5231            ExprKind::Loop(ref block, label, _) => {
5232                self.resolve_labeled_block(label, expr.id, block)
5233            }
5234
5235            ExprKind::While(ref cond, ref block, label) => {
5236                self.with_resolved_label(label, expr.id, |this| {
5237                    this.with_rib(ValueNS, RibKind::Normal, |this| {
5238                        let old = this.diag_metadata.in_if_condition.replace(cond);
5239                        this.visit_expr(cond);
5240                        this.diag_metadata.in_if_condition = old;
5241                        this.visit_block(block);
5242                    })
5243                });
5244            }
5245
5246            ExprKind::ForLoop(ForLoop { ref pat, ref iter, ref body, label, kind: _ }) => {
5247                self.visit_expr(iter);
5248                self.with_rib(ValueNS, RibKind::Normal, |this| {
5249                    this.resolve_pattern_top(pat, PatternSource::For);
5250                    this.resolve_labeled_block(label, expr.id, body);
5251                });
5252            }
5253
5254            ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
5255
5256            // Equivalent to `visit::walk_expr` + passing some context to children.
5257            ExprKind::Field(ref subexpression, _) => {
5258                self.resolve_expr(subexpression, Some(expr));
5259            }
5260            ExprKind::MethodCall(MethodCall { ref seg, ref receiver, ref args, .. }) => {
5261                self.resolve_expr(receiver, Some(expr));
5262                for arg in args {
5263                    self.resolve_expr(arg, None);
5264                }
5265                self.visit_path_segment(seg);
5266            }
5267
5268            ExprKind::Call(ref callee, ref arguments) => {
5269                self.resolve_expr(callee, Some(expr));
5270                let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
5271                for (idx, argument) in arguments.iter().enumerate() {
5272                    // Constant arguments need to be treated as AnonConst since
5273                    // that is how they will be later lowered to HIR.
5274                    if const_args.contains(&idx) {
5275                        // FIXME(mgca): legacy const generics doesn't support mgca but maybe
5276                        // that's okay.
5277                        let is_trivial_const_arg = argument.is_potential_trivial_const_arg();
5278                        self.resolve_anon_const_manual(
5279                            is_trivial_const_arg,
5280                            AnonConstKind::ConstArg(IsRepeatExpr::No),
5281                            |this| this.resolve_expr(argument, None),
5282                        );
5283                    } else {
5284                        self.resolve_expr(argument, None);
5285                    }
5286                }
5287            }
5288            ExprKind::Type(ref _type_expr, ref _ty) => {
5289                visit::walk_expr(self, expr);
5290            }
5291            // For closures, RibKind::FnOrCoroutine is added in visit_fn
5292            ExprKind::Closure(ast::Closure {
5293                binder: ClosureBinder::For { ref generic_params, span },
5294                ..
5295            }) => {
5296                self.with_generic_param_rib(
5297                    generic_params,
5298                    RibKind::Normal,
5299                    expr.id,
5300                    LifetimeBinderKind::Closure,
5301                    span,
5302                    |this| visit::walk_expr(this, expr),
5303                );
5304            }
5305            ExprKind::Closure(..) => visit::walk_expr(self, expr),
5306            ExprKind::Gen(..) => {
5307                self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
5308            }
5309            ExprKind::Repeat(ref elem, ref ct) => {
5310                self.visit_expr(elem);
5311                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
5312            }
5313            ExprKind::ConstBlock(ref ct) => {
5314                self.resolve_anon_const(ct, AnonConstKind::InlineConst);
5315            }
5316            ExprKind::Index(ref elem, ref idx, _) => {
5317                self.resolve_expr(elem, Some(expr));
5318                self.visit_expr(idx);
5319            }
5320            ExprKind::Assign(ref lhs, ref rhs, _) => {
5321                if !self.diag_metadata.is_assign_rhs {
5322                    self.diag_metadata.in_assignment = Some(expr);
5323                }
5324                self.visit_expr(lhs);
5325                self.diag_metadata.is_assign_rhs = true;
5326                self.diag_metadata.in_assignment = None;
5327                self.visit_expr(rhs);
5328                self.diag_metadata.is_assign_rhs = false;
5329            }
5330            ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
5331                self.diag_metadata.in_range = Some((start, end));
5332                self.resolve_expr(start, Some(expr));
5333                self.resolve_expr(end, Some(expr));
5334                self.diag_metadata.in_range = None;
5335            }
5336            _ => {
5337                visit::walk_expr(self, expr);
5338            }
5339        }
5340    }
5341
5342    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
5343        match expr.kind {
5344            ExprKind::Field(_, ident) => {
5345                // #6890: Even though you can't treat a method like a field,
5346                // we need to add any trait methods we find that match the
5347                // field name so that we can do some nice error reporting
5348                // later on in typeck.
5349                self.record_traits_in_scope(expr.id, ident);
5350            }
5351            ExprKind::MethodCall(ref call) => {
5352                {
    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:5352",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5352u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("(recording candidate traits for expr) recording traits for {0}",
                                                    expr.id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
5353                self.record_traits_in_scope(expr.id, call.seg.ident);
5354            }
5355            _ => {
5356                // Nothing to do.
5357            }
5358        }
5359    }
5360
5361    fn record_traits_in_scope(&mut self, node_id: NodeId, ident: Ident) {
5362        let traits = self.r.traits_in_scope(
5363            self.current_trait_ref.as_ref().map(|(module, _)| *module),
5364            &self.parent_scope,
5365            ident.span,
5366            Some((ident.name, ValueNS)),
5367        );
5368        self.r.current_owner.trait_map.insert(node_id, traits);
5369    }
5370
5371    fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
5372        // FIXME: This caching may be incorrect in case of multiple `macro_rules`
5373        // items with the same name in the same module.
5374        // Also hygiene is not considered.
5375        let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
5376        let res = *doc_link_resolutions
5377            .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5378            .or_default()
5379            .entry((Symbol::intern(path_str), ns))
5380            .or_insert_with_key(|(path, ns)| {
5381                let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
5382                if let Some(res) = res
5383                    && let Some(def_id) = res.opt_def_id()
5384                    && self.is_invalid_proc_macro_item_for_doc(def_id)
5385                {
5386                    // Encoding def ids in proc macro crate metadata will ICE,
5387                    // because it will only store proc macros for it.
5388                    return None;
5389                }
5390                res
5391            });
5392        self.r.doc_link_resolutions = doc_link_resolutions;
5393        res
5394    }
5395
5396    fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5397        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)
5398            || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5399        {
5400            return false;
5401        }
5402        let Some(local_did) = did.as_local() else { return true };
5403        !self.r.proc_macros.contains(&local_did)
5404    }
5405
5406    fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5407        match self.r.tcx.sess.opts.resolve_doc_links {
5408            ResolveDocLinks::None => return,
5409            ResolveDocLinks::ExportedMetadata
5410                if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5411                    || !maybe_exported.eval(self.r) =>
5412            {
5413                return;
5414            }
5415            ResolveDocLinks::Exported
5416                if !maybe_exported.eval(self.r)
5417                    && !rustdoc::has_primitive_or_keyword_or_attribute_docs(attrs) =>
5418            {
5419                return;
5420            }
5421            ResolveDocLinks::ExportedMetadata
5422            | ResolveDocLinks::Exported
5423            | ResolveDocLinks::All => {}
5424        }
5425
5426        if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5427            return;
5428        }
5429
5430        let mut need_traits_in_scope = false;
5431        for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5432            // Resolve all namespaces due to no disambiguator or for diagnostics.
5433            let mut any_resolved = false;
5434            let mut need_assoc = false;
5435            for ns in [TypeNS, ValueNS, MacroNS] {
5436                if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5437                    // Rustdoc ignores tool attribute resolutions and attempts
5438                    // to resolve their prefixes for diagnostics.
5439                    any_resolved = !#[allow(non_exhaustive_omitted_patterns)] match res {
    Res::NonMacroAttr(NonMacroAttrKind::Tool) => true,
    _ => false,
}matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5440                } else if ns != MacroNS {
5441                    need_assoc = true;
5442                }
5443            }
5444
5445            // Resolve all prefixes for type-relative resolution or for diagnostics.
5446            if need_assoc || !any_resolved {
5447                let mut path = &path_str[..];
5448                while let Some(idx) = path.rfind("::") {
5449                    path = &path[..idx];
5450                    need_traits_in_scope = true;
5451                    for ns in [TypeNS, ValueNS, MacroNS] {
5452                        self.resolve_and_cache_rustdoc_path(path, ns);
5453                    }
5454                }
5455            }
5456        }
5457
5458        if need_traits_in_scope {
5459            // FIXME: hygiene is not considered.
5460            let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5461            doc_link_traits_in_scope
5462                .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5463                .or_insert_with(|| {
5464                    self.r
5465                        .traits_in_scope(None, &self.parent_scope, DUMMY_SP, None)
5466                        .into_iter()
5467                        .filter_map(|tr| {
5468                            if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5469                                // Encoding def ids in proc macro crate metadata will ICE.
5470                                // because it will only store proc macros for it.
5471                                return None;
5472                            }
5473                            Some(tr.def_id)
5474                        })
5475                        .collect()
5476                });
5477            self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5478        }
5479    }
5480
5481    fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5482        // Don't lint on global paths because the user explicitly wrote out the full path.
5483        if let Some(seg) = path.first()
5484            && seg.ident.name == kw::PathRoot
5485        {
5486            return;
5487        }
5488
5489        if finalize.path_span.from_expansion()
5490            || path.iter().any(|seg| seg.ident.span.from_expansion())
5491        {
5492            return;
5493        }
5494
5495        let end_pos =
5496            path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5497        let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5498            // Preserve the current namespace for the final path segment, but use the type
5499            // namespace for all preceding segments
5500            //
5501            // e.g. for `std::env::args` check the `ValueNS` for `args` but the `TypeNS` for
5502            // `std` and `env`
5503            //
5504            // If the final path segment is beyond `end_pos` all the segments to check will
5505            // use the type namespace
5506            let ns = if i + 1 == path.len() { ns } else { TypeNS };
5507            let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5508            let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5509            (res == binding.res()).then_some((seg, binding))
5510        });
5511
5512        if let Some((seg, decl)) = unqualified {
5513            self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5514                decl,
5515                node_id: finalize.node_id,
5516                path_span: finalize.path_span,
5517                removal_span: path[0].ident.span.until(seg.ident.span),
5518            });
5519        }
5520    }
5521
5522    fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5523        if let Some(define_opaque) = define_opaque {
5524            for (id, path) in define_opaque {
5525                self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5526            }
5527        }
5528    }
5529
5530    fn resolve_eii(&mut self, eii_impl: Option<&EiiImpl>) {
5531        if let Some(EiiImpl { node_id, eii_macro_path, known_eii_macro_resolution, .. }) = eii_impl
5532        {
5533            // See docs on the `known_eii_macro_resolution` field:
5534            // if we already know the resolution statically, don't bother resolving it.
5535            if let Some(target) = known_eii_macro_resolution {
5536                self.smart_resolve_path(*node_id, &None, target, PathSource::ExternItemImpl);
5537            } else {
5538                self.smart_resolve_path(*node_id, &None, &eii_macro_path, PathSource::Macro);
5539            }
5540        }
5541    }
5542}
5543
5544/// Walks the whole crate in DFS order, visiting each item, counting the declared number of
5545/// lifetime generic parameters and function parameters. Also collects all `use` and
5546/// `extern crate` items so that `check_unused` doesn't need to walk the crate again.
5547struct ItemInfoCollector<'a, 'ast, 'ra, 'tcx> {
5548    r: &'a mut Resolver<'ra, 'tcx>,
5549    /// All `use` and `extern crate` items, in the order in which they are visited.
5550    use_items: Vec<&'ast Item>,
5551}
5552
5553impl ItemInfoCollector<'_, '_, '_, '_> {
5554    fn collect_fn_info(&mut self, decl: &FnDecl, id: NodeId) {
5555        self.r
5556            .delegation_fn_sigs
5557            .insert(self.r.owner_def_id(id), DelegationFnSig { has_self: decl.has_self() });
5558    }
5559}
5560
5561fn required_generic_args_suggestion(generics: &ast::Generics) -> Option<String> {
5562    let required = generics
5563        .params
5564        .iter()
5565        .filter_map(|param| match &param.kind {
5566            ast::GenericParamKind::Lifetime => Some("'_"),
5567            ast::GenericParamKind::Type { default } => {
5568                if default.is_none() {
5569                    Some("_")
5570                } else {
5571                    None
5572                }
5573            }
5574            ast::GenericParamKind::Const { default, .. } => {
5575                if default.is_none() {
5576                    Some("_")
5577                } else {
5578                    None
5579                }
5580            }
5581        })
5582        .collect::<Vec<_>>();
5583
5584    if required.is_empty() { None } else { Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>", required.join(", ")))
    })format!("<{}>", required.join(", "))) }
5585}
5586
5587impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, 'ast, '_, '_> {
5588    fn visit_item(&mut self, item: &'ast Item) {
5589        match &item.kind {
5590            ItemKind::TyAlias(TyAlias { generics, .. })
5591            | ItemKind::Const(ConstItem { generics, .. })
5592            | ItemKind::Fn(Fn { generics, .. })
5593            | ItemKind::Enum(_, generics, _)
5594            | ItemKind::Struct(_, generics, _)
5595            | ItemKind::Union(_, generics, _)
5596            | ItemKind::Impl(Impl { generics, .. })
5597            | ItemKind::Trait(Trait { generics, .. })
5598            | ItemKind::TraitAlias(TraitAlias { generics, .. }) => {
5599                if let ItemKind::Fn(Fn { sig, .. }) = &item.kind {
5600                    self.collect_fn_info(&sig.decl, item.id);
5601                }
5602
5603                let def_id = self.r.owner_def_id(item.id);
5604                let count = generics
5605                    .params
5606                    .iter()
5607                    .filter(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    ast::GenericParamKind::Lifetime { .. } => true,
    _ => false,
}matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5608                    .count();
5609                self.r.item_generics_num_lifetimes.insert(def_id, count);
5610            }
5611
5612            ItemKind::ForeignMod(ForeignMod { items, .. }) => {
5613                for foreign_item in items {
5614                    if let ForeignItemKind::Fn(Fn { sig, .. }) = &foreign_item.kind {
5615                        self.collect_fn_info(&sig.decl, foreign_item.id);
5616                    }
5617                }
5618            }
5619
5620            ItemKind::Use(..) | ItemKind::ExternCrate(..) => {
5621                self.use_items.push(item);
5622            }
5623
5624            ItemKind::Mod(..)
5625            | ItemKind::Static(..)
5626            | ItemKind::ConstBlock(..)
5627            | ItemKind::MacroDef(..)
5628            | ItemKind::GlobalAsm(..)
5629            | ItemKind::MacCall(..)
5630            | ItemKind::DelegationMac(..) => {}
5631            ItemKind::Delegation(..) => {
5632                // Delegated functions have lifetimes, their count is not necessarily zero.
5633                // But skipping the delegation items here doesn't mean that the count will be considered zero,
5634                // it means there will be a panic when retrieving the count,
5635                // but for delegation items we are never actually retrieving that count in practice.
5636            }
5637        }
5638        visit::walk_item(self, item)
5639    }
5640
5641    fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5642        if let AssocItemKind::Fn(Fn { sig, .. }) = &item.kind {
5643            self.collect_fn_info(&sig.decl, item.id);
5644        }
5645
5646        if let AssocItemKind::Type(ast::TyAlias { generics, .. }) = &item.kind {
5647            let def_id = self.r.owner_def_id(item.id);
5648            if let Some(suggestion) = required_generic_args_suggestion(generics) {
5649                self.r.item_required_generic_args_suggestions.insert(def_id, suggestion);
5650            }
5651        }
5652        visit::walk_assoc_item(self, item, ctxt);
5653    }
5654}
5655
5656impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5657    /// Returns the `use` and `extern crate` items of the crate, for use by `check_unused`.
5658    pub(crate) fn late_resolve_crate<'ast>(
5659        &mut self,
5660        krate: &'ast Crate,
5661    ) -> (Vec<&'ast Item>, Vec<UseError<'tcx>>) {
5662        with_owner(self, CRATE_NODE_ID, |this| {
5663            let mut info_collector = ItemInfoCollector { r: this, use_items: Vec::new() };
5664            visit::walk_crate(&mut info_collector, krate);
5665            let use_items = info_collector.use_items;
5666            let mut late_resolution_visitor = LateResolutionVisitor::new(this);
5667            late_resolution_visitor
5668                .resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5669            visit::walk_crate(&mut late_resolution_visitor, krate);
5670            let LateResolutionVisitor { use_injections, diag_metadata, .. } =
5671                late_resolution_visitor;
5672            for (id, span) in diag_metadata.unused_labels.iter() {
5673                this.lint_buffer.buffer_lint(
5674                    lint::builtin::UNUSED_LABELS,
5675                    *id,
5676                    *span,
5677                    crate::diagnostics::UnusedLabel,
5678                );
5679            }
5680            (use_items, use_injections)
5681        })
5682    }
5683}
5684
5685/// Check if definition matches a path
5686fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5687    let mut path = expected_path.iter().rev();
5688    while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5689        if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5690            return false;
5691        }
5692        def_id = parent;
5693    }
5694    true
5695}