Skip to main content

rustc_resolve/
late.rs

1// ignore-tidy-file-filelength
2//! "Late resolution" is the pass that resolves most of names in a crate beside imports and macros.
3//! It runs when the crate is fully expanded and its module structure is fully built.
4//! So it just walks through the crate and resolves all the expressions, types, etc.
5//!
6//! If you wonder why there's no `early.rs`, that's because it's split into three files -
7//! `build_reduced_graph.rs`, `macros.rs` and `imports.rs`.
8
9use std::borrow::Cow;
10use std::collections::hash_map::Entry;
11use std::debug_assert_matches;
12use std::mem::{replace, swap, take};
13use std::ops::{ControlFlow, Range};
14
15use rustc_ast::visit::{
16    AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor, try_visit, visit_opt, walk_list,
17};
18use rustc_ast::*;
19use rustc_data_structures::either::Either;
20use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
21use rustc_data_structures::unord::{UnordMap, UnordSet};
22use rustc_errors::codes::*;
23use rustc_errors::{
24    Applicability, Diag, DiagArgValue, Diagnostic, ErrorGuaranteed, IntoDiagArg, MultiSpan,
25    StashKey, Suggestions, elided_lifetime_in_path_suggestion, pluralize,
26};
27use rustc_hir::def::Namespace::{self, *};
28use rustc_hir::def::{CtorKind, DefKind, LifetimeRes, NonMacroAttrKind, PartialRes, PerNS};
29use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE, LocalDefId};
30use rustc_hir::{MissingLifetimeKind, PrimTy};
31use rustc_middle::middle::resolve_bound_vars::Set1;
32use rustc_middle::ty::{AssocTag, DelegationInfo, Visibility};
33use rustc_middle::{bug, span_bug};
34use rustc_session::config::{CrateType, ResolveDocLinks};
35use rustc_session::diagnostics::feature_err;
36use rustc_session::lint;
37use rustc_span::{BytePos, DUMMY_SP, Ident, Span, Spanned, Symbol, kw, respan, sym};
38use smallvec::{SmallVec, smallvec};
39use thin_vec::ThinVec;
40use tracing::{debug, instrument, trace};
41
42use crate::{
43    BindingError, BindingKey, Decl, DelegationFnSig, Finalize, IdentKey, LateDecl, LocalModule,
44    Module, ModuleOrUniformRoot, ParentScope, PathResult, Res, ResolutionError, Resolver, Segment,
45    Stage, TyCtxt, UseError, Used, path_names_to_string, rustdoc, with_owner,
46};
47
48mod diagnostics;
49
50use diagnostics::{ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime};
51
52#[derive(#[automatically_derived]
impl ::core::marker::Copy for BindingInfo { }Copy, #[automatically_derived]
impl ::core::clone::Clone for BindingInfo {
    #[inline]
    fn clone(&self) -> BindingInfo {
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<BindingMode>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for BindingInfo {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "BindingInfo",
            "span", &self.span, "annotation", &&self.annotation)
    }
}Debug)]
53struct BindingInfo {
54    span: Span,
55    annotation: BindingMode,
56}
57
58#[derive(#[automatically_derived]
impl ::core::marker::Copy for PatternSource { }Copy, #[automatically_derived]
impl ::core::clone::Clone for PatternSource {
    #[inline]
    fn clone(&self) -> PatternSource { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for PatternSource {
    #[inline]
    fn eq(&self, other: &PatternSource) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for PatternSource {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for PatternSource {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                PatternSource::Match => "Match",
                PatternSource::Let => "Let",
                PatternSource::For => "For",
                PatternSource::FnParam => "FnParam",
            })
    }
}Debug)]
59pub(crate) enum PatternSource {
60    Match,
61    Let,
62    For,
63    FnParam,
64}
65
66#[derive(#[automatically_derived]
impl ::core::marker::Copy for IsRepeatExpr { }Copy, #[automatically_derived]
impl ::core::clone::Clone for IsRepeatExpr {
    #[inline]
    fn clone(&self) -> IsRepeatExpr { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for IsRepeatExpr {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                IsRepeatExpr::No => "No",
                IsRepeatExpr::Yes => "Yes",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for IsRepeatExpr {
    #[inline]
    fn eq(&self, other: &IsRepeatExpr) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for IsRepeatExpr {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
67enum IsRepeatExpr {
68    No,
69    Yes,
70}
71
72struct IsNeverPattern;
73
74/// Describes whether an `AnonConst` is a type level const arg or
75/// some other form of anon const (i.e. inline consts or enum discriminants)
76#[derive(#[automatically_derived]
impl ::core::marker::Copy for AnonConstKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AnonConstKind {
    #[inline]
    fn clone(&self) -> AnonConstKind {
        let _: ::core::clone::AssertParamIsClone<IsRepeatExpr>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for AnonConstKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            AnonConstKind::EnumDiscriminant =>
                ::core::fmt::Formatter::write_str(f, "EnumDiscriminant"),
            AnonConstKind::FieldDefaultValue =>
                ::core::fmt::Formatter::write_str(f, "FieldDefaultValue"),
            AnonConstKind::InlineConst =>
                ::core::fmt::Formatter::write_str(f, "InlineConst"),
            AnonConstKind::ConstArg(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ConstArg", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for AnonConstKind {
    #[inline]
    fn eq(&self, other: &AnonConstKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (AnonConstKind::ConstArg(__self_0),
                    AnonConstKind::ConstArg(__arg1_0)) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AnonConstKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<IsRepeatExpr>;
    }
}Eq)]
77enum AnonConstKind {
78    EnumDiscriminant,
79    FieldDefaultValue,
80    InlineConst,
81    ConstArg(IsRepeatExpr),
82}
83
84impl PatternSource {
85    fn descr(self) -> &'static str {
86        match self {
87            PatternSource::Match => "match binding",
88            PatternSource::Let => "let binding",
89            PatternSource::For => "for binding",
90            PatternSource::FnParam => "function parameter",
91        }
92    }
93}
94
95impl IntoDiagArg for PatternSource {
96    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
97        DiagArgValue::Str(Cow::Borrowed(self.descr()))
98    }
99}
100
101/// Denotes whether the context for the set of already bound bindings is a `Product`
102/// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
103/// See those functions for more information.
104#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for PatBoundCtx {
    #[inline]
    fn eq(&self, other: &PatBoundCtx) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
105enum PatBoundCtx {
106    /// A product pattern context, e.g., `Variant(a, b)`.
107    Product,
108    /// An or-pattern context, e.g., `p_0 | ... | p_n`.
109    Or,
110}
111
112/// Tracks bindings resolved within a pattern. This serves two purposes:
113///
114/// - This tracks when identifiers are bound multiple times within a pattern. In a product context,
115///   this is an error. In an or-pattern, this lets us reuse the same resolution for each instance.
116///   See `fresh_binding` and `resolve_pattern_inner` for more information.
117///
118/// - The guard expression of a guard pattern may use bindings from within the guard pattern, but
119///   not from elsewhere in the pattern containing it. This allows us to isolate the bindings in the
120///   subpattern to construct the scope for the guard.
121///
122/// Each identifier must map to at most one distinct [`Res`].
123type PatternBindings = SmallVec<[(PatBoundCtx, FxIndexMap<Ident, Res>); 1]>;
124
125/// Does this the item (from the item rib scope) allow generic parameters?
126#[derive(#[automatically_derived]
impl ::core::marker::Copy for HasGenericParams { }Copy, #[automatically_derived]
impl ::core::clone::Clone for HasGenericParams {
    #[inline]
    fn clone(&self) -> HasGenericParams {
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for HasGenericParams {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            HasGenericParams::Yes(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Yes",
                    &__self_0),
            HasGenericParams::No =>
                ::core::fmt::Formatter::write_str(f, "No"),
        }
    }
}Debug)]
127pub(crate) enum HasGenericParams {
128    Yes(Span),
129    No,
130}
131
132/// May this constant have generics?
133#[derive(#[automatically_derived]
impl ::core::marker::Copy for ConstantHasGenerics { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ConstantHasGenerics {
    #[inline]
    fn clone(&self) -> ConstantHasGenerics {
        let _: ::core::clone::AssertParamIsClone<NoConstantGenericsReason>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ConstantHasGenerics {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ConstantHasGenerics::Yes =>
                ::core::fmt::Formatter::write_str(f, "Yes"),
            ConstantHasGenerics::No(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "No",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for ConstantHasGenerics {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<NoConstantGenericsReason>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for ConstantHasGenerics {
    #[inline]
    fn eq(&self, other: &ConstantHasGenerics) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (ConstantHasGenerics::No(__self_0),
                    ConstantHasGenerics::No(__arg1_0)) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
134pub(crate) enum ConstantHasGenerics {
135    Yes,
136    No(NoConstantGenericsReason),
137}
138
139impl ConstantHasGenerics {
140    fn force_yes_if(self, b: bool) -> Self {
141        if b { Self::Yes } else { self }
142    }
143}
144
145/// Reason for why an anon const is not allowed to reference generic parameters
146#[derive(#[automatically_derived]
impl ::core::marker::Copy for NoConstantGenericsReason { }Copy, #[automatically_derived]
impl ::core::clone::Clone for NoConstantGenericsReason {
    #[inline]
    fn clone(&self) -> NoConstantGenericsReason { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for NoConstantGenericsReason {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                NoConstantGenericsReason::NonTrivialConstArg =>
                    "NonTrivialConstArg",
                NoConstantGenericsReason::IsEnumDiscriminant =>
                    "IsEnumDiscriminant",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for NoConstantGenericsReason {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for NoConstantGenericsReason {
    #[inline]
    fn eq(&self, other: &NoConstantGenericsReason) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
147pub(crate) enum NoConstantGenericsReason {
148    /// Const arguments are only allowed to use generic parameters when:
149    /// - `feature(generic_const_exprs)` is enabled
150    /// or
151    /// - the const argument is a sole const generic parameter, i.e. `foo::<{ N }>()`
152    ///
153    /// If neither of the above are true then this is used as the cause.
154    NonTrivialConstArg,
155    /// Enum discriminants are not allowed to reference generic parameters ever, this
156    /// is used when an anon const is in the following position:
157    ///
158    /// ```rust,compile_fail
159    /// enum Foo<const N: isize> {
160    ///     Variant = { N }, // this anon const is not allowed to use generics
161    /// }
162    /// ```
163    IsEnumDiscriminant,
164}
165
166#[derive(#[automatically_derived]
impl ::core::marker::Copy for ConstantItemKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ConstantItemKind {
    #[inline]
    fn clone(&self) -> ConstantItemKind { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ConstantItemKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ConstantItemKind::Const => "Const",
                ConstantItemKind::Static => "Static",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for ConstantItemKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for ConstantItemKind {
    #[inline]
    fn eq(&self, other: &ConstantItemKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
167pub(crate) enum ConstantItemKind {
168    Const,
169    Static,
170}
171
172impl ConstantItemKind {
173    pub(crate) fn as_str(&self) -> &'static str {
174        match self {
175            Self::Const => "const",
176            Self::Static => "static",
177        }
178    }
179}
180
181#[derive(#[automatically_derived]
impl ::core::fmt::Debug for RecordPartialRes {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                RecordPartialRes::Yes => "Yes",
                RecordPartialRes::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for RecordPartialRes { }Copy, #[automatically_derived]
impl ::core::clone::Clone for RecordPartialRes {
    #[inline]
    fn clone(&self) -> RecordPartialRes { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for RecordPartialRes {
    #[inline]
    fn eq(&self, other: &RecordPartialRes) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for RecordPartialRes {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
182enum RecordPartialRes {
183    Yes,
184    No,
185}
186
187/// The rib kind restricts certain accesses,
188/// e.g. to a `Res::Local` of an outer item.
189#[derive(#[automatically_derived]
impl<'ra> ::core::marker::Copy for RibKind<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::clone::Clone for RibKind<'ra> {
    #[inline]
    fn clone(&self) -> RibKind<'ra> {
        let _: ::core::clone::AssertParamIsClone<Option<LocalModule<'ra>>>;
        let _: ::core::clone::AssertParamIsClone<HasGenericParams>;
        let _: ::core::clone::AssertParamIsClone<DefKind>;
        let _: ::core::clone::AssertParamIsClone<ConstantHasGenerics>;
        let _:
                ::core::clone::AssertParamIsClone<Option<(Ident,
                ConstantItemKind)>>;
        let _: ::core::clone::AssertParamIsClone<LocalModule<'ra>>;
        let _: ::core::clone::AssertParamIsClone<DefId>;
        let _:
                ::core::clone::AssertParamIsClone<ForwardGenericParamBanReason>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for RibKind<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            RibKind::Normal => ::core::fmt::Formatter::write_str(f, "Normal"),
            RibKind::Block(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Block",
                    &__self_0),
            RibKind::AssocItem =>
                ::core::fmt::Formatter::write_str(f, "AssocItem"),
            RibKind::FnOrCoroutine =>
                ::core::fmt::Formatter::write_str(f, "FnOrCoroutine"),
            RibKind::Item(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Item",
                    __self_0, &__self_1),
            RibKind::ConstantItem(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "ConstantItem", __self_0, &__self_1),
            RibKind::Module(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Module",
                    &__self_0),
            RibKind::MacroDefinition(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "MacroDefinition", &__self_0),
            RibKind::ForwardGenericParamBan(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ForwardGenericParamBan", &__self_0),
            RibKind::ConstParamTy =>
                ::core::fmt::Formatter::write_str(f, "ConstParamTy"),
            RibKind::InlineAsmSym =>
                ::core::fmt::Formatter::write_str(f, "InlineAsmSym"),
        }
    }
}Debug)]
190pub(crate) enum RibKind<'ra> {
191    /// No restriction needs to be applied.
192    Normal,
193
194    /// We passed through an `ast::Block`.
195    /// Behaves like `Normal`, but also partially like `Module` if the block contains items.
196    /// `Block(None)` must be always processed in the same way as `Block(Some(module))`
197    /// with empty `module`. The module can be `None` only because creation of some definitely
198    /// empty modules is skipped as an optimization.
199    Block(Option<LocalModule<'ra>>),
200
201    /// We passed through an impl or trait and are now in one of its
202    /// methods or associated types. Allow references to ty params that impl or trait
203    /// binds. Disallow any other upvars (including other ty params that are
204    /// upvars).
205    AssocItem,
206
207    /// We passed through a function, closure or coroutine signature. Disallow labels.
208    FnOrCoroutine,
209
210    /// We passed through an item scope. Disallow upvars.
211    Item(HasGenericParams, DefKind),
212
213    /// We're in a constant item. Can't refer to dynamic stuff.
214    ///
215    /// The item may reference generic parameters in trivial constant expressions.
216    /// All other constants aren't allowed to use generic params at all.
217    ConstantItem(ConstantHasGenerics, Option<(Ident, ConstantItemKind)>),
218
219    /// We passed through a module item.
220    Module(LocalModule<'ra>),
221
222    /// We passed through a `macro_rules!` statement
223    MacroDefinition(DefId),
224
225    /// All bindings in this rib are generic parameters that can't be used
226    /// from the default of a generic parameter because they're not declared
227    /// before said generic parameter. Also see the `visit_generics` override.
228    ForwardGenericParamBan(ForwardGenericParamBanReason),
229
230    /// We are inside of the type of a const parameter. Can't refer to any
231    /// parameters.
232    ConstParamTy,
233
234    /// We are inside a `sym` inline assembly operand. Can only refer to
235    /// globals.
236    InlineAsmSym,
237}
238
239#[derive(#[automatically_derived]
impl ::core::marker::Copy for ForwardGenericParamBanReason { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ForwardGenericParamBanReason {
    #[inline]
    fn clone(&self) -> ForwardGenericParamBanReason { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ForwardGenericParamBanReason {
    #[inline]
    fn eq(&self, other: &ForwardGenericParamBanReason) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ForwardGenericParamBanReason {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for ForwardGenericParamBanReason {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ForwardGenericParamBanReason::Default => "Default",
                ForwardGenericParamBanReason::ConstParamTy => "ConstParamTy",
            })
    }
}Debug)]
240pub(crate) enum ForwardGenericParamBanReason {
241    Default,
242    ConstParamTy,
243}
244
245impl RibKind<'_> {
246    /// Whether this rib kind contains generic parameters, as opposed to local
247    /// variables.
248    pub(crate) fn contains_params(&self) -> bool {
249        match self {
250            RibKind::Normal
251            | RibKind::Block(..)
252            | RibKind::FnOrCoroutine
253            | RibKind::ConstantItem(..)
254            | RibKind::Module(_)
255            | RibKind::MacroDefinition(_)
256            | RibKind::InlineAsmSym => false,
257            RibKind::ConstParamTy
258            | RibKind::AssocItem
259            | RibKind::Item(..)
260            | RibKind::ForwardGenericParamBan(_) => true,
261        }
262    }
263
264    /// This rib forbids referring to labels defined in upwards ribs.
265    fn is_label_barrier(self) -> bool {
266        match self {
267            RibKind::Normal | RibKind::MacroDefinition(..) => false,
268            RibKind::FnOrCoroutine | RibKind::ConstantItem(..) => true,
269            kind => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected rib kind: {0:?}",
        kind))bug!("unexpected rib kind: {kind:?}"),
270        }
271    }
272}
273
274/// A single local scope.
275///
276/// A rib represents a scope names can live in. Note that these appear in many places, not just
277/// around braces. At any place where the list of accessible names (of the given namespace)
278/// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
279/// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
280/// etc.
281///
282/// Different [rib kinds](enum@RibKind) are transparent for different names.
283///
284/// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
285/// resolving, the name is looked up from inside out.
286#[derive(#[automatically_derived]
impl<'ra, R: ::core::fmt::Debug> ::core::fmt::Debug for Rib<'ra, R> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "Rib",
            "bindings", &self.bindings, "patterns_with_skipped_bindings",
            &self.patterns_with_skipped_bindings, "kind", &&self.kind)
    }
}Debug)]
287pub(crate) struct Rib<'ra, R = Res> {
288    pub bindings: FxIndexMap<Ident, R>,
289    pub patterns_with_skipped_bindings: UnordMap<DefId, Vec<(Span, Result<(), ErrorGuaranteed>)>>,
290    pub kind: RibKind<'ra>,
291}
292
293impl<'ra, R> Rib<'ra, R> {
294    fn new(kind: RibKind<'ra>) -> Rib<'ra, R> {
295        Rib {
296            bindings: Default::default(),
297            patterns_with_skipped_bindings: Default::default(),
298            kind,
299        }
300    }
301}
302
303#[derive(#[automatically_derived]
impl ::core::clone::Clone for LifetimeUseSet {
    #[inline]
    fn clone(&self) -> LifetimeUseSet {
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<visit::LifetimeCtxt>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for LifetimeUseSet { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for LifetimeUseSet {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LifetimeUseSet::One { use_span: __self_0, use_ctxt: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f, "One",
                    "use_span", __self_0, "use_ctxt", &__self_1),
            LifetimeUseSet::Many =>
                ::core::fmt::Formatter::write_str(f, "Many"),
        }
    }
}Debug)]
304enum LifetimeUseSet {
305    One { use_span: Span, use_ctxt: visit::LifetimeCtxt },
306    Many,
307}
308
309#[derive(#[automatically_derived]
impl ::core::marker::Copy for LifetimeRibKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for LifetimeRibKind {
    #[inline]
    fn clone(&self) -> LifetimeRibKind {
        let _: ::core::clone::AssertParamIsClone<NodeId>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<LifetimeBinderKind>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<LifetimeRes>;
        let _: ::core::clone::AssertParamIsClone<NoConstantGenericsReason>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for LifetimeRibKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LifetimeRibKind::Generics {
                binder: __self_0, span: __self_1, kind: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "Generics", "binder", __self_0, "span", __self_1, "kind",
                    &__self_2),
            LifetimeRibKind::AnonymousCreateParameter {
                binder: __self_0, report_in_path: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "AnonymousCreateParameter", "binder", __self_0,
                    "report_in_path", &__self_1),
            LifetimeRibKind::Elided { res: __self_0, error_in_path: __self_1 }
                =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Elided", "res", __self_0, "error_in_path", &__self_1),
            LifetimeRibKind::AnonymousReportError =>
                ::core::fmt::Formatter::write_str(f, "AnonymousReportError"),
            LifetimeRibKind::ElisionFailure =>
                ::core::fmt::Formatter::write_str(f, "ElisionFailure"),
            LifetimeRibKind::ConstParamTy =>
                ::core::fmt::Formatter::write_str(f, "ConstParamTy"),
            LifetimeRibKind::ConcreteAnonConst(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ConcreteAnonConst", &__self_0),
            LifetimeRibKind::Item =>
                ::core::fmt::Formatter::write_str(f, "Item"),
            LifetimeRibKind::ImplTrait =>
                ::core::fmt::Formatter::write_str(f, "ImplTrait"),
        }
    }
}Debug)]
310enum LifetimeRibKind {
311    // -- Ribs introducing named lifetimes
312    //
313    /// This rib declares generic parameters.
314    /// Only for this kind the `LifetimeRib::bindings` field can be non-empty.
315    Generics { binder: NodeId, span: Span, kind: LifetimeBinderKind },
316
317    // -- Ribs introducing unnamed lifetimes
318    //
319    /// Create a new anonymous lifetime parameter and reference it.
320    ///
321    /// If `report_in_path`, report an error when encountering lifetime elision in a path:
322    /// ```compile_fail
323    /// struct Foo<'a> { x: &'a () }
324    /// async fn foo(x: Foo) {}
325    /// ```
326    ///
327    /// Note: the error should not trigger when the elided lifetime is in a pattern or
328    /// expression-position path:
329    /// ```
330    /// struct Foo<'a> { x: &'a () }
331    /// async fn foo(Foo { x: _ }: Foo<'_>) {}
332    /// ```
333    AnonymousCreateParameter { binder: NodeId, report_in_path: bool },
334
335    /// Replace all anonymous lifetimes by provided lifetime.
336    Elided {
337        res: LifetimeRes,
338        /// Always report those lifetimes as an error if in a path
339        error_in_path: bool,
340    },
341
342    // -- Barrier ribs that stop lifetime lookup, or continue it but produce an error later.
343    //
344    /// Give a hard error when either `&` or `'_` is written. Used to
345    /// rule out things like `where T: Foo<'_>`. Does not imply an
346    /// error on default object bounds (e.g., `Box<dyn Foo>`).
347    AnonymousReportError,
348
349    /// Signal we cannot find which should be the anonymous lifetime.
350    ElisionFailure,
351
352    /// This rib forbids usage of generic parameters inside of const parameter types.
353    ///
354    /// While this is desirable to support eventually, it is difficult to do and so is
355    /// currently forbidden. See rust-lang/project-const-generics#28 for more info.
356    ConstParamTy,
357
358    /// Usage of generic parameters is forbidden in various positions for anon consts:
359    /// - const arguments when `generic_const_exprs` is not enabled
360    /// - enum discriminant values
361    ///
362    /// This rib emits an error when a lifetime would resolve to a lifetime parameter.
363    ConcreteAnonConst(NoConstantGenericsReason),
364
365    /// This rib acts as a barrier to forbid reference to lifetimes of a parent item.
366    Item,
367
368    /// Lifetimes cannot be elided in `impl Trait` types without `#![feature(anonymous_lifetime_in_impl_trait)]`.
369    ImplTrait,
370}
371impl LifetimeRibKind {
372    /// Convenience function for creating non-erroring `Elided` variants.
373    fn elided(res: LifetimeRes) -> LifetimeRibKind {
374        LifetimeRibKind::Elided { res, error_in_path: false }
375    }
376}
377
378#[derive(#[automatically_derived]
impl ::core::marker::Copy for LifetimeBinderKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for LifetimeBinderKind {
    #[inline]
    fn clone(&self) -> LifetimeBinderKind { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for LifetimeBinderKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                LifetimeBinderKind::FnPtrType => "FnPtrType",
                LifetimeBinderKind::PolyTrait => "PolyTrait",
                LifetimeBinderKind::WhereBound => "WhereBound",
                LifetimeBinderKind::Item => "Item",
                LifetimeBinderKind::ConstItem => "ConstItem",
                LifetimeBinderKind::Function => "Function",
                LifetimeBinderKind::Closure => "Closure",
                LifetimeBinderKind::ImplBlock => "ImplBlock",
                LifetimeBinderKind::ImplAssocType => "ImplAssocType",
            })
    }
}Debug)]
379enum LifetimeBinderKind {
380    FnPtrType,
381    PolyTrait,
382    WhereBound,
383    // Item covers foreign items, ADTs, type aliases, trait associated items and
384    // trait alias associated items.
385    Item,
386    ConstItem,
387    Function,
388    Closure,
389    ImplBlock,
390    // Covers only `impl` associated types.
391    ImplAssocType,
392}
393
394impl LifetimeBinderKind {
395    fn descr(self) -> &'static str {
396        use LifetimeBinderKind::*;
397        match self {
398            FnPtrType => "type",
399            PolyTrait => "bound",
400            WhereBound => "bound",
401            Item | ConstItem => "item",
402            ImplAssocType => "associated type",
403            ImplBlock => "impl block",
404            Function => "function",
405            Closure => "closure",
406        }
407    }
408}
409
410#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LifetimeRib {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "LifetimeRib",
            "kind", &self.kind, "bindings", &&self.bindings)
    }
}Debug)]
411struct LifetimeRib {
412    kind: LifetimeRibKind,
413    // We need to preserve insertion order for async fns.
414    bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
415}
416
417impl LifetimeRib {
418    fn new(kind: LifetimeRibKind) -> LifetimeRib {
419        LifetimeRib { bindings: Default::default(), kind }
420    }
421}
422
423#[derive(#[automatically_derived]
impl ::core::marker::Copy for AliasPossibility { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AliasPossibility {
    #[inline]
    fn clone(&self) -> AliasPossibility { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for AliasPossibility {
    #[inline]
    fn eq(&self, other: &AliasPossibility) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AliasPossibility {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for AliasPossibility {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                AliasPossibility::No => "No",
                AliasPossibility::Maybe => "Maybe",
            })
    }
}Debug)]
424pub(crate) enum AliasPossibility {
425    No,
426    Maybe,
427}
428
429/// Whether resolving `impl` or `mut` restriction paths
430#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ResolvingRestrictionKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ResolvingRestrictionKind::Impl => "Impl",
                ResolvingRestrictionKind::Mut => "Mut",
            })
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for ResolvingRestrictionKind {
    #[inline]
    fn clone(&self) -> ResolvingRestrictionKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ResolvingRestrictionKind { }Copy)]
