Skip to main content

rustc_resolve/
late.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: T = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.lifetime_ribs.push(LifetimeRib::new(kind));
            let outer_elision_candidates =
                self.lifetime_elision_candidates.take();
            let ret = work(self);
            self.lifetime_elision_candidates = outer_elision_candidates;
            self.lifetime_ribs.pop();
            ret
        }
    }
}#[instrument(level = "debug", skip(self, work))]
1697    fn with_lifetime_rib<T>(
1698        &mut self,
1699        kind: LifetimeRibKind,
1700        work: impl FnOnce(&mut Self) -> T,
1701    ) -> T {
1702        self.lifetime_ribs.push(LifetimeRib::new(kind));
1703        let outer_elision_candidates = self.lifetime_elision_candidates.take();
1704        let ret = work(self);
1705        self.lifetime_elision_candidates = outer_elision_candidates;
1706        self.lifetime_ribs.pop();
1707        ret
1708    }
1709
1710    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("resolve_lifetime",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1710u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["lifetime",
                                                    "use_ctxt"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_ctxt)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ident = lifetime.ident;
            if ident.name == kw::StaticLifetime {
                self.record_lifetime_res(lifetime.id, LifetimeRes::Static,
                    LifetimeElisionCandidate::Named);
                return;
            }
            if ident.name == kw::UnderscoreLifetime {
                return self.resolve_anonymous_lifetime(lifetime, lifetime.id,
                        false);
            }
            let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
            while let Some(rib) = lifetime_rib_iter.next() {
                let normalized_ident = ident.normalize_to_macros_2_0();
                if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
                    self.record_lifetime_res(lifetime.id, res,
                        LifetimeElisionCandidate::Named);
                    if let LifetimeRes::Param { param, binder } = res {
                        match self.lifetime_uses.entry(param) {
                            Entry::Vacant(v) => {
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:1736",
                                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1736u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                                        ::tracing_core::field::FieldSet::new(&["message"],
                                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                        ::tracing::metadata::Kind::EVENT)
                                                };
                                            ::tracing::callsite::DefaultCallsite::new(&META)
                                        };
                                    let enabled =
                                        ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            {
                                                let interest = __CALLSITE.interest();
                                                !interest.is_never() &&
                                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                        interest)
                                            };
                                    if enabled {
                                        (|value_set: ::tracing::field::ValueSet|
                                                    {
                                                        let meta = __CALLSITE.metadata();
                                                        ::tracing::Event::dispatch(meta, &value_set);
                                                        ;
                                                    })({
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                let mut iter = __CALLSITE.metadata().fields().iter();
                                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&format_args!("First use of {0:?} at {1:?}",
                                                                                    res, ident.span) as &dyn Value))])
                                            });
                                    } else { ; }
                                };
                                let use_set =
                                    self.lifetime_ribs.iter().rev().find_map(|rib|
                                                match rib.kind {
                                                    LifetimeRibKind::Item |
                                                        LifetimeRibKind::AnonymousReportError |
                                                        LifetimeRibKind::StaticIfNoLifetimeInScope { .. } |
                                                        LifetimeRibKind::ElisionFailure =>
                                                        Some(LifetimeUseSet::Many),
                                                    LifetimeRibKind::AnonymousCreateParameter {
                                                        binder: anon_binder, .. } =>
                                                        Some(if binder == anon_binder {
                                                                LifetimeUseSet::One { use_span: ident.span, use_ctxt }
                                                            } else { LifetimeUseSet::Many }),
                                                    LifetimeRibKind::Elided(r) =>
                                                        Some(if res == r {
                                                                LifetimeUseSet::One { use_span: ident.span, use_ctxt }
                                                            } else { LifetimeUseSet::Many }),
                                                    LifetimeRibKind::Generics { .. } |
                                                        LifetimeRibKind::ConstParamTy => None,
                                                    LifetimeRibKind::ConcreteAnonConst(_) => {
                                                        ::rustc_middle::util::bug::span_bug_fmt(ident.span,
                                                            format_args!("unexpected rib kind: {0:?}", rib.kind))
                                                    }
                                                }).unwrap_or(LifetimeUseSet::Many);
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:1772",
                                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1772u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                                        ::tracing_core::field::FieldSet::new(&["use_ctxt",
                                                                        "use_set"],
                                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                        ::tracing::metadata::Kind::EVENT)
                                                };
                                            ::tracing::callsite::DefaultCallsite::new(&META)
                                        };
                                    let enabled =
                                        ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            {
                                                let interest = __CALLSITE.interest();
                                                !interest.is_never() &&
                                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                        interest)
                                            };
                                    if enabled {
                                        (|value_set: ::tracing::field::ValueSet|
                                                    {
                                                        let meta = __CALLSITE.metadata();
                                                        ::tracing::Event::dispatch(meta, &value_set);
                                                        ;
                                                    })({
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                let mut iter = __CALLSITE.metadata().fields().iter();
                                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&debug(&use_ctxt)
                                                                            as &dyn Value)),
                                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&debug(&use_set) as
                                                                            &dyn Value))])
                                            });
                                    } else { ; }
                                };
                                v.insert(use_set);
                            }
                            Entry::Occupied(mut o) => {
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:1776",
                                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1776u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                                        ::tracing_core::field::FieldSet::new(&["message"],
                                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                        ::tracing::metadata::Kind::EVENT)
                                                };
                                            ::tracing::callsite::DefaultCallsite::new(&META)
                                        };
                                    let enabled =
                                        ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            {
                                                let interest = __CALLSITE.interest();
                                                !interest.is_never() &&
                                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                        interest)
                                            };
                                    if enabled {
                                        (|value_set: ::tracing::field::ValueSet|
                                                    {
                                                        let meta = __CALLSITE.metadata();
                                                        ::tracing::Event::dispatch(meta, &value_set);
                                                        ;
                                                    })({
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                let mut iter = __CALLSITE.metadata().fields().iter();
                                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&format_args!("Many uses of {0:?} at {1:?}",
                                                                                    res, ident.span) as &dyn Value))])
                                            });
                                    } else { ; }
                                };
                                *o.get_mut() = LifetimeUseSet::Many;
                            }
                        }
                    }
                    return;
                }
                match rib.kind {
                    LifetimeRibKind::Item => break,
                    LifetimeRibKind::ConstParamTy => {
                        let guar =
                            self.emit_non_static_lt_in_const_param_ty_error(lifetime);
                        self.record_lifetime_res(lifetime.id,
                            LifetimeRes::Error(guar), LifetimeElisionCandidate::Ignore);
                        return;
                    }
                    LifetimeRibKind::ConcreteAnonConst(cause) => {
                        let guar =
                            self.emit_forbidden_non_static_lifetime_error(cause,
                                lifetime);
                        self.record_lifetime_res(lifetime.id,
                            LifetimeRes::Error(guar), LifetimeElisionCandidate::Ignore);
                        return;
                    }
                    LifetimeRibKind::AnonymousCreateParameter { .. } |
                        LifetimeRibKind::Elided(_) | LifetimeRibKind::Generics { ..
                        } | LifetimeRibKind::ElisionFailure |
                        LifetimeRibKind::AnonymousReportError |
                        LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {}
                }
            }
            let normalized_ident = ident.normalize_to_macros_2_0();
            let outer_res =
                lifetime_rib_iter.find_map(|rib|
                        rib.bindings.get_key_value(&normalized_ident).map(|(&outer,
                                    _)| outer));
            let guar =
                self.emit_undeclared_lifetime_error(lifetime, outer_res);
            self.record_lifetime_res(lifetime.id, LifetimeRes::Error(guar),
                LifetimeElisionCandidate::Named);
        }
    }
}#[instrument(level = "debug", skip(self))]
1711    fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1712        let ident = lifetime.ident;
1713
1714        if ident.name == kw::StaticLifetime {
1715            self.record_lifetime_res(
1716                lifetime.id,
1717                LifetimeRes::Static,
1718                LifetimeElisionCandidate::Named,
1719            );
1720            return;
1721        }
1722
1723        if ident.name == kw::UnderscoreLifetime {
1724            return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1725        }
1726
1727        let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1728        while let Some(rib) = lifetime_rib_iter.next() {
1729            let normalized_ident = ident.normalize_to_macros_2_0();
1730            if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1731                self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
1732
1733                if let LifetimeRes::Param { param, binder } = res {
1734                    match self.lifetime_uses.entry(param) {
1735                        Entry::Vacant(v) => {
1736                            debug!("First use of {:?} at {:?}", res, ident.span);
1737                            let use_set = self
1738                                .lifetime_ribs
1739                                .iter()
1740                                .rev()
1741                                .find_map(|rib| match rib.kind {
1742                                    // Do not suggest eliding a lifetime where an anonymous
1743                                    // lifetime would be illegal.
1744                                    LifetimeRibKind::Item
1745                                    | LifetimeRibKind::AnonymousReportError
1746                                    | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1747                                    | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1748                                    // An anonymous lifetime is legal here, and bound to the right
1749                                    // place, go ahead.
1750                                    LifetimeRibKind::AnonymousCreateParameter {
1751                                        binder: anon_binder,
1752                                        ..
1753                                    } => Some(if binder == anon_binder {
1754                                        LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1755                                    } else {
1756                                        LifetimeUseSet::Many
1757                                    }),
1758                                    // Only report if eliding the lifetime would have the same
1759                                    // semantics.
1760                                    LifetimeRibKind::Elided(r) => Some(if res == r {
1761                                        LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1762                                    } else {
1763                                        LifetimeUseSet::Many
1764                                    }),
1765                                    LifetimeRibKind::Generics { .. }
1766                                    | LifetimeRibKind::ConstParamTy => None,
1767                                    LifetimeRibKind::ConcreteAnonConst(_) => {
1768                                        span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1769                                    }
1770                                })
1771                                .unwrap_or(LifetimeUseSet::Many);
1772                            debug!(?use_ctxt, ?use_set);
1773                            v.insert(use_set);
1774                        }
1775                        Entry::Occupied(mut o) => {
1776                            debug!("Many uses of {:?} at {:?}", res, ident.span);
1777                            *o.get_mut() = LifetimeUseSet::Many;
1778                        }
1779                    }
1780                }
1781                return;
1782            }
1783
1784            match rib.kind {
1785                LifetimeRibKind::Item => break,
1786                LifetimeRibKind::ConstParamTy => {
1787                    let guar = self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1788                    self.record_lifetime_res(
1789                        lifetime.id,
1790                        LifetimeRes::Error(guar),
1791                        LifetimeElisionCandidate::Ignore,
1792                    );
1793                    return;
1794                }
1795                LifetimeRibKind::ConcreteAnonConst(cause) => {
1796                    let guar = self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1797                    self.record_lifetime_res(
1798                        lifetime.id,
1799                        LifetimeRes::Error(guar),
1800                        LifetimeElisionCandidate::Ignore,
1801                    );
1802                    return;
1803                }
1804                LifetimeRibKind::AnonymousCreateParameter { .. }
1805                | LifetimeRibKind::Elided(_)
1806                | LifetimeRibKind::Generics { .. }
1807                | LifetimeRibKind::ElisionFailure
1808                | LifetimeRibKind::AnonymousReportError
1809                | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {}
1810            }
1811        }
1812
1813        let normalized_ident = ident.normalize_to_macros_2_0();
1814        let outer_res = lifetime_rib_iter
1815            .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1816
1817        let guar = self.emit_undeclared_lifetime_error(lifetime, outer_res);
1818        self.record_lifetime_res(
1819            lifetime.id,
1820            LifetimeRes::Error(guar),
1821            LifetimeElisionCandidate::Named,
1822        );
1823    }
1824
1825    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("resolve_anonymous_lifetime",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1825u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["lifetime",
                                                    "id_for_lint", "elided"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id_for_lint)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&elided as
                                                            &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if true {
                match (&lifetime.ident.name, &kw::UnderscoreLifetime) {
                    (left_val, right_val) => {
                        if !(*left_val == *right_val) {
                            let kind = ::core::panicking::AssertKind::Eq;
                            ::core::panicking::assert_failed(kind, &*left_val,
                                &*right_val, ::core::option::Option::None);
                        }
                    }
                };
            };
            let kind =
                if elided {
                    MissingLifetimeKind::Ampersand
                } else { MissingLifetimeKind::Underscore };
            let missing_lifetime =
                MissingLifetime {
                    id: lifetime.id,
                    span: lifetime.ident.span,
                    kind,
                    count: 1,
                    id_for_lint,
                };
            let elision_candidate =
                LifetimeElisionCandidate::Missing(missing_lifetime);
            for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:1845",
                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1845u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                        ::tracing_core::field::FieldSet::new(&["rib.kind"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&rib.kind)
                                                            as &dyn Value))])
                            });
                    } else { ; }
                };
                match rib.kind {
                    LifetimeRibKind::AnonymousCreateParameter { binder, .. } =>
                        {
                        let res =
                            self.create_fresh_lifetime(lifetime.ident, binder, kind);
                        self.record_lifetime_res(lifetime.id, res,
                            elision_candidate);
                        return;
                    }
                    LifetimeRibKind::StaticIfNoLifetimeInScope {
                        lint_id: node_id, emit_lint } => {
                        let mut lifetimes_in_scope = ::alloc::vec::Vec::new();
                        for rib in self.lifetime_ribs[..i].iter().rev() {
                            lifetimes_in_scope.extend(rib.bindings.iter().map(|(ident,
                                            _)| ident.span));
                            if let LifetimeRibKind::AnonymousCreateParameter { binder,
                                        .. } = rib.kind &&
                                    let Some(extra) =
                                        self.r.extra_lifetime_params_map.get(&binder) {
                                lifetimes_in_scope.extend(extra.iter().map(|(ident, _, _)|
                                            ident.span));
                            }
                            if let LifetimeRibKind::Item = rib.kind { break; }
                        }
                        if lifetimes_in_scope.is_empty() {
                            self.record_lifetime_res(lifetime.id, LifetimeRes::Static,
                                elision_candidate);
                            return;
                        } else if emit_lint {
                            self.r.lint_buffer.buffer_lint(lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
                                node_id, lifetime.ident.span,
                                lint::BuiltinLintDiag::AssociatedConstElidedLifetime {
                                    elided,
                                    span: lifetime.ident.span,
                                    lifetimes_in_scope: lifetimes_in_scope.into(),
                                });
                        }
                    }
                    LifetimeRibKind::AnonymousReportError => {
                        let guar =
                            if elided {
                                let suggestion =
                                    self.lifetime_ribs[i..].iter().rev().find_map(|rib|
                                            {
                                                if let LifetimeRibKind::Generics {
                                                        span,
                                                        kind: LifetimeBinderKind::PolyTrait |
                                                            LifetimeBinderKind::WhereBound, .. } = rib.kind {
                                                    Some(errors::ElidedAnonymousLifetimeReportErrorSuggestion {
                                                            lo: span.shrink_to_lo(),
                                                            hi: lifetime.ident.span.shrink_to_hi(),
                                                        })
                                                } else { None }
                                            });
                                if !self.in_func_body &&
                                                    let Some((module, _)) = &self.current_trait_ref &&
                                                let Some(ty) = &self.diag_metadata.current_self_type &&
                                            Some(true) == self.diag_metadata.in_non_gat_assoc_type &&
                                        let crate::ModuleKind::Def(DefKind::Trait, trait_id, _) =
                                            module.kind {
                                    if def_id_matches_path(self.r.tcx, trait_id,
                                            &["core", "iter", "traits", "iterator", "Iterator"]) {
                                        self.r.dcx().emit_err(errors::LendingIteratorReportError {
                                                lifetime: lifetime.ident.span,
                                                ty: ty.span,
                                            })
                                    } else {
                                        let decl =
                                            if !trait_id.is_local() &&
                                                                    let Some(assoc) = self.diag_metadata.current_impl_item &&
                                                                let AssocItemKind::Type(_) = assoc.kind &&
                                                            let assocs = self.r.tcx.associated_items(trait_id) &&
                                                        let Some(ident) = assoc.kind.ident() &&
                                                    let Some(assoc) =
                                                        assocs.find_by_ident_and_kind(self.r.tcx, ident,
                                                            AssocTag::Type, trait_id) {
                                                let mut decl: MultiSpan =
                                                    self.r.tcx.def_span(assoc.def_id).into();
                                                decl.push_span_label(self.r.tcx.def_span(trait_id),
                                                    String::new());
                                                decl
                                            } else { DUMMY_SP.into() };
                                        let mut err =
                                            self.r.dcx().create_err(errors::AnonymousLifetimeNonGatReportError {
                                                    lifetime: lifetime.ident.span,
                                                    decl,
                                                });
                                        self.point_at_impl_lifetimes(&mut err, i,
                                            lifetime.ident.span);
                                        err.emit()
                                    }
                                } else {
                                    self.r.dcx().emit_err(errors::ElidedAnonymousLifetimeReportError {
                                            span: lifetime.ident.span,
                                            suggestion,
                                        })
                                }
                            } else {
                                self.r.dcx().emit_err(errors::ExplicitAnonymousLifetimeReportError {
                                        span: lifetime.ident.span,
                                    })
                            };
                        self.record_lifetime_res(lifetime.id,
                            LifetimeRes::Error(guar), elision_candidate);
                        return;
                    }
                    LifetimeRibKind::Elided(res) => {
                        self.record_lifetime_res(lifetime.id, res,
                            elision_candidate);
                        return;
                    }
                    LifetimeRibKind::ElisionFailure => {
                        self.diag_metadata.current_elision_failures.push((missing_lifetime,
                                elision_candidate, Either::Left(lifetime.id)));
                        return;
                    }
                    LifetimeRibKind::Item => break,
                    LifetimeRibKind::Generics { .. } |
                        LifetimeRibKind::ConstParamTy => {}
                    LifetimeRibKind::ConcreteAnonConst(_) => {
                        ::rustc_middle::util::bug::span_bug_fmt(lifetime.ident.span,
                            format_args!("unexpected rib kind: {0:?}", rib.kind))
                    }
                }
            }
            let guar =
                self.report_missing_lifetime_specifiers([&missing_lifetime],
                    None);
            self.record_lifetime_res(lifetime.id, LifetimeRes::Error(guar),
                elision_candidate);
        }
    }
}#[instrument(level = "debug", skip(self))]
1826    fn resolve_anonymous_lifetime(
1827        &mut self,
1828        lifetime: &Lifetime,
1829        id_for_lint: NodeId,
1830        elided: bool,
1831    ) {
1832        debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1833
1834        let kind =
1835            if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1836        let missing_lifetime = MissingLifetime {
1837            id: lifetime.id,
1838            span: lifetime.ident.span,
1839            kind,
1840            count: 1,
1841            id_for_lint,
1842        };
1843        let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1844        for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1845            debug!(?rib.kind);
1846            match rib.kind {
1847                LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1848                    let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1849                    self.record_lifetime_res(lifetime.id, res, elision_candidate);
1850                    return;
1851                }
1852                LifetimeRibKind::StaticIfNoLifetimeInScope { lint_id: node_id, emit_lint } => {
1853                    let mut lifetimes_in_scope = vec![];
1854                    for rib in self.lifetime_ribs[..i].iter().rev() {
1855                        lifetimes_in_scope.extend(rib.bindings.iter().map(|(ident, _)| ident.span));
1856                        // Consider any anonymous lifetimes, too
1857                        if let LifetimeRibKind::AnonymousCreateParameter { binder, .. } = rib.kind
1858                            && let Some(extra) = self.r.extra_lifetime_params_map.get(&binder)
1859                        {
1860                            lifetimes_in_scope.extend(extra.iter().map(|(ident, _, _)| ident.span));
1861                        }
1862                        if let LifetimeRibKind::Item = rib.kind {
1863                            break;
1864                        }
1865                    }
1866                    if lifetimes_in_scope.is_empty() {
1867                        self.record_lifetime_res(
1868                            lifetime.id,
1869                            LifetimeRes::Static,
1870                            elision_candidate,
1871                        );
1872                        return;
1873                    } else if emit_lint {
1874                        self.r.lint_buffer.buffer_lint(
1875                            lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
1876                            node_id,
1877                            lifetime.ident.span,
1878                            lint::BuiltinLintDiag::AssociatedConstElidedLifetime {
1879                                elided,
1880                                span: lifetime.ident.span,
1881                                lifetimes_in_scope: lifetimes_in_scope.into(),
1882                            },
1883                        );
1884                    }
1885                }
1886                LifetimeRibKind::AnonymousReportError => {
1887                    let guar = if elided {
1888                        let suggestion = self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1889                            if let LifetimeRibKind::Generics {
1890                                span,
1891                                kind: LifetimeBinderKind::PolyTrait | LifetimeBinderKind::WhereBound,
1892                                ..
1893                            } = rib.kind
1894                            {
1895                                Some(errors::ElidedAnonymousLifetimeReportErrorSuggestion {
1896                                    lo: span.shrink_to_lo(),
1897                                    hi: lifetime.ident.span.shrink_to_hi(),
1898                                })
1899                            } else {
1900                                None
1901                            }
1902                        });
1903                        // are we trying to use an anonymous lifetime
1904                        // on a non GAT associated trait type?
1905                        if !self.in_func_body
1906                            && let Some((module, _)) = &self.current_trait_ref
1907                            && let Some(ty) = &self.diag_metadata.current_self_type
1908                            && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1909                            && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _) = module.kind
1910                        {
1911                            if def_id_matches_path(
1912                                self.r.tcx,
1913                                trait_id,
1914                                &["core", "iter", "traits", "iterator", "Iterator"],
1915                            ) {
1916                                self.r.dcx().emit_err(errors::LendingIteratorReportError {
1917                                    lifetime: lifetime.ident.span,
1918                                    ty: ty.span,
1919                                })
1920                            } else {
1921                                let decl = if !trait_id.is_local()
1922                                    && let Some(assoc) = self.diag_metadata.current_impl_item
1923                                    && let AssocItemKind::Type(_) = assoc.kind
1924                                    && let assocs = self.r.tcx.associated_items(trait_id)
1925                                    && let Some(ident) = assoc.kind.ident()
1926                                    && let Some(assoc) = assocs.find_by_ident_and_kind(
1927                                        self.r.tcx,
1928                                        ident,
1929                                        AssocTag::Type,
1930                                        trait_id,
1931                                    ) {
1932                                    let mut decl: MultiSpan =
1933                                        self.r.tcx.def_span(assoc.def_id).into();
1934                                    decl.push_span_label(
1935                                        self.r.tcx.def_span(trait_id),
1936                                        String::new(),
1937                                    );
1938                                    decl
1939                                } else {
1940                                    DUMMY_SP.into()
1941                                };
1942                                let mut err = self.r.dcx().create_err(
1943                                    errors::AnonymousLifetimeNonGatReportError {
1944                                        lifetime: lifetime.ident.span,
1945                                        decl,
1946                                    },
1947                                );
1948                                self.point_at_impl_lifetimes(&mut err, i, lifetime.ident.span);
1949                                err.emit()
1950                            }
1951                        } else {
1952                            self.r.dcx().emit_err(errors::ElidedAnonymousLifetimeReportError {
1953                                span: lifetime.ident.span,
1954                                suggestion,
1955                            })
1956                        }
1957                    } else {
1958                        self.r.dcx().emit_err(errors::ExplicitAnonymousLifetimeReportError {
1959                            span: lifetime.ident.span,
1960                        })
1961                    };
1962                    self.record_lifetime_res(
1963                        lifetime.id,
1964                        LifetimeRes::Error(guar),
1965                        elision_candidate,
1966                    );
1967                    return;
1968                }
1969                LifetimeRibKind::Elided(res) => {
1970                    self.record_lifetime_res(lifetime.id, res, elision_candidate);
1971                    return;
1972                }
1973                LifetimeRibKind::ElisionFailure => {
1974                    self.diag_metadata.current_elision_failures.push((
1975                        missing_lifetime,
1976                        elision_candidate,
1977                        Either::Left(lifetime.id),
1978                    ));
1979                    return;
1980                }
1981                LifetimeRibKind::Item => break,
1982                LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
1983                LifetimeRibKind::ConcreteAnonConst(_) => {
1984                    // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
1985                    span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
1986                }
1987            }
1988        }
1989        let guar = self.report_missing_lifetime_specifiers([&missing_lifetime], None);
1990        self.record_lifetime_res(lifetime.id, LifetimeRes::Error(guar), elision_candidate);
1991    }
1992
1993    fn point_at_impl_lifetimes(&mut self, err: &mut Diag<'_>, i: usize, lifetime: Span) {
1994        let Some((rib, span)) =
1995            self.lifetime_ribs[..i].iter().rev().find_map(|rib| match rib.kind {
1996                LifetimeRibKind::Generics { span, kind: LifetimeBinderKind::ImplBlock, .. } => {
1997                    Some((rib, span))
1998                }
1999                _ => None,
2000            })
2001        else {
2002            return;
2003        };
2004        if !rib.bindings.is_empty() {
2005            err.span_label(
2006                span,
2007                ::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!(
2008                    "there {} named lifetime{} specified on the impl block you could use",
2009                    if rib.bindings.len() == 1 { "is a" } else { "are" },
2010                    pluralize!(rib.bindings.len()),
2011                ),
2012            );
2013            if rib.bindings.len() == 1 {
2014                err.span_suggestion_verbose(
2015                    lifetime.shrink_to_hi(),
2016                    "consider using the lifetime from the impl block",
2017                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ",
                rib.bindings.keys().next().unwrap()))
    })format!("{} ", rib.bindings.keys().next().unwrap()),
