Skip to main content

rustc_resolve/
late.rs

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