431pub(crate) enum ResolvingRestrictionKind {
432    Impl,
433    Mut,
434}
435
436impl IntoDiagArg for ResolvingRestrictionKind {
437    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
438        use std::borrow::Cow;
439        match self {
440            ResolvingRestrictionKind::Impl => DiagArgValue::Str(Cow::Borrowed("impl")),
441            ResolvingRestrictionKind::Mut => DiagArgValue::Str(Cow::Borrowed("mut")),
442        }
443    }
444}
445
446#[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)]
447pub(crate) enum PathSource<'a, 'ast, 'ra> {
448    /// Type paths `Path`.
449    Type,
450    /// Trait paths in bounds or impls.
451    Trait(AliasPossibility),
452    /// Expression paths `path`, with optional parent context.
453    Expr(Option<&'ast Expr>),
454    /// Paths in path patterns `Path`.
455    Pat,
456    /// Paths in struct expressions and patterns `Path { .. }`.
457    Struct(Option<&'a Expr>),
458    /// Paths in tuple struct patterns `Path(..)`.
459    TupleStruct(Span, &'ra [Span]),
460    /// `m::A::B` in `<T as m::A>::B::C`.
461    ///
462    /// Second field holds the "cause" of this one, i.e. the context within
463    /// which the trait item is resolved. Used for diagnostics.
464    TraitItem(Namespace, &'a PathSource<'a, 'ast, 'ra>),
465    /// Paths in delegation item
466    Delegation,
467    /// Paths in externally implementable item declarations.
468    ExternItemImpl,
469    /// An arg in a `use<'a, N>` precise-capturing bound.
470    PreciseCapturingArg(Namespace),
471    /// Paths that end with `(..)`, for return type notation.
472    ReturnTypeNotation,
473    /// Paths from `#[define_opaque]` attributes
474    DefineOpaques,
475    /// Resolving a macro
476    Macro,
477    /// Paths for module or crate root. Used for restrictions.
478    Module,
479}
480
481impl PathSource<'_, '_, '_> {
482    fn namespace(self) -> Namespace {
483        match self {
484            PathSource::Type
485            | PathSource::Trait(_)
486            | PathSource::Struct(_)
487            | PathSource::DefineOpaques
488            | PathSource::Module => TypeNS,
489            PathSource::Expr(..)
490            | PathSource::Pat
491            | PathSource::TupleStruct(..)
492            | PathSource::Delegation
493            | PathSource::ExternItemImpl
494            | PathSource::ReturnTypeNotation => ValueNS,
495            PathSource::TraitItem(ns, _) => ns,
496            PathSource::PreciseCapturingArg(ns) => ns,
497            PathSource::Macro => MacroNS,
498        }
499    }
500
501    fn defer_to_typeck(self) -> bool {
502        match self {
503            PathSource::Type
504            | PathSource::Expr(..)
505            | PathSource::Pat
506            | PathSource::Struct(_)
507            | PathSource::TupleStruct(..)
508            | PathSource::ReturnTypeNotation => true,
509            PathSource::Trait(_)
510            | PathSource::TraitItem(..)
511            | PathSource::DefineOpaques
512            | PathSource::Delegation
513            | PathSource::ExternItemImpl
514            | PathSource::PreciseCapturingArg(..)
515            | PathSource::Macro
516            | PathSource::Module => false,
517        }
518    }
519
520    fn descr_expected(self) -> &'static str {
521        match &self {
522            PathSource::DefineOpaques => "type alias or associated type with opaqaue types",
523            PathSource::Type => "type",
524            PathSource::Trait(_) => "trait",
525            PathSource::Pat => "unit struct, unit variant or constant",
526            PathSource::Struct(_) => "struct, variant or union type",
527            PathSource::TraitItem(ValueNS, PathSource::TupleStruct(..))
528            | PathSource::TupleStruct(..) => "tuple struct or tuple variant",
529            PathSource::TraitItem(ns, _) => match ns {
530                TypeNS => "associated type",
531                ValueNS => "method or associated constant",
532                MacroNS => ::rustc_middle::util::bug::bug_fmt(format_args!("associated macro"))bug!("associated macro"),
533            },
534            PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
535                // "function" here means "anything callable" rather than `DefKind::Fn`,
536                // this is not precise but usually more helpful than just "value".
537                Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
538                    // the case of `::some_crate()`
539                    ExprKind::Path(_, path)
540                        if let [segment, _] = path.segments.as_slice()
541                            && segment.ident.name == kw::PathRoot =>
542                    {
543                        "external crate"
544                    }
545                    ExprKind::Path(_, path)
546                        if let Some(segment) = path.segments.last()
547                            && let Some(c) = segment.ident.to_string().chars().next()
548                            && c.is_uppercase() =>
549                    {
550                        "function, tuple struct or tuple variant"
551                    }
552                    _ => "function",
553                },
554                _ => "value",
555            },
556            PathSource::ReturnTypeNotation | PathSource::Delegation => "function",
557            PathSource::ExternItemImpl => "function or static",
558            PathSource::PreciseCapturingArg(..) => "type or const parameter",
559            PathSource::Macro => "macro",
560            PathSource::Module => "module",
561        }
562    }
563
564    fn is_call(self) -> bool {
565        #[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(..), .. })))
566    }
567
568    pub(crate) fn is_expected(self, res: Res) -> bool {
569        match self {
570            PathSource::DefineOpaques => {
571                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum |
        DefKind::TyAlias | DefKind::AssocTy, _) | Res::SelfTyAlias { .. } =>
        true,
    _ => false,
}matches!(
572                    res,
573                    Res::Def(
574                        DefKind::Struct
575                            | DefKind::Union
576                            | DefKind::Enum
577                            | DefKind::TyAlias
578                            | DefKind::AssocTy,
579                        _
580                    ) | Res::SelfTyAlias { .. }
581                )
582            }
583            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!(
584                res,
585                Res::Def(
586                    DefKind::Struct
587                        | DefKind::Union
588                        | DefKind::Enum
589                        | DefKind::Trait
590                        | DefKind::TraitAlias
591                        | DefKind::TyAlias
592                        | DefKind::AssocTy
593                        | DefKind::TyParam
594                        | DefKind::OpaqueTy
595                        | DefKind::ForeignTy,
596                    _,
597                ) | Res::PrimTy(..)
598                    | Res::SelfTyParam { .. }
599                    | Res::SelfTyAlias { .. }
600            ),
601            PathSource::Trait(AliasPossibility::No) => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Trait, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Trait, _)),
602            PathSource::Trait(AliasPossibility::Maybe) => {
603                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
604            }
605            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!(
606                res,
607                Res::Def(
608                    DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
609                        | DefKind::Const { .. }
610                        | DefKind::Static { .. }
611                        | DefKind::Fn
612                        | DefKind::AssocFn
613                        | DefKind::AssocConst { .. }
614                        | DefKind::ConstParam,
615                    _,
616                ) | Res::Local(..)
617                    | Res::SelfCtor(..)
618            ),
619            PathSource::Pat => {
620                res.expected_in_unit_struct_pat()
621                    || #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Const { .. } | DefKind::AssocConst { .. }, _) => true,
    _ => false,
}matches!(
622                        res,
623                        Res::Def(DefKind::Const { .. } | DefKind::AssocConst { .. }, _)
624                    )
625            }
626            PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
627            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!(
628                res,
629                Res::Def(
630                    DefKind::Struct
631                        | DefKind::Union
632                        | DefKind::Variant
633                        | DefKind::TyAlias
634                        | DefKind::AssocTy,
635                    _,
636                ) | Res::SelfTyParam { .. }
637                    | Res::SelfTyAlias { .. }
638            ),
639            PathSource::TraitItem(ns, _) => match res {
640                Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn, _) if ns == ValueNS => true,
641                Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
642                _ => false,
643            },
644            PathSource::ReturnTypeNotation => match res {
645                Res::Def(DefKind::AssocFn, _) => true,
646                _ => false,
647            },
648            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, _)),
649            PathSource::ExternItemImpl => {
650                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) |
        DefKind::Static { .. }, _) => true,
    _ => false,
}matches!(
651                    res,
652                    Res::Def(
653                        DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::Static { .. },
654                        _
655                    )
656                )
657            }
658            PathSource::PreciseCapturingArg(ValueNS) => {
659                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::ConstParam, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::ConstParam, _))
660            }
661            // We allow `SelfTyAlias` here so we can give a more descriptive error later.
662            PathSource::PreciseCapturingArg(TypeNS) => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } |
        Res::SelfTyAlias { .. } => true,
    _ => false,
}matches!(
663                res,
664                Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }
665            ),
666            PathSource::PreciseCapturingArg(MacroNS) => false,
667            PathSource::Macro => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Macro(_), _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Macro(_), _)),
668            PathSource::Module => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Mod, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Mod, _)),
669        }
670    }
671
672    fn error_code(self, has_unexpected_resolution: bool) -> ErrCode {
673        match (self, has_unexpected_resolution) {
674            (PathSource::Trait(_), true) => E0404,
675            (PathSource::Trait(_), false) => E0405,
676            (PathSource::Type | PathSource::DefineOpaques, true) => E0573,
677            (PathSource::Type | PathSource::DefineOpaques, false) => E0425,
678            (PathSource::Struct(_), true) => E0574,
679            (PathSource::Struct(_), false) => E0422,
680            (PathSource::Expr(..), true)
681            | (PathSource::Delegation, true)
682            | (PathSource::ExternItemImpl, true) => E0423,
683            (PathSource::Expr(..), false)
684            | (PathSource::Delegation, false)
685            | (PathSource::ExternItemImpl, false) => E0425,
686            (PathSource::Pat | PathSource::TupleStruct(..), true) => E0532,
687            (PathSource::Pat | PathSource::TupleStruct(..), false) => E0531,
688            (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, true) => E0575,
689            (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, false) => E0576,
690            (PathSource::PreciseCapturingArg(..), true) => E0799,
691            (PathSource::PreciseCapturingArg(..), false) => E0800,
692            (PathSource::Macro, _) => E0425,
693            // FIXME: There is no dedicated error code for this case yet.
694            // E0577 already covers the same situation for visibilities,
695            // so we reuse it here for now. It may make sense to generalize
696            // it for restrictions in the future.
697            (PathSource::Module, true) => E0577,
698            (PathSource::Module, false) => E0433,
699        }
700    }
701}
702
703/// At this point for most items we can answer whether that item is exported or not,
704/// but some items like impls require type information to determine exported-ness, so we make a
705/// conservative estimate for them (e.g. based on nominal visibility).
706#[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)]
707enum MaybeExported<'a> {
708    Ok(NodeId),
709    Impl(Option<DefId>),
710    ImplItem(Result<DefId, &'a ast::Visibility>),
711    NestedUse(&'a ast::Visibility),
712}
713
714impl MaybeExported<'_> {
715    fn eval(self, r: &Resolver<'_, '_>) -> bool {
716        let def_id = match self {
717            MaybeExported::Ok(node_id) => Some(if r.current_owner.id == node_id {
718                r.current_owner.def_id
719            } else {
720                r.current_owner.node_id_to_def_id[&node_id]
721            }),
722            MaybeExported::Impl(Some(trait_def_id)) | MaybeExported::ImplItem(Ok(trait_def_id)) => {
723                trait_def_id.as_local()
724            }
725            MaybeExported::Impl(None) => return true,
726            MaybeExported::ImplItem(Err(vis)) | MaybeExported::NestedUse(vis) => {
727                return vis.kind.is_pub();
728            }
729        };
730        def_id.is_none_or(|def_id| r.effective_visibilities.is_exported(def_id))
731    }
732}
733
734/// Used for recording UnnecessaryQualification.
735#[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)]
736pub(crate) struct UnnecessaryQualification<'ra> {
737    pub decl: LateDecl<'ra>,
738    pub node_id: NodeId,
739    pub path_span: Span,
740    pub removal_span: Span,
741}
742
743#[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)]
744pub(crate) struct DiagMetadata<'ast> {
745    /// The current trait's associated items' ident, used for diagnostic suggestions.
746    current_trait_assoc_items: Option<&'ast [Box<AssocItem>]>,
747
748    /// The current self type if inside an impl (used for better errors).
749    pub(crate) current_self_type: Option<&'ast Ty>,
750
751    /// The current self item if inside an ADT (used for better errors).
752    current_self_item: Option<NodeId>,
753
754    /// The current item being evaluated (used for suggestions and more detail in errors).
755    pub(crate) current_item: Option<&'ast Item>,
756
757    /// When processing generic arguments and encountering an unresolved ident not found,
758    /// suggest introducing a type or const param depending on the context.
759    currently_processing_generic_args: bool,
760
761    /// The current enclosing (non-closure) function (used for better errors).
762    current_function: Option<(FnKind<'ast>, Span)>,
763
764    /// A list of labels as of yet unused. Labels will be removed from this map when
765    /// they are used (in a `break` or `continue` statement)
766    unused_labels: FxIndexMap<NodeId, Span>,
767
768    /// Only used for better errors on `let <pat>: <expr, not type>;`.
769    current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
770
771    current_pat: Option<&'ast Pat>,
772
773    /// Used to detect possible `if let` written without `let` and to provide structured suggestion.
774    in_if_condition: Option<&'ast Expr>,
775
776    /// Used to detect possible new binding written without `let` and to provide structured suggestion.
777    in_assignment: Option<&'ast Expr>,
778    is_assign_rhs: bool,
779
780    /// If we are setting an associated type in trait impl, is it a non-GAT type?
781    in_non_gat_assoc_type: Option<bool>,
782
783    /// Used to detect possible `.` -> `..` typo when calling methods.
784    in_range: Option<(&'ast Expr, &'ast Expr)>,
785
786    /// If we are currently in a trait object definition. Used to point at the bounds when
787    /// encountering a struct or enum.
788    current_trait_object: Option<&'ast [ast::GenericBound]>,
789
790    /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
791    current_where_predicate: Option<&'ast WherePredicate>,
792
793    /// Whether we are visiting an associated type equality binding like `Trait<Assoc = &T>`.
794    in_assoc_ty_binding: bool,
795
796    current_type_path: Option<&'ast Ty>,
797
798    /// The current impl items (used to suggest).
799    current_impl_items: Option<&'ast [Box<AssocItem>]>,
800
801    /// The current impl items (used to suggest).
802    current_impl_item: Option<&'ast AssocItem>,
803
804    /// When processing impl trait
805    currently_processing_impl_trait: Option<(TraitRef, Ty)>,
806
807    /// Accumulate the errors due to missed lifetime elision,
808    /// and report them all at once for each function.
809    current_elision_failures: Vec<(MissingLifetime, Either<NodeId, Range<NodeId>>)>,
810}
811
812struct LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
813    r: &'a mut Resolver<'ra, 'tcx>,
814
815    /// The module that represents the current item scope.
816    parent_scope: ParentScope<'ra>,
817
818    /// The current set of local scopes for types and values.
819    ribs: PerNS<Vec<Rib<'ra>>>,
820
821    /// Previous popped `rib`, only used for diagnostic.
822    last_block_rib: Option<Rib<'ra>>,
823
824    /// The current set of local scopes, for labels.
825    label_ribs: Vec<Rib<'ra, NodeId>>,
826
827    /// The current set of local scopes for lifetimes.
828    lifetime_ribs: Vec<LifetimeRib>,
829
830    /// We are looking for lifetimes in an elision context.
831    /// The set contains all the resolutions that we encountered so far.
832    /// They will be used to determine the correct lifetime for the fn return type.
833    /// The `LifetimeElisionCandidate` is used for diagnostics, to suggest introducing named
834    /// lifetimes.
835    lifetime_elision_candidates: Option<Vec<(LifetimeRes, LifetimeElisionCandidate)>>,
836
837    /// The trait that the current context can refer to.
838    current_trait_ref: Option<(Module<'ra>, TraitRef)>,
839
840    /// Fields used to add information to diagnostic errors.
841    diag_metadata: Box<DiagMetadata<'ast>>,
842
843    /// State used to know whether to ignore resolution errors for function bodies.
844    ///
845    /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
846    /// In most cases this will be `None`, in which case errors will always be reported.
847    /// If it is `true`, then it will be updated when entering a nested function or trait body.
848    in_func_body: bool,
849
850    /// Count the number of places a lifetime is used.
851    lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
852
853    /// `use` injections are delayed for better placement and deduplication.
854    use_injections: Vec<UseError<'tcx>>,
855}
856
857impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for LateResolutionVisitor<'_, '_, 'ra, 'tcx> {
858    fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
859        &self.r
860    }
861}
862impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for LateResolutionVisitor<'_, '_, 'ra, 'tcx> {
863    fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
864        &mut self.r
865    }
866}
867
868/// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
869impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
870    fn visit_attribute(&mut self, _: &'ast Attribute) {
871        // We do not want to resolve expressions that appear in attributes,
872        // as they do not correspond to actual code.
873    }
874    fn visit_item(&mut self, item: &'ast Item) {
875        let prev = replace(&mut self.diag_metadata.current_item, Some(item));
876        // Always report errors in items we just entered.
877        let old_ignore = replace(&mut self.in_func_body, false);
878        with_owner(self, item.id, |this| {
879            this.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item))
880        });
881        self.in_func_body = old_ignore;
882        self.diag_metadata.current_item = prev;
883    }
884    fn visit_arm(&mut self, arm: &'ast Arm) {
885        self.resolve_arm(arm);
886    }
887    fn visit_block(&mut self, block: &'ast Block) {
888        let old_macro_rules = self.parent_scope.macro_rules;
889        self.resolve_block(block);
890        self.parent_scope.macro_rules = old_macro_rules;
891    }
892    fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
893        ::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:#?}");
894    }
895    fn visit_expr(&mut self, expr: &'ast Expr) {
896        self.resolve_expr(expr, None);
897    }
898    fn visit_pat(&mut self, p: &'ast Pat) {
899        let prev = self.diag_metadata.current_pat;
900        self.diag_metadata.current_pat = Some(p);
901
902        if let PatKind::Guard(subpat, _) = &p.kind {
903            // We walk the guard expression in `resolve_pattern_inner`. Don't resolve it twice.
904            self.visit_pat(subpat);
905        } else {
906            visit::walk_pat(self, p);
907        }
908
909        self.diag_metadata.current_pat = prev;
910    }
911    fn visit_local(&mut self, local: &'ast Local) {
912        let local_spans = match local.pat.kind {
913            // We check for this to avoid tuple struct fields.
914            PatKind::Wild => None,
915            _ => Some((
916                local.pat.span,
917                local.ty.as_ref().map(|ty| ty.span),
918                local.kind.init().map(|init| init.span),
919            )),
920        };
921        let original = replace(&mut self.diag_metadata.current_let_binding, local_spans);
922        self.resolve_local(local);
923        self.diag_metadata.current_let_binding = original;
924    }
925    fn visit_ty(&mut self, ty: &'ast Ty) {
926        let prev = self.diag_metadata.current_trait_object;
927        let prev_ty = self.diag_metadata.current_type_path;
928        match &ty.kind {
929            TyKind::Ref(None, _) | TyKind::PinnedRef(None, _) => {
930                // Elided lifetime in reference: we resolve as if there was some lifetime `'_` with
931                // NodeId `ty.id`.
932                // This span will be used in case of elision failure.
933                let span = self.r.tcx.sess.source_map().start_point(ty.span);
934                self.resolve_elided_lifetime(ty.id, span);
935                visit::walk_ty(self, ty);
936            }
937            TyKind::Path(qself, path) => {
938                self.diag_metadata.current_type_path = Some(ty);
939
940                // If we have a path that ends with `(..)`, then it must be
941                // return type notation. Resolve that path in the *value*
942                // namespace.
943                let source = if let Some(seg) = path.segments.last()
944                    && let Some(args) = &seg.args
945                    && #[allow(non_exhaustive_omitted_patterns)] match **args {
    GenericArgs::ParenthesizedElided(..) => true,
    _ => false,
}matches!(**args, GenericArgs::ParenthesizedElided(..))
946                {
947                    PathSource::ReturnTypeNotation
948                } else {
949                    PathSource::Type
950                };
951
952                self.smart_resolve_path(ty.id, qself, path, source);
953
954                // Check whether we should interpret this as a bare trait object.
955                if qself.is_none()
956                    && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
957                    && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) =
958                        partial_res.full_res()
959                {
960                    // This path is actually a bare trait object. In case of a bare `Fn`-trait
961                    // object with anonymous lifetimes, we need this rib to correctly place the
962                    // synthetic lifetimes.
963                    let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
964                    self.with_generic_param_rib(
965                        &[],
966                        RibKind::Normal,
967                        ty.id,
968                        LifetimeBinderKind::PolyTrait,
969                        span,
970                        |this| this.visit_path(path),
971                    );
972                } else {
973                    visit::walk_ty(self, ty)
974                }
975            }
976            TyKind::ImplicitSelf => {
977                let self_ty = Ident::with_dummy_span(kw::SelfUpper);
978                let res = self
979                    .resolve_ident_in_lexical_scope(
980                        self_ty,
981                        TypeNS,
982                        Some(Finalize::new(ty.id, ty.span)),
983                        None,
984                    )
985                    .map_or(Res::Err, |d| d.res());
986                self.r.record_partial_res(ty.id, PartialRes::new(res));
987                visit::walk_ty(self, ty)
988            }
989            TyKind::ImplTrait(..) => {
990                let candidates = self.lifetime_elision_candidates.take();
991                self.with_lifetime_rib(LifetimeRibKind::ImplTrait, |this| visit::walk_ty(this, ty));
992                self.lifetime_elision_candidates = candidates;
993            }
994            TyKind::TraitObject(bounds, ..) => {
995                self.diag_metadata.current_trait_object = Some(&bounds[..]);
996                visit::walk_ty(self, ty)
997            }
998            TyKind::FnPtr(fn_ptr) => {
999                let span = ty.span.shrink_to_lo().to(fn_ptr.decl_span.shrink_to_lo());
1000                self.with_generic_param_rib(
1001                    &fn_ptr.generic_params,
1002                    RibKind::Normal,
1003                    ty.id,
1004                    LifetimeBinderKind::FnPtrType,
1005                    span,
1006                    |this| {
1007                        this.visit_generic_params(&fn_ptr.generic_params, false);
1008                        this.resolve_fn_signature(
1009                            ty.id,
1010                            false,
1011                            // We don't need to deal with patterns in parameters, because
1012                            // they are not possible for foreign or bodiless functions.
1013                            fn_ptr.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1014                            &fn_ptr.decl.output,
1015                            false,
1016                        )
1017                    },
1018                )
1019            }
1020            TyKind::UnsafeBinder(unsafe_binder) => {
1021                let span = ty.span.shrink_to_lo().to(unsafe_binder.inner_ty.span.shrink_to_lo());
1022                self.with_generic_param_rib(
1023                    &unsafe_binder.generic_params,
1024                    RibKind::Normal,
1025                    ty.id,
1026                    LifetimeBinderKind::FnPtrType,
1027                    span,
1028                    |this| {
1029                        this.visit_generic_params(&unsafe_binder.generic_params, false);
1030                        this.with_lifetime_rib(
1031                            // We don't allow anonymous `unsafe &'_ ()` binders,
1032                            // although I guess we could.
1033                            LifetimeRibKind::AnonymousReportError,
1034                            |this| this.visit_ty(&unsafe_binder.inner_ty),
1035                        );
1036                    },
1037                )
1038            }
1039            TyKind::Array(element_ty, length) => {
1040                self.visit_ty(element_ty);
1041                self.resolve_anon_const(length, AnonConstKind::ConstArg(IsRepeatExpr::No));
1042            }
1043            _ => visit::walk_ty(self, ty),
1044        }
1045        self.diag_metadata.current_trait_object = prev;
1046        self.diag_metadata.current_type_path = prev_ty;
1047    }
1048
1049    fn visit_ty_pat(&mut self, t: &'ast TyPat) -> Self::Result {
1050        match &t.kind {
1051            TyPatKind::Range(start, end, _) => {
1052                if let Some(start) = start {
1053                    self.resolve_anon_const(start, AnonConstKind::ConstArg(IsRepeatExpr::No));
1054                }
1055                if let Some(end) = end {
1056                    self.resolve_anon_const(end, AnonConstKind::ConstArg(IsRepeatExpr::No));
1057                }
1058            }
1059            TyPatKind::Or(patterns) => {
1060                for pat in patterns {
1061                    self.visit_ty_pat(pat)
1062                }
1063            }
1064            TyPatKind::NotNull | TyPatKind::Err(_) => {}
1065        }
1066    }
1067
1068    fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
1069        let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
1070        self.with_generic_param_rib(
1071            &tref.bound_generic_params,
1072            RibKind::Normal,
1073            tref.trait_ref.ref_id,
1074            LifetimeBinderKind::PolyTrait,
1075            span,
1076            |this| {
1077                this.visit_generic_params(&tref.bound_generic_params, false);
1078                this.smart_resolve_path(
1079                    tref.trait_ref.ref_id,
1080                    &None,
1081                    &tref.trait_ref.path,
1082                    PathSource::Trait(AliasPossibility::Maybe),
1083                );
1084                this.visit_trait_ref(&tref.trait_ref);
1085            },
1086        );
1087    }
1088    fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
1089        with_owner(self, foreign_item.id, |this| {
1090            this.resolve_doc_links(&foreign_item.attrs, MaybeExported::Ok(foreign_item.id));
1091            let def_kind = this.r.tcx.def_kind(this.r.current_owner.def_id);
1092            match foreign_item.kind {
1093                ForeignItemKind::TyAlias(TyAlias { ref generics, .. }) => {
1094                    this.with_generic_param_rib(
1095                        &generics.params,
1096                        RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1097                        foreign_item.id,
1098                        LifetimeBinderKind::Item,
1099                        generics.span,
1100                        |this| visit::walk_item(this, foreign_item),
1101                    );
1102                }
1103                ForeignItemKind::Fn(Fn { ref generics, .. }) => {
1104                    this.with_generic_param_rib(
1105                        &generics.params,
1106                        RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1107                        foreign_item.id,
1108                        LifetimeBinderKind::Function,
1109                        generics.span,
1110                        |this| visit::walk_item(this, foreign_item),
1111                    );
1112                }
1113                ForeignItemKind::Static(..) => {
1114                    this.with_static_rib(def_kind, |this| visit::walk_item(this, foreign_item))
1115                }
1116                ForeignItemKind::MacCall(..) => {
1117                    {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
1118                }
1119            }
1120        })
1121    }
1122    fn visit_fn(&mut self, fn_kind: FnKind<'ast>, _: &AttrVec, sp: Span, fn_id: NodeId) {
1123        let previous_value = self.diag_metadata.current_function;
1124        match fn_kind {
1125            // Bail if the function is foreign, and thus cannot validly have
1126            // a body, or if there's no body for some other reason.
1127            FnKind::Fn(FnCtxt::Foreign, _, Fn { sig, ident, generics, .. })
1128            | FnKind::Fn(_, _, Fn { sig, ident, generics, body: None, .. }) => {
1129                self.visit_fn_header(&sig.header);
1130                self.visit_ident(ident);
1131                self.visit_generics(generics);
1132                self.resolve_fn_signature(
1133                    fn_id,
1134                    sig.decl.has_self(),
1135                    sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1136                    &sig.decl.output,
1137                    false,
1138                );
1139                return;
1140            }
1141            FnKind::Fn(..) => {
1142                self.diag_metadata.current_function = Some((fn_kind, sp));
1143            }
1144            // Do not update `current_function` for closures: it suggests `self` parameters.
1145            FnKind::Closure(..) => {}
1146        };
1147        {
    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:1147",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1147u32),
                        ::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");
1148
1149        if let FnKind::Fn(_, _, f) = fn_kind {
1150            self.resolve_eii(&f.eii_impls);
1151        }
1152
1153        // Create a value rib for the function.
1154        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
1155            // Create a label rib for the function.
1156            this.with_label_rib(RibKind::FnOrCoroutine, |this| {
1157                match fn_kind {
1158                    FnKind::Fn(_, _, Fn { sig, generics, contract, body, .. }) => {
1159                        this.visit_generics(generics);
1160
1161                        let declaration = &sig.decl;
1162                        let coro_node_id = sig
1163                            .header
1164                            .coroutine_kind
1165                            .map(|coroutine_kind| coroutine_kind.return_id());
1166
1167                        this.resolve_fn_signature(
1168                            fn_id,
1169                            declaration.has_self(),
1170                            declaration
1171                                .inputs
1172                                .iter()
1173                                .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
1174                            &declaration.output,
1175                            coro_node_id.is_some(),
1176                        );
1177
1178                        if let Some(contract) = contract {
1179                            this.visit_contract(contract);
1180                        }
1181
1182                        if let Some(body) = body {
1183                            // Ignore errors in function bodies if this is rustdoc
1184                            // Be sure not to set this until the function signature has been resolved.
1185                            let previous_state = replace(&mut this.in_func_body, true);
1186                            // We only care block in the same function
1187                            this.last_block_rib = None;
1188                            // Resolve the function body, potentially inside the body of an async closure
1189                            this.with_lifetime_rib(
1190                                LifetimeRibKind::elided(LifetimeRes::Infer),
1191                                |this| this.visit_block(body),
1192                            );
1193
1194                            {
    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:1194",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1194u32),
                        ::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");
1195                            this.in_func_body = previous_state;
1196                        }
1197                    }
1198                    FnKind::Closure(binder, _, declaration, body) => {
1199                        this.visit_closure_binder(binder);
1200
1201                        this.with_lifetime_rib(
1202                            match binder {
1203                                // We do not have any explicit generic lifetime parameter.
1204                                ClosureBinder::NotPresent => {
1205                                    LifetimeRibKind::AnonymousCreateParameter {
1206                                        binder: fn_id,
1207                                        report_in_path: false,
1208                                    }
1209                                }
1210                                ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1211                            },
1212                            // Add each argument to the rib.
1213                            |this| this.resolve_params(&declaration.inputs),
1214                        );
1215                        this.with_lifetime_rib(
1216                            match binder {
1217                                ClosureBinder::NotPresent => {
1218                                    LifetimeRibKind::elided(LifetimeRes::Infer)
1219                                }
1220                                ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1221                            },
1222                            |this| visit::walk_fn_ret_ty(this, &declaration.output),
1223                        );
1224
1225                        // Ignore errors in function bodies if this is rustdoc
1226                        // Be sure not to set this until the function signature has been resolved.
1227                        let previous_state = replace(&mut this.in_func_body, true);
1228                        // Resolve the function body, potentially inside the body of an async closure
1229                        this.with_lifetime_rib(
1230                            LifetimeRibKind::elided(LifetimeRes::Infer),
1231                            |this| this.visit_expr(body),
1232                        );
1233
1234                        {
    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:1234",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1234u32),
                        ::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");
1235                        this.in_func_body = previous_state;
1236                    }
1237                }
1238            })
1239        });
1240        self.diag_metadata.current_function = previous_value;
1241    }
1242
1243    fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1244        self.resolve_lifetime(lifetime, use_ctxt)
1245    }
1246
1247    fn visit_precise_capturing_arg(&mut self, arg: &'ast PreciseCapturingArg) {
1248        match arg {
1249            // Lower the lifetime regularly; we'll resolve the lifetime and check
1250            // it's a parameter later on in HIR lowering.
1251            PreciseCapturingArg::Lifetime(_) => {}
1252
1253            PreciseCapturingArg::Arg(path, id) => {
1254                // we want `impl use<C>` to try to resolve `C` as both a type parameter or
1255                // a const parameter. Since the resolver specifically doesn't allow having
1256                // two generic params with the same name, even if they're a different namespace,
1257                // it doesn't really matter which we try resolving first, but just like
1258                // `Ty::Param` we just fall back to the value namespace only if it's missing
1259                // from the type namespace.
1260                let mut check_ns = |ns| {
1261                    self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns).is_some()
1262                };
1263                // Like `Ty::Param`, we try resolving this as both a const and a type.
1264                if !check_ns(TypeNS) && check_ns(ValueNS) {
1265                    self.smart_resolve_path(
1266                        *id,
1267                        &None,
1268                        path,
1269                        PathSource::PreciseCapturingArg(ValueNS),
1270                    );
1271                } else {
1272                    self.smart_resolve_path(
1273                        *id,
1274                        &None,
1275                        path,
1276                        PathSource::PreciseCapturingArg(TypeNS),
1277                    );
1278                }
1279            }
1280        }
1281
1282        visit::walk_precise_capturing_arg(self, arg)
1283    }
1284
1285    fn visit_generics(&mut self, generics: &'ast Generics) {
1286        self.visit_generic_params(&generics.params, self.diag_metadata.current_self_item.is_some());
1287        for p in &generics.where_clause.predicates {
1288            self.visit_where_predicate(p);
1289        }
1290    }
1291
1292    fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
1293        match b {
1294            ClosureBinder::NotPresent => {}
1295            ClosureBinder::For { generic_params, .. } => {
1296                self.visit_generic_params(
1297                    generic_params,
1298                    self.diag_metadata.current_self_item.is_some(),
1299                );
1300            }
1301        }
1302    }
1303
1304    fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
1305        {
    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:1305",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1305u32),
                        ::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_generic_arg({0:?})",
                                                    arg) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("visit_generic_arg({:?})", arg);
