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