Skip to main content

rustc_resolve/
late.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let proj_start = path.len() - partial_res.unresolved_segments();
            for (i, segment) in path.iter().enumerate() {
                if segment.has_lifetime_args { continue; }
                let Some(segment_id) = segment.id else { continue; };
                let type_def_id =
                    match partial_res.base_res() {
                        Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start =>
                            {
                            self.r.tcx.parent(def_id)
                        }
                        Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start =>
                            {
                            self.r.tcx.parent(def_id)
                        }
                        Res::Def(DefKind::Struct, def_id) |
                            Res::Def(DefKind::Union, def_id) |
                            Res::Def(DefKind::Enum, def_id) |
                            Res::Def(DefKind::TyAlias, def_id) |
                            Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start => {
                            def_id
                        }
                        _ => continue,
                    };
                let expected_lifetimes =
                    self.r.item_generics_num_lifetimes(type_def_id);
                if expected_lifetimes == 0 { continue; }
                let node_ids = self.r.next_node_ids(expected_lifetimes);
                self.record_lifetime_res(segment_id,
                    LifetimeRes::ElidedAnchor {
                        start: node_ids.start,
                        end: node_ids.end,
                    }, LifetimeElisionCandidate::Ignore);
                let inferred =
                    match source {
                        PathSource::Trait(..) | PathSource::TraitItem(..) |
                            PathSource::Type | PathSource::PreciseCapturingArg(..) |
                            PathSource::ReturnTypeNotation | PathSource::Macro |
                            PathSource::Module => false,
                        PathSource::Expr(..) | PathSource::Pat |
                            PathSource::Struct(_) | PathSource::TupleStruct(..) |
                            PathSource::DefineOpaques | PathSource::Delegation => 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);
                            let guar =
                                self.r.dcx().emit_err(errors::ImplicitElidedLifetimeNotAllowedHere {
                                        span: path_span,
                                        subdiag,
                                    });
                            should_lint = false;
                            for id in node_ids {
                                self.record_lifetime_res(id, LifetimeRes::Error(guar),
                                    LifetimeElisionCandidate::Named);
                            }
                            break;
                        }
                        LifetimeRibKind::AnonymousCreateParameter { binder, .. } =>
                            {
                            let mut candidate =
                                LifetimeElisionCandidate::Missing(missing_lifetime);
                            for id in node_ids {
                                let res = self.create_fresh_lifetime(ident, binder, kind);
                                self.record_lifetime_res(id, res,
                                    replace(&mut candidate, LifetimeElisionCandidate::Named));
                            }
                            break;
                        }
                        LifetimeRibKind::Elided(res) => {
                            let mut candidate =
                                LifetimeElisionCandidate::Missing(missing_lifetime);
                            for id in node_ids {
                                self.record_lifetime_res(id, res,
                                    replace(&mut candidate, LifetimeElisionCandidate::Ignore));
                            }
                            break;
                        }
                        LifetimeRibKind::ElisionFailure => {
                            self.diag_metadata.current_elision_failures.push((missing_lifetime,
                                    LifetimeElisionCandidate::Ignore, Either::Right(node_ids)));
                            break;
                        }
                        LifetimeRibKind::AnonymousReportError |
                            LifetimeRibKind::Item => {
                            let guar =
                                self.report_missing_lifetime_specifiers([&missing_lifetime],
                                    None);
                            for id in node_ids {
                                self.record_lifetime_res(id, LifetimeRes::Error(guar),
                                    LifetimeElisionCandidate::Ignore);
                            }
                            break;
                        }
                        LifetimeRibKind::Generics { .. } |
                            LifetimeRibKind::ConstParamTy => {}
                        LifetimeRibKind::ConcreteAnonConst(_) => {
                            ::rustc_middle::util::bug::span_bug_fmt(elided_lifetime_span,
                                format_args!("unexpected rib kind: {0:?}", rib.kind))
                        }
                    }
                }
                if should_lint {
                    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))]
2139    fn resolve_elided_lifetimes_in_path(
2140        &mut self,
2141        partial_res: PartialRes,
2142        path: &[Segment],
2143        source: PathSource<'_, 'ast, 'ra>,
2144        path_span: Span,
2145    ) {
2146        let proj_start = path.len() - partial_res.unresolved_segments();
2147        for (i, segment) in path.iter().enumerate() {
2148            if segment.has_lifetime_args {
2149                continue;
2150            }
2151            let Some(segment_id) = segment.id else {
2152                continue;
2153            };
2154
2155            // Figure out if this is a type/trait segment,
2156            // which may need lifetime elision performed.
2157            let type_def_id = match partial_res.base_res() {
2158                Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2159                    self.r.tcx.parent(def_id)
2160                }
2161                Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
2162                    self.r.tcx.parent(def_id)
2163                }
2164                Res::Def(DefKind::Struct, def_id)
2165                | Res::Def(DefKind::Union, def_id)
2166                | Res::Def(DefKind::Enum, def_id)
2167                | Res::Def(DefKind::TyAlias, def_id)
2168                | Res::Def(DefKind::Trait, def_id)
2169                    if i + 1 == proj_start =>
2170                {
2171                    def_id
2172                }
2173                _ => continue,
2174            };
2175
2176            let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2177            if expected_lifetimes == 0 {
2178                continue;
2179            }
2180
2181            let node_ids = self.r.next_node_ids(expected_lifetimes);
2182            self.record_lifetime_res(
2183                segment_id,
2184                LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2185                LifetimeElisionCandidate::Ignore,
2186            );
2187
2188            let inferred = match source {
2189                PathSource::Trait(..)
2190                | PathSource::TraitItem(..)
2191                | PathSource::Type
2192                | PathSource::PreciseCapturingArg(..)
2193                | PathSource::ReturnTypeNotation
2194                | PathSource::Macro
2195                | PathSource::Module => false,
2196                PathSource::Expr(..)
2197                | PathSource::Pat
2198                | PathSource::Struct(_)
2199                | PathSource::TupleStruct(..)
2200                | PathSource::DefineOpaques
2201                | PathSource::Delegation => true,
2202            };
2203            if inferred {
2204                // Do not create a parameter for patterns and expressions: type checking can infer
2205                // the appropriate lifetime for us.
2206                for id in node_ids {
2207                    self.record_lifetime_res(
2208                        id,
2209                        LifetimeRes::Infer,
2210                        LifetimeElisionCandidate::Named,
2211                    );
2212                }
2213                continue;
2214            }
2215
2216            let elided_lifetime_span = if segment.has_generic_args {
2217                // If there are brackets, but not generic arguments, then use the opening bracket
2218                segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2219            } else {
2220                // If there are no brackets, use the identifier span.
2221                // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
2222                // originating from macros, since the segment's span might be from a macro arg.
2223                segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2224            };
2225            let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2226
2227            let kind = if segment.has_generic_args {
2228                MissingLifetimeKind::Comma
2229            } else {
2230                MissingLifetimeKind::Brackets
2231            };
2232            let missing_lifetime = MissingLifetime {
2233                id: node_ids.start,
2234                id_for_lint: segment_id,
2235                span: elided_lifetime_span,
2236                kind,
2237                count: expected_lifetimes,
2238            };
2239            let mut should_lint = true;
2240            for rib in self.lifetime_ribs.iter().rev() {
2241                match rib.kind {
2242                    // In create-parameter mode we error here because we don't want to support
2243                    // deprecated impl elision in new features like impl elision and `async fn`,
2244                    // both of which work using the `CreateParameter` mode:
2245                    //
2246                    //     impl Foo for std::cell::Ref<u32> // note lack of '_
2247                    //     async fn foo(_: std::cell::Ref<u32>) { ... }
2248                    LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2249                    | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {
2250                        let sess = self.r.tcx.sess;
2251                        let subdiag = rustc_errors::elided_lifetime_in_path_suggestion(
2252                            sess.source_map(),
2253                            expected_lifetimes,
2254                            path_span,
2255                            !segment.has_generic_args,
2256                            elided_lifetime_span,
2257                        );
2258                        let guar =
2259                            self.r.dcx().emit_err(errors::ImplicitElidedLifetimeNotAllowedHere {
2260                                span: path_span,
2261                                subdiag,
2262                            });
2263                        should_lint = false;
2264
2265                        for id in node_ids {
2266                            self.record_lifetime_res(
2267                                id,
2268                                LifetimeRes::Error(guar),
2269                                LifetimeElisionCandidate::Named,
2270                            );
2271                        }
2272                        break;
2273                    }
2274                    // Do not create a parameter for patterns and expressions.
2275                    LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2276                        // Group all suggestions into the first record.
2277                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2278                        for id in node_ids {
2279                            let res = self.create_fresh_lifetime(ident, binder, kind);
2280                            self.record_lifetime_res(
2281                                id,
2282                                res,
2283                                replace(&mut candidate, LifetimeElisionCandidate::Named),
2284                            );
2285                        }
2286                        break;
2287                    }
2288                    LifetimeRibKind::Elided(res) => {
2289                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2290                        for id in node_ids {
2291                            self.record_lifetime_res(
2292                                id,
2293                                res,
2294                                replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2295                            );
2296                        }
2297                        break;
2298                    }
2299                    LifetimeRibKind::ElisionFailure => {
2300                        self.diag_metadata.current_elision_failures.push((
2301                            missing_lifetime,
2302                            LifetimeElisionCandidate::Ignore,
2303                            Either::Right(node_ids),
2304                        ));
2305                        break;
2306                    }
2307                    // `LifetimeRes::Error`, which would usually be used in the case of
2308                    // `ReportError`, is unsuitable here, as we don't emit an error yet. Instead,
2309                    // we simply resolve to an implicit lifetime, which will be checked later, at
2310                    // which point a suitable error will be emitted.
2311                    LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2312                        let guar =
2313                            self.report_missing_lifetime_specifiers([&missing_lifetime], None);
2314                        for id in node_ids {
2315                            self.record_lifetime_res(
2316                                id,
2317                                LifetimeRes::Error(guar),
2318                                LifetimeElisionCandidate::Ignore,
2319                            );
2320                        }
2321                        break;
2322                    }
2323                    LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
2324                    LifetimeRibKind::ConcreteAnonConst(_) => {
2325                        // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
2326                        span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2327                    }
2328                }
2329            }
2330
2331            if should_lint {
2332                self.r.lint_buffer.buffer_lint(
2333                    lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2334                    segment_id,
2335                    elided_lifetime_span,
2336                    lint::BuiltinLintDiag::ElidedLifetimesInPaths(
2337                        expected_lifetimes,
2338                        path_span,
2339                        !segment.has_generic_args,
2340                        elided_lifetime_span,
2341                    ),
2342                );
2343            }
2344        }
2345    }
2346
2347    #[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(2347u32),
                                    ::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))]