1306        let prev = replace(&mut self.diag_metadata.currently_processing_generic_args, true);
1307        match arg {
1308            GenericArg::Type(ty) => {
1309                // We parse const arguments as path types as we cannot distinguish them during
1310                // parsing. We try to resolve that ambiguity by attempting resolution the type
1311                // namespace first, and if that fails we try again in the value namespace. If
1312                // resolution in the value namespace succeeds, we have an generic const argument on
1313                // our hands.
1314                if let TyKind::Path(None, ref path) = ty.kind
1315                    // We cannot disambiguate multi-segment paths right now as that requires type
1316                    // checking.
1317                    && path.is_potential_trivial_const_arg()
1318                {
1319                    let mut check_ns = |ns| {
1320                        self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
1321                            .is_some()
1322                    };
1323                    if !check_ns(TypeNS) && check_ns(ValueNS) {
1324                        self.resolve_anon_const_manual(
1325                            true,
1326                            AnonConstKind::ConstArg(IsRepeatExpr::No),
1327                            |this| {
1328                                this.smart_resolve_path(ty.id, &None, path, PathSource::Expr(None));
1329                                this.visit_path(path);
1330                            },
1331                        );
1332
1333                        self.diag_metadata.currently_processing_generic_args = prev;
1334                        return;
1335                    }
1336                }
1337
1338                self.visit_ty(ty);
1339            }
1340            GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1341            GenericArg::Const(ct) => {
1342                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
1343            }
1344        }
1345        self.diag_metadata.currently_processing_generic_args = prev;
1346    }
1347
1348    fn visit_assoc_item_constraint(&mut self, constraint: &'ast AssocItemConstraint) {
1349        self.visit_ident(&constraint.ident);
1350        if let Some(ref gen_args) = constraint.gen_args {
1351            // Forbid anonymous lifetimes in GAT parameters until proper semantics are decided.
1352            self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1353                this.visit_generic_args(gen_args)
1354            });
1355        }
1356        match constraint.kind {
1357            AssocItemConstraintKind::Equality { ref term } => match term {
1358                Term::Ty(ty) => {
1359                    let prev = replace(&mut self.diag_metadata.in_assoc_ty_binding, true);
1360                    self.visit_ty(ty);
1361                    self.diag_metadata.in_assoc_ty_binding = prev;
1362                }
1363                Term::Const(c) => {
1364                    self.resolve_anon_const(c, AnonConstKind::ConstArg(IsRepeatExpr::No))
1365                }
1366            },
1367            AssocItemConstraintKind::Bound { ref bounds } => {
1368                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);
1369            }
1370        }
1371    }
1372
1373    fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1374        let Some(ref args) = path_segment.args else {
1375            return;
1376        };
1377
1378        match &**args {
1379            GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1380            GenericArgs::Parenthesized(p_args) => {
1381                // Probe the lifetime ribs to know how to behave.
1382                for rib in self.lifetime_ribs.iter().rev() {
1383                    match rib.kind {
1384                        // We are inside a `PolyTraitRef`. The lifetimes are
1385                        // to be introduced in that (maybe implicit) `for<>` binder.
1386                        LifetimeRibKind::Generics {
1387                            binder,
1388                            kind: LifetimeBinderKind::PolyTrait,
1389                            ..
1390                        } => {
1391                            self.resolve_fn_signature(
1392                                binder,
1393                                false,
1394                                p_args.inputs.iter().map(|ty| (None, &**ty)),
1395                                &p_args.output,
1396                                false,
1397                            );
1398                            break;
1399                        }
1400                        // We have nowhere to introduce generics. Code is malformed,
1401                        // so use regular lifetime resolution to avoid spurious errors.
1402                        LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1403                            visit::walk_generic_args(self, args);
1404                            break;
1405                        }
1406                        LifetimeRibKind::AnonymousCreateParameter { .. }
1407                        | LifetimeRibKind::AnonymousReportError
1408                        | LifetimeRibKind::ImplTrait
1409                        | LifetimeRibKind::Elided { .. }
1410                        | LifetimeRibKind::ElisionFailure
1411                        | LifetimeRibKind::ConcreteAnonConst(_)
1412                        | LifetimeRibKind::ConstParamTy => {}
1413                    }
1414                }
1415            }
1416            GenericArgs::ParenthesizedElided(_) => {}
1417        }
1418    }
1419
1420    fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1421        {
    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:1421",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1421u32),
                        ::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);
1422        let previous_value = replace(&mut self.diag_metadata.current_where_predicate, Some(p));
1423        self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1424            if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1425                bounded_ty,
1426                bounds,
1427                bound_generic_params,
1428                ..
1429            }) = &p.kind
1430            {
1431                let span = p.span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1432                this.with_generic_param_rib(
1433                    bound_generic_params,
1434                    RibKind::Normal,
1435                    bounded_ty.id,
1436                    LifetimeBinderKind::WhereBound,
1437                    span,
1438                    |this| {
1439                        this.visit_generic_params(bound_generic_params, false);
1440                        this.visit_ty(bounded_ty);
1441                        for bound in bounds {
1442                            this.visit_param_bound(bound, BoundKind::Bound)
1443                        }
1444                    },
1445                );
1446            } else {
1447                visit::walk_where_predicate(this, p);
1448            }
1449        });
1450        self.diag_metadata.current_where_predicate = previous_value;
1451    }
1452
1453    fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1454        for (op, _) in &asm.operands {
1455            match op {
1456                InlineAsmOperand::In { expr, .. }
1457                | InlineAsmOperand::Out { expr: Some(expr), .. }
1458                | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1459                InlineAsmOperand::Out { expr: None, .. } => {}
1460                InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1461                    self.visit_expr(in_expr);
1462                    if let Some(out_expr) = out_expr {
1463                        self.visit_expr(out_expr);
1464                    }
1465                }
1466                InlineAsmOperand::Const { anon_const, .. } => {
1467                    // Although this is `DefKind::AnonConst`, it is allowed to reference outer
1468                    // generic parameters like an inline const.
1469                    self.resolve_anon_const(anon_const, AnonConstKind::InlineConst);
1470                }
1471                InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1472                InlineAsmOperand::Label { block } => self.visit_block(block),
1473            }
1474        }
1475    }
1476
1477    fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1478        // This is similar to the code for AnonConst.
1479        self.with_rib(ValueNS, RibKind::InlineAsmSym, |this| {
1480            this.with_rib(TypeNS, RibKind::InlineAsmSym, |this| {
1481                this.with_label_rib(RibKind::InlineAsmSym, |this| {
1482                    this.smart_resolve_path(sym.id, &sym.qself, &sym.path, PathSource::Expr(None));
1483                    visit::walk_inline_asm_sym(this, sym);
1484                });
1485            })
1486        });
1487    }
1488
1489    fn visit_variant(&mut self, v: &'ast Variant) {
1490        self.resolve_doc_links(&v.attrs, MaybeExported::Ok(v.id));
1491        self.visit_id(v.id);
1492        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);
1493        self.visit_vis(&v.vis);
1494        self.visit_ident(&v.ident);
1495        self.visit_variant_data(&v.data);
1496        if let Some(discr) = &v.disr_expr {
1497            self.resolve_anon_const(discr, AnonConstKind::EnumDiscriminant);
1498        }
1499    }
1500
1501    fn visit_field_def(&mut self, f: &'ast FieldDef) {
1502        self.resolve_doc_links(&f.attrs, MaybeExported::Ok(f.id));
1503        let FieldDef {
1504            attrs,
1505            id: _,
1506            span: _,
1507            vis,
1508            ident,
1509            ty,
1510            is_placeholder: _,
1511            default,
1512            mut_restriction,
1513            safety: _,
1514        } = f;
1515        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);
1516        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));
1517        self.resolve_restriction_path(&mut_restriction.kind, ResolvingRestrictionKind::Mut);
1518        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);
1519        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));
1520        if let Some(v) = &default {
1521            self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);
1522        }
1523    }
1524}
1525
1526impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1527    fn new(resolver: &'a mut Resolver<'ra, 'tcx>) -> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1528        // During late resolution we only track the module component of the parent scope,
1529        // although it may be useful to track other components as well for diagnostics.
1530        let graph_root = resolver.graph_root;
1531        let parent_scope = ParentScope::module(graph_root, resolver.arenas);
1532        let start_rib_kind = RibKind::Module(graph_root);
1533        LateResolutionVisitor {
1534            r: resolver,
1535            parent_scope,
1536            ribs: PerNS {
1537                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)],
1538                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)],
1539                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)],
1540            },
1541            last_block_rib: None,
1542            label_ribs: Vec::new(),
1543            lifetime_ribs: Vec::new(),
1544            lifetime_elision_candidates: None,
1545            current_trait_ref: None,
1546            diag_metadata: Default::default(),
1547            // errors at module scope should always be reported
1548            in_func_body: false,
1549            lifetime_uses: Default::default(),
1550            use_injections: Vec::new(),
1551        }
1552    }
1553
1554    fn maybe_resolve_ident_in_lexical_scope(
1555        &mut self,
1556        ident: Ident,
1557        ns: Namespace,
1558    ) -> Option<LateDecl<'ra>> {
1559        self.r.resolve_ident_in_lexical_scope(
1560            ident,
1561            ns,
1562            &self.parent_scope,
1563            None,
1564            &self.ribs[ns],
1565            None,
1566            Some(&self.diag_metadata),
1567        )
1568    }
1569
1570    fn resolve_ident_in_lexical_scope(
1571        &mut self,
1572        ident: Ident,
1573        ns: Namespace,
1574        finalize: Option<Finalize>,
1575        ignore_decl: Option<Decl<'ra>>,
1576    ) -> Option<LateDecl<'ra>> {
1577        self.r.resolve_ident_in_lexical_scope(
1578            ident,
1579            ns,
1580            &self.parent_scope,
1581            finalize,
1582            &self.ribs[ns],
1583            ignore_decl,
1584            Some(&self.diag_metadata),
1585        )
1586    }
1587
1588    fn resolve_path(
1589        &mut self,
1590        path: &[Segment],
1591        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1592        finalize: Option<Finalize>,
1593        source: PathSource<'_, 'ast, 'ra>,
1594    ) -> PathResult<'ra> {
1595        self.r.cm().resolve_path_with_ribs(
1596            path,
1597            opt_ns,
1598            &self.parent_scope,
1599            Some(source),
1600            finalize.map(|finalize| Finalize { stage: Stage::Late, ..finalize }),
1601            Some(&self.ribs),
1602            None,
1603            None,
1604            Some(&self.diag_metadata),
1605        )
1606    }
1607
1608    // AST resolution
1609    //
1610    // We maintain a list of value ribs and type ribs.
1611    //
1612    // Simultaneously, we keep track of the current position in the module
1613    // graph in the `parent_scope.module` pointer. When we go to resolve a name in
1614    // the value or type namespaces, we first look through all the ribs and
1615    // then query the module graph. When we resolve a name in the module
1616    // namespace, we can skip all the ribs (since nested modules are not
1617    // allowed within blocks in Rust) and jump straight to the current module
1618    // graph node.
1619    //
1620    // Named implementations are handled separately. When we find a method
1621    // call, we consult the module node to find all of the implementations in
1622    // scope. This information is lazily cached in the module node. We then
1623    // generate a fake "implementation scope" containing all the
1624    // implementations thus found, for compatibility with old resolve pass.
1625
1626    /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
1627    fn with_rib<T>(
1628        &mut self,
1629        ns: Namespace,
1630        kind: RibKind<'ra>,
1631        work: impl FnOnce(&mut Self) -> T,
1632    ) -> T {
1633        self.ribs[ns].push(Rib::new(kind));
1634        let ret = work(self);
1635        self.ribs[ns].pop();
1636        ret
1637    }
1638
1639    fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1640        // For type parameter defaults, we have to ban access
1641        // to following type parameters, as the GenericArgs can only
1642        // provide previous type parameters as they're built. We
1643        // put all the parameters on the ban list and then remove
1644        // them one by one as they are processed and become available.
1645        let mut forward_ty_ban_rib =
1646            Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1647        let mut forward_const_ban_rib =
1648            Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1649        for param in params.iter() {
1650            match param.kind {
1651                GenericParamKind::Type { .. } => {
1652                    forward_ty_ban_rib
1653                        .bindings
1654                        .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1655                }
1656                GenericParamKind::Const { .. } => {
1657                    forward_const_ban_rib
1658                        .bindings
1659                        .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1660                }
1661                GenericParamKind::Lifetime => {}
1662            }
1663        }
1664
1665        // rust-lang/rust#61631: The type `Self` is essentially
1666        // another type parameter. For ADTs, we consider it
1667        // well-defined only after all of the ADT type parameters have
1668        // been provided. Therefore, we do not allow use of `Self`
1669        // anywhere in ADT type parameter defaults.
1670        //
1671        // (We however cannot ban `Self` for defaults on *all* generic
1672        // lists; e.g. trait generics can usefully refer to `Self`,
1673        // such as in the case of `trait Add<Rhs = Self>`.)
1674        if add_self_upper {
1675            // (`Some` if + only if we are in ADT's generics.)
1676            forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1677        }
1678
1679        // NOTE: We use different ribs here not for a technical reason, but just
1680        // for better diagnostics.
1681        let mut forward_ty_ban_rib_const_param_ty = Rib {
1682            bindings: forward_ty_ban_rib.bindings.clone(),
1683            patterns_with_skipped_bindings: Default::default(),
1684            kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1685        };
1686        let mut forward_const_ban_rib_const_param_ty = Rib {
1687            bindings: forward_const_ban_rib.bindings.clone(),
1688            patterns_with_skipped_bindings: Default::default(),
1689            kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1690        };
1691        // We'll ban these with a `ConstParamTy` rib, so just clear these ribs for better
1692        // diagnostics, so we don't mention anything about const param tys having generics at all.
1693        if !self.r.features.generic_const_parameter_types() {
1694            forward_ty_ban_rib_const_param_ty.bindings.clear();
1695            forward_const_ban_rib_const_param_ty.bindings.clear();
1696        }
1697
1698        self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1699            for param in params {
1700                match param.kind {
1701                    GenericParamKind::Lifetime => {
1702                        for bound in &param.bounds {
1703                            this.visit_param_bound(bound, BoundKind::Bound);
1704                        }
1705                    }
1706                    GenericParamKind::Type { ref default } => {
1707                        for bound in &param.bounds {
1708                            this.visit_param_bound(bound, BoundKind::Bound);
1709                        }
1710
1711                        if let Some(ty) = default {
1712                            this.ribs[TypeNS].push(forward_ty_ban_rib);
1713                            this.ribs[ValueNS].push(forward_const_ban_rib);
1714                            this.visit_ty(ty);
1715                            forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1716                            forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1717                        }
1718
1719                        // Allow all following defaults to refer to this type parameter.
1720                        let i = &Ident::with_dummy_span(param.ident.name);
1721                        forward_ty_ban_rib.bindings.swap_remove(i);
1722                        forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);
1723                    }
1724                    GenericParamKind::Const { ref ty, span: _, ref default } => {
1725                        // Const parameters can't have param bounds.
1726                        if !param.bounds.is_empty() {
    ::core::panicking::panic("assertion failed: param.bounds.is_empty()")
};assert!(param.bounds.is_empty());
1727
1728                        this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);
1729                        this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);
1730                        if this.r.features.generic_const_parameter_types() {
1731                            this.visit_ty(ty)
1732                        } else {
1733                            this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));
1734                            this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));
1735                            this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {
1736                                this.visit_ty(ty)
1737                            });
1738                            this.ribs[TypeNS].pop().unwrap();
1739                            this.ribs[ValueNS].pop().unwrap();
1740                        }
1741                        forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();
1742                        forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();
1743
1744                        if let Some(expr) = default {
1745                            this.ribs[TypeNS].push(forward_ty_ban_rib);
1746                            this.ribs[ValueNS].push(forward_const_ban_rib);
1747                            this.resolve_anon_const(
1748                                expr,
1749                                AnonConstKind::ConstArg(IsRepeatExpr::No),
1750                            );
1751                            forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1752                            forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1753                        }
1754
1755                        // Allow all following defaults to refer to this const parameter.
1756                        let i = &Ident::with_dummy_span(param.ident.name);
1757                        forward_const_ban_rib.bindings.swap_remove(i);
1758                        forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);
1759                    }
1760                }
1761            }
1762        })
1763    }
1764
1765    #[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(1765u32),
                                    ::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))]
1766    fn with_lifetime_rib<T>(
1767        &mut self,
1768        kind: LifetimeRibKind,
1769        work: impl FnOnce(&mut Self) -> T,
1770    ) -> T {
1771        self.lifetime_ribs.push(LifetimeRib::new(kind));
1772        let outer_elision_candidates = self.lifetime_elision_candidates.take();
1773        let ret = work(self);
1774        self.lifetime_elision_candidates = outer_elision_candidates;
1775        self.lifetime_ribs.pop();
1776        ret
1777    }
1778
1779    #[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(1779u32),
                                    ::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:1805",
                                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1805u32),
                                                        ::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:1850",
                                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1850u32),
                                                        ::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:1854",
                                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1854u32),
                                                        ::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))]
1780    fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1781        let ident = lifetime.ident;
1782
1783        if ident.name == kw::StaticLifetime {
1784            self.record_lifetime_use(
1785                lifetime.id,
1786                LifetimeRes::Static,
1787                LifetimeElisionCandidate::Ignore,
1788            );
1789            return;
1790        }
1791
1792        if ident.name == kw::UnderscoreLifetime {
1793            return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1794        }
1795
1796        let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1797        while let Some(rib) = lifetime_rib_iter.next() {
1798            let normalized_ident = ident.normalize_to_macros_2_0();
1799            if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1800                self.record_lifetime_use(lifetime.id, res, LifetimeElisionCandidate::Ignore);
1801
1802                if let LifetimeRes::Param { param, binder } = res {
1803                    match self.lifetime_uses.entry(param) {
1804                        Entry::Vacant(v) => {
1805                            debug!("First use of {:?} at {:?}", res, ident.span);
1806                            let use_set = self
1807                                .lifetime_ribs
1808                                .iter()
1809                                .rev()
1810                                .find_map(|rib| match rib.kind {
1811                                    // Do not suggest eliding a lifetime where an anonymous
1812                                    // lifetime would be illegal.
1813                                    LifetimeRibKind::Item
1814                                    | LifetimeRibKind::AnonymousReportError
1815                                    | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1816                                    // An anonymous lifetime is legal here, and bound to the right
1817                                    // place, go ahead.
1818                                    LifetimeRibKind::AnonymousCreateParameter {
1819                                        binder: anon_binder,
1820                                        ..
1821                                    } => Some(if binder == anon_binder {
1822                                        LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1823                                    } else {
1824                                        LifetimeUseSet::Many
1825                                    }),
1826                                    // Only report if eliding the lifetime would have the same
1827                                    // semantics.
1828                                    LifetimeRibKind::Elided { res: r, error_in_path } => {
1829                                        Some(if res == r && !error_in_path {
1830                                            LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1831                                        } else {
1832                                            LifetimeUseSet::Many
1833                                        })
1834                                    }
1835                                    LifetimeRibKind::Generics { .. }
1836                                    | LifetimeRibKind::ConstParamTy => None,
1837                                    LifetimeRibKind::ConcreteAnonConst(_) => {
1838                                        span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1839                                    }
1840
1841                                    LifetimeRibKind::ImplTrait => {
1842                                        if self.r.features.anonymous_lifetime_in_impl_trait() {
1843                                            None
1844                                        } else {
1845                                            Some(LifetimeUseSet::Many)
1846                                        }
1847                                    }
1848                                })
1849                                .unwrap_or(LifetimeUseSet::Many);
1850                            debug!(?use_ctxt, ?use_set);
1851                            v.insert(use_set);
1852                        }
1853                        Entry::Occupied(mut o) => {
1854                            debug!("Many uses of {:?} at {:?}", res, ident.span);
1855                            *o.get_mut() = LifetimeUseSet::Many;
1856                        }
1857                    }
1858                }
1859                return;
1860            }
1861
1862            match rib.kind {
1863                LifetimeRibKind::Item => break,
1864                LifetimeRibKind::ConstParamTy => {
1865                    let guar = self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1866                    self.record_lifetime_err(lifetime.id, guar);
1867                    return;
1868                }
1869                LifetimeRibKind::ConcreteAnonConst(cause) => {
1870                    let guar = self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1871                    self.record_lifetime_err(lifetime.id, guar);
1872                    return;
1873                }
1874                LifetimeRibKind::AnonymousCreateParameter { .. }
1875                | LifetimeRibKind::Elided { .. }
1876                | LifetimeRibKind::Generics { .. }
1877                | LifetimeRibKind::ElisionFailure
1878                | LifetimeRibKind::AnonymousReportError
1879                | LifetimeRibKind::ImplTrait => {}
1880            }
1881        }
1882
1883        let normalized_ident = ident.normalize_to_macros_2_0();
1884        let outer_res = lifetime_rib_iter
1885            .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1886
1887        let guar = self.emit_undeclared_lifetime_error(lifetime, outer_res);
1888        self.record_lifetime_err(lifetime.id, guar);
1889    }
1890
1891    #[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(1891u32),
                                    ::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:1911",
                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1911u32),
                                        ::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))]
