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