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, TraitCandidate};
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::lint;
36use rustc_session::parse::feature_err;
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, errors, path_names_to_string, rustdoc,
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(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Elided",
                    &__self_0),
            LifetimeRibKind::AnonymousReportError =>
                ::core::fmt::Formatter::write_str(f, "AnonymousReportError"),
            LifetimeRibKind::StaticIfNoLifetimeInScope {
                lint_id: __self_0, emit_lint: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "StaticIfNoLifetimeInScope", "lint_id", __self_0,
                    "emit_lint", &__self_1),
            LifetimeRibKind::ElisionFailure =>
                ::core::fmt::Formatter::write_str(f, "ElisionFailure"),
            LifetimeRibKind::ConstParamTy =>
                ::core::fmt::Formatter::write_str(f, "ConstParamTy"),
            LifetimeRibKind::ConcreteAnonConst(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ConcreteAnonConst", &__self_0),
            LifetimeRibKind::Item =>
                ::core::fmt::Formatter::write_str(f, "Item"),
        }
    }
}Debug)]
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(LifetimeRes),
337
338    // -- Barrier ribs that stop lifetime lookup, or continue it but produce an error later.
339    //
340    /// Give a hard error when either `&` or `'_` is written. Used to
341    /// rule out things like `where T: Foo<'_>`. Does not imply an
342    /// error on default object bounds (e.g., `Box<dyn Foo>`).
343    AnonymousReportError,
344
345    /// Resolves elided lifetimes to `'static` if there are no other lifetimes in scope,
346    /// otherwise give a warning that the previous behavior of introducing a new early-bound
347    /// lifetime is a bug and will be removed (if `emit_lint` is enabled).
348    StaticIfNoLifetimeInScope { lint_id: NodeId, emit_lint: bool },
349
350    /// Signal we cannot find which should be the anonymous lifetime.
351    ElisionFailure,
352
353    /// This rib forbids usage of generic parameters inside of const parameter types.
354    ///
355    /// While this is desirable to support eventually, it is difficult to do and so is
356    /// currently forbidden. See rust-lang/project-const-generics#28 for more info.
357    ConstParamTy,
358
359    /// Usage of generic parameters is forbidden in various positions for anon consts:
360    /// - const arguments when `generic_const_exprs` is not enabled
361    /// - enum discriminant values
362    ///
363    /// This rib emits an error when a lifetime would resolve to a lifetime parameter.
364    ConcreteAnonConst(NoConstantGenericsReason),
365
366    /// This rib acts as a barrier to forbid reference to lifetimes of a parent item.
367    Item,
368}
369
370#[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)]
371enum LifetimeBinderKind {
372    FnPtrType,
373    PolyTrait,
374    WhereBound,
375    // Item covers foreign items, ADTs, type aliases, trait associated items and
376    // trait alias associated items.
377    Item,
378    ConstItem,
379    Function,
380    Closure,
381    ImplBlock,
382    // Covers only `impl` associated types.
383    ImplAssocType,
384}
385
386impl LifetimeBinderKind {
387    fn descr(self) -> &'static str {
388        use LifetimeBinderKind::*;
389        match self {
390            FnPtrType => "type",
391            PolyTrait => "bound",
392            WhereBound => "bound",
393            Item | ConstItem => "item",
394            ImplAssocType => "associated type",
395            ImplBlock => "impl block",
396            Function => "function",
397            Closure => "closure",
398        }
399    }
400}
401
402#[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)]
403struct LifetimeRib {
404    kind: LifetimeRibKind,
405    // We need to preserve insertion order for async fns.
406    bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
407}
408
409impl LifetimeRib {
410    fn new(kind: LifetimeRibKind) -> LifetimeRib {
411        LifetimeRib { bindings: Default::default(), kind }
412    }
413}
414
415#[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)]
416pub(crate) enum AliasPossibility {
417    No,
418    Maybe,
419}
420
421#[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)]
422pub(crate) enum PathSource<'a, 'ast, 'ra> {
423    /// Type paths `Path`.
424    Type,
425    /// Trait paths in bounds or impls.
426    Trait(AliasPossibility),
427    /// Expression paths `path`, with optional parent context.
428    Expr(Option<&'ast Expr>),
429    /// Paths in path patterns `Path`.
430    Pat,
431    /// Paths in struct expressions and patterns `Path { .. }`.
432    Struct(Option<&'a Expr>),
433    /// Paths in tuple struct patterns `Path(..)`.
434    TupleStruct(Span, &'ra [Span]),
435    /// `m::A::B` in `<T as m::A>::B::C`.
436    ///
437    /// Second field holds the "cause" of this one, i.e. the context within
438    /// which the trait item is resolved. Used for diagnostics.
439    TraitItem(Namespace, &'a PathSource<'a, 'ast, 'ra>),
440    /// Paths in delegation item
441    Delegation,
442    /// Paths in externally implementable item declarations.
443    ExternItemImpl,
444    /// An arg in a `use<'a, N>` precise-capturing bound.
445    PreciseCapturingArg(Namespace),
446    /// Paths that end with `(..)`, for return type notation.
447    ReturnTypeNotation,
448    /// Paths from `#[define_opaque]` attributes
449    DefineOpaques,
450    /// Resolving a macro
451    Macro,
452    /// Paths for module or crate root. Used for restrictions.
453    Module,
454}
455
456impl PathSource<'_, '_, '_> {
457    fn namespace(self) -> Namespace {
458        match self {
459            PathSource::Type
460            | PathSource::Trait(_)
461            | PathSource::Struct(_)
462            | PathSource::DefineOpaques
463            | PathSource::Module => TypeNS,
464            PathSource::Expr(..)
465            | PathSource::Pat
466            | PathSource::TupleStruct(..)
467            | PathSource::Delegation
468            | PathSource::ExternItemImpl
469            | PathSource::ReturnTypeNotation => ValueNS,
470            PathSource::TraitItem(ns, _) => ns,
471            PathSource::PreciseCapturingArg(ns) => ns,
472            PathSource::Macro => MacroNS,
473        }
474    }
475
476    fn defer_to_typeck(self) -> bool {
477        match self {
478            PathSource::Type
479            | PathSource::Expr(..)
480            | PathSource::Pat
481            | PathSource::Struct(_)
482            | PathSource::TupleStruct(..)
483            | PathSource::ReturnTypeNotation => true,
484            PathSource::Trait(_)
485            | PathSource::TraitItem(..)
486            | PathSource::DefineOpaques
487            | PathSource::Delegation
488            | PathSource::ExternItemImpl
489            | PathSource::PreciseCapturingArg(..)
490            | PathSource::Macro
491            | PathSource::Module => false,
492        }
493    }
494
495    fn descr_expected(self) -> &'static str {
496        match &self {
497            PathSource::DefineOpaques => "type alias or associated type with opaqaue types",
498            PathSource::Type => "type",
499            PathSource::Trait(_) => "trait",
500            PathSource::Pat => "unit struct, unit variant or constant",
501            PathSource::Struct(_) => "struct, variant or union type",
502            PathSource::TraitItem(ValueNS, PathSource::TupleStruct(..))
503            | PathSource::TupleStruct(..) => "tuple struct or tuple variant",
504            PathSource::TraitItem(ns, _) => match ns {
505                TypeNS => "associated type",
506                ValueNS => "method or associated constant",
507                MacroNS => ::rustc_middle::util::bug::bug_fmt(format_args!("associated macro"))bug!("associated macro"),
508            },
509            PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
510                // "function" here means "anything callable" rather than `DefKind::Fn`,
511                // this is not precise but usually more helpful than just "value".
512                Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
513                    // the case of `::some_crate()`
514                    ExprKind::Path(_, path)
515                        if let [segment, _] = path.segments.as_slice()
516                            && segment.ident.name == kw::PathRoot =>
517                    {
518                        "external crate"
519                    }
520                    ExprKind::Path(_, path)
521                        if let Some(segment) = path.segments.last()
522                            && let Some(c) = segment.ident.to_string().chars().next()
523                            && c.is_uppercase() =>
524                    {
525                        "function, tuple struct or tuple variant"
526                    }
527                    _ => "function",
528                },
529                _ => "value",
530            },
531            PathSource::ReturnTypeNotation | PathSource::Delegation => "function",
532            PathSource::ExternItemImpl => "function or static",
533            PathSource::PreciseCapturingArg(..) => "type or const parameter",
534            PathSource::Macro => "macro",
535            PathSource::Module => "module",
536        }
537    }
538
539    fn is_call(self) -> bool {
540        #[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(..), .. })))
541    }
542
543    pub(crate) fn is_expected(self, res: Res) -> bool {
544        match self {
545            PathSource::DefineOpaques => {
546                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum |
        DefKind::TyAlias | DefKind::AssocTy, _) | Res::SelfTyAlias { .. } =>
        true,
    _ => false,
}matches!(
547                    res,
548                    Res::Def(
549                        DefKind::Struct
550                            | DefKind::Union
551                            | DefKind::Enum
552                            | DefKind::TyAlias
553                            | DefKind::AssocTy,
554                        _
555                    ) | Res::SelfTyAlias { .. }
556                )
557            }
558            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!(
559                res,
560                Res::Def(
561                    DefKind::Struct
562                        | DefKind::Union
563                        | DefKind::Enum
564                        | DefKind::Trait
565                        | DefKind::TraitAlias
566                        | DefKind::TyAlias
567                        | DefKind::AssocTy
568                        | DefKind::TyParam
569                        | DefKind::OpaqueTy
570                        | DefKind::ForeignTy,
571                    _,
572                ) | Res::PrimTy(..)
573                    | Res::SelfTyParam { .. }
574                    | Res::SelfTyAlias { .. }
575            ),
576            PathSource::Trait(AliasPossibility::No) => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Trait, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Trait, _)),
577            PathSource::Trait(AliasPossibility::Maybe) => {
578                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
579            }
580            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!(
581                res,
582                Res::Def(
583                    DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
584                        | DefKind::Const { .. }
585                        | DefKind::Static { .. }
586                        | DefKind::Fn
587                        | DefKind::AssocFn
588                        | DefKind::AssocConst { .. }
589                        | DefKind::ConstParam,
590                    _,
591                ) | Res::Local(..)
592                    | Res::SelfCtor(..)
593            ),
594            PathSource::Pat => {
595                res.expected_in_unit_struct_pat()
596                    || #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Const { .. } | DefKind::AssocConst { .. }, _) => true,
    _ => false,
}matches!(
597                        res,
598                        Res::Def(DefKind::Const { .. } | DefKind::AssocConst { .. }, _)
599                    )
600            }
601            PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
602            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!(
603                res,
604                Res::Def(
605                    DefKind::Struct
606                        | DefKind::Union
607                        | DefKind::Variant
608                        | DefKind::TyAlias
609                        | DefKind::AssocTy,
610                    _,
611                ) | Res::SelfTyParam { .. }
612                    | Res::SelfTyAlias { .. }
613            ),
614            PathSource::TraitItem(ns, _) => match res {
615                Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn, _) if ns == ValueNS => true,
616                Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
617                _ => false,
618            },
619            PathSource::ReturnTypeNotation => match res {
620                Res::Def(DefKind::AssocFn, _) => true,
621                _ => false,
622            },
623            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, _)),
624            PathSource::ExternItemImpl => {
625                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) |
        DefKind::Static { .. }, _) => true,
    _ => false,
}matches!(
626                    res,
627                    Res::Def(
628                        DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::Static { .. },
629                        _
630                    )
631                )
632            }
633            PathSource::PreciseCapturingArg(ValueNS) => {
634                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::ConstParam, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::ConstParam, _))
635            }
636            // We allow `SelfTyAlias` here so we can give a more descriptive error later.
637            PathSource::PreciseCapturingArg(TypeNS) => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } |
        Res::SelfTyAlias { .. } => true,
    _ => false,
}matches!(
638                res,
639                Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }
640            ),
641            PathSource::PreciseCapturingArg(MacroNS) => false,
642            PathSource::Macro => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Macro(_), _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Macro(_), _)),
643            PathSource::Module => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Mod, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Mod, _)),
644        }
645    }
646
647    fn error_code(self, has_unexpected_resolution: bool) -> ErrCode {
648        match (self, has_unexpected_resolution) {
649            (PathSource::Trait(_), true) => E0404,
650            (PathSource::Trait(_), false) => E0405,
651            (PathSource::Type | PathSource::DefineOpaques, true) => E0573,
652            (PathSource::Type | PathSource::DefineOpaques, false) => E0425,
653            (PathSource::Struct(_), true) => E0574,
654            (PathSource::Struct(_), false) => E0422,
655            (PathSource::Expr(..), true)
656            | (PathSource::Delegation, true)
657            | (PathSource::ExternItemImpl, true) => E0423,
658            (PathSource::Expr(..), false)
659            | (PathSource::Delegation, false)
660            | (PathSource::ExternItemImpl, false) => E0425,
661            (PathSource::Pat | PathSource::TupleStruct(..), true) => E0532,
662            (PathSource::Pat | PathSource::TupleStruct(..), false) => E0531,
663            (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, true) => E0575,
664            (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, false) => E0576,
665            (PathSource::PreciseCapturingArg(..), true) => E0799,
666            (PathSource::PreciseCapturingArg(..), false) => E0800,
667            (PathSource::Macro, _) => E0425,
668            // FIXME: There is no dedicated error code for this case yet.
669            // E0577 already covers the same situation for visibilities,
670            // so we reuse it here for now. It may make sense to generalize
671            // it for restrictions in the future.
672            (PathSource::Module, true) => E0577,
673            (PathSource::Module, false) => E0433,
674        }
675    }
676}
677
678/// At this point for most items we can answer whether that item is exported or not,
679/// but some items like impls require type information to determine exported-ness, so we make a
680/// conservative estimate for them (e.g. based on nominal visibility).
681#[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)]
682enum MaybeExported<'a> {
683    Ok(NodeId),
684    Impl(Option<DefId>),
685    ImplItem(Result<DefId, &'a ast::Visibility>),
686    NestedUse(&'a ast::Visibility),
687}
688
689impl MaybeExported<'_> {
690    fn eval(self, r: &Resolver<'_, '_>) -> bool {
691        let def_id = match self {
692            MaybeExported::Ok(node_id) => Some(r.local_def_id(node_id)),
693            MaybeExported::Impl(Some(trait_def_id)) | MaybeExported::ImplItem(Ok(trait_def_id)) => {
694                trait_def_id.as_local()
695            }
696            MaybeExported::Impl(None) => return true,
697            MaybeExported::ImplItem(Err(vis)) | MaybeExported::NestedUse(vis) => {
698                return vis.kind.is_pub();
699            }
700        };
701        def_id.is_none_or(|def_id| r.effective_visibilities.is_exported(def_id))
702    }
703}
704
705/// Used for recording UnnecessaryQualification.
706#[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)]
707pub(crate) struct UnnecessaryQualification<'ra> {
708    pub decl: LateDecl<'ra>,
709    pub node_id: NodeId,
710    pub path_span: Span,
711    pub removal_span: Span,
712}
713
714#[derive(#[automatically_derived]
impl<'ast> ::core::default::Default for DiagMetadata<'ast> {
    #[inline]
    fn default() -> DiagMetadata<'ast> {
        DiagMetadata {
            current_trait_assoc_items: ::core::default::Default::default(),
            current_self_type: ::core::default::Default::default(),
            current_self_item: ::core::default::Default::default(),
            current_item: ::core::default::Default::default(),
            currently_processing_generic_args: ::core::default::Default::default(),
            current_function: ::core::default::Default::default(),
            unused_labels: ::core::default::Default::default(),
            current_let_binding: ::core::default::Default::default(),
            current_pat: ::core::default::Default::default(),
            in_if_condition: ::core::default::Default::default(),
            in_assignment: ::core::default::Default::default(),
            is_assign_rhs: ::core::default::Default::default(),
            in_non_gat_assoc_type: ::core::default::Default::default(),
            in_range: ::core::default::Default::default(),
            current_trait_object: ::core::default::Default::default(),
            current_where_predicate: ::core::default::Default::default(),
            current_type_path: ::core::default::Default::default(),
            current_impl_items: ::core::default::Default::default(),
            current_impl_item: ::core::default::Default::default(),
            currently_processing_impl_trait: ::core::default::Default::default(),
            current_elision_failures: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]
impl<'ast> ::core::fmt::Debug for DiagMetadata<'ast> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["current_trait_assoc_items", "current_self_type",
                        "current_self_item", "current_item",
                        "currently_processing_generic_args", "current_function",
                        "unused_labels", "current_let_binding", "current_pat",
                        "in_if_condition", "in_assignment", "is_assign_rhs",
                        "in_non_gat_assoc_type", "in_range", "current_trait_object",
                        "current_where_predicate", "current_type_path",
                        "current_impl_items", "current_impl_item",
                        "currently_processing_impl_trait",
                        "current_elision_failures"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.current_trait_assoc_items, &self.current_self_type,
                        &self.current_self_item, &self.current_item,
                        &self.currently_processing_generic_args,
                        &self.current_function, &self.unused_labels,
                        &self.current_let_binding, &self.current_pat,
                        &self.in_if_condition, &self.in_assignment,
                        &self.is_assign_rhs, &self.in_non_gat_assoc_type,
                        &self.in_range, &self.current_trait_object,
                        &self.current_where_predicate, &self.current_type_path,
                        &self.current_impl_items, &self.current_impl_item,
                        &self.currently_processing_impl_trait,
                        &&self.current_elision_failures];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "DiagMetadata",
            names, values)
    }
}Debug)]
715pub(crate) struct DiagMetadata<'ast> {
716    /// The current trait's associated items' ident, used for diagnostic suggestions.
717    current_trait_assoc_items: Option<&'ast [Box<AssocItem>]>,
718
719    /// The current self type if inside an impl (used for better errors).
720    pub(crate) current_self_type: Option<Ty>,
721
722    /// The current self item if inside an ADT (used for better errors).
723    current_self_item: Option<NodeId>,
724
725    /// The current item being evaluated (used for suggestions and more detail in errors).
726    pub(crate) current_item: Option<&'ast Item>,
727
728    /// When processing generic arguments and encountering an unresolved ident not found,
729    /// suggest introducing a type or const param depending on the context.
730    currently_processing_generic_args: bool,
731
732    /// The current enclosing (non-closure) function (used for better errors).
733    current_function: Option<(FnKind<'ast>, Span)>,
734
735    /// A list of labels as of yet unused. Labels will be removed from this map when
736    /// they are used (in a `break` or `continue` statement)
737    unused_labels: FxIndexMap<NodeId, Span>,
738
739    /// Only used for better errors on `let <pat>: <expr, not type>;`.
740    current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
741
742    current_pat: Option<&'ast Pat>,
743
744    /// Used to detect possible `if let` written without `let` and to provide structured suggestion.
745    in_if_condition: Option<&'ast Expr>,
746
747    /// Used to detect possible new binding written without `let` and to provide structured suggestion.
748    in_assignment: Option<&'ast Expr>,
749    is_assign_rhs: bool,
750
751    /// If we are setting an associated type in trait impl, is it a non-GAT type?
752    in_non_gat_assoc_type: Option<bool>,
753
754    /// Used to detect possible `.` -> `..` typo when calling methods.
755    in_range: Option<(&'ast Expr, &'ast Expr)>,
756
757    /// If we are currently in a trait object definition. Used to point at the bounds when
758    /// encountering a struct or enum.
759    current_trait_object: Option<&'ast [ast::GenericBound]>,
760
761    /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
762    current_where_predicate: Option<&'ast WherePredicate>,
763
764    current_type_path: Option<&'ast Ty>,
765
766    /// The current impl items (used to suggest).
767    current_impl_items: Option<&'ast [Box<AssocItem>]>,
768
769    /// The current impl items (used to suggest).
770    current_impl_item: Option<&'ast AssocItem>,
771
772    /// When processing impl trait
773    currently_processing_impl_trait: Option<(TraitRef, Ty)>,
774
775    /// Accumulate the errors due to missed lifetime elision,
776    /// and report them all at once for each function.
777    current_elision_failures:
778        Vec<(MissingLifetime, LifetimeElisionCandidate, Either<NodeId, Range<NodeId>>)>,
779}
780
781struct LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
782    r: &'a mut Resolver<'ra, 'tcx>,
783
784    /// The module that represents the current item scope.
785    parent_scope: ParentScope<'ra>,
786
787    /// The current set of local scopes for types and values.
788    ribs: PerNS<Vec<Rib<'ra>>>,
789
790    /// Previous popped `rib`, only used for diagnostic.
791    last_block_rib: Option<Rib<'ra>>,
792
793    /// The current set of local scopes, for labels.
794    label_ribs: Vec<Rib<'ra, NodeId>>,
795
796    /// The current set of local scopes for lifetimes.
797    lifetime_ribs: Vec<LifetimeRib>,
798
799    /// We are looking for lifetimes in an elision context.
800    /// The set contains all the resolutions that we encountered so far.
801    /// They will be used to determine the correct lifetime for the fn return type.
802    /// The `LifetimeElisionCandidate` is used for diagnostics, to suggest introducing named
803    /// lifetimes.
804    lifetime_elision_candidates: Option<Vec<(LifetimeRes, LifetimeElisionCandidate)>>,
805
806    /// The trait that the current context can refer to.
807    current_trait_ref: Option<(Module<'ra>, TraitRef)>,
808
809    /// Fields used to add information to diagnostic errors.
810    diag_metadata: Box<DiagMetadata<'ast>>,
811
812    /// State used to know whether to ignore resolution errors for function bodies.
813    ///
814    /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
815    /// In most cases this will be `None`, in which case errors will always be reported.
816    /// If it is `true`, then it will be updated when entering a nested function or trait body.
817    in_func_body: bool,
818
819    /// Count the number of places a lifetime is used.
820    lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
821}
822
823/// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
824impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
825    fn visit_attribute(&mut self, _: &'ast Attribute) {
826        // We do not want to resolve expressions that appear in attributes,
827        // as they do not correspond to actual code.
828    }
829    fn visit_item(&mut self, item: &'ast Item) {
830        let prev = replace(&mut self.diag_metadata.current_item, Some(item));
831        // Always report errors in items we just entered.
832        let old_ignore = replace(&mut self.in_func_body, false);
833        self.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item));
834        self.in_func_body = old_ignore;
835        self.diag_metadata.current_item = prev;
836    }
837    fn visit_arm(&mut self, arm: &'ast Arm) {
838        self.resolve_arm(arm);
839    }
840    fn visit_block(&mut self, block: &'ast Block) {
841        let old_macro_rules = self.parent_scope.macro_rules;
842        self.resolve_block(block);
843        self.parent_scope.macro_rules = old_macro_rules;
844    }
845    fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
846        ::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:#?}");
847    }
848    fn visit_expr(&mut self, expr: &'ast Expr) {
849        self.resolve_expr(expr, None);
850    }
851    fn visit_pat(&mut self, p: &'ast Pat) {
852        let prev = self.diag_metadata.current_pat;
853        self.diag_metadata.current_pat = Some(p);
854
855        if let PatKind::Guard(subpat, _) = &p.kind {
856            // We walk the guard expression in `resolve_pattern_inner`. Don't resolve it twice.
857            self.visit_pat(subpat);
858        } else {
859            visit::walk_pat(self, p);
860        }
861
862        self.diag_metadata.current_pat = prev;
863    }
864    fn visit_local(&mut self, local: &'ast Local) {
865        let local_spans = match local.pat.kind {
866            // We check for this to avoid tuple struct fields.
867            PatKind::Wild => None,
868            _ => Some((
869                local.pat.span,
870                local.ty.as_ref().map(|ty| ty.span),
871                local.kind.init().map(|init| init.span),
872            )),
873        };
874        let original = replace(&mut self.diag_metadata.current_let_binding, local_spans);
875        self.resolve_local(local);
876        self.diag_metadata.current_let_binding = original;
877    }
878    fn visit_ty(&mut self, ty: &'ast Ty) {
879        let prev = self.diag_metadata.current_trait_object;
880        let prev_ty = self.diag_metadata.current_type_path;
881        match &ty.kind {
882            TyKind::Ref(None, _) | TyKind::PinnedRef(None, _) => {
883                // Elided lifetime in reference: we resolve as if there was some lifetime `'_` with
884                // NodeId `ty.id`.
885                // This span will be used in case of elision failure.
886                let span = self.r.tcx.sess.source_map().start_point(ty.span);
887                self.resolve_elided_lifetime(ty.id, span);
888                visit::walk_ty(self, ty);
889            }
890            TyKind::Path(qself, path) => {
891                self.diag_metadata.current_type_path = Some(ty);
892
893                // If we have a path that ends with `(..)`, then it must be
894                // return type notation. Resolve that path in the *value*
895                // namespace.
896                let source = if let Some(seg) = path.segments.last()
897                    && let Some(args) = &seg.args
898                    && #[allow(non_exhaustive_omitted_patterns)] match **args {
    GenericArgs::ParenthesizedElided(..) => true,
    _ => false,
}matches!(**args, GenericArgs::ParenthesizedElided(..))
899                {
900                    PathSource::ReturnTypeNotation
901                } else {
902                    PathSource::Type
903                };
904
905                self.smart_resolve_path(ty.id, qself, path, source);
906
907                // Check whether we should interpret this as a bare trait object.
908                if qself.is_none()
909                    && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
910                    && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) =
911                        partial_res.full_res()
912                {
913                    // This path is actually a bare trait object. In case of a bare `Fn`-trait
914                    // object with anonymous lifetimes, we need this rib to correctly place the
915                    // synthetic lifetimes.
916                    let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
917                    self.with_generic_param_rib(
918                        &[],
919                        RibKind::Normal,
920                        ty.id,
921                        LifetimeBinderKind::PolyTrait,
922                        span,
923                        |this| this.visit_path(path),
924                    );
925                } else {
926                    visit::walk_ty(self, ty)
927                }
928            }
929            TyKind::ImplicitSelf => {
930                let self_ty = Ident::with_dummy_span(kw::SelfUpper);
931                let res = self
932                    .resolve_ident_in_lexical_scope(
933                        self_ty,
934                        TypeNS,
935                        Some(Finalize::new(ty.id, ty.span)),
936                        None,
937                    )
938                    .map_or(Res::Err, |d| d.res());
939                self.r.record_partial_res(ty.id, PartialRes::new(res));
940                visit::walk_ty(self, ty)
941            }
942            TyKind::ImplTrait(..) => {
943                let candidates = self.lifetime_elision_candidates.take();
944                visit::walk_ty(self, ty);
945                self.lifetime_elision_candidates = candidates;
946            }
947            TyKind::TraitObject(bounds, ..) => {
948                self.diag_metadata.current_trait_object = Some(&bounds[..]);
949                visit::walk_ty(self, ty)
950            }
951            TyKind::FnPtr(fn_ptr) => {
952                let span = ty.span.shrink_to_lo().to(fn_ptr.decl_span.shrink_to_lo());
953                self.with_generic_param_rib(
954                    &fn_ptr.generic_params,
955                    RibKind::Normal,
956                    ty.id,
957                    LifetimeBinderKind::FnPtrType,
958                    span,
959                    |this| {
960                        this.visit_generic_params(&fn_ptr.generic_params, false);
961                        this.resolve_fn_signature(
962                            ty.id,
963                            false,
964                            // We don't need to deal with patterns in parameters, because
965                            // they are not possible for foreign or bodiless functions.
966                            fn_ptr.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
967                            &fn_ptr.decl.output,
968                            false,
969                        )
970                    },
971                )
972            }
973            TyKind::UnsafeBinder(unsafe_binder) => {
974                let span = ty.span.shrink_to_lo().to(unsafe_binder.inner_ty.span.shrink_to_lo());
975                self.with_generic_param_rib(
976                    &unsafe_binder.generic_params,
977                    RibKind::Normal,
978                    ty.id,
979                    LifetimeBinderKind::FnPtrType,
980                    span,
981                    |this| {
982                        this.visit_generic_params(&unsafe_binder.generic_params, false);
983                        this.with_lifetime_rib(
984                            // We don't allow anonymous `unsafe &'_ ()` binders,
985                            // although I guess we could.
986                            LifetimeRibKind::AnonymousReportError,
987                            |this| this.visit_ty(&unsafe_binder.inner_ty),
988                        );
989                    },
990                )
991            }
992            TyKind::Array(element_ty, length) => {
993                self.visit_ty(element_ty);
994                self.resolve_anon_const(length, AnonConstKind::ConstArg(IsRepeatExpr::No));
995            }
996            _ => visit::walk_ty(self, ty),
997        }
998        self.diag_metadata.current_trait_object = prev;
999        self.diag_metadata.current_type_path = prev_ty;
1000    }
1001
1002    fn visit_ty_pat(&mut self, t: &'ast TyPat) -> Self::Result {
1003        match &t.kind {
1004            TyPatKind::Range(start, end, _) => {
1005                if let Some(start) = start {
1006                    self.resolve_anon_const(start, AnonConstKind::ConstArg(IsRepeatExpr::No));
1007                }
1008                if let Some(end) = end {
1009                    self.resolve_anon_const(end, AnonConstKind::ConstArg(IsRepeatExpr::No));
1010                }
1011            }
1012            TyPatKind::Or(patterns) => {
1013                for pat in patterns {
1014                    self.visit_ty_pat(pat)
1015                }
1016            }
1017            TyPatKind::NotNull | TyPatKind::Err(_) => {}
1018        }
1019    }
1020
1021    fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
1022        let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
1023        self.with_generic_param_rib(
1024            &tref.bound_generic_params,
1025            RibKind::Normal,
1026            tref.trait_ref.ref_id,
1027            LifetimeBinderKind::PolyTrait,
1028            span,
1029            |this| {
1030                this.visit_generic_params(&tref.bound_generic_params, false);
1031                this.smart_resolve_path(
1032                    tref.trait_ref.ref_id,
1033                    &None,
1034                    &tref.trait_ref.path,
1035                    PathSource::Trait(AliasPossibility::Maybe),
1036                );
1037                this.visit_trait_ref(&tref.trait_ref);
1038            },
1039        );
1040    }
1041    fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
1042        self.resolve_doc_links(&foreign_item.attrs, MaybeExported::Ok(foreign_item.id));
1043        let def_kind = self.r.local_def_kind(foreign_item.id);
1044        match foreign_item.kind {
1045            ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
1046                self.with_generic_param_rib(
1047                    &generics.params,
1048                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1049                    foreign_item.id,
1050                    LifetimeBinderKind::Item,
1051                    generics.span,
1052                    |this| visit::walk_item(this, foreign_item),
1053                );
1054            }
1055            ForeignItemKind::Fn(box Fn { ref generics, .. }) => {
1056                self.with_generic_param_rib(
1057                    &generics.params,
1058                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1059                    foreign_item.id,
1060                    LifetimeBinderKind::Function,
1061                    generics.span,
1062                    |this| visit::walk_item(this, foreign_item),
1063                );
1064            }
1065            ForeignItemKind::Static(..) => {
1066                self.with_static_rib(def_kind, |this| visit::walk_item(this, foreign_item))
1067            }
1068            ForeignItemKind::MacCall(..) => {
1069                {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
1070            }
1071        }
1072    }
1073    fn visit_fn(&mut self, fn_kind: FnKind<'ast>, _: &AttrVec, sp: Span, fn_id: NodeId) {
1074        let previous_value = self.diag_metadata.current_function;
1075        match fn_kind {
1076            // Bail if the function is foreign, and thus cannot validly have
1077            // a body, or if there's no body for some other reason.
1078            FnKind::Fn(FnCtxt::Foreign, _, Fn { sig, ident, generics, .. })
1079            | FnKind::Fn(_, _, Fn { sig, ident, generics, body: None, .. }) => {
1080                self.visit_fn_header(&sig.header);
1081                self.visit_ident(ident);
1082                self.visit_generics(generics);
1083                self.resolve_fn_signature(
1084                    fn_id,
1085                    sig.decl.has_self(),
1086                    sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1087                    &sig.decl.output,
1088                    false,
1089                );
1090                return;
1091            }
1092            FnKind::Fn(..) => {
1093                self.diag_metadata.current_function = Some((fn_kind, sp));
1094            }
1095            // Do not update `current_function` for closures: it suggests `self` parameters.
1096            FnKind::Closure(..) => {}
1097        };
1098        {
    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:1098",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1098u32),
                        ::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");
1099
1100        if let FnKind::Fn(_, _, f) = fn_kind {
1101            self.resolve_eii(&f.eii_impls);
1102        }
1103
1104        // Create a value rib for the function.
1105        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
1106            // Create a label rib for the function.
1107            this.with_label_rib(RibKind::FnOrCoroutine, |this| {
1108                match fn_kind {
1109                    FnKind::Fn(_, _, Fn { sig, generics, contract, body, .. }) => {
1110                        this.visit_generics(generics);
1111
1112                        let declaration = &sig.decl;
1113                        let coro_node_id = sig
1114                            .header
1115                            .coroutine_kind
1116                            .map(|coroutine_kind| coroutine_kind.return_id());
1117
1118                        this.resolve_fn_signature(
1119                            fn_id,
1120                            declaration.has_self(),
1121                            declaration
1122                                .inputs
1123                                .iter()
1124                                .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
1125                            &declaration.output,
1126                            coro_node_id.is_some(),
1127                        );
1128
1129                        if let Some(contract) = contract {
1130                            this.visit_contract(contract);
1131                        }
1132
1133                        if let Some(body) = body {
1134                            // Ignore errors in function bodies if this is rustdoc
1135                            // Be sure not to set this until the function signature has been resolved.
1136                            let previous_state = replace(&mut this.in_func_body, true);
1137                            // We only care block in the same function
1138                            this.last_block_rib = None;
1139                            // Resolve the function body, potentially inside the body of an async closure
1140                            this.with_lifetime_rib(
1141                                LifetimeRibKind::Elided(LifetimeRes::Infer),
1142                                |this| this.visit_block(body),
1143                            );
1144
1145                            {
    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:1145",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1145u32),
                        ::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");
1146                            this.in_func_body = previous_state;
1147                        }
1148                    }
1149                    FnKind::Closure(binder, _, declaration, body) => {
1150                        this.visit_closure_binder(binder);
1151
1152                        this.with_lifetime_rib(
1153                            match binder {
1154                                // We do not have any explicit generic lifetime parameter.
1155                                ClosureBinder::NotPresent => {
1156                                    LifetimeRibKind::AnonymousCreateParameter {
1157                                        binder: fn_id,
1158                                        report_in_path: false,
1159                                    }
1160                                }
1161                                ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1162                            },
1163                            // Add each argument to the rib.
1164                            |this| this.resolve_params(&declaration.inputs),
1165                        );
1166                        this.with_lifetime_rib(
1167                            match binder {
1168                                ClosureBinder::NotPresent => {
1169                                    LifetimeRibKind::Elided(LifetimeRes::Infer)
1170                                }
1171                                ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1172                            },
1173                            |this| visit::walk_fn_ret_ty(this, &declaration.output),
1174                        );
1175
1176                        // Ignore errors in function bodies if this is rustdoc
1177                        // Be sure not to set this until the function signature has been resolved.
1178                        let previous_state = replace(&mut this.in_func_body, true);
1179                        // Resolve the function body, potentially inside the body of an async closure
1180                        this.with_lifetime_rib(
1181                            LifetimeRibKind::Elided(LifetimeRes::Infer),
1182                            |this| this.visit_expr(body),
1183                        );
1184
1185                        {
    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:1185",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1185u32),
                        ::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");
1186                        this.in_func_body = previous_state;
1187                    }
1188                }
1189            })
1190        });
1191        self.diag_metadata.current_function = previous_value;
1192    }
1193
1194    fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1195        self.resolve_lifetime(lifetime, use_ctxt)
1196    }
1197
1198    fn visit_precise_capturing_arg(&mut self, arg: &'ast PreciseCapturingArg) {
1199        match arg {
1200            // Lower the lifetime regularly; we'll resolve the lifetime and check
1201            // it's a parameter later on in HIR lowering.
1202            PreciseCapturingArg::Lifetime(_) => {}
1203
1204            PreciseCapturingArg::Arg(path, id) => {
1205                // we want `impl use<C>` to try to resolve `C` as both a type parameter or
1206                // a const parameter. Since the resolver specifically doesn't allow having
1207                // two generic params with the same name, even if they're a different namespace,
1208                // it doesn't really matter which we try resolving first, but just like
1209                // `Ty::Param` we just fall back to the value namespace only if it's missing
1210                // from the type namespace.
1211                let mut check_ns = |ns| {
1212                    self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns).is_some()
1213                };
1214                // Like `Ty::Param`, we try resolving this as both a const and a type.
1215                if !check_ns(TypeNS) && check_ns(ValueNS) {
1216                    self.smart_resolve_path(
1217                        *id,
1218                        &None,
1219                        path,
1220                        PathSource::PreciseCapturingArg(ValueNS),
1221                    );
1222                } else {
1223                    self.smart_resolve_path(
1224                        *id,
1225                        &None,
1226                        path,
1227                        PathSource::PreciseCapturingArg(TypeNS),
1228                    );
1229                }
1230            }
1231        }
1232
1233        visit::walk_precise_capturing_arg(self, arg)
1234    }
1235
1236    fn visit_generics(&mut self, generics: &'ast Generics) {
1237        self.visit_generic_params(&generics.params, self.diag_metadata.current_self_item.is_some());
1238        for p in &generics.where_clause.predicates {
1239            self.visit_where_predicate(p);
1240        }
1241    }
1242
1243    fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
1244        match b {
1245            ClosureBinder::NotPresent => {}
1246            ClosureBinder::For { generic_params, .. } => {
1247                self.visit_generic_params(
1248                    generic_params,
1249                    self.diag_metadata.current_self_item.is_some(),
1250                );
1251            }
1252        }
1253    }
1254
1255    fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
1256        {
    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:1256",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1256u32),
                        ::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);