1892    fn resolve_anonymous_lifetime(
1893        &mut self,
1894        lifetime: &Lifetime,
1895        id_for_lint: NodeId,
1896        elided: bool,
1897    ) {
1898        debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1899
1900        let kind =
1901            if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1902        let missing_lifetime = MissingLifetime {
1903            id: lifetime.id,
1904            span: lifetime.ident.span,
1905            kind,
1906            count: 1,
1907            id_for_lint,
1908        };
1909        let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1910        for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1911            debug!(?rib.kind);
1912            match rib.kind {
1913                LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1914                    let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1915                    self.record_lifetime_use(lifetime.id, res, elision_candidate);
1916                    return;
1917                }
1918                LifetimeRibKind::AnonymousReportError => {
1919                    let guar = if elided {
1920                        let suggestion = if self.diag_metadata.in_assoc_ty_binding {
1921                            // In an associated type binding like `I: IntoIterator<Item = &T>`,
1922                            // introducing the lifetime on the trait ref would produce
1923                            // `I: for<'a> IntoIterator<Item = &'a T>`. Prefer a named lifetime
1924                            // from an enclosing item instead, so the assoc-ty-binding-specific path
1925                            // below builds that suggestion.
1926                            None
1927                        } else {
1928                            self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1929                                // Look for a `Generics` rib that represents a trait or where-bound
1930                                // binder (`T: Trait<&U>` or `where T: Trait<&U>`), since that is
1931                                // where the generic E0637 diagnostic can insert `for<'a>`.
1932                                if let LifetimeRibKind::Generics {
1933                                    span,
1934                                    kind:
1935                                        LifetimeBinderKind::PolyTrait
1936                                        | LifetimeBinderKind::WhereBound,
1937                                    ..
1938                                } = rib.kind
1939                                {
1940                                    Some(crate::diagnostics::ElidedAnonymousLifetimeReportErrorSuggestion {
1941                                        lo: span.shrink_to_lo(),
1942                                        hi: lifetime.ident.span.shrink_to_hi(),
1943                                    })
1944                                } else {
1945                                    None
1946                                }
1947                            })
1948                        };
1949                        // are we trying to use an anonymous lifetime
1950                        // on a non GAT associated trait type?
1951                        if !self.in_func_body
1952                            && let Some((module, _)) = &self.current_trait_ref
1953                            && let Some(ty) = &self.diag_metadata.current_self_type
1954                            && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1955                            && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _, _) =
1956                                module.kind
1957                        {
1958                            if def_id_matches_path(
1959                                self.r.tcx,
1960                                trait_id,
1961                                &["core", "iter", "traits", "iterator", "Iterator"],
1962                            ) {
1963                                self.r.dcx().emit_err(
1964                                    crate::diagnostics::LendingIteratorReportError {
1965                                        lifetime: lifetime.ident.span,
1966                                        ty: ty.span,
1967                                    },
1968                                )
1969                            } else {
1970                                let decl = if !trait_id.is_local()
1971                                    && let Some(assoc) = self.diag_metadata.current_impl_item
1972                                    && let AssocItemKind::Type(_) = assoc.kind
1973                                    && let assocs = self.r.tcx.associated_items(trait_id)
1974                                    && let Some(ident) = assoc.kind.ident()
1975                                    && let Some(assoc) = assocs.find_by_ident_and_kind(
1976                                        self.r.tcx,
1977                                        ident,
1978                                        AssocTag::Type,
1979                                        trait_id,
1980                                    ) {
1981                                    let mut decl: MultiSpan =
1982                                        self.r.tcx.def_span(assoc.def_id).into();
1983                                    decl.push_span_label(
1984                                        self.r.tcx.def_span(trait_id),
1985                                        String::new(),
1986                                    );
1987                                    decl
1988                                } else {
1989                                    DUMMY_SP.into()
1990                                };
1991                                let mut err = self.r.dcx().create_err(
1992                                    crate::diagnostics::AnonymousLifetimeNonGatReportError {
1993                                        lifetime: lifetime.ident.span,
1994                                        decl,
1995                                    },
1996                                );
1997                                self.point_at_impl_lifetimes(&mut err, i, lifetime.ident.span);
1998                                err.emit()
1999                            }
2000                        } else if self.diag_metadata.in_assoc_ty_binding {
2001                            // For associated type bindings, e.g.
2002                            // `fn f<I: IntoIterator<Item = &T>>()`, introduce a named lifetime
2003                            // on an enclosing generics binder instead:
2004                            // `fn f<'a, I: IntoIterator<Item = &'a T>>()`.
2005                            let mut err = self.r.dcx().create_err(
2006                                crate::diagnostics::ElidedAnonymousLifetimeReportError {
2007                                    span: lifetime.ident.span,
2008                                    suggestion,
2009                                },
2010                            );
2011                            self.suggest_introducing_lifetime_for_assoc_ty_binding(
2012                                &mut err,
2013                                lifetime.ident.span,
2014                            );
2015                            err.emit()
2016                        } else {
2017                            self.r.dcx().emit_err(
2018                                crate::diagnostics::ElidedAnonymousLifetimeReportError {
2019                                    span: lifetime.ident.span,
2020                                    suggestion,
2021                                },
2022                            )
2023                        }
2024                    } else {
2025                        self.r.dcx().emit_err(
2026                            crate::diagnostics::ExplicitAnonymousLifetimeReportError {
2027                                span: lifetime.ident.span,
2028                            },
2029                        )
2030                    };
2031                    self.record_lifetime_err(lifetime.id, guar);
2032                    return;
2033                }
2034                LifetimeRibKind::Elided { res, .. } => {
2035                    self.record_lifetime_use(lifetime.id, res, elision_candidate);
2036                    return;
2037                }
2038                LifetimeRibKind::ElisionFailure => {
2039                    self.diag_metadata
2040                        .current_elision_failures
2041                        .push((missing_lifetime, Either::Left(lifetime.id)));
2042                    return;
2043                }
2044                LifetimeRibKind::Item => break,
2045                LifetimeRibKind::Generics { .. }
2046                | LifetimeRibKind::ConstParamTy
2047                | LifetimeRibKind::ImplTrait => {}
2048                LifetimeRibKind::ConcreteAnonConst(_) => {
2049                    // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
2050                    span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
2051                }
2052            }
2053        }
2054        let guar = self.report_missing_lifetime_specifiers([&missing_lifetime], None);
2055        self.record_lifetime_err(lifetime.id, guar);
2056    }
2057
2058    fn point_at_impl_lifetimes(&mut self, err: &mut Diag<'_>, i: usize, lifetime: Span) {
2059        let Some((rib, span)) =
2060            self.lifetime_ribs[..i].iter().rev().find_map(|rib| match rib.kind {
2061                LifetimeRibKind::Generics { span, kind: LifetimeBinderKind::ImplBlock, .. } => {
2062                    Some((rib, span))
2063                }
2064                _ => None,
2065            })
2066        else {
2067            return;
2068        };
2069        if !rib.bindings.is_empty() {
2070            err.span_label(
2071                span,
2072                ::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!(
2073                    "there {} named lifetime{} specified on the impl block you could use",
2074                    if rib.bindings.len() == 1 { "is a" } else { "are" },
2075                    pluralize!(rib.bindings.len()),
2076                ),
2077            );
2078            if rib.bindings.len() == 1 {
2079                err.span_suggestion_verbose(
2080                    lifetime.shrink_to_hi(),
2081                    "consider using the lifetime from the impl block",
2082                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ",
                rib.bindings.keys().next().unwrap()))
    })format!("{} ", rib.bindings.keys().next().unwrap()),
2083                    Applicability::MaybeIncorrect,
2084                );
2085            }
2086        } else {
2087            struct AnonRefFinder;
2088            impl<'ast> Visitor<'ast> for AnonRefFinder {
2089                type Result = ControlFlow<Span>;
2090
2091                fn visit_ty(&mut self, ty: &'ast ast::Ty) -> Self::Result {
2092                    if let ast::TyKind::Ref(None, mut_ty) = &ty.kind {
2093                        return ControlFlow::Break(mut_ty.ty.span.shrink_to_lo());
2094                    }
2095                    visit::walk_ty(self, ty)
2096                }
2097
2098                fn visit_lifetime(
2099                    &mut self,
2100                    lt: &'ast ast::Lifetime,
2101                    _cx: visit::LifetimeCtxt,
2102                ) -> Self::Result {
2103                    if lt.ident.name == kw::UnderscoreLifetime {
2104                        return ControlFlow::Break(lt.ident.span);
2105                    }
2106                    visit::walk_lifetime(self, lt)
2107                }
2108            }
2109
2110            if let Some(ty) = &self.diag_metadata.current_self_type
2111                && let ControlFlow::Break(sp) = AnonRefFinder.visit_ty(ty)
2112            {
2113                err.multipart_suggestion(
2114                    "add a lifetime to the impl block and use it in the self type and associated \
2115                     type",
2116                    ::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![
2117                        (span, "<'a>".to_string()),
2118                        (sp, "'a ".to_string()),
2119                        (lifetime.shrink_to_hi(), "'a ".to_string()),
2120                    ],
2121                    Applicability::MaybeIncorrect,
2122                );
2123            } else if let Some(item) = &self.diag_metadata.current_item
2124                && let ItemKind::Impl(impl_) = &item.kind
2125                && let Some(of_trait) = &impl_.of_trait
2126                && let ControlFlow::Break(sp) = AnonRefFinder.visit_trait_ref(&of_trait.trait_ref)
2127            {
2128                err.multipart_suggestion(
2129                    "add a lifetime to the impl block and use it in the trait and associated type",
2130                    ::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![
2131                        (span, "<'a>".to_string()),
2132                        (sp, "'a".to_string()),
2133                        (lifetime.shrink_to_hi(), "'a ".to_string()),
2134                    ],
2135                    Applicability::MaybeIncorrect,
2136                );
2137            } else {
2138                err.span_label(
2139                    span,
2140                    "you could add a lifetime on the impl block, if the trait or the self type \
2141                     could have one",
2142                );
2143            }
2144        }
2145    }
2146
2147    #[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(2147u32),
                                    ::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))]
2148    fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
2149        let id = self.r.next_node_id();
2150        let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
2151
2152        self.record_lifetime_use(
2153            anchor_id,
2154            LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
2155            LifetimeElisionCandidate::Ignore,
2156        );
2157        self.resolve_anonymous_lifetime(&lt, anchor_id, true);
2158    }
2159
2160    #[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(2160u32),
                                    ::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:2168",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2168u32),
                                    ::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))]
2161    fn create_fresh_lifetime(
2162        &mut self,
2163        ident: Ident,
2164        binder: NodeId,
2165        kind: MissingLifetimeKind,
2166    ) -> LifetimeRes {
2167        debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
2168        debug!(?ident.span);
2169
2170        // Leave the responsibility to create the `LocalDefId` to lowering.
2171        let param = self.r.next_node_id();
2172        let res = LifetimeRes::Fresh { param, kind };
2173        self.record_lifetime_def(param, res);
2174
2175        // Record the created lifetime parameter so lowering can pick it up and add it to HIR.
2176        self.r
2177            .current_owner
2178            .extra_lifetime_params_map
2179            .entry(binder)
2180            .or_insert_with(Vec::new)
2181            .push((ident, param, kind));
2182        res
2183    }
2184
2185    #[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(2185u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("partial_res")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("partial_res");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path_span");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&partial_res)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path_span)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let proj_start = path.len() - partial_res.unresolved_segments();
            for (i, segment) in path.iter().enumerate() {
                if segment.has_lifetime_args { continue; }
                let Some(segment_id) = segment.id else { continue; };
                let type_def_id =
                    match partial_res.base_res() {
                        Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start =>
                            {
                            self.r.tcx.parent(def_id)
                        }
                        Res::Def(DefKind::Variant, def_id) if
                            i + 2 == proj_start && segment.has_generic_args => {
                            self.r.tcx.parent(def_id)
                        }
                        Res::Def(DefKind::Variant, def_id) if
                            i + 1 == proj_start &&
                                !i.checked_sub(1).is_some_and(|i| path[i].has_generic_args)
                            => {
                            self.r.tcx.parent(def_id)
                        }
                        Res::Def(DefKind::Struct, def_id) |
                            Res::Def(DefKind::Union, def_id) |
                            Res::Def(DefKind::Enum, def_id) |
                            Res::Def(DefKind::TyAlias, def_id) |
                            Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start => {
                            def_id
                        }
                        _ => continue,
                    };
                let expected_lifetimes =
                    self.r.item_generics_num_lifetimes(type_def_id);
                if expected_lifetimes == 0 { continue; }
                let node_ids = self.r.next_node_ids(expected_lifetimes);
                self.record_lifetime_use(segment_id,
                    LifetimeRes::ElidedAnchor {
                        start: node_ids.start,
                        end: node_ids.end,
                    }, LifetimeElisionCandidate::Ignore);
                let inferred =
                    match source {
                        PathSource::Trait(..) | PathSource::TraitItem(..) |
                            PathSource::Type | PathSource::PreciseCapturingArg(..) |
                            PathSource::ReturnTypeNotation | PathSource::Macro |
                            PathSource::Module => false,
                        PathSource::Expr(..) | PathSource::Pat |
                            PathSource::Struct(_) | PathSource::TupleStruct(..) |
                            PathSource::DefineOpaques | PathSource::Delegation |
                            PathSource::ExternItemImpl => true,
                    };
                if inferred {
                    for id in node_ids {
                        self.record_lifetime_use(id, LifetimeRes::Infer,
                            LifetimeElisionCandidate::Ignore);
                    }
                    continue;
                }
                let elided_lifetime_span =
                    if segment.has_generic_args {
                        segment.args_span.with_hi(segment.args_span.lo() +
                                BytePos(1))
                    } else {
                        segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
                    };
                let ident =
                    Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
                let kind =
                    if segment.has_generic_args {
                        MissingLifetimeKind::Comma
                    } else { MissingLifetimeKind::Brackets };
                let missing_lifetime =
                    MissingLifetime {
                        id: node_ids.start,
                        id_for_lint: segment_id,
                        span: elided_lifetime_span,
                        kind,
                        count: expected_lifetimes,
                    };
                let mut should_lint = true;
                for rib in self.lifetime_ribs.iter().rev() {
                    match rib.kind {
                        LifetimeRibKind::AnonymousCreateParameter {
                            report_in_path: true, .. } | LifetimeRibKind::Elided {
                            error_in_path: true, .. } => {
                            let sess = self.r.tcx.sess;
                            let subdiag =
                                elided_lifetime_in_path_suggestion(sess.source_map(),
                                    expected_lifetimes, path_span, !segment.has_generic_args,
                                    elided_lifetime_span);
                            let guar =
                                self.r.dcx().emit_err(crate::diagnostics::ImplicitElidedLifetimeNotAllowedHere {
                                        span: path_span,
                                        subdiag,
                                    });
                            should_lint = false;
                            for id in node_ids { self.record_lifetime_err(id, guar); }
                            break;
                        }
                        LifetimeRibKind::AnonymousCreateParameter { binder, .. } =>
                            {
                            let mut candidate =
                                LifetimeElisionCandidate::Missing(missing_lifetime);
                            for id in node_ids {
                                let res = self.create_fresh_lifetime(ident, binder, kind);
                                self.record_lifetime_use(id, res,
                                    replace(&mut candidate, LifetimeElisionCandidate::Ignore));
                            }
                            break;
                        }
                        LifetimeRibKind::Elided { res, error_in_path: false } => {
                            let mut candidate =
                                LifetimeElisionCandidate::Missing(missing_lifetime);
                            for id in node_ids {
                                self.record_lifetime_use(id, res,
                                    replace(&mut candidate, LifetimeElisionCandidate::Ignore));
                            }
                            break;
                        }
                        LifetimeRibKind::ElisionFailure => {
                            self.diag_metadata.current_elision_failures.push((missing_lifetime,
                                    Either::Right(node_ids)));
                            break;
                        }
                        LifetimeRibKind::AnonymousReportError |
                            LifetimeRibKind::Item => {
                            let guar =
                                self.report_missing_lifetime_specifiers([&missing_lifetime],
                                    None);
                            for id in node_ids { self.record_lifetime_err(id, guar); }
                            break;
                        }
                        LifetimeRibKind::Generics { .. } |
                            LifetimeRibKind::ConstParamTy | LifetimeRibKind::ImplTrait
                            => {}
                        LifetimeRibKind::ConcreteAnonConst(_) => {
                            ::rustc_middle::util::bug::span_bug_fmt(elided_lifetime_span,
                                format_args!("unexpected rib kind: {0:?}", rib.kind))
                        }
                    }
                }
                if should_lint {
                    let include_angle_bracket = !segment.has_generic_args;
                    self.r.lint_buffer.dyn_buffer_lint_any(lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
                        segment_id, elided_lifetime_span,
                        move |dcx, level, sess|
                            {
                                let source_map =
                                    sess.downcast_ref::<rustc_session::Session>().expect("expected a `Session`").source_map();
                                crate::diagnostics::ElidedLifetimesInPaths {
                                        subdiag: elided_lifetime_in_path_suggestion(source_map,
                                            expected_lifetimes, path_span, include_angle_bracket,
                                            elided_lifetime_span),
                                    }.into_diag(dcx, level)
                            });
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2186    fn resolve_elided_lifetimes_in_path(
2187        &mut self,
2188        partial_res: PartialRes,
2189        path: &[Segment],
2190        source: PathSource<'_, 'ast, 'ra>,
2191        path_span: Span,
2192    ) {
2193        let proj_start = path.len() - partial_res.unresolved_segments();
2194        for (i, segment) in path.iter().enumerate() {
2195            if segment.has_lifetime_args {
2196                continue;
2197            }
2198            let Some(segment_id) = segment.id else {
2199                continue;
2200            };
2201
2202            // Figure out if this is a type/trait segment,
2203            // which may need lifetime elision performed.
2204            let type_def_id = match partial_res.base_res() {
2205                Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2206                    self.r.tcx.parent(def_id)
2207                }
2208                Res::Def(DefKind::Variant, def_id)
2209                    if i + 2 == proj_start && segment.has_generic_args =>
2210                {
2211                    self.r.tcx.parent(def_id)
2212                }
2213                Res::Def(DefKind::Variant, def_id)
2214                    if i + 1 == proj_start
2215                        && !i.checked_sub(1).is_some_and(|i| path[i].has_generic_args) =>
2216                {
2217                    self.r.tcx.parent(def_id)
2218                }
2219                Res::Def(DefKind::Struct, def_id)
2220                | Res::Def(DefKind::Union, def_id)
2221                | Res::Def(DefKind::Enum, def_id)
2222                | Res::Def(DefKind::TyAlias, def_id)
2223                | Res::Def(DefKind::Trait, def_id)
2224                    if i + 1 == proj_start =>
2225                {
2226                    def_id
2227                }
2228                _ => continue,
2229            };
2230
2231            let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2232            if expected_lifetimes == 0 {
2233                continue;
2234            }
2235
2236            let node_ids = self.r.next_node_ids(expected_lifetimes);
2237            self.record_lifetime_use(
2238                segment_id,
2239                LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2240                LifetimeElisionCandidate::Ignore,
2241            );
2242
2243            let inferred = match source {
2244                PathSource::Trait(..)
2245                | PathSource::TraitItem(..)
2246                | PathSource::Type
2247                | PathSource::PreciseCapturingArg(..)
2248                | PathSource::ReturnTypeNotation
2249                | PathSource::Macro
2250                | PathSource::Module => false,
2251                PathSource::Expr(..)
2252                | PathSource::Pat
2253                | PathSource::Struct(_)
2254                | PathSource::TupleStruct(..)
2255                | PathSource::DefineOpaques
2256                | PathSource::Delegation
2257                | PathSource::ExternItemImpl => true,
2258            };
2259            if inferred {
2260                // Do not create a parameter for patterns and expressions: type checking can infer
2261                // the appropriate lifetime for us.
2262                for id in node_ids {
2263                    self.record_lifetime_use(
2264                        id,
2265                        LifetimeRes::Infer,
2266                        LifetimeElisionCandidate::Ignore,
2267                    );
2268                }
2269                continue;
2270            }
2271
2272            let elided_lifetime_span = if segment.has_generic_args {
2273                // If there are brackets, but not generic arguments, then use the opening bracket
2274                segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2275            } else {
2276                // If there are no brackets, use the identifier span.
2277                // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
2278                // originating from macros, since the segment's span might be from a macro arg.
2279                segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2280            };
2281            let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2282
2283            let kind = if segment.has_generic_args {
2284                MissingLifetimeKind::Comma
2285            } else {
2286                MissingLifetimeKind::Brackets
2287            };
2288            let missing_lifetime = MissingLifetime {
2289                id: node_ids.start,
2290                id_for_lint: segment_id,
2291                span: elided_lifetime_span,
2292                kind,
2293                count: expected_lifetimes,
2294            };
2295            let mut should_lint = true;
2296            for rib in self.lifetime_ribs.iter().rev() {
2297                match rib.kind {
2298                    // In create-parameter mode we error here because we don't want to support
2299                    // deprecated impl elision in new features like impl elision and `async fn`,
2300                    // both of which work using the `CreateParameter` mode:
2301                    //
2302                    //     impl Foo for std::cell::Ref<u32> // note lack of '_
2303                    //     async fn foo(_: std::cell::Ref<u32>) { ... }
2304                    LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2305                    | LifetimeRibKind::Elided { error_in_path: true, .. } => {
2306                        let sess = self.r.tcx.sess;
2307                        let subdiag = elided_lifetime_in_path_suggestion(
2308                            sess.source_map(),
2309                            expected_lifetimes,
2310                            path_span,
2311                            !segment.has_generic_args,
2312                            elided_lifetime_span,
2313                        );
2314                        let guar = self.r.dcx().emit_err(
2315                            crate::diagnostics::ImplicitElidedLifetimeNotAllowedHere {
2316                                span: path_span,
2317                                subdiag,
2318                            },
2319                        );
2320                        should_lint = false;
2321
2322                        for id in node_ids {
2323                            self.record_lifetime_err(id, guar);
2324                        }
2325                        break;
2326                    }
2327                    // Do not create a parameter for patterns and expressions.
2328                    LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2329                        // Group all suggestions into the first record.
2330                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2331                        for id in node_ids {
2332                            let res = self.create_fresh_lifetime(ident, binder, kind);
2333                            self.record_lifetime_use(
2334                                id,
2335                                res,
2336                                replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2337                            );
2338                        }
2339                        break;
2340                    }
2341                    LifetimeRibKind::Elided { res, error_in_path: false } => {
2342                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2343                        for id in node_ids {
2344                            self.record_lifetime_use(
2345                                id,
2346                                res,
2347                                replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2348                            );
2349                        }
2350                        break;
2351                    }
2352                    LifetimeRibKind::ElisionFailure => {
2353                        self.diag_metadata
2354                            .current_elision_failures
2355                            .push((missing_lifetime, Either::Right(node_ids)));
2356                        break;
2357                    }
2358                    // `LifetimeRes::Error`, which would usually be used in the case of
2359                    // `ReportError`, is unsuitable here, as we don't emit an error yet. Instead,
2360                    // we simply resolve to an implicit lifetime, which will be checked later, at
2361                    // which point a suitable error will be emitted.
2362                    LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2363                        let guar =
2364                            self.report_missing_lifetime_specifiers([&missing_lifetime], None);
2365                        for id in node_ids {
2366                            self.record_lifetime_err(id, guar);
2367                        }
2368                        break;
2369                    }
2370                    LifetimeRibKind::Generics { .. }
2371                    | LifetimeRibKind::ConstParamTy
2372                    | LifetimeRibKind::ImplTrait => {}
2373                    LifetimeRibKind::ConcreteAnonConst(_) => {
2374                        // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
2375                        span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2376                    }
2377                }
2378            }
2379
2380            if should_lint {
2381                let include_angle_bracket = !segment.has_generic_args;
2382                self.r.lint_buffer.dyn_buffer_lint_any(
2383                    lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2384                    segment_id,
2385                    elided_lifetime_span,
2386                    move |dcx, level, sess| {
2387                        let source_map = sess
2388                            .downcast_ref::<rustc_session::Session>()
2389                            .expect("expected a `Session`")
2390                            .source_map();
2391                        crate::diagnostics::ElidedLifetimesInPaths {
2392                            subdiag: elided_lifetime_in_path_suggestion(
2393                                source_map,
2394                                expected_lifetimes,
2395                                path_span,
2396                                include_angle_bracket,
2397                                elided_lifetime_span,
2398                            ),
2399                        }
2400                        .into_diag(dcx, level)
2401                    },
2402                );
2403            }
2404        }
2405    }
2406
2407    /// Register a use of an already defined lifetime.
2408    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("record_lifetime_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(2408u32),
                                    ::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))]
2409    fn record_lifetime_use(
2410        &mut self,
2411        id: NodeId,
2412        res: LifetimeRes,
2413        candidate: LifetimeElisionCandidate,
2414    ) {
2415        self.record_lifetime_def(id, res);
2416
2417        match res {
2418            LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2419                if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2420                    candidates.push((res, candidate));
2421                }
2422            }
2423            LifetimeRes::Infer | LifetimeRes::Error(..) | LifetimeRes::ElidedAnchor { .. } => {}
2424        }
2425    }
2426
2427    /// Can be used for both definitions and uses of lifetimes, as an error
2428    /// has already been reported.
2429    #[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(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("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))]
2430    fn record_lifetime_err(&mut self, id: NodeId, guar: ErrorGuaranteed) {
2431        self.record_lifetime_def(id, LifetimeRes::Error(guar));
2432    }
2433
2434    /// Define a new lifetime (e.g. in generics)
2435    #[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(2435u32),
                                    ::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))]
2436    fn record_lifetime_def(&mut self, id: NodeId, res: LifetimeRes) {
2437        if let Some(prev_res) = self.r.current_owner.lifetimes_res_map.insert(id, res) {
2438            panic!(
2439                "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2440            )
2441        }
2442    }
2443
2444    /// Perform resolution of a function signature, accounting for lifetime elision.
2445    #[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(2445u32),
                                    ::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:2461",
                                                "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                ::tracing_core::__macro_support::Option::Some(2461u32),
                                                ::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))]