2348    fn record_lifetime_res(
2349        &mut self,
2350        id: NodeId,
2351        res: LifetimeRes,
2352        candidate: LifetimeElisionCandidate,
2353    ) {
2354        if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2355            panic!("lifetime {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)")
2356        }
2357
2358        match res {
2359            LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2360                if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2361                    candidates.push((res, candidate));
2362                }
2363            }
2364            LifetimeRes::Infer | LifetimeRes::Error(..) | LifetimeRes::ElidedAnchor { .. } => {}
2365        }
2366    }
2367
2368    #[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(2368u32),
                                    ::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))]
2369    fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
2370        if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2371            panic!(
2372                "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2373            )
2374        }
2375    }
2376
2377    /// Perform resolution of a function signature, accounting for lifetime elision.
2378    #[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(2378u32),
                                    ::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:2394",
                                                "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                ::tracing_core::__macro_support::Option::Some(2394u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                                ::tracing_core::field::FieldSet::new(&["elision_lifetime"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&elision_lifetime)
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        let outer_failures =
                            take(&mut this.diag_metadata.current_elision_failures);
                        let output_rib =
                            if let Ok(res) = elision_lifetime.as_ref() {
                                this.r.lifetime_elision_allowed.insert(fn_id);
                                LifetimeRibKind::Elided(*res)
                            } else { LifetimeRibKind::ElisionFailure };
                        this.with_lifetime_rib(output_rib,
                            |this| visit::walk_fn_ret_ty(this, output_ty));
                        let elision_failures =
                            replace(&mut this.diag_metadata.current_elision_failures,
                                outer_failures);
                        if !elision_failures.is_empty() {
                            let Err(failure_info) =
                                elision_lifetime else {
                                    ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
                                };
                            let guar =
                                this.report_missing_lifetime_specifiers(elision_failures.iter().map(|(missing_lifetime,
                                                ..)| missing_lifetime), Some(failure_info));
                            let mut record_res =
                                |lifetime, candidate|
                                    {
                                        this.record_lifetime_res(lifetime, LifetimeRes::Error(guar),
                                            candidate)
                                    };
                            for (_, candidate, nodes) in elision_failures {
                                match nodes {
                                    Either::Left(node_id) => record_res(node_id, candidate),
                                    Either::Right(node_ids) => {
                                        for lifetime in node_ids { record_res(lifetime, candidate) }
                                    }
                                }
                            }
                        }
                    });
        }
    }
}#[instrument(level = "debug", skip(self, inputs))]
2379    fn resolve_fn_signature(
2380        &mut self,
2381        fn_id: NodeId,
2382        has_self: bool,
2383        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2384        output_ty: &'ast FnRetTy,
2385        report_elided_lifetimes_in_path: bool,
2386    ) {
2387        let rib = LifetimeRibKind::AnonymousCreateParameter {
2388            binder: fn_id,
2389            report_in_path: report_elided_lifetimes_in_path,
2390        };
2391        self.with_lifetime_rib(rib, |this| {
2392            // Add each argument to the rib.
2393            let elision_lifetime = this.resolve_fn_params(has_self, inputs);
2394            debug!(?elision_lifetime);
2395
2396            let outer_failures = take(&mut this.diag_metadata.current_elision_failures);
2397            let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2398                this.r.lifetime_elision_allowed.insert(fn_id);
2399                LifetimeRibKind::Elided(*res)
2400            } else {
2401                LifetimeRibKind::ElisionFailure
2402            };
2403            this.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2404            let elision_failures =
2405                replace(&mut this.diag_metadata.current_elision_failures, outer_failures);
2406            if !elision_failures.is_empty() {
2407                let Err(failure_info) = elision_lifetime else { bug!() };
2408                let guar = this.report_missing_lifetime_specifiers(
2409                    elision_failures.iter().map(|(missing_lifetime, ..)| missing_lifetime),
2410                    Some(failure_info),
2411                );
2412                let mut record_res = |lifetime, candidate| {
2413                    this.record_lifetime_res(lifetime, LifetimeRes::Error(guar), candidate)
2414                };
2415                for (_, candidate, nodes) in elision_failures {
2416                    match nodes {
2417                        Either::Left(node_id) => record_res(node_id, candidate),
2418                        Either::Right(node_ids) => {
2419                            for lifetime in node_ids {
2420                                record_res(lifetime, candidate)
2421                            }
2422                        }
2423                    }
2424                }
2425            }
2426        });
2427    }
2428
2429    /// Resolve inside function parameters and parameter types.
2430    /// Returns the lifetime for elision in fn return type,
2431    /// or diagnostic information in case of elision failure.
2432    fn resolve_fn_params(
2433        &mut self,
2434        has_self: bool,
2435        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2436    ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2437        enum Elision {
2438            /// We have not found any candidate.
2439            None,
2440            /// We have a candidate bound to `self`.
2441            Self_(LifetimeRes),
2442            /// We have a candidate bound to a parameter.
2443            Param(LifetimeRes),
2444            /// We failed elision.
2445            Err,
2446        }
2447
2448        // Save elision state to reinstate it later.
2449        let outer_candidates = self.lifetime_elision_candidates.take();
2450
2451        // Result of elision.
2452        let mut elision_lifetime = Elision::None;
2453        // Information for diagnostics.
2454        let mut parameter_info = Vec::new();
2455        let mut all_candidates = Vec::new();
2456
2457        // Resolve and apply bindings first so diagnostics can see if they're used in types.
2458        let mut bindings = {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push((PatBoundCtx::Product, Default::default()));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [(PatBoundCtx::Product, Default::default())])))
    }
}smallvec![(PatBoundCtx::Product, Default::default())];
2459        for (pat, _) in inputs.clone() {
2460            {
    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:2460",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2460u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["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:?}");
2461            self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2462                if let Some(pat) = pat {
2463                    this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2464                }
2465            });
2466        }
2467        self.apply_pattern_bindings(bindings);
2468
2469        for (index, (pat, ty)) in inputs.enumerate() {
2470            {
    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:2470",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2470u32),
                        ::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:?}");
2471            // Record elision candidates only for this parameter.
2472            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);
2473            self.lifetime_elision_candidates = Some(Default::default());
2474            self.visit_ty(ty);
2475            let local_candidates = self.lifetime_elision_candidates.take();
2476
2477            if let Some(candidates) = local_candidates {
2478                let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2479                let lifetime_count = distinct.len();
2480                if lifetime_count != 0 {
2481                    parameter_info.push(ElisionFnParameter {
2482                        index,
2483                        ident: if let Some(pat) = pat
2484                            && let PatKind::Ident(_, ident, _) = pat.kind
2485                        {
2486                            Some(ident)
2487                        } else {
2488                            None
2489                        },
2490                        lifetime_count,
2491                        span: ty.span,
2492                    });
2493                    all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2494                        match candidate {
2495                            LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {
2496                                None
2497                            }
2498                            LifetimeElisionCandidate::Missing(missing) => Some(missing),
2499                        }
2500                    }));
2501                }
2502                if !distinct.is_empty() {
2503                    match elision_lifetime {
2504                        // We are the first parameter to bind lifetimes.
2505                        Elision::None => {
2506                            if let Some(res) = distinct.get_only() {
2507                                // We have a single lifetime => success.
2508                                elision_lifetime = Elision::Param(*res)
2509                            } else {
2510                                // We have multiple lifetimes => error.
2511                                elision_lifetime = Elision::Err;
2512                            }
2513                        }
2514                        // We have 2 parameters that bind lifetimes => error.
2515                        Elision::Param(_) => elision_lifetime = Elision::Err,
2516                        // `self` elision takes precedence over everything else.
2517                        Elision::Self_(_) | Elision::Err => {}
2518                    }
2519                }
2520            }
2521
2522            // Handle `self` specially.
2523            if index == 0 && has_self {
2524                let self_lifetime = self.find_lifetime_for_self(ty);
2525                elision_lifetime = match self_lifetime {
2526                    // We found `self` elision.
2527                    Set1::One(lifetime) => Elision::Self_(lifetime),
2528                    // `self` itself had ambiguous lifetimes, e.g.
2529                    // &Box<&Self>. In this case we won't consider
2530                    // taking an alternative parameter lifetime; just avoid elision
2531                    // entirely.
2532                    Set1::Many => Elision::Err,
2533                    // We do not have `self` elision: disregard the `Elision::Param` that we may
2534                    // have found.
2535                    Set1::Empty => Elision::None,
2536                }
2537            }
2538            {
    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:2538",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2538u32),
                        ::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");
2539        }
2540
2541        // Reinstate elision state.
2542        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);
2543        self.lifetime_elision_candidates = outer_candidates;
2544
2545        if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2546            return Ok(res);
2547        }
2548
2549        // We do not have a candidate.
2550        Err((all_candidates, parameter_info))
2551    }
2552
2553    /// List all the lifetimes that appear in the provided type.
2554    fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2555        /// Visits a type to find all the &references, and determines the
2556        /// set of lifetimes for all of those references where the referent
2557        /// contains Self.
2558        struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2559            r: &'a Resolver<'ra, 'tcx>,
2560            impl_self: Option<Res>,
2561            lifetime: Set1<LifetimeRes>,
2562        }
2563
2564        impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2565            fn visit_ty(&mut self, ty: &'ra Ty) {
2566                {
    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:2566",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2566u32),
                        ::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);
2567                if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2568                    // See if anything inside the &thing contains Self
2569                    let mut visitor =
2570                        SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2571                    visitor.visit_ty(ty);
2572                    {
    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:2572",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2572u32),
                        ::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);
2573                    if visitor.self_found {
2574                        let lt_id = if let Some(lt) = lt {
2575                            lt.id
2576                        } else {
2577                            let res = self.r.lifetimes_res_map[&ty.id];
2578                            let LifetimeRes::ElidedAnchor { start, .. } = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2579                            start
2580                        };
2581                        let lt_res = self.r.lifetimes_res_map[&lt_id];
2582                        {
    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:2582",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2582u32),
                        ::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);
2583                        self.lifetime.insert(lt_res);
2584                    }
2585                }
2586                visit::walk_ty(self, ty)
2587            }
2588
2589            // A type may have an expression as a const generic argument.
2590            // We do not want to recurse into those.
2591            fn visit_expr(&mut self, _: &'ra Expr) {}
2592        }
2593
2594        /// Visitor which checks the referent of a &Thing to see if the
2595        /// Thing contains Self
2596        struct SelfVisitor<'a, 'ra, 'tcx> {
2597            r: &'a Resolver<'ra, 'tcx>,
2598            impl_self: Option<Res>,
2599            self_found: bool,
2600        }
2601
2602        impl SelfVisitor<'_, '_, '_> {
2603            // Look for `self: &'a Self` - also desugared from `&'a self`
2604            fn is_self_ty(&self, ty: &Ty) -> bool {
2605                match ty.kind {
2606                    TyKind::ImplicitSelf => true,
2607                    TyKind::Path(None, _) => {
2608                        let path_res = self.r.partial_res_map[&ty.id].full_res();
2609                        if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2610                            return true;
2611                        }
2612                        self.impl_self.is_some() && path_res == self.impl_self
2613                    }
2614                    _ => false,
2615                }
2616            }
2617        }
2618
2619        impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2620            fn visit_ty(&mut self, ty: &'ra Ty) {
2621                {
    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:2621",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2621u32),
                        ::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);
2622                if self.is_self_ty(ty) {
2623                    {
    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:2623",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2623u32),
                        ::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");
2624                    self.self_found = true;
2625                }
2626                visit::walk_ty(self, ty)
2627            }
2628
2629            // A type may have an expression as a const generic argument.
2630            // We do not want to recurse into those.
2631            fn visit_expr(&mut self, _: &'ra Expr) {}
2632        }
2633
2634        let impl_self = self
2635            .diag_metadata
2636            .current_self_type
2637            .as_ref()
2638            .and_then(|ty| {
2639                if let TyKind::Path(None, _) = ty.kind {
2640                    self.r.partial_res_map.get(&ty.id)
2641                } else {
2642                    None
2643                }
2644            })
2645            .and_then(|res| res.full_res())
2646            .filter(|res| {
2647                // Permit the types that unambiguously always
2648                // result in the same type constructor being used
2649                // (it can't differ between `Self` and `self`).
2650                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _) |
        Res::PrimTy(_) => true,
    _ => false,
}matches!(
2651                    res,
2652                    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2653                )
2654            });
2655        let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2656        visitor.visit_ty(ty);
2657        {
    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:2657",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2657u32),
                        ::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);