1257        let prev = replace(&mut self.diag_metadata.currently_processing_generic_args, true);
1258        match arg {
1259            GenericArg::Type(ty) => {
1260                // We parse const arguments as path types as we cannot distinguish them during
1261                // parsing. We try to resolve that ambiguity by attempting resolution the type
1262                // namespace first, and if that fails we try again in the value namespace. If
1263                // resolution in the value namespace succeeds, we have an generic const argument on
1264                // our hands.
1265                if let TyKind::Path(None, ref path) = ty.kind
1266                    // We cannot disambiguate multi-segment paths right now as that requires type
1267                    // checking.
1268                    && path.is_potential_trivial_const_arg()
1269                {
1270                    let mut check_ns = |ns| {
1271                        self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
1272                            .is_some()
1273                    };
1274                    if !check_ns(TypeNS) && check_ns(ValueNS) {
1275                        self.resolve_anon_const_manual(
1276                            true,
1277                            AnonConstKind::ConstArg(IsRepeatExpr::No),
1278                            |this| {
1279                                this.smart_resolve_path(ty.id, &None, path, PathSource::Expr(None));
1280                                this.visit_path(path);
1281                            },
1282                        );
1283
1284                        self.diag_metadata.currently_processing_generic_args = prev;
1285                        return;
1286                    }
1287                }
1288
1289                self.visit_ty(ty);
1290            }
1291            GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1292            GenericArg::Const(ct) => {
1293                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
1294            }
1295        }
1296        self.diag_metadata.currently_processing_generic_args = prev;
1297    }
1298
1299    fn visit_assoc_item_constraint(&mut self, constraint: &'ast AssocItemConstraint) {
1300        self.visit_ident(&constraint.ident);
1301        if let Some(ref gen_args) = constraint.gen_args {
1302            // Forbid anonymous lifetimes in GAT parameters until proper semantics are decided.
1303            self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1304                this.visit_generic_args(gen_args)
1305            });
1306        }
1307        match constraint.kind {
1308            AssocItemConstraintKind::Equality { ref term } => match term {
1309                Term::Ty(ty) => self.visit_ty(ty),
1310                Term::Const(c) => {
1311                    self.resolve_anon_const(c, AnonConstKind::ConstArg(IsRepeatExpr::No))
1312                }
1313            },
1314            AssocItemConstraintKind::Bound { ref bounds } => {
1315                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);
1316            }
1317        }
1318    }
1319
1320    fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1321        let Some(ref args) = path_segment.args else {
1322            return;
1323        };
1324
1325        match &**args {
1326            GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1327            GenericArgs::Parenthesized(p_args) => {
1328                // Probe the lifetime ribs to know how to behave.
1329                for rib in self.lifetime_ribs.iter().rev() {
1330                    match rib.kind {
1331                        // We are inside a `PolyTraitRef`. The lifetimes are
1332                        // to be introduced in that (maybe implicit) `for<>` binder.
1333                        LifetimeRibKind::Generics {
1334                            binder,
1335                            kind: LifetimeBinderKind::PolyTrait,
1336                            ..
1337                        } => {
1338                            self.resolve_fn_signature(
1339                                binder,
1340                                false,
1341                                p_args.inputs.iter().map(|ty| (None, &**ty)),
1342                                &p_args.output,
1343                                false,
1344                            );
1345                            break;
1346                        }
1347                        // We have nowhere to introduce generics. Code is malformed,
1348                        // so use regular lifetime resolution to avoid spurious errors.
1349                        LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1350                            visit::walk_generic_args(self, args);
1351                            break;
1352                        }
1353                        LifetimeRibKind::AnonymousCreateParameter { .. }
1354                        | LifetimeRibKind::AnonymousReportError
1355                        | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1356                        | LifetimeRibKind::Elided(_)
1357                        | LifetimeRibKind::ElisionFailure
1358                        | LifetimeRibKind::ConcreteAnonConst(_)
1359                        | LifetimeRibKind::ConstParamTy => {}
1360                    }
1361                }
1362            }
1363            GenericArgs::ParenthesizedElided(_) => {}
1364        }
1365    }
1366
1367    fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1368        {
    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:1368",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1368u32),
                        ::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);
1369        let previous_value = replace(&mut self.diag_metadata.current_where_predicate, Some(p));
1370        self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1371            if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1372                bounded_ty,
1373                bounds,
1374                bound_generic_params,
1375                ..
1376            }) = &p.kind
1377            {
1378                let span = p.span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1379                this.with_generic_param_rib(
1380                    bound_generic_params,
1381                    RibKind::Normal,
1382                    bounded_ty.id,
1383                    LifetimeBinderKind::WhereBound,
1384                    span,
1385                    |this| {
1386                        this.visit_generic_params(bound_generic_params, false);
1387                        this.visit_ty(bounded_ty);
1388                        for bound in bounds {
1389                            this.visit_param_bound(bound, BoundKind::Bound)
1390                        }
1391                    },
1392                );
1393            } else {
1394                visit::walk_where_predicate(this, p);
1395            }
1396        });
1397        self.diag_metadata.current_where_predicate = previous_value;
1398    }
1399
1400    fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1401        for (op, _) in &asm.operands {
1402            match op {
1403                InlineAsmOperand::In { expr, .. }
1404                | InlineAsmOperand::Out { expr: Some(expr), .. }
1405                | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1406                InlineAsmOperand::Out { expr: None, .. } => {}
1407                InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1408                    self.visit_expr(in_expr);
1409                    if let Some(out_expr) = out_expr {
1410                        self.visit_expr(out_expr);
1411                    }
1412                }
1413                InlineAsmOperand::Const { anon_const, .. } => {
1414                    // Although this is `DefKind::AnonConst`, it is allowed to reference outer
1415                    // generic parameters like an inline const.
1416                    self.resolve_anon_const(anon_const, AnonConstKind::InlineConst);
1417                }
1418                InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1419                InlineAsmOperand::Label { block } => self.visit_block(block),
1420            }
1421        }
1422    }
1423
1424    fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1425        // This is similar to the code for AnonConst.
1426        self.with_rib(ValueNS, RibKind::InlineAsmSym, |this| {
1427            this.with_rib(TypeNS, RibKind::InlineAsmSym, |this| {
1428                this.with_label_rib(RibKind::InlineAsmSym, |this| {
1429                    this.smart_resolve_path(sym.id, &sym.qself, &sym.path, PathSource::Expr(None));
1430                    visit::walk_inline_asm_sym(this, sym);
1431                });
1432            })
1433        });
1434    }
1435
1436    fn visit_variant(&mut self, v: &'ast Variant) {
1437        self.resolve_doc_links(&v.attrs, MaybeExported::Ok(v.id));
1438        self.visit_id(v.id);
1439        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);
1440        self.visit_vis(&v.vis);
1441        self.visit_ident(&v.ident);
1442        self.visit_variant_data(&v.data);
1443        if let Some(discr) = &v.disr_expr {
1444            self.resolve_anon_const(discr, AnonConstKind::EnumDiscriminant);
1445        }
1446    }
1447
1448    fn visit_field_def(&mut self, f: &'ast FieldDef) {
1449        self.resolve_doc_links(&f.attrs, MaybeExported::Ok(f.id));
1450        let FieldDef {
1451            attrs,
1452            id: _,
1453            span: _,
1454            vis,
1455            ident,
1456            ty,
1457            is_placeholder: _,
1458            default,
1459            safety: _,
1460        } = f;
1461        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);
1462        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));
1463        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);
1464        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));
1465        if let Some(v) = &default {
1466            self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);
1467        }
1468    }
1469}
1470
1471impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1472    fn new(resolver: &'a mut Resolver<'ra, 'tcx>) -> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1473        // During late resolution we only track the module component of the parent scope,
1474        // although it may be useful to track other components as well for diagnostics.
1475        let graph_root = resolver.graph_root;
1476        let parent_scope = ParentScope::module(graph_root.to_module(), resolver.arenas);
1477        let start_rib_kind = RibKind::Module(graph_root);
1478        LateResolutionVisitor {
1479            r: resolver,
1480            parent_scope,
1481            ribs: PerNS {
1482                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)],
1483                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)],
1484                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)],
1485            },
1486            last_block_rib: None,
1487            label_ribs: Vec::new(),
1488            lifetime_ribs: Vec::new(),
1489            lifetime_elision_candidates: None,
1490            current_trait_ref: None,
1491            diag_metadata: Default::default(),
1492            // errors at module scope should always be reported
1493            in_func_body: false,
1494            lifetime_uses: Default::default(),
1495        }
1496    }
1497
1498    fn maybe_resolve_ident_in_lexical_scope(
1499        &mut self,
1500        ident: Ident,
1501        ns: Namespace,
1502    ) -> Option<LateDecl<'ra>> {
1503        self.r.resolve_ident_in_lexical_scope(
1504            ident,
1505            ns,
1506            &self.parent_scope,
1507            None,
1508            &self.ribs[ns],
1509            None,
1510            Some(&self.diag_metadata),
1511        )
1512    }
1513
1514    fn resolve_ident_in_lexical_scope(
1515        &mut self,
1516        ident: Ident,
1517        ns: Namespace,
1518        finalize: Option<Finalize>,
1519        ignore_decl: Option<Decl<'ra>>,
1520    ) -> Option<LateDecl<'ra>> {
1521        self.r.resolve_ident_in_lexical_scope(
1522            ident,
1523            ns,
1524            &self.parent_scope,
1525            finalize,
1526            &self.ribs[ns],
1527            ignore_decl,
1528            Some(&self.diag_metadata),
1529        )
1530    }
1531
1532    fn resolve_path(
1533        &mut self,
1534        path: &[Segment],
1535        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1536        finalize: Option<Finalize>,
1537        source: PathSource<'_, 'ast, 'ra>,
1538    ) -> PathResult<'ra> {
1539        self.r.cm().resolve_path_with_ribs(
1540            path,
1541            opt_ns,
1542            &self.parent_scope,
1543            Some(source),
1544            finalize.map(|finalize| Finalize { stage: Stage::Late, ..finalize }),
1545            Some(&self.ribs),
1546            None,
1547            None,
1548            Some(&self.diag_metadata),
1549        )
1550    }
1551
1552    // AST resolution
1553    //
1554    // We maintain a list of value ribs and type ribs.
1555    //
1556    // Simultaneously, we keep track of the current position in the module
1557    // graph in the `parent_scope.module` pointer. When we go to resolve a name in
1558    // the value or type namespaces, we first look through all the ribs and
1559    // then query the module graph. When we resolve a name in the module
1560    // namespace, we can skip all the ribs (since nested modules are not
1561    // allowed within blocks in Rust) and jump straight to the current module
1562    // graph node.
1563    //
1564    // Named implementations are handled separately. When we find a method
1565    // call, we consult the module node to find all of the implementations in
1566    // scope. This information is lazily cached in the module node. We then
1567    // generate a fake "implementation scope" containing all the
1568    // implementations thus found, for compatibility with old resolve pass.
1569
1570    /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
1571    fn with_rib<T>(
1572        &mut self,
1573        ns: Namespace,
1574        kind: RibKind<'ra>,
1575        work: impl FnOnce(&mut Self) -> T,
1576    ) -> T {
1577        self.ribs[ns].push(Rib::new(kind));
1578        let ret = work(self);
1579        self.ribs[ns].pop();
1580        ret
1581    }
1582
1583    fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1584        // For type parameter defaults, we have to ban access
1585        // to following type parameters, as the GenericArgs can only
1586        // provide previous type parameters as they're built. We
1587        // put all the parameters on the ban list and then remove
1588        // them one by one as they are processed and become available.
1589        let mut forward_ty_ban_rib =
1590            Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1591        let mut forward_const_ban_rib =
1592            Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1593        for param in params.iter() {
1594            match param.kind {
1595                GenericParamKind::Type { .. } => {
1596                    forward_ty_ban_rib
1597                        .bindings
1598                        .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1599                }
1600                GenericParamKind::Const { .. } => {
1601                    forward_const_ban_rib
1602                        .bindings
1603                        .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1604                }
1605                GenericParamKind::Lifetime => {}
1606            }
1607        }
1608
1609        // rust-lang/rust#61631: The type `Self` is essentially
1610        // another type parameter. For ADTs, we consider it
1611        // well-defined only after all of the ADT type parameters have
1612        // been provided. Therefore, we do not allow use of `Self`
1613        // anywhere in ADT type parameter defaults.
1614        //
1615        // (We however cannot ban `Self` for defaults on *all* generic
1616        // lists; e.g. trait generics can usefully refer to `Self`,
1617        // such as in the case of `trait Add<Rhs = Self>`.)
1618        if add_self_upper {
1619            // (`Some` if + only if we are in ADT's generics.)
1620            forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1621        }
1622
1623        // NOTE: We use different ribs here not for a technical reason, but just
1624        // for better diagnostics.
1625        let mut forward_ty_ban_rib_const_param_ty = Rib {
1626            bindings: forward_ty_ban_rib.bindings.clone(),
1627            patterns_with_skipped_bindings: Default::default(),
1628            kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1629        };
1630        let mut forward_const_ban_rib_const_param_ty = Rib {
1631            bindings: forward_const_ban_rib.bindings.clone(),
1632            patterns_with_skipped_bindings: Default::default(),
1633            kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1634        };
1635        // We'll ban these with a `ConstParamTy` rib, so just clear these ribs for better
1636        // diagnostics, so we don't mention anything about const param tys having generics at all.
1637        if !self.r.tcx.features().generic_const_parameter_types() {
1638            forward_ty_ban_rib_const_param_ty.bindings.clear();
1639            forward_const_ban_rib_const_param_ty.bindings.clear();
1640        }
1641
1642        self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1643            for param in params {
1644                match param.kind {
1645                    GenericParamKind::Lifetime => {
1646                        for bound in &param.bounds {
1647                            this.visit_param_bound(bound, BoundKind::Bound);
1648                        }
1649                    }
1650                    GenericParamKind::Type { ref default } => {
1651                        for bound in &param.bounds {
1652                            this.visit_param_bound(bound, BoundKind::Bound);
1653                        }
1654
1655                        if let Some(ty) = default {
1656                            this.ribs[TypeNS].push(forward_ty_ban_rib);
1657                            this.ribs[ValueNS].push(forward_const_ban_rib);
1658                            this.visit_ty(ty);
1659                            forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1660                            forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1661                        }
1662
1663                        // Allow all following defaults to refer to this type parameter.
1664                        let i = &Ident::with_dummy_span(param.ident.name);
1665                        forward_ty_ban_rib.bindings.swap_remove(i);
1666                        forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);
1667                    }
1668                    GenericParamKind::Const { ref ty, span: _, ref default } => {
1669                        // Const parameters can't have param bounds.
1670                        if !param.bounds.is_empty() {
    ::core::panicking::panic("assertion failed: param.bounds.is_empty()")
};assert!(param.bounds.is_empty());
1671
1672                        this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);
1673                        this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);
1674                        if this.r.tcx.features().generic_const_parameter_types() {
1675                            this.visit_ty(ty)
1676                        } else {
1677                            this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));
1678                            this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));
1679                            this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {
1680                                this.visit_ty(ty)
1681                            });
1682                            this.ribs[TypeNS].pop().unwrap();
1683                            this.ribs[ValueNS].pop().unwrap();
1684                        }
1685                        forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();
1686                        forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();
1687
1688                        if let Some(expr) = default {
1689                            this.ribs[TypeNS].push(forward_ty_ban_rib);
1690                            this.ribs[ValueNS].push(forward_const_ban_rib);
1691                            this.resolve_anon_const(
1692                                expr,
1693                                AnonConstKind::ConstArg(IsRepeatExpr::No),
1694                            );
1695                            forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1696                            forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1697                        }
1698
1699                        // Allow all following defaults to refer to this const parameter.
1700                        let i = &Ident::with_dummy_span(param.ident.name);
1701                        forward_const_ban_rib.bindings.swap_remove(i);
1702                        forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);
1703                    }
1704                }
1705            }
1706        })
1707    }
1708
1709    #[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(1709u32),
                                    ::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))]