2446    fn resolve_fn_signature(
2447        &mut self,
2448        fn_id: NodeId,
2449        has_self: bool,
2450        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2451        output_ty: &'ast FnRetTy,
2452        report_elided_lifetimes_in_path: bool,
2453    ) {
2454        let rib = LifetimeRibKind::AnonymousCreateParameter {
2455            binder: fn_id,
2456            report_in_path: report_elided_lifetimes_in_path,
2457        };
2458        self.with_lifetime_rib(rib, |this| {
2459            // Add each argument to the rib.
2460            let elision_lifetime = this.resolve_fn_params(has_self, inputs);
2461            debug!(?elision_lifetime);
2462
2463            let outer_failures = take(&mut this.diag_metadata.current_elision_failures);
2464            let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2465                if fn_id == this.r.current_owner.id {
2466                    this.r.current_owner.lifetime_elision_allowed = true;
2467                }
2468                LifetimeRibKind::elided(*res)
2469            } else {
2470                LifetimeRibKind::ElisionFailure
2471            };
2472            this.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2473            let elision_failures =
2474                replace(&mut this.diag_metadata.current_elision_failures, outer_failures);
2475            if !elision_failures.is_empty() {
2476                let Err(failure_info) = elision_lifetime else { bug!() };
2477                let guar = this.report_missing_lifetime_specifiers(
2478                    elision_failures.iter().map(|(missing_lifetime, ..)| missing_lifetime),
2479                    Some(failure_info),
2480                );
2481                let mut record_res = |lifetime| this.record_lifetime_err(lifetime, guar);
2482                for (_, nodes) in elision_failures {
2483                    match nodes {
2484                        Either::Left(node_id) => record_res(node_id),
2485                        Either::Right(node_ids) => {
2486                            for lifetime in node_ids {
2487                                record_res(lifetime)
2488                            }
2489                        }
2490                    }
2491                }
2492            }
2493        });
2494    }
2495
2496    /// Resolve inside function parameters and parameter types.
2497    /// Returns the lifetime for elision in fn return type,
2498    /// or diagnostic information in case of elision failure.
2499    fn resolve_fn_params(
2500        &mut self,
2501        has_self: bool,
2502        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2503    ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2504        enum Elision {
2505            /// We have not found any candidate.
2506            None,
2507            /// We have a candidate bound to `self`.
2508            Self_(LifetimeRes),
2509            /// We have a candidate bound to a parameter.
2510            Param(LifetimeRes),
2511            /// We failed elision.
2512            Err,
2513        }
2514
2515        // Save elision state to reinstate it later.
2516        let outer_candidates = self.lifetime_elision_candidates.take();
2517
2518        // Result of elision.
2519        let mut elision_lifetime = Elision::None;
2520        // Information for diagnostics.
2521        let mut parameter_info = Vec::new();
2522        let mut all_candidates = Vec::new();
2523
2524        // Resolve and apply bindings first so diagnostics can see if they're used in types.
2525        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())];
2526        for (pat, _) in inputs.clone() {
2527            {
    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:2527",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2527u32),
                        ::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:?}");
2528            self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
2529                if let Some(pat) = pat {
2530                    this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2531                }
2532            });
2533        }
2534        self.apply_pattern_bindings(bindings);
2535
2536        for (index, (pat, ty)) in inputs.enumerate() {
2537            {
    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:2537",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2537u32),
                        ::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:?}");
2538            // Record elision candidates only for this parameter.
2539            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);
2540            self.lifetime_elision_candidates = Some(Default::default());
2541            self.visit_ty(ty);
2542            let local_candidates = self.lifetime_elision_candidates.take();
2543
2544            if let Some(candidates) = local_candidates {
2545                let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2546                let lifetime_count = distinct.len();
2547                if lifetime_count != 0 {
2548                    parameter_info.push(ElisionFnParameter {
2549                        index,
2550                        ident: if let Some(pat) = pat
2551                            && let PatKind::Ident(_, ident, _) = pat.kind
2552                        {
2553                            Some(ident)
2554                        } else {
2555                            None
2556                        },
2557                        lifetime_count,
2558                        span: ty.span,
2559                    });
2560                    all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2561                        match candidate {
2562                            LifetimeElisionCandidate::Ignore => None,
2563                            LifetimeElisionCandidate::Missing(missing) => Some(missing),
2564                        }
2565                    }));
2566                }
2567                if !distinct.is_empty() {
2568                    match elision_lifetime {
2569                        // We are the first parameter to bind lifetimes.
2570                        Elision::None => {
2571                            if let Some(res) = distinct.get_only() {
2572                                // We have a single lifetime => success.
2573                                elision_lifetime = Elision::Param(*res)
2574                            } else {
2575                                // We have multiple lifetimes => error.
2576                                elision_lifetime = Elision::Err;
2577                            }
2578                        }
2579                        // We have 2 parameters that bind lifetimes => error.
2580                        Elision::Param(_) => elision_lifetime = Elision::Err,
2581                        // `self` elision takes precedence over everything else.
2582                        Elision::Self_(_) | Elision::Err => {}
2583                    }
2584                }
2585            }
2586
2587            // Handle `self` specially.
2588            if index == 0 && has_self {
2589                let self_lifetime = self.find_lifetime_for_self(ty);
2590                elision_lifetime = match self_lifetime {
2591                    // We found `self` elision.
2592                    Set1::One(lifetime) => Elision::Self_(lifetime),
2593                    // `self` itself had ambiguous lifetimes, e.g.
2594                    // &Box<&Self>. In this case we won't consider
2595                    // taking an alternative parameter lifetime; just avoid elision
2596                    // entirely.
2597                    Set1::Many => Elision::Err,
2598                    // We do not have `self` elision: disregard the `Elision::Param` that we may
2599                    // have found.
2600                    Set1::Empty => Elision::None,
2601                }
2602            }
2603            {
    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:2603",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2603u32),
                        ::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");
2604        }
2605
2606        // Reinstate elision state.
2607        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);
2608        self.lifetime_elision_candidates = outer_candidates;
2609
2610        if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2611            return Ok(res);
2612        }
2613
2614        // We do not have a candidate.
2615        Err((all_candidates, parameter_info))
2616    }
2617
2618    /// List all the lifetimes that appear in the provided type.
2619    fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2620        /// Visits a type to find all the &references, and determines the
2621        /// set of lifetimes for all of those references where the referent
2622        /// contains Self.
2623        struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2624            r: &'a Resolver<'ra, 'tcx>,
2625            impl_self: Option<Res>,
2626            lifetime: Set1<LifetimeRes>,
2627        }
2628
2629        impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2630            fn visit_ty(&mut self, ty: &'ra Ty) {
2631                {
    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:2631",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2631u32),
                        ::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);
2632                if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2633                    // See if anything inside the &thing contains Self
2634                    let mut visitor =
2635                        SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2636                    visitor.visit_ty(ty);
2637                    {
    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:2637",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2637u32),
                        ::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);
2638                    if visitor.self_found {
2639                        let lt_id = if let Some(lt) = lt {
2640                            lt.id
2641                        } else {
2642                            let res = self.r.current_owner.lifetimes_res_map[&ty.id];
2643                            let LifetimeRes::ElidedAnchor { start, .. } = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2644                            start
2645                        };
2646                        let lt_res = self.r.current_owner.lifetimes_res_map[&lt_id];
2647                        {
    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:2647",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2647u32),
                        ::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);
2648                        self.lifetime.insert(lt_res);
2649                    }
2650                }
2651                visit::walk_ty(self, ty)
2652            }
2653
2654            // A type may have an expression as a const generic argument.
2655            // We do not want to recurse into those.
2656            fn visit_expr(&mut self, _: &'ra Expr) {}
2657        }
2658
2659        /// Visitor which checks the referent of a &Thing to see if the
2660        /// Thing contains Self
2661        struct SelfVisitor<'a, 'ra, 'tcx> {
2662            r: &'a Resolver<'ra, 'tcx>,
2663            impl_self: Option<Res>,
2664            self_found: bool,
2665        }
2666
2667        impl SelfVisitor<'_, '_, '_> {
2668            // Look for `self: &'a Self` - also desugared from `&'a self`
2669            fn is_self_ty(&self, ty: &Ty) -> bool {
2670                match ty.kind {
2671                    TyKind::ImplicitSelf => true,
2672                    TyKind::Path(None, _) => {
2673                        let path_res = self.r.partial_res_map[&ty.id].full_res();
2674                        if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2675                            return true;
2676                        }
2677                        self.impl_self.is_some() && path_res == self.impl_self
2678                    }
2679                    _ => false,
2680                }
2681            }
2682        }
2683
2684        impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2685            fn visit_ty(&mut self, ty: &'ra Ty) {
2686                {
    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:2686",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2686u32),
                        ::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);
2687                if self.is_self_ty(ty) {
2688                    {
    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:2688",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2688u32),
                        ::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");
2689                    self.self_found = true;
2690                }
2691                visit::walk_ty(self, ty)
2692            }
2693
2694            // A type may have an expression as a const generic argument.
2695            // We do not want to recurse into those.
2696            fn visit_expr(&mut self, _: &'ra Expr) {}
2697        }
2698
2699        let impl_self = self
2700            .diag_metadata
2701            .current_self_type
2702            .and_then(|ty| {
2703                if let TyKind::Path(None, _) = ty.kind {
2704                    self.r.partial_res_map.get(&ty.id)
2705                } else {
2706                    None
2707                }
2708            })
2709            .and_then(|res| res.full_res())
2710            .filter(|res| {
2711                // Permit the types that unambiguously always
2712                // result in the same type constructor being used
2713                // (it can't differ between `Self` and `self`).
2714                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _) |
        Res::PrimTy(_) => true,
    _ => false,
}matches!(
2715                    res,
2716                    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2717                )
2718            });
2719        let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2720        visitor.visit_ty(ty);
2721        {
    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:2721",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2721u32),
                        ::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);
2722        visitor.lifetime
2723    }
2724
2725    /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
2726    /// label and reports an error if the label is not found or is unreachable.
2727    fn resolve_label(&self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2728        let mut suggestion = None;
2729
2730        for i in (0..self.label_ribs.len()).rev() {
2731            let rib = &self.label_ribs[i];
2732
2733            if let RibKind::MacroDefinition(def) = rib.kind
2734                // If an invocation of this macro created `ident`, give up on `ident`
2735                // and switch to `ident`'s source from the macro definition.
2736                && def == self.r.macro_def(label.span.ctxt())
2737            {
2738                label.span.remove_mark();
2739            }
2740
2741            let ident = label.normalize_to_macro_rules();
2742            if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2743                let definition_span = ident.span;
2744                return if self.is_label_valid_from_rib(i) {
2745                    Ok((*id, definition_span))
2746                } else {
2747                    Err(ResolutionError::UnreachableLabel {
2748                        name: label.name,
2749                        definition_span,
2750                        suggestion,
2751                    })
2752                };
2753            }
2754
2755            // Diagnostics: Check if this rib contains a label with a similar name, keep track of
2756            // the first such label that is encountered.
2757            suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2758        }
2759
2760        Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2761    }
2762
2763    /// Determine whether or not a label from the `rib_index`th label rib is reachable.
2764    fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2765        let ribs = &self.label_ribs[rib_index + 1..];
2766        ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2767    }
2768
2769    fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2770        {
    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:2770",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2770u32),
                        ::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");
2771        let kind = self.r.tcx.def_kind(self.r.current_owner.def_id);
2772        self.with_current_self_item(item, |this| {
2773            this.with_generic_param_rib(
2774                &generics.params,
2775                RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2776                item.id,
2777                LifetimeBinderKind::Item,
2778                generics.span,
2779                |this| {
2780                    let item_def_id = this.r.current_owner.def_id.to_def_id();
2781                    this.with_self_rib(
2782                        Res::SelfTyAlias { alias_to: item_def_id, is_trait_impl: false },
2783                        |this| {
2784                            visit::walk_item(this, item);
2785                        },
2786                    );
2787                },
2788            );
2789        });
2790    }
2791
2792    fn future_proof_import(&mut self, use_tree: &UseTree) {
2793        if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2794            let ident = segment.ident;
2795            if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2796                return;
2797            }
2798
2799            let nss = match use_tree.kind {
2800                UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2801                _ => &[TypeNS],
2802            };
2803            let report_error = |this: &Self, ns| {
2804                if this.should_report_errs() {
2805                    let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2806                    this.r.dcx().emit_err(crate::diagnostics::ImportsCannotReferTo {
2807                        span: ident.span,
2808                        what,
2809                    });
2810                }
2811            };
2812
2813            for &ns in nss {
2814                match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2815                    Some(LateDecl::RibDef(..)) => {
2816                        report_error(self, ns);
2817                    }
2818                    Some(LateDecl::Decl(binding)) => {
2819                        if let Some(LateDecl::RibDef(..)) =
2820                            self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2821                        {
2822                            report_error(self, ns);
2823                        }
2824                    }
2825                    None => {}
2826                }
2827            }
2828        } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2829            for (use_tree, _) in items {
2830                self.future_proof_import(use_tree);
2831            }
2832        }
2833    }
2834
2835    fn resolve_item(&mut self, item: &'ast Item) {
2836        let mod_inner_docs =
2837            #[allow(non_exhaustive_omitted_patterns)] match item.kind {
    ItemKind::Mod(..) => true,
    _ => false,
}matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2838        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(..)) {
2839            self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2840        }
2841
2842        {
    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:2842",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2842u32),
                        ::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);
2843
2844        let def_kind = self.r.tcx.def_kind(self.r.current_owner.def_id);
2845        match &item.kind {
2846            ItemKind::TyAlias(TyAlias { generics, .. }) => {
2847                self.with_generic_param_rib(
2848                    &generics.params,
2849                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2850                    item.id,
2851                    LifetimeBinderKind::Item,
2852                    generics.span,
2853                    |this| visit::walk_item(this, item),
2854                );
2855            }
2856
2857            ItemKind::Fn(Fn { generics, define_opaque, .. }) => {
2858                self.with_generic_param_rib(
2859                    &generics.params,
2860                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2861                    item.id,
2862                    LifetimeBinderKind::Function,
2863                    generics.span,
2864                    |this| visit::walk_item(this, item),
2865                );
2866                self.resolve_define_opaques(define_opaque);
2867            }
2868
2869            ItemKind::Enum(_, generics, _)
2870            | ItemKind::Struct(_, generics, _)
2871            | ItemKind::Union(_, generics, _) => {
2872                self.resolve_adt(item, generics);
2873            }
2874
2875            ItemKind::Impl(Impl { generics, of_trait, self_ty, items: impl_items, .. }) => {
2876                self.diag_metadata.current_impl_items = Some(impl_items);
2877                self.resolve_implementation(
2878                    &item.attrs,
2879                    generics,
2880                    of_trait.as_deref(),
2881                    self_ty,
2882                    item.id,
2883                    impl_items,
2884                );
2885                self.diag_metadata.current_impl_items = None;
2886            }
2887
2888            ItemKind::Trait(Trait { generics, bounds, items, impl_restriction, .. }) => {
2889                // resolve paths for `impl` restrictions
2890                self.resolve_restriction_path(
2891                    &impl_restriction.kind,
2892                    ResolvingRestrictionKind::Impl,
2893                );
2894
2895                // Create a new rib for the trait-wide type parameters.
2896                self.with_generic_param_rib(
2897                    &generics.params,
2898                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2899                    item.id,
2900                    LifetimeBinderKind::Item,
2901                    generics.span,
2902                    |this| {
2903                        let local_def_id = this.r.current_owner.def_id.to_def_id();
2904                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2905                            this.visit_generics(generics);
2906                            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);
2907                            this.resolve_trait_items(items);
2908                        });
2909                    },
2910                );
2911            }
2912
2913            ItemKind::TraitAlias(TraitAlias { generics, bounds, .. }) => {
2914                // Create a new rib for the trait-wide type parameters.
2915                self.with_generic_param_rib(
2916                    &generics.params,
2917                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2918                    item.id,
2919                    LifetimeBinderKind::Item,
2920                    generics.span,
2921                    |this| {
2922                        let local_def_id = this.r.current_owner.def_id.to_def_id();
2923                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2924                            this.visit_generics(generics);
2925                            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);
2926                        });
2927                    },
2928                );
2929            }
2930
2931            ItemKind::Mod(..) => {
2932                let module = self.r.expect_module(self.r.current_owner.def_id.to_def_id());
2933                let orig_module = replace(&mut self.parent_scope.module, module);
2934                self.with_rib(ValueNS, RibKind::Module(module.expect_local()), |this| {
2935                    this.with_rib(TypeNS, RibKind::Module(module.expect_local()), |this| {
2936                        if mod_inner_docs {
2937                            this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2938                        }
2939                        let old_macro_rules = this.parent_scope.macro_rules;
2940                        visit::walk_item(this, item);
2941                        // Maintain macro_rules scopes in the same way as during early resolution
2942                        // for diagnostics and doc links.
2943                        if item.attrs.iter().all(|attr| {
2944                            !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2945                        }) {
2946                            this.parent_scope.macro_rules = old_macro_rules;
2947                        }
2948                    })
2949                });
2950                self.parent_scope.module = orig_module;
2951            }
2952
2953            ItemKind::Static(ast::StaticItem {
2954                ident, ty, expr, define_opaque, eii_impls, ..
2955            }) => {
2956                self.with_static_rib(def_kind, |this| {
2957                    this.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Static), |this| {
2958                        this.visit_ty(ty);
2959                    });
2960                    if let Some(expr) = expr {
2961                        // We already forbid generic params because of the above item rib,
2962                        // so it doesn't matter whether this is a trivial constant.
2963                        this.resolve_static_body(expr, Some((*ident, ConstantItemKind::Static)));
2964                    }
2965                });
2966                self.resolve_define_opaques(define_opaque);
2967                self.resolve_eii(&eii_impls);
2968            }
2969
2970            ItemKind::Const(ast::ConstItem {
2971                ident,
2972                generics,
2973                ty,
2974                rhs_kind,
2975                define_opaque,
2976                defaultness: _,
2977            }) => {
2978                self.with_generic_param_rib(
2979                    &generics.params,
2980                    RibKind::Item(
2981                        if self.r.features.generic_const_items() {
2982                            HasGenericParams::Yes(generics.span)
2983                        } else {
2984                            HasGenericParams::No
2985                        },
2986                        def_kind,
2987                    ),
2988                    item.id,
2989                    LifetimeBinderKind::ConstItem,
2990                    generics.span,
2991                    |this| {
2992                        this.visit_generics(generics);
2993
2994                        this.with_lifetime_rib(
2995                            LifetimeRibKind::elided(LifetimeRes::Static),
2996                            |this: &mut LateResolutionVisitor<'a, 'ast, 'ra, 'tcx>| {
2997                                if rhs_kind.is_type_const()
2998                                    && !this.r.features.generic_const_parameter_types()
2999                                {
3000                                    this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3001                                        this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
3002                                            this.with_lifetime_rib(
3003                                                LifetimeRibKind::ConstParamTy,
3004                                                |this| this.visit_ty(ty),
3005                                            )
3006                                        })
3007                                    });
3008                                } else {
3009                                    this.visit_ty(ty);
3010                                }
3011                            },
3012                        );
3013
3014                        this.resolve_const_item_rhs(
3015                            rhs_kind,
3016                            Some((*ident, ConstantItemKind::Const)),
3017                        );
3018                    },
3019                );
3020                self.resolve_define_opaques(define_opaque);
3021            }
3022            ItemKind::ConstBlock(ConstBlockItem { id: _, span: _, block }) => self
3023                .with_generic_param_rib(
3024                    &[],
3025                    RibKind::Item(HasGenericParams::No, def_kind),
3026                    item.id,
3027                    LifetimeBinderKind::ConstItem,
3028                    DUMMY_SP,
3029                    |this| {
3030                        this.with_lifetime_rib(
3031                            LifetimeRibKind::elided(LifetimeRes::Infer),
3032                            |this| {
3033                                this.with_constant_rib(
3034                                    IsRepeatExpr::No,
3035                                    ConstantHasGenerics::Yes,
3036                                    Some((ConstBlockItem::IDENT, ConstantItemKind::Const)),
3037                                    |this| this.resolve_labeled_block(None, block.id, block),
3038                                )
3039                            },
3040                        );
3041                    },
3042                ),
3043
3044            ItemKind::Use(use_tree) => {
3045                let maybe_exported = match use_tree.kind {
3046                    UseTreeKind::Simple(_) | UseTreeKind::Glob(_) => MaybeExported::Ok(item.id),
3047                    UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
3048                };
3049                self.resolve_doc_links(&item.attrs, maybe_exported);
3050
3051                self.future_proof_import(use_tree);
3052            }
3053
3054            ItemKind::MacroDef(_, macro_def) => {
3055                // Maintain macro_rules scopes in the same way as during early resolution
3056                // for diagnostics and doc links.
3057                if macro_def.macro_rules {
3058                    let def_id = self.r.current_owner.def_id;
3059                    self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
3060                }
3061
3062                if let Some(EiiDecl { foreign_item: extern_item_path, impl_unsafe: _ }) =
3063                    &macro_def.eii_declaration
3064                {
3065                    self.smart_resolve_path(
3066                        item.id,
3067                        &None,
3068                        extern_item_path,
3069                        PathSource::ExternItemImpl,
3070                    );
3071                }
3072            }
3073
3074            ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
3075                visit::walk_item(self, item);
3076            }
3077
3078            ItemKind::Delegation(delegation) => {
3079                let span = delegation.path.segments.last().unwrap().ident.span;
3080                self.with_generic_param_rib(
3081                    &[],
3082                    RibKind::Item(HasGenericParams::Yes(span), def_kind),
3083                    item.id,
3084                    LifetimeBinderKind::Function,
3085                    span,
3086                    |this| this.resolve_delegation(delegation, item.id, false),
3087                );
3088            }
3089
3090            ItemKind::ExternCrate(..) => {}
3091
3092            ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
3093                {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3094            }
3095        }
3096    }
3097
3098    fn with_generic_param_rib<F>(
3099        &mut self,
3100        params: &[GenericParam],
3101        kind: RibKind<'ra>,
3102        binder: NodeId,
3103        generics_kind: LifetimeBinderKind,
3104        generics_span: Span,
3105        f: F,
3106    ) where
3107        F: FnOnce(&mut Self),
3108    {
3109        {
    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:3109",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3109u32),
                        ::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");
3110        let lifetime_kind =
3111            LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind };
3112
3113        let mut function_type_rib = Rib::new(kind);
3114        let mut function_value_rib = Rib::new(kind);
3115        let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
3116
3117        // Only check for shadowed bindings if we're declaring new params.
3118        if !params.is_empty() {
3119            let mut seen_bindings = FxHashMap::default();
3120            // Store all seen lifetimes names from outer scopes.
3121            let mut seen_lifetimes = FxHashSet::default();
3122
3123            // We also can't shadow bindings from associated parent items.
3124            for ns in [ValueNS, TypeNS] {
3125                for parent_rib in self.ribs[ns].iter().rev() {
3126                    // Break at module or block level, to account for nested items which are
3127                    // allowed to shadow generic param names.
3128                    if #[allow(non_exhaustive_omitted_patterns)] match parent_rib.kind {
    RibKind::Module(..) | RibKind::Block(..) => true,
    _ => false,
}matches!(parent_rib.kind, RibKind::Module(..) | RibKind::Block(..)) {
3129                        break;
3130                    }
3131
3132                    seen_bindings
3133                        .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
3134                }
3135            }
3136
3137            // Forbid shadowing lifetime bindings
3138            for rib in self.lifetime_ribs.iter().rev() {
3139                seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
3140                if let LifetimeRibKind::Item = rib.kind {
3141                    break;
3142                }
3143            }
3144
3145            for param in params {
3146                let ident = param.ident.normalize_to_macros_2_0();
3147                {
    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:3147",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3147u32),
                        ::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);
3148
3149                if let GenericParamKind::Lifetime = param.kind
3150                    && let Some(&original) = seen_lifetimes.get(&ident)
3151                {
3152                    let guar = diagnostics::signal_lifetime_shadowing(
3153                        self.r.tcx.sess,
3154                        original,
3155                        param.ident,
3156                    );
3157                    // Record lifetime res, so lowering knows there is something fishy.
3158                    self.record_lifetime_err(param.id, guar);
3159                    continue;
3160                }
3161
3162                match seen_bindings.entry(ident) {
3163                    Entry::Occupied(entry) => {
3164                        let span = *entry.get();
3165                        let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
3166                        let guar = self.r.report_error(param.ident.span, err);
3167                        let rib = match param.kind {
3168                            GenericParamKind::Lifetime => {
3169                                // Record lifetime res, so lowering knows there is something fishy.
3170                                self.record_lifetime_err(param.id, guar);
3171                                continue;
3172                            }
3173                            GenericParamKind::Type { .. } => &mut function_type_rib,
3174                            GenericParamKind::Const { .. } => &mut function_value_rib,
3175                        };
3176
3177                        // Taint the resolution in case of errors to prevent follow up errors in typeck
3178                        self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
3179                        rib.bindings.insert(ident, Res::Err);
3180                        continue;
3181                    }
3182                    Entry::Vacant(entry) => {
3183                        entry.insert(param.ident.span);
3184                    }
3185                }
3186
3187                if param.ident.name == kw::UnderscoreLifetime {
3188                    // To avoid emitting two similar errors,
3189                    // we need to check if the span is a raw underscore lifetime, see issue #143152
3190                    let is_raw_underscore_lifetime = self
3191                        .r
3192                        .tcx
3193                        .sess
3194                        .psess
3195                        .raw_identifier_spans
3196                        .iter()
3197                        .any(|span| span == param.span());
3198
3199                    let guar = self
3200                        .r
3201                        .dcx()
3202                        .create_err(crate::diagnostics::UnderscoreLifetimeIsReserved {
3203                            span: param.ident.span,
3204                        })
3205                        .emit_unless_delay(is_raw_underscore_lifetime);
3206                    // Record lifetime res, so lowering knows there is something fishy.
3207                    self.record_lifetime_err(param.id, guar);
3208                    continue;
3209                }
3210
3211                if param.ident.name == kw::StaticLifetime {
3212                    let guar =
3213                        self.r.dcx().emit_err(crate::diagnostics::StaticLifetimeIsReserved {
3214                            span: param.ident.span,
3215                            lifetime: param.ident,
3216                        });
3217                    // Record lifetime res, so lowering knows there is something fishy.
3218                    self.record_lifetime_err(param.id, guar);
3219                    continue;
3220                }
3221
3222                let def_id = self.r.local_def_id(param.id);
3223
3224                // Plain insert (no renaming).
3225                let (rib, def_kind) = match param.kind {
3226                    GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
3227                    GenericParamKind::Const { .. } => {
3228                        (&mut function_value_rib, DefKind::ConstParam)
3229                    }
3230                    GenericParamKind::Lifetime => {
3231                        let res = LifetimeRes::Param { param: def_id, binder };
3232                        self.record_lifetime_def(param.id, res);
3233                        function_lifetime_rib.bindings.insert(ident, (param.id, res));
3234                        continue;
3235                    }
3236                };
3237
3238                let res = match kind {
3239                    RibKind::Item(..) | RibKind::AssocItem => {
3240                        Res::Def(def_kind, def_id.to_def_id())
3241                    }
3242                    RibKind::Normal => {
3243                        // FIXME(non_lifetime_binders): Stop special-casing
3244                        // const params to error out here.
3245                        if self.r.features.non_lifetime_binders()
3246                            && #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    GenericParamKind::Type { .. } => true,
    _ => false,
}matches!(param.kind, GenericParamKind::Type { .. })
3247                        {
3248                            Res::Def(def_kind, def_id.to_def_id())
3249                        } else {
3250                            Res::Err
3251                        }
3252                    }
3253                    _ => ::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),
3254                };
3255                self.r.record_partial_res(param.id, PartialRes::new(res));
3256                rib.bindings.insert(ident, res);
3257            }
3258        }
3259
3260        self.lifetime_ribs.push(function_lifetime_rib);
3261        self.ribs[ValueNS].push(function_value_rib);
3262        self.ribs[TypeNS].push(function_type_rib);
3263
3264        f(self);
3265
3266        self.ribs[TypeNS].pop();
3267        self.ribs[ValueNS].pop();
3268        let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
3269
3270        // Do not account for the parameters we just bound for function lifetime elision.
3271        if let Some(ref mut candidates) = self.lifetime_elision_candidates {
3272            for (_, res) in function_lifetime_rib.bindings.values() {
3273                candidates.retain(|(r, _)| r != res);
3274            }
3275        }
3276
3277        if let LifetimeBinderKind::FnPtrType
3278        | LifetimeBinderKind::WhereBound
3279        | LifetimeBinderKind::Function
3280        | LifetimeBinderKind::ImplBlock = generics_kind
3281        {
3282            self.maybe_report_lifetime_uses(generics_span, params)
3283        }
3284    }
3285
3286    fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
3287        self.label_ribs.push(Rib::new(kind));
3288        f(self);
3289        self.label_ribs.pop();
3290    }
3291
3292    fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
3293        let kind = RibKind::Item(HasGenericParams::No, def_kind);
3294        self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
3295    }
3296
3297    // HACK(min_const_generics, generic_const_exprs): We
3298    // want to keep allowing `[0; size_of::<*mut T>()]`
3299    // with a future compat lint for now. We do this by adding an
3300    // additional special case for repeat expressions.
3301    //
3302    // Note that we intentionally still forbid `[0; N + 1]` during
3303    // name resolution so that we don't extend the future
3304    // compat lint to new cases.
3305    #[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(3305u32),
                                    ::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))]