2658        visitor.lifetime
2659    }
2660
2661    /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
2662    /// label and reports an error if the label is not found or is unreachable.
2663    fn resolve_label(&self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2664        let mut suggestion = None;
2665
2666        for i in (0..self.label_ribs.len()).rev() {
2667            let rib = &self.label_ribs[i];
2668
2669            if let RibKind::MacroDefinition(def) = rib.kind
2670                // If an invocation of this macro created `ident`, give up on `ident`
2671                // and switch to `ident`'s source from the macro definition.
2672                && def == self.r.macro_def(label.span.ctxt())
2673            {
2674                label.span.remove_mark();
2675            }
2676
2677            let ident = label.normalize_to_macro_rules();
2678            if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2679                let definition_span = ident.span;
2680                return if self.is_label_valid_from_rib(i) {
2681                    Ok((*id, definition_span))
2682                } else {
2683                    Err(ResolutionError::UnreachableLabel {
2684                        name: label.name,
2685                        definition_span,
2686                        suggestion,
2687                    })
2688                };
2689            }
2690
2691            // Diagnostics: Check if this rib contains a label with a similar name, keep track of
2692            // the first such label that is encountered.
2693            suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2694        }
2695
2696        Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2697    }
2698
2699    /// Determine whether or not a label from the `rib_index`th label rib is reachable.
2700    fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2701        let ribs = &self.label_ribs[rib_index + 1..];
2702        ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2703    }
2704
2705    fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2706        {
    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:2706",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2706u32),
                        ::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");
2707        let kind = self.r.local_def_kind(item.id);
2708        self.with_current_self_item(item, |this| {
2709            this.with_generic_param_rib(
2710                &generics.params,
2711                RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2712                item.id,
2713                LifetimeBinderKind::Item,
2714                generics.span,
2715                |this| {
2716                    let item_def_id = this.r.local_def_id(item.id).to_def_id();
2717                    this.with_self_rib(
2718                        Res::SelfTyAlias { alias_to: item_def_id, is_trait_impl: false },
2719                        |this| {
2720                            visit::walk_item(this, item);
2721                        },
2722                    );
2723                },
2724            );
2725        });
2726    }
2727
2728    fn future_proof_import(&mut self, use_tree: &UseTree) {
2729        if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2730            let ident = segment.ident;
2731            if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2732                return;
2733            }
2734
2735            let nss = match use_tree.kind {
2736                UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2737                _ => &[TypeNS],
2738            };
2739            let report_error = |this: &Self, ns| {
2740                if this.should_report_errs() {
2741                    let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2742                    this.r.dcx().emit_err(errors::ImportsCannotReferTo { span: ident.span, what });
2743                }
2744            };
2745
2746            for &ns in nss {
2747                match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2748                    Some(LateDecl::RibDef(..)) => {
2749                        report_error(self, ns);
2750                    }
2751                    Some(LateDecl::Decl(binding)) => {
2752                        if let Some(LateDecl::RibDef(..)) =
2753                            self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2754                        {
2755                            report_error(self, ns);
2756                        }
2757                    }
2758                    None => {}
2759                }
2760            }
2761        } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2762            for (use_tree, _) in items {
2763                self.future_proof_import(use_tree);
2764            }
2765        }
2766    }
2767
2768    fn resolve_item(&mut self, item: &'ast Item) {
2769        let mod_inner_docs =
2770            #[allow(non_exhaustive_omitted_patterns)] match item.kind {
    ItemKind::Mod(..) => true,
    _ => false,
}matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2771        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(..)) {
2772            self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2773        }
2774
2775        {
    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:2775",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2775u32),
                        ::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);