1710    fn with_lifetime_rib<T>(
1711        &mut self,
1712        kind: LifetimeRibKind,
1713        work: impl FnOnce(&mut Self) -> T,
1714    ) -> T {
1715        self.lifetime_ribs.push(LifetimeRib::new(kind));
1716        let outer_elision_candidates = self.lifetime_elision_candidates.take();
1717        let ret = work(self);
1718        self.lifetime_elision_candidates = outer_elision_candidates;
1719        self.lifetime_ribs.pop();
1720        ret
1721    }
1722
1723    #[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(1723u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["lifetime",
                                                    "use_ctxt"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_ctxt)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ident = lifetime.ident;
            if ident.name == kw::StaticLifetime {
                self.record_lifetime_res(lifetime.id, LifetimeRes::Static,
                    LifetimeElisionCandidate::Named);
                return;
            }
            if ident.name == kw::UnderscoreLifetime {
                return self.resolve_anonymous_lifetime(lifetime, lifetime.id,
                        false);
            }
            let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
            while let Some(rib) = lifetime_rib_iter.next() {
                let normalized_ident = ident.normalize_to_macros_2_0();
                if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
                    self.record_lifetime_res(lifetime.id, res,
                        LifetimeElisionCandidate::Named);
                    if let LifetimeRes::Param { param, binder } = res {
                        match self.lifetime_uses.entry(param) {
                            Entry::Vacant(v) => {
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:1749",
                                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1749u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                                        ::tracing_core::field::FieldSet::new(&["message"],
                                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                        ::tracing::metadata::Kind::EVENT)
                                                };
                                            ::tracing::callsite::DefaultCallsite::new(&META)
                                        };
                                    let enabled =
                                        ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            {
                                                let interest = __CALLSITE.interest();
                                                !interest.is_never() &&
                                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                        interest)
                                            };
                                    if enabled {
                                        (|value_set: ::tracing::field::ValueSet|
                                                    {
                                                        let meta = __CALLSITE.metadata();
                                                        ::tracing::Event::dispatch(meta, &value_set);
                                                        ;
                                                    })({
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                let mut iter = __CALLSITE.metadata().fields().iter();
                                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&format_args!("First use of {0:?} at {1:?}",
                                                                                    res, ident.span) as &dyn Value))])
                                            });
                                    } else { ; }
                                };
                                let use_set =
                                    self.lifetime_ribs.iter().rev().find_map(|rib|
                                                match rib.kind {
                                                    LifetimeRibKind::Item |
                                                        LifetimeRibKind::AnonymousReportError |
                                                        LifetimeRibKind::StaticIfNoLifetimeInScope { .. } |
                                                        LifetimeRibKind::ElisionFailure =>
                                                        Some(LifetimeUseSet::Many),
                                                    LifetimeRibKind::AnonymousCreateParameter {
                                                        binder: anon_binder, .. } =>
                                                        Some(if binder == anon_binder {
                                                                LifetimeUseSet::One { use_span: ident.span, use_ctxt }
                                                            } else { LifetimeUseSet::Many }),
                                                    LifetimeRibKind::Elided(r) =>
                                                        Some(if res == r {
                                                                LifetimeUseSet::One { use_span: ident.span, use_ctxt }
                                                            } else { LifetimeUseSet::Many }),
                                                    LifetimeRibKind::Generics { .. } |
                                                        LifetimeRibKind::ConstParamTy => None,
                                                    LifetimeRibKind::ConcreteAnonConst(_) => {
                                                        ::rustc_middle::util::bug::span_bug_fmt(ident.span,
                                                            format_args!("unexpected rib kind: {0:?}", rib.kind))
                                                    }
                                                }).unwrap_or(LifetimeUseSet::Many);
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:1785",
                                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1785u32),
                                                        ::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:1789",
                                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1789u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                                        ::tracing_core::field::FieldSet::new(&["message"],
                                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                        ::tracing::metadata::Kind::EVENT)
                                                };
                                            ::tracing::callsite::DefaultCallsite::new(&META)
                                        };
                                    let enabled =
                                        ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            {
                                                let interest = __CALLSITE.interest();
                                                !interest.is_never() &&
                                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                        interest)
                                            };
                                    if enabled {
                                        (|value_set: ::tracing::field::ValueSet|
                                                    {
                                                        let meta = __CALLSITE.metadata();
                                                        ::tracing::Event::dispatch(meta, &value_set);
                                                        ;
                                                    })({
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                let mut iter = __CALLSITE.metadata().fields().iter();
                                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&format_args!("Many uses of {0:?} at {1:?}",
                                                                                    res, ident.span) as &dyn Value))])
                                            });
                                    } else { ; }
                                };
                                *o.get_mut() = LifetimeUseSet::Many;
                            }
                        }
                    }
                    return;
                }
                match rib.kind {
                    LifetimeRibKind::Item => break,
                    LifetimeRibKind::ConstParamTy => {
                        let guar =
                            self.emit_non_static_lt_in_const_param_ty_error(lifetime);
                        self.record_lifetime_res(lifetime.id,
                            LifetimeRes::Error(guar), LifetimeElisionCandidate::Ignore);
                        return;
                    }
                    LifetimeRibKind::ConcreteAnonConst(cause) => {
                        let guar =
                            self.emit_forbidden_non_static_lifetime_error(cause,
                                lifetime);
                        self.record_lifetime_res(lifetime.id,
                            LifetimeRes::Error(guar), LifetimeElisionCandidate::Ignore);
                        return;
                    }
                    LifetimeRibKind::AnonymousCreateParameter { .. } |
                        LifetimeRibKind::Elided(_) | LifetimeRibKind::Generics { ..
                        } | LifetimeRibKind::ElisionFailure |
                        LifetimeRibKind::AnonymousReportError |
                        LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {}
                }
            }
            let normalized_ident = ident.normalize_to_macros_2_0();
            let outer_res =
                lifetime_rib_iter.find_map(|rib|
                        rib.bindings.get_key_value(&normalized_ident).map(|(&outer,
                                    _)| outer));
            let guar =
                self.emit_undeclared_lifetime_error(lifetime, outer_res);
            self.record_lifetime_res(lifetime.id, LifetimeRes::Error(guar),
                LifetimeElisionCandidate::Named);
        }
    }
}#[instrument(level = "debug", skip(self))]
1724    fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1725        let ident = lifetime.ident;
1726
1727        if ident.name == kw::StaticLifetime {
1728            self.record_lifetime_res(
1729                lifetime.id,
1730                LifetimeRes::Static,
1731                LifetimeElisionCandidate::Named,
1732            );
1733            return;
1734        }
1735
1736        if ident.name == kw::UnderscoreLifetime {
1737            return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1738        }
1739
1740        let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1741        while let Some(rib) = lifetime_rib_iter.next() {
1742            let normalized_ident = ident.normalize_to_macros_2_0();
1743            if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1744                self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
1745
1746                if let LifetimeRes::Param { param, binder } = res {
1747                    match self.lifetime_uses.entry(param) {
1748                        Entry::Vacant(v) => {
1749                            debug!("First use of {:?} at {:?}", res, ident.span);
1750                            let use_set = self
1751                                .lifetime_ribs
1752                                .iter()
1753                                .rev()
1754                                .find_map(|rib| match rib.kind {
1755                                    // Do not suggest eliding a lifetime where an anonymous
1756                                    // lifetime would be illegal.
1757                                    LifetimeRibKind::Item
1758                                    | LifetimeRibKind::AnonymousReportError
1759                                    | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1760                                    | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1761                                    // An anonymous lifetime is legal here, and bound to the right
1762                                    // place, go ahead.
1763                                    LifetimeRibKind::AnonymousCreateParameter {
1764                                        binder: anon_binder,
1765                                        ..
1766                                    } => Some(if binder == anon_binder {
1767                                        LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1768                                    } else {
1769                                        LifetimeUseSet::Many
1770                                    }),
1771                                    // Only report if eliding the lifetime would have the same
1772                                    // semantics.
1773                                    LifetimeRibKind::Elided(r) => Some(if res == r {
1774                                        LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1775                                    } else {
1776                                        LifetimeUseSet::Many
1777                                    }),
1778                                    LifetimeRibKind::Generics { .. }
1779                                    | LifetimeRibKind::ConstParamTy => None,
1780                                    LifetimeRibKind::ConcreteAnonConst(_) => {
1781                                        span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1782                                    }
1783                                })
1784                                .unwrap_or(LifetimeUseSet::Many);
1785                            debug!(?use_ctxt, ?use_set);
1786                            v.insert(use_set);
1787                        }
1788                        Entry::Occupied(mut o) => {
1789                            debug!("Many uses of {:?} at {:?}", res, ident.span);
1790                            *o.get_mut() = LifetimeUseSet::Many;
1791                        }
1792                    }
1793                }
1794                return;
1795            }
1796
1797            match rib.kind {
1798                LifetimeRibKind::Item => break,
1799                LifetimeRibKind::ConstParamTy => {
1800                    let guar = self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1801                    self.record_lifetime_res(
1802                        lifetime.id,
1803                        LifetimeRes::Error(guar),
1804                        LifetimeElisionCandidate::Ignore,
1805                    );
1806                    return;
1807                }
1808                LifetimeRibKind::ConcreteAnonConst(cause) => {
1809                    let guar = self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1810                    self.record_lifetime_res(
1811                        lifetime.id,
1812                        LifetimeRes::Error(guar),
1813                        LifetimeElisionCandidate::Ignore,
1814                    );
1815                    return;
1816                }
1817                LifetimeRibKind::AnonymousCreateParameter { .. }
1818                | LifetimeRibKind::Elided(_)
1819                | LifetimeRibKind::Generics { .. }
1820                | LifetimeRibKind::ElisionFailure
1821                | LifetimeRibKind::AnonymousReportError
1822                | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {}
1823            }
1824        }
1825
1826        let normalized_ident = ident.normalize_to_macros_2_0();
1827        let outer_res = lifetime_rib_iter
1828            .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1829
1830        let guar = self.emit_undeclared_lifetime_error(lifetime, outer_res);
1831        self.record_lifetime_res(
1832            lifetime.id,
1833            LifetimeRes::Error(guar),
1834            LifetimeElisionCandidate::Named,
1835        );
1836    }
1837
1838    #[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(1838u32),
                                    ::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:1858",
                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1858u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                        ::tracing_core::field::FieldSet::new(&["rib.kind"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&debug(&rib.kind)
                                                            as &dyn Value))])
                            });
                    } else { ; }
                };
                match rib.kind {
                    LifetimeRibKind::AnonymousCreateParameter { binder, .. } =>
                        {
                        let res =
                            self.create_fresh_lifetime(lifetime.ident, binder, kind);
                        self.record_lifetime_res(lifetime.id, res,
                            elision_candidate);
                        return;
                    }
                    LifetimeRibKind::StaticIfNoLifetimeInScope {
                        lint_id: node_id, emit_lint } => {
                        let mut lifetimes_in_scope = ::alloc::vec::Vec::new();
                        for rib in self.lifetime_ribs[..i].iter().rev() {
                            lifetimes_in_scope.extend(rib.bindings.iter().map(|(ident,
                                            _)| ident.span));
                            if let LifetimeRibKind::AnonymousCreateParameter { binder,
                                        .. } = rib.kind &&
                                    let Some(extra) =
                                        self.r.extra_lifetime_params_map.get(&binder) {
                                lifetimes_in_scope.extend(extra.iter().map(|(ident, _, _)|
                                            ident.span));
                            }
                            if let LifetimeRibKind::Item = rib.kind { break; }
                        }
                        if lifetimes_in_scope.is_empty() {
                            self.record_lifetime_res(lifetime.id, LifetimeRes::Static,
                                elision_candidate);
                            return;
                        } else if emit_lint {
                            let lt_span =
                                if elided {
                                    lifetime.ident.span.shrink_to_hi()
                                } else { lifetime.ident.span };
                            let code = if elided { "'static " } else { "'static" };
                            self.r.lint_buffer.buffer_lint(lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
                                node_id, lifetime.ident.span,
                                crate::errors::AssociatedConstElidedLifetime {
                                    elided,
                                    code,
                                    span: lt_span,
                                    lifetimes_in_scope: lifetimes_in_scope.into(),
                                });
                        }
                    }
                    LifetimeRibKind::AnonymousReportError => {
                        let guar =
                            if elided {
                                let suggestion =
                                    self.lifetime_ribs[i..].iter().rev().find_map(|rib|
                                            {
                                                if let LifetimeRibKind::Generics {
                                                        span,
                                                        kind: LifetimeBinderKind::PolyTrait |
                                                            LifetimeBinderKind::WhereBound, .. } = rib.kind {
                                                    Some(errors::ElidedAnonymousLifetimeReportErrorSuggestion {
                                                            lo: span.shrink_to_lo(),
                                                            hi: lifetime.ident.span.shrink_to_hi(),
                                                        })
                                                } else { None }
                                            });
                                if !self.in_func_body &&
                                                    let Some((module, _)) = &self.current_trait_ref &&
                                                let Some(ty) = &self.diag_metadata.current_self_type &&
                                            Some(true) == self.diag_metadata.in_non_gat_assoc_type &&
                                        let crate::ModuleKind::Def(DefKind::Trait, trait_id, _) =
                                            module.kind {
                                    if def_id_matches_path(self.r.tcx, trait_id,
                                            &["core", "iter", "traits", "iterator", "Iterator"]) {
                                        self.r.dcx().emit_err(errors::LendingIteratorReportError {
                                                lifetime: lifetime.ident.span,
                                                ty: ty.span,
                                            })
                                    } else {
                                        let decl =
                                            if !trait_id.is_local() &&
                                                                    let Some(assoc) = self.diag_metadata.current_impl_item &&
                                                                let AssocItemKind::Type(_) = assoc.kind &&
                                                            let assocs = self.r.tcx.associated_items(trait_id) &&
                                                        let Some(ident) = assoc.kind.ident() &&
                                                    let Some(assoc) =
                                                        assocs.find_by_ident_and_kind(self.r.tcx, ident,
                                                            AssocTag::Type, trait_id) {
                                                let mut decl: MultiSpan =
                                                    self.r.tcx.def_span(assoc.def_id).into();
                                                decl.push_span_label(self.r.tcx.def_span(trait_id),
                                                    String::new());
                                                decl
                                            } else { DUMMY_SP.into() };
                                        let mut err =
                                            self.r.dcx().create_err(errors::AnonymousLifetimeNonGatReportError {
                                                    lifetime: lifetime.ident.span,
                                                    decl,
                                                });
                                        self.point_at_impl_lifetimes(&mut err, i,
                                            lifetime.ident.span);
                                        err.emit()
                                    }
                                } else {
                                    self.r.dcx().emit_err(errors::ElidedAnonymousLifetimeReportError {
                                            span: lifetime.ident.span,
                                            suggestion,
                                        })
                                }
                            } else {
                                self.r.dcx().emit_err(errors::ExplicitAnonymousLifetimeReportError {
                                        span: lifetime.ident.span,
                                    })
                            };
                        self.record_lifetime_res(lifetime.id,
                            LifetimeRes::Error(guar), elision_candidate);
                        return;
                    }
                    LifetimeRibKind::Elided(res) => {
                        self.record_lifetime_res(lifetime.id, res,
                            elision_candidate);
                        return;
                    }
                    LifetimeRibKind::ElisionFailure => {
                        self.diag_metadata.current_elision_failures.push((missing_lifetime,
                                elision_candidate, Either::Left(lifetime.id)));
                        return;
                    }
                    LifetimeRibKind::Item => break,
                    LifetimeRibKind::Generics { .. } |
                        LifetimeRibKind::ConstParamTy => {}
                    LifetimeRibKind::ConcreteAnonConst(_) => {
                        ::rustc_middle::util::bug::span_bug_fmt(lifetime.ident.span,
                            format_args!("unexpected rib kind: {0:?}", rib.kind))
                    }
                }
            }
            let guar =
                self.report_missing_lifetime_specifiers([&missing_lifetime],
                    None);
            self.record_lifetime_res(lifetime.id, LifetimeRes::Error(guar),
                elision_candidate);
        }
    }
}#[instrument(level = "debug", skip(self))]
1839    fn resolve_anonymous_lifetime(
1840        &mut self,
1841        lifetime: &Lifetime,
1842        id_for_lint: NodeId,
1843        elided: bool,
1844    ) {
1845        debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1846
1847        let kind =
1848            if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1849        let missing_lifetime = MissingLifetime {
1850            id: lifetime.id,
1851            span: lifetime.ident.span,
1852            kind,
1853            count: 1,
1854            id_for_lint,
1855        };
1856        let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1857        for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1858            debug!(?rib.kind);
1859            match rib.kind {
1860                LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1861                    let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1862                    self.record_lifetime_res(lifetime.id, res, elision_candidate);
1863                    return;
1864                }
1865                LifetimeRibKind::StaticIfNoLifetimeInScope { lint_id: node_id, emit_lint } => {
1866                    let mut lifetimes_in_scope = vec![];
1867                    for rib in self.lifetime_ribs[..i].iter().rev() {
1868                        lifetimes_in_scope.extend(rib.bindings.iter().map(|(ident, _)| ident.span));
1869                        // Consider any anonymous lifetimes, too
1870                        if let LifetimeRibKind::AnonymousCreateParameter { binder, .. } = rib.kind
1871                            && let Some(extra) = self.r.extra_lifetime_params_map.get(&binder)
1872                        {
1873                            lifetimes_in_scope.extend(extra.iter().map(|(ident, _, _)| ident.span));
1874                        }
1875                        if let LifetimeRibKind::Item = rib.kind {
1876                            break;
1877                        }
1878                    }
1879                    if lifetimes_in_scope.is_empty() {
1880                        self.record_lifetime_res(
1881                            lifetime.id,
1882                            LifetimeRes::Static,
1883                            elision_candidate,
1884                        );
1885                        return;
1886                    } else if emit_lint {
1887                        let lt_span = if elided {
1888                            lifetime.ident.span.shrink_to_hi()
1889                        } else {
1890                            lifetime.ident.span
1891                        };
1892                        let code = if elided { "'static " } else { "'static" };
1893
1894                        self.r.lint_buffer.buffer_lint(
1895                            lint::builtin::ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT,
1896                            node_id,
1897                            lifetime.ident.span,
1898                            crate::errors::AssociatedConstElidedLifetime {
1899                                elided,
1900                                code,
1901                                span: lt_span,
1902                                lifetimes_in_scope: lifetimes_in_scope.into(),
1903                            },
1904                        );
1905                    }
1906                }
1907                LifetimeRibKind::AnonymousReportError => {
1908                    let guar = if elided {
1909                        let suggestion = self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1910                            if let LifetimeRibKind::Generics {
1911                                span,
1912                                kind: LifetimeBinderKind::PolyTrait | LifetimeBinderKind::WhereBound,
1913                                ..
1914                            } = rib.kind
1915                            {
1916                                Some(errors::ElidedAnonymousLifetimeReportErrorSuggestion {
1917                                    lo: span.shrink_to_lo(),
1918                                    hi: lifetime.ident.span.shrink_to_hi(),
1919                                })
1920                            } else {
1921                                None
1922                            }
1923                        });
1924                        // are we trying to use an anonymous lifetime
1925                        // on a non GAT associated trait type?
1926                        if !self.in_func_body
1927                            && let Some((module, _)) = &self.current_trait_ref
1928                            && let Some(ty) = &self.diag_metadata.current_self_type
1929                            && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1930                            && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _) = module.kind
1931                        {
1932                            if def_id_matches_path(
1933                                self.r.tcx,
1934                                trait_id,
1935                                &["core", "iter", "traits", "iterator", "Iterator"],
1936                            ) {
1937                                self.r.dcx().emit_err(errors::LendingIteratorReportError {
1938                                    lifetime: lifetime.ident.span,
1939                                    ty: ty.span,
1940                                })
1941                            } else {
1942                                let decl = if !trait_id.is_local()
1943                                    && let Some(assoc) = self.diag_metadata.current_impl_item
1944                                    && let AssocItemKind::Type(_) = assoc.kind
1945                                    && let assocs = self.r.tcx.associated_items(trait_id)
1946                                    && let Some(ident) = assoc.kind.ident()
1947                                    && let Some(assoc) = assocs.find_by_ident_and_kind(
1948                                        self.r.tcx,
1949                                        ident,
1950                                        AssocTag::Type,
1951                                        trait_id,
1952                                    ) {
1953                                    let mut decl: MultiSpan =
1954                                        self.r.tcx.def_span(assoc.def_id).into();
1955                                    decl.push_span_label(
1956                                        self.r.tcx.def_span(trait_id),
1957                                        String::new(),
1958                                    );
1959                                    decl
1960                                } else {
1961                                    DUMMY_SP.into()
1962                                };
1963                                let mut err = self.r.dcx().create_err(
1964                                    errors::AnonymousLifetimeNonGatReportError {
1965                                        lifetime: lifetime.ident.span,
1966                                        decl,
1967                                    },
1968                                );
1969                                self.point_at_impl_lifetimes(&mut err, i, lifetime.ident.span);
1970                                err.emit()
1971                            }
1972                        } else {
1973                            self.r.dcx().emit_err(errors::ElidedAnonymousLifetimeReportError {
1974                                span: lifetime.ident.span,
1975                                suggestion,
1976                            })
1977                        }
1978                    } else {
1979                        self.r.dcx().emit_err(errors::ExplicitAnonymousLifetimeReportError {
1980                            span: lifetime.ident.span,
1981                        })
1982                    };
1983                    self.record_lifetime_res(
1984                        lifetime.id,
1985                        LifetimeRes::Error(guar),
1986                        elision_candidate,
1987                    );
1988                    return;
1989                }
1990                LifetimeRibKind::Elided(res) => {
1991                    self.record_lifetime_res(lifetime.id, res, elision_candidate);
1992                    return;
1993                }
1994                LifetimeRibKind::ElisionFailure => {
1995                    self.diag_metadata.current_elision_failures.push((
1996                        missing_lifetime,
1997                        elision_candidate,
1998                        Either::Left(lifetime.id),
1999                    ));
2000                    return;
2001                }
2002                LifetimeRibKind::Item => break,
2003                LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
2004                LifetimeRibKind::ConcreteAnonConst(_) => {
2005                    // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
2006                    span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
2007                }
2008            }
2009        }
2010        let guar = self.report_missing_lifetime_specifiers([&missing_lifetime], None);
2011        self.record_lifetime_res(lifetime.id, LifetimeRes::Error(guar), elision_candidate);
2012    }
2013
2014    fn point_at_impl_lifetimes(&mut self, err: &mut Diag<'_>, i: usize, lifetime: Span) {
2015        let Some((rib, span)) =
2016            self.lifetime_ribs[..i].iter().rev().find_map(|rib| match rib.kind {
2017                LifetimeRibKind::Generics { span, kind: LifetimeBinderKind::ImplBlock, .. } => {
2018                    Some((rib, span))
2019                }
2020                _ => None,
2021            })
2022        else {
2023            return;
2024        };
2025        if !rib.bindings.is_empty() {
2026            err.span_label(
2027                span,
2028                ::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!(
2029                    "there {} named lifetime{} specified on the impl block you could use",
2030                    if rib.bindings.len() == 1 { "is a" } else { "are" },
2031                    pluralize!(rib.bindings.len()),
2032                ),
2033            );
2034            if rib.bindings.len() == 1 {
2035                err.span_suggestion_verbose(
2036                    lifetime.shrink_to_hi(),
2037                    "consider using the lifetime from the impl block",
2038                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ",
                rib.bindings.keys().next().unwrap()))
    })format!("{} ", rib.bindings.keys().next().unwrap()),