3306    fn with_constant_rib(
3307        &mut self,
3308        is_repeat: IsRepeatExpr,
3309        may_use_generics: ConstantHasGenerics,
3310        item: Option<(Ident, ConstantItemKind)>,
3311        f: impl FnOnce(&mut Self),
3312    ) {
3313        let f = |this: &mut Self| {
3314            this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3315                this.with_rib(
3316                    TypeNS,
3317                    RibKind::ConstantItem(
3318                        may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3319                        item,
3320                    ),
3321                    |this| {
3322                        this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3323                    },
3324                )
3325            })
3326        };
3327
3328        if let ConstantHasGenerics::No(cause) = may_use_generics {
3329            self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3330        } else {
3331            f(self)
3332        }
3333    }
3334
3335    fn with_current_self_type<T>(
3336        &mut self,
3337        self_type: &'ast Ty,
3338        f: impl FnOnce(&mut Self) -> T,
3339    ) -> T {
3340        // Handle nested impls (inside fn bodies)
3341        let previous_value = replace(&mut self.diag_metadata.current_self_type, Some(self_type));
3342        let result = f(self);
3343        self.diag_metadata.current_self_type = previous_value;
3344        result
3345    }
3346
3347    fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3348        let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3349        let result = f(self);
3350        self.diag_metadata.current_self_item = previous_value;
3351        result
3352    }
3353
3354    /// When evaluating a `trait` use its associated types' idents for suggestions in E0425.
3355    fn resolve_trait_items(&mut self, trait_items: &'ast [Box<AssocItem>]) {
3356        let trait_assoc_items =
3357            replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3358
3359        for item in trait_items {
3360            with_owner(self, item.id, |this| this.resolve_trait_item(item));
3361        }
3362
3363        self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3364    }
3365
3366    fn resolve_trait_item(&mut self, item: &'ast Item<AssocItemKind>) {
3367        let walk_assoc_item =
3368            |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3369                this.with_generic_param_rib(
3370                    &generics.params,
3371                    RibKind::AssocItem,
3372                    item.id,
3373                    kind,
3374                    generics.span,
3375                    |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3376                );
3377            };
3378
3379        self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3380        match &item.kind {
3381            AssocItemKind::Const(ast::ConstItem {
3382                generics, ty, rhs_kind, define_opaque, ..
3383            }) => {
3384                self.with_generic_param_rib(
3385                    &generics.params,
3386                    RibKind::AssocItem,
3387                    item.id,
3388                    LifetimeBinderKind::ConstItem,
3389                    generics.span,
3390                    |this| {
3391                        this.with_lifetime_rib(
3392                            LifetimeRibKind::Elided {
3393                                res: LifetimeRes::Static,
3394                                error_in_path: true,
3395                            },
3396                            |this| {
3397                                this.visit_generics(generics);
3398                                if rhs_kind.is_type_const()
3399                                    && !this.r.features.generic_const_parameter_types()
3400                                {
3401                                    this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3402                                        this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
3403                                            this.with_lifetime_rib(
3404                                                LifetimeRibKind::ConstParamTy,
3405                                                |this| this.visit_ty(ty),
3406                                            )
3407                                        })
3408                                    });
3409                                } else {
3410                                    this.visit_ty(ty);
3411                                }
3412
3413                                // Only impose the restrictions of `ConstRibKind` for an
3414                                // actual constant expression in a provided default.
3415                                //
3416                                // We allow arbitrary const expressions inside of associated consts,
3417                                // even if they are potentially not const evaluatable.
3418                                //
3419                                // Type parameters can already be used and as associated consts are
3420                                // not used as part of the type system, this is far less surprising.
3421                                this.resolve_const_item_rhs(rhs_kind, None);
3422                            },
3423                        )
3424                    },
3425                );
3426
3427                self.resolve_define_opaques(define_opaque);
3428            }
3429            AssocItemKind::Fn(Fn { generics, define_opaque, .. }) => {
3430                walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3431
3432                self.resolve_define_opaques(define_opaque);
3433            }
3434            AssocItemKind::Delegation(delegation) => {
3435                self.with_generic_param_rib(
3436                    &[],
3437                    RibKind::AssocItem,
3438                    item.id,
3439                    LifetimeBinderKind::Function,
3440                    delegation.path.segments.last().unwrap().ident.span,
3441                    |this| this.resolve_delegation(delegation, item.id, false),
3442                );
3443            }
3444            AssocItemKind::Type(TyAlias { generics, .. }) => self
3445                .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3446                    walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3447                }),
3448            AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3449                {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3450            }
3451        };
3452    }
3453
3454    /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
3455    fn with_optional_trait_ref<T>(
3456        &mut self,
3457        opt_trait_ref: Option<&TraitRef>,
3458        self_type: &'ast Ty,
3459        f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3460    ) -> T {
3461        let mut new_val = None;
3462        let mut new_id = None;
3463        if let Some(trait_ref) = opt_trait_ref {
3464            let path: Vec<_> = Segment::from_path(&trait_ref.path);
3465            self.diag_metadata.currently_processing_impl_trait =
3466                Some((trait_ref.clone(), self_type.clone()));
3467            let res = self.smart_resolve_path_fragment(
3468                &None,
3469                &path,
3470                PathSource::Trait(AliasPossibility::No),
3471                Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3472                RecordPartialRes::Yes,
3473                None,
3474            );
3475            self.diag_metadata.currently_processing_impl_trait = None;
3476            if let Some(def_id) = res.expect_full_res().opt_def_id() {
3477                new_id = Some(def_id);
3478                new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3479            }
3480        }
3481        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3482        let result = f(self, new_id);
3483        self.current_trait_ref = original_trait_ref;
3484        result
3485    }
3486
3487    fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3488        let mut self_type_rib = Rib::new(RibKind::Normal);
3489
3490        // Plain insert (no renaming, since types are not currently hygienic)
3491        self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3492        self.ribs[ns].push(self_type_rib);
3493        f(self);
3494        self.ribs[ns].pop();
3495    }
3496
3497    fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3498        self.with_self_rib_ns(TypeNS, self_res, f)
3499    }
3500
3501    fn resolve_implementation(
3502        &mut self,
3503        attrs: &[ast::Attribute],
3504        generics: &'ast Generics,
3505        of_trait: Option<&'ast ast::TraitImplHeader>,
3506        self_type: &'ast Ty,
3507        item_id: NodeId,
3508        impl_items: &'ast [Box<AssocItem>],
3509    ) {
3510        {
    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:3510",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3510u32),
                        ::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");
3511        // If applicable, create a rib for the type parameters.
3512        self.with_generic_param_rib(
3513            &generics.params,
3514            RibKind::Item(HasGenericParams::Yes(generics.span), self.r.tcx.def_kind(self.r.current_owner.def_id)),
3515            item_id,
3516            LifetimeBinderKind::ImplBlock,
3517            generics.span,
3518            |this| {
3519                // Dummy self type for better errors if `Self` is used in the trait path.
3520                this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3521                    this.with_lifetime_rib(
3522                        LifetimeRibKind::AnonymousCreateParameter {
3523                            binder: item_id,
3524                            report_in_path: true
3525                        },
3526                        |this| {
3527                            // Resolve the trait reference, if necessary.
3528                            this.with_optional_trait_ref(
3529                                of_trait.map(|t| &t.trait_ref),
3530                                self_type,
3531                                |this, trait_id| {
3532                                    this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3533
3534                                    let item_def_id = this.r.current_owner.def_id;
3535
3536                                    // Register the trait definitions from here.
3537                                    if let Some(trait_id) = trait_id {
3538                                        this.r
3539                                            .trait_impls
3540                                            .entry(trait_id)
3541                                            .or_default()
3542                                            .push(item_def_id);
3543                                    }
3544
3545                                    let item_def_id = item_def_id.to_def_id();
3546                                    let res = Res::SelfTyAlias {
3547                                        alias_to: item_def_id,
3548                                        is_trait_impl: trait_id.is_some(),
3549                                    };
3550                                    this.with_self_rib(res, |this| {
3551                                        if let Some(of_trait) = of_trait {
3552                                            // Resolve type arguments in the trait path.
3553                                            visit::walk_trait_ref(this, &of_trait.trait_ref);
3554                                        }
3555                                        // Resolve the self type.
3556                                        this.visit_ty(self_type);
3557                                        // Resolve the generic parameters.
3558                                        this.visit_generics(generics);
3559
3560                                        // Resolve the items within the impl.
3561                                        this.with_current_self_type(self_type, |this| {
3562                                            this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3563                                                {
    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:3563",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3563u32),
                        ::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, ...)");
3564                                                let mut seen_trait_items = Default::default();
3565                                                for item in impl_items {
3566                                                    with_owner(this, item.id, |this| {
3567                                                        this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id, of_trait.is_some());
3568                                                    })
3569                                                }
3570                                            });
3571                                        });
3572                                    });
3573                                },
3574                            )
3575                        },
3576                    );
3577                });
3578            },
3579        );
3580    }
3581
3582    fn resolve_impl_item(
3583        &mut self,
3584        item: &'ast AssocItem,
3585        seen_trait_items: &mut FxHashMap<DefId, Span>,
3586        trait_id: Option<DefId>,
3587        is_in_trait_impl: bool,
3588    ) {
3589        use crate::ResolutionError::*;
3590        self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3591        let prev = self.diag_metadata.current_impl_item.take();
3592        self.diag_metadata.current_impl_item = Some(&item);
3593        match &item.kind {
3594            AssocItemKind::Const(ast::ConstItem {
3595                ident,
3596                generics,
3597                ty,
3598                rhs_kind,
3599                define_opaque,
3600                ..
3601            }) => {
3602                {
    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:3602",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3602u32),
                        ::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");
3603                self.with_generic_param_rib(
3604                    &generics.params,
3605                    RibKind::AssocItem,
3606                    item.id,
3607                    LifetimeBinderKind::ConstItem,
3608                    generics.span,
3609                    |this| {
3610                        this.with_lifetime_rib(
3611                            LifetimeRibKind::Elided {
3612                                res: LifetimeRes::Static,
3613                                error_in_path: true,
3614                            },
3615                            |this| {
3616                                // If this is a trait impl, ensure the const
3617                                // exists in trait
3618                                this.check_trait_item(
3619                                    item.id,
3620                                    *ident,
3621                                    *ident,
3622                                    &item.kind,
3623                                    ValueNS,
3624                                    item.span,
3625                                    seen_trait_items,
3626                                    |i, s, c| ConstNotMemberOfTrait(i, s, c),
3627                                );
3628
3629                                this.visit_generics(generics);
3630                                if rhs_kind.is_type_const()
3631                                    && !this.r.tcx.features().generic_const_parameter_types()
3632                                {
3633                                    this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3634                                        this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
3635                                            this.with_lifetime_rib(
3636                                                LifetimeRibKind::ConstParamTy,
3637                                                |this| this.visit_ty(ty),
3638                                            )
3639                                        })
3640                                    });
3641                                } else {
3642                                    this.visit_ty(ty);
3643                                }
3644                                // We allow arbitrary const expressions inside of associated consts,
3645                                // even if they are potentially not const evaluatable.
3646                                //
3647                                // Type parameters can already be used and as associated consts are
3648                                // not used as part of the type system, this is far less surprising.
3649                                this.resolve_const_item_rhs(rhs_kind, None);
3650                            },
3651                        )
3652                    },
3653                );
3654                self.resolve_define_opaques(define_opaque);
3655            }
3656            AssocItemKind::Fn(fn_kind @ Fn { ident, generics, define_opaque, .. }) => {
3657                {
    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:3657",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3657u32),
                        ::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");
3658                // We also need a new scope for the impl item type parameters.
3659                self.with_generic_param_rib(
3660                    &generics.params,
3661                    RibKind::AssocItem,
3662                    item.id,
3663                    LifetimeBinderKind::Function,
3664                    generics.span,
3665                    |this| {
3666                        let effective_ident = if is_in_trait_impl && fn_kind.is_pin_drop_sugar() {
3667                            Ident::new(sym::pin_drop, ident.span)
3668                        } else {
3669                            *ident
3670                        };
3671                        // If this is a trait impl, ensure the method
3672                        // exists in trait
3673                        this.check_trait_item(
3674                            item.id,
3675                            effective_ident,
3676                            *ident,
3677                            &item.kind,
3678                            ValueNS,
3679                            item.span,
3680                            seen_trait_items,
3681                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3682                        );
3683
3684                        visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3685                    },
3686                );
3687
3688                self.resolve_define_opaques(define_opaque);
3689            }
3690            AssocItemKind::Type(TyAlias { ident, generics, .. }) => {
3691                self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3692                {
    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:3692",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3692u32),
                        ::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");
3693                // We also need a new scope for the impl item type parameters.
3694                self.with_generic_param_rib(
3695                    &generics.params,
3696                    RibKind::AssocItem,
3697                    item.id,
3698                    LifetimeBinderKind::ImplAssocType,
3699                    generics.span,
3700                    |this| {
3701                        this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3702                            // If this is a trait impl, ensure the type
3703                            // exists in trait
3704                            this.check_trait_item(
3705                                item.id,
3706                                *ident,
3707                                *ident,
3708                                &item.kind,
3709                                TypeNS,
3710                                item.span,
3711                                seen_trait_items,
3712                                |i, s, c| TypeNotMemberOfTrait(i, s, c),
3713                            );
3714
3715                            visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3716                        });
3717                    },
3718                );
3719                self.diag_metadata.in_non_gat_assoc_type = None;
3720            }
3721            AssocItemKind::Delegation(delegation) => {
3722                {
    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:3722",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3722u32),
                        ::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");
3723                self.with_generic_param_rib(
3724                    &[],
3725                    RibKind::AssocItem,
3726                    item.id,
3727                    LifetimeBinderKind::Function,
3728                    delegation.path.segments.last().unwrap().ident.span,
3729                    |this| {
3730                        this.check_trait_item(
3731                            item.id,
3732                            delegation.ident,
3733                            delegation.ident,
3734                            &item.kind,
3735                            ValueNS,
3736                            item.span,
3737                            seen_trait_items,
3738                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3739                        );
3740
3741                        // Here we don't use `trait_id`, as we can process unresolved trait, however
3742                        // in this case we are still in a trait impl, https://github.com/rust-lang/rust/issues/150152
3743                        this.resolve_delegation(delegation, item.id, is_in_trait_impl);
3744                    },
3745                );
3746            }
3747            AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3748                {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3749            }
3750        }
3751        self.diag_metadata.current_impl_item = prev;
3752    }
3753
3754    fn check_trait_item<F>(
3755        &mut self,
3756        id: NodeId,
3757        mut ident: Ident,
3758        mut reported_ident: Ident,
3759        kind: &AssocItemKind,
3760        ns: Namespace,
3761        span: Span,
3762        seen_trait_items: &mut FxHashMap<DefId, Span>,
3763        err: F,
3764    ) where
3765        F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3766    {
3767        // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3768        let Some((module, _)) = self.current_trait_ref else {
3769            return;
3770        };
3771        ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3772        reported_ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3773        let key = BindingKey::new(IdentKey::new(ident), ns);
3774        let mut decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3775        {
    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:3775",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3775u32),
                        ::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);
3776        if decl.is_none() {
3777            // We could not find the trait item in the correct namespace.
3778            // Check the other namespace to report an error.
3779            let ns = match ns {
3780                ValueNS => TypeNS,
3781                TypeNS => ValueNS,
3782                _ => ns,
3783            };
3784            let key = BindingKey::new(IdentKey::new(ident), ns);
3785            decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3786            {
    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:3786",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3786u32),
                        ::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);
3787        }
3788
3789        let feed_visibility = |this: &mut Self, def_id| {
3790            let vis = this.r.tcx.visibility(def_id);
3791            let vis = if vis.is_visible_locally() {
3792                vis.expect_local()
3793            } else {
3794                this.r.dcx().span_delayed_bug(
3795                    span,
3796                    "error should be emitted when an unexpected trait item is used",
3797                );
3798                Visibility::Public
3799            };
3800            // HACK: because we don't want to track the `TyCtxtFeed` through the resolver to here
3801            // in a hash-map, we instead conjure a `TyCtxtFeed` for any `DefId` here, but prevent
3802            // it from being used generally.
3803            this.r.tcx.feed_visibility_for_trait_impl_item(this.r.current_owner.def_id, vis);
3804        };
3805
3806        let Some(decl) = decl else {
3807            // We could not find the method: report an error.
3808            let candidate = self.find_similarly_named_assoc_item(reported_ident.name, kind);
3809            let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3810            let path_names = path_names_to_string(path);
3811            self.report_error(span, err(reported_ident, path_names, candidate));
3812            feed_visibility(self, module.def_id());
3813            return;
3814        };
3815
3816        let res = decl.res();
3817        let Res::Def(def_kind, id_in_trait) = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
3818        feed_visibility(self, id_in_trait);
3819
3820        match seen_trait_items.entry(id_in_trait) {
3821            Entry::Occupied(entry) => {
3822                self.report_error(
3823                    span,
3824                    ResolutionError::TraitImplDuplicate {
3825                        name: ident,
3826                        old_span: *entry.get(),
3827                        trait_item_span: decl.span,
3828                    },
3829                );
3830                return;
3831            }
3832            Entry::Vacant(entry) => {
3833                entry.insert(span);
3834            }
3835        };
3836
3837        match (def_kind, kind) {
3838            (DefKind::AssocTy, AssocItemKind::Type(..))
3839            | (DefKind::AssocFn, AssocItemKind::Fn(..))
3840            | (DefKind::AssocConst { .. }, AssocItemKind::Const(..))
3841            | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3842                self.r.record_partial_res(id, PartialRes::new(res));
3843                return;
3844            }
3845            _ => {}
3846        }
3847
3848        // The method kind does not correspond to what appeared in the trait, report.
3849        let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3850        let (code, kind) = match kind {
3851            AssocItemKind::Const(..) => (E0323, "const"),
3852            AssocItemKind::Fn(..) => (E0324, "method"),
3853            AssocItemKind::Type(..) => (E0325, "type"),
3854            AssocItemKind::Delegation(..) => (E0324, "method"),
3855            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3856                ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("unexpanded macro"))span_bug!(span, "unexpanded macro")
3857            }
3858        };
3859        let trait_path = path_names_to_string(path);
3860        self.report_error(
3861            span,
3862            ResolutionError::TraitImplMismatch {
3863                name: ident,
3864                kind,
3865                code,
3866                trait_path,
3867                trait_item_span: decl.span,
3868            },
3869        );
3870    }
3871
3872    fn resolve_static_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3873        self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3874            this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3875                this.visit_expr(expr)
3876            });
3877        })
3878    }
3879
3880    fn resolve_const_item_rhs(
3881        &mut self,
3882        rhs_kind: &'ast ConstItemRhsKind,
3883        item: Option<(Ident, ConstantItemKind)>,
3884    ) {
3885        self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| match rhs_kind {
3886            ConstItemRhsKind::TypeConst { rhs: Some(anon_const) } => {
3887                this.resolve_anon_const(anon_const, AnonConstKind::ConstArg(IsRepeatExpr::No));
3888            }
3889            ConstItemRhsKind::Body { rhs: Some(expr) } => {
3890                this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3891                    this.visit_expr(expr)
3892                });
3893            }
3894            _ => (),
3895        })
3896    }
3897
3898    fn resolve_delegation(
3899        &mut self,
3900        delegation: &'ast Delegation,
3901        item_id: NodeId,
3902        is_in_trait_impl: bool,
3903    ) {
3904        self.smart_resolve_path(
3905            delegation.id,
3906            &delegation.qself,
3907            &delegation.path,
3908            PathSource::Delegation,
3909        );
3910
3911        // Create lifetimes not with `LifetimeRibKind::Generics` but with `LifetimeRibKind::Elided`,
3912        // as we are not processing generic params but generic args in a future call (#156342, #156758).
3913        self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3914            if let Some(qself) = &delegation.qself {
3915                this.visit_ty(&qself.ty);
3916            }
3917
3918            this.visit_path(&delegation.path);
3919        });
3920
3921        let resolution_node_id = if is_in_trait_impl { item_id } else { delegation.id };
3922        let def_id = self
3923            .r
3924            .partial_res_map
3925            .get(&resolution_node_id)
3926            .and_then(|r| r.expect_full_res().opt_def_id());
3927
3928        let resolution_id = def_id.ok_or_else(|| {
3929            self.r.tcx.dcx().span_delayed_bug(
3930                delegation.path.span,
3931                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("LateResolutionVisitor: couldn\'t resolve node {0:?} in delegation item",
                resolution_node_id))
    })format!(
3932                    "LateResolutionVisitor: couldn't resolve node {resolution_node_id:?} in delegation item",
3933                ),
3934            )
3935        });
3936
3937        let info = DelegationInfo { resolution_id };
3938        self.r.delegation_infos.insert(self.r.current_owner.def_id, info);
3939
3940        let Some(body) = &delegation.body else { return };
3941        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3942            let ident = Ident::new(kw::SelfLower, body.span.normalize_to_macro_rules());
3943            let res = Res::Local(delegation.id);
3944            this.innermost_rib_bindings(ValueNS).insert(ident, res);
3945
3946            //As we lower target_expr_template body to a body of a function we need a label rib (#148889)
3947            this.with_label_rib(RibKind::FnOrCoroutine, |this| {
3948                this.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3949                    this.visit_block(body);
3950                });
3951            });
3952        });
3953    }
3954
3955    fn resolve_params(&mut self, params: &'ast [Param]) {
3956        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())];
3957        self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3958            for Param { pat, .. } in params {
3959                this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3960            }
3961            this.apply_pattern_bindings(bindings);
3962        });
3963        for Param { ty, .. } in params {
3964            self.visit_ty(ty);
3965        }
3966    }
3967
3968    fn resolve_local(&mut self, local: &'ast Local) {
3969        {
    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:3969",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3969u32),
                        ::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);
3970        // Resolve the type.
3971        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);
3972
3973        // Resolve the initializer.
3974        if let Some((init, els)) = local.kind.init_else_opt() {
3975            self.visit_expr(init);
3976
3977            // Resolve the `else` block
3978            if let Some(els) = els {
3979                self.visit_block(els);
3980            }
3981        }
3982
3983        // Resolve the pattern.
3984        self.resolve_pattern_top(&local.pat, PatternSource::Let);
3985    }
3986
3987    /// Build a map from pattern identifiers to binding-info's, and check the bindings are
3988    /// consistent when encountering or-patterns and never patterns.
3989    /// This is done hygienically: this could arise for a macro that expands into an or-pattern
3990    /// where one 'x' was from the user and one 'x' came from the macro.
3991    ///
3992    /// A never pattern by definition indicates an unreachable case. For example, matching on
3993    /// `Result<T, &!>` could look like:
3994    /// ```rust
3995    /// # #![feature(never_type)]
3996    /// # #![feature(never_patterns)]
3997    /// # fn bar(_x: u32) {}
3998    /// let foo: Result<u32, &!> = Ok(0);
3999    /// match foo {
4000    ///     Ok(x) => bar(x),
4001    ///     Err(&!),
4002    /// }
4003    /// ```
4004    /// This extends to product types: `(x, !)` is likewise unreachable. So it doesn't make sense to
4005    /// have a binding here, and we tell the user to use `_` instead.
4006    fn compute_and_check_binding_map(
4007        &mut self,
4008        pat: &Pat,
4009    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
4010        let mut binding_map = FxIndexMap::default();
4011        let mut is_never_pat = false;
4012
4013        pat.walk(&mut |pat| {
4014            match pat.kind {
4015                PatKind::Ident(annotation, ident, ref sub_pat)
4016                    if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
4017                {
4018                    binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
4019                }
4020                PatKind::Or(ref ps) => {
4021                    // Check the consistency of this or-pattern and
4022                    // then add all bindings to the larger map.
4023                    match self.compute_and_check_or_pat_binding_map(ps) {
4024                        Ok(bm) => binding_map.extend(bm),
4025                        Err(IsNeverPattern) => is_never_pat = true,
4026                    }
4027                    return false;
4028                }
4029                PatKind::Never => is_never_pat = true,
4030                _ => {}
4031            }
4032
4033            true
4034        });
4035
4036        if is_never_pat {
4037            for (_, binding) in binding_map {
4038                self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
4039            }
4040            Err(IsNeverPattern)
4041        } else {
4042            Ok(binding_map)
4043        }
4044    }
4045
4046    fn is_base_res_local(&self, nid: NodeId) -> bool {
4047        #[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!(
4048            self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
4049            Some(Res::Local(..))
4050        )
4051    }
4052
4053    /// Compute the binding map for an or-pattern. Checks that all of the arms in the or-pattern
4054    /// have exactly the same set of bindings, with the same binding modes for each.
4055    /// Returns the computed binding map and a boolean indicating whether the pattern is a never
4056    /// pattern.
4057    ///
4058    /// A never pattern by definition indicates an unreachable case. For example, destructuring a
4059    /// `Result<T, &!>` could look like:
4060    /// ```rust
4061    /// # #![feature(never_type)]
4062    /// # #![feature(never_patterns)]
4063    /// # fn foo() -> Result<bool, &'static !> { Ok(true) }
4064    /// let (Ok(x) | Err(&!)) = foo();
4065    /// # let _ = x;
4066    /// ```
4067    /// Because the `Err(&!)` branch is never reached, it does not need to have the same bindings as
4068    /// the other branches of the or-pattern. So we must ignore never pattern when checking the
4069    /// bindings of an or-pattern.
4070    /// Moreover, if all the subpatterns are never patterns (e.g. `Ok(!) | Err(!)`), then the
4071    /// pattern as a whole counts as a never pattern (since it's definitionallly unreachable).
4072    fn compute_and_check_or_pat_binding_map(
4073        &mut self,
4074        pats: &[Pat],
4075    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
4076        let mut missing_vars = FxIndexMap::default();
4077        let mut inconsistent_vars = FxIndexMap::default();
4078
4079        // 1) Compute the binding maps of all arms; we must ignore never patterns here.
4080        let not_never_pats = pats
4081            .iter()
4082            .filter_map(|pat| {
4083                let binding_map = self.compute_and_check_binding_map(pat).ok()?;
4084                Some((binding_map, pat))
4085            })
4086            .collect::<Vec<_>>();
4087
4088        // 2) Record any missing bindings or binding mode inconsistencies.
4089        for &(ref map_outer, pat_outer) in not_never_pats.iter() {
4090            // Check against all arms except for the same pattern which is always self-consistent.
4091            let inners = not_never_pats.iter().filter(|(_, pat)| pat.id != pat_outer.id);
4092
4093            for &(ref map, pat) in inners {
4094                for (&name, binding_inner) in map {
4095                    match map_outer.get(&name) {
4096                        None => {
4097                            // The inner binding is missing in the outer.
4098                            let binding_error =
4099                                missing_vars.entry(name).or_insert_with(|| BindingError {
4100                                    name,
4101                                    origin: Default::default(),
4102                                    target: Default::default(),
4103                                    could_be_path: name.as_str().starts_with(char::is_uppercase),
4104                                });
4105                            binding_error.origin.push((binding_inner.span, pat.clone()));
4106                            binding_error.target.push(pat_outer.clone());
4107                        }
4108                        Some(binding_outer) => {
4109                            if binding_outer.annotation != binding_inner.annotation {
4110                                // The binding modes in the outer and inner bindings differ.
4111                                inconsistent_vars
4112                                    .entry(name)
4113                                    .or_insert((binding_inner.span, binding_outer.span));
4114                            }
4115                        }
4116                    }
4117                }
4118            }
4119        }
4120
4121        // 3) Report all missing variables we found.
4122        for (name, mut v) in missing_vars {
4123            if inconsistent_vars.contains_key(&name) {
4124                v.could_be_path = false;
4125            }
4126            self.report_error(
4127                v.origin.iter().next().unwrap().0,
4128                ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
4129            );
4130        }
4131
4132        // 4) Report all inconsistencies in binding modes we found.
4133        for (name, v) in inconsistent_vars {
4134            self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
4135        }
4136
4137        // 5) Bubble up the final binding map.
4138        if not_never_pats.is_empty() {
4139            // All the patterns are never patterns, so the whole or-pattern is one too.
4140            Err(IsNeverPattern)
4141        } else {
4142            let mut binding_map = FxIndexMap::default();
4143            for (bm, _) in not_never_pats {
4144                binding_map.extend(bm);
4145            }
4146            Ok(binding_map)
4147        }
4148    }
4149
4150    /// Check the consistency of bindings wrt or-patterns and never patterns.
4151    fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
4152        let mut is_or_or_never = false;
4153        pat.walk(&mut |pat| match pat.kind {
4154            PatKind::Or(..) | PatKind::Never => {
4155                is_or_or_never = true;
4156                false
4157            }
4158            _ => true,
4159        });
4160        if is_or_or_never {
4161            let _ = self.compute_and_check_binding_map(pat);
4162        }
4163    }
4164
4165    fn resolve_arm(&mut self, arm: &'ast Arm) {
4166        self.with_rib(ValueNS, RibKind::Normal, |this| {
4167            this.resolve_pattern_top(&arm.pat, PatternSource::Match);
4168            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));
4169            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);
4170        });
4171    }
4172
4173    /// Arising from `source`, resolve a top level pattern.
4174    fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
4175        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())];
4176        self.resolve_pattern(pat, pat_src, &mut bindings);
4177        self.apply_pattern_bindings(bindings);
4178    }
4179
4180    /// Apply the bindings from a pattern to the innermost rib of the current scope.
4181    fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
4182        let rib_bindings = self.innermost_rib_bindings(ValueNS);
4183        let Some((_, pat_bindings)) = pat_bindings.pop() else {
4184            ::rustc_middle::util::bug::bug_fmt(format_args!("tried applying nonexistent bindings from pattern"));bug!("tried applying nonexistent bindings from pattern");
4185        };
4186
4187        if rib_bindings.is_empty() {
4188            // Often, such as for match arms, the bindings are introduced into a new rib.
4189            // In this case, we can move the bindings over directly.
4190            *rib_bindings = pat_bindings;
4191        } else {
4192            rib_bindings.extend(pat_bindings);
4193        }
4194    }
4195
4196    /// Resolve bindings in a pattern. `apply_pattern_bindings` must be called after to introduce
4197    /// the bindings into scope.
4198    fn resolve_pattern(
4199        &mut self,
4200        pat: &'ast Pat,
4201        pat_src: PatternSource,
4202        bindings: &mut PatternBindings,
4203    ) {
4204        // We walk the pattern before declaring the pattern's inner bindings,
4205        // so that we avoid resolving a literal expression to a binding defined
4206        // by the pattern.
4207        // NB: `Self::visit_pat` must be used rather than `visit::walk_pat` to avoid resolving guard
4208        // patterns' guard expressions multiple times (#141265).
4209        self.visit_pat(pat);
4210        self.resolve_pattern_inner(pat, pat_src, bindings);
4211        // This has to happen *after* we determine which pat_idents are variants:
4212        self.check_consistent_bindings(pat);
4213    }
4214
4215    /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
4216    ///
4217    /// ### `bindings`
4218    ///
4219    /// A stack of sets of bindings accumulated.
4220    ///
4221    /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
4222    /// be interpreted as re-binding an already bound binding. This results in an error.
4223    /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
4224    /// in reusing this binding rather than creating a fresh one.
4225    ///
4226    /// When called at the top level, the stack must have a single element
4227    /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
4228    /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
4229    /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
4230    /// When each `p_i` has been dealt with, the top set is merged with its parent.
4231    /// When a whole or-pattern has been dealt with, the thing happens.
4232    ///
4233    /// See the implementation and `fresh_binding` for more details.
4234    #[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(4234u32),
                                    ::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")]
