Skip to main content

rustc_resolve/
late.rs

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