2776
2777        let def_kind = self.r.local_def_kind(item.id);
2778        match &item.kind {
2779            ItemKind::TyAlias(box TyAlias { generics, .. }) => {
2780                self.with_generic_param_rib(
2781                    &generics.params,
2782                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2783                    item.id,
2784                    LifetimeBinderKind::Item,
2785                    generics.span,
2786                    |this| visit::walk_item(this, item),
2787                );
2788            }
2789
2790            ItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
2791                self.with_generic_param_rib(
2792                    &generics.params,
2793                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2794                    item.id,
2795                    LifetimeBinderKind::Function,
2796                    generics.span,
2797                    |this| visit::walk_item(this, item),
2798                );
2799                self.resolve_define_opaques(define_opaque);
2800            }
2801
2802            ItemKind::Enum(_, generics, _)
2803            | ItemKind::Struct(_, generics, _)
2804            | ItemKind::Union(_, generics, _) => {
2805                self.resolve_adt(item, generics);
2806            }
2807
2808            ItemKind::Impl(Impl { generics, of_trait, self_ty, items: impl_items, .. }) => {
2809                self.diag_metadata.current_impl_items = Some(impl_items);
2810                self.resolve_implementation(
2811                    &item.attrs,
2812                    generics,
2813                    of_trait.as_deref(),
2814                    self_ty,
2815                    item.id,
2816                    impl_items,
2817                );
2818                self.diag_metadata.current_impl_items = None;
2819            }
2820
2821            ItemKind::Trait(box Trait { generics, bounds, items, impl_restriction, .. }) => {
2822                // resolve paths for `impl` restrictions
2823                self.resolve_impl_restriction_path(impl_restriction);
2824
2825                // Create a new rib for the trait-wide type parameters.
2826                self.with_generic_param_rib(
2827                    &generics.params,
2828                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2829                    item.id,
2830                    LifetimeBinderKind::Item,
2831                    generics.span,
2832                    |this| {
2833                        let local_def_id = this.r.local_def_id(item.id).to_def_id();
2834                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2835                            this.visit_generics(generics);
2836                            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);
2837                            this.resolve_trait_items(items);
2838                        });
2839                    },
2840                );
2841            }
2842
2843            ItemKind::TraitAlias(box TraitAlias { generics, bounds, .. }) => {
2844                // Create a new rib for the trait-wide type parameters.
2845                self.with_generic_param_rib(
2846                    &generics.params,
2847                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2848                    item.id,
2849                    LifetimeBinderKind::Item,
2850                    generics.span,
2851                    |this| {
2852                        let local_def_id = this.r.local_def_id(item.id).to_def_id();
2853                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2854                            this.visit_generics(generics);
2855                            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);
2856                        });
2857                    },
2858                );
2859            }
2860
2861            ItemKind::Mod(..) => {
2862                let module = self.r.expect_module(self.r.local_def_id(item.id).to_def_id());
2863                let orig_module = replace(&mut self.parent_scope.module, module);
2864                self.with_rib(ValueNS, RibKind::Module(module), |this| {
2865                    this.with_rib(TypeNS, RibKind::Module(module), |this| {
2866                        if mod_inner_docs {
2867                            this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2868                        }
2869                        let old_macro_rules = this.parent_scope.macro_rules;
2870                        visit::walk_item(this, item);
2871                        // Maintain macro_rules scopes in the same way as during early resolution
2872                        // for diagnostics and doc links.
2873                        if item.attrs.iter().all(|attr| {
2874                            !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2875                        }) {
2876                            this.parent_scope.macro_rules = old_macro_rules;
2877                        }
2878                    })
2879                });
2880                self.parent_scope.module = orig_module;
2881            }
2882
2883            ItemKind::Static(box ast::StaticItem { ident, ty, expr, define_opaque, .. }) => {
2884                self.with_static_rib(def_kind, |this| {
2885                    this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2886                        this.visit_ty(ty);
2887                    });
2888                    if let Some(expr) = expr {
2889                        // We already forbid generic params because of the above item rib,
2890                        // so it doesn't matter whether this is a trivial constant.
2891                        this.resolve_static_body(expr, Some((*ident, ConstantItemKind::Static)));
2892                    }
2893                });
2894                self.resolve_define_opaques(define_opaque);
2895            }
2896
2897            ItemKind::Const(box ast::ConstItem {
2898                ident,
2899                generics,
2900                ty,
2901                rhs_kind,
2902                define_opaque,
2903                defaultness: _,
2904            }) => {
2905                self.with_generic_param_rib(
2906                    &generics.params,
2907                    RibKind::Item(
2908                        if self.r.tcx.features().generic_const_items() {
2909                            HasGenericParams::Yes(generics.span)
2910                        } else {
2911                            HasGenericParams::No
2912                        },
2913                        def_kind,
2914                    ),
2915                    item.id,
2916                    LifetimeBinderKind::ConstItem,
2917                    generics.span,
2918                    |this| {
2919                        this.visit_generics(generics);
2920
2921                        this.with_lifetime_rib(
2922                            LifetimeRibKind::Elided(LifetimeRes::Static),
2923                            |this| {
2924                                if rhs_kind.is_type_const()
2925                                    && !this.r.tcx.features().generic_const_parameter_types()
2926                                {
2927                                    this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
2928                                        this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
2929                                            this.with_lifetime_rib(
2930                                                LifetimeRibKind::ConstParamTy,
2931                                                |this| this.visit_ty(ty),
2932                                            )
2933                                        })
2934                                    });
2935                                } else {
2936                                    this.visit_ty(ty);
2937                                }
2938                            },
2939                        );
2940
2941                        this.resolve_const_item_rhs(
2942                            rhs_kind,
2943                            Some((*ident, ConstantItemKind::Const)),
2944                        );
2945                    },
2946                );
2947                self.resolve_define_opaques(define_opaque);
2948            }
2949            ItemKind::ConstBlock(ConstBlockItem { id: _, span: _, block }) => self
2950                .with_generic_param_rib(
2951                    &[],
2952                    RibKind::Item(HasGenericParams::No, def_kind),
2953                    item.id,
2954                    LifetimeBinderKind::ConstItem,
2955                    DUMMY_SP,
2956                    |this| {
2957                        this.with_lifetime_rib(
2958                            LifetimeRibKind::Elided(LifetimeRes::Infer),
2959                            |this| {
2960                                this.with_constant_rib(
2961                                    IsRepeatExpr::No,
2962                                    ConstantHasGenerics::Yes,
2963                                    Some((ConstBlockItem::IDENT, ConstantItemKind::Const)),
2964                                    |this| this.resolve_labeled_block(None, block.id, block),
2965                                )
2966                            },
2967                        );
2968                    },
2969                ),
2970
2971            ItemKind::Use(use_tree) => {
2972                let maybe_exported = match use_tree.kind {
2973                    UseTreeKind::Simple(_) | UseTreeKind::Glob => MaybeExported::Ok(item.id),
2974                    UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
2975                };
2976                self.resolve_doc_links(&item.attrs, maybe_exported);
2977
2978                self.future_proof_import(use_tree);
2979            }
2980
2981            ItemKind::MacroDef(_, macro_def) => {
2982                // Maintain macro_rules scopes in the same way as during early resolution
2983                // for diagnostics and doc links.
2984                if macro_def.macro_rules {
2985                    let def_id = self.r.local_def_id(item.id);
2986                    self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
2987                }
2988
2989                if let Some(EiiDecl { foreign_item: extern_item_path, impl_unsafe: _ }) =
2990                    &macro_def.eii_declaration
2991                {
2992                    self.smart_resolve_path(
2993                        item.id,
2994                        &None,
2995                        extern_item_path,
2996                        PathSource::Expr(None),
2997                    );
2998                }
2999            }
3000
3001            ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
3002                visit::walk_item(self, item);
3003            }
3004
3005            ItemKind::Delegation(delegation) => {
3006                let span = delegation.path.segments.last().unwrap().ident.span;
3007                self.with_generic_param_rib(
3008                    &[],
3009                    RibKind::Item(HasGenericParams::Yes(span), def_kind),
3010                    item.id,
3011                    LifetimeBinderKind::Function,
3012                    span,
3013                    |this| this.resolve_delegation(delegation, item.id, false),
3014                );
3015            }
3016
3017            ItemKind::ExternCrate(..) => {}
3018
3019            ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
3020                {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3021            }
3022        }
3023    }
3024
3025    fn with_generic_param_rib<F>(
3026        &mut self,
3027        params: &[GenericParam],
3028        kind: RibKind<'ra>,
3029        binder: NodeId,
3030        generics_kind: LifetimeBinderKind,
3031        generics_span: Span,
3032        f: F,
3033    ) where
3034        F: FnOnce(&mut Self),
3035    {
3036        {
    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:3036",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3036u32),
                        ::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");
3037        let lifetime_kind =
3038            LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind };
3039
3040        let mut function_type_rib = Rib::new(kind);
3041        let mut function_value_rib = Rib::new(kind);
3042        let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
3043
3044        // Only check for shadowed bindings if we're declaring new params.
3045        if !params.is_empty() {
3046            let mut seen_bindings = FxHashMap::default();
3047            // Store all seen lifetimes names from outer scopes.
3048            let mut seen_lifetimes = FxHashSet::default();
3049
3050            // We also can't shadow bindings from associated parent items.
3051            for ns in [ValueNS, TypeNS] {
3052                for parent_rib in self.ribs[ns].iter().rev() {
3053                    // Break at module or block level, to account for nested items which are
3054                    // allowed to shadow generic param names.
3055                    if #[allow(non_exhaustive_omitted_patterns)] match parent_rib.kind {
    RibKind::Module(..) | RibKind::Block(..) => true,
    _ => false,
}matches!(parent_rib.kind, RibKind::Module(..) | RibKind::Block(..)) {
3056                        break;
3057                    }
3058
3059                    seen_bindings
3060                        .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
3061                }
3062            }
3063
3064            // Forbid shadowing lifetime bindings
3065            for rib in self.lifetime_ribs.iter().rev() {
3066                seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
3067                if let LifetimeRibKind::Item = rib.kind {
3068                    break;
3069                }
3070            }
3071
3072            for param in params {
3073                let ident = param.ident.normalize_to_macros_2_0();
3074                {
    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:3074",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3074u32),
                        ::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);
3075
3076                if let GenericParamKind::Lifetime = param.kind
3077                    && let Some(&original) = seen_lifetimes.get(&ident)
3078                {
3079                    let guar = diagnostics::signal_lifetime_shadowing(
3080                        self.r.tcx.sess,
3081                        original,
3082                        param.ident,
3083                    );
3084                    // Record lifetime res, so lowering knows there is something fishy.
3085                    self.record_lifetime_param(param.id, LifetimeRes::Error(guar));
3086                    continue;
3087                }
3088
3089                match seen_bindings.entry(ident) {
3090                    Entry::Occupied(entry) => {
3091                        let span = *entry.get();
3092                        let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
3093                        let guar = self.r.report_error(param.ident.span, err);
3094                        let rib = match param.kind {
3095                            GenericParamKind::Lifetime => {
3096                                // Record lifetime res, so lowering knows there is something fishy.
3097                                self.record_lifetime_param(param.id, LifetimeRes::Error(guar));
3098                                continue;
3099                            }
3100                            GenericParamKind::Type { .. } => &mut function_type_rib,
3101                            GenericParamKind::Const { .. } => &mut function_value_rib,
3102                        };
3103
3104                        // Taint the resolution in case of errors to prevent follow up errors in typeck
3105                        self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
3106                        rib.bindings.insert(ident, Res::Err);
3107                        continue;
3108                    }
3109                    Entry::Vacant(entry) => {
3110                        entry.insert(param.ident.span);
3111                    }
3112                }
3113
3114                if param.ident.name == kw::UnderscoreLifetime {
3115                    // To avoid emitting two similar errors,
3116                    // we need to check if the span is a raw underscore lifetime, see issue #143152
3117                    let is_raw_underscore_lifetime = self
3118                        .r
3119                        .tcx
3120                        .sess
3121                        .psess
3122                        .raw_identifier_spans
3123                        .iter()
3124                        .any(|span| span == param.span());
3125
3126                    let guar = self
3127                        .r
3128                        .dcx()
3129                        .create_err(errors::UnderscoreLifetimeIsReserved { span: param.ident.span })
3130                        .emit_unless_delay(is_raw_underscore_lifetime);
3131                    // Record lifetime res, so lowering knows there is something fishy.
3132                    self.record_lifetime_param(param.id, LifetimeRes::Error(guar));
3133                    continue;
3134                }
3135
3136                if param.ident.name == kw::StaticLifetime {
3137                    let guar = self.r.dcx().emit_err(errors::StaticLifetimeIsReserved {
3138                        span: param.ident.span,
3139                        lifetime: param.ident,
3140                    });
3141                    // Record lifetime res, so lowering knows there is something fishy.
3142                    self.record_lifetime_param(param.id, LifetimeRes::Error(guar));
3143                    continue;
3144                }
3145
3146                let def_id = self.r.local_def_id(param.id);
3147
3148                // Plain insert (no renaming).
3149                let (rib, def_kind) = match param.kind {
3150                    GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
3151                    GenericParamKind::Const { .. } => {
3152                        (&mut function_value_rib, DefKind::ConstParam)
3153                    }
3154                    GenericParamKind::Lifetime => {
3155                        let res = LifetimeRes::Param { param: def_id, binder };
3156                        self.record_lifetime_param(param.id, res);
3157                        function_lifetime_rib.bindings.insert(ident, (param.id, res));
3158                        continue;
3159                    }
3160                };
3161
3162                let res = match kind {
3163                    RibKind::Item(..) | RibKind::AssocItem => {
3164                        Res::Def(def_kind, def_id.to_def_id())
3165                    }
3166                    RibKind::Normal => {
3167                        // FIXME(non_lifetime_binders): Stop special-casing
3168                        // const params to error out here.
3169                        if self.r.tcx.features().non_lifetime_binders()
3170                            && #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    GenericParamKind::Type { .. } => true,
    _ => false,
}matches!(param.kind, GenericParamKind::Type { .. })
3171                        {
3172                            Res::Def(def_kind, def_id.to_def_id())
3173                        } else {
3174                            Res::Err
3175                        }
3176                    }
3177                    _ => ::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),
3178                };
3179                self.r.record_partial_res(param.id, PartialRes::new(res));
3180                rib.bindings.insert(ident, res);
3181            }
3182        }
3183
3184        self.lifetime_ribs.push(function_lifetime_rib);
3185        self.ribs[ValueNS].push(function_value_rib);
3186        self.ribs[TypeNS].push(function_type_rib);
3187
3188        f(self);
3189
3190        self.ribs[TypeNS].pop();
3191        self.ribs[ValueNS].pop();
3192        let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
3193
3194        // Do not account for the parameters we just bound for function lifetime elision.
3195        if let Some(ref mut candidates) = self.lifetime_elision_candidates {
3196            for (_, res) in function_lifetime_rib.bindings.values() {
3197                candidates.retain(|(r, _)| r != res);
3198            }
3199        }
3200
3201        if let LifetimeBinderKind::FnPtrType
3202        | LifetimeBinderKind::WhereBound
3203        | LifetimeBinderKind::Function
3204        | LifetimeBinderKind::ImplBlock = generics_kind
3205        {
3206            self.maybe_report_lifetime_uses(generics_span, params)
3207        }
3208    }
3209
3210    fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
3211        self.label_ribs.push(Rib::new(kind));
3212        f(self);
3213        self.label_ribs.pop();
3214    }
3215
3216    fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
3217        let kind = RibKind::Item(HasGenericParams::No, def_kind);
3218        self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
3219    }
3220
3221    // HACK(min_const_generics, generic_const_exprs): We
3222    // want to keep allowing `[0; size_of::<*mut T>()]`
3223    // with a future compat lint for now. We do this by adding an
3224    // additional special case for repeat expressions.
3225    //
3226    // Note that we intentionally still forbid `[0; N + 1]` during
3227    // name resolution so that we don't extend the future
3228    // compat lint to new cases.
3229    #[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(3229u32),
                                    ::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))]