2039                    Applicability::MaybeIncorrect,
2040                );
2041            }
2042        } else {
2043            struct AnonRefFinder;
2044            impl<'ast> Visitor<'ast> for AnonRefFinder {
2045                type Result = ControlFlow<Span>;
2046
2047                fn visit_ty(&mut self, ty: &'ast ast::Ty) -> Self::Result {
2048                    if let ast::TyKind::Ref(None, mut_ty) = &ty.kind {
2049                        return ControlFlow::Break(mut_ty.ty.span.shrink_to_lo());
2050                    }
2051                    visit::walk_ty(self, ty)
2052                }
2053
2054                fn visit_lifetime(
2055                    &mut self,
2056                    lt: &'ast ast::Lifetime,
2057                    _cx: visit::LifetimeCtxt,
2058                ) -> Self::Result {
2059                    if lt.ident.name == kw::UnderscoreLifetime {
2060                        return ControlFlow::Break(lt.ident.span);
2061                    }
2062                    visit::walk_lifetime(self, lt)
2063                }
2064            }
2065
2066            if let Some(ty) = &self.diag_metadata.current_self_type
2067                && let ControlFlow::Break(sp) = AnonRefFinder.visit_ty(ty)
2068            {
2069                err.multipart_suggestion(
2070                    "add a lifetime to the impl block and use it in the self type and associated \
2071                     type",
2072                    ::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![
2073                        (span, "<'a>".to_string()),
2074                        (sp, "'a ".to_string()),
2075                        (lifetime.shrink_to_hi(), "'a ".to_string()),
2076                    ],
2077                    Applicability::MaybeIncorrect,
2078                );
2079            } else if let Some(item) = &self.diag_metadata.current_item
2080                && let ItemKind::Impl(impl_) = &item.kind
2081                && let Some(of_trait) = &impl_.of_trait
2082                && let ControlFlow::Break(sp) = AnonRefFinder.visit_trait_ref(&of_trait.trait_ref)
2083            {
2084                err.multipart_suggestion(
2085                    "add a lifetime to the impl block and use it in the trait and associated type",
2086                    ::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![
2087                        (span, "<'a>".to_string()),
2088                        (sp, "'a".to_string()),
2089                        (lifetime.shrink_to_hi(), "'a ".to_string()),
2090                    ],
2091                    Applicability::MaybeIncorrect,
2092                );
2093            } else {
2094                err.span_label(
2095                    span,
2096                    "you could add a lifetime on the impl block, if the trait or the self type \
2097                     could have one",
2098                );
2099            }
2100        }
2101    }
2102
2103    #[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(2103u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["anchor_id", "span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&anchor_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let id = self.r.next_node_id();
            let lt =
                Lifetime {
                    id,
                    ident: Ident::new(kw::UnderscoreLifetime, span),
                };
            self.record_lifetime_res(anchor_id,
                LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
                LifetimeElisionCandidate::Ignore);
            self.resolve_anonymous_lifetime(&lt, anchor_id, true);
        }
    }
}#[instrument(level = "debug", skip(self))]
2104    fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
2105        let id = self.r.next_node_id();
2106        let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
2107
2108        self.record_lifetime_res(
2109            anchor_id,
2110            LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
2111            LifetimeElisionCandidate::Ignore,
2112        );
2113        self.resolve_anonymous_lifetime(&lt, anchor_id, true);
2114    }
2115
2116    #[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(2116u32),
                                    ::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:2124",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2124u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["ident.span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&ident.span)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let param = self.r.next_node_id();
            let res = LifetimeRes::Fresh { param, binder, kind };
            self.record_lifetime_param(param, res);
            self.r.extra_lifetime_params_map.entry(binder).or_insert_with(Vec::new).push((ident,
                    param, res));
            res
        }
    }
}#[instrument(level = "debug", skip(self))]
2117    fn create_fresh_lifetime(
2118        &mut self,
2119        ident: Ident,
2120        binder: NodeId,
2121        kind: MissingLifetimeKind,
2122    ) -> LifetimeRes {
2123        debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
2124        debug!(?ident.span);
2125
2126        // Leave the responsibility to create the `LocalDefId` to lowering.
2127        let param = self.r.next_node_id();
2128        let res = LifetimeRes::Fresh { param, binder, kind };
2129        self.record_lifetime_param(param, res);
2130
2131        // Record the created lifetime parameter so lowering can pick it up and add it to HIR.
2132        self.r
2133            .extra_lifetime_params_map
2134            .entry(binder)
2135            .or_insert_with(Vec::new)
2136            .push((ident, param, res));
2137        res
2138    }
2139
2140    #[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(2140u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["partial_res",
                                                    "path", "source", "path_span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&partial_res)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path_span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
                {
                    ::core::panicking::panic_fmt(format_args!("lifetime {0:?} resolved multiple times ({1:?} before, {2:?} now)",
                            id, prev_res, res));
                }
            }
            match res {
                LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } |
                    LifetimeRes::Static { .. } => {
                    if let Some(ref mut candidates) =
                            self.lifetime_elision_candidates {
                        candidates.push((res, candidate));
                    }
                }
                LifetimeRes::Infer | LifetimeRes::Error(..) |
                    LifetimeRes::ElidedAnchor { .. } => {}
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2362    fn record_lifetime_res(
2363        &mut self,
2364        id: NodeId,
2365        res: LifetimeRes,
2366        candidate: LifetimeElisionCandidate,
2367    ) {
2368        if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2369            panic!("lifetime {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)")
2370        }
2371
2372        match res {
2373            LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2374                if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2375                    candidates.push((res, candidate));
2376                }
2377            }
2378            LifetimeRes::Infer | LifetimeRes::Error(..) | LifetimeRes::ElidedAnchor { .. } => {}
2379        }
2380    }
2381
2382    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("record_lifetime_param",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2382u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&["id", "res"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
                {
                    ::core::panicking::panic_fmt(format_args!("lifetime parameter {0:?} resolved multiple times ({1:?} before, {2:?} now)",
                            id, prev_res, res));
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2383    fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
2384        if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
2385            panic!(
2386                "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2387            )
2388        }
2389    }
2390
2391    /// Perform resolution of a function signature, accounting for lifetime elision.
2392    #[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(2392u32),
                                    ::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:2408",
                                                "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                                                ::tracing_core::__macro_support::Option::Some(2408u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                                ::tracing_core::field::FieldSet::new(&["elision_lifetime"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&elision_lifetime)
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        let outer_failures =
                            take(&mut this.diag_metadata.current_elision_failures);
                        let output_rib =
                            if let Ok(res) = elision_lifetime.as_ref() {
                                this.r.lifetime_elision_allowed.insert(fn_id);
                                LifetimeRibKind::Elided(*res)
                            } else { LifetimeRibKind::ElisionFailure };
                        this.with_lifetime_rib(output_rib,
                            |this| visit::walk_fn_ret_ty(this, output_ty));
                        let elision_failures =
                            replace(&mut this.diag_metadata.current_elision_failures,
                                outer_failures);
                        if !elision_failures.is_empty() {
                            let Err(failure_info) =
                                elision_lifetime else {
                                    ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
                                };
                            let guar =
                                this.report_missing_lifetime_specifiers(elision_failures.iter().map(|(missing_lifetime,
                                                ..)| missing_lifetime), Some(failure_info));
                            let mut record_res =
                                |lifetime, candidate|
                                    {
                                        this.record_lifetime_res(lifetime, LifetimeRes::Error(guar),
                                            candidate)
                                    };
                            for (_, candidate, nodes) in elision_failures {
                                match nodes {
                                    Either::Left(node_id) => record_res(node_id, candidate),
                                    Either::Right(node_ids) => {
                                        for lifetime in node_ids { record_res(lifetime, candidate) }
                                    }
                                }
                            }
                        }
                    });
        }
    }
}#[instrument(level = "debug", skip(self, inputs))]
2393    fn resolve_fn_signature(
2394        &mut self,
2395        fn_id: NodeId,
2396        has_self: bool,
2397        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2398        output_ty: &'ast FnRetTy,
2399        report_elided_lifetimes_in_path: bool,
2400    ) {
2401        let rib = LifetimeRibKind::AnonymousCreateParameter {
2402            binder: fn_id,
2403            report_in_path: report_elided_lifetimes_in_path,
2404        };
2405        self.with_lifetime_rib(rib, |this| {
2406            // Add each argument to the rib.
2407            let elision_lifetime = this.resolve_fn_params(has_self, inputs);
2408            debug!(?elision_lifetime);
2409
2410            let outer_failures = take(&mut this.diag_metadata.current_elision_failures);
2411            let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2412                this.r.lifetime_elision_allowed.insert(fn_id);
2413                LifetimeRibKind::Elided(*res)
2414            } else {
2415                LifetimeRibKind::ElisionFailure
2416            };
2417            this.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2418            let elision_failures =
2419                replace(&mut this.diag_metadata.current_elision_failures, outer_failures);
2420            if !elision_failures.is_empty() {
2421                let Err(failure_info) = elision_lifetime else { bug!() };
2422                let guar = this.report_missing_lifetime_specifiers(
2423                    elision_failures.iter().map(|(missing_lifetime, ..)| missing_lifetime),
2424                    Some(failure_info),
2425                );
2426                let mut record_res = |lifetime, candidate| {
2427                    this.record_lifetime_res(lifetime, LifetimeRes::Error(guar), candidate)
2428                };
2429                for (_, candidate, nodes) in elision_failures {
2430                    match nodes {
2431                        Either::Left(node_id) => record_res(node_id, candidate),
2432                        Either::Right(node_ids) => {
2433                            for lifetime in node_ids {
2434                                record_res(lifetime, candidate)
2435                            }
2436                        }
2437                    }
2438                }
2439            }
2440        });
2441    }
2442
2443    /// Resolve inside function parameters and parameter types.
2444    /// Returns the lifetime for elision in fn return type,
2445    /// or diagnostic information in case of elision failure.
2446    fn resolve_fn_params(
2447        &mut self,
2448        has_self: bool,
2449        inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2450    ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2451        enum Elision {
2452            /// We have not found any candidate.
2453            None,
2454            /// We have a candidate bound to `self`.
2455            Self_(LifetimeRes),
2456            /// We have a candidate bound to a parameter.
2457            Param(LifetimeRes),
2458            /// We failed elision.
2459            Err,
2460        }
2461
2462        // Save elision state to reinstate it later.
2463        let outer_candidates = self.lifetime_elision_candidates.take();
2464
2465        // Result of elision.
2466        let mut elision_lifetime = Elision::None;
2467        // Information for diagnostics.
2468        let mut parameter_info = Vec::new();
2469        let mut all_candidates = Vec::new();
2470
2471        // Resolve and apply bindings first so diagnostics can see if they're used in types.
2472        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())];
2473        for (pat, _) in inputs.clone() {
2474            {
    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:2474",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2474u32),
                        ::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:?}");
2475            self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2476                if let Some(pat) = pat {
2477                    this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2478                }
2479            });
2480        }
2481        self.apply_pattern_bindings(bindings);
2482
2483        for (index, (pat, ty)) in inputs.enumerate() {
2484            {
    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:2484",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2484u32),
                        ::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:?}");
2485            // Record elision candidates only for this parameter.
2486            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);
2487            self.lifetime_elision_candidates = Some(Default::default());
2488            self.visit_ty(ty);
2489            let local_candidates = self.lifetime_elision_candidates.take();
2490
2491            if let Some(candidates) = local_candidates {
2492                let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2493                let lifetime_count = distinct.len();
2494                if lifetime_count != 0 {
2495                    parameter_info.push(ElisionFnParameter {
2496                        index,
2497                        ident: if let Some(pat) = pat
2498                            && let PatKind::Ident(_, ident, _) = pat.kind
2499                        {
2500                            Some(ident)
2501                        } else {
2502                            None
2503                        },
2504                        lifetime_count,
2505                        span: ty.span,
2506                    });
2507                    all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2508                        match candidate {
2509                            LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => {
2510                                None
2511                            }
2512                            LifetimeElisionCandidate::Missing(missing) => Some(missing),
2513                        }
2514                    }));
2515                }
2516                if !distinct.is_empty() {
2517                    match elision_lifetime {
2518                        // We are the first parameter to bind lifetimes.
2519                        Elision::None => {
2520                            if let Some(res) = distinct.get_only() {
2521                                // We have a single lifetime => success.
2522                                elision_lifetime = Elision::Param(*res)
2523                            } else {
2524                                // We have multiple lifetimes => error.
2525                                elision_lifetime = Elision::Err;
2526                            }
2527                        }
2528                        // We have 2 parameters that bind lifetimes => error.
2529                        Elision::Param(_) => elision_lifetime = Elision::Err,
2530                        // `self` elision takes precedence over everything else.
2531                        Elision::Self_(_) | Elision::Err => {}
2532                    }
2533                }
2534            }
2535
2536            // Handle `self` specially.
2537            if index == 0 && has_self {
2538                let self_lifetime = self.find_lifetime_for_self(ty);
2539                elision_lifetime = match self_lifetime {
2540                    // We found `self` elision.
2541                    Set1::One(lifetime) => Elision::Self_(lifetime),
2542                    // `self` itself had ambiguous lifetimes, e.g.
2543                    // &Box<&Self>. In this case we won't consider
2544                    // taking an alternative parameter lifetime; just avoid elision
2545                    // entirely.
2546                    Set1::Many => Elision::Err,
2547                    // We do not have `self` elision: disregard the `Elision::Param` that we may
2548                    // have found.
2549                    Set1::Empty => Elision::None,
2550                }
2551            }
2552            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2552",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2552u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::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");
2553        }
2554
2555        // Reinstate elision state.
2556        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);
2557        self.lifetime_elision_candidates = outer_candidates;
2558
2559        if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2560            return Ok(res);
2561        }
2562
2563        // We do not have a candidate.
2564        Err((all_candidates, parameter_info))
2565    }
2566
2567    /// List all the lifetimes that appear in the provided type.
2568    fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2569        /// Visits a type to find all the &references, and determines the
2570        /// set of lifetimes for all of those references where the referent
2571        /// contains Self.
2572        struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2573            r: &'a Resolver<'ra, 'tcx>,
2574            impl_self: Option<Res>,
2575            lifetime: Set1<LifetimeRes>,
2576        }
2577
2578        impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2579            fn visit_ty(&mut self, ty: &'ra Ty) {
2580                {
    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:2580",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2580u32),
                        ::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);
2581                if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2582                    // See if anything inside the &thing contains Self
2583                    let mut visitor =
2584                        SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2585                    visitor.visit_ty(ty);
2586                    {
    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:2586",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2586u32),
                        ::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);
2587                    if visitor.self_found {
2588                        let lt_id = if let Some(lt) = lt {
2589                            lt.id
2590                        } else {
2591                            let res = self.r.lifetimes_res_map[&ty.id];
2592                            let LifetimeRes::ElidedAnchor { start, .. } = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2593                            start
2594                        };
2595                        let lt_res = self.r.lifetimes_res_map[&lt_id];
2596                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2596",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2596u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("FindReferenceVisitor inserting res={0:?}",
                                                    lt_res) as &dyn Value))])
            });
    } else { ; }
};trace!("FindReferenceVisitor inserting res={:?}", lt_res);
2597                        self.lifetime.insert(lt_res);
2598                    }
2599                }
2600                visit::walk_ty(self, ty)
2601            }
2602
2603            // A type may have an expression as a const generic argument.
2604            // We do not want to recurse into those.
2605            fn visit_expr(&mut self, _: &'ra Expr) {}
2606        }
2607
2608        /// Visitor which checks the referent of a &Thing to see if the
2609        /// Thing contains Self
2610        struct SelfVisitor<'a, 'ra, 'tcx> {
2611            r: &'a Resolver<'ra, 'tcx>,
2612            impl_self: Option<Res>,
2613            self_found: bool,
2614        }
2615
2616        impl SelfVisitor<'_, '_, '_> {
2617            // Look for `self: &'a Self` - also desugared from `&'a self`
2618            fn is_self_ty(&self, ty: &Ty) -> bool {
2619                match ty.kind {
2620                    TyKind::ImplicitSelf => true,
2621                    TyKind::Path(None, _) => {
2622                        let path_res = self.r.partial_res_map[&ty.id].full_res();
2623                        if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2624                            return true;
2625                        }
2626                        self.impl_self.is_some() && path_res == self.impl_self
2627                    }
2628                    _ => false,
2629                }
2630            }
2631        }
2632
2633        impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2634            fn visit_ty(&mut self, ty: &'ra Ty) {
2635                {
    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:2635",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2635u32),
                        ::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);
2636                if self.is_self_ty(ty) {
2637                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2637",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2637u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("SelfVisitor found Self")
                                            as &dyn Value))])
            });
    } else { ; }
};trace!("SelfVisitor found Self");
2638                    self.self_found = true;
2639                }
2640                visit::walk_ty(self, ty)
2641            }
2642
2643            // A type may have an expression as a const generic argument.
2644            // We do not want to recurse into those.
2645            fn visit_expr(&mut self, _: &'ra Expr) {}
2646        }
2647
2648        let impl_self = self
2649            .diag_metadata
2650            .current_self_type
2651            .as_ref()
2652            .and_then(|ty| {
2653                if let TyKind::Path(None, _) = ty.kind {
2654                    self.r.partial_res_map.get(&ty.id)
2655                } else {
2656                    None
2657                }
2658            })
2659            .and_then(|res| res.full_res())
2660            .filter(|res| {
2661                // Permit the types that unambiguously always
2662                // result in the same type constructor being used
2663                // (it can't differ between `Self` and `self`).
2664                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _) |
        Res::PrimTy(_) => true,
    _ => false,
}matches!(
2665                    res,
2666                    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2667                )
2668            });
2669        let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2670        visitor.visit_ty(ty);
2671        {
    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:2671",
                        "rustc_resolve::late", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2671u32),
                        ::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);
2672        visitor.lifetime
2673    }
2674
2675    /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
2676    /// label and reports an error if the label is not found or is unreachable.
2677    fn resolve_label(&self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2678        let mut suggestion = None;
2679
2680        for i in (0..self.label_ribs.len()).rev() {
2681            let rib = &self.label_ribs[i];
2682
2683            if let RibKind::MacroDefinition(def) = rib.kind
2684                // If an invocation of this macro created `ident`, give up on `ident`
2685                // and switch to `ident`'s source from the macro definition.
2686                && def == self.r.macro_def(label.span.ctxt())
2687            {
2688                label.span.remove_mark();
2689            }
2690
2691            let ident = label.normalize_to_macro_rules();
2692            if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2693                let definition_span = ident.span;
2694                return if self.is_label_valid_from_rib(i) {
2695                    Ok((*id, definition_span))
2696                } else {
2697                    Err(ResolutionError::UnreachableLabel {
2698                        name: label.name,
2699                        definition_span,
2700                        suggestion,
2701                    })
2702                };
2703            }
2704
2705            // Diagnostics: Check if this rib contains a label with a similar name, keep track of
2706            // the first such label that is encountered.
2707            suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2708        }
2709
2710        Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2711    }
2712
2713    /// Determine whether or not a label from the `rib_index`th label rib is reachable.
2714    fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2715        let ribs = &self.label_ribs[rib_index + 1..];
2716        ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2717    }
2718
2719    fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2720        {
    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:2720",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2720u32),
                        ::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");
2721        let kind = self.r.local_def_kind(item.id);
2722        self.with_current_self_item(item, |this| {
2723            this.with_generic_param_rib(
2724                &generics.params,
2725                RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2726                item.id,
2727                LifetimeBinderKind::Item,
2728                generics.span,
2729                |this| {
2730                    let item_def_id = this.r.local_def_id(item.id).to_def_id();
2731                    this.with_self_rib(
2732                        Res::SelfTyAlias { alias_to: item_def_id, is_trait_impl: false },
2733                        |this| {
2734                            visit::walk_item(this, item);
2735                        },
2736                    );
2737                },
2738            );
2739        });
2740    }
2741
2742    fn future_proof_import(&mut self, use_tree: &UseTree) {
2743        if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2744            let ident = segment.ident;
2745            if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2746                return;
2747            }
2748
2749            let nss = match use_tree.kind {
2750                UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2751                _ => &[TypeNS],
2752            };
2753            let report_error = |this: &Self, ns| {
2754                if this.should_report_errs() {
2755                    let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2756                    this.r.dcx().emit_err(errors::ImportsCannotReferTo { span: ident.span, what });
2757                }
2758            };
2759
2760            for &ns in nss {
2761                match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2762                    Some(LateDecl::RibDef(..)) => {
2763                        report_error(self, ns);
2764                    }
2765                    Some(LateDecl::Decl(binding)) => {
2766                        if let Some(LateDecl::RibDef(..)) =
2767                            self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2768                        {
2769                            report_error(self, ns);
2770                        }
2771                    }
2772                    None => {}
2773                }
2774            }
2775        } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2776            for (use_tree, _) in items {
2777                self.future_proof_import(use_tree);
2778            }
2779        }
2780    }
2781
2782    fn resolve_item(&mut self, item: &'ast Item) {
2783        let mod_inner_docs =
2784            #[allow(non_exhaustive_omitted_patterns)] match item.kind {
    ItemKind::Mod(..) => true,
    _ => false,
}matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2785        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(..)) {
2786            self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2787        }
2788
2789        {
    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:2789",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(2789u32),
                        ::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);