2018                    Applicability::MaybeIncorrect,
2019                );
2020            }
2021        } else {
2022            struct AnonRefFinder;
2023            impl<'ast> Visitor<'ast> for AnonRefFinder {
2024                type Result = ControlFlow<Span>;
2025
2026                fn visit_ty(&mut self, ty: &'ast ast::Ty) -> Self::Result {
2027                    if let ast::TyKind::Ref(None, mut_ty) = &ty.kind {
2028                        return ControlFlow::Break(mut_ty.ty.span.shrink_to_lo());
2029                    }
2030                    visit::walk_ty(self, ty)
2031                }
2032
2033                fn visit_lifetime(
2034                    &mut self,
2035                    lt: &'ast ast::Lifetime,
2036                    _cx: visit::LifetimeCtxt,
2037                ) -> Self::Result {
2038                    if lt.ident.name == kw::UnderscoreLifetime {
2039                        return ControlFlow::Break(lt.ident.span);
2040                    }
2041                    visit::walk_lifetime(self, lt)
2042                }
2043            }
2044
2045            if let Some(ty) = &self.diag_metadata.current_self_type
2046                && let ControlFlow::Break(sp) = AnonRefFinder.visit_ty(ty)
2047            {
2048                err.multipart_suggestion_verbose(
2049                    "add a lifetime to the impl block and use it in the self type and associated \
2050                     type",
2051                    <[_]>::into_vec(::alloc::boxed::box_new([(span, "<'a>".to_string()),
                (sp, "'a ".to_string()),
                (lifetime.shrink_to_hi(), "'a ".to_string())]))vec![
2052                        (span, "<'a>".to_string()),
2053                        (sp, "'a ".to_string()),
2054                        (lifetime.shrink_to_hi(), "'a ".to_string()),
2055                    ],
2056                    Applicability::MaybeIncorrect,
2057                );
2058            } else if let Some(item) = &self.diag_metadata.current_item
2059                && let ItemKind::Impl(impl_) = &item.kind
2060                && let Some(of_trait) = &impl_.of_trait
2061                && let ControlFlow::Break(sp) = AnonRefFinder.visit_trait_ref(&of_trait.trait_ref)
2062            {
2063                err.multipart_suggestion_verbose(
2064                    "add a lifetime to the impl block and use it in the trait and associated type",
2065                    <[_]>::into_vec(::alloc::boxed::box_new([(span, "<'a>".to_string()),
                (sp, "'a".to_string()),
                (lifetime.shrink_to_hi(), "'a ".to_string())]))vec![
2066                        (span, "<'a>".to_string()),
2067                        (sp, "'a".to_string()),
2068                        (lifetime.shrink_to_hi(), "'a ".to_string()),
2069                    ],
2070                    Applicability::MaybeIncorrect,
2071                );
2072            } else {
2073                err.span_label(
2074                    span,
2075                    "you could add a lifetime on the impl block, if the trait or the self type \
2076                     could have one",
2077                );
2078            }
2079        }
2080    }
2081
2082    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("resolve_elided_lifetime",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2082u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["anchor_id", "span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&anchor_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let id = self.r.next_node_id();
            let lt =
                Lifetime {
                    id,
                    ident: Ident::new(kw::UnderscoreLifetime, span),
                };
            self.record_lifetime_res(anchor_id,
                LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
                LifetimeElisionCandidate::Ignore);
            self.resolve_anonymous_lifetime(&lt, anchor_id, true);
        }
    }
}#[instrument(level = "debug", skip(self))]
2083    fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
2084        let id = self.r.next_node_id();
2085        let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
2086
2087        self.record_lifetime_res(
2088            anchor_id,
2089            LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
2090            LifetimeElisionCandidate::Ignore,
2091        );
2092        self.resolve_anonymous_lifetime(&lt, anchor_id, true);
2093    }
2094
2095    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("create_fresh_lifetime",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2095u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["ident", "binder",
                                                    "kind"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&binder)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: LifetimeRes = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if true {
                match (&ident.name, &kw::UnderscoreLifetime) {
                    (left_val, right_val) => {
                        if !(*left_val == *right_val) {
                            let kind = ::core::panicking::AssertKind::Eq;
                            ::core::panicking::assert_failed(kind, &*left_val,
                                &*right_val, ::core::option::Option::None);
                        }
                    }
                };
            };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2103",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2103u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["ident.span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&ident.span)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let param = self.r.next_node_id();
            let res = LifetimeRes::Fresh { param, binder, kind };
            self.record_lifetime_param(param, res);
            self.r.extra_lifetime_params_map.entry(binder).or_insert_with(Vec::new).push((ident,
                    param, res));
            res
        }
    }
}#[instrument(level = "debug", skip(self))]
2096    fn create_fresh_lifetime(
2097        &mut self,
2098        ident: Ident,
2099        binder: NodeId,
2100        kind: MissingLifetimeKind,
2101    ) -> LifetimeRes {
2102        debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
2103        debug!(?ident.span);
2104
2105        // Leave the responsibility to create the `LocalDefId` to lowering.
2106        let param = self.r.next_node_id();
2107        let res = LifetimeRes::Fresh { param, binder, kind };
2108        self.record_lifetime_param(param, res);
2109
2110        // Record the created lifetime parameter so lowering can pick it up and add it to HIR.
2111        self.r
2112            .extra_lifetime_params_map
2113            .entry(binder)
2114            .or_insert_with(Vec::new)
2115            .push((ident, param, res));
2116        res
2117    }
2118
2119    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("resolve_elided_lifetimes_in_path",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2119u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["partial_res",
                                                    "path", "source", "path_span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&partial_res)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path_span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let proj_start = path.len() - partial_res.unresolved_segments();
            for (i, segment) in path.iter().enumerate() {
                if segment.has_lifetime_args { continue; }
                let Some(segment_id) = segment.id else { continue; };
                let type_def_id =
                    match partial_res.base_res() {
                        Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start =>
                            {
                            self.r.tcx.parent(def_id)
                        }
                        Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start =>
                            {
                            self.r.tcx.parent(def_id)
                        }
                        Res::Def(DefKind::Struct, def_id) |
                            Res::Def(DefKind::Union, def_id) |
                            Res::Def(DefKind::Enum, def_id) |
                            Res::Def(DefKind::TyAlias, def_id) |
                            Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start => {
                            def_id
                        }
                        _ => continue,
                    };
                let expected_lifetimes =
                    self.r.item_generics_num_lifetimes(type_def_id);
                if expected_lifetimes == 0 { continue; }
                let node_ids = self.r.next_node_ids(expected_lifetimes);
                self.record_lifetime_res(segment_id,
                    LifetimeRes::ElidedAnchor {
                        start: node_ids.start,
                        end: node_ids.end,
                    }, LifetimeElisionCandidate::Ignore);
                let inferred =
                    match source {
                        PathSource::Trait(..) | PathSource::TraitItem(..) |
                            PathSource::Type | PathSource::PreciseCapturingArg(..) |
                            PathSource::ReturnTypeNotation | PathSource::Macro => false,
                        PathSource::Expr(..) | PathSource::Pat |
                            PathSource::Struct(_) | PathSource::TupleStruct(..) |
                            PathSource::DefineOpaques | PathSource::Delegation => true,
                    };
                if inferred {
                    for id in node_ids {
                        self.record_lifetime_res(id, LifetimeRes::Infer,
                            LifetimeElisionCandidate::Named);
                    }
                    continue;
                }
                let elided_lifetime_span =
                    if segment.has_generic_args {
                        segment.args_span.with_hi(segment.args_span.lo() +
                                BytePos(1))
                    } else {
                        segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
                    };
                let ident =
                    Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
                let kind =
                    if segment.has_generic_args {
                        MissingLifetimeKind::Comma
                    } else { MissingLifetimeKind::Brackets };
                let missing_lifetime =
                    MissingLifetime {
                        id: node_ids.start,
                        id_for_lint: segment_id,
                        span: elided_lifetime_span,
                        kind,
                        count: expected_lifetimes,
                    };
                let mut should_lint = true;
                for rib in self.lifetime_ribs.iter().rev() {
                    match rib.kind {
                        LifetimeRibKind::AnonymousCreateParameter {
                            report_in_path: true, .. } |
                            LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {
                            let sess = self.r.tcx.sess;
                            let subdiag =
                                rustc_errors::elided_lifetime_in_path_suggestion(sess.source_map(),
                                    expected_lifetimes, path_span, !segment.has_generic_args,
                                    elided_lifetime_span);
                            let guar =
                                self.r.dcx().emit_err(errors::ImplicitElidedLifetimeNotAllowedHere {
                                        span: path_span,
                                        subdiag,
                                    });
                            should_lint = false;
                            for id in node_ids {
                                self.record_lifetime_res(id, LifetimeRes::Error(guar),
                                    LifetimeElisionCandidate::Named);
                            }
                            break;
                        }
                        LifetimeRibKind::AnonymousCreateParameter { binder, .. } =>
                            {
                            let mut candidate =
                                LifetimeElisionCandidate::Missing(missing_lifetime);
                            for id in node_ids {
                                let res = self.create_fresh_lifetime(ident, binder, kind);
                                self.record_lifetime_res(id, res,
                                    replace(&mut candidate, LifetimeElisionCandidate::Named));
                            }
                            break;
                        }
                        LifetimeRibKind::Elided(res) => {
                            let mut candidate =
                                LifetimeElisionCandidate::Missing(missing_lifetime);
                            for id in node_ids {
                                self.record_lifetime_res(id, res,
                                    replace(&mut candidate, LifetimeElisionCandidate::Ignore));
                            }
                            break;
                        }
                        LifetimeRibKind::ElisionFailure => {
                            self.diag_metadata.current_elision_failures.push((missing_lifetime,
                                    LifetimeElisionCandidate::Ignore, Either::Right(node_ids)));
                            break;
                        }
                        LifetimeRibKind::AnonymousReportError |
                            LifetimeRibKind::Item => {
                            let guar =
                                self.report_missing_lifetime_specifiers([&missing_lifetime],
                                    None);
                            for id in node_ids {
                                self.record_lifetime_res(id, LifetimeRes::Error(guar),
                                    LifetimeElisionCandidate::Ignore);
                            }
                            break;
                        }
                        LifetimeRibKind::Generics { .. } |
                            LifetimeRibKind::ConstParamTy => {}
                        LifetimeRibKind::ConcreteAnonConst(_) => {
                            ::rustc_middle::util::bug::span_bug_fmt(elided_lifetime_span,
                                format_args!("unexpected rib kind: {0:?}", rib.kind))
                        }
                    }
                }
                if should_lint {
                    self.r.lint_buffer.buffer_lint(lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
                        segment_id, elided_lifetime_span,
                        lint::BuiltinLintDiag::ElidedLifetimesInPaths(expected_lifetimes,
                            path_span, !segment.has_generic_args,
                            elided_lifetime_span));
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2120    fn resolve_elided_lifetimes_in_path(
2121        &mut self,
2122        partial_res: PartialRes,
2123        path: &[Segment],
2124        source: PathSource<'_, 'ast, 'ra>,
2125        path_span: Span,
2126    ) {
2127        let proj_start = path.len() - partial_res.unresolved_segments();
2128        for (i, segment) in path.iter().enumerate() {
2129            if segment.has_lifetime_args {
2130                continue;
2131            }
2132            let Some(segment_id) = segment.id else {
2133                continue;
2134            };
2135
2136            // Figure out if this is a type/trait segment,
2137            // which may need lifetime elision performed.
2138            let type_def_id = match partial_res.base_res() {
2139                Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2140                    self.r.tcx.parent(def_id)
2141                }
2142                Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => {
2143                    self.r.tcx.parent(def_id)
2144                }
2145                Res::Def(DefKind::Struct, def_id)
2146                | Res::Def(DefKind::Union, def_id)
2147                | Res::Def(DefKind::Enum, def_id)
2148                | Res::Def(DefKind::TyAlias, def_id)
2149                | Res::Def(DefKind::Trait, def_id)
2150                    if i + 1 == proj_start =>
2151                {
2152                    def_id
2153                }
2154                _ => continue,
2155            };
2156
2157            let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2158            if expected_lifetimes == 0 {
2159                continue;
2160            }
2161
2162            let node_ids = self.r.next_node_ids(expected_lifetimes);
2163            self.record_lifetime_res(
2164                segment_id,
2165                LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2166                LifetimeElisionCandidate::Ignore,
2167            );
2168
2169            let inferred = match source {
2170                PathSource::Trait(..)
2171                | PathSource::TraitItem(..)
2172                | PathSource::Type
2173                | PathSource::PreciseCapturingArg(..)
2174                | PathSource::ReturnTypeNotation
2175                | PathSource::Macro => false,
2176                PathSource::Expr(..)
2177                | PathSource::Pat
2178                | PathSource::Struct(_)
2179                | PathSource::TupleStruct(..)
2180                | PathSource::DefineOpaques
2181                | PathSource::Delegation => true,
2182            };
2183            if inferred {
2184                // Do not create a parameter for patterns and expressions: type checking can infer
2185                // the appropriate lifetime for us.
2186                for id in node_ids {
2187                    self.record_lifetime_res(
2188                        id,
2189                        LifetimeRes::Infer,
2190                        LifetimeElisionCandidate::Named,
2191                    );
2192                }
2193                continue;
2194            }
2195
2196            let elided_lifetime_span = if segment.has_generic_args {
2197                // If there are brackets, but not generic arguments, then use the opening bracket
2198                segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2199            } else {
2200                // If there are no brackets, use the identifier span.
2201                // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
2202                // originating from macros, since the segment's span might be from a macro arg.
2203                segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2204            };
2205            let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2206
2207            let kind = if segment.has_generic_args {
2208                MissingLifetimeKind::Comma
2209            } else {
2210                MissingLifetimeKind::Brackets
2211            };
2212            let missing_lifetime = MissingLifetime {
2213                id: node_ids.start,
2214                id_for_lint: segment_id,
2215                span: elided_lifetime_span,
2216                kind,
2217                count: expected_lifetimes,
2218            };
2219            let mut should_lint = true;
2220            for rib in self.lifetime_ribs.iter().rev() {
2221                match rib.kind {
2222                    // In create-parameter mode we error here because we don't want to support
2223                    // deprecated impl elision in new features like impl elision and `async fn`,
2224                    // both of which work using the `CreateParameter` mode:
2225                    //
2226                    //     impl Foo for std::cell::Ref<u32> // note lack of '_
2227                    //     async fn foo(_: std::cell::Ref<u32>) { ... }
2228                    LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2229                    | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {
2230                        let sess = self.r.tcx.sess;
2231                        let subdiag = rustc_errors::elided_lifetime_in_path_suggestion(
2232                            sess.source_map(),
2233                            expected_lifetimes,
2234                            path_span,
2235                            !segment.has_generic_args,
2236                            elided_lifetime_span,
2237                        );
2238                        let guar =
2239                            self.r.dcx().emit_err(errors::ImplicitElidedLifetimeNotAllowedHere {
2240                                span: path_span,
2241                                subdiag,
2242                            });
2243                        should_lint = false;
2244
2245                        for id in node_ids {
2246                            self.record_lifetime_res(
2247                                id,
2248                                LifetimeRes::Error(guar),
2249                                LifetimeElisionCandidate::Named,
2250                            );
2251                        }
2252                        break;
2253                    }
2254                    // Do not create a parameter for patterns and expressions.
2255                    LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2256                        // Group all suggestions into the first record.
2257                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2258                        for id in node_ids {
2259                            let res = self.create_fresh_lifetime(ident, binder, kind);
2260                            self.record_lifetime_res(
2261                                id,
2262                                res,
2263                                replace(&mut candidate, LifetimeElisionCandidate::Named),
2264                            );
2265                        }
2266                        break;
2267                    }
2268                    LifetimeRibKind::Elided(res) => {
2269                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2270                        for id in node_ids {
2271                            self.record_lifetime_res(
2272                                id,
2273                                res,
2274                                replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2275                            );
2276                        }
2277                        break;
2278                    }
2279                    LifetimeRibKind::ElisionFailure => {
2280                        self.diag_metadata.current_elision_failures.push((
2281                            missing_lifetime,
2282                            LifetimeElisionCandidate::Ignore,
2283                            Either::Right(node_ids),
2284                        ));
2285                        break;
2286                    }
2287                    // `LifetimeRes::Error`, which would usually be used in the case of
2288                    // `ReportError`, is unsuitable here, as we don't emit an error yet. Instead,
2289                    // we simply resolve to an implicit lifetime, which will be checked later, at
2290                    // which point a suitable error will be emitted.
2291                    LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2292                        let guar =
2293                            self.report_missing_lifetime_specifiers([&missing_lifetime], None);
2294                        for id in node_ids {
2295                            self.record_lifetime_res(
2296                                id,
2297                                LifetimeRes::Error(guar),
2298                                LifetimeElisionCandidate::Ignore,
2299                            );
2300                        }
2301                        break;
2302                    }
2303                    LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
2304                    LifetimeRibKind::ConcreteAnonConst(_) => {
2305                        // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
2306                        span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2307                    }
2308                }
2309            }
2310
2311            if should_lint {
2312                self.r.lint_buffer.buffer_lint(
2313                    lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2314                    segment_id,
2315                    elided_lifetime_span,
2316                    lint::BuiltinLintDiag::ElidedLifetimesInPaths(
2317                        expected_lifetimes,
2318                        path_span,
2319                        !segment.has_generic_args,
2320                        elided_lifetime_span,
2321                    ),
2322                );
2323            }
2324        }
2325    }
2326
2327    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("record_lifetime_res",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2327u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["id", "res",
                                                    "candidate"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidate)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
                {
                    ::core::panicking::panic_fmt(format_args!("lifetime {0:?} resolved multiple times ({1:?} before, {2:?} now)",
                            id, prev_res, res));
                }
            }
            match res {
                LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } |
                    LifetimeRes::Static { .. } => {
                    if let Some(ref mut candidates) =
                            self.lifetime_elision_candidates {
                        candidates.push((res, candidate));
                    }
                }
                LifetimeRes::Infer | LifetimeRes::Error(..) |
                    LifetimeRes::ElidedAnchor { .. } => {}
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2328    fn record_lifetime_res(
2329        &mut self,
2330        id: NodeId,
2331        res: LifetimeRes,
2332        candidate: LifetimeElisionCandidate,
2333    ) {
2334        if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2335            panic!("lifetime {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)")
2336        }
2337
2338        match res {
2339            LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2340                if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2341                    candidates.push((res, candidate));
2342                }
2343            }
2344            LifetimeRes::Infer | LifetimeRes::Error(..) | LifetimeRes::ElidedAnchor { .. } => {}
2345        }
2346    }
2347
2348    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("record_lifetime_param",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2348u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["id", "res"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
                {
                    ::core::panicking::panic_fmt(format_args!("lifetime parameter {0:?} resolved multiple times ({1:?} before, {2:?} now)",
                            id, prev_res, res));
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2349    fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
2350        if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2351            panic!(
2352                "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2353            )
2354        }
2355    }
2356
2357    /// Perform resolution of a function signature, accounting for lifetime elision.
2358    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("resolve_fn_signature",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2358u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["fn_id", "has_self",
                                                    "output_ty", "report_elided_lifetimes_in_path"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&has_self as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&output_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&report_elided_lifetimes_in_path
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let rib =
                LifetimeRibKind::AnonymousCreateParameter {
                    binder: fn_id,
                    report_in_path: report_elided_lifetimes_in_path,
                };
            self.with_lifetime_rib(rib,
                |this|
                    {
                        let elision_lifetime =
                            this.resolve_fn_params(has_self, inputs);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2374",
                                                "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                ::tracing_core::__macro_support::Option::Some(2374u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                                ::tracing_core::field::FieldSet::new(&["elision_lifetime"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&elision_lifetime)
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        let outer_failures =
                            take(&mut this.diag_metadata.current_elision_failures);
                        let output_rib =
                            if let Ok(res) = elision_lifetime.as_ref() {
                                this.r.lifetime_elision_allowed.insert(fn_id);
                                LifetimeRibKind::Elided(*res)
                            } else { LifetimeRibKind::ElisionFailure };
                        this.with_lifetime_rib(output_rib,
                            |this| visit::walk_fn_ret_ty(this, output_ty));
                        let elision_failures =
                            replace(&mut this.diag_metadata.current_elision_failures,
                                outer_failures);
                        if !elision_failures.is_empty() {
                            let Err(failure_info) =
                                elision_lifetime else {
                                    ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
                                };
                            let guar =
                                this.report_missing_lifetime_specifiers(elision_failures.iter().map(|(missing_lifetime,
                                                ..)| missing_lifetime), Some(failure_info));
                            let mut record_res =
                                |lifetime, candidate|
                                    {
                                        this.record_lifetime_res(lifetime, LifetimeRes::Error(guar),
                                            candidate)
                                    };
                            for (_, candidate, nodes) in elision_failures {
                                match nodes {
                                    Either::Left(node_id) => record_res(node_id, candidate),
                                    Either::Right(node_ids) => {
                                        for lifetime in node_ids { record_res(lifetime, candidate) }
                                    }
                                }
                            }
                        }
                    });
        }
    }
}#[instrument(level = "debug", skip(self, inputs))]
2359    fn resolve_fn_signature(
2360        &mut self,
2361        fn_id: NodeId,
2362        has_self: bool,
2363        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2364        output_ty: &'ast FnRetTy,
2365        report_elided_lifetimes_in_path: bool,
2366    ) {
2367        let rib = LifetimeRibKind::AnonymousCreateParameter {
2368            binder: fn_id,
2369            report_in_path: report_elided_lifetimes_in_path,
2370        };
2371        self.with_lifetime_rib(rib, |this| {
2372            // Add each argument to the rib.
2373            let elision_lifetime = this.resolve_fn_params(has_self, inputs);
2374            debug!(?elision_lifetime);
2375
2376            let outer_failures = take(&mut this.diag_metadata.current_elision_failures);
2377            let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2378                this.r.lifetime_elision_allowed.insert(fn_id);
2379                LifetimeRibKind::Elided(*res)
2380            } else {
2381                LifetimeRibKind::ElisionFailure
2382            };
2383            this.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2384            let elision_failures =
2385                replace(&mut this.diag_metadata.current_elision_failures, outer_failures);
2386            if !elision_failures.is_empty() {
2387                let Err(failure_info) = elision_lifetime else { bug!() };
2388                let guar = this.report_missing_lifetime_specifiers(
2389                    elision_failures.iter().map(|(missing_lifetime, ..)| missing_lifetime),
2390                    Some(failure_info),
2391                );
2392                let mut record_res = |lifetime, candidate| {
2393                    this.record_lifetime_res(lifetime, LifetimeRes::Error(guar), candidate)
2394                };
2395                for (_, candidate, nodes) in elision_failures {
2396                    match nodes {
2397                        Either::Left(node_id) => record_res(node_id, candidate),
2398                        Either::Right(node_ids) => {
2399                            for lifetime in node_ids {
2400                                record_res(lifetime, candidate)
2401                            }
2402                        }
2403                    }
2404                }
2405            }
2406        });
2407    }
2408
2409    /// Resolve inside function parameters and parameter types.
2410    /// Returns the lifetime for elision in fn return type,
2411    /// or diagnostic information in case of elision failure.
2412    fn resolve_fn_params(
2413        &mut self,
2414        has_self: bool,
2415        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2416    ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2417        enum Elision {
2418            /// We have not found any candidate.
2419            None,
2420            /// We have a candidate bound to `self`.
2421            Self_(LifetimeRes),
2422            /// We have a candidate bound to a parameter.
2423            Param(LifetimeRes),
2424            /// We failed elision.
2425            Err,
2426        }
2427
2428        // Save elision state to reinstate it later.
2429        let outer_candidates = self.lifetime_elision_candidates.take();
2430
2431        // Result of elision.
2432        let mut elision_lifetime = Elision::None;
2433        // Information for diagnostics.
2434        let mut parameter_info = Vec::new();
2435        let mut all_candidates = Vec::new();
2436
2437        // Resolve and apply bindings first so diagnostics can see if they're used in types.
2438        let mut bindings = {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push((PatBoundCtx::Product, Default::default()));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(<[_]>::into_vec(::alloc::boxed::box_new([(PatBoundCtx::Product,
                                Default::default())])))
    }
}smallvec![(PatBoundCtx::Product, Default::default())];
2439        for (pat, _) in inputs.clone() {
2440            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2440",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2440u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolving bindings in pat = {0:?}",
                                                    pat) as &dyn Value))])
            });
    } else { ; }
};debug!("resolving bindings in pat = {pat:?}");
2441            self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2442                if let Some(pat) = pat {
2443                    this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2444                }
2445            });
2446        }
2447        self.apply_pattern_bindings(bindings);
2448
2449        for (index, (pat, ty)) in inputs.enumerate() {
2450            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2450",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2450u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolving type for pat = {0:?}, ty = {1:?}",
                                                    pat, ty) as &dyn Value))])
            });
    } else { ; }
};debug!("resolving type for pat = {pat:?}, ty = {ty:?}");
2451            // Record elision candidates only for this parameter.
2452            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);
2453            self.lifetime_elision_candidates = Some(Default::default());
2454            self.visit_ty(ty);
2455            let local_candidates = self.lifetime_elision_candidates.take();
2456
2457            if let Some(candidates) = local_candidates {
2458                let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2459                let lifetime_count = distinct.len();
2460                if lifetime_count != 0 {
2461                    parameter_info.push(ElisionFnParameter {
2462                        index,
2463                        ident: if let Some(pat) = pat
2464                            && let PatKind::Ident(_, ident, _) = pat.kind
2465                        {
2466                            Some(ident)
2467                        } else {
2468                            None
2469                        },
2470                        lifetime_count,
2471                        span: ty.span,
2472                    });
2473                    all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2474                        match candidate {
2475                            LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {
2476                                None
2477                            }
2478                            LifetimeElisionCandidate::Missing(missing) => Some(missing),
2479                        }
2480                    }));
2481                }
2482                if !distinct.is_empty() {
2483                    match elision_lifetime {
2484                        // We are the first parameter to bind lifetimes.
2485                        Elision::None => {
2486                            if let Some(res) = distinct.get_only() {
2487                                // We have a single lifetime => success.
2488                                elision_lifetime = Elision::Param(*res)
2489                            } else {
2490                                // We have multiple lifetimes => error.
2491                                elision_lifetime = Elision::Err;
2492                            }
2493                        }
2494                        // We have 2 parameters that bind lifetimes => error.
2495                        Elision::Param(_) => elision_lifetime = Elision::Err,
2496                        // `self` elision takes precedence over everything else.
2497                        Elision::Self_(_) | Elision::Err => {}
2498                    }
2499                }
2500            }
2501
2502            // Handle `self` specially.
2503            if index == 0 && has_self {
2504                let self_lifetime = self.find_lifetime_for_self(ty);
2505                elision_lifetime = match self_lifetime {
2506                    // We found `self` elision.
2507                    Set1::One(lifetime) => Elision::Self_(lifetime),
2508                    // `self` itself had ambiguous lifetimes, e.g.
2509                    // &Box<&Self>. In this case we won't consider
2510                    // taking an alternative parameter lifetime; just avoid elision
2511                    // entirely.
2512                    Set1::Many => Elision::Err,
2513                    // We do not have `self` elision: disregard the `Elision::Param` that we may
2514                    // have found.
2515                    Set1::Empty => Elision::None,
2516                }
2517            }
2518            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2518",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2518u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("(resolving function / closure) recorded parameter")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("(resolving function / closure) recorded parameter");
2519        }
2520
2521        // Reinstate elision state.
2522        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);
2523        self.lifetime_elision_candidates = outer_candidates;
2524
2525        if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2526            return Ok(res);
2527        }
2528
2529        // We do not have a candidate.
2530        Err((all_candidates, parameter_info))
2531    }
2532
2533    /// List all the lifetimes that appear in the provided type.
2534    fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2535        /// Visits a type to find all the &references, and determines the
2536        /// set of lifetimes for all of those references where the referent
2537        /// contains Self.
2538        struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2539            r: &'a Resolver<'ra, 'tcx>,
2540            impl_self: Option<Res>,
2541            lifetime: Set1<LifetimeRes>,
2542        }
2543
2544        impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2545            fn visit_ty(&mut self, ty: &'ra Ty) {
2546                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2546",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2546u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("FindReferenceVisitor considering ty={0:?}",
                                                    ty) as &dyn Value))])
            });
    } else { ; }
};trace!("FindReferenceVisitor considering ty={:?}", ty);
2547                if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2548                    // See if anything inside the &thing contains Self
2549                    let mut visitor =
2550                        SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2551                    visitor.visit_ty(ty);
2552                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2552",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2552u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("FindReferenceVisitor: SelfVisitor self_found={0:?}",
                                                    visitor.self_found) as &dyn Value))])
            });
    } else { ; }
};trace!("FindReferenceVisitor: SelfVisitor self_found={:?}", visitor.self_found);
2553                    if visitor.self_found {
2554                        let lt_id = if let Some(lt) = lt {
2555                            lt.id
2556                        } else {
2557                            let res = self.r.lifetimes_res_map[&ty.id];
2558                            let LifetimeRes::ElidedAnchor { start, .. } = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2559                            start
2560                        };
2561                        let lt_res = self.r.lifetimes_res_map[&lt_id];
2562                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2562",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2562u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("FindReferenceVisitor inserting res={0:?}",
                                                    lt_res) as &dyn Value))])
            });
    } else { ; }
};trace!("FindReferenceVisitor inserting res={:?}", lt_res);
2563                        self.lifetime.insert(lt_res);
2564                    }
2565                }
2566                visit::walk_ty(self, ty)
2567            }
2568
2569            // A type may have an expression as a const generic argument.
2570            // We do not want to recurse into those.
2571            fn visit_expr(&mut self, _: &'ra Expr) {}
2572        }
2573
2574        /// Visitor which checks the referent of a &Thing to see if the
2575        /// Thing contains Self
2576        struct SelfVisitor<'a, 'ra, 'tcx> {
2577            r: &'a Resolver<'ra, 'tcx>,
2578            impl_self: Option<Res>,
2579            self_found: bool,
2580        }
2581
2582        impl SelfVisitor<'_, '_, '_> {
2583            // Look for `self: &'a Self` - also desugared from `&'a self`
2584            fn is_self_ty(&self, ty: &Ty) -> bool {
2585                match ty.kind {
2586                    TyKind::ImplicitSelf => true,
2587                    TyKind::Path(None, _) => {
2588                        let path_res = self.r.partial_res_map[&ty.id].full_res();
2589                        if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2590                            return true;
2591                        }
2592                        self.impl_self.is_some() && path_res == self.impl_self
2593                    }
2594                    _ => false,
2595                }
2596            }
2597        }
2598
2599        impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2600            fn visit_ty(&mut self, ty: &'ra Ty) {
2601                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2601",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2601u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("SelfVisitor considering ty={0:?}",
                                                    ty) as &dyn Value))])
            });
    } else { ; }
};trace!("SelfVisitor considering ty={:?}", ty);
2602                if self.is_self_ty(ty) {
2603                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2603",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2603u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("SelfVisitor found Self")
                                            as &dyn Value))])
            });
    } else { ; }
};trace!("SelfVisitor found Self");
2604                    self.self_found = true;
2605                }
2606                visit::walk_ty(self, ty)
2607            }
2608
2609            // A type may have an expression as a const generic argument.
2610            // We do not want to recurse into those.
2611            fn visit_expr(&mut self, _: &'ra Expr) {}
2612        }
2613
2614        let impl_self = self
2615            .diag_metadata
2616            .current_self_type
2617            .as_ref()
2618            .and_then(|ty| {
2619                if let TyKind::Path(None, _) = ty.kind {
2620                    self.r.partial_res_map.get(&ty.id)
2621                } else {
2622                    None
2623                }
2624            })
2625            .and_then(|res| res.full_res())
2626            .filter(|res| {
2627                // Permit the types that unambiguously always
2628                // result in the same type constructor being used
2629                // (it can't differ between `Self` and `self`).
2630                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _) |
        Res::PrimTy(_) => true,
    _ => false,
}matches!(
2631                    res,
2632                    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2633                )
2634            });
2635        let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2636        visitor.visit_ty(ty);
2637        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2637",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2637u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("FindReferenceVisitor found={0:?}",
                                                    visitor.lifetime) as &dyn Value))])
            });
    } else { ; }
};trace!("FindReferenceVisitor found={:?}", visitor.lifetime);
2638        visitor.lifetime
2639    }
2640
2641    /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
2642    /// label and reports an error if the label is not found or is unreachable.
2643    fn resolve_label(&self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2644        let mut suggestion = None;
2645
2646        for i in (0..self.label_ribs.len()).rev() {
2647            let rib = &self.label_ribs[i];
2648
2649            if let RibKind::MacroDefinition(def) = rib.kind
2650                // If an invocation of this macro created `ident`, give up on `ident`
2651                // and switch to `ident`'s source from the macro definition.
2652                && def == self.r.macro_def(label.span.ctxt())
2653            {
2654                label.span.remove_mark();
2655            }
2656
2657            let ident = label.normalize_to_macro_rules();
2658            if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2659                let definition_span = ident.span;
2660                return if self.is_label_valid_from_rib(i) {
2661                    Ok((*id, definition_span))
2662                } else {
2663                    Err(ResolutionError::UnreachableLabel {
2664                        name: label.name,
2665                        definition_span,
2666                        suggestion,
2667                    })
2668                };
2669            }
2670
2671            // Diagnostics: Check if this rib contains a label with a similar name, keep track of
2672            // the first such label that is encountered.
2673            suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2674        }
2675
2676        Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2677    }
2678
2679    /// Determine whether or not a label from the `rib_index`th label rib is reachable.
2680    fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2681        let ribs = &self.label_ribs[rib_index + 1..];
2682        ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2683    }
2684
2685    fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2686        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2686",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2686u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_adt")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_adt");
2687        let kind = self.r.local_def_kind(item.id);
2688        self.with_current_self_item(item, |this| {
2689            this.with_generic_param_rib(
2690                &generics.params,
2691                RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2692                item.id,
2693                LifetimeBinderKind::Item,
2694                generics.span,
2695                |this| {
2696                    let item_def_id = this.r.local_def_id(item.id).to_def_id();
2697                    this.with_self_rib(
2698                        Res::SelfTyAlias { alias_to: item_def_id, is_trait_impl: false },
2699                        |this| {
2700                            visit::walk_item(this, item);
2701                        },
2702                    );
2703                },
2704            );
2705        });
2706    }
2707
2708    fn future_proof_import(&mut self, use_tree: &UseTree) {
2709        if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2710            let ident = segment.ident;
2711            if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2712                return;
2713            }
2714
2715            let nss = match use_tree.kind {
2716                UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2717                _ => &[TypeNS],
2718            };
2719            let report_error = |this: &Self, ns| {
2720                if this.should_report_errs() {
2721                    let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2722                    this.r.dcx().emit_err(errors::ImportsCannotReferTo { span: ident.span, what });
2723                }
2724            };
2725
2726            for &ns in nss {
2727                match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2728                    Some(LateDecl::RibDef(..)) => {
2729                        report_error(self, ns);
2730                    }
2731                    Some(LateDecl::Decl(binding)) => {
2732                        if let Some(LateDecl::RibDef(..)) =
2733                            self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2734                        {
2735                            report_error(self, ns);
2736                        }
2737                    }
2738                    None => {}
2739                }
2740            }
2741        } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2742            for (use_tree, _) in items {
2743                self.future_proof_import(use_tree);
2744            }
2745        }
2746    }
2747
2748    fn resolve_item(&mut self, item: &'ast Item) {
2749        let mod_inner_docs =
2750            #[allow(non_exhaustive_omitted_patterns)] match item.kind {
    ItemKind::Mod(..) => true,
    _ => false,
}matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2751        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(..)) {
2752            self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2753        }
2754
2755        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2755",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2755u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("(resolving item) resolving {0:?} ({1:?})",
                                                    item.kind.ident(), item.kind) as &dyn Value))])
            });
    } else { ; }
};debug!("(resolving item) resolving {:?} ({:?})", item.kind.ident(), item.kind);
2756
2757        let def_kind = self.r.local_def_kind(item.id);
2758        match &item.kind {
2759            ItemKind::TyAlias(box TyAlias { generics, .. }) => {
2760                self.with_generic_param_rib(
2761                    &generics.params,
2762                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2763                    item.id,
2764                    LifetimeBinderKind::Item,
2765                    generics.span,
2766                    |this| visit::walk_item(this, item),
2767                );
2768            }
2769
2770            ItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
2771                self.with_generic_param_rib(
2772                    &generics.params,
2773                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2774                    item.id,
2775                    LifetimeBinderKind::Function,
2776                    generics.span,
2777                    |this| visit::walk_item(this, item),
2778                );
2779                self.resolve_define_opaques(define_opaque);
2780            }
2781
2782            ItemKind::Enum(_, generics, _)
2783            | ItemKind::Struct(_, generics, _)
2784            | ItemKind::Union(_, generics, _) => {
2785                self.resolve_adt(item, generics);
2786            }
2787
2788            ItemKind::Impl(Impl { generics, of_trait, self_ty, items: impl_items, .. }) => {
2789                self.diag_metadata.current_impl_items = Some(impl_items);
2790                self.resolve_implementation(
2791                    &item.attrs,
2792                    generics,
2793                    of_trait.as_deref(),
2794                    self_ty,
2795                    item.id,
2796                    impl_items,
2797                );
2798                self.diag_metadata.current_impl_items = None;
2799            }
2800
2801            ItemKind::Trait(box Trait { generics, bounds, items, .. }) => {
2802                // Create a new rib for the trait-wide type parameters.
2803                self.with_generic_param_rib(
2804                    &generics.params,
2805                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2806                    item.id,
2807                    LifetimeBinderKind::Item,
2808                    generics.span,
2809                    |this| {
2810                        let local_def_id = this.r.local_def_id(item.id).to_def_id();
2811                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2812                            this.visit_generics(generics);
2813                            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);
2814                            this.resolve_trait_items(items);
2815                        });
2816                    },
2817                );
2818            }
2819
2820            ItemKind::TraitAlias(box TraitAlias { generics, bounds, .. }) => {
2821                // Create a new rib for the trait-wide type parameters.
2822                self.with_generic_param_rib(
2823                    &generics.params,
2824                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2825                    item.id,
2826                    LifetimeBinderKind::Item,
2827                    generics.span,
2828                    |this| {
2829                        let local_def_id = this.r.local_def_id(item.id).to_def_id();
2830                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2831                            this.visit_generics(generics);
2832                            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);
2833                        });
2834                    },
2835                );
2836            }
2837
2838            ItemKind::Mod(..) => {
2839                let module = self.r.expect_module(self.r.local_def_id(item.id).to_def_id());
2840                let orig_module = replace(&mut self.parent_scope.module, module);
2841                self.with_rib(ValueNS, RibKind::Module(module), |this| {
2842                    this.with_rib(TypeNS, RibKind::Module(module), |this| {
2843                        if mod_inner_docs {
2844                            this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2845                        }
2846                        let old_macro_rules = this.parent_scope.macro_rules;
2847                        visit::walk_item(this, item);
2848                        // Maintain macro_rules scopes in the same way as during early resolution
2849                        // for diagnostics and doc links.
2850                        if item.attrs.iter().all(|attr| {
2851                            !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2852                        }) {
2853                            this.parent_scope.macro_rules = old_macro_rules;
2854                        }
2855                    })
2856                });
2857                self.parent_scope.module = orig_module;
2858            }
2859
2860            ItemKind::Static(box ast::StaticItem { ident, ty, expr, define_opaque, .. }) => {
2861                self.with_static_rib(def_kind, |this| {
2862                    this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2863                        this.visit_ty(ty);
2864                    });
2865                    if let Some(expr) = expr {
2866                        // We already forbid generic params because of the above item rib,
2867                        // so it doesn't matter whether this is a trivial constant.
2868                        this.resolve_static_body(expr, Some((*ident, ConstantItemKind::Static)));
2869                    }
2870                });
2871                self.resolve_define_opaques(define_opaque);
2872            }
2873
2874            ItemKind::Const(box ast::ConstItem {
2875                ident,
2876                generics,
2877                ty,
2878                rhs_kind,
2879                define_opaque,
2880                defaultness: _,
2881            }) => {
2882                self.with_generic_param_rib(
2883                    &generics.params,
2884                    RibKind::Item(
2885                        if self.r.tcx.features().generic_const_items() {
2886                            HasGenericParams::Yes(generics.span)
2887                        } else {
2888                            HasGenericParams::No
2889                        },
2890                        def_kind,
2891                    ),
2892                    item.id,
2893                    LifetimeBinderKind::ConstItem,
2894                    generics.span,
2895                    |this| {
2896                        this.visit_generics(generics);
2897
2898                        this.with_lifetime_rib(
2899                            LifetimeRibKind::Elided(LifetimeRes::Static),
2900                            |this| {
2901                                if rhs_kind.is_type_const()
2902                                    && !this.r.tcx.features().generic_const_parameter_types()
2903                                {
2904                                    this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
2905                                        this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
2906                                            this.with_lifetime_rib(
2907                                                LifetimeRibKind::ConstParamTy,
2908                                                |this| this.visit_ty(ty),
2909                                            )
2910                                        })
2911                                    });
2912                                } else {
2913                                    this.visit_ty(ty);
2914                                }
2915                            },
2916                        );
2917
2918                        this.resolve_const_item_rhs(
2919                            rhs_kind,
2920                            Some((*ident, ConstantItemKind::Const)),
2921                        );
2922                    },
2923                );
2924                self.resolve_define_opaques(define_opaque);
2925            }
2926            ItemKind::ConstBlock(ConstBlockItem { id: _, span: _, block }) => self
2927                .with_generic_param_rib(
2928                    &[],
2929                    RibKind::Item(HasGenericParams::No, def_kind),
2930                    item.id,
2931                    LifetimeBinderKind::ConstItem,
2932                    DUMMY_SP,
2933                    |this| {
2934                        this.with_lifetime_rib(
2935                            LifetimeRibKind::Elided(LifetimeRes::Infer),
2936                            |this| {
2937                                this.with_constant_rib(
2938                                    IsRepeatExpr::No,
2939                                    ConstantHasGenerics::Yes,
2940                                    Some((ConstBlockItem::IDENT, ConstantItemKind::Const)),
2941                                    |this| this.resolve_labeled_block(None, block.id, block),
2942                                )
2943                            },
2944                        );
2945                    },
2946                ),
2947
2948            ItemKind::Use(use_tree) => {
2949                let maybe_exported = match use_tree.kind {
2950                    UseTreeKind::Simple(_) | UseTreeKind::Glob => MaybeExported::Ok(item.id),
2951                    UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
2952                };
2953                self.resolve_doc_links(&item.attrs, maybe_exported);
2954
2955                self.future_proof_import(use_tree);
2956            }
2957
2958            ItemKind::MacroDef(_, macro_def) => {
2959                // Maintain macro_rules scopes in the same way as during early resolution
2960                // for diagnostics and doc links.
2961                if macro_def.macro_rules {
2962                    let def_id = self.r.local_def_id(item.id);
2963                    self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
2964                }
2965
2966                if let Some(EiiDecl { foreign_item: extern_item_path, impl_unsafe: _ }) =
2967                    &macro_def.eii_declaration
2968                {
2969                    self.smart_resolve_path(
2970                        item.id,
2971                        &None,
2972                        extern_item_path,
2973                        PathSource::Expr(None),
2974                    );
2975                }
2976            }
2977
2978            ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
2979                visit::walk_item(self, item);
2980            }
2981
2982            ItemKind::Delegation(delegation) => {
2983                let span = delegation.path.segments.last().unwrap().ident.span;
2984                self.with_generic_param_rib(
2985                    &[],
2986                    RibKind::Item(HasGenericParams::Yes(span), def_kind),
2987                    item.id,
2988                    LifetimeBinderKind::Function,
2989                    span,
2990                    |this| this.resolve_delegation(delegation, item.id, false, &item.attrs),
2991                );
2992            }
2993
2994            ItemKind::ExternCrate(..) => {}
2995
2996            ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
2997                {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
2998            }
2999        }
3000    }
3001
3002    fn with_generic_param_rib<F>(
3003        &mut self,
3004        params: &[GenericParam],
3005        kind: RibKind<'ra>,
3006        binder: NodeId,
3007        generics_kind: LifetimeBinderKind,
3008        generics_span: Span,
3009        f: F,
3010    ) where
3011        F: FnOnce(&mut Self),
3012    {
3013        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3013",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3013u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("with_generic_param_rib")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("with_generic_param_rib");
3014        let lifetime_kind =
3015            LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind };
3016
3017        let mut function_type_rib = Rib::new(kind);
3018        let mut function_value_rib = Rib::new(kind);
3019        let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
3020
3021        // Only check for shadowed bindings if we're declaring new params.
3022        if !params.is_empty() {
3023            let mut seen_bindings = FxHashMap::default();
3024            // Store all seen lifetimes names from outer scopes.
3025            let mut seen_lifetimes = FxHashSet::default();
3026
3027            // We also can't shadow bindings from associated parent items.
3028            for ns in [ValueNS, TypeNS] {
3029                for parent_rib in self.ribs[ns].iter().rev() {
3030                    // Break at module or block level, to account for nested items which are
3031                    // allowed to shadow generic param names.
3032                    if #[allow(non_exhaustive_omitted_patterns)] match parent_rib.kind {
    RibKind::Module(..) | RibKind::Block(..) => true,
    _ => false,
}matches!(parent_rib.kind, RibKind::Module(..) | RibKind::Block(..)) {
3033                        break;
3034                    }
3035
3036                    seen_bindings
3037                        .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
3038                }
3039            }
3040
3041            // Forbid shadowing lifetime bindings
3042            for rib in self.lifetime_ribs.iter().rev() {
3043                seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
3044                if let LifetimeRibKind::Item = rib.kind {
3045                    break;
3046                }
3047            }
3048
3049            for param in params {
3050                let ident = param.ident.normalize_to_macros_2_0();
3051                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3051",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3051u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("with_generic_param_rib: {0}",
                                                    param.id) as &dyn Value))])
            });
    } else { ; }
};debug!("with_generic_param_rib: {}", param.id);
3052
3053                if let GenericParamKind::Lifetime = param.kind
3054                    && let Some(&original) = seen_lifetimes.get(&ident)
3055                {
3056                    let guar = diagnostics::signal_lifetime_shadowing(
3057                        self.r.tcx.sess,
3058                        original,
3059                        param.ident,
3060                    );
3061                    // Record lifetime res, so lowering knows there is something fishy.
3062                    self.record_lifetime_param(param.id, LifetimeRes::Error(guar));
3063                    continue;
3064                }
3065
3066                match seen_bindings.entry(ident) {
3067                    Entry::Occupied(entry) => {
3068                        let span = *entry.get();
3069                        let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
3070                        let guar = self.r.report_error(param.ident.span, err);
3071                        let rib = match param.kind {
3072                            GenericParamKind::Lifetime => {
3073                                // Record lifetime res, so lowering knows there is something fishy.
3074                                self.record_lifetime_param(param.id, LifetimeRes::Error(guar));
3075                                continue;
3076                            }
3077                            GenericParamKind::Type { .. } => &mut function_type_rib,
3078                            GenericParamKind::Const { .. } => &mut function_value_rib,
3079                        };
3080
3081                        // Taint the resolution in case of errors to prevent follow up errors in typeck
3082                        self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
3083                        rib.bindings.insert(ident, Res::Err);
3084                        continue;
3085                    }
3086                    Entry::Vacant(entry) => {
3087                        entry.insert(param.ident.span);
3088                    }
3089                }
3090
3091                if param.ident.name == kw::UnderscoreLifetime {
3092                    // To avoid emitting two similar errors,
3093                    // we need to check if the span is a raw underscore lifetime, see issue #143152
3094                    let is_raw_underscore_lifetime = self
3095                        .r
3096                        .tcx
3097                        .sess
3098                        .psess
3099                        .raw_identifier_spans
3100                        .iter()
3101                        .any(|span| span == param.span());
3102
3103                    let guar = self
3104                        .r
3105                        .dcx()
3106                        .create_err(errors::UnderscoreLifetimeIsReserved { span: param.ident.span })
3107                        .emit_unless_delay(is_raw_underscore_lifetime);
3108                    // Record lifetime res, so lowering knows there is something fishy.
3109                    self.record_lifetime_param(param.id, LifetimeRes::Error(guar));
3110                    continue;
3111                }
3112
3113                if param.ident.name == kw::StaticLifetime {
3114                    let guar = self.r.dcx().emit_err(errors::StaticLifetimeIsReserved {
3115                        span: param.ident.span,
3116                        lifetime: param.ident,
3117                    });
3118                    // Record lifetime res, so lowering knows there is something fishy.
3119                    self.record_lifetime_param(param.id, LifetimeRes::Error(guar));
3120                    continue;
3121                }
3122
3123                let def_id = self.r.local_def_id(param.id);
3124
3125                // Plain insert (no renaming).
3126                let (rib, def_kind) = match param.kind {
3127                    GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
3128                    GenericParamKind::Const { .. } => {
3129                        (&mut function_value_rib, DefKind::ConstParam)
3130                    }
3131                    GenericParamKind::Lifetime => {
3132                        let res = LifetimeRes::Param { param: def_id, binder };
3133                        self.record_lifetime_param(param.id, res);
3134                        function_lifetime_rib.bindings.insert(ident, (param.id, res));
3135                        continue;
3136                    }
3137                };
3138
3139                let res = match kind {
3140                    RibKind::Item(..) | RibKind::AssocItem => {
3141                        Res::Def(def_kind, def_id.to_def_id())
3142                    }
3143                    RibKind::Normal => {
3144                        // FIXME(non_lifetime_binders): Stop special-casing
3145                        // const params to error out here.
3146                        if self.r.tcx.features().non_lifetime_binders()
3147                            && #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    GenericParamKind::Type { .. } => true,
    _ => false,
}matches!(param.kind, GenericParamKind::Type { .. })
3148                        {
3149                            Res::Def(def_kind, def_id.to_def_id())
3150                        } else {
3151                            Res::Err
3152                        }
3153                    }
3154                    _ => ::rustc_middle::util::bug::span_bug_fmt(param.ident.span,
    format_args!("Unexpected rib kind {0:?}", kind))span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