3230    fn with_constant_rib(
3231        &mut self,
3232        is_repeat: IsRepeatExpr,
3233        may_use_generics: ConstantHasGenerics,
3234        item: Option<(Ident, ConstantItemKind)>,
3235        f: impl FnOnce(&mut Self),
3236    ) {
3237        let f = |this: &mut Self| {
3238            this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3239                this.with_rib(
3240                    TypeNS,
3241                    RibKind::ConstantItem(
3242                        may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3243                        item,
3244                    ),
3245                    |this| {
3246                        this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3247                    },
3248                )
3249            })
3250        };
3251
3252        if let ConstantHasGenerics::No(cause) = may_use_generics {
3253            self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3254        } else {
3255            f(self)
3256        }
3257    }
3258
3259    fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
3260        // Handle nested impls (inside fn bodies)
3261        let previous_value =
3262            replace(&mut self.diag_metadata.current_self_type, Some(self_type.clone()));
3263        let result = f(self);
3264        self.diag_metadata.current_self_type = previous_value;
3265        result
3266    }
3267
3268    fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3269        let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3270        let result = f(self);
3271        self.diag_metadata.current_self_item = previous_value;
3272        result
3273    }
3274
3275    /// When evaluating a `trait` use its associated types' idents for suggestions in E0425.
3276    fn resolve_trait_items(&mut self, trait_items: &'ast [Box<AssocItem>]) {
3277        let trait_assoc_items =
3278            replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3279
3280        let walk_assoc_item =
3281            |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3282                this.with_generic_param_rib(
3283                    &generics.params,
3284                    RibKind::AssocItem,
3285                    item.id,
3286                    kind,
3287                    generics.span,
3288                    |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3289                );
3290            };
3291
3292        for item in trait_items {
3293            self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3294            match &item.kind {
3295                AssocItemKind::Const(box ast::ConstItem {
3296                    generics,
3297                    ty,
3298                    rhs_kind,
3299                    define_opaque,
3300                    ..
3301                }) => {
3302                    self.with_generic_param_rib(
3303                        &generics.params,
3304                        RibKind::AssocItem,
3305                        item.id,
3306                        LifetimeBinderKind::ConstItem,
3307                        generics.span,
3308                        |this| {
3309                            this.with_lifetime_rib(
3310                                LifetimeRibKind::StaticIfNoLifetimeInScope {
3311                                    lint_id: item.id,
3312                                    emit_lint: false,
3313                                },
3314                                |this| {
3315                                    this.visit_generics(generics);
3316                                    if rhs_kind.is_type_const()
3317                                        && !this.r.tcx.features().generic_const_parameter_types()
3318                                    {
3319                                        this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3320                                            this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
3321                                                this.with_lifetime_rib(
3322                                                    LifetimeRibKind::ConstParamTy,
3323                                                    |this| this.visit_ty(ty),
3324                                                )
3325                                            })
3326                                        });
3327                                    } else {
3328                                        this.visit_ty(ty);
3329                                    }
3330
3331                                    // Only impose the restrictions of `ConstRibKind` for an
3332                                    // actual constant expression in a provided default.
3333                                    //
3334                                    // We allow arbitrary const expressions inside of associated consts,
3335                                    // even if they are potentially not const evaluatable.
3336                                    //
3337                                    // Type parameters can already be used and as associated consts are
3338                                    // not used as part of the type system, this is far less surprising.
3339                                    this.resolve_const_item_rhs(rhs_kind, None);
3340                                },
3341                            )
3342                        },
3343                    );
3344
3345                    self.resolve_define_opaques(define_opaque);
3346                }
3347                AssocItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
3348                    walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3349
3350                    self.resolve_define_opaques(define_opaque);
3351                }
3352                AssocItemKind::Delegation(delegation) => {
3353                    self.with_generic_param_rib(
3354                        &[],
3355                        RibKind::AssocItem,
3356                        item.id,
3357                        LifetimeBinderKind::Function,
3358                        delegation.path.segments.last().unwrap().ident.span,
3359                        |this| this.resolve_delegation(delegation, item.id, false),
3360                    );
3361                }
3362                AssocItemKind::Type(box TyAlias { generics, .. }) => self
3363                    .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3364                        walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3365                    }),
3366                AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3367                    {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3368                }
3369            };
3370        }
3371
3372        self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3373    }
3374
3375    /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
3376    fn with_optional_trait_ref<T>(
3377        &mut self,
3378        opt_trait_ref: Option<&TraitRef>,
3379        self_type: &'ast Ty,
3380        f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3381    ) -> T {
3382        let mut new_val = None;
3383        let mut new_id = None;
3384        if let Some(trait_ref) = opt_trait_ref {
3385            let path: Vec<_> = Segment::from_path(&trait_ref.path);
3386            self.diag_metadata.currently_processing_impl_trait =
3387                Some((trait_ref.clone(), self_type.clone()));
3388            let res = self.smart_resolve_path_fragment(
3389                &None,
3390                &path,
3391                PathSource::Trait(AliasPossibility::No),
3392                Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3393                RecordPartialRes::Yes,
3394                None,
3395            );
3396            self.diag_metadata.currently_processing_impl_trait = None;
3397            if let Some(def_id) = res.expect_full_res().opt_def_id() {
3398                new_id = Some(def_id);
3399                new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3400            }
3401        }
3402        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3403        let result = f(self, new_id);
3404        self.current_trait_ref = original_trait_ref;
3405        result
3406    }
3407
3408    fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3409        let mut self_type_rib = Rib::new(RibKind::Normal);
3410
3411        // Plain insert (no renaming, since types are not currently hygienic)
3412        self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3413        self.ribs[ns].push(self_type_rib);
3414        f(self);
3415        self.ribs[ns].pop();
3416    }
3417
3418    fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3419        self.with_self_rib_ns(TypeNS, self_res, f)
3420    }
3421
3422    fn resolve_implementation(
3423        &mut self,
3424        attrs: &[ast::Attribute],
3425        generics: &'ast Generics,
3426        of_trait: Option<&'ast ast::TraitImplHeader>,
3427        self_type: &'ast Ty,
3428        item_id: NodeId,
3429        impl_items: &'ast [Box<AssocItem>],
3430    ) {
3431        {
    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:3431",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3431u32),
                        ::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");
3432        // If applicable, create a rib for the type parameters.
3433        self.with_generic_param_rib(
3434            &generics.params,
3435            RibKind::Item(HasGenericParams::Yes(generics.span), self.r.local_def_kind(item_id)),
3436            item_id,
3437            LifetimeBinderKind::ImplBlock,
3438            generics.span,
3439            |this| {
3440                // Dummy self type for better errors if `Self` is used in the trait path.
3441                this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3442                    this.with_lifetime_rib(
3443                        LifetimeRibKind::AnonymousCreateParameter {
3444                            binder: item_id,
3445                            report_in_path: true
3446                        },
3447                        |this| {
3448                            // Resolve the trait reference, if necessary.
3449                            this.with_optional_trait_ref(
3450                                of_trait.map(|t| &t.trait_ref),
3451                                self_type,
3452                                |this, trait_id| {
3453                                    this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3454
3455                                    let item_def_id = this.r.local_def_id(item_id);
3456
3457                                    // Register the trait definitions from here.
3458                                    if let Some(trait_id) = trait_id {
3459                                        this.r
3460                                            .trait_impls
3461                                            .entry(trait_id)
3462                                            .or_default()
3463                                            .push(item_def_id);
3464                                    }
3465
3466                                    let item_def_id = item_def_id.to_def_id();
3467                                    let res = Res::SelfTyAlias {
3468                                        alias_to: item_def_id,
3469                                        is_trait_impl: trait_id.is_some(),
3470                                    };
3471                                    this.with_self_rib(res, |this| {
3472                                        if let Some(of_trait) = of_trait {
3473                                            // Resolve type arguments in the trait path.
3474                                            visit::walk_trait_ref(this, &of_trait.trait_ref);
3475                                        }
3476                                        // Resolve the self type.
3477                                        this.visit_ty(self_type);
3478                                        // Resolve the generic parameters.
3479                                        this.visit_generics(generics);
3480
3481                                        // Resolve the items within the impl.
3482                                        this.with_current_self_type(self_type, |this| {
3483                                            this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3484                                                {
    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:3484",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3484u32),
                        ::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, ...)");
3485                                                let mut seen_trait_items = Default::default();
3486                                                for item in impl_items {
3487                                                    this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id, of_trait.is_some());
3488                                                }
3489                                            });
3490                                        });
3491                                    });
3492                                },
3493                            )
3494                        },
3495                    );
3496                });
3497            },
3498        );
3499    }
3500
3501    fn resolve_impl_item(
3502        &mut self,
3503        item: &'ast AssocItem,
3504        seen_trait_items: &mut FxHashMap<DefId, Span>,
3505        trait_id: Option<DefId>,
3506        is_in_trait_impl: bool,
3507    ) {
3508        use crate::ResolutionError::*;
3509        self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3510        let prev = self.diag_metadata.current_impl_item.take();
3511        self.diag_metadata.current_impl_item = Some(&item);
3512        match &item.kind {
3513            AssocItemKind::Const(box ast::ConstItem {
3514                ident,
3515                generics,
3516                ty,
3517                rhs_kind,
3518                define_opaque,
3519                ..
3520            }) => {
3521                {
    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:3521",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3521u32),
                        ::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");
3522                self.with_generic_param_rib(
3523                    &generics.params,
3524                    RibKind::AssocItem,
3525                    item.id,
3526                    LifetimeBinderKind::ConstItem,
3527                    generics.span,
3528                    |this| {
3529                        this.with_lifetime_rib(
3530                            // Until these are a hard error, we need to create them within the
3531                            // correct binder, Otherwise the lifetimes of this assoc const think
3532                            // they are lifetimes of the trait.
3533                            LifetimeRibKind::AnonymousCreateParameter {
3534                                binder: item.id,
3535                                report_in_path: true,
3536                            },
3537                            |this| {
3538                                this.with_lifetime_rib(
3539                                    LifetimeRibKind::StaticIfNoLifetimeInScope {
3540                                        lint_id: item.id,
3541                                        // In impls, it's not a hard error yet due to backcompat.
3542                                        emit_lint: true,
3543                                    },
3544                                    |this| {
3545                                        // If this is a trait impl, ensure the const
3546                                        // exists in trait
3547                                        this.check_trait_item(
3548                                            item.id,
3549                                            *ident,
3550                                            &item.kind,
3551                                            ValueNS,
3552                                            item.span,
3553                                            seen_trait_items,
3554                                            |i, s, c| ConstNotMemberOfTrait(i, s, c),
3555                                        );
3556
3557                                        this.visit_generics(generics);
3558                                        if rhs_kind.is_type_const()
3559                                            && !this
3560                                                .r
3561                                                .tcx
3562                                                .features()
3563                                                .generic_const_parameter_types()
3564                                        {
3565                                            this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3566                                                this.with_rib(
3567                                                    ValueNS,
3568                                                    RibKind::ConstParamTy,
3569                                                    |this| {
3570                                                        this.with_lifetime_rib(
3571                                                            LifetimeRibKind::ConstParamTy,
3572                                                            |this| this.visit_ty(ty),
3573                                                        )
3574                                                    },
3575                                                )
3576                                            });
3577                                        } else {
3578                                            this.visit_ty(ty);
3579                                        }
3580                                        // We allow arbitrary const expressions inside of associated consts,
3581                                        // even if they are potentially not const evaluatable.
3582                                        //
3583                                        // Type parameters can already be used and as associated consts are
3584                                        // not used as part of the type system, this is far less surprising.
3585                                        this.resolve_const_item_rhs(rhs_kind, None);
3586                                    },
3587                                )
3588                            },
3589                        );
3590                    },
3591                );
3592                self.resolve_define_opaques(define_opaque);
3593            }
3594            AssocItemKind::Fn(box Fn { ident, generics, define_opaque, .. }) => {
3595                {
    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:3595",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3595u32),
                        ::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");
3596                // We also need a new scope for the impl item type parameters.
3597                self.with_generic_param_rib(
3598                    &generics.params,
3599                    RibKind::AssocItem,
3600                    item.id,
3601                    LifetimeBinderKind::Function,
3602                    generics.span,
3603                    |this| {
3604                        // If this is a trait impl, ensure the method
3605                        // exists in trait
3606                        this.check_trait_item(
3607                            item.id,
3608                            *ident,
3609                            &item.kind,
3610                            ValueNS,
3611                            item.span,
3612                            seen_trait_items,
3613                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3614                        );
3615
3616                        visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3617                    },
3618                );
3619
3620                self.resolve_define_opaques(define_opaque);
3621            }
3622            AssocItemKind::Type(box TyAlias { ident, generics, .. }) => {
3623                self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3624                {
    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:3624",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3624u32),
                        ::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");
3625                // We also need a new scope for the impl item type parameters.
3626                self.with_generic_param_rib(
3627                    &generics.params,
3628                    RibKind::AssocItem,
3629                    item.id,
3630                    LifetimeBinderKind::ImplAssocType,
3631                    generics.span,
3632                    |this| {
3633                        this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3634                            // If this is a trait impl, ensure the type
3635                            // exists in trait
3636                            this.check_trait_item(
3637                                item.id,
3638                                *ident,
3639                                &item.kind,
3640                                TypeNS,
3641                                item.span,
3642                                seen_trait_items,
3643                                |i, s, c| TypeNotMemberOfTrait(i, s, c),
3644                            );
3645
3646                            visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3647                        });
3648                    },
3649                );
3650                self.diag_metadata.in_non_gat_assoc_type = None;
3651            }
3652            AssocItemKind::Delegation(box delegation) => {
3653                {
    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:3653",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3653u32),
                        ::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");
3654                self.with_generic_param_rib(
3655                    &[],
3656                    RibKind::AssocItem,
3657                    item.id,
3658                    LifetimeBinderKind::Function,
3659                    delegation.path.segments.last().unwrap().ident.span,
3660                    |this| {
3661                        this.check_trait_item(
3662                            item.id,
3663                            delegation.ident,
3664                            &item.kind,
3665                            ValueNS,
3666                            item.span,
3667                            seen_trait_items,
3668                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3669                        );
3670
3671                        // Here we don't use `trait_id`, as we can process unresolved trait, however
3672                        // in this case we are still in a trait impl, https://github.com/rust-lang/rust/issues/150152
3673                        this.resolve_delegation(delegation, item.id, is_in_trait_impl);
3674                    },
3675                );
3676            }
3677            AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3678                {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3679            }
3680        }
3681        self.diag_metadata.current_impl_item = prev;
3682    }
3683
3684    fn check_trait_item<F>(
3685        &mut self,
3686        id: NodeId,
3687        mut ident: Ident,
3688        kind: &AssocItemKind,
3689        ns: Namespace,
3690        span: Span,
3691        seen_trait_items: &mut FxHashMap<DefId, Span>,
3692        err: F,
3693    ) where
3694        F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3695    {
3696        // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3697        let Some((module, _)) = self.current_trait_ref else {
3698            return;
3699        };
3700        ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3701        let key = BindingKey::new(IdentKey::new(ident), ns);
3702        let mut decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3703        {
    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:3703",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3703u32),
                        ::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);