4235    fn resolve_pattern_inner(
4236        &mut self,
4237        pat: &'ast Pat,
4238        pat_src: PatternSource,
4239        bindings: &mut PatternBindings,
4240    ) {
4241        // Visit all direct subpatterns of this pattern.
4242        pat.walk(&mut |pat| {
4243            match pat.kind {
4244                PatKind::Ident(bmode, ident, ref sub) => {
4245                    // First try to resolve the identifier as some existing entity,
4246                    // then fall back to a fresh binding.
4247                    let has_sub = sub.is_some();
4248                    let res = self
4249                        .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
4250                        .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
4251                    self.r.record_partial_res(pat.id, PartialRes::new(res));
4252                    self.r.record_pat_span(pat.id, pat.span);
4253                }
4254                PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
4255                    self.smart_resolve_path(
4256                        pat.id,
4257                        qself,
4258                        path,
4259                        PathSource::TupleStruct(
4260                            pat.span,
4261                            self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
4262                        ),
4263                    );
4264                }
4265                PatKind::Path(ref qself, ref path) => {
4266                    self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
4267                }
4268                PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
4269                    self.smart_resolve_path(pat.id, qself, path, PathSource::Struct(None));
4270                    self.record_patterns_with_skipped_bindings(pat, rest);
4271                }
4272                PatKind::Or(ref ps) => {
4273                    // Add a new set of bindings to the stack. `Or` here records that when a
4274                    // binding already exists in this set, it should not result in an error because
4275                    // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
4276                    bindings.push((PatBoundCtx::Or, Default::default()));
4277                    for p in ps {
4278                        // Now we need to switch back to a product context so that each
4279                        // part of the or-pattern internally rejects already bound names.
4280                        // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
4281                        bindings.push((PatBoundCtx::Product, Default::default()));
4282                        self.resolve_pattern_inner(p, pat_src, bindings);
4283                        // Move up the non-overlapping bindings to the or-pattern.
4284                        // Existing bindings just get "merged".
4285                        let collected = bindings.pop().unwrap().1;
4286                        bindings.last_mut().unwrap().1.extend(collected);
4287                    }
4288                    // This or-pattern itself can itself be part of a product,
4289                    // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
4290                    // Both cases bind `a` again in a product pattern and must be rejected.
4291                    let collected = bindings.pop().unwrap().1;
4292                    bindings.last_mut().unwrap().1.extend(collected);
4293
4294                    // Prevent visiting `ps` as we've already done so above.
4295                    return false;
4296                }
4297                PatKind::Guard(ref subpat, ref guard) => {
4298                    // Add a new set of bindings to the stack to collect bindings in `subpat`.
4299                    bindings.push((PatBoundCtx::Product, Default::default()));
4300                    // Resolving `subpat` adds bindings onto the newly-pushed context. After, the
4301                    // total number of contexts on the stack should be the same as before.
4302                    let binding_ctx_stack_len = bindings.len();
4303                    self.resolve_pattern_inner(subpat, pat_src, bindings);
4304                    assert_eq!(bindings.len(), binding_ctx_stack_len);
4305                    // These bindings, but none from the surrounding pattern, are visible in the
4306                    // guard; put them in scope and resolve `guard`.
4307                    let subpat_bindings = bindings.pop().unwrap().1;
4308                    self.with_rib(ValueNS, RibKind::Normal, |this| {
4309                        *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
4310                        this.resolve_expr(&guard.cond, None);
4311                    });
4312                    // Propagate the subpattern's bindings upwards.
4313                    // FIXME(guard_patterns): For `if let` guards, we'll also need to get the
4314                    // bindings introduced by the guard from its rib and propagate them upwards.
4315                    // This will require checking the identifiers for overlaps with `bindings`, like
4316                    // what `fresh_binding` does (ideally sharing its logic). To keep them separate
4317                    // from `subpat_bindings`, we can introduce a fresh rib for the guard.
4318                    bindings.last_mut().unwrap().1.extend(subpat_bindings);
4319                    // Prevent visiting `subpat` as we've already done so above.
4320                    return false;
4321                }
4322                _ => {}
4323            }
4324            true
4325        });
4326    }
4327
4328    fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
4329        match rest {
4330            ast::PatFieldsRest::Rest(_) | ast::PatFieldsRest::Recovered(_) => {
4331                // Record that the pattern doesn't introduce all the bindings it could.
4332                if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
4333                    && let Some(res) = partial_res.full_res()
4334                    && let Some(def_id) = res.opt_def_id()
4335                {
4336                    self.ribs[ValueNS]
4337                        .last_mut()
4338                        .unwrap()
4339                        .patterns_with_skipped_bindings
4340                        .entry(def_id)
4341                        .or_default()
4342                        .push((
4343                            pat.span,
4344                            match rest {
4345                                ast::PatFieldsRest::Recovered(guar) => Err(*guar),
4346                                _ => Ok(()),
4347                            },
4348                        ));
4349                }
4350            }
4351            ast::PatFieldsRest::None => {}
4352        }
4353    }
4354
4355    fn fresh_binding(
4356        &mut self,
4357        ident: Ident,
4358        pat_id: NodeId,
4359        pat_src: PatternSource,
4360        bindings: &mut PatternBindings,
4361    ) -> Res {
4362        // Add the binding to the bindings map, if it doesn't already exist.
4363        // (We must not add it if it's in the bindings map because that breaks the assumptions
4364        // later passes make about or-patterns.)
4365        let ident = ident.normalize_to_macro_rules();
4366
4367        // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
4368        let already_bound_and = bindings
4369            .iter()
4370            .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
4371        if already_bound_and {
4372            // Overlap in a product pattern somewhere; report an error.
4373            use ResolutionError::*;
4374            let error = match pat_src {
4375                // `fn f(a: u8, a: u8)`:
4376                PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
4377                // `Variant(a, a)`:
4378                _ => IdentifierBoundMoreThanOnceInSamePattern,
4379            };
4380            self.report_error(ident.span, error(ident));
4381        }
4382
4383        // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
4384        // This is *required* for consistency which is checked later.
4385        let already_bound_or = bindings
4386            .iter()
4387            .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
4388        let res = if let Some(&res) = already_bound_or {
4389            // `Variant1(a) | Variant2(a)`, ok
4390            // Reuse definition from the first `a`.
4391            res
4392        } else {
4393            // A completely fresh binding is added to the map.
4394            Res::Local(pat_id)
4395        };
4396
4397        // Record as bound.
4398        bindings.last_mut().unwrap().1.insert(ident, res);
4399        res
4400    }
4401
4402    fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4403        &mut self.ribs[ns].last_mut().unwrap().bindings
4404    }
4405
4406    fn try_resolve_as_non_binding(
4407        &mut self,
4408        pat_src: PatternSource,
4409        ann: BindingMode,
4410        ident: Ident,
4411        has_sub: bool,
4412    ) -> Option<Res> {
4413        // An immutable (no `mut`) by-value (no `ref`) binding pattern without
4414        // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
4415        // also be interpreted as a path to e.g. a constant, variant, etc.
4416        let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4417
4418        let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4419        let (res, binding) = match ls_binding {
4420            LateDecl::Decl(binding)
4421                if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4422            {
4423                // For ambiguous bindings we don't know all their definitions and cannot check
4424                // whether they can be shadowed by fresh bindings or not, so force an error.
4425                // issues/33118#issuecomment-233962221 (see below) still applies here,
4426                // but we have to ignore it for backward compatibility.
4427                self.r.record_use(ident, binding, Used::Other);
4428                return None;
4429            }
4430            LateDecl::Decl(binding) => (binding.res(), Some(binding)),
4431            LateDecl::RibDef(res) => (res, None),
4432        };
4433
4434        match res {
4435            Res::SelfCtor(_) // See #70549.
4436            | Res::Def(
4437                DefKind::Ctor(_, CtorKind::Const) | DefKind::Const { .. } | DefKind::AssocConst { .. } | DefKind::ConstParam,
4438                _,
4439            ) if is_syntactic_ambiguity => {
4440                // Disambiguate in favor of a unit struct/variant or constant pattern.
4441                if let Some(binding) = binding {
4442                    self.r.record_use(ident, binding, Used::Other);
4443                }
4444                Some(res)
4445            }
4446            Res::Def(
4447                DefKind::Ctor(..)
4448                | DefKind::Const { .. }
4449                | DefKind::AssocConst { .. }
4450                | DefKind::Static { .. },
4451                _,
4452            ) => {
4453                // This is unambiguously a fresh binding, either syntactically
4454                // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
4455                // to something unusable as a pattern (e.g., constructor function),
4456                // but we still conservatively report an error, see
4457                // issues/33118#issuecomment-233962221 for one reason why.
4458                let binding = binding.expect("no binding for a ctor or static");
4459                self.report_error(
4460                    ident.span,
4461                    ResolutionError::BindingShadowsSomethingUnacceptable {
4462                        shadowing_binding: pat_src,
4463                        name: ident.name,
4464                        participle: if binding.is_import() { "imported" } else { "defined" },
4465                        article: binding.res().article(),
4466                        shadowed_binding: binding.res(),
4467                        shadowed_binding_span: binding.span,
4468                    },
4469                );
4470                None
4471            }
4472            Res::Def(DefKind::ConstParam, def_id) => {
4473                // Same as for DefKind::Const { .. } above, but here, `binding` is `None`, so we
4474                // have to construct the error differently
4475                self.report_error(
4476                    ident.span,
4477                    ResolutionError::BindingShadowsSomethingUnacceptable {
4478                        shadowing_binding: pat_src,
4479                        name: ident.name,
4480                        participle: "defined",
4481                        article: res.article(),
4482                        shadowed_binding: res,
4483                        shadowed_binding_span: self.r.def_span(def_id),
4484                    },
4485                );
4486                None
4487            }
4488            Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4489                // These entities are explicitly allowed to be shadowed by fresh bindings.
4490                None
4491            }
4492            Res::SelfCtor(_) => {
4493                // We resolve `Self` in pattern position as an ident sometimes during recovery,
4494                // so delay a bug instead of ICEing.
4495                self.r.dcx().span_delayed_bug(
4496                    ident.span,
4497                    "unexpected `SelfCtor` in pattern, expected identifier",
4498                );
4499                None
4500            }
4501            _ => ::rustc_middle::util::bug::span_bug_fmt(ident.span,
    format_args!("unexpected resolution for an identifier in pattern: {0:?}",
        res))span_bug!(
4502                ident.span,
4503                "unexpected resolution for an identifier in pattern: {:?}",
4504                res,
4505            ),
4506        }
4507    }
4508
4509    fn resolve_restriction_path(
4510        &mut self,
4511        restriction: &'ast ast::RestrictionKind,
4512        kind: ResolvingRestrictionKind,
4513    ) {
4514        match &restriction {
4515            ast::RestrictionKind::Unrestricted => (),
4516            ast::RestrictionKind::Restricted { path, id, shorthand: _ } => {
4517                self.smart_resolve_path(*id, &None, path, PathSource::Module);
4518                if let Some(res) = self.r.partial_res_map[&id].full_res()
4519                    && let Some(def_id) = res.opt_def_id()
4520                {
4521                    if !self.r.is_accessible_from(
4522                        Visibility::Restricted(def_id),
4523                        self.parent_scope.module,
4524                    ) {
4525                        self.r
4526                            .dcx()
4527                            .create_err(crate::diagnostics::RestrictionAncestorOnly {
4528                                span: path.span,
4529                                kind,
4530                            })
4531                            .emit();
4532                    }
4533                }
4534            }
4535        }
4536    }
4537
4538    // High-level and context dependent path resolution routine.
4539    // Resolves the path and records the resolution into definition map.
4540    // If resolution fails tries several techniques to find likely
4541    // resolution candidates, suggest imports or other help, and report
4542    // errors in user friendly way.
4543    fn smart_resolve_path(
4544        &mut self,
4545        id: NodeId,
4546        qself: &Option<Box<QSelf>>,
4547        path: &Path,
4548        source: PathSource<'_, 'ast, 'ra>,
4549    ) {
4550        self.smart_resolve_path_fragment(
4551            qself,
4552            &Segment::from_path(path),
4553            source,
4554            Finalize::new(id, path.span),
4555            RecordPartialRes::Yes,
4556            None,
4557        );
4558    }
4559
4560    fn smart_resolve_path_fragment(
4561        &mut self,
4562        qself: &Option<Box<QSelf>>,
4563        path: &[Segment],
4564        source: PathSource<'_, 'ast, 'ra>,
4565        finalize: Finalize,
4566        record_partial_res: RecordPartialRes,
4567        parent_qself: Option<&QSelf>,
4568    ) -> PartialRes {
4569        let ns = source.namespace();
4570
4571        let Finalize { node_id, path_span, .. } = finalize;
4572        let report_errors = |this: &mut Self, res: Option<Res>| {
4573            if this.should_report_errs() {
4574                let (mut err, candidates) = this.smart_resolve_report_errors(
4575                    path,
4576                    None,
4577                    path_span,
4578                    source,
4579                    res,
4580                    parent_qself,
4581                );
4582
4583                let node_id = this.parent_scope.module.nearest_parent_mod_node_id();
4584                let instead = res.is_some();
4585                let (suggestion, const_err) = if let Some((start, end)) =
4586                    this.diag_metadata.in_range
4587                    && path[0].ident.span.lo() == end.span.lo()
4588                    && !#[allow(non_exhaustive_omitted_patterns)] match start.kind {
    ExprKind::Lit(_) => true,
    _ => false,
}matches!(start.kind, ExprKind::Lit(_))
4589                {
4590                    let mut sugg = ".";
4591                    let mut span = start.span.between(end.span);
4592                    if span.lo() + BytePos(2) == span.hi() {
4593                        // There's no space between the start, the range op and the end, suggest
4594                        // removal which will look better.
4595                        span = span.with_lo(span.lo() + BytePos(1));
4596                        sugg = "";
4597                    }
4598                    (
4599                        Some((
4600                            span,
4601                            "you might have meant to write `.` instead of `..`",
4602                            sugg.to_string(),
4603                            Applicability::MaybeIncorrect,
4604                        )),
4605                        None,
4606                    )
4607                } else if res.is_none()
4608                    && let PathSource::Type
4609                    | PathSource::Expr(_)
4610                    | PathSource::PreciseCapturingArg(..) = source
4611                {
4612                    this.suggest_adding_generic_parameter(path, source)
4613                } else {
4614                    (None, None)
4615                };
4616
4617                if let Some(const_err) = const_err {
4618                    err.cancel();
4619                    err = const_err;
4620                }
4621
4622                let ue = UseError {
4623                    err,
4624                    candidates,
4625                    node_id,
4626                    instead,
4627                    suggestion,
4628                    path: path.into(),
4629                    is_call: source.is_call(),
4630                };
4631
4632                this.use_injections.push(ue);
4633            }
4634
4635            PartialRes::new(Res::Err)
4636        };
4637
4638        // For paths originating from calls (like in `HashMap::new()`), tries
4639        // to enrich the plain `failed to resolve: ...` message with hints
4640        // about possible missing imports.
4641        //
4642        // Similar thing, for types, happens in `report_errors` above.
4643        let report_errors_for_call =
4644            |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4645                // Before we start looking for candidates, we have to get our hands
4646                // on the type user is trying to perform invocation on; basically:
4647                // we're transforming `HashMap::new` into just `HashMap`.
4648                let (following_seg, prefix_path) = match path.split_last() {
4649                    Some((last, path)) if !path.is_empty() => (Some(last), path),
4650                    _ => return Some(parent_err),
4651                };
4652
4653                let (mut err, candidates) = this.smart_resolve_report_errors(
4654                    prefix_path,
4655                    following_seg,
4656                    path_span,
4657                    PathSource::Type,
4658                    None,
4659                    parent_qself,
4660                );
4661
4662                // There are two different error messages user might receive at
4663                // this point:
4664                // - E0425 cannot find type `{}` in this scope
4665                // - E0433 failed to resolve: use of undeclared type or module `{}`
4666                //
4667                // The first one is emitted for paths in type-position, and the
4668                // latter one - for paths in expression-position.
4669                //
4670                // Thus (since we're in expression-position at this point), not to
4671                // confuse the user, we want to keep the *message* from E0433 (so
4672                // `parent_err`), but we want *hints* from E0425 (so `err`).
4673                //
4674                // And that's what happens below - we're just mixing both messages
4675                // into a single one.
4676                let failed_to_resolve = match parent_err.node {
4677                    ResolutionError::FailedToResolve { .. } => true,
4678                    _ => false,
4679                };
4680                let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4681
4682                // overwrite all properties with the parent's error message
4683                err.messages = take(&mut parent_err.messages);
4684                err.code = take(&mut parent_err.code);
4685                swap(&mut err.span, &mut parent_err.span);
4686                if failed_to_resolve {
4687                    err.children = take(&mut parent_err.children);
4688                } else {
4689                    err.children.append(&mut parent_err.children);
4690                }
4691                err.sort_span = parent_err.sort_span;
4692                err.is_lint = parent_err.is_lint.clone();
4693
4694                // merge the parent_err's suggestions with the typo (err's) suggestions
4695                match &mut err.suggestions {
4696                    Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4697                        Suggestions::Enabled(parent_suggestions) => {
4698                            // If both suggestions are enabled, append parent_err's suggestions to err's suggestions.
4699                            typo_suggestions.append(parent_suggestions)
4700                        }
4701                        Suggestions::Sealed(_) | Suggestions::Disabled => {
4702                            // If the parent's suggestions are either sealed or disabled, it signifies that
4703                            // new suggestions cannot be added or removed from the diagnostic. Therefore,
4704                            // we assign both types of suggestions to err's suggestions and discard the
4705                            // existing suggestions in err.
4706                            err.suggestions = std::mem::take(&mut parent_err.suggestions);
4707                        }
4708                    },
4709                    Suggestions::Sealed(_) | Suggestions::Disabled => (),
4710                }
4711
4712                parent_err.cancel();
4713
4714                let node_id = this.parent_scope.module.nearest_parent_mod_node_id();
4715
4716                if this.should_report_errs() {
4717                    if candidates.is_empty() {
4718                        if path.len() == 2
4719                            && let [segment] = prefix_path
4720                        {
4721                            // Delay to check whether method name is an associated function or not
4722                            // ```
4723                            // let foo = Foo {};
4724                            // foo::bar(); // possibly suggest to foo.bar();
4725                            //```
4726                            err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4727                        } else {
4728                            // When there is no suggested imports, we can just emit the error
4729                            // and suggestions immediately. Note that we bypass the usually error
4730                            // reporting routine (ie via `self.r.report_error`) because we need
4731                            // to post-process the `ResolutionError` above.
4732                            err.emit();
4733                        }
4734                    } else {
4735                        // If there are suggested imports, the error reporting is delayed
4736                        this.use_injections.push(UseError {
4737                            err,
4738                            candidates,
4739                            node_id,
4740                            instead: false,
4741                            suggestion: None,
4742                            path: prefix_path.into(),
4743                            is_call: source.is_call(),
4744                        });
4745                    }
4746                } else {
4747                    err.cancel();
4748                }
4749
4750                // We don't return `Some(parent_err)` here, because the error will
4751                // be already printed either immediately or as part of the `use` injections
4752                None
4753            };
4754
4755        let partial_res = match self.resolve_qpath_anywhere(
4756            qself,
4757            path,
4758            ns,
4759            source.defer_to_typeck(),
4760            finalize,
4761            source,
4762        ) {
4763            Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4764                // if we also have an associated type that matches the ident, stash a suggestion
4765                if let Some(items) = self.diag_metadata.current_trait_assoc_items
4766                    && let [Segment { ident, .. }] = path
4767                    && items.iter().any(|item| {
4768                        if let AssocItemKind::Type(alias) = &item.kind
4769                            && alias.ident == *ident
4770                        {
4771                            true
4772                        } else {
4773                            false
4774                        }
4775                    })
4776                {
4777                    let mut diag = self.r.tcx.dcx().struct_allow("");
4778                    diag.span_suggestion_verbose(
4779                        path_span.shrink_to_lo(),
4780                        "there is an associated type with the same name",
4781                        "Self::",
4782                        Applicability::MaybeIncorrect,
4783                    );
4784                    diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4785                }
4786
4787                if source.is_expected(res) || res == Res::Err {
4788                    partial_res
4789                } else {
4790                    report_errors(self, Some(res))
4791                }
4792            }
4793
4794            Ok(Some(partial_res)) if source.defer_to_typeck() => {
4795                // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
4796                // or `<T>::A::B`. If `B` should be resolved in value namespace then
4797                // it needs to be added to the trait map.
4798                if ns == ValueNS {
4799                    let item_name = path.last().unwrap().ident;
4800                    self.record_traits_in_scope(node_id, item_name);
4801                }
4802
4803                if PrimTy::from_name(path[0].ident.name).is_some() {
4804                    let mut std_path = Vec::with_capacity(1 + path.len());
4805
4806                    std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4807                    std_path.extend(path);
4808                    if let PathResult::Module(_) | PathResult::NonModule(_) =
4809                        self.resolve_path(&std_path, Some(ns), None, source)
4810                    {
4811                        // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
4812                        let item_span =
4813                            path.iter().last().map_or(path_span, |segment| segment.ident.span);
4814
4815                        self.r.confused_type_with_std_module.insert(item_span, path_span);
4816                        self.r.confused_type_with_std_module.insert(path_span, path_span);
4817                    }
4818                }
4819
4820                partial_res
4821            }
4822
4823            Err(err) => {
4824                if let Some(err) = report_errors_for_call(self, err) {
4825                    self.report_error(err.span, err.node);
4826                }
4827
4828                PartialRes::new(Res::Err)
4829            }
4830
4831            _ => report_errors(self, None),
4832        };
4833
4834        if record_partial_res == RecordPartialRes::Yes {
4835            // Avoid recording definition of `A::B` in `<T as A>::B::C`.
4836            self.r.record_partial_res(node_id, partial_res);
4837            self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4838            self.lint_unused_qualifications(path, ns, finalize);
4839        }
4840
4841        partial_res
4842    }
4843
4844    fn self_type_is_available(&mut self) -> bool {
4845        let binding = self
4846            .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4847        if let Some(LateDecl::RibDef(res)) = binding { res != Res::Err } else { false }
4848    }
4849
4850    fn self_value_is_available(&mut self, self_span: Span) -> bool {
4851        let ident = Ident::new(kw::SelfLower, self_span);
4852        let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4853        if let Some(LateDecl::RibDef(res)) = binding { res != Res::Err } else { false }
4854    }
4855
4856    /// A wrapper around [`Resolver::report_error`].
4857    ///
4858    /// This doesn't emit errors for function bodies if this is rustdoc.
4859    fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4860        if self.should_report_errs() {
4861            self.r.report_error(span, resolution_error);
4862        }
4863    }
4864
4865    #[inline]
4866    /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items or
4867    // an invalid `use foo::*;` was found, which can cause unbounded amounts of "item not found"
4868    // errors. We silence them all.
4869    fn should_report_errs(&self) -> bool {
4870        !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4871            && !self.r.glob_error.is_some()
4872    }
4873
4874    // Resolve in alternative namespaces if resolution in the primary namespace fails.
4875    fn resolve_qpath_anywhere(
4876        &mut self,
4877        qself: &Option<Box<QSelf>>,
4878        path: &[Segment],
4879        primary_ns: Namespace,
4880        defer_to_typeck: bool,
4881        finalize: Finalize,
4882        source: PathSource<'_, 'ast, 'ra>,
4883    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4884        let mut fin_res = None;
4885
4886        for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4887            if i == 0 || ns != primary_ns {
4888                match self.resolve_qpath(qself, path, ns, finalize, source)? {
4889                    Some(partial_res)
4890                        if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4891                    {
4892                        return Ok(Some(partial_res));
4893                    }
4894                    partial_res => {
4895                        if fin_res.is_none() {
4896                            fin_res = partial_res;
4897                        }
4898                    }
4899                }
4900            }
4901        }
4902
4903        if !(primary_ns != MacroNS) {
    ::core::panicking::panic("assertion failed: primary_ns != MacroNS")
};assert!(primary_ns != MacroNS);
4904        if qself.is_none()
4905            && let PathResult::NonModule(res) =
4906                self.r.cm().maybe_resolve_path(path, Some(MacroNS), &self.parent_scope, None)
4907        {
4908            return Ok(Some(res));
4909        }
4910
4911        Ok(fin_res)
4912    }
4913
4914    /// Handles paths that may refer to associated items.
4915    fn resolve_qpath(
4916        &mut self,
4917        qself: &Option<Box<QSelf>>,
4918        path: &[Segment],
4919        ns: Namespace,
4920        finalize: Finalize,
4921        source: PathSource<'_, 'ast, 'ra>,
4922    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4923        {
    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:4923",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(4923u32),
                        ::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!(
4924            "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4925            qself, path, ns, finalize,
4926        );
4927
4928        if let Some(qself) = qself {
4929            if qself.position == 0 {
4930                // This is a case like `<T>::B`, where there is no
4931                // trait to resolve. In that case, we leave the `B`
4932                // segment to be resolved by type-check.
4933                return Ok(Some(PartialRes::with_unresolved_segments(
4934                    Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4935                    path.len(),
4936                )));
4937            }
4938
4939            let num_privacy_errors = self.r.privacy_errors.len();
4940            // Make sure that `A` in `<T as A>::B::C` is a trait.
4941            let trait_res = self.smart_resolve_path_fragment(
4942                &None,
4943                &path[..qself.position],
4944                PathSource::Trait(AliasPossibility::No),
4945                Finalize::new(finalize.node_id, qself.path_span),
4946                RecordPartialRes::No,
4947                Some(&qself),
4948            );
4949
4950            if trait_res.expect_full_res() == Res::Err {
4951                return Ok(Some(trait_res));
4952            }
4953
4954            // Truncate additional privacy errors reported above,
4955            // because they'll be recomputed below.
4956            self.r.privacy_errors.truncate(num_privacy_errors);
4957
4958            // Make sure `A::B` in `<T as A>::B::C` is a trait item.
4959            //
4960            // Currently, `path` names the full item (`A::B::C`, in
4961            // our example). so we extract the prefix of that that is
4962            // the trait (the slice upto and including
4963            // `qself.position`). And then we recursively resolve that,
4964            // but with `qself` set to `None`.
4965            let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4966            let partial_res = self.smart_resolve_path_fragment(
4967                &None,
4968                &path[..=qself.position],
4969                PathSource::TraitItem(ns, &source),
4970                Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4971                RecordPartialRes::No,
4972                Some(&qself),
4973            );
4974
4975            // The remaining segments (the `C` in our example) will
4976            // have to be resolved by type-check, since that requires doing
4977            // trait resolution.
4978            return Ok(Some(PartialRes::with_unresolved_segments(
4979                partial_res.base_res(),
4980                partial_res.unresolved_segments() + path.len() - qself.position - 1,
4981            )));
4982        }
4983
4984        let result = match self.resolve_path(path, Some(ns), Some(finalize), source) {
4985            PathResult::NonModule(path_res) => path_res,
4986            PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4987                PartialRes::new(module.res().unwrap())
4988            }
4989            // A part of this path references a `mod` that had a parse error. To avoid resolution
4990            // errors for each reference to that module, we don't emit an error for them until the
4991            // `mod` is fixed. this can have a significant cascade effect.
4992            PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4993                PartialRes::new(Res::Err)
4994            }
4995            // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
4996            // don't report an error right away, but try to fallback to a primitive type.
4997            // So, we are still able to successfully resolve something like
4998            //
4999            // use std::u8; // bring module u8 in scope
5000            // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
5001            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
5002            //                     // not to nonexistent std::u8::max_value
5003            // }
5004            //
5005            // Such behavior is required for backward compatibility.
5006            // The same fallback is used when `a` resolves to nothing.
5007            PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
5008                if (ns == TypeNS || path.len() > 1)
5009                    && PrimTy::from_name(path[0].ident.name).is_some() =>
5010            {
5011                let prim = PrimTy::from_name(path[0].ident.name).unwrap();
5012                let tcx = self.r.tcx();
5013
5014                let gate_err_sym_msg = match prim {
5015                    PrimTy::Float(FloatTy::F16) if !self.r.features.f16() => {
5016                        Some((sym::f16, "the type `f16` is unstable"))
5017                    }
5018                    PrimTy::Float(FloatTy::F128) if !self.r.features.f128() => {
5019                        Some((sym::f128, "the type `f128` is unstable"))
5020                    }
5021                    _ => None,
5022                };
5023
5024                if let Some((sym, msg)) = gate_err_sym_msg {
5025                    let span = path[0].ident.span;
5026                    if !span.allows_unstable(sym) {
5027                        feature_err(tcx.sess, sym, span, msg).emit();
5028                    }
5029                };
5030
5031                // Fix up partial res of segment from `resolve_path` call.
5032                if let Some(id) = path[0].id {
5033                    self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
5034                }
5035
5036                PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
5037            }
5038            PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
5039                PartialRes::new(module.res().unwrap())
5040            }
5041            PathResult::Failed {
5042                is_error_from_last_segment: false,
5043                span,
5044                label,
5045                suggestion,
5046                module,
5047                segment,
5048                error_implied_by_parse_error: _,
5049                message,
5050                note: _,
5051            } => {
5052                return Err(respan(
5053                    span,
5054                    ResolutionError::FailedToResolve {
5055                        segment: segment.name,
5056                        label,
5057                        suggestion,
5058                        module,
5059                        message,
5060                    },
5061                ));
5062            }
5063            PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
5064            PathResult::Indeterminate => ::rustc_middle::util::bug::bug_fmt(format_args!("indeterminate path result in resolve_qpath"))bug!("indeterminate path result in resolve_qpath"),
5065        };
5066
5067        Ok(Some(result))
5068    }
5069
5070    fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
5071        if let Some(label) = label {
5072            if label.ident.as_str().as_bytes()[1] != b'_' {
5073                self.diag_metadata.unused_labels.insert(id, label.ident.span);
5074            }
5075
5076            if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
5077                diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
5078            }
5079
5080            self.with_label_rib(RibKind::Normal, |this| {
5081                let ident = label.ident.normalize_to_macro_rules();
5082                this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
5083                f(this);
5084            });
5085        } else {
5086            f(self);
5087        }
5088    }
5089
5090    fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
5091        self.with_resolved_label(label, id, |this| this.visit_block(block));
5092    }
5093
5094    fn resolve_block(&mut self, block: &'ast Block) {
5095        {
    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:5095",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5095u32),
                        ::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");
5096        // Move down in the graph, if there's an anonymous module rooted here.
5097        let orig_module = self.parent_scope.module;
5098        let anonymous_module = self.r.block_map.get(&block.id).copied();
5099
5100        let mut num_macro_definition_ribs = 0;
5101        if let Some(anonymous_module) = anonymous_module {
5102            {
    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:5102",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5102u32),
                        ::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");
5103            self.ribs[ValueNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
5104            self.ribs[TypeNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
5105            self.parent_scope.module = anonymous_module.to_module();
5106        } else {
5107            self.ribs[ValueNS].push(Rib::new(RibKind::Block(None)));
5108        }
5109
5110        // Descend into the block.
5111        for stmt in &block.stmts {
5112            if let StmtKind::Item(ref item) = stmt.kind
5113                && let ItemKind::MacroDef(..) = item.kind
5114            {
5115                num_macro_definition_ribs += 1;
5116                let res = self.r.owner_def_id(item.id).to_def_id();
5117                self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
5118                self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
5119            }
5120
5121            self.visit_stmt(stmt);
5122        }
5123
5124        // Move back up.
5125        self.parent_scope.module = orig_module;
5126        for _ in 0..num_macro_definition_ribs {
5127            self.ribs[ValueNS].pop();
5128            self.label_ribs.pop();
5129        }
5130        self.last_block_rib = self.ribs[ValueNS].pop();
5131        if anonymous_module.is_some() {
5132            self.ribs[TypeNS].pop();
5133        }
5134        {
    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:5134",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5134u32),
                        ::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");
5135    }
5136
5137    fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
5138        {
    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:5138",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5138u32),
                        ::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!(
5139            "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
5140            constant, anon_const_kind
5141        );
5142
5143        let is_trivial_const_arg = constant.value.is_potential_trivial_const_arg();
5144        self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
5145            this.resolve_expr(&constant.value, None)
5146        })
5147    }
5148
5149    /// There are a few places that we need to resolve an anon const but we did not parse an
5150    /// anon const so cannot provide an `&'ast AnonConst`. Right now this is just unbraced
5151    /// const arguments that were parsed as type arguments, and `legacy_const_generics` which
5152    /// parse as normal function argument expressions. To avoid duplicating the code for resolving
5153    /// an anon const we have this function which lets the caller manually call `resolve_expr` or
5154    /// `smart_resolve_path`.
5155    fn resolve_anon_const_manual(
5156        &mut self,
5157        is_trivial_const_arg: bool,
5158        anon_const_kind: AnonConstKind,
5159        resolve_expr: impl FnOnce(&mut Self),
5160    ) {
5161        let is_repeat_expr = match anon_const_kind {
5162            AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
5163            _ => IsRepeatExpr::No,
5164        };
5165
5166        let may_use_generics = match anon_const_kind {
5167            AnonConstKind::EnumDiscriminant => {
5168                ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
5169            }
5170            AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
5171            AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
5172            AnonConstKind::ConstArg(_) => {
5173                if self.r.features.generic_const_exprs()
5174                    || self.r.features.min_generic_const_args()
5175                    || is_trivial_const_arg
5176                {
5177                    ConstantHasGenerics::Yes
5178                } else {
5179                    ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
5180                }
5181            }
5182        };
5183
5184        self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
5185            this.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
5186                resolve_expr(this);
5187            });
5188        });
5189    }
5190
5191    fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
5192        self.resolve_expr(&f.expr, Some(e));
5193        self.visit_ident(&f.ident);
5194        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());
5195    }
5196
5197    fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
5198        // First, record candidate traits for this expression if it could
5199        // result in the invocation of a method call.
5200
5201        self.record_candidate_traits_for_expr_if_necessary(expr);
5202
5203        // Next, resolve the node.
5204        match expr.kind {
5205            ExprKind::Path(ref qself, ref path) => {
5206                self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
5207                visit::walk_expr(self, expr);
5208            }
5209
5210            ExprKind::Struct(ref se) => {
5211                self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct(parent));
5212                // This is the same as `visit::walk_expr(self, expr);`, but we want to pass the
5213                // parent in for accurate suggestions when encountering `Foo { bar }` that should
5214                // have been `Foo { bar: self.bar }`.
5215                if let Some(qself) = &se.qself {
5216                    self.visit_ty(&qself.ty);
5217                }
5218                self.visit_path(&se.path);
5219                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);
5220                match &se.rest {
5221                    StructRest::Base(expr) => self.visit_expr(expr),
5222                    StructRest::Rest(_span) => {}
5223                    StructRest::None | StructRest::NoneWithError(_) => {}
5224                }
5225            }
5226
5227            ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
5228                match self.resolve_label(label.ident) {
5229                    Ok((node_id, _)) => {
5230                        // Since this res is a label, it is never read.
5231                        self.r.current_owner.label_res_map.insert(expr.id, node_id);
5232                        self.diag_metadata.unused_labels.swap_remove(&node_id);
5233                    }
5234                    Err(error) => {
5235                        self.report_error(label.ident.span, error);
5236                    }
5237                }
5238
5239                // visit `break` argument if any
5240                visit::walk_expr(self, expr);
5241            }
5242
5243            ExprKind::Break(None, Some(ref e)) => {
5244                // We use this instead of `visit::walk_expr` to keep the parent expr around for
5245                // better diagnostics.
5246                self.resolve_expr(e, Some(expr));
5247            }
5248
5249            ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
5250                self.visit_expr(scrutinee);
5251                self.resolve_pattern_top(pat, PatternSource::Let);
5252            }
5253
5254            ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
5255                self.visit_expr(scrutinee);
5256                // This is basically a tweaked, inlined `resolve_pattern_top`.
5257                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())];
5258                self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
5259                // We still collect the bindings in this `let` expression which is in
5260                // an invalid position (and therefore shouldn't declare variables into
5261                // its parent scope). To avoid unnecessary errors though, we do just
5262                // reassign the resolutions to `Res::Err`.
5263                for (_, bindings) in &mut bindings {
5264                    for (_, binding) in bindings {
5265                        *binding = Res::Err;
5266                    }
5267                }
5268                self.apply_pattern_bindings(bindings);
5269            }
5270
5271            ExprKind::If(ref cond, ref then, ref opt_else) => {
5272                self.with_rib(ValueNS, RibKind::Normal, |this| {
5273                    let old = this.diag_metadata.in_if_condition.replace(cond);
5274                    this.visit_expr(cond);
5275                    this.diag_metadata.in_if_condition = old;
5276                    this.visit_block(then);
5277                });
5278                if let Some(expr) = opt_else {
5279                    self.visit_expr(expr);
5280                }
5281            }
5282
5283            ExprKind::Loop(ref block, label, _) => {
5284                self.resolve_labeled_block(label, expr.id, block)
5285            }
5286
5287            ExprKind::While(ref cond, ref block, label) => {
5288                self.with_resolved_label(label, expr.id, |this| {
5289                    this.with_rib(ValueNS, RibKind::Normal, |this| {
5290                        let old = this.diag_metadata.in_if_condition.replace(cond);
5291                        this.visit_expr(cond);
5292                        this.diag_metadata.in_if_condition = old;
5293                        this.visit_block(block);
5294                    })
5295                });
5296            }
5297
5298            ExprKind::ForLoop(ForLoop { ref pat, ref iter, ref body, label, kind: _ }) => {
5299                self.visit_expr(iter);
5300                self.with_rib(ValueNS, RibKind::Normal, |this| {
5301                    this.resolve_pattern_top(pat, PatternSource::For);
5302                    this.resolve_labeled_block(label, expr.id, body);
5303                });
5304            }
5305
5306            ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
5307
5308            // Equivalent to `visit::walk_expr` + passing some context to children.
5309            ExprKind::Field(ref subexpression, _) => {
5310                self.resolve_expr(subexpression, Some(expr));
5311            }
5312            ExprKind::MethodCall(MethodCall { ref seg, ref receiver, ref args, .. }) => {
5313                self.resolve_expr(receiver, Some(expr));
5314                for arg in args {
5315                    self.resolve_expr(arg, None);
5316                }
5317                self.visit_path_segment(seg);
5318            }
5319
5320            ExprKind::Call(ref callee, ref arguments) => {
5321                self.resolve_expr(callee, Some(expr));
5322                let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
5323                for (idx, argument) in arguments.iter().enumerate() {
5324                    // Constant arguments need to be treated as AnonConst since
5325                    // that is how they will be later lowered to HIR.
5326                    if const_args.contains(&idx) {
5327                        // FIXME(mgca): legacy const generics doesn't support mgca but maybe
5328                        // that's okay.
5329                        let is_trivial_const_arg = argument.is_potential_trivial_const_arg();
5330                        self.resolve_anon_const_manual(
5331                            is_trivial_const_arg,
5332                            AnonConstKind::ConstArg(IsRepeatExpr::No),
5333                            |this| this.resolve_expr(argument, None),
5334                        );
5335                    } else {
5336                        self.resolve_expr(argument, None);
5337                    }
5338                }
5339            }
5340            ExprKind::Type(ref _type_expr, ref _ty) => {
5341                visit::walk_expr(self, expr);
5342            }
5343            // For closures, RibKind::FnOrCoroutine is added in visit_fn
5344            ExprKind::Closure(ast::Closure {
5345                binder: ClosureBinder::For { ref generic_params, span },
5346                ..
5347            }) => {
5348                self.with_generic_param_rib(
5349                    generic_params,
5350                    RibKind::Normal,
5351                    expr.id,
5352                    LifetimeBinderKind::Closure,
5353                    span,
5354                    |this| visit::walk_expr(this, expr),
5355                );
5356            }
5357            ExprKind::Closure(..) => visit::walk_expr(self, expr),
5358            ExprKind::Gen(..) => {
5359                self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
5360            }
5361            ExprKind::Repeat(ref elem, ref ct) => {
5362                self.visit_expr(elem);
5363                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
5364            }
5365            ExprKind::ConstBlock(ref ct) => {
5366                self.resolve_anon_const(ct, AnonConstKind::InlineConst);
5367            }
5368            ExprKind::Index(ref elem, ref idx, _) => {
5369                self.resolve_expr(elem, Some(expr));
5370                self.visit_expr(idx);
5371            }
5372            ExprKind::Assign(ref lhs, ref rhs, _) => {
5373                if !self.diag_metadata.is_assign_rhs {
5374                    self.diag_metadata.in_assignment = Some(expr);
5375                }
5376                self.visit_expr(lhs);
5377                self.diag_metadata.is_assign_rhs = true;
5378                self.diag_metadata.in_assignment = None;
5379                self.visit_expr(rhs);
5380                self.diag_metadata.is_assign_rhs = false;
5381            }
5382            ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
5383                self.diag_metadata.in_range = Some((start, end));
5384                self.resolve_expr(start, Some(expr));
5385                self.resolve_expr(end, Some(expr));
5386                self.diag_metadata.in_range = None;
5387            }
5388            _ => {
5389                visit::walk_expr(self, expr);
5390            }
5391        }
5392    }
5393
5394    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
5395        match expr.kind {
5396            ExprKind::Field(_, ident) => {
5397                // #6890: Even though you can't treat a method like a field,
5398                // we need to add any trait methods we find that match the
5399                // field name so that we can do some nice error reporting
5400                // later on in typeck.
5401                self.record_traits_in_scope(expr.id, ident);
5402            }
5403            ExprKind::MethodCall(ref call) => {
5404                {
    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:5404",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5404u32),
                        ::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);
5405                self.record_traits_in_scope(expr.id, call.seg.ident);
5406            }
5407            _ => {
5408                // Nothing to do.
5409            }
5410        }
5411    }
5412
5413    fn record_traits_in_scope(&mut self, node_id: NodeId, ident: Ident) {
5414        let traits = self.r.traits_in_scope(
5415            self.current_trait_ref.as_ref().map(|(module, _)| *module),
5416            &self.parent_scope,
5417            ident.span,
5418            Some((ident.name, ValueNS)),
5419        );
5420        self.r.current_owner.trait_map.insert(node_id, traits);
5421    }
5422
5423    fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
5424        // FIXME: This caching may be incorrect in case of multiple `macro_rules`
5425        // items with the same name in the same module.
5426        // Also hygiene is not considered.
5427        let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
5428        let res = *doc_link_resolutions
5429            .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5430            .or_default()
5431            .entry((Symbol::intern(path_str), ns))
5432            .or_insert_with_key(|(path, ns)| {
5433                let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
5434                if let Some(res) = res
5435                    && let Some(def_id) = res.opt_def_id()
5436                    && self.is_invalid_proc_macro_item_for_doc(def_id)
5437                {
5438                    // Encoding def ids in proc macro crate metadata will ICE,
5439                    // because it will only store proc macros for it.
5440                    return None;
5441                }
5442                res
5443            });
5444        self.r.doc_link_resolutions = doc_link_resolutions;
5445        res
5446    }
5447
5448    fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5449        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)
5450            || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5451        {
5452            return false;
5453        }
5454        let Some(local_did) = did.as_local() else { return true };
5455        !self.r.proc_macros.contains(&local_did)
5456    }
5457
5458    fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5459        match self.r.tcx.sess.opts.resolve_doc_links {
5460            ResolveDocLinks::None => return,
5461            ResolveDocLinks::ExportedMetadata
5462                if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5463                    || !maybe_exported.eval(self.r) =>
5464            {
5465                return;
5466            }
5467            ResolveDocLinks::Exported
5468                if !maybe_exported.eval(self.r)
5469                    && !rustdoc::has_primitive_or_keyword_or_attribute_docs(attrs) =>
5470            {
5471                return;
5472            }
5473            ResolveDocLinks::ExportedMetadata
5474            | ResolveDocLinks::Exported
5475            | ResolveDocLinks::All => {}
5476        }
5477
5478        if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5479            return;
5480        }
5481
5482        let mut need_traits_in_scope = false;
5483        for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5484            // Resolve all namespaces due to no disambiguator or for diagnostics.
5485            let mut any_resolved = false;
5486            let mut need_assoc = false;
5487            for ns in [TypeNS, ValueNS, MacroNS] {
5488                if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5489                    // Rustdoc ignores tool attribute resolutions and attempts
5490                    // to resolve their prefixes for diagnostics.
5491                    any_resolved = !#[allow(non_exhaustive_omitted_patterns)] match res {
    Res::NonMacroAttr(NonMacroAttrKind::Tool) => true,
    _ => false,
}matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5492                } else if ns != MacroNS {
5493                    need_assoc = true;
5494                }
5495            }
5496
5497            // Resolve all prefixes for type-relative resolution or for diagnostics.
5498            if need_assoc || !any_resolved {
5499                let mut path = &path_str[..];
5500                while let Some(idx) = path.rfind("::") {
5501                    path = &path[..idx];
5502                    need_traits_in_scope = true;
5503                    for ns in [TypeNS, ValueNS, MacroNS] {
5504                        self.resolve_and_cache_rustdoc_path(path, ns);
5505                    }
5506                }
5507            }
5508        }
5509
5510        if need_traits_in_scope {
5511            // FIXME: hygiene is not considered.
5512            let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5513            doc_link_traits_in_scope
5514                .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5515                .or_insert_with(|| {
5516                    self.r
5517                        .traits_in_scope(None, &self.parent_scope, DUMMY_SP, None)
5518                        .into_iter()
5519                        .filter_map(|tr| {
5520                            if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5521                                // Encoding def ids in proc macro crate metadata will ICE.
5522                                // because it will only store proc macros for it.
5523                                return None;
5524                            }
5525                            Some(tr.def_id)
5526                        })
5527                        .collect()
5528                });
5529            self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5530        }
5531    }
5532
5533    fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5534        // Don't lint on global paths because the user explicitly wrote out the full path.
5535        if let Some(seg) = path.first()
5536            && seg.ident.name == kw::PathRoot
5537        {
5538            return;
5539        }
5540
5541        if finalize.path_span.from_expansion()
5542            || path.iter().any(|seg| seg.ident.span.from_expansion())
5543        {
5544            return;
5545        }
5546
5547        let end_pos =
5548            path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5549        let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5550            // Preserve the current namespace for the final path segment, but use the type
5551            // namespace for all preceding segments
5552            //
5553            // e.g. for `std::env::args` check the `ValueNS` for `args` but the `TypeNS` for
5554            // `std` and `env`
5555            //
5556            // If the final path segment is beyond `end_pos` all the segments to check will
5557            // use the type namespace
5558            let ns = if i + 1 == path.len() { ns } else { TypeNS };
5559            let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5560            let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5561            (res == binding.res()).then_some((seg, binding))
5562        });
5563
5564        if let Some((seg, decl)) = unqualified {
5565            self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5566                decl,
5567                node_id: finalize.node_id,
5568                path_span: finalize.path_span,
5569                removal_span: path[0].ident.span.until(seg.ident.span),
5570            });
5571        }
5572    }
5573
5574    fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5575        if let Some(define_opaque) = define_opaque {
5576            for (id, path) in define_opaque {
5577                self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5578            }
5579        }
5580    }
5581
5582    fn resolve_eii(&mut self, eii_impls: &[EiiImpl]) {
5583        for EiiImpl { node_id, eii_macro_path, known_eii_macro_resolution, .. } in eii_impls {
5584            // See docs on the `known_eii_macro_resolution` field:
5585            // if we already know the resolution statically, don't bother resolving it.
5586            if let Some(target) = known_eii_macro_resolution {
5587                self.smart_resolve_path(*node_id, &None, target, PathSource::ExternItemImpl);
5588            } else {
5589                self.smart_resolve_path(*node_id, &None, &eii_macro_path, PathSource::Macro);
5590            }
5591        }
5592    }
5593}
5594
5595/// Walks the whole crate in DFS order, visiting each item, counting the declared number of
5596/// lifetime generic parameters and function parameters. Also collects all `use` and
5597/// `extern crate` items so that `check_unused` doesn't need to walk the crate again.
5598struct ItemInfoCollector<'a, 'ast, 'ra, 'tcx> {
5599    r: &'a mut Resolver<'ra, 'tcx>,
5600    /// All `use` and `extern crate` items, in the order in which they are visited.
5601    use_items: Vec<&'ast Item>,
5602}
5603
5604impl ItemInfoCollector<'_, '_, '_, '_> {
5605    fn collect_fn_info(&mut self, decl: &FnDecl, id: NodeId) {
5606        self.r
5607            .delegation_fn_sigs
5608            .insert(self.r.owner_def_id(id), DelegationFnSig { has_self: decl.has_self() });
5609    }
5610}
5611
5612fn required_generic_args_suggestion(generics: &ast::Generics) -> Option<String> {
5613    let required = generics
5614        .params
5615        .iter()
5616        .filter_map(|param| match &param.kind {
5617            ast::GenericParamKind::Lifetime => Some("'_"),
5618            ast::GenericParamKind::Type { default } => {
5619                if default.is_none() {
5620                    Some("_")
5621                } else {
5622                    None
5623                }
5624            }
5625            ast::GenericParamKind::Const { default, .. } => {
5626                if default.is_none() {
5627                    Some("_")
5628                } else {
5629                    None
5630                }
5631            }
5632        })
5633        .collect::<Vec<_>>();
5634
5635    if required.is_empty() { None } else { Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>", required.join(", ")))
    })format!("<{}>", required.join(", "))) }