2790
2791        let def_kind = self.r.local_def_kind(item.id);
2792        match &item.kind {
2793            ItemKind::TyAlias(box TyAlias { generics, .. }) => {
2794                self.with_generic_param_rib(
2795                    &generics.params,
2796                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2797                    item.id,
2798                    LifetimeBinderKind::Item,
2799                    generics.span,
2800                    |this| visit::walk_item(this, item),
2801                );
2802            }
2803
2804            ItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
2805                self.with_generic_param_rib(
2806                    &generics.params,
2807                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2808                    item.id,
2809                    LifetimeBinderKind::Function,
2810                    generics.span,
2811                    |this| visit::walk_item(this, item),
2812                );
2813                self.resolve_define_opaques(define_opaque);
2814            }
2815
2816            ItemKind::Enum(_, generics, _)
2817            | ItemKind::Struct(_, generics, _)
2818            | ItemKind::Union(_, generics, _) => {
2819                self.resolve_adt(item, generics);
2820            }
2821
2822            ItemKind::Impl(Impl { generics, of_trait, self_ty, items: impl_items, .. }) => {
2823                self.diag_metadata.current_impl_items = Some(impl_items);
2824                self.resolve_implementation(
2825                    &item.attrs,
2826                    generics,
2827                    of_trait.as_deref(),
2828                    self_ty,
2829                    item.id,
2830                    impl_items,
2831                );
2832                self.diag_metadata.current_impl_items = None;
2833            }
2834
2835            ItemKind::Trait(box Trait { generics, bounds, items, impl_restriction, .. }) => {
2836                // resolve paths for `impl` restrictions
2837                self.resolve_impl_restriction_path(impl_restriction);
2838
2839                // Create a new rib for the trait-wide type parameters.
2840                self.with_generic_param_rib(
2841                    &generics.params,
2842                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2843                    item.id,
2844                    LifetimeBinderKind::Item,
2845                    generics.span,
2846                    |this| {
2847                        let local_def_id = this.r.local_def_id(item.id).to_def_id();
2848                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2849                            this.visit_generics(generics);
2850                            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);
2851                            this.resolve_trait_items(items);
2852                        });
2853                    },
2854                );
2855            }
2856
2857            ItemKind::TraitAlias(box TraitAlias { generics, bounds, .. }) => {
2858                // Create a new rib for the trait-wide type parameters.
2859                self.with_generic_param_rib(
2860                    &generics.params,
2861                    RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2862                    item.id,
2863                    LifetimeBinderKind::Item,
2864                    generics.span,
2865                    |this| {
2866                        let local_def_id = this.r.local_def_id(item.id).to_def_id();
2867                        this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2868                            this.visit_generics(generics);
2869                            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);
2870                        });
2871                    },
2872                );
2873            }
2874
2875            ItemKind::Mod(..) => {
2876                let module = self.r.expect_module(self.r.local_def_id(item.id).to_def_id());
2877                let orig_module = replace(&mut self.parent_scope.module, module);
2878                self.with_rib(ValueNS, RibKind::Module(module.expect_local()), |this| {
2879                    this.with_rib(TypeNS, RibKind::Module(module.expect_local()), |this| {
2880                        if mod_inner_docs {
2881                            this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2882                        }
2883                        let old_macro_rules = this.parent_scope.macro_rules;
2884                        visit::walk_item(this, item);
2885                        // Maintain macro_rules scopes in the same way as during early resolution
2886                        // for diagnostics and doc links.
2887                        if item.attrs.iter().all(|attr| {
2888                            !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2889                        }) {
2890                            this.parent_scope.macro_rules = old_macro_rules;
2891                        }
2892                    })
2893                });
2894                self.parent_scope.module = orig_module;
2895            }
2896
2897            ItemKind::Static(box ast::StaticItem {
2898                ident,
2899                ty,
2900                expr,
2901                define_opaque,
2902                eii_impls,
2903                ..
2904            }) => {
2905                self.with_static_rib(def_kind, |this| {
2906                    this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2907                        this.visit_ty(ty);
2908                    });
2909                    if let Some(expr) = expr {
2910                        // We already forbid generic params because of the above item rib,
2911                        // so it doesn't matter whether this is a trivial constant.
2912                        this.resolve_static_body(expr, Some((*ident, ConstantItemKind::Static)));
2913                    }
2914                });
2915                self.resolve_define_opaques(define_opaque);
2916                self.resolve_eii(&eii_impls);
2917            }
2918
2919            ItemKind::Const(box ast::ConstItem {
2920                ident,
2921                generics,
2922                ty,
2923                rhs_kind,
2924                define_opaque,
2925                defaultness: _,
2926            }) => {
2927                self.with_generic_param_rib(
2928                    &generics.params,
2929                    RibKind::Item(
2930                        if self.r.tcx.features().generic_const_items() {
2931                            HasGenericParams::Yes(generics.span)
2932                        } else {
2933                            HasGenericParams::No
2934                        },
2935                        def_kind,
2936                    ),
2937                    item.id,
2938                    LifetimeBinderKind::ConstItem,
2939                    generics.span,
2940                    |this| {
2941                        this.visit_generics(generics);
2942
2943                        this.with_lifetime_rib(
2944                            LifetimeRibKind::Elided(LifetimeRes::Static),
2945                            |this| {
2946                                if rhs_kind.is_type_const()
2947                                    && !this.r.tcx.features().generic_const_parameter_types()
2948                                {
2949                                    this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
2950                                        this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
2951                                            this.with_lifetime_rib(
2952                                                LifetimeRibKind::ConstParamTy,
2953                                                |this| this.visit_ty(ty),
2954                                            )
2955                                        })
2956                                    });
2957                                } else {
2958                                    this.visit_ty(ty);
2959                                }
2960                            },
2961                        );
2962
2963                        this.resolve_const_item_rhs(
2964                            rhs_kind,
2965                            Some((*ident, ConstantItemKind::Const)),
2966                        );
2967                    },
2968                );
2969                self.resolve_define_opaques(define_opaque);
2970            }
2971            ItemKind::ConstBlock(ConstBlockItem { id: _, span: _, block }) => self
2972                .with_generic_param_rib(
2973                    &[],
2974                    RibKind::Item(HasGenericParams::No, def_kind),
2975                    item.id,
2976                    LifetimeBinderKind::ConstItem,
2977                    DUMMY_SP,
2978                    |this| {
2979                        this.with_lifetime_rib(
2980                            LifetimeRibKind::Elided(LifetimeRes::Infer),
2981                            |this| {
2982                                this.with_constant_rib(
2983                                    IsRepeatExpr::No,
2984                                    ConstantHasGenerics::Yes,
2985                                    Some((ConstBlockItem::IDENT, ConstantItemKind::Const)),
2986                                    |this| this.resolve_labeled_block(None, block.id, block),
2987                                )
2988                            },
2989                        );
2990                    },
2991                ),
2992
2993            ItemKind::Use(use_tree) => {
2994                let maybe_exported = match use_tree.kind {
2995                    UseTreeKind::Simple(_) | UseTreeKind::Glob(_) => MaybeExported::Ok(item.id),
2996                    UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
2997                };
2998                self.resolve_doc_links(&item.attrs, maybe_exported);
2999
3000                self.future_proof_import(use_tree);
3001            }
3002
3003            ItemKind::MacroDef(_, macro_def) => {
3004                // Maintain macro_rules scopes in the same way as during early resolution
3005                // for diagnostics and doc links.
3006                if macro_def.macro_rules {
3007                    let def_id = self.r.local_def_id(item.id);
3008                    self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
3009                }
3010
3011                if let Some(EiiDecl { foreign_item: extern_item_path, impl_unsafe: _ }) =
3012                    &macro_def.eii_declaration
3013                {
3014                    self.smart_resolve_path(
3015                        item.id,
3016                        &None,
3017                        extern_item_path,
3018                        PathSource::ExternItemImpl,
3019                    );
3020                }
3021            }
3022
3023            ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
3024                visit::walk_item(self, item);
3025            }
3026
3027            ItemKind::Delegation(delegation) => {
3028                let span = delegation.path.segments.last().unwrap().ident.span;
3029                self.with_generic_param_rib(
3030                    &[],
3031                    RibKind::Item(HasGenericParams::Yes(span), def_kind),
3032                    item.id,
3033                    LifetimeBinderKind::Function,
3034                    span,
3035                    |this| this.resolve_delegation(delegation, item.id, false),
3036                );
3037            }
3038
3039            ItemKind::ExternCrate(..) => {}
3040
3041            ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
3042                {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3043            }
3044        }
3045    }
3046
3047    fn with_generic_param_rib<F>(
3048        &mut self,
3049        params: &[GenericParam],
3050        kind: RibKind<'ra>,
3051        binder: NodeId,
3052        generics_kind: LifetimeBinderKind,
3053        generics_span: Span,
3054        f: F,
3055    ) where
3056        F: FnOnce(&mut Self),
3057    {
3058        {
    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:3058",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3058u32),
                        ::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");
3059        let lifetime_kind =
3060            LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind };
3061
3062        let mut function_type_rib = Rib::new(kind);
3063        let mut function_value_rib = Rib::new(kind);
3064        let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
3065
3066        // Only check for shadowed bindings if we're declaring new params.
3067        if !params.is_empty() {
3068            let mut seen_bindings = FxHashMap::default();
3069            // Store all seen lifetimes names from outer scopes.
3070            let mut seen_lifetimes = FxHashSet::default();
3071
3072            // We also can't shadow bindings from associated parent items.
3073            for ns in [ValueNS, TypeNS] {
3074                for parent_rib in self.ribs[ns].iter().rev() {
3075                    // Break at module or block level, to account for nested items which are
3076                    // allowed to shadow generic param names.
3077                    if #[allow(non_exhaustive_omitted_patterns)] match parent_rib.kind {
    RibKind::Module(..) | RibKind::Block(..) => true,
    _ => false,
}matches!(parent_rib.kind, RibKind::Module(..) | RibKind::Block(..)) {
3078                        break;
3079                    }
3080
3081                    seen_bindings
3082                        .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
3083                }
3084            }
3085
3086            // Forbid shadowing lifetime bindings
3087            for rib in self.lifetime_ribs.iter().rev() {
3088                seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
3089                if let LifetimeRibKind::Item = rib.kind {
3090                    break;
3091                }
3092            }
3093
3094            for param in params {
3095                let ident = param.ident.normalize_to_macros_2_0();
3096                {
    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:3096",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3096u32),
                        ::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);
3097
3098                if let GenericParamKind::Lifetime = param.kind
3099                    && let Some(&original) = seen_lifetimes.get(&ident)
3100                {
3101                    let guar = diagnostics::signal_lifetime_shadowing(
3102                        self.r.tcx.sess,
3103                        original,
3104                        param.ident,
3105                    );
3106                    // Record lifetime res, so lowering knows there is something fishy.
3107                    self.record_lifetime_param(param.id, LifetimeRes::Error(guar));
3108                    continue;
3109                }
3110
3111                match seen_bindings.entry(ident) {
3112                    Entry::Occupied(entry) => {
3113                        let span = *entry.get();
3114                        let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
3115                        let guar = self.r.report_error(param.ident.span, err);
3116                        let rib = match param.kind {
3117                            GenericParamKind::Lifetime => {
3118                                // Record lifetime res, so lowering knows there is something fishy.
3119                                self.record_lifetime_param(param.id, LifetimeRes::Error(guar));
3120                                continue;
3121                            }
3122                            GenericParamKind::Type { .. } => &mut function_type_rib,
3123                            GenericParamKind::Const { .. } => &mut function_value_rib,
3124                        };
3125
3126                        // Taint the resolution in case of errors to prevent follow up errors in typeck
3127                        self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
3128                        rib.bindings.insert(ident, Res::Err);
3129                        continue;
3130                    }
3131                    Entry::Vacant(entry) => {
3132                        entry.insert(param.ident.span);
3133                    }
3134                }
3135
3136                if param.ident.name == kw::UnderscoreLifetime {
3137                    // To avoid emitting two similar errors,
3138                    // we need to check if the span is a raw underscore lifetime, see issue #143152
3139                    let is_raw_underscore_lifetime = self
3140                        .r
3141                        .tcx
3142                        .sess
3143                        .psess
3144                        .raw_identifier_spans
3145                        .iter()
3146                        .any(|span| span == param.span());
3147
3148                    let guar = self
3149                        .r
3150                        .dcx()
3151                        .create_err(errors::UnderscoreLifetimeIsReserved { span: param.ident.span })
3152                        .emit_unless_delay(is_raw_underscore_lifetime);
3153                    // Record lifetime res, so lowering knows there is something fishy.
3154                    self.record_lifetime_param(param.id, LifetimeRes::Error(guar));
3155                    continue;
3156                }
3157
3158                if param.ident.name == kw::StaticLifetime {
3159                    let guar = self.r.dcx().emit_err(errors::StaticLifetimeIsReserved {
3160                        span: param.ident.span,
3161                        lifetime: param.ident,
3162                    });
3163                    // Record lifetime res, so lowering knows there is something fishy.
3164                    self.record_lifetime_param(param.id, LifetimeRes::Error(guar));
3165                    continue;
3166                }
3167
3168                let def_id = self.r.local_def_id(param.id);
3169
3170                // Plain insert (no renaming).
3171                let (rib, def_kind) = match param.kind {
3172                    GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
3173                    GenericParamKind::Const { .. } => {
3174                        (&mut function_value_rib, DefKind::ConstParam)
3175                    }
3176                    GenericParamKind::Lifetime => {
3177                        let res = LifetimeRes::Param { param: def_id, binder };
3178                        self.record_lifetime_param(param.id, res);
3179                        function_lifetime_rib.bindings.insert(ident, (param.id, res));
3180                        continue;
3181                    }
3182                };
3183
3184                let res = match kind {
3185                    RibKind::Item(..) | RibKind::AssocItem => {
3186                        Res::Def(def_kind, def_id.to_def_id())
3187                    }
3188                    RibKind::Normal => {
3189                        // FIXME(non_lifetime_binders): Stop special-casing
3190                        // const params to error out here.
3191                        if self.r.tcx.features().non_lifetime_binders()
3192                            && #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    GenericParamKind::Type { .. } => true,
    _ => false,
}matches!(param.kind, GenericParamKind::Type { .. })
3193                        {
3194                            Res::Def(def_kind, def_id.to_def_id())
3195                        } else {
3196                            Res::Err
3197                        }
3198                    }
3199                    _ => ::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),
3200                };
3201                self.r.record_partial_res(param.id, PartialRes::new(res));
3202                rib.bindings.insert(ident, res);
3203            }
3204        }
3205
3206        self.lifetime_ribs.push(function_lifetime_rib);
3207        self.ribs[ValueNS].push(function_value_rib);
3208        self.ribs[TypeNS].push(function_type_rib);
3209
3210        f(self);
3211
3212        self.ribs[TypeNS].pop();
3213        self.ribs[ValueNS].pop();
3214        let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
3215
3216        // Do not account for the parameters we just bound for function lifetime elision.
3217        if let Some(ref mut candidates) = self.lifetime_elision_candidates {
3218            for (_, res) in function_lifetime_rib.bindings.values() {
3219                candidates.retain(|(r, _)| r != res);
3220            }
3221        }
3222
3223        if let LifetimeBinderKind::FnPtrType
3224        | LifetimeBinderKind::WhereBound
3225        | LifetimeBinderKind::Function
3226        | LifetimeBinderKind::ImplBlock = generics_kind
3227        {
3228            self.maybe_report_lifetime_uses(generics_span, params)
3229        }
3230    }
3231
3232    fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
3233        self.label_ribs.push(Rib::new(kind));
3234        f(self);
3235        self.label_ribs.pop();
3236    }
3237
3238    fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
3239        let kind = RibKind::Item(HasGenericParams::No, def_kind);
3240        self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
3241    }
3242
3243    // HACK(min_const_generics, generic_const_exprs): We
3244    // want to keep allowing `[0; size_of::<*mut T>()]`
3245    // with a future compat lint for now. We do this by adding an
3246    // additional special case for repeat expressions.
3247    //
3248    // Note that we intentionally still forbid `[0; N + 1]` during
3249    // name resolution so that we don't extend the future
3250    // compat lint to new cases.
3251    #[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(3251u32),
                                    ::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))]
