Skip to main content

rustc_resolve/
late.rs

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