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