3252    fn with_constant_rib(
3253        &mut self,
3254        is_repeat: IsRepeatExpr,
3255        may_use_generics: ConstantHasGenerics,
3256        item: Option<(Ident, ConstantItemKind)>,
3257        f: impl FnOnce(&mut Self),
3258    ) {
3259        let f = |this: &mut Self| {
3260            this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3261                this.with_rib(
3262                    TypeNS,
3263                    RibKind::ConstantItem(
3264                        may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3265                        item,
3266                    ),
3267                    |this| {
3268                        this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3269                    },
3270                )
3271            })
3272        };
3273
3274        if let ConstantHasGenerics::No(cause) = may_use_generics {
3275            self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3276        } else {
3277            f(self)
3278        }
3279    }
3280
3281    fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
3282        // Handle nested impls (inside fn bodies)
3283        let previous_value =
3284            replace(&mut self.diag_metadata.current_self_type, Some(self_type.clone()));
3285        let result = f(self);
3286        self.diag_metadata.current_self_type = previous_value;
3287        result
3288    }
3289
3290    fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3291        let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3292        let result = f(self);
3293        self.diag_metadata.current_self_item = previous_value;
3294        result
3295    }
3296
3297    /// When evaluating a `trait` use its associated types' idents for suggestions in E0425.
3298    fn resolve_trait_items(&mut self, trait_items: &'ast [Box<AssocItem>]) {
3299        let trait_assoc_items =
3300            replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3301
3302        let walk_assoc_item =
3303            |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3304                this.with_generic_param_rib(
3305                    &generics.params,
3306                    RibKind::AssocItem,
3307                    item.id,
3308                    kind,
3309                    generics.span,
3310                    |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3311                );
3312            };
3313
3314        for item in trait_items {
3315            self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3316            match &item.kind {
3317                AssocItemKind::Const(box ast::ConstItem {
3318                    generics,
3319                    ty,
3320                    rhs_kind,
3321                    define_opaque,
3322                    ..
3323                }) => {
3324                    self.with_generic_param_rib(
3325                        &generics.params,
3326                        RibKind::AssocItem,
3327                        item.id,
3328                        LifetimeBinderKind::ConstItem,
3329                        generics.span,
3330                        |this| {
3331                            this.with_lifetime_rib(
3332                                LifetimeRibKind::StaticIfNoLifetimeInScope {
3333                                    lint_id: item.id,
3334                                    emit_lint: false,
3335                                },
3336                                |this| {
3337                                    this.visit_generics(generics);
3338                                    if rhs_kind.is_type_const()
3339                                        && !this.r.tcx.features().generic_const_parameter_types()
3340                                    {
3341                                        this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3342                                            this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
3343                                                this.with_lifetime_rib(
3344                                                    LifetimeRibKind::ConstParamTy,
3345                                                    |this| this.visit_ty(ty),
3346                                                )
3347                                            })
3348                                        });
3349                                    } else {
3350                                        this.visit_ty(ty);
3351                                    }
3352
3353                                    // Only impose the restrictions of `ConstRibKind` for an
3354                                    // actual constant expression in a provided default.
3355                                    //
3356                                    // We allow arbitrary const expressions inside of associated consts,
3357                                    // even if they are potentially not const evaluatable.
3358                                    //
3359                                    // Type parameters can already be used and as associated consts are
3360                                    // not used as part of the type system, this is far less surprising.
3361                                    this.resolve_const_item_rhs(rhs_kind, None);
3362                                },
3363                            )
3364                        },
3365                    );
3366
3367                    self.resolve_define_opaques(define_opaque);
3368                }
3369                AssocItemKind::Fn(box Fn { generics, define_opaque, .. }) => {
3370                    walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3371
3372                    self.resolve_define_opaques(define_opaque);
3373                }
3374                AssocItemKind::Delegation(delegation) => {
3375                    self.with_generic_param_rib(
3376                        &[],
3377                        RibKind::AssocItem,
3378                        item.id,
3379                        LifetimeBinderKind::Function,
3380                        delegation.path.segments.last().unwrap().ident.span,
3381                        |this| this.resolve_delegation(delegation, item.id, false),
3382                    );
3383                }
3384                AssocItemKind::Type(box TyAlias { generics, .. }) => self
3385                    .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3386                        walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3387                    }),
3388                AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3389                    {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3390                }
3391            };
3392        }
3393
3394        self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3395    }
3396
3397    /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
3398    fn with_optional_trait_ref<T>(
3399        &mut self,
3400        opt_trait_ref: Option<&TraitRef>,
3401        self_type: &'ast Ty,
3402        f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3403    ) -> T {
3404        let mut new_val = None;
3405        let mut new_id = None;
3406        if let Some(trait_ref) = opt_trait_ref {
3407            let path: Vec<_> = Segment::from_path(&trait_ref.path);
3408            self.diag_metadata.currently_processing_impl_trait =
3409                Some((trait_ref.clone(), self_type.clone()));
3410            let res = self.smart_resolve_path_fragment(
3411                &None,
3412                &path,
3413                PathSource::Trait(AliasPossibility::No),
3414                Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3415                RecordPartialRes::Yes,
3416                None,
3417            );
3418            self.diag_metadata.currently_processing_impl_trait = None;
3419            if let Some(def_id) = res.expect_full_res().opt_def_id() {
3420                new_id = Some(def_id);
3421                new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3422            }
3423        }
3424        let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3425        let result = f(self, new_id);
3426        self.current_trait_ref = original_trait_ref;
3427        result
3428    }
3429
3430    fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3431        let mut self_type_rib = Rib::new(RibKind::Normal);
3432
3433        // Plain insert (no renaming, since types are not currently hygienic)
3434        self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3435        self.ribs[ns].push(self_type_rib);
3436        f(self);
3437        self.ribs[ns].pop();
3438    }
3439
3440    fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3441        self.with_self_rib_ns(TypeNS, self_res, f)
3442    }
3443
3444    fn resolve_implementation(
3445        &mut self,
3446        attrs: &[ast::Attribute],
3447        generics: &'ast Generics,
3448        of_trait: Option<&'ast ast::TraitImplHeader>,
3449        self_type: &'ast Ty,
3450        item_id: NodeId,
3451        impl_items: &'ast [Box<AssocItem>],
3452    ) {
3453        {
    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:3453",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3453u32),
                        ::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");
3454        // If applicable, create a rib for the type parameters.
3455        self.with_generic_param_rib(
3456            &generics.params,
3457            RibKind::Item(HasGenericParams::Yes(generics.span), self.r.local_def_kind(item_id)),
3458            item_id,
3459            LifetimeBinderKind::ImplBlock,
3460            generics.span,
3461            |this| {
3462                // Dummy self type for better errors if `Self` is used in the trait path.
3463                this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3464                    this.with_lifetime_rib(
3465                        LifetimeRibKind::AnonymousCreateParameter {
3466                            binder: item_id,
3467                            report_in_path: true
3468                        },
3469                        |this| {
3470                            // Resolve the trait reference, if necessary.
3471                            this.with_optional_trait_ref(
3472                                of_trait.map(|t| &t.trait_ref),
3473                                self_type,
3474                                |this, trait_id| {
3475                                    this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3476
3477                                    let item_def_id = this.r.local_def_id(item_id);
3478
3479                                    // Register the trait definitions from here.
3480                                    if let Some(trait_id) = trait_id {
3481                                        this.r
3482                                            .trait_impls
3483                                            .entry(trait_id)
3484                                            .or_default()
3485                                            .push(item_def_id);
3486                                    }
3487
3488                                    let item_def_id = item_def_id.to_def_id();
3489                                    let res = Res::SelfTyAlias {
3490                                        alias_to: item_def_id,
3491                                        is_trait_impl: trait_id.is_some(),
3492                                    };
3493                                    this.with_self_rib(res, |this| {
3494                                        if let Some(of_trait) = of_trait {
3495                                            // Resolve type arguments in the trait path.
3496                                            visit::walk_trait_ref(this, &of_trait.trait_ref);
3497                                        }
3498                                        // Resolve the self type.
3499                                        this.visit_ty(self_type);
3500                                        // Resolve the generic parameters.
3501                                        this.visit_generics(generics);
3502
3503                                        // Resolve the items within the impl.
3504                                        this.with_current_self_type(self_type, |this| {
3505                                            this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3506                                                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3506",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3506u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("resolve_implementation with_self_rib_ns(ValueNS, ...)")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
3507                                                let mut seen_trait_items = Default::default();
3508                                                for item in impl_items {
3509                                                    this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id, of_trait.is_some());
3510                                                }
3511                                            });
3512                                        });
3513                                    });
3514                                },
3515                            )
3516                        },
3517                    );
3518                });
3519            },
3520        );
3521    }
3522
3523    fn resolve_impl_item(
3524        &mut self,
3525        item: &'ast AssocItem,
3526        seen_trait_items: &mut FxHashMap<DefId, Span>,
3527        trait_id: Option<DefId>,
3528        is_in_trait_impl: bool,
3529    ) {
3530        use crate::ResolutionError::*;
3531        self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3532        let prev = self.diag_metadata.current_impl_item.take();
3533        self.diag_metadata.current_impl_item = Some(&item);
3534        match &item.kind {
3535            AssocItemKind::Const(box ast::ConstItem {
3536                ident,
3537                generics,
3538                ty,
3539                rhs_kind,
3540                define_opaque,
3541                ..
3542            }) => {
3543                {
    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:3543",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3543u32),
                        ::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");
3544                self.with_generic_param_rib(
3545                    &generics.params,
3546                    RibKind::AssocItem,
3547                    item.id,
3548                    LifetimeBinderKind::ConstItem,
3549                    generics.span,
3550                    |this| {
3551                        this.with_lifetime_rib(
3552                            // Until these are a hard error, we need to create them within the
3553                            // correct binder, Otherwise the lifetimes of this assoc const think
3554                            // they are lifetimes of the trait.
3555                            LifetimeRibKind::AnonymousCreateParameter {
3556                                binder: item.id,
3557                                report_in_path: true,
3558                            },
3559                            |this| {
3560                                this.with_lifetime_rib(
3561                                    LifetimeRibKind::StaticIfNoLifetimeInScope {
3562                                        lint_id: item.id,
3563                                        // In impls, it's not a hard error yet due to backcompat.
3564                                        emit_lint: true,
3565                                    },
3566                                    |this| {
3567                                        // If this is a trait impl, ensure the const
3568                                        // exists in trait
3569                                        this.check_trait_item(
3570                                            item.id,
3571                                            *ident,
3572                                            &item.kind,
3573                                            ValueNS,
3574                                            item.span,
3575                                            seen_trait_items,
3576                                            |i, s, c| ConstNotMemberOfTrait(i, s, c),
3577                                        );
3578
3579                                        this.visit_generics(generics);
3580                                        if rhs_kind.is_type_const()
3581                                            && !this
3582                                                .r
3583                                                .tcx
3584                                                .features()
3585                                                .generic_const_parameter_types()
3586                                        {
3587                                            this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3588                                                this.with_rib(
3589                                                    ValueNS,
3590                                                    RibKind::ConstParamTy,
3591                                                    |this| {
3592                                                        this.with_lifetime_rib(
3593                                                            LifetimeRibKind::ConstParamTy,
3594                                                            |this| this.visit_ty(ty),
3595                                                        )
3596                                                    },
3597                                                )
3598                                            });
3599                                        } else {
3600                                            this.visit_ty(ty);
3601                                        }
3602                                        // We allow arbitrary const expressions inside of associated consts,
3603                                        // even if they are potentially not const evaluatable.
3604                                        //
3605                                        // Type parameters can already be used and as associated consts are
3606                                        // not used as part of the type system, this is far less surprising.
3607                                        this.resolve_const_item_rhs(rhs_kind, None);
3608                                    },
3609                                )
3610                            },
3611                        );
3612                    },
3613                );
3614                self.resolve_define_opaques(define_opaque);
3615            }
3616            AssocItemKind::Fn(box Fn { ident, generics, define_opaque, .. }) => {
3617                {
    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:3617",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3617u32),
                        ::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");
3618                // We also need a new scope for the impl item type parameters.
3619                self.with_generic_param_rib(
3620                    &generics.params,
3621                    RibKind::AssocItem,
3622                    item.id,
3623                    LifetimeBinderKind::Function,
3624                    generics.span,
3625                    |this| {
3626                        // If this is a trait impl, ensure the method
3627                        // exists in trait
3628                        this.check_trait_item(
3629                            item.id,
3630                            *ident,
3631                            &item.kind,
3632                            ValueNS,
3633                            item.span,
3634                            seen_trait_items,
3635                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3636                        );
3637
3638                        visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3639                    },
3640                );
3641
3642                self.resolve_define_opaques(define_opaque);
3643            }
3644            AssocItemKind::Type(box TyAlias { ident, generics, .. }) => {
3645                self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3646                {
    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:3646",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3646u32),
                        ::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");
3647                // We also need a new scope for the impl item type parameters.
3648                self.with_generic_param_rib(
3649                    &generics.params,
3650                    RibKind::AssocItem,
3651                    item.id,
3652                    LifetimeBinderKind::ImplAssocType,
3653                    generics.span,
3654                    |this| {
3655                        this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3656                            // If this is a trait impl, ensure the type
3657                            // exists in trait
3658                            this.check_trait_item(
3659                                item.id,
3660                                *ident,
3661                                &item.kind,
3662                                TypeNS,
3663                                item.span,
3664                                seen_trait_items,
3665                                |i, s, c| TypeNotMemberOfTrait(i, s, c),
3666                            );
3667
3668                            visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3669                        });
3670                    },
3671                );
3672                self.diag_metadata.in_non_gat_assoc_type = None;
3673            }
3674            AssocItemKind::Delegation(box delegation) => {
3675                {
    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:3675",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3675u32),
                        ::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");
3676                self.with_generic_param_rib(
3677                    &[],
3678                    RibKind::AssocItem,
3679                    item.id,
3680                    LifetimeBinderKind::Function,
3681                    delegation.path.segments.last().unwrap().ident.span,
3682                    |this| {
3683                        this.check_trait_item(
3684                            item.id,
3685                            delegation.ident,
3686                            &item.kind,
3687                            ValueNS,
3688                            item.span,
3689                            seen_trait_items,
3690                            |i, s, c| MethodNotMemberOfTrait(i, s, c),
3691                        );
3692
3693                        // Here we don't use `trait_id`, as we can process unresolved trait, however
3694                        // in this case we are still in a trait impl, https://github.com/rust-lang/rust/issues/150152
3695                        this.resolve_delegation(delegation, item.id, is_in_trait_impl);
3696                    },
3697                );
3698            }
3699            AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3700                {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3701            }
3702        }
3703        self.diag_metadata.current_impl_item = prev;
3704    }
3705
3706    fn check_trait_item<F>(
3707        &mut self,
3708        id: NodeId,
3709        mut ident: Ident,
3710        kind: &AssocItemKind,
3711        ns: Namespace,
3712        span: Span,
3713        seen_trait_items: &mut FxHashMap<DefId, Span>,
3714        err: F,
3715    ) where
3716        F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3717    {
3718        // If there is a TraitRef in scope for an impl, then the method must be in the trait.
3719        let Some((module, _)) = self.current_trait_ref else {
3720            return;
3721        };
3722        ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3723        let key = BindingKey::new(IdentKey::new(ident), ns);
3724        let mut decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3725        {
    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:3725",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3725u32),
                        ::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);
3726        if decl.is_none() {
3727            // We could not find the trait item in the correct namespace.
3728            // Check the other namespace to report an error.
3729            let ns = match ns {
3730                ValueNS => TypeNS,
3731                TypeNS => ValueNS,
3732                _ => ns,
3733            };
3734            let key = BindingKey::new(IdentKey::new(ident), ns);
3735            decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3736            {
    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:3736",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3736u32),
                        ::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);
3737        }
3738
3739        let feed_visibility = |this: &mut Self, def_id| {
3740            let vis = this.r.tcx.visibility(def_id);
3741            let vis = if vis.is_visible_locally() {
3742                vis.expect_local()
3743            } else {
3744                this.r.dcx().span_delayed_bug(
3745                    span,
3746                    "error should be emitted when an unexpected trait item is used",
3747                );
3748                Visibility::Public
3749            };
3750            this.r.feed_visibility(this.r.feed(id), vis);
3751        };
3752
3753        let Some(decl) = decl else {
3754            // We could not find the method: report an error.
3755            let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
3756            let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3757            let path_names = path_names_to_string(path);
3758            self.report_error(span, err(ident, path_names, candidate));
3759            feed_visibility(self, module.def_id());
3760            return;
3761        };
3762
3763        let res = decl.res();
3764        let Res::Def(def_kind, id_in_trait) = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
3765        feed_visibility(self, id_in_trait);
3766
3767        match seen_trait_items.entry(id_in_trait) {
3768            Entry::Occupied(entry) => {
3769                self.report_error(
3770                    span,
3771                    ResolutionError::TraitImplDuplicate {
3772                        name: ident,
3773                        old_span: *entry.get(),
3774                        trait_item_span: decl.span,
3775                    },
3776                );
3777                return;
3778            }
3779            Entry::Vacant(entry) => {
3780                entry.insert(span);
3781            }
3782        };
3783
3784        match (def_kind, kind) {
3785            (DefKind::AssocTy, AssocItemKind::Type(..))
3786            | (DefKind::AssocFn, AssocItemKind::Fn(..))
3787            | (DefKind::AssocConst { .. }, AssocItemKind::Const(..))
3788            | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3789                self.r.record_partial_res(id, PartialRes::new(res));
3790                return;
3791            }
3792            _ => {}
3793        }
3794
3795        // The method kind does not correspond to what appeared in the trait, report.
3796        let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3797        let (code, kind) = match kind {
3798            AssocItemKind::Const(..) => (E0323, "const"),
3799            AssocItemKind::Fn(..) => (E0324, "method"),
3800            AssocItemKind::Type(..) => (E0325, "type"),
3801            AssocItemKind::Delegation(..) => (E0324, "method"),
3802            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3803                ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("unexpanded macro"))span_bug!(span, "unexpanded macro")
3804            }
3805        };
3806        let trait_path = path_names_to_string(path);
3807        self.report_error(
3808            span,
3809            ResolutionError::TraitImplMismatch {
3810                name: ident,
3811                kind,
3812                code,
3813                trait_path,
3814                trait_item_span: decl.span,
3815            },
3816        );
3817    }
3818
3819    fn resolve_static_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3820        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3821            this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3822                this.visit_expr(expr)
3823            });
3824        })
3825    }
3826
3827    fn resolve_const_item_rhs(
3828        &mut self,
3829        rhs_kind: &'ast ConstItemRhsKind,
3830        item: Option<(Ident, ConstantItemKind)>,
3831    ) {
3832        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| match rhs_kind {
3833            ConstItemRhsKind::TypeConst { rhs: Some(anon_const) } => {
3834                this.resolve_anon_const(anon_const, AnonConstKind::ConstArg(IsRepeatExpr::No));
3835            }
3836            ConstItemRhsKind::Body { rhs: Some(expr) } => {
3837                this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3838                    this.visit_expr(expr)
3839                });
3840            }
3841            _ => (),
3842        })
3843    }
3844
3845    fn resolve_delegation(
3846        &mut self,
3847        delegation: &'ast Delegation,
3848        item_id: NodeId,
3849        is_in_trait_impl: bool,
3850    ) {
3851        self.smart_resolve_path(
3852            delegation.id,
3853            &delegation.qself,
3854            &delegation.path,
3855            PathSource::Delegation,
3856        );
3857
3858        if let Some(qself) = &delegation.qself {
3859            self.visit_ty(&qself.ty);
3860        }
3861
3862        self.visit_path(&delegation.path);
3863
3864        self.r.delegation_infos.insert(
3865            self.r.local_def_id(item_id),
3866            DelegationInfo {
3867                resolution_node: if is_in_trait_impl { item_id } else { delegation.id },
3868            },
3869        );
3870
3871        let Some(body) = &delegation.body else { return };
3872        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3873            let ident = Ident::new(kw::SelfLower, body.span.normalize_to_macro_rules());
3874            let res = Res::Local(delegation.id);
3875            this.innermost_rib_bindings(ValueNS).insert(ident, res);
3876
3877            //As we lower target_expr_template body to a body of a function we need a label rib (#148889)
3878            this.with_label_rib(RibKind::FnOrCoroutine, |this| {
3879                this.visit_block(body);
3880            });
3881        });
3882    }
3883
3884    fn resolve_params(&mut self, params: &'ast [Param]) {
3885        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())];
3886        self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
3887            for Param { pat, .. } in params {
3888                this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3889            }
3890            this.apply_pattern_bindings(bindings);
3891        });
3892        for Param { ty, .. } in params {
3893            self.visit_ty(ty);
3894        }
3895    }
3896
3897    fn resolve_local(&mut self, local: &'ast Local) {
3898        {
    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:3898",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(3898u32),
                        ::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);
3899        // Resolve the type.
3900        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);
3901
3902        // Resolve the initializer.
3903        if let Some((init, els)) = local.kind.init_else_opt() {
3904            self.visit_expr(init);
3905
3906            // Resolve the `else` block
3907            if let Some(els) = els {
3908                self.visit_block(els);
3909            }
3910        }
3911
3912        // Resolve the pattern.
3913        self.resolve_pattern_top(&local.pat, PatternSource::Let);
3914    }
3915
3916    /// Build a map from pattern identifiers to binding-info's, and check the bindings are
3917    /// consistent when encountering or-patterns and never patterns.
3918    /// This is done hygienically: this could arise for a macro that expands into an or-pattern
3919    /// where one 'x' was from the user and one 'x' came from the macro.
3920    ///
3921    /// A never pattern by definition indicates an unreachable case. For example, matching on
3922    /// `Result<T, &!>` could look like:
3923    /// ```rust
3924    /// # #![feature(never_type)]
3925    /// # #![feature(never_patterns)]
3926    /// # fn bar(_x: u32) {}
3927    /// let foo: Result<u32, &!> = Ok(0);
3928    /// match foo {
3929    ///     Ok(x) => bar(x),
3930    ///     Err(&!),
3931    /// }
3932    /// ```
3933    /// This extends to product types: `(x, !)` is likewise unreachable. So it doesn't make sense to
3934    /// have a binding here, and we tell the user to use `_` instead.
3935    fn compute_and_check_binding_map(
3936        &mut self,
3937        pat: &Pat,
3938    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3939        let mut binding_map = FxIndexMap::default();
3940        let mut is_never_pat = false;
3941
3942        pat.walk(&mut |pat| {
3943            match pat.kind {
3944                PatKind::Ident(annotation, ident, ref sub_pat)
3945                    if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3946                {
3947                    binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3948                }
3949                PatKind::Or(ref ps) => {
3950                    // Check the consistency of this or-pattern and
3951                    // then add all bindings to the larger map.
3952                    match self.compute_and_check_or_pat_binding_map(ps) {
3953                        Ok(bm) => binding_map.extend(bm),
3954                        Err(IsNeverPattern) => is_never_pat = true,
3955                    }
3956                    return false;
3957                }
3958                PatKind::Never => is_never_pat = true,
3959                _ => {}
3960            }
3961
3962            true
3963        });
3964
3965        if is_never_pat {
3966            for (_, binding) in binding_map {
3967                self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3968            }
3969            Err(IsNeverPattern)
3970        } else {
3971            Ok(binding_map)
3972        }
3973    }
3974
3975    fn is_base_res_local(&self, nid: NodeId) -> bool {
3976        #[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!(
3977            self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
3978            Some(Res::Local(..))
3979        )
3980    }
3981
3982    /// Compute the binding map for an or-pattern. Checks that all of the arms in the or-pattern
3983    /// have exactly the same set of bindings, with the same binding modes for each.
3984    /// Returns the computed binding map and a boolean indicating whether the pattern is a never
3985    /// pattern.
3986    ///
3987    /// A never pattern by definition indicates an unreachable case. For example, destructuring a
3988    /// `Result<T, &!>` could look like:
3989    /// ```rust
3990    /// # #![feature(never_type)]
3991    /// # #![feature(never_patterns)]
3992    /// # fn foo() -> Result<bool, &'static !> { Ok(true) }
3993    /// let (Ok(x) | Err(&!)) = foo();
3994    /// # let _ = x;
3995    /// ```
3996    /// Because the `Err(&!)` branch is never reached, it does not need to have the same bindings as
3997    /// the other branches of the or-pattern. So we must ignore never pattern when checking the
3998    /// bindings of an or-pattern.
3999    /// Moreover, if all the subpatterns are never patterns (e.g. `Ok(!) | Err(!)`), then the
4000    /// pattern as a whole counts as a never pattern (since it's definitionallly unreachable).
4001    fn compute_and_check_or_pat_binding_map(
4002        &mut self,
4003        pats: &[Pat],
4004    ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
4005        let mut missing_vars = FxIndexMap::default();
4006        let mut inconsistent_vars = FxIndexMap::default();
4007
4008        // 1) Compute the binding maps of all arms; we must ignore never patterns here.
4009        let not_never_pats = pats
4010            .iter()
4011            .filter_map(|pat| {
4012                let binding_map = self.compute_and_check_binding_map(pat).ok()?;
4013                Some((binding_map, pat))
4014            })
4015            .collect::<Vec<_>>();
4016
4017        // 2) Record any missing bindings or binding mode inconsistencies.
4018        for &(ref map_outer, pat_outer) in not_never_pats.iter() {
4019            // Check against all arms except for the same pattern which is always self-consistent.
4020            let inners = not_never_pats.iter().filter(|(_, pat)| pat.id != pat_outer.id);
4021
4022            for &(ref map, pat) in inners {
4023                for (&name, binding_inner) in map {
4024                    match map_outer.get(&name) {
4025                        None => {
4026                            // The inner binding is missing in the outer.
4027                            let binding_error =
4028                                missing_vars.entry(name).or_insert_with(|| BindingError {
4029                                    name,
4030                                    origin: Default::default(),
4031                                    target: Default::default(),
4032                                    could_be_path: name.as_str().starts_with(char::is_uppercase),
4033                                });
4034                            binding_error.origin.push((binding_inner.span, pat.clone()));
4035                            binding_error.target.push(pat_outer.clone());
4036                        }
4037                        Some(binding_outer) => {
4038                            if binding_outer.annotation != binding_inner.annotation {
4039                                // The binding modes in the outer and inner bindings differ.
4040                                inconsistent_vars
4041                                    .entry(name)
4042                                    .or_insert((binding_inner.span, binding_outer.span));
4043                            }
4044                        }
4045                    }
4046                }
4047            }
4048        }
4049
4050        // 3) Report all missing variables we found.
4051        for (name, mut v) in missing_vars {
4052            if inconsistent_vars.contains_key(&name) {
4053                v.could_be_path = false;
4054            }
4055            self.report_error(
4056                v.origin.iter().next().unwrap().0,
4057                ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
4058            );
4059        }
4060
4061        // 4) Report all inconsistencies in binding modes we found.
4062        for (name, v) in inconsistent_vars {
4063            self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
4064        }
4065
4066        // 5) Bubble up the final binding map.
4067        if not_never_pats.is_empty() {
4068            // All the patterns are never patterns, so the whole or-pattern is one too.
4069            Err(IsNeverPattern)
4070        } else {
4071            let mut binding_map = FxIndexMap::default();
4072            for (bm, _) in not_never_pats {
4073                binding_map.extend(bm);
4074            }
4075            Ok(binding_map)
4076        }
4077    }
4078
4079    /// Check the consistency of bindings wrt or-patterns and never patterns.
4080    fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
4081        let mut is_or_or_never = false;
4082        pat.walk(&mut |pat| match pat.kind {
4083            PatKind::Or(..) | PatKind::Never => {
4084                is_or_or_never = true;
4085                false
4086            }
4087            _ => true,
4088        });
4089        if is_or_or_never {
4090            let _ = self.compute_and_check_binding_map(pat);
4091        }
4092    }
4093
4094    fn resolve_arm(&mut self, arm: &'ast Arm) {
4095        self.with_rib(ValueNS, RibKind::Normal, |this| {
4096            this.resolve_pattern_top(&arm.pat, PatternSource::Match);
4097            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));
4098            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);
4099        });
4100    }
4101
4102    /// Arising from `source`, resolve a top level pattern.
4103    fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
4104        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())];
4105        self.resolve_pattern(pat, pat_src, &mut bindings);
4106        self.apply_pattern_bindings(bindings);
4107    }
4108
4109    /// Apply the bindings from a pattern to the innermost rib of the current scope.
4110    fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
4111        let rib_bindings = self.innermost_rib_bindings(ValueNS);
4112        let Some((_, pat_bindings)) = pat_bindings.pop() else {
4113            ::rustc_middle::util::bug::bug_fmt(format_args!("tried applying nonexistent bindings from pattern"));bug!("tried applying nonexistent bindings from pattern");
4114        };
4115
4116        if rib_bindings.is_empty() {
4117            // Often, such as for match arms, the bindings are introduced into a new rib.
4118            // In this case, we can move the bindings over directly.
4119            *rib_bindings = pat_bindings;
4120        } else {
4121            rib_bindings.extend(pat_bindings);
4122        }
4123    }
4124
4125    /// Resolve bindings in a pattern. `apply_pattern_bindings` must be called after to introduce
4126    /// the bindings into scope.
4127    fn resolve_pattern(
4128        &mut self,
4129        pat: &'ast Pat,
4130        pat_src: PatternSource,
4131        bindings: &mut PatternBindings,
4132    ) {
4133        // We walk the pattern before declaring the pattern's inner bindings,
4134        // so that we avoid resolving a literal expression to a binding defined
4135        // by the pattern.
4136        // NB: `Self::visit_pat` must be used rather than `visit::walk_pat` to avoid resolving guard
4137        // patterns' guard expressions multiple times (#141265).
4138        self.visit_pat(pat);
4139        self.resolve_pattern_inner(pat, pat_src, bindings);
4140        // This has to happen *after* we determine which pat_idents are variants:
4141        self.check_consistent_bindings(pat);
4142    }
4143
4144    /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
4145    ///
4146    /// ### `bindings`
4147    ///
4148    /// A stack of sets of bindings accumulated.
4149    ///
4150    /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
4151    /// be interpreted as re-binding an already bound binding. This results in an error.
4152    /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
4153    /// in reusing this binding rather than creating a fresh one.
4154    ///
4155    /// When called at the top level, the stack must have a single element
4156    /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
4157    /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
4158    /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
4159    /// When each `p_i` has been dealt with, the top set is merged with its parent.
4160    /// When a whole or-pattern has been dealt with, the thing happens.
4161    ///
4162    /// See the implementation and `fresh_binding` for more details.
4163    #[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(4163u32),
                                    ::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")]
