Skip to main content

rustc_resolve/
late.rs

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