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