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