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