5636}
5637
5638impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, 'ast, '_, '_> {
5639    fn visit_item(&mut self, item: &'ast Item) {
5640        match &item.kind {
5641            ItemKind::TyAlias(TyAlias { generics, .. })
5642            | ItemKind::Const(ConstItem { generics, .. })
5643            | ItemKind::Fn(Fn { generics, .. })
5644            | ItemKind::Enum(_, generics, _)
5645            | ItemKind::Struct(_, generics, _)
5646            | ItemKind::Union(_, generics, _)
5647            | ItemKind::Impl(Impl { generics, .. })
5648            | ItemKind::Trait(Trait { generics, .. })
5649            | ItemKind::TraitAlias(TraitAlias { generics, .. }) => {
5650                if let ItemKind::Fn(Fn { sig, .. }) = &item.kind {
5651                    self.collect_fn_info(&sig.decl, item.id);
5652                }
5653
5654                let def_id = self.r.owner_def_id(item.id);
5655                let count = generics
5656                    .params
5657                    .iter()
5658                    .filter(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    ast::GenericParamKind::Lifetime { .. } => true,
    _ => false,
}matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5659                    .count();
5660                self.r.item_generics_num_lifetimes.insert(def_id, count);
5661            }
5662
5663            ItemKind::ForeignMod(ForeignMod { items, .. }) => {
5664                for foreign_item in items {
5665                    if let ForeignItemKind::Fn(Fn { sig, .. }) = &foreign_item.kind {
5666                        self.collect_fn_info(&sig.decl, foreign_item.id);
5667                    }
5668                }
5669            }
5670
5671            ItemKind::Use(..) | ItemKind::ExternCrate(..) => {
5672                self.use_items.push(item);
5673            }
5674
5675            ItemKind::Mod(..)
5676            | ItemKind::Static(..)
5677            | ItemKind::ConstBlock(..)
5678            | ItemKind::MacroDef(..)
5679            | ItemKind::GlobalAsm(..)
5680            | ItemKind::MacCall(..)
5681            | ItemKind::DelegationMac(..) => {}
5682            ItemKind::Delegation(..) => {
5683                // Delegated functions have lifetimes, their count is not necessarily zero.
5684                // But skipping the delegation items here doesn't mean that the count will be considered zero,
5685                // it means there will be a panic when retrieving the count,
5686                // but for delegation items we are never actually retrieving that count in practice.
5687            }
5688        }
5689        visit::walk_item(self, item)
5690    }
5691
5692    fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5693        if let AssocItemKind::Fn(Fn { sig, .. }) = &item.kind {
5694            self.collect_fn_info(&sig.decl, item.id);
5695        }
5696
5697        if let AssocItemKind::Type(ast::TyAlias { generics, .. }) = &item.kind {
5698            let def_id = self.r.owner_def_id(item.id);
5699            if let Some(suggestion) = required_generic_args_suggestion(generics) {
5700                self.r.item_required_generic_args_suggestions.insert(def_id, suggestion);
5701            }
5702        }
5703        visit::walk_assoc_item(self, item, ctxt);
5704    }
5705}
5706
5707impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5708    /// Returns the `use` and `extern crate` items of the crate, for use by `check_unused`.
5709    pub(crate) fn late_resolve_crate<'ast>(
5710        &mut self,
5711        krate: &'ast Crate,
5712    ) -> (Vec<&'ast Item>, Vec<UseError<'tcx>>) {
5713        with_owner(self, CRATE_NODE_ID, |this| {
5714            let mut info_collector = ItemInfoCollector { r: this, use_items: Vec::new() };
5715            visit::walk_crate(&mut info_collector, krate);
5716            let use_items = info_collector.use_items;
5717            let mut late_resolution_visitor = LateResolutionVisitor::new(this);
5718            late_resolution_visitor
5719                .resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5720            visit::walk_crate(&mut late_resolution_visitor, krate);
5721            let LateResolutionVisitor { use_injections, diag_metadata, .. } =
5722                late_resolution_visitor;
5723            for (id, span) in diag_metadata.unused_labels.iter() {
5724                this.lint_buffer.buffer_lint(
5725                    lint::builtin::UNUSED_LABELS,
5726                    *id,
5727                    *span,
5728                    crate::diagnostics::UnusedLabel,
5729                );
5730            }
5731            (use_items, use_injections)
5732        })
5733    }
5734}
5735
5736/// Check if definition matches a path
5737fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5738    let mut path = expected_path.iter().rev();
5739    while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5740        if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5741            return false;
5742        }
5743        def_id = parent;
5744    }
5745    true
5746}