Skip to main content

rustc_resolve/
late.rs

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