3704        if decl.is_none() {
3705            // We could not find the trait item in the correct namespace.
3706            // Check the other namespace to report an error.
3707            let ns = match ns {
3708                ValueNS => TypeNS,
3709                TypeNS => ValueNS,
3710                _ => ns,
3711            };
3712            let key = BindingKey::new(IdentKey::new(ident), ns);
3713            decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3714            {
    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:3714",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3714u32),
                        ::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);
3715        }
3716
3717        let feed_visibility = |this: &mut Self, def_id| {
3718            let vis = this.r.tcx.visibility(def_id);
3719            let vis = if vis.is_visible_locally() {
3720                vis.expect_local()
3721            } else {
3722                this.r.dcx().span_delayed_bug(
3723                    span,
3724                    "error should be emitted when an unexpected trait item is used",
3725                );
3726                Visibility::Public
3727            };
3728            this.r.feed_visibility(this.r.feed(id), vis);
3729        };
3730
3731        let Some(decl) = decl else {
3732            // We could not find the method: report an error.
3733            let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
3734            let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3735            let path_names = path_names_to_string(path);
3736            self.report_error(span, err(ident, path_names, candidate));
3737            feed_visibility(self, module.def_id());
3738            return;
3739        };
3740
3741        let res = decl.res();
3742        let Res::Def(def_kind, id_in_trait) = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
3743        feed_visibility(self, id_in_trait);
3744
3745        match seen_trait_items.entry(id_in_trait) {
3746            Entry::Occupied(entry) => {
3747                self.report_error(
3748                    span,
3749                    ResolutionError::TraitImplDuplicate {
3750                        name: ident,
3751                        old_span: *entry.get(),
3752                        trait_item_span: decl.span,
3753                    },
3754                );
3755                return;
3756            }
3757            Entry::Vacant(entry) => {
3758                entry.insert(span);
3759            }
3760        };
3761
3762        match (def_kind, kind) {
3763            (DefKind::AssocTy, AssocItemKind::Type(..))
3764            | (DefKind::AssocFn, AssocItemKind::Fn(..))
3765            | (DefKind::AssocConst { .. }, AssocItemKind::Const(..))
3766            | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3767                self.r.record_partial_res(id, PartialRes::new(res));
3768                return;
3769            }
3770            _ => {}
3771        }
3772
3773        // The method kind does not correspond to what appeared in the trait, report.
3774        let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3775        let (code, kind) = match kind {
3776            AssocItemKind::Const(..) => (E0323, "const"),
3777            AssocItemKind::Fn(..) => (E0324, "method"),
3778            AssocItemKind::Type(..) => (E0325, "type"),
3779            AssocItemKind::Delegation(..) => (E0324, "method"),
3780            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3781                ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("unexpanded macro"))span_bug!(span, "unexpanded macro")
3782            }
3783        };
3784        let trait_path = path_names_to_string(path);
3785        self.report_error(
3786            span,
3787            ResolutionError::TraitImplMismatch {
3788                name: ident,
3789                kind,
3790                code,
3791                trait_path,
3792                trait_item_span: decl.span,
3793            },
3794        );
3795    }
3796
3797    fn resolve_static_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3798        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3799            this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3800                this.visit_expr(expr)
3801            });
3802        })
3803    }
3804
3805    fn resolve_const_item_rhs(
3806        &mut self,
3807        rhs_kind: &'ast ConstItemRhsKind,
3808        item: Option<(Ident, ConstantItemKind)>,
3809    ) {
3810        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| match rhs_kind {
3811            ConstItemRhsKind::TypeConst { rhs: Some(anon_const) } => {
3812                this.resolve_anon_const(anon_const, AnonConstKind::ConstArg(IsRepeatExpr::No));
3813            }
3814            ConstItemRhsKind::Body { rhs: Some(expr) } => {
3815                this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3816                    this.visit_expr(expr)
3817                });
3818            }
3819            _ => (),
3820        })
3821    }
3822
3823    fn resolve_delegation(
3824        &mut self,
3825        delegation: &'ast Delegation,
3826        item_id: NodeId,
3827        is_in_trait_impl: bool,
3828    ) {
3829        self.smart_resolve_path(
3830            delegation.id,
3831            &delegation.qself,
3832            &delegation.path,
3833            PathSource::Delegation,
3834        );
3835
3836        if let Some(qself) = &delegation.qself {
3837            self.visit_ty(&qself.ty);
3838        }
3839
3840        self.visit_path(&delegation.path);
3841
3842        self.r.delegation_infos.insert(
3843            self.r.local_def_id(item_id),
3844            DelegationInfo {
3845                resolution_node: if is_in_trait_impl { item_id } else { delegation.id },
3846            },
3847        );
3848
3849        let Some(body) = &delegation.body else { return };
3850        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3851            let span = delegation.path.segments.last().unwrap().ident.span;
3852            let ident = Ident::new(kw::SelfLower, span.normalize_to_macro_rules());
3853            let res = Res::Local(delegation.id);
3854            this.innermost_rib_bindings(ValueNS).insert(ident, res);
3855
3856            //As we lower target_expr_template body to a body of a function we need a label rib (#148889)
3857            this.with_label_rib(RibKind::FnOrCoroutine, |this| {
3858                this.visit_block(body);
3859            });
3860        });
3861    }
3862
3863    fn resolve_params(&mut self, params: &'ast [Param]) {
3864        let mut bindings = {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push((PatBoundCtx::Product, Default::default()));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [(PatBoundCtx::Product, Default::default())])))
    }
}smallvec![(PatBoundCtx::Product, Default::default())];
3865        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3866            for Param { pat, .. } in params {
3867                this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3868            }
3869            this.apply_pattern_bindings(bindings);
3870        });
3871        for Param { ty, .. } in params {
3872            self.visit_ty(ty);
3873        }
3874    }
3875
3876    fn resolve_local(&mut self, local: &'ast Local) {
3877        {
    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:3877",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3877u32),
                        ::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);
3878        // Resolve the type.
3879        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);
3880
3881        // Resolve the initializer.
3882        if let Some((init, els)) = local.kind.init_else_opt() {
3883            self.visit_expr(init);
3884
3885            // Resolve the `else` block
3886            if let Some(els) = els {
3887                self.visit_block(els);
3888            }
3889        }
3890
3891        // Resolve the pattern.
3892        self.resolve_pattern_top(&local.pat, PatternSource::Let);
3893    }
3894
3895    /// Build a map from pattern identifiers to binding-info's, and check the bindings are
3896    /// consistent when encountering or-patterns and never patterns.
3897    /// This is done hygienically: this could arise for a macro that expands into an or-pattern
3898    /// where one 'x' was from the user and one 'x' came from the macro.
3899    ///
3900    /// A never pattern by definition indicates an unreachable case. For example, matching on
3901    /// `Result<T, &!>` could look like:
3902    /// ```rust
3903    /// # #![feature(never_type)]
3904    /// # #![feature(never_patterns)]
3905    /// # fn bar(_x: u32) {}
3906    /// let foo: Result<u32, &!> = Ok(0);
3907    /// match foo {
3908    ///     Ok(x) => bar(x),
3909    ///     Err(&!),
3910    /// }
3911    /// ```
3912    /// This extends to product types: `(x, !)` is likewise unreachable. So it doesn't make sense to
3913    /// have a binding here, and we tell the user to use `_` instead.
3914    fn compute_and_check_binding_map(
3915        &mut self,
3916        pat: &Pat,
3917    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3918        let mut binding_map = FxIndexMap::default();
3919        let mut is_never_pat = false;
3920
3921        pat.walk(&mut |pat| {
3922            match pat.kind {
3923                PatKind::Ident(annotation, ident, ref sub_pat)
3924                    if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3925                {
3926                    binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3927                }
3928                PatKind::Or(ref ps) => {
3929                    // Check the consistency of this or-pattern and
3930                    // then add all bindings to the larger map.
3931                    match self.compute_and_check_or_pat_binding_map(ps) {
3932                        Ok(bm) => binding_map.extend(bm),
3933                        Err(IsNeverPattern) => is_never_pat = true,
3934                    }
3935                    return false;
3936                }
3937                PatKind::Never => is_never_pat = true,
3938                _ => {}
3939            }
3940
3941            true
3942        });
3943
3944        if is_never_pat {
3945            for (_, binding) in binding_map {
3946                self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3947            }
3948            Err(IsNeverPattern)
3949        } else {
3950            Ok(binding_map)
3951        }
3952    }
3953
3954    fn is_base_res_local(&self, nid: NodeId) -> bool {
3955        #[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!(
3956            self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
3957            Some(Res::Local(..))
3958        )
3959    }
3960
3961    /// Compute the binding map for an or-pattern. Checks that all of the arms in the or-pattern
3962    /// have exactly the same set of bindings, with the same binding modes for each.
3963    /// Returns the computed binding map and a boolean indicating whether the pattern is a never
3964    /// pattern.
3965    ///
3966    /// A never pattern by definition indicates an unreachable case. For example, destructuring a
3967    /// `Result<T, &!>` could look like:
3968    /// ```rust
3969    /// # #![feature(never_type)]
3970    /// # #![feature(never_patterns)]
3971    /// # fn foo() -> Result<bool, &'static !> { Ok(true) }
3972    /// let (Ok(x) | Err(&!)) = foo();
3973    /// # let _ = x;
3974    /// ```
3975    /// Because the `Err(&!)` branch is never reached, it does not need to have the same bindings as
3976    /// the other branches of the or-pattern. So we must ignore never pattern when checking the
3977    /// bindings of an or-pattern.
3978    /// Moreover, if all the subpatterns are never patterns (e.g. `Ok(!) | Err(!)`), then the
3979    /// pattern as a whole counts as a never pattern (since it's definitionallly unreachable).
3980    fn compute_and_check_or_pat_binding_map(
3981        &mut self,
3982        pats: &[Pat],
3983    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3984        let mut missing_vars = FxIndexMap::default();
3985        let mut inconsistent_vars = FxIndexMap::default();
3986
3987        // 1) Compute the binding maps of all arms; we must ignore never patterns here.
3988        let not_never_pats = pats
3989            .iter()
3990            .filter_map(|pat| {
3991                let binding_map = self.compute_and_check_binding_map(pat).ok()?;
3992                Some((binding_map, pat))
3993            })
3994            .collect::<Vec<_>>();
3995
3996        // 2) Record any missing bindings or binding mode inconsistencies.
3997        for &(ref map_outer, pat_outer) in not_never_pats.iter() {
3998            // Check against all arms except for the same pattern which is always self-consistent.
3999            let inners = not_never_pats.iter().filter(|(_, pat)| pat.id != pat_outer.id);
4000
4001            for &(ref map, pat) in inners {
4002                for (&name, binding_inner) in map {
4003                    match map_outer.get(&name) {
4004                        None => {
4005                            // The inner binding is missing in the outer.
4006                            let binding_error =
4007                                missing_vars.entry(name).or_insert_with(|| BindingError {
4008                                    name,
4009                                    origin: Default::default(),
4010                                    target: Default::default(),
4011                                    could_be_path: name.as_str().starts_with(char::is_uppercase),
4012                                });
4013                            binding_error.origin.push((binding_inner.span, pat.clone()));
4014                            binding_error.target.push(pat_outer.clone());
4015                        }
4016                        Some(binding_outer) => {
4017                            if binding_outer.annotation != binding_inner.annotation {
4018                                // The binding modes in the outer and inner bindings differ.
4019                                inconsistent_vars
4020                                    .entry(name)
4021                                    .or_insert((binding_inner.span, binding_outer.span));
4022                            }
4023                        }
4024                    }
4025                }
4026            }
4027        }
4028
4029        // 3) Report all missing variables we found.
4030        for (name, mut v) in missing_vars {
4031            if inconsistent_vars.contains_key(&name) {
4032                v.could_be_path = false;
4033            }
4034            self.report_error(
4035                v.origin.iter().next().unwrap().0,
4036                ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
4037            );
4038        }
4039
4040        // 4) Report all inconsistencies in binding modes we found.
4041        for (name, v) in inconsistent_vars {
4042            self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
4043        }
4044
4045        // 5) Bubble up the final binding map.
4046        if not_never_pats.is_empty() {
4047            // All the patterns are never patterns, so the whole or-pattern is one too.
4048            Err(IsNeverPattern)
4049        } else {
4050            let mut binding_map = FxIndexMap::default();
4051            for (bm, _) in not_never_pats {
4052                binding_map.extend(bm);
4053            }
4054            Ok(binding_map)
4055        }
4056    }
4057
4058    /// Check the consistency of bindings wrt or-patterns and never patterns.
4059    fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
4060        let mut is_or_or_never = false;
4061        pat.walk(&mut |pat| match pat.kind {
4062            PatKind::Or(..) | PatKind::Never => {
4063                is_or_or_never = true;
4064                false
4065            }
4066            _ => true,
4067        });
4068        if is_or_or_never {
4069            let _ = self.compute_and_check_binding_map(pat);
4070        }
4071    }
4072
4073    fn resolve_arm(&mut self, arm: &'ast Arm) {
4074        self.with_rib(ValueNS, RibKind::Normal, |this| {
4075            this.resolve_pattern_top(&arm.pat, PatternSource::Match);
4076            if let Some(x) = arm.guard.as_ref().map(|g| &g.cond) {
    match ::rustc_ast_ir::visit::VisitorResult::branch(this.visit_expr(x)) {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};visit_opt!(this, visit_expr, arm.guard.as_ref().map(|g| &g.cond));
4077            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);
4078        });
4079    }
4080
4081    /// Arising from `source`, resolve a top level pattern.
4082    fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
4083        let mut bindings = {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push((PatBoundCtx::Product, Default::default()));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [(PatBoundCtx::Product, Default::default())])))
    }
}smallvec![(PatBoundCtx::Product, Default::default())];
4084        self.resolve_pattern(pat, pat_src, &mut bindings);
4085        self.apply_pattern_bindings(bindings);
4086    }
4087
4088    /// Apply the bindings from a pattern to the innermost rib of the current scope.
4089    fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
4090        let rib_bindings = self.innermost_rib_bindings(ValueNS);
4091        let Some((_, pat_bindings)) = pat_bindings.pop() else {
4092            ::rustc_middle::util::bug::bug_fmt(format_args!("tried applying nonexistent bindings from pattern"));bug!("tried applying nonexistent bindings from pattern");
4093        };
4094
4095        if rib_bindings.is_empty() {
4096            // Often, such as for match arms, the bindings are introduced into a new rib.
4097            // In this case, we can move the bindings over directly.
4098            *rib_bindings = pat_bindings;
4099        } else {
4100            rib_bindings.extend(pat_bindings);
4101        }
4102    }
4103
4104    /// Resolve bindings in a pattern. `apply_pattern_bindings` must be called after to introduce
4105    /// the bindings into scope.
4106    fn resolve_pattern(
4107        &mut self,
4108        pat: &'ast Pat,
4109        pat_src: PatternSource,
4110        bindings: &mut PatternBindings,
4111    ) {
4112        // We walk the pattern before declaring the pattern's inner bindings,
4113        // so that we avoid resolving a literal expression to a binding defined
4114        // by the pattern.
4115        // NB: `Self::visit_pat` must be used rather than `visit::walk_pat` to avoid resolving guard
4116        // patterns' guard expressions multiple times (#141265).
4117        self.visit_pat(pat);
4118        self.resolve_pattern_inner(pat, pat_src, bindings);
4119        // This has to happen *after* we determine which pat_idents are variants:
4120        self.check_consistent_bindings(pat);
4121    }
4122
4123    /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
4124    ///
4125    /// ### `bindings`
4126    ///
4127    /// A stack of sets of bindings accumulated.
4128    ///
4129    /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
4130    /// be interpreted as re-binding an already bound binding. This results in an error.
4131    /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
4132    /// in reusing this binding rather than creating a fresh one.
4133    ///
4134    /// When called at the top level, the stack must have a single element
4135    /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
4136    /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
4137    /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
4138    /// When each `p_i` has been dealt with, the top set is merged with its parent.
4139    /// When a whole or-pattern has been dealt with, the thing happens.
4140    ///
4141    /// See the implementation and `fresh_binding` for more details.
4142    #[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(4142u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["pat", "pat_src"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat_src)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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