Skip to main content

rustc_resolve/
late.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let id = self.r.next_node_id();
            let lt =
                Lifetime {
                    id,
                    ident: Ident::new(kw::UnderscoreLifetime, span),
                };
            self.record_lifetime_use(anchor_id,
                LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
                LifetimeElisionCandidate::Ignore);
            self.resolve_anonymous_lifetime(&lt, anchor_id, true);
        }
    }
}#[instrument(level = "debug", skip(self))]
2164    fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
2165        let id = self.r.next_node_id();
2166        let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
2167
2168        self.record_lifetime_use(
2169            anchor_id,
2170            LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
2171            LifetimeElisionCandidate::Ignore,
2172        );
2173        self.resolve_anonymous_lifetime(&lt, anchor_id, true);
2174    }
2175
2176    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("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(2176u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["ident", "binder",
                                                    "kind"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&binder)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: LifetimeRes = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if true {
                {
                    match (&ident.name, &kw::UnderscoreLifetime) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    }
                };
            };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2184",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2184u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["ident.span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&ident.span)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let param = self.r.next_node_id();
            let res = LifetimeRes::Fresh { param, kind };
            self.record_lifetime_def(param, res);
            self.r.extra_lifetime_params_map.entry(binder).or_insert_with(Vec::new).push((ident,
                    param, kind));
            res
        }
    }
}#[instrument(level = "debug", skip(self))]
2177    fn create_fresh_lifetime(
2178        &mut self,
2179        ident: Ident,
2180        binder: NodeId,
2181        kind: MissingLifetimeKind,
2182    ) -> LifetimeRes {
2183        debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
2184        debug!(?ident.span);
2185
2186        // Leave the responsibility to create the `LocalDefId` to lowering.
2187        let param = self.r.next_node_id();
2188        let res = LifetimeRes::Fresh { param, kind };
2189        self.record_lifetime_def(param, res);
2190
2191        // Record the created lifetime parameter so lowering can pick it up and add it to HIR.
2192        self.r
2193            .extra_lifetime_params_map
2194            .entry(binder)
2195            .or_insert_with(Vec::new)
2196            .push((ident, param, kind));
2197        res
2198    }
2199
2200    #[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(2200u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["partial_res",
                                                    "path", "source", "path_span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&partial_res)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path_span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.record_lifetime_def(id, res);
            match res {
                LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } |
                    LifetimeRes::Static { .. } => {
                    if let Some(ref mut candidates) =
                            self.lifetime_elision_candidates {
                        candidates.push((res, candidate));
                    }
                }
                LifetimeRes::Infer | LifetimeRes::Error(..) |
                    LifetimeRes::ElidedAnchor { .. } => {}
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2424    fn record_lifetime_use(
2425        &mut self,
2426        id: NodeId,
2427        res: LifetimeRes,
2428        candidate: LifetimeElisionCandidate,
2429    ) {
2430        self.record_lifetime_def(id, res);
2431
2432        match res {
2433            LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2434                if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2435                    candidates.push((res, candidate));
2436                }
2437            }
2438            LifetimeRes::Infer | LifetimeRes::Error(..) | LifetimeRes::ElidedAnchor { .. } => {}
2439        }
2440    }
2441
2442    /// Can be used for both definitions and uses of lifetimes, as an error
2443    /// has already been reported.
2444    #[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(2444u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["id", "guar"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&guar)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(prev_res) =
                    self.r.current_owner.lifetimes_res_map.insert(id, res) {
                {
                    ::core::panicking::panic_fmt(format_args!("lifetime parameter {0:?} resolved multiple times ({1:?} before, {2:?} now)",
                            id, prev_res, res));
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2451    fn record_lifetime_def(&mut self, id: NodeId, res: LifetimeRes) {
2452        if let Some(prev_res) = self.r.current_owner.lifetimes_res_map.insert(id, res) {
2453            panic!(
2454                "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2455            )
2456        }
2457    }
2458
2459    /// Perform resolution of a function signature, accounting for lifetime elision.
2460    #[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(2460u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["fn_id", "has_self",
                                                    "output_ty", "report_elided_lifetimes_in_path"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&has_self as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&output_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&report_elided_lifetimes_in_path
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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