4164    fn resolve_pattern_inner(
4165        &mut self,
4166        pat: &'ast Pat,
4167        pat_src: PatternSource,
4168        bindings: &mut PatternBindings,
4169    ) {
4170        // Visit all direct subpatterns of this pattern.
4171        pat.walk(&mut |pat| {
4172            match pat.kind {
4173                PatKind::Ident(bmode, ident, ref sub) => {
4174                    // First try to resolve the identifier as some existing entity,
4175                    // then fall back to a fresh binding.
4176                    let has_sub = sub.is_some();
4177                    let res = self
4178                        .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
4179                        .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
4180                    self.r.record_partial_res(pat.id, PartialRes::new(res));
4181                    self.r.record_pat_span(pat.id, pat.span);
4182                }
4183                PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
4184                    self.smart_resolve_path(
4185                        pat.id,
4186                        qself,
4187                        path,
4188                        PathSource::TupleStruct(
4189                            pat.span,
4190                            self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
4191                        ),
4192                    );
4193                }
4194                PatKind::Path(ref qself, ref path) => {
4195                    self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
4196                }
4197                PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
4198                    self.smart_resolve_path(pat.id, qself, path, PathSource::Struct(None));
4199                    self.record_patterns_with_skipped_bindings(pat, rest);
4200                }
4201                PatKind::Or(ref ps) => {
4202                    // Add a new set of bindings to the stack. `Or` here records that when a
4203                    // binding already exists in this set, it should not result in an error because
4204                    // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
4205                    bindings.push((PatBoundCtx::Or, Default::default()));
4206                    for p in ps {
4207                        // Now we need to switch back to a product context so that each
4208                        // part of the or-pattern internally rejects already bound names.
4209                        // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
4210                        bindings.push((PatBoundCtx::Product, Default::default()));
4211                        self.resolve_pattern_inner(p, pat_src, bindings);
4212                        // Move up the non-overlapping bindings to the or-pattern.
4213                        // Existing bindings just get "merged".
4214                        let collected = bindings.pop().unwrap().1;
4215                        bindings.last_mut().unwrap().1.extend(collected);
4216                    }
4217                    // This or-pattern itself can itself be part of a product,
4218                    // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
4219                    // Both cases bind `a` again in a product pattern and must be rejected.
4220                    let collected = bindings.pop().unwrap().1;
4221                    bindings.last_mut().unwrap().1.extend(collected);
4222
4223                    // Prevent visiting `ps` as we've already done so above.
4224                    return false;
4225                }
4226                PatKind::Guard(ref subpat, ref guard) => {
4227                    // Add a new set of bindings to the stack to collect bindings in `subpat`.
4228                    bindings.push((PatBoundCtx::Product, Default::default()));
4229                    // Resolving `subpat` adds bindings onto the newly-pushed context. After, the
4230                    // total number of contexts on the stack should be the same as before.
4231                    let binding_ctx_stack_len = bindings.len();
4232                    self.resolve_pattern_inner(subpat, pat_src, bindings);
4233                    assert_eq!(bindings.len(), binding_ctx_stack_len);
4234                    // These bindings, but none from the surrounding pattern, are visible in the
4235                    // guard; put them in scope and resolve `guard`.
4236                    let subpat_bindings = bindings.pop().unwrap().1;
4237                    self.with_rib(ValueNS, RibKind::Normal, |this| {
4238                        *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
4239                        this.resolve_expr(&guard.cond, None);
4240                    });
4241                    // Propagate the subpattern's bindings upwards.
4242                    // FIXME(guard_patterns): For `if let` guards, we'll also need to get the
4243                    // bindings introduced by the guard from its rib and propagate them upwards.
4244                    // This will require checking the identifiers for overlaps with `bindings`, like
4245                    // what `fresh_binding` does (ideally sharing its logic). To keep them separate
4246                    // from `subpat_bindings`, we can introduce a fresh rib for the guard.
4247                    bindings.last_mut().unwrap().1.extend(subpat_bindings);
4248                    // Prevent visiting `subpat` as we've already done so above.
4249                    return false;
4250                }
4251                _ => {}
4252            }
4253            true
4254        });
4255    }
4256
4257    fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
4258        match rest {
4259            ast::PatFieldsRest::Rest(_) | ast::PatFieldsRest::Recovered(_) => {
4260                // Record that the pattern doesn't introduce all the bindings it could.
4261                if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
4262                    && let Some(res) = partial_res.full_res()
4263                    && let Some(def_id) = res.opt_def_id()
4264                {
4265                    self.ribs[ValueNS]
4266                        .last_mut()
4267                        .unwrap()
4268                        .patterns_with_skipped_bindings
4269                        .entry(def_id)
4270                        .or_default()
4271                        .push((
4272                            pat.span,
4273                            match rest {
4274                                ast::PatFieldsRest::Recovered(guar) => Err(*guar),
4275                                _ => Ok(()),
4276                            },
4277                        ));
4278                }
4279            }
4280            ast::PatFieldsRest::None => {}
4281        }
4282    }
4283
4284    fn fresh_binding(
4285        &mut self,
4286        ident: Ident,
4287        pat_id: NodeId,
4288        pat_src: PatternSource,
4289        bindings: &mut PatternBindings,
4290    ) -> Res {
4291        // Add the binding to the bindings map, if it doesn't already exist.
4292        // (We must not add it if it's in the bindings map because that breaks the assumptions
4293        // later passes make about or-patterns.)
4294        let ident = ident.normalize_to_macro_rules();
4295
4296        // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
4297        let already_bound_and = bindings
4298            .iter()
4299            .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
4300        if already_bound_and {
4301            // Overlap in a product pattern somewhere; report an error.
4302            use ResolutionError::*;
4303            let error = match pat_src {
4304                // `fn f(a: u8, a: u8)`:
4305                PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
4306                // `Variant(a, a)`:
4307                _ => IdentifierBoundMoreThanOnceInSamePattern,
4308            };
4309            self.report_error(ident.span, error(ident));
4310        }
4311
4312        // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
4313        // This is *required* for consistency which is checked later.
4314        let already_bound_or = bindings
4315            .iter()
4316            .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
4317        let res = if let Some(&res) = already_bound_or {
4318            // `Variant1(a) | Variant2(a)`, ok
4319            // Reuse definition from the first `a`.
4320            res
4321        } else {
4322            // A completely fresh binding is added to the map.
4323            Res::Local(pat_id)
4324        };
4325
4326        // Record as bound.
4327        bindings.last_mut().unwrap().1.insert(ident, res);
4328        res
4329    }
4330
4331    fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4332        &mut self.ribs[ns].last_mut().unwrap().bindings
4333    }
4334
4335    fn try_resolve_as_non_binding(
4336        &mut self,
4337        pat_src: PatternSource,
4338        ann: BindingMode,
4339        ident: Ident,
4340        has_sub: bool,
4341    ) -> Option<Res> {
4342        // An immutable (no `mut`) by-value (no `ref`) binding pattern without
4343        // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
4344        // also be interpreted as a path to e.g. a constant, variant, etc.
4345        let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4346
4347        let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4348        let (res, binding) = match ls_binding {
4349            LateDecl::Decl(binding)
4350                if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4351            {
4352                // For ambiguous bindings we don't know all their definitions and cannot check
4353                // whether they can be shadowed by fresh bindings or not, so force an error.
4354                // issues/33118#issuecomment-233962221 (see below) still applies here,
4355                // but we have to ignore it for backward compatibility.
4356                self.r.record_use(ident, binding, Used::Other);
4357                return None;
4358            }
4359            LateDecl::Decl(binding) => (binding.res(), Some(binding)),
4360            LateDecl::RibDef(res) => (res, None),
4361        };
4362
4363        match res {
4364            Res::SelfCtor(_) // See #70549.
4365            | Res::Def(
4366                DefKind::Ctor(_, CtorKind::Const) | DefKind::Const { .. } | DefKind::AssocConst { .. } | DefKind::ConstParam,
4367                _,
4368            ) if is_syntactic_ambiguity => {
4369                // Disambiguate in favor of a unit struct/variant or constant pattern.
4370                if let Some(binding) = binding {
4371                    self.r.record_use(ident, binding, Used::Other);
4372                }
4373                Some(res)
4374            }
4375            Res::Def(DefKind::Ctor(..) | DefKind::Const { .. } | DefKind::AssocConst { .. } | DefKind::Static { .. }, _) => {
4376                // This is unambiguously a fresh binding, either syntactically
4377                // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
4378                // to something unusable as a pattern (e.g., constructor function),
4379                // but we still conservatively report an error, see
4380                // issues/33118#issuecomment-233962221 for one reason why.
4381                let binding = binding.expect("no binding for a ctor or static");
4382                self.report_error(
4383                    ident.span,
4384                    ResolutionError::BindingShadowsSomethingUnacceptable {
4385                        shadowing_binding: pat_src,
4386                        name: ident.name,
4387                        participle: if binding.is_import() { "imported" } else { "defined" },
4388                        article: binding.res().article(),
4389                        shadowed_binding: binding.res(),
4390                        shadowed_binding_span: binding.span,
4391                    },
4392                );
4393                None
4394            }
4395            Res::Def(DefKind::ConstParam, def_id) => {
4396                // Same as for DefKind::Const { .. } above, but here, `binding` is `None`, so we
4397                // have to construct the error differently
4398                self.report_error(
4399                    ident.span,
4400                    ResolutionError::BindingShadowsSomethingUnacceptable {
4401                        shadowing_binding: pat_src,
4402                        name: ident.name,
4403                        participle: "defined",
4404                        article: res.article(),
4405                        shadowed_binding: res,
4406                        shadowed_binding_span: self.r.def_span(def_id),
4407                    }
4408                );
4409                None
4410            }
4411            Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4412                // These entities are explicitly allowed to be shadowed by fresh bindings.
4413                None
4414            }
4415            Res::SelfCtor(_) => {
4416                // We resolve `Self` in pattern position as an ident sometimes during recovery,
4417                // so delay a bug instead of ICEing.
4418                self.r.dcx().span_delayed_bug(
4419                    ident.span,
4420                    "unexpected `SelfCtor` in pattern, expected identifier"
4421                );
4422                None
4423            }
4424            _ => ::rustc_middle::util::bug::span_bug_fmt(ident.span,
    format_args!("unexpected resolution for an identifier in pattern: {0:?}",
        res))span_bug!(
4425                ident.span,
4426                "unexpected resolution for an identifier in pattern: {:?}",
4427                res,
4428            ),
4429        }
4430    }
4431
4432    fn resolve_impl_restriction_path(&mut self, restriction: &'ast ast::ImplRestriction) {
4433        match &restriction.kind {
4434            ast::RestrictionKind::Unrestricted => (),
4435            ast::RestrictionKind::Restricted { path, id, shorthand: _ } => {
4436                self.smart_resolve_path(*id, &None, path, PathSource::Module);
4437                if let Some(res) = self.r.partial_res_map[&id].full_res()
4438                    && let Some(def_id) = res.opt_def_id()
4439                {
4440                    if !self.r.is_accessible_from(
4441                        Visibility::Restricted(def_id),
4442                        self.parent_scope.module,
4443                    ) {
4444                        self.r.dcx().create_err(errors::RestrictionAncestorOnly(path.span)).emit();
4445                    }
4446                }
4447            }
4448        }
4449    }
4450
4451    // High-level and context dependent path resolution routine.
4452    // Resolves the path and records the resolution into definition map.
4453    // If resolution fails tries several techniques to find likely
4454    // resolution candidates, suggest imports or other help, and report
4455    // errors in user friendly way.
4456    fn smart_resolve_path(
4457        &mut self,
4458        id: NodeId,
4459        qself: &Option<Box<QSelf>>,
4460        path: &Path,
4461        source: PathSource<'_, 'ast, 'ra>,
4462    ) {
4463        self.smart_resolve_path_fragment(
4464            qself,
4465            &Segment::from_path(path),
4466            source,
4467            Finalize::new(id, path.span),
4468            RecordPartialRes::Yes,
4469            None,
4470        );
4471    }
4472
4473    fn smart_resolve_path_fragment(
4474        &mut self,
4475        qself: &Option<Box<QSelf>>,
4476        path: &[Segment],
4477        source: PathSource<'_, 'ast, 'ra>,
4478        finalize: Finalize,
4479        record_partial_res: RecordPartialRes,
4480        parent_qself: Option<&QSelf>,
4481    ) -> PartialRes {
4482        let ns = source.namespace();
4483
4484        let Finalize { node_id, path_span, .. } = finalize;
4485        let report_errors = |this: &mut Self, res: Option<Res>| {
4486            if this.should_report_errs() {
4487                let (mut err, candidates) = this.smart_resolve_report_errors(
4488                    path,
4489                    None,
4490                    path_span,
4491                    source,
4492                    res,
4493                    parent_qself,
4494                );
4495
4496                let def_id = this.parent_scope.module.nearest_parent_mod();
4497                let instead = res.is_some();
4498                let (suggestion, const_err) = if let Some((start, end)) =
4499                    this.diag_metadata.in_range
4500                    && path[0].ident.span.lo() == end.span.lo()
4501                    && !#[allow(non_exhaustive_omitted_patterns)] match start.kind {
    ExprKind::Lit(_) => true,
    _ => false,
}matches!(start.kind, ExprKind::Lit(_))
4502                {
4503                    let mut sugg = ".";
4504                    let mut span = start.span.between(end.span);
4505                    if span.lo() + BytePos(2) == span.hi() {
4506                        // There's no space between the start, the range op and the end, suggest
4507                        // removal which will look better.
4508                        span = span.with_lo(span.lo() + BytePos(1));
4509                        sugg = "";
4510                    }
4511                    (
4512                        Some((
4513                            span,
4514                            "you might have meant to write `.` instead of `..`",
4515                            sugg.to_string(),
4516                            Applicability::MaybeIncorrect,
4517                        )),
4518                        None,
4519                    )
4520                } else if res.is_none()
4521                    && let PathSource::Type
4522                    | PathSource::Expr(_)
4523                    | PathSource::PreciseCapturingArg(..) = source
4524                {
4525                    this.suggest_adding_generic_parameter(path, source)
4526                } else {
4527                    (None, None)
4528                };
4529
4530                if let Some(const_err) = const_err {
4531                    err.cancel();
4532                    err = const_err;
4533                }
4534
4535                let ue = UseError {
4536                    err,
4537                    candidates,
4538                    def_id,
4539                    instead,
4540                    suggestion,
4541                    path: path.into(),
4542                    is_call: source.is_call(),
4543                };
4544
4545                this.r.use_injections.push(ue);
4546            }
4547
4548            PartialRes::new(Res::Err)
4549        };
4550
4551        // For paths originating from calls (like in `HashMap::new()`), tries
4552        // to enrich the plain `failed to resolve: ...` message with hints
4553        // about possible missing imports.
4554        //
4555        // Similar thing, for types, happens in `report_errors` above.
4556        let report_errors_for_call =
4557            |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4558                // Before we start looking for candidates, we have to get our hands
4559                // on the type user is trying to perform invocation on; basically:
4560                // we're transforming `HashMap::new` into just `HashMap`.
4561                let (following_seg, prefix_path) = match path.split_last() {
4562                    Some((last, path)) if !path.is_empty() => (Some(last), path),
4563                    _ => return Some(parent_err),
4564                };
4565
4566                let (mut err, candidates) = this.smart_resolve_report_errors(
4567                    prefix_path,
4568                    following_seg,
4569                    path_span,
4570                    PathSource::Type,
4571                    None,
4572                    parent_qself,
4573                );
4574
4575                // There are two different error messages user might receive at
4576                // this point:
4577                // - E0425 cannot find type `{}` in this scope
4578                // - E0433 failed to resolve: use of undeclared type or module `{}`
4579                //
4580                // The first one is emitted for paths in type-position, and the
4581                // latter one - for paths in expression-position.
4582                //
4583                // Thus (since we're in expression-position at this point), not to
4584                // confuse the user, we want to keep the *message* from E0433 (so
4585                // `parent_err`), but we want *hints* from E0425 (so `err`).
4586                //
4587                // And that's what happens below - we're just mixing both messages
4588                // into a single one.
4589                let failed_to_resolve = match parent_err.node {
4590                    ResolutionError::FailedToResolve { .. } => true,
4591                    _ => false,
4592                };
4593                let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4594
4595                // overwrite all properties with the parent's error message
4596                err.messages = take(&mut parent_err.messages);
4597                err.code = take(&mut parent_err.code);
4598                swap(&mut err.span, &mut parent_err.span);
4599                if failed_to_resolve {
4600                    err.children = take(&mut parent_err.children);
4601                } else {
4602                    err.children.append(&mut parent_err.children);
4603                }
4604                err.sort_span = parent_err.sort_span;
4605                err.is_lint = parent_err.is_lint.clone();
4606
4607                // merge the parent_err's suggestions with the typo (err's) suggestions
4608                match &mut err.suggestions {
4609                    Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4610                        Suggestions::Enabled(parent_suggestions) => {
4611                            // If both suggestions are enabled, append parent_err's suggestions to err's suggestions.
4612                            typo_suggestions.append(parent_suggestions)
4613                        }
4614                        Suggestions::Sealed(_) | Suggestions::Disabled => {
4615                            // If the parent's suggestions are either sealed or disabled, it signifies that
4616                            // new suggestions cannot be added or removed from the diagnostic. Therefore,
4617                            // we assign both types of suggestions to err's suggestions and discard the
4618                            // existing suggestions in err.
4619                            err.suggestions = std::mem::take(&mut parent_err.suggestions);
4620                        }
4621                    },
4622                    Suggestions::Sealed(_) | Suggestions::Disabled => (),
4623                }
4624
4625                parent_err.cancel();
4626
4627                let def_id = this.parent_scope.module.nearest_parent_mod();
4628
4629                if this.should_report_errs() {
4630                    if candidates.is_empty() {
4631                        if path.len() == 2
4632                            && let [segment] = prefix_path
4633                        {
4634                            // Delay to check whether method name is an associated function or not
4635                            // ```
4636                            // let foo = Foo {};
4637                            // foo::bar(); // possibly suggest to foo.bar();
4638                            //```
4639                            err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4640                        } else {
4641                            // When there is no suggested imports, we can just emit the error
4642                            // and suggestions immediately. Note that we bypass the usually error
4643                            // reporting routine (ie via `self.r.report_error`) because we need
4644                            // to post-process the `ResolutionError` above.
4645                            err.emit();
4646                        }
4647                    } else {
4648                        // If there are suggested imports, the error reporting is delayed
4649                        this.r.use_injections.push(UseError {
4650                            err,
4651                            candidates,
4652                            def_id,
4653                            instead: false,
4654                            suggestion: None,
4655                            path: prefix_path.into(),
4656                            is_call: source.is_call(),
4657                        });
4658                    }
4659                } else {
4660                    err.cancel();
4661                }
4662
4663                // We don't return `Some(parent_err)` here, because the error will
4664                // be already printed either immediately or as part of the `use` injections
4665                None
4666            };
4667
4668        let partial_res = match self.resolve_qpath_anywhere(
4669            qself,
4670            path,
4671            ns,
4672            source.defer_to_typeck(),
4673            finalize,
4674            source,
4675        ) {
4676            Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4677                // if we also have an associated type that matches the ident, stash a suggestion
4678                if let Some(items) = self.diag_metadata.current_trait_assoc_items
4679                    && let [Segment { ident, .. }] = path
4680                    && items.iter().any(|item| {
4681                        if let AssocItemKind::Type(alias) = &item.kind
4682                            && alias.ident == *ident
4683                        {
4684                            true
4685                        } else {
4686                            false
4687                        }
4688                    })
4689                {
4690                    let mut diag = self.r.tcx.dcx().struct_allow("");
4691                    diag.span_suggestion_verbose(
4692                        path_span.shrink_to_lo(),
4693                        "there is an associated type with the same name",
4694                        "Self::",
4695                        Applicability::MaybeIncorrect,
4696                    );
4697                    diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4698                }
4699
4700                if source.is_expected(res) || res == Res::Err {
4701                    partial_res
4702                } else {
4703                    report_errors(self, Some(res))
4704                }
4705            }
4706
4707            Ok(Some(partial_res)) if source.defer_to_typeck() => {
4708                // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
4709                // or `<T>::A::B`. If `B` should be resolved in value namespace then
4710                // it needs to be added to the trait map.
4711                if ns == ValueNS {
4712                    let item_name = path.last().unwrap().ident;
4713                    let traits = self.traits_in_scope(item_name, ns);
4714                    self.r.trait_map.insert(node_id, traits);
4715                }
4716
4717                if PrimTy::from_name(path[0].ident.name).is_some() {
4718                    let mut std_path = Vec::with_capacity(1 + path.len());
4719
4720                    std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4721                    std_path.extend(path);
4722                    if let PathResult::Module(_) | PathResult::NonModule(_) =
4723                        self.resolve_path(&std_path, Some(ns), None, source)
4724                    {
4725                        // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
4726                        let item_span =
4727                            path.iter().last().map_or(path_span, |segment| segment.ident.span);
4728
4729                        self.r.confused_type_with_std_module.insert(item_span, path_span);
4730                        self.r.confused_type_with_std_module.insert(path_span, path_span);
4731                    }
4732                }
4733
4734                partial_res
4735            }
4736
4737            Err(err) => {
4738                if let Some(err) = report_errors_for_call(self, err) {
4739                    self.report_error(err.span, err.node);
4740                }
4741
4742                PartialRes::new(Res::Err)
4743            }
4744
4745            _ => report_errors(self, None),
4746        };
4747
4748        if record_partial_res == RecordPartialRes::Yes {
4749            // Avoid recording definition of `A::B` in `<T as A>::B::C`.
4750            self.r.record_partial_res(node_id, partial_res);
4751            self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4752            self.lint_unused_qualifications(path, ns, finalize);
4753        }
4754
4755        partial_res
4756    }
4757
4758    fn self_type_is_available(&mut self) -> bool {
4759        let binding = self
4760            .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4761        if let Some(LateDecl::RibDef(res)) = binding { res != Res::Err } else { false }
4762    }
4763
4764    fn self_value_is_available(&mut self, self_span: Span) -> bool {
4765        let ident = Ident::new(kw::SelfLower, self_span);
4766        let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4767        if let Some(LateDecl::RibDef(res)) = binding { res != Res::Err } else { false }
4768    }
4769
4770    /// A wrapper around [`Resolver::report_error`].
4771    ///
4772    /// This doesn't emit errors for function bodies if this is rustdoc.
4773    fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4774        if self.should_report_errs() {
4775            self.r.report_error(span, resolution_error);
4776        }
4777    }
4778
4779    #[inline]
4780    /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items or
4781    // an invalid `use foo::*;` was found, which can cause unbounded amounts of "item not found"
4782    // errors. We silence them all.
4783    fn should_report_errs(&self) -> bool {
4784        !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4785            && !self.r.glob_error.is_some()
4786    }
4787
4788    // Resolve in alternative namespaces if resolution in the primary namespace fails.
4789    fn resolve_qpath_anywhere(
4790        &mut self,
4791        qself: &Option<Box<QSelf>>,
4792        path: &[Segment],
4793        primary_ns: Namespace,
4794        defer_to_typeck: bool,
4795        finalize: Finalize,
4796        source: PathSource<'_, 'ast, 'ra>,
4797    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4798        let mut fin_res = None;
4799
4800        for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4801            if i == 0 || ns != primary_ns {
4802                match self.resolve_qpath(qself, path, ns, finalize, source)? {
4803                    Some(partial_res)
4804                        if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4805                    {
4806                        return Ok(Some(partial_res));
4807                    }
4808                    partial_res => {
4809                        if fin_res.is_none() {
4810                            fin_res = partial_res;
4811                        }
4812                    }
4813                }
4814            }
4815        }
4816
4817        if !(primary_ns != MacroNS) {
    ::core::panicking::panic("assertion failed: primary_ns != MacroNS")
};assert!(primary_ns != MacroNS);
4818        if qself.is_none()
4819            && let PathResult::NonModule(res) =
4820                self.r.cm().maybe_resolve_path(path, Some(MacroNS), &self.parent_scope, None)
4821        {
4822            return Ok(Some(res));
4823        }
4824
4825        Ok(fin_res)
4826    }
4827
4828    /// Handles paths that may refer to associated items.
4829    fn resolve_qpath(
4830        &mut self,
4831        qself: &Option<Box<QSelf>>,
4832        path: &[Segment],
4833        ns: Namespace,
4834        finalize: Finalize,
4835        source: PathSource<'_, 'ast, 'ra>,
4836    ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4837        {
    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:4837",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(4837u32),
                        ::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!(
4838            "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4839            qself, path, ns, finalize,
4840        );
4841
4842        if let Some(qself) = qself {
4843            if qself.position == 0 {
4844                // This is a case like `<T>::B`, where there is no
4845                // trait to resolve. In that case, we leave the `B`
4846                // segment to be resolved by type-check.
4847                return Ok(Some(PartialRes::with_unresolved_segments(
4848                    Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4849                    path.len(),
4850                )));
4851            }
4852
4853            let num_privacy_errors = self.r.privacy_errors.len();
4854            // Make sure that `A` in `<T as A>::B::C` is a trait.
4855            let trait_res = self.smart_resolve_path_fragment(
4856                &None,
4857                &path[..qself.position],
4858                PathSource::Trait(AliasPossibility::No),
4859                Finalize::new(finalize.node_id, qself.path_span),
4860                RecordPartialRes::No,
4861                Some(&qself),
4862            );
4863
4864            if trait_res.expect_full_res() == Res::Err {
4865                return Ok(Some(trait_res));
4866            }
4867
4868            // Truncate additional privacy errors reported above,
4869            // because they'll be recomputed below.
4870            self.r.privacy_errors.truncate(num_privacy_errors);
4871
4872            // Make sure `A::B` in `<T as A>::B::C` is a trait item.
4873            //
4874            // Currently, `path` names the full item (`A::B::C`, in
4875            // our example). so we extract the prefix of that that is
4876            // the trait (the slice upto and including
4877            // `qself.position`). And then we recursively resolve that,
4878            // but with `qself` set to `None`.
4879            let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4880            let partial_res = self.smart_resolve_path_fragment(
4881                &None,
4882                &path[..=qself.position],
4883                PathSource::TraitItem(ns, &source),
4884                Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4885                RecordPartialRes::No,
4886                Some(&qself),
4887            );
4888
4889            // The remaining segments (the `C` in our example) will
4890            // have to be resolved by type-check, since that requires doing
4891            // trait resolution.
4892            return Ok(Some(PartialRes::with_unresolved_segments(
4893                partial_res.base_res(),
4894                partial_res.unresolved_segments() + path.len() - qself.position - 1,
4895            )));
4896        }
4897
4898        let result = match self.resolve_path(path, Some(ns), Some(finalize), source) {
4899            PathResult::NonModule(path_res) => path_res,
4900            PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4901                PartialRes::new(module.res().unwrap())
4902            }
4903            // A part of this path references a `mod` that had a parse error. To avoid resolution
4904            // errors for each reference to that module, we don't emit an error for them until the
4905            // `mod` is fixed. this can have a significant cascade effect.
4906            PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4907                PartialRes::new(Res::Err)
4908            }
4909            // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
4910            // don't report an error right away, but try to fallback to a primitive type.
4911            // So, we are still able to successfully resolve something like
4912            //
4913            // use std::u8; // bring module u8 in scope
4914            // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
4915            //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
4916            //                     // not to nonexistent std::u8::max_value
4917            // }
4918            //
4919            // Such behavior is required for backward compatibility.
4920            // The same fallback is used when `a` resolves to nothing.
4921            PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4922                if (ns == TypeNS || path.len() > 1)
4923                    && PrimTy::from_name(path[0].ident.name).is_some() =>
4924            {
4925                let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4926                let tcx = self.r.tcx();
4927
4928                let gate_err_sym_msg = match prim {
4929                    PrimTy::Float(FloatTy::F16) if !tcx.features().f16() => {
4930                        Some((sym::f16, "the type `f16` is unstable"))
4931                    }
4932                    PrimTy::Float(FloatTy::F128) if !tcx.features().f128() => {
4933                        Some((sym::f128, "the type `f128` is unstable"))
4934                    }
4935                    _ => None,
4936                };
4937
4938                if let Some((sym, msg)) = gate_err_sym_msg {
4939                    let span = path[0].ident.span;
4940                    if !span.allows_unstable(sym) {
4941                        feature_err(tcx.sess, sym, span, msg).emit();
4942                    }
4943                };
4944
4945                // Fix up partial res of segment from `resolve_path` call.
4946                if let Some(id) = path[0].id {
4947                    self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
4948                }
4949
4950                PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
4951            }
4952            PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4953                PartialRes::new(module.res().unwrap())
4954            }
4955            PathResult::Failed {
4956                is_error_from_last_segment: false,
4957                span,
4958                label,
4959                suggestion,
4960                module,
4961                segment_name,
4962                error_implied_by_parse_error: _,
4963                message,
4964            } => {
4965                return Err(respan(
4966                    span,
4967                    ResolutionError::FailedToResolve {
4968                        segment: segment_name,
4969                        label,
4970                        suggestion,
4971                        module,
4972                        message,
4973                    },
4974                ));
4975            }
4976            PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
4977            PathResult::Indeterminate => ::rustc_middle::util::bug::bug_fmt(format_args!("indeterminate path result in resolve_qpath"))bug!("indeterminate path result in resolve_qpath"),
4978        };
4979
4980        Ok(Some(result))
4981    }
4982
4983    fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
4984        if let Some(label) = label {
4985            if label.ident.as_str().as_bytes()[1] != b'_' {
4986                self.diag_metadata.unused_labels.insert(id, label.ident.span);
4987            }
4988
4989            if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
4990                diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
4991            }
4992
4993            self.with_label_rib(RibKind::Normal, |this| {
4994                let ident = label.ident.normalize_to_macro_rules();
4995                this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
4996                f(this);
4997            });
4998        } else {
4999            f(self);
5000        }
5001    }
5002
5003    fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
5004        self.with_resolved_label(label, id, |this| this.visit_block(block));
5005    }
5006
5007    fn resolve_block(&mut self, block: &'ast Block) {
5008        {
    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:5008",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5008u32),
                        ::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");
5009        // Move down in the graph, if there's an anonymous module rooted here.
5010        let orig_module = self.parent_scope.module;
5011        let anonymous_module = self.r.block_map.get(&block.id).copied();
5012
5013        let mut num_macro_definition_ribs = 0;
5014        if let Some(anonymous_module) = anonymous_module {
5015            {
    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:5015",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5015u32),
                        ::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");
5016            self.ribs[ValueNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
5017            self.ribs[TypeNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
5018            self.parent_scope.module = anonymous_module.to_module();
5019        } else {
5020            self.ribs[ValueNS].push(Rib::new(RibKind::Block(None)));
5021        }
5022
5023        // Descend into the block.
5024        for stmt in &block.stmts {
5025            if let StmtKind::Item(ref item) = stmt.kind
5026                && let ItemKind::MacroDef(..) = item.kind
5027            {
5028                num_macro_definition_ribs += 1;
5029                let res = self.r.local_def_id(item.id).to_def_id();
5030                self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
5031                self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
5032            }
5033
5034            self.visit_stmt(stmt);
5035        }
5036
5037        // Move back up.
5038        self.parent_scope.module = orig_module;
5039        for _ in 0..num_macro_definition_ribs {
5040            self.ribs[ValueNS].pop();
5041            self.label_ribs.pop();
5042        }
5043        self.last_block_rib = self.ribs[ValueNS].pop();
5044        if anonymous_module.is_some() {
5045            self.ribs[TypeNS].pop();
5046        }
5047        {
    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:5047",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5047u32),
                        ::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");
5048    }
5049
5050    fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
5051        {
    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:5051",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5051u32),
                        ::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!(
5052            "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
5053            constant, anon_const_kind
5054        );
5055
5056        let is_trivial_const_arg = constant.value.is_potential_trivial_const_arg();
5057        self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
5058            this.resolve_expr(&constant.value, None)
5059        })
5060    }
5061
5062    /// There are a few places that we need to resolve an anon const but we did not parse an
5063    /// anon const so cannot provide an `&'ast AnonConst`. Right now this is just unbraced
5064    /// const arguments that were parsed as type arguments, and `legacy_const_generics` which
5065    /// parse as normal function argument expressions. To avoid duplicating the code for resolving
5066    /// an anon const we have this function which lets the caller manually call `resolve_expr` or
5067    /// `smart_resolve_path`.
5068    fn resolve_anon_const_manual(
5069        &mut self,
5070        is_trivial_const_arg: bool,
5071        anon_const_kind: AnonConstKind,
5072        resolve_expr: impl FnOnce(&mut Self),
5073    ) {
5074        let is_repeat_expr = match anon_const_kind {
5075            AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
5076            _ => IsRepeatExpr::No,
5077        };
5078
5079        let may_use_generics = match anon_const_kind {
5080            AnonConstKind::EnumDiscriminant => {
5081                ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
5082            }
5083            AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
5084            AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
5085            AnonConstKind::ConstArg(_) => {
5086                if self.r.tcx.features().generic_const_exprs()
5087                    || self.r.tcx.features().min_generic_const_args()
5088                    || is_trivial_const_arg
5089                {
5090                    ConstantHasGenerics::Yes
5091                } else {
5092                    ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
5093                }
5094            }
5095        };
5096
5097        self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
5098            this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
5099                resolve_expr(this);
5100            });
5101        });
5102    }
5103
5104    fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
5105        self.resolve_expr(&f.expr, Some(e));
5106        self.visit_ident(&f.ident);
5107        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());
5108    }
5109
5110    fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
5111        // First, record candidate traits for this expression if it could
5112        // result in the invocation of a method call.
5113
5114        self.record_candidate_traits_for_expr_if_necessary(expr);
5115
5116        // Next, resolve the node.
5117        match expr.kind {
5118            ExprKind::Path(ref qself, ref path) => {
5119                self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
5120                visit::walk_expr(self, expr);
5121            }
5122
5123            ExprKind::Struct(ref se) => {
5124                self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct(parent));
5125                // This is the same as `visit::walk_expr(self, expr);`, but we want to pass the
5126                // parent in for accurate suggestions when encountering `Foo { bar }` that should
5127                // have been `Foo { bar: self.bar }`.
5128                if let Some(qself) = &se.qself {
5129                    self.visit_ty(&qself.ty);
5130                }
5131                self.visit_path(&se.path);
5132                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);
5133                match &se.rest {
5134                    StructRest::Base(expr) => self.visit_expr(expr),
5135                    StructRest::Rest(_span) => {}
5136                    StructRest::None | StructRest::NoneWithError(_) => {}
5137                }
5138            }
5139
5140            ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
5141                match self.resolve_label(label.ident) {
5142                    Ok((node_id, _)) => {
5143                        // Since this res is a label, it is never read.
5144                        self.r.label_res_map.insert(expr.id, node_id);
5145                        self.diag_metadata.unused_labels.swap_remove(&node_id);
5146                    }
5147                    Err(error) => {
5148                        self.report_error(label.ident.span, error);
5149                    }
5150                }
5151
5152                // visit `break` argument if any
5153                visit::walk_expr(self, expr);
5154            }
5155
5156            ExprKind::Break(None, Some(ref e)) => {
5157                // We use this instead of `visit::walk_expr` to keep the parent expr around for
5158                // better diagnostics.
5159                self.resolve_expr(e, Some(expr));
5160            }
5161
5162            ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
5163                self.visit_expr(scrutinee);
5164                self.resolve_pattern_top(pat, PatternSource::Let);
5165            }
5166
5167            ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
5168                self.visit_expr(scrutinee);
5169                // This is basically a tweaked, inlined `resolve_pattern_top`.
5170                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())];
5171                self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
5172                // We still collect the bindings in this `let` expression which is in
5173                // an invalid position (and therefore shouldn't declare variables into
5174                // its parent scope). To avoid unnecessary errors though, we do just
5175                // reassign the resolutions to `Res::Err`.
5176                for (_, bindings) in &mut bindings {
5177                    for (_, binding) in bindings {
5178                        *binding = Res::Err;
5179                    }
5180                }
5181                self.apply_pattern_bindings(bindings);
5182            }
5183
5184            ExprKind::If(ref cond, ref then, ref opt_else) => {
5185                self.with_rib(ValueNS, RibKind::Normal, |this| {
5186                    let old = this.diag_metadata.in_if_condition.replace(cond);
5187                    this.visit_expr(cond);
5188                    this.diag_metadata.in_if_condition = old;
5189                    this.visit_block(then);
5190                });
5191                if let Some(expr) = opt_else {
5192                    self.visit_expr(expr);
5193                }
5194            }
5195
5196            ExprKind::Loop(ref block, label, _) => {
5197                self.resolve_labeled_block(label, expr.id, block)
5198            }
5199
5200            ExprKind::While(ref cond, ref block, label) => {
5201                self.with_resolved_label(label, expr.id, |this| {
5202                    this.with_rib(ValueNS, RibKind::Normal, |this| {
5203                        let old = this.diag_metadata.in_if_condition.replace(cond);
5204                        this.visit_expr(cond);
5205                        this.diag_metadata.in_if_condition = old;
5206                        this.visit_block(block);
5207                    })
5208                });
5209            }
5210
5211            ExprKind::ForLoop { ref pat, ref iter, ref body, label, kind: _ } => {
5212                self.visit_expr(iter);
5213                self.with_rib(ValueNS, RibKind::Normal, |this| {
5214                    this.resolve_pattern_top(pat, PatternSource::For);
5215                    this.resolve_labeled_block(label, expr.id, body);
5216                });
5217            }
5218
5219            ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
5220
5221            // Equivalent to `visit::walk_expr` + passing some context to children.
5222            ExprKind::Field(ref subexpression, _) => {
5223                self.resolve_expr(subexpression, Some(expr));
5224            }
5225            ExprKind::MethodCall(box MethodCall { ref seg, ref receiver, ref args, .. }) => {
5226                self.resolve_expr(receiver, Some(expr));
5227                for arg in args {
5228                    self.resolve_expr(arg, None);
5229                }
5230                self.visit_path_segment(seg);
5231            }
5232
5233            ExprKind::Call(ref callee, ref arguments) => {
5234                self.resolve_expr(callee, Some(expr));
5235                let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
5236                for (idx, argument) in arguments.iter().enumerate() {
5237                    // Constant arguments need to be treated as AnonConst since
5238                    // that is how they will be later lowered to HIR.
5239                    if const_args.contains(&idx) {
5240                        // FIXME(mgca): legacy const generics doesn't support mgca but maybe
5241                        // that's okay.
5242                        let is_trivial_const_arg = argument.is_potential_trivial_const_arg();
5243                        self.resolve_anon_const_manual(
5244                            is_trivial_const_arg,
5245                            AnonConstKind::ConstArg(IsRepeatExpr::No),
5246                            |this| this.resolve_expr(argument, None),
5247                        );
5248                    } else {
5249                        self.resolve_expr(argument, None);
5250                    }
5251                }
5252            }
5253            ExprKind::Type(ref _type_expr, ref _ty) => {
5254                visit::walk_expr(self, expr);
5255            }
5256            // For closures, RibKind::FnOrCoroutine is added in visit_fn
5257            ExprKind::Closure(box ast::Closure {
5258                binder: ClosureBinder::For { ref generic_params, span },
5259                ..
5260            }) => {
5261                self.with_generic_param_rib(
5262                    generic_params,
5263                    RibKind::Normal,
5264                    expr.id,
5265                    LifetimeBinderKind::Closure,
5266                    span,
5267                    |this| visit::walk_expr(this, expr),
5268                );
5269            }
5270            ExprKind::Closure(..) => visit::walk_expr(self, expr),
5271            ExprKind::Gen(..) => {
5272                self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
5273            }
5274            ExprKind::Repeat(ref elem, ref ct) => {
5275                self.visit_expr(elem);
5276                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
5277            }
5278            ExprKind::ConstBlock(ref ct) => {
5279                self.resolve_anon_const(ct, AnonConstKind::InlineConst);
5280            }
5281            ExprKind::Index(ref elem, ref idx, _) => {
5282                self.resolve_expr(elem, Some(expr));
5283                self.visit_expr(idx);
5284            }
5285            ExprKind::Assign(ref lhs, ref rhs, _) => {
5286                if !self.diag_metadata.is_assign_rhs {
5287                    self.diag_metadata.in_assignment = Some(expr);
5288                }
5289                self.visit_expr(lhs);
5290                self.diag_metadata.is_assign_rhs = true;
5291                self.diag_metadata.in_assignment = None;
5292                self.visit_expr(rhs);
5293                self.diag_metadata.is_assign_rhs = false;
5294            }
5295            ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
5296                self.diag_metadata.in_range = Some((start, end));
5297                self.resolve_expr(start, Some(expr));
5298                self.resolve_expr(end, Some(expr));
5299                self.diag_metadata.in_range = None;
5300            }
5301            _ => {
5302                visit::walk_expr(self, expr);
5303            }
5304        }
5305    }
5306
5307    fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
5308        match expr.kind {
5309            ExprKind::Field(_, ident) => {
5310                // #6890: Even though you can't treat a method like a field,
5311                // we need to add any trait methods we find that match the
5312                // field name so that we can do some nice error reporting
5313                // later on in typeck.
5314                let traits = self.traits_in_scope(ident, ValueNS);
5315                self.r.trait_map.insert(expr.id, traits);
5316            }
5317            ExprKind::MethodCall(ref call) => {
5318                {
    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:5318",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(5318u32),
                        ::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);
5319                let traits = self.traits_in_scope(call.seg.ident, ValueNS);
5320                self.r.trait_map.insert(expr.id, traits);
5321            }
5322            _ => {
5323                // Nothing to do.
5324            }
5325        }
5326    }
5327
5328    fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> &'tcx [TraitCandidate<'tcx>] {
5329        self.r.traits_in_scope(
5330            self.current_trait_ref.as_ref().map(|(module, _)| *module),
5331            &self.parent_scope,
5332            ident.span,
5333            Some((ident.name, ns)),
5334        )
5335    }
5336
5337    fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
5338        // FIXME: This caching may be incorrect in case of multiple `macro_rules`
5339        // items with the same name in the same module.
5340        // Also hygiene is not considered.
5341        let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
5342        let res = *doc_link_resolutions
5343            .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5344            .or_default()
5345            .entry((Symbol::intern(path_str), ns))
5346            .or_insert_with_key(|(path, ns)| {
5347                let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
5348                if let Some(res) = res
5349                    && let Some(def_id) = res.opt_def_id()
5350                    && self.is_invalid_proc_macro_item_for_doc(def_id)
5351                {
5352                    // Encoding def ids in proc macro crate metadata will ICE,
5353                    // because it will only store proc macros for it.
5354                    return None;
5355                }
5356                res
5357            });
5358        self.r.doc_link_resolutions = doc_link_resolutions;
5359        res
5360    }
5361
5362    fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5363        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)
5364            || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5365        {
5366            return false;
5367        }
5368        let Some(local_did) = did.as_local() else { return true };
5369        !self.r.proc_macros.contains(&local_did)
5370    }
5371
5372    fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5373        match self.r.tcx.sess.opts.resolve_doc_links {
5374            ResolveDocLinks::None => return,
5375            ResolveDocLinks::ExportedMetadata
5376                if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5377                    || !maybe_exported.eval(self.r) =>
5378            {
5379                return;
5380            }
5381            ResolveDocLinks::Exported
5382                if !maybe_exported.eval(self.r)
5383                    && !rustdoc::has_primitive_or_keyword_or_attribute_docs(attrs) =>
5384            {
5385                return;
5386            }
5387            ResolveDocLinks::ExportedMetadata
5388            | ResolveDocLinks::Exported
5389            | ResolveDocLinks::All => {}
5390        }
5391
5392        if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5393            return;
5394        }
5395
5396        let mut need_traits_in_scope = false;
5397        for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5398            // Resolve all namespaces due to no disambiguator or for diagnostics.
5399            let mut any_resolved = false;
5400            let mut need_assoc = false;
5401            for ns in [TypeNS, ValueNS, MacroNS] {
5402                if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5403                    // Rustdoc ignores tool attribute resolutions and attempts
5404                    // to resolve their prefixes for diagnostics.
5405                    any_resolved = !#[allow(non_exhaustive_omitted_patterns)] match res {
    Res::NonMacroAttr(NonMacroAttrKind::Tool) => true,
    _ => false,
}matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5406                } else if ns != MacroNS {
5407                    need_assoc = true;
5408                }
5409            }
5410
5411            // Resolve all prefixes for type-relative resolution or for diagnostics.
5412            if need_assoc || !any_resolved {
5413                let mut path = &path_str[..];
5414                while let Some(idx) = path.rfind("::") {
5415                    path = &path[..idx];
5416                    need_traits_in_scope = true;
5417                    for ns in [TypeNS, ValueNS, MacroNS] {
5418                        self.resolve_and_cache_rustdoc_path(path, ns);
5419                    }
5420                }
5421            }
5422        }
5423
5424        if need_traits_in_scope {
5425            // FIXME: hygiene is not considered.
5426            let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5427            doc_link_traits_in_scope
5428                .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5429                .or_insert_with(|| {
5430                    self.r
5431                        .traits_in_scope(None, &self.parent_scope, DUMMY_SP, None)
5432                        .into_iter()
5433                        .filter_map(|tr| {
5434                            if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5435                                // Encoding def ids in proc macro crate metadata will ICE.
5436                                // because it will only store proc macros for it.
5437                                return None;
5438                            }
5439                            Some(tr.def_id)
5440                        })
5441                        .collect()
5442                });
5443            self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5444        }
5445    }
5446
5447    fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5448        // Don't lint on global paths because the user explicitly wrote out the full path.
5449        if let Some(seg) = path.first()
5450            && seg.ident.name == kw::PathRoot
5451        {
5452            return;
5453        }
5454
5455        if finalize.path_span.from_expansion()
5456            || path.iter().any(|seg| seg.ident.span.from_expansion())
5457        {
5458            return;
5459        }
5460
5461        let end_pos =
5462            path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5463        let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5464            // Preserve the current namespace for the final path segment, but use the type
5465            // namespace for all preceding segments
5466            //
5467            // e.g. for `std::env::args` check the `ValueNS` for `args` but the `TypeNS` for
5468            // `std` and `env`
5469            //
5470            // If the final path segment is beyond `end_pos` all the segments to check will
5471            // use the type namespace
5472            let ns = if i + 1 == path.len() { ns } else { TypeNS };
5473            let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5474            let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5475            (res == binding.res()).then_some((seg, binding))
5476        });
5477
5478        if let Some((seg, decl)) = unqualified {
5479            self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5480                decl,
5481                node_id: finalize.node_id,
5482                path_span: finalize.path_span,
5483                removal_span: path[0].ident.span.until(seg.ident.span),
5484            });
5485        }
5486    }
5487
5488    fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5489        if let Some(define_opaque) = define_opaque {
5490            for (id, path) in define_opaque {
5491                self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5492            }
5493        }
5494    }
5495
5496    fn resolve_eii(&mut self, eii_impls: &[EiiImpl]) {
5497        for EiiImpl { node_id, eii_macro_path, known_eii_macro_resolution, .. } in eii_impls {
5498            // See docs on the `known_eii_macro_resolution` field:
5499            // if we already know the resolution statically, don't bother resolving it.
5500            if let Some(target) = known_eii_macro_resolution {
5501                self.smart_resolve_path(
5502                    *node_id,
5503                    &None,
5504                    &target.foreign_item,
5505                    PathSource::ExternItemImpl,
5506                );
5507            } else {
5508                self.smart_resolve_path(*node_id, &None, &eii_macro_path, PathSource::Macro);
5509            }
5510        }
5511    }
5512}
5513
5514/// Walks the whole crate in DFS order, visiting each item, counting the declared number of
5515/// lifetime generic parameters and function parameters.
5516struct ItemInfoCollector<'a, 'ra, 'tcx> {
5517    r: &'a mut Resolver<'ra, 'tcx>,
5518}
5519
5520impl ItemInfoCollector<'_, '_, '_> {
5521    fn collect_fn_info(&mut self, decl: &FnDecl, id: NodeId) {
5522        self.r
5523            .delegation_fn_sigs
5524            .insert(self.r.local_def_id(id), DelegationFnSig { has_self: decl.has_self() });
5525    }
5526}
5527
5528fn required_generic_args_suggestion(generics: &ast::Generics) -> Option<String> {
5529    let required = generics
5530        .params
5531        .iter()
5532        .filter_map(|param| match &param.kind {
5533            ast::GenericParamKind::Lifetime => Some("'_"),
5534            ast::GenericParamKind::Type { default } => {
5535                if default.is_none() {
5536                    Some("_")
5537                } else {
5538                    None
5539                }
5540            }
5541            ast::GenericParamKind::Const { default, .. } => {
5542                if default.is_none() {
5543                    Some("_")
5544                } else {
5545                    None
5546                }
5547            }
5548        })
5549        .collect::<Vec<_>>();
5550
5551    if required.is_empty() { None } else { Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>", required.join(", ")))
    })format!("<{}>", required.join(", "))) }