3155                };
3156                self.r.record_partial_res(param.id, PartialRes::new(res));
3157                rib.bindings.insert(ident, res);
3158            }
3159        }
3160
3161        self.lifetime_ribs.push(function_lifetime_rib);
3162        self.ribs[ValueNS].push(function_value_rib);
3163        self.ribs[TypeNS].push(function_type_rib);
3164
3165        f(self);
3166
3167        self.ribs[TypeNS].pop();
3168        self.ribs[ValueNS].pop();
3169        let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
3170
3171        // Do not account for the parameters we just bound for function lifetime elision.
3172        if let Some(ref mut candidates) = self.lifetime_elision_candidates {
3173            for (_, res) in function_lifetime_rib.bindings.values() {
3174                candidates.retain(|(r, _)| r != res);
3175            }
3176        }
3177
3178        if let LifetimeBinderKind::FnPtrType
3179        | LifetimeBinderKind::WhereBound
3180        | LifetimeBinderKind::Function
3181        | LifetimeBinderKind::ImplBlock = generics_kind
3182        {
3183            self.maybe_report_lifetime_uses(generics_span, params)
3184        }
3185    }
3186
3187    fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
3188        self.label_ribs.push(Rib::new(kind));
3189        f(self);
3190        self.label_ribs.pop();
3191    }
3192
3193    fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
3194        let kind = RibKind::Item(HasGenericParams::No, def_kind);
3195        self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
3196    }
3197
3198    // HACK(min_const_generics, generic_const_exprs): We
3199    // want to keep allowing `[0; size_of::<*mut T>()]`
3200    // with a future compat lint for now. We do this by adding an
3201    // additional special case for repeat expressions.
3202    //
3203    // Note that we intentionally still forbid `[0; N + 1]` during
3204    // name resolution so that we don't extend the future
3205    // compat lint to new cases.
3206    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("with_constant_rib",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3206u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["is_repeat",
                                                    "may_use_generics", "item"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&is_repeat)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&may_use_generics)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let f =
                |this: &mut Self|
                    {
                        this.with_rib(ValueNS,
                            RibKind::ConstantItem(may_use_generics, item),
                            |this|
                                {
                                    this.with_rib(TypeNS,
                                        RibKind::ConstantItem(may_use_generics.force_yes_if(is_repeat
                                                    == IsRepeatExpr::Yes), item),
                                        |this|
                                            {
                                                this.with_label_rib(RibKind::ConstantItem(may_use_generics,
                                                        item), f);
                                            })
                                })
                    };
            if let ConstantHasGenerics::No(cause) = may_use_generics {
                self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause),
                    f)
            } else { f(self) }
        }
    }
}#[instrument(level = "debug", skip(self, f))]
3207    fn with_constant_rib(
3208        &mut self,
3209        is_repeat: IsRepeatExpr,
3210        may_use_generics: ConstantHasGenerics,
3211        item: Option<(Ident, ConstantItemKind)>,
3212        f: impl FnOnce(&mut Self),
3213    ) {
3214        let f = |this: &mut Self| {
3215            this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3216                this.with_rib(
3217                    TypeNS,
3218                    RibKind::ConstantItem(
3219                        may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3220                        item,
3221                    ),
3222                    |this| {
3223                        this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3224                    },
3225                )
3226            })
3227        };
3228
3229        if let ConstantHasGenerics::No(cause) = may_use_generics {
3230            self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3231        } else {
3232            f(self)
3233        }
3234    }
3235
3236    fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
3237        // Handle nested impls (inside fn bodies)
3238        let previous_value =
3239            replace(&mut self.diag_metadata.current_self_type, Some(self_type.clone()));
3240        let result = f(self);
3241        self.diag_metadata.current_self_type = previous_value;
3242        result
3243    }
3244
3245    fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3246        let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3247        let result = f(self);
3248        self.diag_metadata.current_self_item = previous_value;
3249        result
3250    }
3251
3252    /// When evaluating a `trait` use its associated types' idents for suggestions in E0425.
3253    fn resolve_trait_items(&mut self, trait_items: &'ast [Box<AssocItem>]) {
3254        let trait_assoc_items =
3255            replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3256
3257        let walk_assoc_item =
3258            |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3259                this.with_generic_param_rib(
3260                    &generics.params,
3261                    RibKind::AssocItem,
3262                    item.id,
3263                    kind,
3264                    generics.span,
3265                    |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3266                );
3267            };
3268
3269        for item in trait_items {
3270            self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3271            match &item.kind {
3272                AssocItemKind::Const(box ast::ConstItem {
3273                    generics,
3274                    ty,
3275                    rhs_kind,
3276                    define_opaque,
3277                    ..
3278                }) => {
3279                    self.with_generic_param_rib(
3280                        &generics.params,
3281                        RibKind::AssocItem,
3282                        item.id,
3283                        LifetimeBinderKind::ConstItem,
3284                        generics.span,
3285                        |this| {
3286                            this.with_lifetime_rib(
3287                                LifetimeRibKind::StaticIfNoLifetimeInScope {
3288                                    lint_id: item.id,
3289                                    emit_lint: false,
3290                                },
3291                                |this| {
3292                                    this.visit_generics(generics);
3293                                    if rhs_kind.is_type_const()
3294                                        && !this.r.tcx.features().generic_const_parameter_types()
3295                                    {
3296                                        this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3297                                            this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
3298                                                this.with_lifetime_rib(
3299                                                    LifetimeRibKind::ConstParamTy,
3300                                                    |this| this.visit_ty(ty),
3301                                                )
3302                                            })
3303                                        });
3304                                    } else {
3305                                        this.visit_ty(ty);
3306                                    }
3307
3308                                    // Only impose the restrictions of `ConstRibKind` for an
3309                                    // actual constant expression in a provided default.
3310                                    //
3311                                    // We allow arbitrary const expressions inside of associated consts,
3312                                    // even if they are potentially not const evaluatable.
3313                                    //
3314                                    // Type parameters can already be used and as associated consts are
3315                                    // not used as part of the type system, this is far less surprising.
3316                                    this.resolve_const_item_rhs(rhs_kind, None);
3317                                },
3318                            )
3319                        },
3320                    );
3321
3322                    self.resolve_define_opaques(define_opaque);
3323                }
3324                AssocItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
3325                    walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3326
3327                    self.resolve_define_opaques(define_opaque);
3328                }
3329                AssocItemKind::Delegation(delegation) => {
3330                    self.with_generic_param_rib(
3331                        &[],
3332                        RibKind::AssocItem,
3333                        item.id,
3334                        LifetimeBinderKind::Function,
3335                        delegation.path.segments.last().unwrap().ident.span,
3336                        |this| this.resolve_delegation(delegation, item.id, false, &item.attrs),
3337                    );
3338                }
3339                AssocItemKind::Type(box TyAlias { generics, .. }) => self
3340                    .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3341                        walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3342                    }),
3343                AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3344                    {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3345                }
3346            };
3347        }
3348
3349        self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3350    }
3351
3352    /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
3353    fn with_optional_trait_ref<T>(
3354        &mut self,
3355        opt_trait_ref: Option<&TraitRef>,
3356        self_type: &'ast Ty,
3357        f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3358    ) -> T {
3359        let mut new_val = None;
3360        let mut new_id = None;
3361        if let Some(trait_ref) = opt_trait_ref {
3362            let path: Vec<_> = Segment::from_path(&trait_ref.path);
3363            self.diag_metadata.currently_processing_impl_trait =
3364                Some((trait_ref.clone(), self_type.clone()));
3365            let res = self.smart_resolve_path_fragment(
3366                &None,
3367                &path,
3368                PathSource::Trait(AliasPossibility::No),
3369                Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3370                RecordPartialRes::Yes,
3371                None,
3372            );
3373            self.diag_metadata.currently_processing_impl_trait = None;
3374            if let Some(def_id) = res.expect_full_res().opt_def_id() {
3375                new_id = Some(def_id);
3376                new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3377            }
3378        }
3379        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3380        let result = f(self, new_id);
3381        self.current_trait_ref = original_trait_ref;
3382        result
3383    }
3384
3385    fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3386        let mut self_type_rib = Rib::new(RibKind::Normal);
3387
3388        // Plain insert (no renaming, since types are not currently hygienic)
3389        self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3390        self.ribs[ns].push(self_type_rib);
3391        f(self);
3392        self.ribs[ns].pop();
3393    }
3394
3395    fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3396        self.with_self_rib_ns(TypeNS, self_res, f)
3397    }
3398
3399    fn resolve_implementation(
3400        &mut self,
3401        attrs: &[ast::Attribute],
3402        generics: &'ast Generics,
3403        of_trait: Option<&'ast ast::TraitImplHeader>,
3404        self_type: &'ast Ty,
3405        item_id: NodeId,
3406        impl_items: &'ast [Box<AssocItem>],
3407    ) {
3408        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3408",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3408u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_implementation")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_implementation");
3409        // If applicable, create a rib for the type parameters.
3410        self.with_generic_param_rib(
3411            &generics.params,
3412            RibKind::Item(HasGenericParams::Yes(generics.span), self.r.local_def_kind(item_id)),
3413            item_id,
3414            LifetimeBinderKind::ImplBlock,
3415            generics.span,
3416            |this| {
3417                // Dummy self type for better errors if `Self` is used in the trait path.
3418                this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3419                    this.with_lifetime_rib(
3420                        LifetimeRibKind::AnonymousCreateParameter {
3421                            binder: item_id,
3422                            report_in_path: true
3423                        },
3424                        |this| {
3425                            // Resolve the trait reference, if necessary.
3426                            this.with_optional_trait_ref(
3427                                of_trait.map(|t| &t.trait_ref),
3428                                self_type,
3429                                |this, trait_id| {
3430                                    this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3431
3432                                    let item_def_id = this.r.local_def_id(item_id);
3433
3434                                    // Register the trait definitions from here.
3435                                    if let Some(trait_id) = trait_id {
3436                                        this.r
3437                                            .trait_impls
3438                                            .entry(trait_id)
3439                                            .or_default()
3440                                            .push(item_def_id);
3441                                    }
3442
3443                                    let item_def_id = item_def_id.to_def_id();
3444                                    let res = Res::SelfTyAlias {
3445                                        alias_to: item_def_id,
3446                                        is_trait_impl: trait_id.is_some(),
3447                                    };
3448                                    this.with_self_rib(res, |this| {
3449                                        if let Some(of_trait) = of_trait {
3450                                            // Resolve type arguments in the trait path.
3451                                            visit::walk_trait_ref(this, &of_trait.trait_ref);
3452                                        }
3453                                        // Resolve the self type.
3454                                        this.visit_ty(self_type);
3455                                        // Resolve the generic parameters.
3456                                        this.visit_generics(generics);
3457
3458                                        // Resolve the items within the impl.
3459                                        this.with_current_self_type(self_type, |this| {
3460                                            this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3461                                                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3461",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3461u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_implementation with_self_rib_ns(ValueNS, ...)")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
3462                                                let mut seen_trait_items = Default::default();
3463                                                for item in impl_items {
3464                                                    this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id, of_trait.is_some());
3465                                                }
3466                                            });
3467                                        });
3468                                    });
3469                                },
3470                            )
3471                        },
3472                    );
3473                });
3474            },
3475        );
3476    }
3477
3478    fn resolve_impl_item(
3479        &mut self,
3480        item: &'ast AssocItem,
3481        seen_trait_items: &mut FxHashMap<DefId, Span>,
3482        trait_id: Option<DefId>,
3483        is_in_trait_impl: bool,
3484    ) {
3485        use crate::ResolutionError::*;
3486        self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3487        let prev = self.diag_metadata.current_impl_item.take();
3488        self.diag_metadata.current_impl_item = Some(&item);
3489        match &item.kind {
3490            AssocItemKind::Const(box ast::ConstItem {
3491                ident,
3492                generics,
3493                ty,
3494                rhs_kind,
3495                define_opaque,
3496                ..
3497            }) => {
3498                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3498",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3498u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_implementation AssocItemKind::Const")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_implementation AssocItemKind::Const");
3499                self.with_generic_param_rib(
3500                    &generics.params,
3501                    RibKind::AssocItem,
3502                    item.id,
3503                    LifetimeBinderKind::ConstItem,
3504                    generics.span,
3505                    |this| {
3506                        this.with_lifetime_rib(
3507                            // Until these are a hard error, we need to create them within the
3508                            // correct binder, Otherwise the lifetimes of this assoc const think
3509                            // they are lifetimes of the trait.
3510                            LifetimeRibKind::AnonymousCreateParameter {
3511                                binder: item.id,
3512                                report_in_path: true,
3513                            },
3514                            |this| {
3515                                this.with_lifetime_rib(
3516                                    LifetimeRibKind::StaticIfNoLifetimeInScope {
3517                                        lint_id: item.id,
3518                                        // In impls, it's not a hard error yet due to backcompat.
3519                                        emit_lint: true,
3520                                    },
3521                                    |this| {
3522                                        // If this is a trait impl, ensure the const
3523                                        // exists in trait
3524                                        this.check_trait_item(
3525                                            item.id,
3526                                            *ident,
3527                                            &item.kind,
3528                                            ValueNS,
3529                                            item.span,
3530                                            seen_trait_items,
3531                                            |i, s, c| ConstNotMemberOfTrait(i, s, c),
3532                                        );
3533
3534                                        this.visit_generics(generics);
3535                                        if rhs_kind.is_type_const()
3536                                            && !this
3537                                                .r
3538                                                .tcx
3539                                                .features()
3540                                                .generic_const_parameter_types()
3541                                        {
3542                                            this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3543                                                this.with_rib(
3544                                                    ValueNS,
3545                                                    RibKind::ConstParamTy,
3546                                                    |this| {
3547                                                        this.with_lifetime_rib(
3548                                                            LifetimeRibKind::ConstParamTy,
3549                                                            |this| this.visit_ty(ty),
3550                                                        )
3551                                                    },
3552                                                )
3553                                            });
3554                                        } else {
3555                                            this.visit_ty(ty);
3556                                        }
3557                                        // We allow arbitrary const expressions inside of associated consts,
3558                                        // even if they are potentially not const evaluatable.
3559                                        //
3560                                        // Type parameters can already be used and as associated consts are
3561                                        // not used as part of the type system, this is far less surprising.
3562                                        this.resolve_const_item_rhs(rhs_kind, None);
3563                                    },
3564                                )
3565                            },
3566                        );
3567                    },
3568                );
3569                self.resolve_define_opaques(define_opaque);
3570            }
3571            AssocItemKind::Fn(box Fn { ident, generics, define_opaque, .. }) => {
3572                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3572",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3572u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_implementation AssocItemKind::Fn")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_implementation AssocItemKind::Fn");
3573                // We also need a new scope for the impl item type parameters.
3574                self.with_generic_param_rib(
3575                    &generics.params,
3576                    RibKind::AssocItem,
3577                    item.id,
3578                    LifetimeBinderKind::Function,
3579                    generics.span,
3580                    |this| {
3581                        // If this is a trait impl, ensure the method
3582                        // exists in trait
3583                        this.check_trait_item(
3584                            item.id,
3585                            *ident,
3586                            &item.kind,
3587                            ValueNS,
3588                            item.span,
3589                            seen_trait_items,
3590                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3591                        );
3592
3593                        visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3594                    },
3595                );
3596
3597                self.resolve_define_opaques(define_opaque);
3598            }
3599            AssocItemKind::Type(box TyAlias { ident, generics, .. }) => {
3600                self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3601                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3601",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3601u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_implementation AssocItemKind::Type")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_implementation AssocItemKind::Type");
3602                // We also need a new scope for the impl item type parameters.
3603                self.with_generic_param_rib(
3604                    &generics.params,
3605                    RibKind::AssocItem,
3606                    item.id,
3607                    LifetimeBinderKind::ImplAssocType,
3608                    generics.span,
3609                    |this| {
3610                        this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3611                            // If this is a trait impl, ensure the type
3612                            // exists in trait
3613                            this.check_trait_item(
3614                                item.id,
3615                                *ident,
3616                                &item.kind,
3617                                TypeNS,
3618                                item.span,
3619                                seen_trait_items,
3620                                |i, s, c| TypeNotMemberOfTrait(i, s, c),
3621                            );
3622
3623                            visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3624                        });
3625                    },
3626                );
3627                self.diag_metadata.in_non_gat_assoc_type = None;
3628            }
3629            AssocItemKind::Delegation(box delegation) => {
3630                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3630",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3630u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_implementation AssocItemKind::Delegation")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_implementation AssocItemKind::Delegation");
3631                self.with_generic_param_rib(
3632                    &[],
3633                    RibKind::AssocItem,
3634                    item.id,
3635                    LifetimeBinderKind::Function,
3636                    delegation.path.segments.last().unwrap().ident.span,
3637                    |this| {
3638                        this.check_trait_item(
3639                            item.id,
3640                            delegation.ident,
3641                            &item.kind,
3642                            ValueNS,
3643                            item.span,
3644                            seen_trait_items,
3645                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3646                        );
3647
3648                        // Here we don't use `trait_id`, as we can process unresolved trait, however
3649                        // in this case we are still in a trait impl, https://github.com/rust-lang/rust/issues/150152
3650                        this.resolve_delegation(delegation, item.id, is_in_trait_impl, &item.attrs);
3651                    },
3652                );
3653            }
3654            AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3655                {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3656            }
3657        }
3658        self.diag_metadata.current_impl_item = prev;
3659    }
3660
3661    fn check_trait_item<F>(
3662        &mut self,
3663        id: NodeId,
3664        mut ident: Ident,
3665        kind: &AssocItemKind,
3666        ns: Namespace,
3667        span: Span,
3668        seen_trait_items: &mut FxHashMap<DefId, Span>,
3669        err: F,
3670    ) where
3671        F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3672    {
3673        // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3674        let Some((module, _)) = self.current_trait_ref else {
3675            return;
3676        };
3677        ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3678        let key = BindingKey::new(IdentKey::new(ident), ns);
3679        let mut decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3680        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3680",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("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(&["decl"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&decl) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?decl);
3681        if decl.is_none() {
3682            // We could not find the trait item in the correct namespace.
3683            // Check the other namespace to report an error.
3684            let ns = match ns {
3685                ValueNS => TypeNS,
3686                TypeNS => ValueNS,
3687                _ => ns,
3688            };
3689            let key = BindingKey::new(IdentKey::new(ident), ns);
3690            decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3691            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3691",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3691u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["decl"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&decl) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?decl);
3692        }
3693
3694        let feed_visibility = |this: &mut Self, def_id| {
3695            let vis = this.r.tcx.visibility(def_id);
3696            let vis = if vis.is_visible_locally() {
3697                vis.expect_local()
3698            } else {
3699                this.r.dcx().span_delayed_bug(
3700                    span,
3701                    "error should be emitted when an unexpected trait item is used",
3702                );
3703                Visibility::Public
3704            };
3705            this.r.feed_visibility(this.r.feed(id), vis);
3706        };
3707
3708        let Some(decl) = decl else {
3709            // We could not find the method: report an error.
3710            let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
3711            let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3712            let path_names = path_names_to_string(path);
3713            self.report_error(span, err(ident, path_names, candidate));
3714            feed_visibility(self, module.def_id());
3715            return;
3716        };
3717
3718        let res = decl.res();
3719        let Res::Def(def_kind, id_in_trait) = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
3720        feed_visibility(self, id_in_trait);
3721
3722        match seen_trait_items.entry(id_in_trait) {
3723            Entry::Occupied(entry) => {
3724                self.report_error(
3725                    span,
3726                    ResolutionError::TraitImplDuplicate {
3727                        name: ident,
3728                        old_span: *entry.get(),
3729                        trait_item_span: decl.span,
3730                    },
3731                );
3732                return;
3733            }
3734            Entry::Vacant(entry) => {
3735                entry.insert(span);
3736            }
3737        };
3738
3739        match (def_kind, kind) {
3740            (DefKind::AssocTy, AssocItemKind::Type(..))
3741            | (DefKind::AssocFn, AssocItemKind::Fn(..))
3742            | (DefKind::AssocConst, AssocItemKind::Const(..))
3743            | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3744                self.r.record_partial_res(id, PartialRes::new(res));
3745                return;
3746            }
3747            _ => {}
3748        }
3749
3750        // The method kind does not correspond to what appeared in the trait, report.
3751        let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3752        let (code, kind) = match kind {
3753            AssocItemKind::Const(..) => (E0323, "const"),
3754            AssocItemKind::Fn(..) => (E0324, "method"),
3755            AssocItemKind::Type(..) => (E0325, "type"),
3756            AssocItemKind::Delegation(..) => (E0324, "method"),
3757            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3758                ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("unexpanded macro"))span_bug!(span, "unexpanded macro")
3759            }
3760        };
3761        let trait_path = path_names_to_string(path);
3762        self.report_error(
3763            span,
3764            ResolutionError::TraitImplMismatch {
3765                name: ident,
3766                kind,
3767                code,
3768                trait_path,
3769                trait_item_span: decl.span,
3770            },
3771        );
3772    }
3773
3774    fn resolve_static_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3775        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3776            this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3777                this.visit_expr(expr)
3778            });
3779        })
3780    }
3781
3782    fn resolve_const_item_rhs(
3783        &mut self,
3784        rhs_kind: &'ast ConstItemRhsKind,
3785        item: Option<(Ident, ConstantItemKind)>,
3786    ) {
3787        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| match rhs_kind {
3788            ConstItemRhsKind::TypeConst { rhs: Some(anon_const) } => {
3789                this.resolve_anon_const(anon_const, AnonConstKind::ConstArg(IsRepeatExpr::No));
3790            }
3791            ConstItemRhsKind::Body { rhs: Some(expr) } => {
3792                this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3793                    this.visit_expr(expr)
3794                });
3795            }
3796            _ => (),
3797        })
3798    }
3799
3800    fn resolve_delegation(
3801        &mut self,
3802        delegation: &'ast Delegation,
3803        item_id: NodeId,
3804        is_in_trait_impl: bool,
3805        attrs: &[Attribute],
3806    ) {
3807        self.smart_resolve_path(
3808            delegation.id,
3809            &delegation.qself,
3810            &delegation.path,
3811            PathSource::Delegation,
3812        );
3813
3814        if let Some(qself) = &delegation.qself {
3815            self.visit_ty(&qself.ty);
3816        }
3817
3818        self.visit_path(&delegation.path);
3819
3820        self.r.delegation_infos.insert(
3821            self.r.local_def_id(item_id),
3822            DelegationInfo {
3823                attrs: create_delegation_attrs(attrs),
3824                resolution_node: if is_in_trait_impl { item_id } else { delegation.id },
3825            },
3826        );
3827
3828        let Some(body) = &delegation.body else { return };
3829        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3830            let span = delegation.path.segments.last().unwrap().ident.span;
3831            let ident = Ident::new(kw::SelfLower, span.normalize_to_macro_rules());
3832            let res = Res::Local(delegation.id);
3833            this.innermost_rib_bindings(ValueNS).insert(ident, res);
3834
3835            //As we lower target_expr_template body to a body of a function we need a label rib (#148889)
3836            this.with_label_rib(RibKind::FnOrCoroutine, |this| {
3837                this.visit_block(body);
3838            });
3839        });
3840    }
3841
3842    fn resolve_params(&mut self, params: &'ast [Param]) {
3843        let mut bindings = {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push((PatBoundCtx::Product, Default::default()));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(<[_]>::into_vec(::alloc::boxed::box_new([(PatBoundCtx::Product,
                                Default::default())])))
    }
}smallvec![(PatBoundCtx::Product, Default::default())];
3844        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3845            for Param { pat, .. } in params {
3846                this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3847            }
3848            this.apply_pattern_bindings(bindings);
3849        });
3850        for Param { ty, .. } in params {
3851            self.visit_ty(ty);
3852        }
3853    }
3854
3855    fn resolve_local(&mut self, local: &'ast Local) {
3856        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3856",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3856u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolving local ({0:?})",
                                                    local) as &dyn Value))])
            });
    } else { ; }
};debug!("resolving local ({:?})", local);
3857        // Resolve the type.
3858        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);
3859
3860        // Resolve the initializer.
3861        if let Some((init, els)) = local.kind.init_else_opt() {
3862            self.visit_expr(init);
3863
3864            // Resolve the `else` block
3865            if let Some(els) = els {
3866                self.visit_block(els);
3867            }
3868        }
3869
3870        // Resolve the pattern.
3871        self.resolve_pattern_top(&local.pat, PatternSource::Let);
3872    }
3873
3874    /// Build a map from pattern identifiers to binding-info's, and check the bindings are
3875    /// consistent when encountering or-patterns and never patterns.
3876    /// This is done hygienically: this could arise for a macro that expands into an or-pattern
3877    /// where one 'x' was from the user and one 'x' came from the macro.
3878    ///
3879    /// A never pattern by definition indicates an unreachable case. For example, matching on
3880    /// `Result<T, &!>` could look like:
3881    /// ```rust
3882    /// # #![feature(never_type)]
3883    /// # #![feature(never_patterns)]
3884    /// # fn bar(_x: u32) {}
3885    /// let foo: Result<u32, &!> = Ok(0);
3886    /// match foo {
3887    ///     Ok(x) => bar(x),
3888    ///     Err(&!),
3889    /// }
3890    /// ```
3891    /// This extends to product types: `(x, !)` is likewise unreachable. So it doesn't make sense to
3892    /// have a binding here, and we tell the user to use `_` instead.
3893    fn compute_and_check_binding_map(
3894        &mut self,
3895        pat: &Pat,
3896    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3897        let mut binding_map = FxIndexMap::default();
3898        let mut is_never_pat = false;
3899
3900        pat.walk(&mut |pat| {
3901            match pat.kind {
3902                PatKind::Ident(annotation, ident, ref sub_pat)
3903                    if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3904                {
3905                    binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3906                }
3907                PatKind::Or(ref ps) => {
3908                    // Check the consistency of this or-pattern and
3909                    // then add all bindings to the larger map.
3910                    match self.compute_and_check_or_pat_binding_map(ps) {
3911                        Ok(bm) => binding_map.extend(bm),
3912                        Err(IsNeverPattern) => is_never_pat = true,
3913                    }
3914                    return false;
3915                }
3916                PatKind::Never => is_never_pat = true,
3917                _ => {}
3918            }
3919
3920            true
3921        });
3922
3923        if is_never_pat {
3924            for (_, binding) in binding_map {
3925                self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3926            }
3927            Err(IsNeverPattern)
3928        } else {
3929            Ok(binding_map)
3930        }
3931    }
3932
3933    fn is_base_res_local(&self, nid: NodeId) -> bool {
3934        #[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!(
3935            self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
3936            Some(Res::Local(..))
3937        )
3938    }
3939
3940    /// Compute the binding map for an or-pattern. Checks that all of the arms in the or-pattern
3941    /// have exactly the same set of bindings, with the same binding modes for each.
3942    /// Returns the computed binding map and a boolean indicating whether the pattern is a never
3943    /// pattern.
3944    ///
3945    /// A never pattern by definition indicates an unreachable case. For example, destructuring a
3946    /// `Result<T, &!>` could look like:
3947    /// ```rust
3948    /// # #![feature(never_type)]
3949    /// # #![feature(never_patterns)]
3950    /// # fn foo() -> Result<bool, &'static !> { Ok(true) }
3951    /// let (Ok(x) | Err(&!)) = foo();
3952    /// # let _ = x;
3953    /// ```
3954    /// Because the `Err(&!)` branch is never reached, it does not need to have the same bindings as
3955    /// the other branches of the or-pattern. So we must ignore never pattern when checking the
3956    /// bindings of an or-pattern.
3957    /// Moreover, if all the subpatterns are never patterns (e.g. `Ok(!) | Err(!)`), then the
3958    /// pattern as a whole counts as a never pattern (since it's definitionallly unreachable).
3959    fn compute_and_check_or_pat_binding_map(
3960        &mut self,
3961        pats: &[Pat],
3962    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3963        let mut missing_vars = FxIndexMap::default();
3964        let mut inconsistent_vars = FxIndexMap::default();
3965
3966        // 1) Compute the binding maps of all arms; we must ignore never patterns here.
3967        let not_never_pats = pats
3968            .iter()
3969            .filter_map(|pat| {
3970                let binding_map = self.compute_and_check_binding_map(pat).ok()?;
3971                Some((binding_map, pat))
3972            })
3973            .collect::<Vec<_>>();
3974
3975        // 2) Record any missing bindings or binding mode inconsistencies.
3976        for &(ref map_outer, pat_outer) in not_never_pats.iter() {
3977            // Check against all arms except for the same pattern which is always self-consistent.
3978            let inners = not_never_pats.iter().filter(|(_, pat)| pat.id != pat_outer.id);
3979
3980            for &(ref map, pat) in inners {
3981                for (&name, binding_inner) in map {
3982                    match map_outer.get(&name) {
3983                        None => {
3984                            // The inner binding is missing in the outer.
3985                            let binding_error =
3986                                missing_vars.entry(name).or_insert_with(|| BindingError {
3987                                    name,
3988                                    origin: Default::default(),
3989                                    target: Default::default(),
3990                                    could_be_path: name.as_str().starts_with(char::is_uppercase),
3991                                });
3992                            binding_error.origin.push((binding_inner.span, pat.clone()));
3993                            binding_error.target.push(pat_outer.clone());
3994                        }
3995                        Some(binding_outer) => {
3996                            if binding_outer.annotation != binding_inner.annotation {
3997                                // The binding modes in the outer and inner bindings differ.
3998                                inconsistent_vars
3999                                    .entry(name)
4000                                    .or_insert((binding_inner.span, binding_outer.span));
4001                            }
4002                        }
4003                    }
4004                }
4005            }
4006        }
4007
4008        // 3) Report all missing variables we found.
4009        for (name, mut v) in missing_vars {
4010            if inconsistent_vars.contains_key(&name) {
4011                v.could_be_path = false;
4012            }
4013            self.report_error(
4014                v.origin.iter().next().unwrap().0,
4015                ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
4016            );
4017        }
4018
4019        // 4) Report all inconsistencies in binding modes we found.
4020        for (name, v) in inconsistent_vars {
4021            self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
4022        }
4023
4024        // 5) Bubble up the final binding map.
4025        if not_never_pats.is_empty() {
4026            // All the patterns are never patterns, so the whole or-pattern is one too.
4027            Err(IsNeverPattern)
4028        } else {
4029            let mut binding_map = FxIndexMap::default();
4030            for (bm, _) in not_never_pats {
4031                binding_map.extend(bm);
4032            }
4033            Ok(binding_map)
4034        }
4035    }
4036
4037    /// Check the consistency of bindings wrt or-patterns and never patterns.
4038    fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
4039        let mut is_or_or_never = false;
4040        pat.walk(&mut |pat| match pat.kind {
4041            PatKind::Or(..) | PatKind::Never => {
4042                is_or_or_never = true;
4043                false
4044            }
4045            _ => true,
4046        });
4047        if is_or_or_never {
4048            let _ = self.compute_and_check_binding_map(pat);
4049        }
4050    }
4051
4052    fn resolve_arm(&mut self, arm: &'ast Arm) {
4053        self.with_rib(ValueNS, RibKind::Normal, |this| {
4054            this.resolve_pattern_top(&arm.pat, PatternSource::Match);
4055            if let Some(x) = &arm.guard {
    match ::rustc_ast_ir::visit::VisitorResult::branch(this.visit_expr(x)) {
        core::ops::ControlFlow::Continue(()) =>
            (),
            #[allow(unreachable_code)]
            core::ops::ControlFlow::Break(r) => {
            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
        }
    };
};visit_opt!(this, visit_expr, &arm.guard);
4056            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);
4057        });
4058    }
4059
4060    /// Arising from `source`, resolve a top level pattern.
4061    fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
4062        let mut bindings = {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push((PatBoundCtx::Product, Default::default()));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(<[_]>::into_vec(::alloc::boxed::box_new([(PatBoundCtx::Product,
                                Default::default())])))
    }
}smallvec![(PatBoundCtx::Product, Default::default())];
4063        self.resolve_pattern(pat, pat_src, &mut bindings);
4064        self.apply_pattern_bindings(bindings);
4065    }
4066
4067    /// Apply the bindings from a pattern to the innermost rib of the current scope.
4068    fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
4069        let rib_bindings = self.innermost_rib_bindings(ValueNS);
4070        let Some((_, pat_bindings)) = pat_bindings.pop() else {
4071            ::rustc_middle::util::bug::bug_fmt(format_args!("tried applying nonexistent bindings from pattern"));bug!("tried applying nonexistent bindings from pattern");
4072        };
4073
4074        if rib_bindings.is_empty() {
4075            // Often, such as for match arms, the bindings are introduced into a new rib.
4076            // In this case, we can move the bindings over directly.
4077            *rib_bindings = pat_bindings;
4078        } else {
4079            rib_bindings.extend(pat_bindings);
4080        }
4081    }
4082
4083    /// Resolve bindings in a pattern. `apply_pattern_bindings` must be called after to introduce
4084    /// the bindings into scope.
4085    fn resolve_pattern(
4086        &mut self,
4087        pat: &'ast Pat,
4088        pat_src: PatternSource,
4089        bindings: &mut PatternBindings,
4090    ) {
4091        // We walk the pattern before declaring the pattern's inner bindings,
4092        // so that we avoid resolving a literal expression to a binding defined
4093        // by the pattern.
4094        // NB: `Self::visit_pat` must be used rather than `visit::walk_pat` to avoid resolving guard
4095        // patterns' guard expressions multiple times (#141265).
4096        self.visit_pat(pat);
4097        self.resolve_pattern_inner(pat, pat_src, bindings);
4098        // This has to happen *after* we determine which pat_idents are variants:
4099        self.check_consistent_bindings(pat);
4100    }
4101
4102    /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
4103    ///
4104    /// ### `bindings`
4105    ///
4106    /// A stack of sets of bindings accumulated.
4107    ///
4108    /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
4109    /// be interpreted as re-binding an already bound binding. This results in an error.
4110    /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
4111    /// in reusing this binding rather than creating a fresh one.
4112    ///
4113    /// When called at the top level, the stack must have a single element
4114    /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
4115    /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
4116    /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
4117    /// When each `p_i` has been dealt with, the top set is merged with its parent.
4118    /// When a whole or-pattern has been dealt with, the thing happens.
4119    ///
4120    /// See the implementation and `fresh_binding` for more details.
4121    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("resolve_pattern_inner",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(4121u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["pat", "pat_src"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat_src)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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