5552}
5553
5554impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
5555    fn visit_item(&mut self, item: &'ast Item) {
5556        match &item.kind {
5557            ItemKind::TyAlias(box TyAlias { generics, .. })
5558            | ItemKind::Const(box ConstItem { generics, .. })
5559            | ItemKind::Fn(box Fn { generics, .. })
5560            | ItemKind::Enum(_, generics, _)
5561            | ItemKind::Struct(_, generics, _)
5562            | ItemKind::Union(_, generics, _)
5563            | ItemKind::Impl(Impl { generics, .. })
5564            | ItemKind::Trait(box Trait { generics, .. })
5565            | ItemKind::TraitAlias(box TraitAlias { generics, .. }) => {
5566                if let ItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5567                    self.collect_fn_info(&sig.decl, item.id);
5568                }
5569
5570                let def_id = self.r.local_def_id(item.id);
5571                let count = generics
5572                    .params
5573                    .iter()
5574                    .filter(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    ast::GenericParamKind::Lifetime { .. } => true,
    _ => false,
}matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5575                    .count();
5576                self.r.item_generics_num_lifetimes.insert(def_id, count);
5577            }
5578
5579            ItemKind::ForeignMod(ForeignMod { items, .. }) => {
5580                for foreign_item in items {
5581                    if let ForeignItemKind::Fn(box Fn { sig, .. }) = &foreign_item.kind {
5582                        self.collect_fn_info(&sig.decl, foreign_item.id);
5583                    }
5584                }
5585            }
5586
5587            ItemKind::Mod(..)
5588            | ItemKind::Static(..)
5589            | ItemKind::ConstBlock(..)
5590            | ItemKind::Use(..)
5591            | ItemKind::ExternCrate(..)
5592            | ItemKind::MacroDef(..)
5593            | ItemKind::GlobalAsm(..)
5594            | ItemKind::MacCall(..)
5595            | ItemKind::DelegationMac(..) => {}
5596            ItemKind::Delegation(..) => {
5597                // Delegated functions have lifetimes, their count is not necessarily zero.
5598                // But skipping the delegation items here doesn't mean that the count will be considered zero,
5599                // it means there will be a panic when retrieving the count,
5600                // but for delegation items we are never actually retrieving that count in practice.
5601            }
5602        }
5603        visit::walk_item(self, item)
5604    }
5605
5606    fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5607        if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
5608            self.collect_fn_info(&sig.decl, item.id);
5609        }
5610
5611        if let AssocItemKind::Type(box ast::TyAlias { generics, .. }) = &item.kind {
5612            let def_id = self.r.local_def_id(item.id);
5613            if let Some(suggestion) = required_generic_args_suggestion(generics) {
5614                self.r.item_required_generic_args_suggestions.insert(def_id, suggestion);
5615            }
5616        }
5617        visit::walk_assoc_item(self, item, ctxt);
5618    }
5619}
5620
5621impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5622    pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
5623        visit::walk_crate(&mut ItemInfoCollector { r: self }, krate);
5624        let mut late_resolution_visitor = LateResolutionVisitor::new(self);
5625        late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5626        visit::walk_crate(&mut late_resolution_visitor, krate);
5627        for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() {
5628            self.lint_buffer.buffer_lint(
5629                lint::builtin::UNUSED_LABELS,
5630                *id,
5631                *span,
5632                errors::UnusedLabel,
5633            );
5634        }
5635    }
5636}
5637
5638/// Check if definition matches a path
5639fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5640    let mut path = expected_path.iter().rev();
5641    while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5642        if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5643            return false;
5644        }
5645        def_id = parent;
5646    }
5647    true
5648}