Skip to main content

rustc_resolve/
late.rs

1// ignore-tidy-file-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, NonMacroAttrKind, PerNS};
29use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE, LocalDefId};
30use rustc_hir::{MissingLifetimeKind, PrimTy};
31use rustc_lint_defs::builtin::{ELIDED_LIFETIMES_IN_PATHS, UNUSED_LABELS};
32use rustc_middle::middle::resolve::{
33    DelegationInfo, DelegationInherentFnKind, DelegationResolution, LifetimeRes, PartialRes,
34};
35use rustc_middle::middle::resolve_bound_vars::Set1;
36use rustc_middle::ty::{AssocTag, Visibility};
37use rustc_middle::{bug, span_bug};
38use rustc_session::config::ResolveDocLinks;
39use rustc_session::diagnostics::feature_err;
40use rustc_span::{BytePos, DUMMY_SP, Ident, Span, Spanned, Symbol, kw, respan, sym};
41use rustc_structures::CrateType;
42use smallvec::{SmallVec, smallvec};
43use thin_vec::ThinVec;
44use tracing::{debug, instrument, trace};
45
46use crate::{
47    BindingError, BindingKey, Decl, DelegationFnSig, Finalize, IdentKey, LateDecl, LocalModule,
48    Module, ModuleOrUniformRoot, ParentScope, PathResult, Res, ResolutionError, Resolver, Segment,
49    Stage, TyCtxt, UseError, Used, path_names_to_string, rustdoc, with_owner,
50};
51
52mod diagnostics;
53
54use diagnostics::{ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime};
55
56#[derive(#[automatically_derived]
impl ::core::marker::Copy for BindingInfo { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for BindingInfo { }
#[automatically_derived]
impl ::core::clone::Clone for BindingInfo {
    #[inline]
    fn clone(&self) -> BindingInfo {
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<BindingMode>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for BindingInfo {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "BindingInfo",
            "span", &self.span, "annotation", &&self.annotation)
    }
}Debug)]
57struct BindingInfo {
58    span: Span,
59    annotation: BindingMode,
60}
61
62#[derive(#[automatically_derived]
impl ::core::marker::Copy for PatternSource { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for PatternSource { }
#[automatically_derived]
impl ::core::clone::Clone for PatternSource {
    #[inline]
    fn clone(&self) -> PatternSource { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for PatternSource { }
#[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 { }Eq, #[automatically_derived]
impl ::core::fmt::Debug for PatternSource {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                PatternSource::Match => "Match",
                PatternSource::Let => "Let",
                PatternSource::For => "For",
                PatternSource::FnParam => "FnParam",
            })
    }
}Debug)]
63pub(crate) enum PatternSource {
64    Match,
65    Let,
66    For,
67    FnParam,
68}
69
70#[derive(#[automatically_derived]
impl ::core::marker::Copy for IsRepeatExpr { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for IsRepeatExpr { }
#[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::marker::StructuralPartialEq for IsRepeatExpr { }
#[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 { }Eq)]
71enum IsRepeatExpr {
72    No,
73    Yes,
74}
75
76struct IsNeverPattern;
77
78/// Describes whether an `AnonConst` is a type level const arg or
79/// some other form of anon const (i.e. inline consts or enum discriminants)
80#[derive(#[automatically_derived]
impl ::core::marker::Copy for AnonConstKind { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AnonConstKind { }
#[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),
            AnonConstKind::ArrayLength =>
                ::core::fmt::Formatter::write_str(f, "ArrayLength"),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for AnonConstKind { }
#[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)]
81enum AnonConstKind {
82    EnumDiscriminant,
83    FieldDefaultValue,
84    InlineConst,
85    ConstArg(IsRepeatExpr),
86    ArrayLength,
87}
88
89impl PatternSource {
90    fn descr(self) -> &'static str {
91        match self {
92            PatternSource::Match => "match binding",
93            PatternSource::Let => "let binding",
94            PatternSource::For => "for binding",
95            PatternSource::FnParam => "function parameter",
96        }
97    }
98}
99
100impl IntoDiagArg for PatternSource {
101    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
102        DiagArgValue::Str(Cow::Borrowed(self.descr()))
103    }
104}
105
106/// Denotes whether the context for the set of already bound bindings is a `Product`
107/// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
108/// See those functions for more information.
109#[derive(#[automatically_derived]
impl ::core::marker::StructuralPartialEq for PatBoundCtx { }
#[automatically_derived]
impl ::core::cmp::PartialEq for PatBoundCtx {
    #[inline]
    fn eq(&self, other: &PatBoundCtx) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
110enum PatBoundCtx {
111    /// A product pattern context, e.g., `Variant(a, b)`.
112    Product,
113    /// An or-pattern context, e.g., `p_0 | ... | p_n`.
114    Or,
115}
116
117/// Tracks bindings resolved within a pattern. This serves two purposes:
118///
119/// - This tracks when identifiers are bound multiple times within a pattern. In a product context,
120///   this is an error. In an or-pattern, this lets us reuse the same resolution for each instance.
121///   See `fresh_binding` and `resolve_pattern_inner` for more information.
122///
123/// - The guard expression of a guard pattern may use bindings from within the guard pattern, but
124///   not from elsewhere in the pattern containing it. This allows us to isolate the bindings in the
125///   subpattern to construct the scope for the guard.
126///
127/// Each identifier must map to at most one distinct [`Res`].
128type PatternBindings = SmallVec<[(PatBoundCtx, FxIndexMap<Ident, Res>); 1]>;
129
130/// Does this the item (from the item rib scope) allow generic parameters?
131#[derive(#[automatically_derived]
impl ::core::marker::Copy for HasGenericParams { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for HasGenericParams { }
#[automatically_derived]
impl ::core::clone::Clone for HasGenericParams {
    #[inline]
    fn clone(&self) -> HasGenericParams {
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for HasGenericParams {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            HasGenericParams::Yes(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Yes",
                    &__self_0),
            HasGenericParams::No =>
                ::core::fmt::Formatter::write_str(f, "No"),
        }
    }
}Debug)]
132pub(crate) enum HasGenericParams {
133    Yes(Span),
134    No,
135}
136
137/// May this constant have generics?
138#[derive(#[automatically_derived]
impl ::core::marker::Copy for ConstantHasGenerics { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ConstantHasGenerics { }
#[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::marker::StructuralPartialEq for ConstantHasGenerics { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ConstantHasGenerics {
    #[inline]
    fn eq(&self, other: &ConstantHasGenerics) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (ConstantHasGenerics::No(__self_0),
                    ConstantHasGenerics::No(__arg1_0)) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
139pub(crate) enum ConstantHasGenerics {
140    Yes,
141    No(NoConstantGenericsReason),
142}
143
144/// Does this constant requires an specific type?
145#[derive(#[automatically_derived]
impl ::core::marker::Copy for ConstantRequiresType { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ConstantRequiresType { }
#[automatically_derived]
impl ::core::clone::Clone for ConstantRequiresType {
    #[inline]
    fn clone(&self) -> ConstantRequiresType { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ConstantRequiresType {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ConstantRequiresType::Usize => "Usize",
                ConstantRequiresType::No => "No",
            })
    }
}Debug)]
146pub(crate) enum ConstantRequiresType {
147    Usize,
148    No,
149}
150
151impl ConstantHasGenerics {
152    fn force_yes_if(self, b: bool) -> Self {
153        if b { Self::Yes } else { self }
154    }
155}
156
157/// Reason for why an anon const is not allowed to reference generic parameters
158#[derive(#[automatically_derived]
impl ::core::marker::Copy for NoConstantGenericsReason { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for NoConstantGenericsReason { }
#[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 { }Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for NoConstantGenericsReason { }
#[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)]
159pub(crate) enum NoConstantGenericsReason {
160    /// Const arguments are only allowed to use generic parameters when:
161    /// - `feature(generic_const_exprs)` is enabled
162    /// or
163    /// - the const argument is a sole const generic parameter, i.e. `foo::<{ N }>()`
164    ///
165    /// If neither of the above are true then this is used as the cause.
166    NonTrivialConstArg,
167    /// Enum discriminants are not allowed to reference generic parameters ever, this
168    /// is used when an anon const is in the following position:
169    ///
170    /// ```rust,compile_fail
171    /// enum Foo<const N: isize> {
172    ///     Variant = { N }, // this anon const is not allowed to use generics
173    /// }
174    /// ```
175    IsEnumDiscriminant,
176}
177
178#[derive(#[automatically_derived]
impl ::core::marker::Copy for ConstantItemKind { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ConstantItemKind { }
#[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 { }Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ConstantItemKind { }
#[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)]
179pub(crate) enum ConstantItemKind {
180    Const,
181    Static,
182}
183
184impl ConstantItemKind {
185    pub(crate) fn as_str(&self) -> &'static str {
186        match self {
187            Self::Const => "const",
188            Self::Static => "static",
189        }
190    }
191}
192
193#[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]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for RecordPartialRes { }
#[automatically_derived]
impl ::core::clone::Clone for RecordPartialRes {
    #[inline]
    fn clone(&self) -> RecordPartialRes { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for RecordPartialRes { }
#[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 { }Eq)]
194enum RecordPartialRes {
195    Yes,
196    No,
197}
198
199/// The rib kind restricts certain accesses,
200/// e.g. to a `Res::Local` of an outer item.
201#[derive(#[automatically_derived]
impl<'ra> ::core::marker::Copy for RibKind<'ra> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'ra> ::core::clone::TrivialClone for RibKind<'ra> { }
#[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<ConstantRequiresType>;
        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, __self_2) =>
                ::core::fmt::Formatter::debug_tuple_field3_finish(f,
                    "ConstantItem", __self_0, __self_1, &__self_2),
            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)]
202pub(crate) enum RibKind<'ra> {
203    /// No restriction needs to be applied.
204    Normal,
205
206    /// We passed through an `ast::Block`.
207    /// Behaves like `Normal`, but also partially like `Module` if the block contains items.
208    /// `Block(None)` must be always processed in the same way as `Block(Some(module))`
209    /// with empty `module`. The module can be `None` only because creation of some definitely
210    /// empty modules is skipped as an optimization.
211    Block(Option<LocalModule<'ra>>),
212
213    /// We passed through an impl or trait and are now in one of its
214    /// methods or associated types. Allow references to ty params that impl or trait
215    /// binds. Disallow any other upvars (including other ty params that are
216    /// upvars).
217    AssocItem,
218
219    /// We passed through a function, closure or coroutine signature. Disallow labels.
220    FnOrCoroutine,
221
222    /// We passed through an item scope. Disallow upvars.
223    Item(HasGenericParams, DefKind),
224
225    /// We're in a constant item. Can't refer to dynamic stuff.
226    ///
227    /// The item may reference generic parameters in trivial constant expressions.
228    /// All other constants aren't allowed to use generic params at all.
229    ///
230    /// If the constant comes from specific contexts (like array length) it might require an specific type.
231    ConstantItem(ConstantHasGenerics, Option<(Ident, ConstantItemKind)>, ConstantRequiresType),
232
233    /// We passed through a module item.
234    Module(LocalModule<'ra>),
235
236    /// We passed through a `macro_rules!` statement
237    MacroDefinition(DefId),
238
239    /// All bindings in this rib are generic parameters that can't be used
240    /// from the default of a generic parameter because they're not declared
241    /// before said generic parameter. Also see the `visit_generics` override.
242    ForwardGenericParamBan(ForwardGenericParamBanReason),
243
244    /// We are inside of the type of a const parameter. Can't refer to any
245    /// parameters.
246    ConstParamTy,
247
248    /// We are inside a `sym` inline assembly operand. Can only refer to
249    /// globals.
250    InlineAsmSym,
251}
252
253#[derive(#[automatically_derived]
impl ::core::marker::Copy for ForwardGenericParamBanReason { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ForwardGenericParamBanReason { }
#[automatically_derived]
impl ::core::clone::Clone for ForwardGenericParamBanReason {
    #[inline]
    fn clone(&self) -> ForwardGenericParamBanReason { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ForwardGenericParamBanReason { }
#[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 { }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)]
254pub(crate) enum ForwardGenericParamBanReason {
255    Default,
256    ConstParamTy,
257}
258
259impl RibKind<'_> {
260    /// Whether this rib kind contains generic parameters, as opposed to local
261    /// variables.
262    pub(crate) fn contains_params(&self) -> bool {
263        match self {
264            RibKind::Normal
265            | RibKind::Block(..)
266            | RibKind::FnOrCoroutine
267            | RibKind::ConstantItem(..)
268            | RibKind::Module(_)
269            | RibKind::MacroDefinition(_)
270            | RibKind::InlineAsmSym => false,
271            RibKind::ConstParamTy
272            | RibKind::AssocItem
273            | RibKind::Item(..)
274            | RibKind::ForwardGenericParamBan(_) => true,
275        }
276    }
277
278    /// This rib forbids referring to labels defined in upwards ribs.
279    fn is_label_barrier(self) -> bool {
280        match self {
281            RibKind::Normal | RibKind::MacroDefinition(..) => false,
282            RibKind::FnOrCoroutine | RibKind::ConstantItem(..) => true,
283            kind => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected rib kind: {0:?}",
        kind))bug!("unexpected rib kind: {kind:?}"),
284        }
285    }
286}
287
288/// A single local scope.
289///
290/// A rib represents a scope names can live in. Note that these appear in many places, not just
291/// around braces. At any place where the list of accessible names (of the given namespace)
292/// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
293/// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
294/// etc.
295///
296/// Different [rib kinds](enum@RibKind) are transparent for different names.
297///
298/// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
299/// resolving, the name is looked up from inside out.
300#[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)]
301pub(crate) struct Rib<'ra, R = Res> {
302    pub bindings: FxIndexMap<Ident, R>,
303    pub patterns_with_skipped_bindings:
304        UnordMap<DefId, Vec<(Span, Option<Span>, Result<(), ErrorGuaranteed>)>>,
305    pub kind: RibKind<'ra>,
306}
307
308impl<'ra, R> Rib<'ra, R> {
309    fn new(kind: RibKind<'ra>) -> Rib<'ra, R> {
310        Rib {
311            bindings: Default::default(),
312            patterns_with_skipped_bindings: Default::default(),
313            kind,
314        }
315    }
316}
317
318#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for LifetimeUseSet { }
#[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)]
319enum LifetimeUseSet {
320    One { use_span: Span, use_ctxt: visit::LifetimeCtxt },
321    Many,
322}
323
324#[derive(#[automatically_derived]
impl ::core::marker::Copy for LifetimeRibKind { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for LifetimeRibKind { }
#[automatically_derived]
impl ::core::clone::Clone for LifetimeRibKind {
    #[inline]
    fn clone(&self) -> LifetimeRibKind {
        let _: ::core::clone::AssertParamIsClone<NodeId>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<LifetimeBinderKind>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<LifetimeRes>;
        let _: ::core::clone::AssertParamIsClone<NoConstantGenericsReason>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for LifetimeRibKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LifetimeRibKind::Generics {
                binder: __self_0, span: __self_1, kind: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "Generics", "binder", __self_0, "span", __self_1, "kind",
                    &__self_2),
            LifetimeRibKind::AnonymousCreateParameter {
                binder: __self_0, report_in_path: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "AnonymousCreateParameter", "binder", __self_0,
                    "report_in_path", &__self_1),
            LifetimeRibKind::Elided { res: __self_0, error_in_path: __self_1 }
                =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Elided", "res", __self_0, "error_in_path", &__self_1),
            LifetimeRibKind::AnonymousReportError =>
                ::core::fmt::Formatter::write_str(f, "AnonymousReportError"),
            LifetimeRibKind::ElisionFailure =>
                ::core::fmt::Formatter::write_str(f, "ElisionFailure"),
            LifetimeRibKind::ConstParamTy =>
                ::core::fmt::Formatter::write_str(f, "ConstParamTy"),
            LifetimeRibKind::ConcreteAnonConst(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ConcreteAnonConst", &__self_0),
            LifetimeRibKind::Item =>
                ::core::fmt::Formatter::write_str(f, "Item"),
            LifetimeRibKind::ImplTrait =>
                ::core::fmt::Formatter::write_str(f, "ImplTrait"),
        }
    }
}Debug)]
325enum LifetimeRibKind {
326    // -- Ribs introducing named lifetimes
327    //
328    /// This rib declares generic parameters.
329    /// Only for this kind the `LifetimeRib::bindings` field can be non-empty.
330    Generics { binder: NodeId, span: Span, kind: LifetimeBinderKind },
331
332    // -- Ribs introducing unnamed lifetimes
333    //
334    /// Create a new anonymous lifetime parameter and reference it.
335    ///
336    /// If `report_in_path`, report an error when encountering lifetime elision in a path:
337    /// ```compile_fail
338    /// struct Foo<'a> { x: &'a () }
339    /// async fn foo(x: Foo) {}
340    /// ```
341    ///
342    /// Note: the error should not trigger when the elided lifetime is in a pattern or
343    /// expression-position path:
344    /// ```
345    /// struct Foo<'a> { x: &'a () }
346    /// async fn foo(Foo { x: _ }: Foo<'_>) {}
347    /// ```
348    AnonymousCreateParameter { binder: NodeId, report_in_path: bool },
349
350    /// Replace all anonymous lifetimes by provided lifetime.
351    Elided {
352        res: LifetimeRes,
353        /// Always report those lifetimes as an error if in a path
354        error_in_path: bool,
355    },
356
357    // -- Barrier ribs that stop lifetime lookup, or continue it but produce an error later.
358    //
359    /// Give a hard error when either `&` or `'_` is written. Used to
360    /// rule out things like `where T: Foo<'_>`. Does not imply an
361    /// error on default object bounds (e.g., `Box<dyn Foo>`).
362    AnonymousReportError,
363
364    /// Signal we cannot find which should be the anonymous lifetime.
365    ElisionFailure,
366
367    /// This rib forbids usage of generic parameters inside of const parameter types.
368    ///
369    /// While this is desirable to support eventually, it is difficult to do and so is
370    /// currently forbidden. See rust-lang/project-const-generics#28 for more info.
371    ConstParamTy,
372
373    /// Usage of generic parameters is forbidden in various positions for anon consts:
374    /// - const arguments when `generic_const_exprs` is not enabled
375    /// - enum discriminant values
376    ///
377    /// This rib emits an error when a lifetime would resolve to a lifetime parameter.
378    ConcreteAnonConst(NoConstantGenericsReason),
379
380    /// This rib acts as a barrier to forbid reference to lifetimes of a parent item.
381    Item,
382
383    /// Lifetimes cannot be elided in `impl Trait` types without `#![feature(anonymous_lifetime_in_impl_trait)]`.
384    ImplTrait,
385}
386impl LifetimeRibKind {
387    /// Convenience function for creating non-erroring `Elided` variants.
388    fn elided(res: LifetimeRes) -> LifetimeRibKind {
389        LifetimeRibKind::Elided { res, error_in_path: false }
390    }
391}
392
393#[derive(#[automatically_derived]
impl ::core::marker::Copy for LifetimeBinderKind { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for LifetimeBinderKind { }
#[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)]
394enum LifetimeBinderKind {
395    FnPtrType,
396    PolyTrait,
397    WhereBound,
398    // Item covers foreign items, ADTs, type aliases, trait associated items and
399    // trait alias associated items.
400    Item,
401    ConstItem,
402    Function,
403    Closure,
404    ImplBlock,
405    // Covers only `impl` associated types.
406    ImplAssocType,
407}
408
409impl LifetimeBinderKind {
410    fn descr(self) -> &'static str {
411        use LifetimeBinderKind::*;
412        match self {
413            FnPtrType => "type",
414            PolyTrait => "bound",
415            WhereBound => "bound",
416            Item | ConstItem => "item",
417            ImplAssocType => "associated type",
418            ImplBlock => "impl block",
419            Function => "function",
420            Closure => "closure",
421        }
422    }
423}
424
425#[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)]
426struct LifetimeRib {
427    kind: LifetimeRibKind,
428    // We need to preserve insertion order for async fns.
429    bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
430}
431
432impl LifetimeRib {
433    fn new(kind: LifetimeRibKind) -> LifetimeRib {
434        LifetimeRib { bindings: Default::default(), kind }
435    }
436}
437
438#[derive(#[automatically_derived]
impl ::core::marker::Copy for AliasPossibility { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AliasPossibility { }
#[automatically_derived]
impl ::core::clone::Clone for AliasPossibility {
    #[inline]
    fn clone(&self) -> AliasPossibility { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for AliasPossibility { }
#[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 { }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)]
439pub(crate) enum AliasPossibility {
440    No,
441    Maybe,
442}
443
444#[derive(#[automatically_derived]
impl<'a, 'ast, 'ra> ::core::marker::Copy for PathSource<'a, 'ast, 'ra> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'a, 'ast, 'ra> ::core::clone::TrivialClone for
    PathSource<'a, 'ast, 'ra> {
}
#[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)]
445pub(crate) enum PathSource<'a, 'ast, 'ra> {
446    /// Type paths `Path`.
447    Type,
448    /// Trait paths in bounds or impls.
449    Trait(AliasPossibility),
450    /// Expression paths `path`, with optional parent context.
451    Expr(Option<&'ast Expr>),
452    /// Paths in path patterns `Path`.
453    Pat,
454    /// Paths in struct expressions and patterns `Path { .. }`.
455    Struct(Option<&'a Expr>),
456    /// Paths in tuple struct patterns `Path(..)`.
457    TupleStruct(Span, &'ra [Span]),
458    /// `m::A::B` in `<T as m::A>::B::C`.
459    ///
460    /// Second field holds the "cause" of this one, i.e. the context within
461    /// which the trait item is resolved. Used for diagnostics.
462    TraitItem(Namespace, &'a PathSource<'a, 'ast, 'ra>),
463    /// Paths in delegation item
464    Delegation,
465    /// Paths in externally implementable item declarations.
466    ExternItemImpl,
467    /// An arg in a `use<'a, N>` precise-capturing bound.
468    PreciseCapturingArg(Namespace),
469    /// Paths that end with `(..)`, for return type notation.
470    ReturnTypeNotation,
471    /// Paths from `#[define_opaque]` attributes
472    DefineOpaques,
473    /// Resolving a macro
474    Macro,
475    /// Paths for module or crate root. Used for restrictions.
476    Module,
477}
478
479impl PathSource<'_, '_, '_> {
480    fn namespace(self) -> Namespace {
481        match self {
482            PathSource::Type
483            | PathSource::Trait(_)
484            | PathSource::Struct(_)
485            | PathSource::DefineOpaques
486            | PathSource::Module => TypeNS,
487            PathSource::Expr(..)
488            | PathSource::Pat
489            | PathSource::TupleStruct(..)
490            | PathSource::Delegation
491            | PathSource::ExternItemImpl
492            | PathSource::ReturnTypeNotation => ValueNS,
493            PathSource::TraitItem(ns, _) => ns,
494            PathSource::PreciseCapturingArg(ns) => ns,
495            PathSource::Macro => MacroNS,
496        }
497    }
498
499    fn defer_to_typeck(self) -> bool {
500        match self {
501            PathSource::Type
502            | PathSource::Expr(..)
503            | PathSource::Pat
504            | PathSource::Struct(_)
505            | PathSource::TupleStruct(..)
506            | PathSource::Delegation
507            | PathSource::ReturnTypeNotation => true,
508            PathSource::Trait(_)
509            | PathSource::TraitItem(..)
510            | PathSource::DefineOpaques
511            | PathSource::ExternItemImpl
512            | PathSource::PreciseCapturingArg(..)
513            | PathSource::Macro
514            | PathSource::Module => false,
515        }
516    }
517
518    fn descr_expected(self) -> &'static str {
519        match &self {
520            PathSource::DefineOpaques => "type alias or associated type with opaqaue types",
521            PathSource::Type => "type",
522            PathSource::Trait(_) => "trait",
523            PathSource::Pat => "unit struct, unit variant or constant",
524            PathSource::Struct(_) => "struct, variant or union type",
525            PathSource::TraitItem(ValueNS, PathSource::TupleStruct(..))
526            | PathSource::TupleStruct(..) => "tuple struct or tuple variant",
527            PathSource::TraitItem(ns, _) => match ns {
528                TypeNS => "associated type",
529                ValueNS => "method or associated constant",
530                MacroNS => ::rustc_middle::util::bug::bug_fmt(format_args!("associated macro"))bug!("associated macro"),
531            },
532            PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
533                // "function" here means "anything callable" rather than `DefKind::Fn`,
534                // this is not precise but usually more helpful than just "value".
535                Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
536                    // the case of `::some_crate()`
537                    ExprKind::Path(_, path)
538                        if let [segment, _] = path.segments.as_slice()
539                            && segment.ident.name == kw::PathRoot =>
540                    {
541                        "external crate"
542                    }
543                    ExprKind::Path(_, path)
544                        if let Some(segment) = path.segments.last()
545                            && let Some(c) = segment.ident.to_string().chars().next()
546                            && c.is_uppercase() =>
547                    {
548                        "function, tuple struct or tuple variant"
549                    }
550                    _ => "function",
551                },
552                _ => "value",
553            },
554            PathSource::ReturnTypeNotation | PathSource::Delegation => "function",
555            PathSource::ExternItemImpl => "function or static",
556            PathSource::PreciseCapturingArg(..) => "type or const parameter",
557            PathSource::Macro => "macro",
558            PathSource::Module => "module",
559        }
560    }
561
562    fn is_call(self) -> bool {
563        #[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(..), .. })))
564    }
565
566    pub(crate) fn is_expected(self, res: Res) -> bool {
567        match self {
568            PathSource::DefineOpaques => {
569                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum |
        DefKind::TyAlias | DefKind::AssocTy, _) | Res::SelfTyAlias { .. } =>
        true,
    _ => false,
}matches!(
570                    res,
571                    Res::Def(
572                        DefKind::Struct
573                            | DefKind::Union
574                            | DefKind::Enum
575                            | DefKind::TyAlias
576                            | DefKind::AssocTy,
577                        _
578                    ) | Res::SelfTyAlias { .. }
579                )
580            }
581            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!(
582                res,
583                Res::Def(
584                    DefKind::Struct
585                        | DefKind::Union
586                        | DefKind::Enum
587                        | DefKind::Trait
588                        | DefKind::TraitAlias
589                        | DefKind::TyAlias
590                        | DefKind::AssocTy
591                        | DefKind::TyParam
592                        | DefKind::OpaqueTy
593                        | DefKind::ForeignTy,
594                    _,
595                ) | Res::PrimTy(..)
596                    | Res::SelfTyParam { .. }
597                    | Res::SelfTyAlias { .. }
598            ),
599            PathSource::Trait(AliasPossibility::No) => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Trait, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Trait, _)),
600            PathSource::Trait(AliasPossibility::Maybe) => {
601                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
602            }
603            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!(
604                res,
605                Res::Def(
606                    DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
607                        | DefKind::Const
608                        | DefKind::Static { .. }
609                        | DefKind::Fn
610                        | DefKind::AssocFn
611                        | DefKind::AssocConst
612                        | DefKind::ConstParam,
613                    _,
614                ) | Res::Local(..)
615                    | Res::SelfCtor(..)
616            ),
617            PathSource::Pat => {
618                res.expected_in_unit_struct_pat()
619                    || #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Const | DefKind::AssocConst, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
620            }
621            PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
622            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!(
623                res,
624                Res::Def(
625                    DefKind::Struct
626                        | DefKind::Union
627                        | DefKind::Variant
628                        | DefKind::TyAlias
629                        | DefKind::AssocTy,
630                    _,
631                ) | Res::SelfTyParam { .. }
632                    | Res::SelfTyAlias { .. }
633            ),
634            PathSource::TraitItem(ns, _) => match res {
635                Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
636                Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
637                _ => false,
638            },
639            PathSource::ReturnTypeNotation => match res {
640                Res::Def(DefKind::AssocFn, _) => true,
641                _ => false,
642            },
643            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, _)),
644            PathSource::ExternItemImpl => {
645                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) |
        DefKind::Static { .. }, _) => true,
    _ => false,
}matches!(
646                    res,
647                    Res::Def(
648                        DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::Static { .. },
649                        _
650                    )
651                )
652            }
653            PathSource::PreciseCapturingArg(ValueNS) => {
654                #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::ConstParam, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::ConstParam, _))
655            }
656            // We allow `SelfTyAlias` here so we can give a more descriptive error later.
657            PathSource::PreciseCapturingArg(TypeNS) => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } |
        Res::SelfTyAlias { .. } => true,
    _ => false,
}matches!(
658                res,
659                Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }
660            ),
661            PathSource::PreciseCapturingArg(MacroNS) => false,
662            PathSource::Macro => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Macro(_), _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Macro(_), _)),
663            PathSource::Module => #[allow(non_exhaustive_omitted_patterns)] match res {
    Res::Def(DefKind::Mod, _) => true,
    _ => false,
}matches!(res, Res::Def(DefKind::Mod, _)),
664        }
665    }
666
667    fn error_code(self, has_unexpected_resolution: bool) -> ErrCode {
668        match (self, has_unexpected_resolution) {
669            (PathSource::Trait(_), true) => E0404,
670            (PathSource::Trait(_), false) => E0405,
671            (PathSource::Type | PathSource::DefineOpaques, true) => E0573,
672            (PathSource::Type | PathSource::DefineOpaques, false) => E0425,
673            (PathSource::Struct(_), true) => E0574,
674            (PathSource::Struct(_), false) => E0422,
675            (PathSource::Expr(..), true)
676            | (PathSource::Delegation, true)
677            | (PathSource::ExternItemImpl, true) => E0423,
678            (PathSource::Expr(..), false)
679            | (PathSource::Delegation, false)
680            | (PathSource::ExternItemImpl, false) => E0425,
681            (PathSource::Pat | PathSource::TupleStruct(..), true) => E0532,
682            (PathSource::Pat | PathSource::TupleStruct(..), false) => E0531,
683            (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, true) => E0575,
684            (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, false) => E0576,
685            (PathSource::PreciseCapturingArg(..), true) => E0799,
686            (PathSource::PreciseCapturingArg(..), false) => E0800,
687            (PathSource::Macro, _) => E0425,
688            // FIXME: There is no dedicated error code for this case yet.
689            // E0577 already covers the same situation for visibilities,
690            // so we reuse it here for now. It may make sense to generalize
691            // it for restrictions in the future.
692            (PathSource::Module, true) => E0577,
693            (PathSource::Module, false) => E0433,
694        }
695    }
696}
697
698/// At this point for most items we can answer whether that item is exported or not,
699/// but some items like impls require type information to determine exported-ness, so we make a
700/// conservative estimate for them (e.g. based on nominal visibility).
701#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'a> ::core::clone::TrivialClone for MaybeExported<'a> { }
#[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)]
702enum MaybeExported<'a> {
703    Ok(NodeId),
704    Impl(Option<DefId>),
705    ImplItem(Result<DefId, &'a ast::Visibility>),
706    NestedUse(&'a ast::Visibility),
707}
708
709impl MaybeExported<'_> {
710    fn eval(self, r: &Resolver<'_, '_>) -> bool {
711        let def_id = match self {
712            MaybeExported::Ok(node_id) => Some(if r.current_owner.id == node_id {
713                r.current_owner.def_id
714            } else {
715                r.current_owner.node_id_to_def_id[&node_id]
716            }),
717            MaybeExported::Impl(Some(trait_def_id)) | MaybeExported::ImplItem(Ok(trait_def_id)) => {
718                trait_def_id.as_local()
719            }
720            MaybeExported::Impl(None) => return true,
721            MaybeExported::ImplItem(Err(vis)) | MaybeExported::NestedUse(vis) => {
722                return vis.kind.is_pub();
723            }
724        };
725        def_id.is_none_or(|def_id| r.effective_visibilities.is_exported(def_id))
726    }
727}
728
729/// Used for recording UnnecessaryQualification.
730#[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)]
731pub(crate) struct UnnecessaryQualification<'ra> {
732    pub decl: LateDecl<'ra>,
733    pub node_id: NodeId,
734    pub path_span: Span,
735    pub removal_span: Span,
736}
737
738#[derive(#[automatically_derived]
impl<'ast> ::core::default::Default for DiagMetadata<'ast> {
    #[inline]
    fn default() -> DiagMetadata<'ast> {
        DiagMetadata {
            current_trait_assoc_items: ::core::default::Default::default(),
            current_self_type: ::core::default::Default::default(),
            current_self_item: ::core::default::Default::default(),
            current_item: ::core::default::Default::default(),
            currently_processing_generic_args: ::core::default::Default::default(),
            current_function: ::core::default::Default::default(),
            unused_labels: ::core::default::Default::default(),
            current_let_binding: ::core::default::Default::default(),
            current_pat: ::core::default::Default::default(),
            in_if_condition: ::core::default::Default::default(),
            in_assignment: ::core::default::Default::default(),
            is_assign_rhs: ::core::default::Default::default(),
            in_non_gat_assoc_type: ::core::default::Default::default(),
            in_range: ::core::default::Default::default(),
            current_trait_object: ::core::default::Default::default(),
            current_where_predicate: ::core::default::Default::default(),
            in_assoc_ty_binding: ::core::default::Default::default(),
            current_type_path: ::core::default::Default::default(),
            current_impl_items: ::core::default::Default::default(),
            current_impl_item: ::core::default::Default::default(),
            currently_processing_impl_trait: ::core::default::Default::default(),
            current_elision_failures: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]
impl<'ast> ::core::fmt::Debug for DiagMetadata<'ast> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["current_trait_assoc_items", "current_self_type",
                        "current_self_item", "current_item",
                        "currently_processing_generic_args", "current_function",
                        "unused_labels", "current_let_binding", "current_pat",
                        "in_if_condition", "in_assignment", "is_assign_rhs",
                        "in_non_gat_assoc_type", "in_range", "current_trait_object",
                        "current_where_predicate", "in_assoc_ty_binding",
                        "current_type_path", "current_impl_items",
                        "current_impl_item", "currently_processing_impl_trait",
                        "current_elision_failures"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.current_trait_assoc_items, &self.current_self_type,
                        &self.current_self_item, &self.current_item,
                        &self.currently_processing_generic_args,
                        &self.current_function, &self.unused_labels,
                        &self.current_let_binding, &self.current_pat,
                        &self.in_if_condition, &self.in_assignment,
                        &self.is_assign_rhs, &self.in_non_gat_assoc_type,
                        &self.in_range, &self.current_trait_object,
                        &self.current_where_predicate, &self.in_assoc_ty_binding,
                        &self.current_type_path, &self.current_impl_items,
                        &self.current_impl_item,
                        &self.currently_processing_impl_trait,
                        &&self.current_elision_failures];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "DiagMetadata",
            names, values)
    }
}Debug)]
739pub(crate) struct DiagMetadata<'ast> {
740    /// The current trait's associated items' ident, used for diagnostic suggestions.
741    current_trait_assoc_items: Option<&'ast [Box<AssocItem>]>,
742
743    /// The current self type if inside an impl (used for better errors).
744    pub(crate) current_self_type: Option<&'ast Ty>,
745
746    /// The current self item if inside an ADT (used for better errors).
747    current_self_item: Option<NodeId>,
748
749    /// The current item being evaluated (used for suggestions and more detail in errors).
750    pub(crate) current_item: Option<&'ast Item>,
751
752    /// When processing generic arguments and encountering an unresolved ident not found,
753    /// suggest introducing a type or const param depending on the context.
754    currently_processing_generic_args: bool,
755
756    /// The current enclosing (non-closure) function (used for better errors).
757    current_function: Option<(FnKind<'ast>, Span)>,
758
759    /// A list of labels as of yet unused. Labels will be removed from this map when
760    /// they are used (in a `break` or `continue` statement)
761    unused_labels: FxIndexMap<NodeId, Span>,
762
763    /// Only used for better errors on `let <pat>: <expr, not type>;`.
764    current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
765
766    current_pat: Option<&'ast Pat>,
767
768    /// Used to detect possible `if let` written without `let` and to provide structured suggestion.
769    in_if_condition: Option<&'ast Expr>,
770
771    /// Used to detect possible new binding written without `let` and to provide structured suggestion.
772    in_assignment: Option<&'ast Expr>,
773    is_assign_rhs: bool,
774
775    /// If we are setting an associated type in trait impl, is it a non-GAT type?
776    in_non_gat_assoc_type: Option<bool>,
777
778    /// Used to detect possible `.` -> `..` typo when calling methods.
779    in_range: Option<(&'ast Expr, &'ast Expr)>,
780
781    /// If we are currently in a trait object definition. Used to point at the bounds when
782    /// encountering a struct or enum.
783    current_trait_object: Option<&'ast [ast::GenericBound]>,
784
785    /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
786    current_where_predicate: Option<&'ast WherePredicate>,
787
788    /// Whether we are visiting an associated type equality binding like `Trait<Assoc = &T>`.
789    in_assoc_ty_binding: bool,
790
791    current_type_path: Option<&'ast Ty>,
792
793    /// The current impl items (used to suggest).
794    current_impl_items: Option<&'ast [Box<AssocItem>]>,
795
796    /// The current impl items (used to suggest).
797    current_impl_item: Option<&'ast AssocItem>,
798
799    /// When processing impl trait
800    currently_processing_impl_trait: Option<(TraitRef, Ty)>,
801
802    /// Accumulate the errors due to missed lifetime elision,
803    /// and report them all at once for each function.
804    current_elision_failures: Vec<(MissingLifetime, Either<NodeId, Range<NodeId>>)>,
805}
806
807struct LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
808    r: &'a mut Resolver<'ra, 'tcx>,
809
810    /// The module that represents the current item scope.
811    parent_scope: ParentScope<'ra>,
812
813    /// The current set of local scopes for types and values.
814    ribs: PerNS<Vec<Rib<'ra>>>,
815
816    /// Previous popped `rib`, only used for diagnostic.
817    last_block_rib: Option<Rib<'ra>>,
818
819    /// The current set of local scopes, for labels.
820    label_ribs: Vec<Rib<'ra, NodeId>>,
821
822    /// The current set of local scopes for lifetimes.
823    lifetime_ribs: Vec<LifetimeRib>,
824
825    /// We are looking for lifetimes in an elision context.
826    /// The set contains all the resolutions that we encountered so far.
827    /// They will be used to determine the correct lifetime for the fn return type.
828    /// The `LifetimeElisionCandidate` is used for diagnostics, to suggest introducing named
829    /// lifetimes.
830    lifetime_elision_candidates: Option<Vec<(LifetimeRes, LifetimeElisionCandidate)>>,
831
832    /// The trait that the current context can refer to.
833    current_trait_ref: Option<(Module<'ra>, TraitRef)>,
834
835    /// Fields used to add information to diagnostic errors.
836    diag_metadata: Box<DiagMetadata<'ast>>,
837
838    /// State used to know whether to ignore resolution errors for function bodies.
839    ///
840    /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
841    /// In most cases this will be `None`, in which case errors will always be reported.
842    /// If it is `true`, then it will be updated when entering a nested function or trait body.
843    in_func_body: bool,
844
845    /// Count the number of places a lifetime is used.
846    lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
847
848    /// `use` injections are delayed for better placement and deduplication.
849    use_injections: Vec<UseError<'tcx>>,
850}
851
852impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for LateResolutionVisitor<'_, '_, 'ra, 'tcx> {
853    fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
854        &self.r
855    }
856}
857impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for LateResolutionVisitor<'_, '_, 'ra, 'tcx> {
858    fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
859        &mut self.r
860    }
861}
862
863/// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
864impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
865    fn visit_attribute(&mut self, _: &'ast Attribute) {
866        // We do not want to resolve expressions that appear in attributes,
867        // as they do not correspond to actual code.
868    }
869    fn visit_item(&mut self, item: &'ast Item) {
870        let prev = replace(&mut self.diag_metadata.current_item, Some(item));
871        // Always report errors in items we just entered.
872        let old_ignore = replace(&mut self.in_func_body, false);
873        with_owner(self, item.id, |this| {
874            this.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item))
875        });
876        self.in_func_body = old_ignore;
877        self.diag_metadata.current_item = prev;
878    }
879    fn visit_arm(&mut self, arm: &'ast Arm) {
880        self.resolve_arm(arm);
881    }
882    fn visit_block(&mut self, block: &'ast Block) {
883        let old_macro_rules = self.parent_scope.macro_rules;
884        self.resolve_block(block);
885        self.parent_scope.macro_rules = old_macro_rules;
886    }
887    fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
888        ::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:#?}");
889    }
890    fn visit_expr(&mut self, expr: &'ast Expr) {
891        self.resolve_expr(expr, None);
892    }
893    fn visit_pat(&mut self, p: &'ast Pat) {
894        let prev = self.diag_metadata.current_pat;
895        self.diag_metadata.current_pat = Some(p);
896
897        if let PatKind::Guard(subpat, _) = &p.kind {
898            // We walk the guard expression in `resolve_pattern_inner`. Don't resolve it twice.
899            self.visit_pat(subpat);
900        } else {
901            visit::walk_pat(self, p);
902        }
903
904        self.diag_metadata.current_pat = prev;
905    }
906    fn visit_local(&mut self, local: &'ast Local) {
907        let local_spans = match local.pat.kind {
908            // We check for this to avoid tuple struct fields.
909            PatKind::Wild => None,
910            _ => Some((
911                local.pat.span,
912                local.ty.as_ref().map(|ty| ty.span),
913                local.kind.init().map(|init| init.span),
914            )),
915        };
916        let original = replace(&mut self.diag_metadata.current_let_binding, local_spans);
917        self.resolve_local(local);
918        self.diag_metadata.current_let_binding = original;
919    }
920    fn visit_ty(&mut self, ty: &'ast Ty) {
921        let prev = self.diag_metadata.current_trait_object;
922        let prev_ty = self.diag_metadata.current_type_path;
923        match &ty.kind {
924            TyKind::Ref(None, _) | TyKind::PinnedRef(None, _) => {
925                // Elided lifetime in reference: we resolve as if there was some lifetime `'_` with
926                // NodeId `ty.id`.
927                // This span will be used in case of elision failure.
928                let span = self.r.tcx.sess.source_map().start_point(ty.span);
929                self.resolve_elided_lifetime(ty.id, span);
930                visit::walk_ty(self, ty);
931            }
932            TyKind::Path(qself, path) => {
933                self.diag_metadata.current_type_path = Some(ty);
934
935                // If we have a path that ends with `(..)`, then it must be
936                // return type notation. Resolve that path in the *value*
937                // namespace.
938                let source = if let Some(seg) = path.segments.last()
939                    && let Some(args) = &seg.args
940                    && #[allow(non_exhaustive_omitted_patterns)] match **args {
    GenericArgs::ParenthesizedElided(..) => true,
    _ => false,
}matches!(**args, GenericArgs::ParenthesizedElided(..))
941                {
942                    PathSource::ReturnTypeNotation
943                } else {
944                    PathSource::Type
945                };
946
947                self.smart_resolve_path(ty.id, qself, path, source);
948
949                // Check whether we should interpret this as a bare trait object.
950                if qself.is_none()
951                    && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
952                    && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) =
953                        partial_res.full_res()
954                {
955                    // This path is actually a bare trait object. In case of a bare `Fn`-trait
956                    // object with anonymous lifetimes, we need this rib to correctly place the
957                    // synthetic lifetimes.
958                    let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
959                    self.with_generic_param_rib(
960                        &[],
961                        RibKind::Normal,
962                        ty.id,
963                        LifetimeBinderKind::PolyTrait,
964                        span,
965                        |this| this.visit_path(path),
966                    );
967                } else {
968                    visit::walk_ty(self, ty)
969                }
970            }
971            TyKind::ImplicitSelf => {
972                let self_ty = Ident::with_dummy_span(kw::SelfUpper);
973                let res = self
974                    .resolve_ident_in_lexical_scope(
975                        self_ty,
976                        TypeNS,
977                        Some(Finalize::new(ty.id, ty.span)),
978                        None,
979                    )
980                    .map_or(Res::Err, |d| d.res());
981                self.r.record_partial_res(ty.id, PartialRes::new(res));
982                visit::walk_ty(self, ty)
983            }
984            TyKind::ImplTrait(..) => {
985                let candidates = self.lifetime_elision_candidates.take();
986                self.with_lifetime_rib(LifetimeRibKind::ImplTrait, |this| visit::walk_ty(this, ty));
987                self.lifetime_elision_candidates = candidates;
988            }
989            TyKind::TraitObject(bounds, ..) => {
990                self.diag_metadata.current_trait_object = Some(&bounds[..]);
991                visit::walk_ty(self, ty)
992            }
993            TyKind::FnPtr(fn_ptr) => {
994                let span = ty.span.shrink_to_lo().to(fn_ptr.decl_span.shrink_to_lo());
995                self.with_generic_param_rib(
996                    &fn_ptr.generic_params,
997                    RibKind::Normal,
998                    ty.id,
999                    LifetimeBinderKind::FnPtrType,
1000                    span,
1001                    |this| {
1002                        this.visit_generic_params(&fn_ptr.generic_params, false);
1003                        this.resolve_fn_signature(
1004                            ty.id,
1005                            false,
1006                            // We don't need to deal with patterns in parameters, because
1007                            // they are not possible for foreign or bodiless functions.
1008                            fn_ptr.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1009                            &fn_ptr.decl.output,
1010                            false,
1011                        )
1012                    },
1013                )
1014            }
1015            TyKind::UnsafeBinder(unsafe_binder) => {
1016                let span = ty.span.shrink_to_lo().to(unsafe_binder.inner_ty.span.shrink_to_lo());
1017                self.with_generic_param_rib(
1018                    &unsafe_binder.generic_params,
1019                    RibKind::Normal,
1020                    ty.id,
1021                    LifetimeBinderKind::FnPtrType,
1022                    span,
1023                    |this| {
1024                        this.visit_generic_params(&unsafe_binder.generic_params, false);
1025                        this.with_lifetime_rib(
1026                            // We don't allow anonymous `unsafe &'_ ()` binders,
1027                            // although I guess we could.
1028                            LifetimeRibKind::AnonymousReportError,
1029                            |this| this.visit_ty(&unsafe_binder.inner_ty),
1030                        );
1031                    },
1032                )
1033            }
1034            TyKind::Array(element_ty, length) => {
1035                self.visit_ty(element_ty);
1036                self.resolve_anon_const(length, AnonConstKind::ArrayLength);
1037            }
1038            TyKind::DirectConstArg(expr) => self.resolve_anon_const_manual(
1039                true,
1040                AnonConstKind::ConstArg(IsRepeatExpr::No),
1041                |this| this.resolve_expr(expr, None),
1042            ),
1043            _ => visit::walk_ty(self, ty),
1044        }
1045        self.diag_metadata.current_trait_object = prev;
1046        self.diag_metadata.current_type_path = prev_ty;
1047    }
1048
1049    fn visit_ty_pat(&mut self, t: &'ast TyPat) -> Self::Result {
1050        match &t.kind {
1051            TyPatKind::Range(start, end, _) => {
1052                if let Some(start) = start {
1053                    self.resolve_anon_const(start, AnonConstKind::ConstArg(IsRepeatExpr::No));
1054                }
1055                if let Some(end) = end {
1056                    self.resolve_anon_const(end, AnonConstKind::ConstArg(IsRepeatExpr::No));
1057                }
1058            }
1059            TyPatKind::Or(patterns) => {
1060                for pat in patterns {
1061                    self.visit_ty_pat(pat)
1062                }
1063            }
1064            TyPatKind::NotNull | TyPatKind::Err(_) => {}
1065        }
1066    }
1067
1068    fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
1069        let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
1070        self.with_generic_param_rib(
1071            &tref.bound_generic_params,
1072            RibKind::Normal,
1073            tref.trait_ref.ref_id,
1074            LifetimeBinderKind::PolyTrait,
1075            span,
1076            |this| {
1077                this.visit_generic_params(&tref.bound_generic_params, false);
1078                this.smart_resolve_path(
1079                    tref.trait_ref.ref_id,
1080                    &None,
1081                    &tref.trait_ref.path,
1082                    PathSource::Trait(AliasPossibility::Maybe),
1083                );
1084                this.visit_trait_ref(&tref.trait_ref);
1085            },
1086        );
1087    }
1088    fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
1089        with_owner(self, foreign_item.id, |this| {
1090            this.resolve_doc_links(&foreign_item.attrs, MaybeExported::Ok(foreign_item.id));
1091            let def_kind = this.r.tcx.def_kind(this.r.current_owner.def_id);
1092            match foreign_item.kind {
1093                ForeignItemKind::TyAlias(TyAlias { ref generics, .. }) => {
1094                    this.with_generic_param_rib(
1095                        &generics.params,
1096                        RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1097                        foreign_item.id,
1098                        LifetimeBinderKind::Item,
1099                        generics.span,
1100                        |this| visit::walk_item(this, foreign_item),
1101                    );
1102                }
1103                ForeignItemKind::Fn(Fn { ref generics, .. }) => {
1104                    this.with_generic_param_rib(
1105                        &generics.params,
1106                        RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1107                        foreign_item.id,
1108                        LifetimeBinderKind::Function,
1109                        generics.span,
1110                        |this| visit::walk_item(this, foreign_item),
1111                    );
1112                }
1113                ForeignItemKind::Static(..) => {
1114                    this.with_static_rib(def_kind, |this| visit::walk_item(this, foreign_item))
1115                }
1116                ForeignItemKind::MacCall(..) => {
1117                    {
    ::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
1118                }
1119            }
1120        })
1121    }
1122    fn visit_fn(&mut self, fn_kind: FnKind<'ast>, _: &AttrVec, sp: Span, fn_id: NodeId) {
1123        let previous_value = self.diag_metadata.current_function;
1124        match fn_kind {
1125            // Bail if the function is foreign, and thus cannot validly have
1126            // a body, or if there's no body for some other reason.
1127            FnKind::Fn(FnCtxt::Foreign, _, Fn { sig, ident, generics, .. })
1128            | FnKind::Fn(_, _, Fn { sig, ident, generics, body: None, .. }) => {
1129                self.visit_fn_header(&sig.header);
1130                self.visit_ident(ident);
1131                self.visit_generics(generics);
1132                self.resolve_fn_signature(
1133                    fn_id,
1134                    sig.decl.has_self(),
1135                    sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1136                    &sig.decl.output,
1137                    false,
1138                );
1139                return;
1140            }
1141            FnKind::Fn(..) => {
1142                self.diag_metadata.current_function = Some((fn_kind, sp));
1143            }
1144            // Do not update `current_function` for closures: it suggests `self` parameters.
1145            FnKind::Closure(..) => {}
1146        };
1147        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs:1147",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1147u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("(resolving function) entering function")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("(resolving function) entering function");
1148
1149        if let FnKind::Fn(_, _, f) = fn_kind {
1150            self.resolve_eii(f.eii_impl.as_deref());
1151        }
1152
1153        // Create a value rib for the function.
1154        self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
1155            // Create a label rib for the function.
1156            this.with_label_rib(RibKind::FnOrCoroutine, |this| {
1157                match fn_kind {
1158                    FnKind::Fn(_, _, Fn { sig, generics, contract, body, .. }) => {
1159                        this.visit_generics(generics);
1160
1161                        let declaration = &sig.decl;
1162                        this.resolve_fn_signature(
1163                            fn_id,
1164                            declaration.has_self(),
1165                            declaration
1166                                .inputs
1167                                .iter()
1168                                .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
1169                            &declaration.output,
1170                            sig.header.coroutine_marker.is_some(),
1171                        );
1172
1173                        if let Some(contract) = contract {
1174                            this.visit_contract(contract);
1175                        }
1176
1177                        if let Some(body) = body {
1178                            // Ignore errors in function bodies if this is rustdoc. Be sure not to
1179                            // set this until the function signature has been resolved.
1180                            let previous_state = replace(&mut this.in_func_body, true);
1181                            // We only care block in the same function
1182                            this.last_block_rib = None;
1183                            // Resolve the function body, potentially inside the body of an async
1184                            // closure.
1185                            this.with_lifetime_rib(
1186                                LifetimeRibKind::elided(LifetimeRes::Infer),
1187                                |this| this.visit_block(body),
1188                            );
1189
1190                            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs:1190",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1190u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("(resolving function) leaving function")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("(resolving function) leaving function");
1191                            this.in_func_body = previous_state;
1192                        }
1193                    }
1194                    FnKind::Closure(binder, _, declaration, body) => {
1195                        this.visit_closure_binder(binder);
1196
1197                        this.with_lifetime_rib(
1198                            match binder {
1199                                // We do not have any explicit generic lifetime parameter.
1200                                ClosureBinder::NotPresent => {
1201                                    LifetimeRibKind::AnonymousCreateParameter {
1202                                        binder: fn_id,
1203                                        report_in_path: false,
1204                                    }
1205                                }
1206                                ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1207                            },
1208                            // Add each argument to the rib.
1209                            |this| this.resolve_params(&declaration.inputs),
1210                        );
1211                        this.with_lifetime_rib(
1212                            match binder {
1213                                ClosureBinder::NotPresent => {
1214                                    LifetimeRibKind::elided(LifetimeRes::Infer)
1215                                }
1216                                ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1217                            },
1218                            |this| visit::walk_fn_ret_ty(this, &declaration.output),
1219                        );
1220
1221                        // Ignore errors in function bodies if this is rustdoc
1222                        // Be sure not to set this until the function signature has been resolved.
1223                        let previous_state = replace(&mut this.in_func_body, true);
1224                        // Resolve the function body, potentially inside the body of an async closure
1225                        this.with_lifetime_rib(
1226                            LifetimeRibKind::elided(LifetimeRes::Infer),
1227                            |this| this.visit_expr(body),
1228                        );
1229
1230                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs:1230",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1230u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("(resolving function) leaving function")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("(resolving function) leaving function");
1231                        this.in_func_body = previous_state;
1232                    }
1233                }
1234            })
1235        });
1236        self.diag_metadata.current_function = previous_value;
1237    }
1238
1239    fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1240        self.resolve_lifetime(lifetime, use_ctxt)
1241    }
1242
1243    fn visit_precise_capturing_arg(&mut self, arg: &'ast PreciseCapturingArg) {
1244        match arg {
1245            // Lower the lifetime regularly; we'll resolve the lifetime and check
1246            // it's a parameter later on in HIR lowering.
1247            PreciseCapturingArg::Lifetime(_) => {}
1248
1249            PreciseCapturingArg::Arg(path, id) => {
1250                // we want `impl use<C>` to try to resolve `C` as both a type parameter or
1251                // a const parameter. Since the resolver specifically doesn't allow having
1252                // two generic params with the same name, even if they're a different namespace,
1253                // it doesn't really matter which we try resolving first, but just like
1254                // `Ty::Param` we just fall back to the value namespace only if it's missing
1255                // from the type namespace.
1256                let mut check_ns = |ns| {
1257                    self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns).is_some()
1258                };
1259                // Like `Ty::Param`, we try resolving this as both a const and a type.
1260                if !check_ns(TypeNS) && check_ns(ValueNS) {
1261                    self.smart_resolve_path(
1262                        *id,
1263                        &None,
1264                        path,
1265                        PathSource::PreciseCapturingArg(ValueNS),
1266                    );
1267                } else {
1268                    self.smart_resolve_path(
1269                        *id,
1270                        &None,
1271                        path,
1272                        PathSource::PreciseCapturingArg(TypeNS),
1273                    );
1274                }
1275            }
1276        }
1277
1278        visit::walk_precise_capturing_arg(self, arg)
1279    }
1280
1281    fn visit_generics(&mut self, generics: &'ast Generics) {
1282        self.visit_generic_params(&generics.params, self.diag_metadata.current_self_item.is_some());
1283        for p in &generics.where_clause.predicates {
1284            self.visit_where_predicate(p);
1285        }
1286    }
1287
1288    fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
1289        match b {
1290            ClosureBinder::NotPresent => {}
1291            ClosureBinder::For { generic_params, .. } => {
1292                self.visit_generic_params(
1293                    generic_params,
1294                    self.diag_metadata.current_self_item.is_some(),
1295                );
1296            }
1297        }
1298    }
1299
1300    {}
#[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("visit_generic_arg",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1300u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("arg")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("arg");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arg)
                                                            as &dyn ::tracing::field::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 prev =
                replace(&mut self.diag_metadata.currently_processing_generic_args,
                    true);
            match arg {
                GenericArg::Type(ty) => {
                    if let TyKind::Path(None, ref path) = ty.kind &&
                                    let Some(ident) = path.as_single_argless_ident() &&
                                self.maybe_resolve_ident_in_lexical_scope(ident,
                                        TypeNS).is_none() &&
                            self.maybe_resolve_ident_in_lexical_scope(ident,
                                    ValueNS).is_some() {
                        self.resolve_anon_const_manual(true,
                            AnonConstKind::ConstArg(IsRepeatExpr::No),
                            |this|
                                {
                                    this.smart_resolve_path(ty.id, &None, path,
                                        PathSource::Expr(None));
                                    this.visit_path(path);
                                })
                    } else { self.visit_ty(ty) }
                }
                GenericArg::Lifetime(lt) =>
                    self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
                GenericArg::Const(ct) => {
                    self.resolve_anon_const(ct,
                        AnonConstKind::ConstArg(IsRepeatExpr::No))
                }
            }
            self.diag_metadata.currently_processing_generic_args = prev;
        }
    }
}#[instrument(level = "debug", skip(self))]
1301    fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
1302        let prev = replace(&mut self.diag_metadata.currently_processing_generic_args, true);
1303        match arg {
1304            GenericArg::Type(ty) => {
1305                // We parse const arguments as path types as we cannot distinguish them during
1306                // parsing. We try to resolve that ambiguity by attempting resolution the type
1307                // namespace first, and if that fails we try again in the value namespace. If
1308                // resolution in the value namespace succeeds, we have an generic const argument on
1309                // our hands.
1310                //
1311                // We cannot disambiguate multi-segment paths right now as that requires type
1312                // checking.
1313                if let TyKind::Path(None, ref path) = ty.kind
1314                    && let Some(ident) = path.as_single_argless_ident()
1315                    && self.maybe_resolve_ident_in_lexical_scope(ident, TypeNS).is_none()
1316                    && self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS).is_some()
1317                {
1318                    self.resolve_anon_const_manual(
1319                        true,
1320                        AnonConstKind::ConstArg(IsRepeatExpr::No),
1321                        |this| {
1322                            this.smart_resolve_path(ty.id, &None, path, PathSource::Expr(None));
1323                            this.visit_path(path);
1324                        },
1325                    )
1326                } else {
1327                    self.visit_ty(ty)
1328                }
1329            }
1330            GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1331            GenericArg::Const(ct) => {
1332                self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
1333            }
1334        }
1335        self.diag_metadata.currently_processing_generic_args = prev;
1336    }
1337
1338    fn visit_assoc_item_constraint(&mut self, constraint: &'ast AssocItemConstraint) {
1339        self.visit_ident(&constraint.ident);
1340        if let Some(ref gen_args) = constraint.gen_args {
1341            // Forbid anonymous lifetimes in GAT parameters until proper semantics are decided.
1342            self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1343                this.visit_generic_args(gen_args)
1344            });
1345        }
1346        match constraint.kind {
1347            AssocItemConstraintKind::Equality { ref term } => match term {
1348                Term::Ty(ty) => {
1349                    let prev = replace(&mut self.diag_metadata.in_assoc_ty_binding, true);
1350                    self.visit_ty(ty);
1351                    self.diag_metadata.in_assoc_ty_binding = prev;
1352                }
1353                Term::Const(c) => {
1354                    self.resolve_anon_const(c, AnonConstKind::ConstArg(IsRepeatExpr::No))
1355                }
1356            },
1357            AssocItemConstraintKind::Bound { ref bounds } => {
1358                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);
1359            }
1360        }
1361    }
1362
1363    fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1364        let Some(ref args) = path_segment.args else {
1365            return;
1366        };
1367
1368        match &**args {
1369            GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1370            GenericArgs::Parenthesized(p_args) => {
1371                // Probe the lifetime ribs to know how to behave.
1372                for rib in self.lifetime_ribs.iter().rev() {
1373                    match rib.kind {
1374                        // We are inside a `PolyTraitRef`. The lifetimes are
1375                        // to be introduced in that (maybe implicit) `for<>` binder.
1376                        LifetimeRibKind::Generics {
1377                            binder,
1378                            kind: LifetimeBinderKind::PolyTrait,
1379                            ..
1380                        } => {
1381                            self.resolve_fn_signature(
1382                                binder,
1383                                false,
1384                                p_args.inputs.iter().map(|param| (None, &*param.ty)),
1385                                &p_args.output,
1386                                false,
1387                            );
1388                            break;
1389                        }
1390                        // We have nowhere to introduce generics. Code is malformed,
1391                        // so use regular lifetime resolution to avoid spurious errors.
1392                        LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1393                            visit::walk_generic_args(self, args);
1394                            break;
1395                        }
1396                        LifetimeRibKind::AnonymousCreateParameter { .. }
1397                        | LifetimeRibKind::AnonymousReportError
1398                        | LifetimeRibKind::ImplTrait
1399                        | LifetimeRibKind::Elided { .. }
1400                        | LifetimeRibKind::ElisionFailure
1401                        | LifetimeRibKind::ConcreteAnonConst(_)
1402                        | LifetimeRibKind::ConstParamTy => {}
1403                    }
1404                }
1405            }
1406            GenericArgs::ParenthesizedElided(_) => {}
1407        }
1408    }
1409
1410    fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1411        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs:1411",
                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                        ::tracing_core::__macro_support::Option::Some(1411u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_where_predicate {0:?}",
                                                    p) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("visit_where_predicate {:?}", p);
1412        let previous_value = replace(&mut self.diag_metadata.current_where_predicate, Some(p));
1413        self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1414            if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1415                bounded_ty,
1416                bounds,
1417                bound_generic_params,
1418                ..
1419            }) = &p.kind
1420            {
1421                let span = p.span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1422                this.with_generic_param_rib(
1423                    bound_generic_params,
1424                    RibKind::Normal,
1425                    bounded_ty.id,
1426                    LifetimeBinderKind::WhereBound,
1427                    span,
1428                    |this| {
1429                        this.visit_generic_params(bound_generic_params, false);
1430                        this.visit_ty(bounded_ty);
1431                        for bound in bounds {
1432                            this.visit_param_bound(bound, BoundKind::Bound)
1433                        }
1434                    },
1435                );
1436            } else {
1437                visit::walk_where_predicate(this, p);
1438            }
1439        });
1440        self.diag_metadata.current_where_predicate = previous_value;
1441    }
1442
1443    fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1444        for (op, _) in &asm.operands {
1445            match op {
1446                InlineAsmOperand::In { expr, .. }
1447                | InlineAsmOperand::Out { expr: Some(expr), .. }
1448                | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1449                InlineAsmOperand::Out { expr: None, .. } => {}
1450                InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1451                    self.visit_expr(in_expr);
1452                    if let Some(out_expr) = out_expr {
1453                        self.visit_expr(out_expr);
1454                    }
1455                }
1456                InlineAsmOperand::Const { anon_const, .. } => {
1457                    // Although this is `DefKind::AnonConst`, it is allowed to reference outer
1458                    // generic parameters like an inline const.
1459                    self.resolve_anon_const(anon_const, AnonConstKind::InlineConst);
1460                }
1461                InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1462                InlineAsmOperand::Label { block } => self.visit_block(block),
1463            }
1464        }
1465    }
1466
1467    fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1468        // This is similar to the code for AnonConst.
1469        self.with_rib(ValueNS, RibKind::InlineAsmSym, |this| {
1470            this.with_rib(TypeNS, RibKind::InlineAsmSym, |this| {
1471                this.with_label_rib(RibKind::InlineAsmSym, |this| {
1472                    this.smart_resolve_path(sym.id, &sym.qself, &sym.path, PathSource::Expr(None));
1473                    visit::walk_inline_asm_sym(this, sym);
1474                });
1475            })
1476        });
1477    }
1478
1479    fn visit_variant(&mut self, v: &'ast Variant) {
1480        self.resolve_doc_links(&v.attrs, MaybeExported::Ok(v.id));
1481        self.visit_id(v.id);
1482        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);
1483        self.visit_vis(&v.vis);
1484        self.visit_ident(&v.ident);
1485        self.visit_variant_data(&v.data);
1486        if let Some(discr) = &v.disr_expr {
1487            self.resolve_anon_const(discr, AnonConstKind::EnumDiscriminant);
1488        }
1489    }
1490
1491    fn visit_field_def(&mut self, f: &'ast FieldDef) {
1492        self.resolve_doc_links(&f.attrs, MaybeExported::Ok(f.id));
1493        let FieldDef { attrs, id: _, span: _, vis, ident, ty, is_placeholder: _, extras: _ } = f;
1494        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);
1495        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));
1496        self.resolve_restriction_path(&f.mut_restriction().kind);
1497        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);
1498        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));
1499        if let Some(v) = f.default_value() {
1500            self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);
1501        }
1502    }
1503
1504    fn visit_test_binder_forall(&mut self, forall: &'ast TestBinderForall) {
1505        self.with_generic_param_rib(
1506            &forall.generics.params,
1507            RibKind::Normal,
1508            forall.node_id,
1509            LifetimeBinderKind::WhereBound,
1510            forall.span,
1511            |this| {
1512                this.visit_generics(&forall.generics);
1513                this.visit_test_binder_body(&forall.body)
1514            },
1515        );
1516        // exit assertions don't have the bound vars in scope
1517        if let Some(assert_on_exit) = &forall.assert_on_exit {
1518            for constraint in assert_on_exit {
1519                self.visit_test_binder_constraint(constraint);
1520            }
1521        }
1522    }
1523
1524    fn visit_test_binder_exists(&mut self, exists: &'ast TestBinderExists) {
1525        self.with_generic_param_rib(
1526            &exists.params,
1527            RibKind::Normal,
1528            exists.node_id,
1529            LifetimeBinderKind::WhereBound,
1530            exists.span,
1531            |this| visit::walk_test_binder_exists(this, exists),
1532        );
1533    }
1534
1535    fn visit_test_binder_bound_type_constraint(
1536        &mut self,
1537        bound_type: &'ast TestBinderBoundTypeConstraint,
1538    ) {
1539        self.with_generic_param_rib(
1540            &bound_type.params,
1541            RibKind::Normal,
1542            bound_type.node_id,
1543            LifetimeBinderKind::WhereBound,
1544            bound_type.lhs.span.to(bound_type.rhs.ident.span),
1545            |this| visit::walk_test_binder_bound_type_constraint(this, bound_type),
1546        );
1547    }
1548}
1549
1550impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1551    fn new(resolver: &'a mut Resolver<'ra, 'tcx>) -> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1552        // During late resolution we only track the module component of the parent scope,
1553        // although it may be useful to track other components as well for diagnostics.
1554        let graph_root = resolver.graph_root;
1555        let parent_scope = ParentScope::module(graph_root, resolver.arenas);
1556        let start_rib_kind = RibKind::Module(graph_root);
1557        LateResolutionVisitor {
1558            r: resolver,
1559            parent_scope,
1560            ribs: PerNS {
1561                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)],
1562                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)],
1563                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)],
1564            },
1565            last_block_rib: None,
1566            label_ribs: Vec::new(),
1567            lifetime_ribs: Vec::new(),
1568            lifetime_elision_candidates: None,
1569            current_trait_ref: None,
1570            diag_metadata: Default::default(),
1571            // errors at module scope should always be reported
1572            in_func_body: false,
1573            lifetime_uses: Default::default(),
1574            use_injections: Vec::new(),
1575        }
1576    }
1577
1578    fn maybe_resolve_ident_in_lexical_scope(
1579        &mut self,
1580        ident: Ident,
1581        ns: Namespace,
1582    ) -> Option<LateDecl<'ra>> {
1583        self.r.resolve_ident_in_lexical_scope(
1584            ident,
1585            ns,
1586            &self.parent_scope,
1587            None,
1588            &self.ribs[ns],
1589            None,
1590            Some(&self.diag_metadata),
1591        )
1592    }
1593
1594    fn resolve_ident_in_lexical_scope(
1595        &mut self,
1596        ident: Ident,
1597        ns: Namespace,
1598        finalize: Option<Finalize>,
1599        ignore_decl: Option<Decl<'ra>>,
1600    ) -> Option<LateDecl<'ra>> {
1601        self.r.resolve_ident_in_lexical_scope(
1602            ident,
1603            ns,
1604            &self.parent_scope,
1605            finalize,
1606            &self.ribs[ns],
1607            ignore_decl,
1608            Some(&self.diag_metadata),
1609        )
1610    }
1611
1612    fn resolve_path(
1613        &mut self,
1614        path: &[Segment],
1615        opt_ns: Option<Namespace>, // `None` indicates a module path in import
1616        finalize: Option<Finalize>,
1617        source: PathSource<'_, 'ast, 'ra>,
1618    ) -> PathResult<'ra> {
1619        self.r.cm_mut().resolve_path_with_ribs(
1620            path,
1621            opt_ns,
1622            &self.parent_scope,
1623            Some(source),
1624            finalize.map(|finalize| Finalize { stage: Stage::Late, ..finalize }),
1625            Some(&self.ribs),
1626            None,
1627            None,
1628            Some(&self.diag_metadata),
1629        )
1630    }
1631
1632    // AST resolution
1633    //
1634    // We maintain a list of value ribs and type ribs.
1635    //
1636    // Simultaneously, we keep track of the current position in the module
1637    // graph in the `parent_scope.module` pointer. When we go to resolve a name in
1638    // the value or type namespaces, we first look through all the ribs and
1639    // then query the module graph. When we resolve a name in the module
1640    // namespace, we can skip all the ribs (since nested modules are not
1641    // allowed within blocks in Rust) and jump straight to the current module
1642    // graph node.
1643    //
1644    // Named implementations are handled separately. When we find a method
1645    // call, we consult the module node to find all of the implementations in
1646    // scope. This information is lazily cached in the module node. We then
1647    // generate a fake "implementation scope" containing all the
1648    // implementations thus found, for compatibility with old resolve pass.
1649
1650    /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
1651    fn with_rib<T>(
1652        &mut self,
1653        ns: Namespace,
1654        kind: RibKind<'ra>,
1655        work: impl FnOnce(&mut Self) -> T,
1656    ) -> T {
1657        self.ribs[ns].push(Rib::new(kind));
1658        let ret = work(self);
1659        self.ribs[ns].pop();
1660        ret
1661    }
1662
1663    fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1664        // For type parameter defaults, we have to ban access
1665        // to following type parameters, as the GenericArgs can only
1666        // provide previous type parameters as they're built. We
1667        // put all the parameters on the ban list and then remove
1668        // them one by one as they are processed and become available.
1669        let mut forward_ty_ban_rib =
1670            Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1671        let mut forward_const_ban_rib =
1672            Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1673        for param in params.iter() {
1674            match param.kind {
1675                GenericParamKind::Type { .. } => {
1676                    forward_ty_ban_rib
1677                        .bindings
1678                        .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1679                }
1680                GenericParamKind::Const { .. } => {
1681                    forward_const_ban_rib
1682                        .bindings
1683                        .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1684                }
1685                GenericParamKind::Lifetime => {}
1686            }
1687        }
1688
1689        // rust-lang/rust#61631: The type `Self` is essentially
1690        // another type parameter. For ADTs, we consider it
1691        // well-defined only after all of the ADT type parameters have
1692        // been provided. Therefore, we do not allow use of `Self`
1693        // anywhere in ADT type parameter defaults.
1694        //
1695        // (We however cannot ban `Self` for defaults on *all* generic
1696        // lists; e.g. trait generics can usefully refer to `Self`,
1697        // such as in the case of `trait Add<Rhs = Self>`.)
1698        if add_self_upper {
1699            // (`Some` if + only if we are in ADT's generics.)
1700            forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1701        }
1702
1703        // NOTE: We use different ribs here not for a technical reason, but just
1704        // for better diagnostics.
1705        let mut forward_ty_ban_rib_const_param_ty = Rib {
1706            bindings: forward_ty_ban_rib.bindings.clone(),
1707            patterns_with_skipped_bindings: Default::default(),
1708            kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1709        };
1710        let mut forward_const_ban_rib_const_param_ty = Rib {
1711            bindings: forward_const_ban_rib.bindings.clone(),
1712            patterns_with_skipped_bindings: Default::default(),
1713            kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1714        };
1715        // We'll ban these with a `ConstParamTy` rib, so just clear these ribs for better
1716        // diagnostics, so we don't mention anything about const param tys having generics at all.
1717        if !self.r.features.generic_const_parameter_types() {
1718            forward_ty_ban_rib_const_param_ty.bindings.clear();
1719            forward_const_ban_rib_const_param_ty.bindings.clear();
1720        }
1721
1722        self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1723            for param in params {
1724                match param.kind {
1725                    GenericParamKind::Lifetime => {
1726                        for bound in &param.bounds {
1727                            this.visit_param_bound(bound, BoundKind::Bound);
1728                        }
1729                    }
1730                    GenericParamKind::Type { ref default } => {
1731                        for bound in &param.bounds {
1732                            this.visit_param_bound(bound, BoundKind::Bound);
1733                        }
1734
1735                        if let Some(ty) = default {
1736                            this.ribs[TypeNS].push(forward_ty_ban_rib);
1737                            this.ribs[ValueNS].push(forward_const_ban_rib);
1738                            this.visit_ty(ty);
1739                            forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1740                            forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1741                        }
1742
1743                        // Allow all following defaults to refer to this type parameter.
1744                        let i = &Ident::with_dummy_span(param.ident.name);
1745                        forward_ty_ban_rib.bindings.swap_remove(i);
1746                        forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);
1747                    }
1748                    GenericParamKind::Const { ref ty, span: _, ref default } => {
1749                        // Const parameters can't have param bounds.
1750                        if !param.bounds.is_empty() {
    ::core::panicking::panic("assertion failed: param.bounds.is_empty()")
};assert!(param.bounds.is_empty());
1751
1752                        this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);
1753                        this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);
1754                        if this.r.features.generic_const_parameter_types() {
1755                            this.visit_ty(ty)
1756                        } else {
1757                            this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));
1758                            this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));
1759                            this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {
1760                                this.visit_ty(ty)
1761                            });
1762                            this.ribs[TypeNS].pop().unwrap();
1763                            this.ribs[ValueNS].pop().unwrap();
1764                        }
1765                        forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();
1766                        forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();
1767
1768                        if let Some(expr) = default {
1769                            this.ribs[TypeNS].push(forward_ty_ban_rib);
1770                            this.ribs[ValueNS].push(forward_const_ban_rib);
1771                            this.resolve_anon_const(
1772                                expr,
1773                                AnonConstKind::ConstArg(IsRepeatExpr::No),
1774                            );
1775                            forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1776                            forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1777                        }
1778
1779                        // Allow all following defaults to refer to this const parameter.
1780                        let i = &Ident::with_dummy_span(param.ident.name);
1781                        forward_const_ban_rib.bindings.swap_remove(i);
1782                        forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);
1783                    }
1784                }
1785            }
1786        })
1787    }
1788
1789    {}
#[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("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/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(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("kind")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("kind");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                            as &dyn ::tracing::field::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))]
1790    fn with_lifetime_rib<T>(
1791        &mut self,
1792        kind: LifetimeRibKind,
1793        work: impl FnOnce(&mut Self) -> T,
1794    ) -> T {
1795        self.lifetime_ribs.push(LifetimeRib::new(kind));
1796        let outer_elision_candidates = self.lifetime_elision_candidates.take();
1797        let ret = work(self);
1798        self.lifetime_elision_candidates = outer_elision_candidates;
1799        self.lifetime_ribs.pop();
1800        ret
1801    }
1802
1803    {}
#[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("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1803u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("lifetime")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("lifetime");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("use_ctxt")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("use_ctxt");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_ctxt)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ident = lifetime.ident;
            if ident.name == kw::StaticLifetime {
                self.record_lifetime_use(lifetime.id, LifetimeRes::Static,
                    LifetimeElisionCandidate::Ignore);
                return;
            }
            if ident.name == kw::UnderscoreLifetime {
                return self.resolve_anonymous_lifetime(lifetime, lifetime.id,
                        false);
            }
            let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
            while let Some(rib) = lifetime_rib_iter.next() {
                let normalized_ident = ident.normalize_to_macros_2_0();
                if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
                    self.record_lifetime_use(lifetime.id, res,
                        LifetimeElisionCandidate::Ignore);
                    if let LifetimeRes::Param { param, binder } = res {
                        match self.lifetime_uses.entry(param) {
                            Entry::Vacant(v) => {
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs:1829",
                                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1829u32),
                                                        ::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};
                                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("First use of {0:?} at {1:?}",
                                                                                    res, ident.span) as &dyn ::tracing::field::Value))])
                                            });
                                    } else { ; }
                                };
                                let use_set =
                                    self.lifetime_ribs.iter().rev().find_map(|rib|
                                                match rib.kind {
                                                    LifetimeRibKind::Item |
                                                        LifetimeRibKind::AnonymousReportError |
                                                        LifetimeRibKind::ElisionFailure =>
                                                        Some(LifetimeUseSet::Many),
                                                    LifetimeRibKind::AnonymousCreateParameter {
                                                        binder: anon_binder, .. } =>
                                                        Some(if binder == anon_binder {
                                                                LifetimeUseSet::One { use_span: ident.span, use_ctxt }
                                                            } else { LifetimeUseSet::Many }),
                                                    LifetimeRibKind::Elided { res: r, error_in_path } => {
                                                        Some(if res == r && !error_in_path {
                                                                LifetimeUseSet::One { use_span: ident.span, use_ctxt }
                                                            } else { LifetimeUseSet::Many })
                                                    }
                                                    LifetimeRibKind::Generics { .. } |
                                                        LifetimeRibKind::ConstParamTy => None,
                                                    LifetimeRibKind::ConcreteAnonConst(_) => {
                                                        ::rustc_middle::util::bug::span_bug_fmt(ident.span,
                                                            format_args!("unexpected rib kind: {0:?}", rib.kind))
                                                    }
                                                    LifetimeRibKind::ImplTrait => {
                                                        if self.r.features.anonymous_lifetime_in_impl_trait() {
                                                            None
                                                        } else { Some(LifetimeUseSet::Many) }
                                                    }
                                                }).unwrap_or(LifetimeUseSet::Many);
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs:1874",
                                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1874u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                                        ::tracing_core::field::FieldSet::new(&[{
                                                                            const NAME:
                                                                                ::tracing::__macro_support::FieldName<{
                                                                                    ::tracing::__macro_support::FieldName::len("use_ctxt")
                                                                                }> =
                                                                                ::tracing::__macro_support::FieldName::new("use_ctxt");
                                                                            NAME.as_str()
                                                                        },
                                                                        {
                                                                            const NAME:
                                                                                ::tracing::__macro_support::FieldName<{
                                                                                    ::tracing::__macro_support::FieldName::len("use_set")
                                                                                }> =
                                                                                ::tracing::__macro_support::FieldName::new("use_set");
                                                                            NAME.as_str()
                                                                        }], ::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};
                                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_ctxt)
                                                                            as &dyn ::tracing::field::Value)),
                                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_set)
                                                                            as &dyn ::tracing::field::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 /rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs:1878",
                                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1878u32),
                                                        ::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};
                                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Many uses of {0:?} at {1:?}",
                                                                                    res, ident.span) as &dyn ::tracing::field::Value))])
                                            });
                                    } else { ; }
                                };
                                *o.get_mut() = LifetimeUseSet::Many;
                            }
                        }
                    }
                    return;
                }
                match rib.kind {
                    LifetimeRibKind::Item => break,
                    LifetimeRibKind::ConstParamTy => {
                        let guar =
                            self.emit_non_static_lt_in_const_param_ty_error(lifetime);
                        self.record_lifetime_err(lifetime.id, guar);
                        return;
                    }
                    LifetimeRibKind::ConcreteAnonConst(cause) => {
                        let guar =
                            self.emit_forbidden_non_static_lifetime_error(cause,
                                lifetime);
                        self.record_lifetime_err(lifetime.id, guar);
                        return;
                    }
                    LifetimeRibKind::AnonymousCreateParameter { .. } |
                        LifetimeRibKind::Elided { .. } | LifetimeRibKind::Generics {
                        .. } | LifetimeRibKind::ElisionFailure |
                        LifetimeRibKind::AnonymousReportError |
                        LifetimeRibKind::ImplTrait => {}
                }
            }
            let normalized_ident = ident.normalize_to_macros_2_0();
            let outer_res =
                lifetime_rib_iter.find_map(|rib|
                        rib.bindings.get_key_value(&normalized_ident).map(|(&outer,
                                    _)| outer));
            let guar =
                self.emit_undeclared_lifetime_error(lifetime, outer_res);
            self.record_lifetime_err(lifetime.id, guar);
        }
    }
}#[instrument(level = "debug", skip(self))]
1804    fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1805        let ident = lifetime.ident;
1806
1807        if ident.name == kw::StaticLifetime {
1808            self.record_lifetime_use(
1809                lifetime.id,
1810                LifetimeRes::Static,
1811                LifetimeElisionCandidate::Ignore,
1812            );
1813            return;
1814        }
1815
1816        if ident.name == kw::UnderscoreLifetime {
1817            return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1818        }
1819
1820        let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1821        while let Some(rib) = lifetime_rib_iter.next() {
1822            let normalized_ident = ident.normalize_to_macros_2_0();
1823            if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1824                self.record_lifetime_use(lifetime.id, res, LifetimeElisionCandidate::Ignore);
1825
1826                if let LifetimeRes::Param { param, binder } = res {
1827                    match self.lifetime_uses.entry(param) {
1828                        Entry::Vacant(v) => {
1829                            debug!("First use of {:?} at {:?}", res, ident.span);
1830                            let use_set = self
1831                                .lifetime_ribs
1832                                .iter()
1833                                .rev()
1834                                .find_map(|rib| match rib.kind {
1835                                    // Do not suggest eliding a lifetime where an anonymous
1836                                    // lifetime would be illegal.
1837                                    LifetimeRibKind::Item
1838                                    | LifetimeRibKind::AnonymousReportError
1839                                    | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1840                                    // An anonymous lifetime is legal here, and bound to the right
1841                                    // place, go ahead.
1842                                    LifetimeRibKind::AnonymousCreateParameter {
1843                                        binder: anon_binder,
1844                                        ..
1845                                    } => Some(if binder == anon_binder {
1846                                        LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1847                                    } else {
1848                                        LifetimeUseSet::Many
1849                                    }),
1850                                    // Only report if eliding the lifetime would have the same
1851                                    // semantics.
1852                                    LifetimeRibKind::Elided { res: r, error_in_path } => {
1853                                        Some(if res == r && !error_in_path {
1854                                            LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1855                                        } else {
1856                                            LifetimeUseSet::Many
1857                                        })
1858                                    }
1859                                    LifetimeRibKind::Generics { .. }
1860                                    | LifetimeRibKind::ConstParamTy => None,
1861                                    LifetimeRibKind::ConcreteAnonConst(_) => {
1862                                        span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1863                                    }
1864
1865                                    LifetimeRibKind::ImplTrait => {
1866                                        if self.r.features.anonymous_lifetime_in_impl_trait() {
1867                                            None
1868                                        } else {
1869                                            Some(LifetimeUseSet::Many)
1870                                        }
1871                                    }
1872                                })
1873                                .unwrap_or(LifetimeUseSet::Many);
1874                            debug!(?use_ctxt, ?use_set);
1875                            v.insert(use_set);
1876                        }
1877                        Entry::Occupied(mut o) => {
1878                            debug!("Many uses of {:?} at {:?}", res, ident.span);
1879                            *o.get_mut() = LifetimeUseSet::Many;
1880                        }
1881                    }
1882                }
1883                return;
1884            }
1885
1886            match rib.kind {
1887                LifetimeRibKind::Item => break,
1888                LifetimeRibKind::ConstParamTy => {
1889                    let guar = self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1890                    self.record_lifetime_err(lifetime.id, guar);
1891                    return;
1892                }
1893                LifetimeRibKind::ConcreteAnonConst(cause) => {
1894                    let guar = self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1895                    self.record_lifetime_err(lifetime.id, guar);
1896                    return;
1897                }
1898                LifetimeRibKind::AnonymousCreateParameter { .. }
1899                | LifetimeRibKind::Elided { .. }
1900                | LifetimeRibKind::Generics { .. }
1901                | LifetimeRibKind::ElisionFailure
1902                | LifetimeRibKind::AnonymousReportError
1903                | LifetimeRibKind::ImplTrait => {}
1904            }
1905        }
1906
1907        let normalized_ident = ident.normalize_to_macros_2_0();
1908        let outer_res = lifetime_rib_iter
1909            .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1910
1911        let guar = self.emit_undeclared_lifetime_error(lifetime, outer_res);
1912        self.record_lifetime_err(lifetime.id, guar);
1913    }
1914
1915    {}
#[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("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1915u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("lifetime")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("lifetime");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("id_for_lint")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("id_for_lint");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("elided")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("elided");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lifetime)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id_for_lint)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&elided as
                                                            &dyn ::tracing::field::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 /rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs:1935",
                                        "rustc_resolve::late", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1935u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                        ::tracing_core::field::FieldSet::new(&[{
                                                            const NAME:
                                                                ::tracing::__macro_support::FieldName<{
                                                                    ::tracing::__macro_support::FieldName::len("rib.kind")
                                                                }> =
                                                                ::tracing::__macro_support::FieldName::new("rib.kind");
                                                            NAME.as_str()
                                                        }], ::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};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rib.kind)
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                match rib.kind {
                    LifetimeRibKind::AnonymousCreateParameter { binder, .. } =>
                        {
                        let res =
                            self.create_fresh_lifetime(lifetime.ident, binder, kind);
                        self.record_lifetime_use(lifetime.id, res,
                            elision_candidate);
                        return;
                    }
                    LifetimeRibKind::AnonymousReportError => {
                        let guar =
                            if elided {
                                let suggestion =
                                    if self.diag_metadata.in_assoc_ty_binding {
                                        None
                                    } else {
                                        self.lifetime_ribs[i..].iter().rev().find_map(|rib|
                                                {
                                                    if let LifetimeRibKind::Generics {
                                                            span,
                                                            kind: LifetimeBinderKind::PolyTrait |
                                                                LifetimeBinderKind::WhereBound, .. } = rib.kind {
                                                        Some(crate::diagnostics::ElidedAnonymousLifetimeReportErrorSuggestion {
                                                                lo: span.shrink_to_lo(),
                                                                hi: lifetime.ident.span.shrink_to_hi(),
                                                            })
                                                    } else { None }
                                                })
                                    };
                                if !self.in_func_body &&
                                                    let Some((module, _)) = &self.current_trait_ref &&
                                                let Some(ty) = &self.diag_metadata.current_self_type &&
                                            Some(true) == self.diag_metadata.in_non_gat_assoc_type &&
                                        let crate::ModuleKind::Def(DefKind::Trait, trait_id, _, _) =
                                            module.kind {
                                    if def_id_matches_path(self.r.tcx, trait_id,
                                            &["core", "iter", "traits", "iterator", "Iterator"]) {
                                        self.r.dcx().emit_err(crate::diagnostics::LendingIteratorReportError {
                                                lifetime: lifetime.ident.span,
                                                ty: ty.span,
                                            })
                                    } else {
                                        let decl =
                                            if !trait_id.is_local() &&
                                                                    let Some(assoc) = self.diag_metadata.current_impl_item &&
                                                                let AssocItemKind::Type(_) = assoc.kind &&
                                                            let assocs = self.r.tcx.associated_items(trait_id) &&
                                                        let Some(ident) = assoc.kind.ident() &&
                                                    let Some(assoc) =
                                                        assocs.find_by_ident_and_kind(self.r.tcx, ident,
                                                            AssocTag::Type, trait_id) {
                                                let mut decl: MultiSpan =
                                                    self.r.tcx.def_span(assoc.def_id).into();
                                                decl.push_span_label(self.r.tcx.def_span(trait_id),
                                                    String::new());
                                                decl
                                            } else { DUMMY_SP.into() };
                                        let mut err =
                                            self.r.dcx().create_err(crate::diagnostics::AnonymousLifetimeNonGatReportError {
                                                    lifetime: lifetime.ident.span,
                                                    decl,
                                                });
                                        self.point_at_impl_lifetimes(&mut err, i,
                                            lifetime.ident.span);
                                        err.emit()
                                    }
                                } else if self.diag_metadata.in_assoc_ty_binding {
                                    let mut err =
                                        self.r.dcx().create_err(crate::diagnostics::ElidedAnonymousLifetimeReportError {
                                                span: lifetime.ident.span,
                                                suggestion,
                                            });
                                    self.suggest_introducing_lifetime_for_assoc_ty_binding(&mut err,
                                        lifetime.ident.span);
                                    err.emit()
                                } else {
                                    self.r.dcx().emit_err(crate::diagnostics::ElidedAnonymousLifetimeReportError {
                                            span: lifetime.ident.span,
                                            suggestion,
                                        })
                                }
                            } else {
                                self.r.dcx().emit_err(crate::diagnostics::ExplicitAnonymousLifetimeReportError {
                                        span: lifetime.ident.span,
                                    })
                            };
                        self.record_lifetime_err(lifetime.id, guar);
                        return;
                    }
                    LifetimeRibKind::Elided { res, .. } => {
                        self.record_lifetime_use(lifetime.id, res,
                            elision_candidate);
                        return;
                    }
                    LifetimeRibKind::ElisionFailure => {
                        self.diag_metadata.current_elision_failures.push((missing_lifetime,
                                Either::Left(lifetime.id)));
                        return;
                    }
                    LifetimeRibKind::Item => break,
                    LifetimeRibKind::Generics { .. } |
                        LifetimeRibKind::ConstParamTy | LifetimeRibKind::ImplTrait
                        => {}
                    LifetimeRibKind::ConcreteAnonConst(_) => {
                        ::rustc_middle::util::bug::span_bug_fmt(lifetime.ident.span,
                            format_args!("unexpected rib kind: {0:?}", rib.kind))
                    }
                }
            }
            let guar =
                self.report_missing_lifetime_specifiers([&missing_lifetime],
                    None);
            self.record_lifetime_err(lifetime.id, guar);
        }
    }
}#[instrument(level = "debug", skip(self))]
1916    fn resolve_anonymous_lifetime(
1917        &mut self,
1918        lifetime: &Lifetime,
1919        id_for_lint: NodeId,
1920        elided: bool,
1921    ) {
1922        debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1923
1924        let kind =
1925            if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1926        let missing_lifetime = MissingLifetime {
1927            id: lifetime.id,
1928            span: lifetime.ident.span,
1929            kind,
1930            count: 1,
1931            id_for_lint,
1932        };
1933        let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1934        for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1935            debug!(?rib.kind);
1936            match rib.kind {
1937                LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1938                    let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1939                    self.record_lifetime_use(lifetime.id, res, elision_candidate);
1940                    return;
1941                }
1942                LifetimeRibKind::AnonymousReportError => {
1943                    let guar = if elided {
1944                        let suggestion = if self.diag_metadata.in_assoc_ty_binding {
1945                            // In an associated type binding like `I: IntoIterator<Item = &T>`,
1946                            // introducing the lifetime on the trait ref would produce
1947                            // `I: for<'a> IntoIterator<Item = &'a T>`. Prefer a named lifetime
1948                            // from an enclosing item instead, so the assoc-ty-binding-specific path
1949                            // below builds that suggestion.
1950                            None
1951                        } else {
1952                            self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1953                                // Look for a `Generics` rib that represents a trait or where-bound
1954                                // binder (`T: Trait<&U>` or `where T: Trait<&U>`), since that is
1955                                // where the generic E0637 diagnostic can insert `for<'a>`.
1956                                if let LifetimeRibKind::Generics {
1957                                    span,
1958                                    kind:
1959                                        LifetimeBinderKind::PolyTrait
1960                                        | LifetimeBinderKind::WhereBound,
1961                                    ..
1962                                } = rib.kind
1963                                {
1964                                    Some(crate::diagnostics::ElidedAnonymousLifetimeReportErrorSuggestion {
1965                                        lo: span.shrink_to_lo(),
1966                                        hi: lifetime.ident.span.shrink_to_hi(),
1967                                    })
1968                                } else {
1969                                    None
1970                                }
1971                            })
1972                        };
1973                        // are we trying to use an anonymous lifetime
1974                        // on a non GAT associated trait type?
1975                        if !self.in_func_body
1976                            && let Some((module, _)) = &self.current_trait_ref
1977                            && let Some(ty) = &self.diag_metadata.current_self_type
1978                            && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1979                            && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _, _) =
1980                                module.kind
1981                        {
1982                            if def_id_matches_path(
1983                                self.r.tcx,
1984                                trait_id,
1985                                &["core", "iter", "traits", "iterator", "Iterator"],
1986                            ) {
1987                                self.r.dcx().emit_err(
1988                                    crate::diagnostics::LendingIteratorReportError {
1989                                        lifetime: lifetime.ident.span,
1990                                        ty: ty.span,
1991                                    },
1992                                )
1993                            } else {
1994                                let decl = if !trait_id.is_local()
1995                                    && let Some(assoc) = self.diag_metadata.current_impl_item
1996                                    && let AssocItemKind::Type(_) = assoc.kind
1997                                    && let assocs = self.r.tcx.associated_items(trait_id)
1998                                    && let Some(ident) = assoc.kind.ident()
1999                                    && let Some(assoc) = assocs.find_by_ident_and_kind(
2000                                        self.r.tcx,
2001                                        ident,
2002                                        AssocTag::Type,
2003                                        trait_id,
2004                                    ) {
2005                                    let mut decl: MultiSpan =
2006                                        self.r.tcx.def_span(assoc.def_id).into();
2007                                    decl.push_span_label(
2008                                        self.r.tcx.def_span(trait_id),
2009                                        String::new(),
2010                                    );
2011                                    decl
2012                                } else {
2013                                    DUMMY_SP.into()
2014                                };
2015                                let mut err = self.r.dcx().create_err(
2016                                    crate::diagnostics::AnonymousLifetimeNonGatReportError {
2017                                        lifetime: lifetime.ident.span,
2018                                        decl,
2019                                    },
2020                                );
2021                                self.point_at_impl_lifetimes(&mut err, i, lifetime.ident.span);
2022                                err.emit()
2023                            }
2024                        } else if self.diag_metadata.in_assoc_ty_binding {
2025                            // For associated type bindings, e.g.
2026                            // `fn f<I: IntoIterator<Item = &T>>()`, introduce a named lifetime
2027                            // on an enclosing generics binder instead:
2028                            // `fn f<'a, I: IntoIterator<Item = &'a T>>()`.
2029                            let mut err = self.r.dcx().create_err(
2030                                crate::diagnostics::ElidedAnonymousLifetimeReportError {
2031                                    span: lifetime.ident.span,
2032                                    suggestion,
2033                                },
2034                            );
2035                            self.suggest_introducing_lifetime_for_assoc_ty_binding(
2036                                &mut err,
2037                                lifetime.ident.span,
2038                            );
2039                            err.emit()
2040                        } else {
2041                            self.r.dcx().emit_err(
2042                                crate::diagnostics::ElidedAnonymousLifetimeReportError {
2043                                    span: lifetime.ident.span,
2044                                    suggestion,
2045                                },
2046                            )
2047                        }
2048                    } else {
2049                        self.r.dcx().emit_err(
2050                            crate::diagnostics::ExplicitAnonymousLifetimeReportError {
2051                                span: lifetime.ident.span,
2052                            },
2053                        )
2054                    };
2055                    self.record_lifetime_err(lifetime.id, guar);
2056                    return;
2057                }
2058                LifetimeRibKind::Elided { res, .. } => {
2059                    self.record_lifetime_use(lifetime.id, res, elision_candidate);
2060                    return;
2061                }
2062                LifetimeRibKind::ElisionFailure => {
2063                    self.diag_metadata
2064                        .current_elision_failures
2065                        .push((missing_lifetime, Either::Left(lifetime.id)));
2066                    return;
2067                }
2068                LifetimeRibKind::Item => break,
2069                LifetimeRibKind::Generics { .. }
2070                | LifetimeRibKind::ConstParamTy
2071                | LifetimeRibKind::ImplTrait => {}
2072                LifetimeRibKind::ConcreteAnonConst(_) => {
2073                    // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
2074                    span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
2075                }
2076            }
2077        }
2078        let guar = self.report_missing_lifetime_specifiers([&missing_lifetime], None);
2079        self.record_lifetime_err(lifetime.id, guar);
2080    }
2081
2082    fn point_at_impl_lifetimes(&mut self, err: &mut Diag<'_>, i: usize, lifetime: Span) {
2083        let Some((rib, span)) =
2084            self.lifetime_ribs[..i].iter().rev().find_map(|rib| match rib.kind {
2085                LifetimeRibKind::Generics { span, kind: LifetimeBinderKind::ImplBlock, .. } => {
2086                    Some((rib, span))
2087                }
2088                _ => None,
2089            })
2090        else {
2091            return;
2092        };
2093        if !rib.bindings.is_empty() {
2094            err.span_label(
2095                span,
2096                ::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!(
2097                    "there {} named lifetime{} specified on the impl block you could use",
2098                    if rib.bindings.len() == 1 { "is a" } else { "are" },
2099                    pluralize!(rib.bindings.len()),
2100                ),
2101            );
2102            if rib.bindings.len() == 1 {
2103                err.span_suggestion_verbose(
2104                    lifetime.shrink_to_hi(),
2105                    "consider using the lifetime from the impl block",
2106                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ",
                rib.bindings.keys().next().unwrap()))
    })format!("{} ", rib.bindings.keys().next().unwrap()),
2107                    Applicability::MaybeIncorrect,
2108                );
2109            }
2110        } else {
2111            struct AnonRefFinder;
2112            impl<'ast> Visitor<'ast> for AnonRefFinder {
2113                type Result = ControlFlow<Span>;
2114
2115                fn visit_ty(&mut self, ty: &'ast ast::Ty) -> Self::Result {
2116                    if let ast::TyKind::Ref(None, mut_ty) = &ty.kind {
2117                        return ControlFlow::Break(mut_ty.ty.span.shrink_to_lo());
2118                    }
2119                    visit::walk_ty(self, ty)
2120                }
2121
2122                fn visit_lifetime(
2123                    &mut self,
2124                    lt: &'ast ast::Lifetime,
2125                    _cx: visit::LifetimeCtxt,
2126                ) -> Self::Result {
2127                    if lt.ident.name == kw::UnderscoreLifetime {
2128                        return ControlFlow::Break(lt.ident.span);
2129                    }
2130                    visit::walk_lifetime(self, lt)
2131                }
2132            }
2133
2134            if let Some(ty) = &self.diag_metadata.current_self_type
2135                && let ControlFlow::Break(sp) = AnonRefFinder.visit_ty(ty)
2136            {
2137                err.multipart_suggestion(
2138                    "add a lifetime to the impl block and use it in the self type and associated \
2139                     type",
2140                    ::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![
2141                        (span, "<'a>".to_string()),
2142                        (sp, "'a ".to_string()),
2143                        (lifetime.shrink_to_hi(), "'a ".to_string()),
2144                    ],
2145                    Applicability::MaybeIncorrect,
2146                );
2147            } else if let Some(item) = &self.diag_metadata.current_item
2148                && let ItemKind::Impl(impl_) = &item.kind
2149                && let Some(of_trait) = &impl_.of_trait
2150                && let ControlFlow::Break(sp) = AnonRefFinder.visit_trait_ref(&of_trait.trait_ref)
2151            {
2152                err.multipart_suggestion(
2153                    "add a lifetime to the impl block and use it in the trait and associated type",
2154                    ::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![
2155                        (span, "<'a>".to_string()),
2156                        (sp, "'a".to_string()),
2157                        (lifetime.shrink_to_hi(), "'a ".to_string()),
2158                    ],
2159                    Applicability::MaybeIncorrect,
2160                );
2161            } else {
2162                err.span_label(
2163                    span,
2164                    "you could add a lifetime on the impl block, if the trait or the self type \
2165                     could have one",
2166                );
2167            }
2168        }
2169    }
2170
2171    {}
#[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("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2171u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("anchor_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("anchor_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&anchor_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let id = self.r.next_node_id();
            let lt =
                Lifetime {
                    id,
                    ident: Ident::new(kw::UnderscoreLifetime, span),
                };
            self.record_lifetime_use(anchor_id,
                LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
                LifetimeElisionCandidate::Ignore);
            self.resolve_anonymous_lifetime(&lt, anchor_id, true);
        }
    }
}#[instrument(level = "debug", skip(self))]
2172    fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
2173        let id = self.r.next_node_id();
2174        let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
2175
2176        self.record_lifetime_use(
2177            anchor_id,
2178            LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
2179            LifetimeElisionCandidate::Ignore,
2180        );
2181        self.resolve_anonymous_lifetime(&lt, anchor_id, true);
2182    }
2183
2184    {}
#[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("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2184u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ident")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ident");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("binder")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("binder");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("kind")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("kind");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&binder)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                            as &dyn ::tracing::field::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 /rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs:2192",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2192u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ident.span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ident.span");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident.span)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let param = self.r.next_node_id();
            let res = LifetimeRes::Fresh { param, kind };
            self.record_lifetime_def(param, res);
            self.r.current_owner.extra_lifetime_params_map.entry(binder).or_insert_with(Vec::new).push((ident,
                    param, kind));
            res
        }
    }
}#[instrument(level = "debug", skip(self))]
2185    fn create_fresh_lifetime(
2186        &mut self,
2187        ident: Ident,
2188        binder: NodeId,
2189        kind: MissingLifetimeKind,
2190    ) -> LifetimeRes {
2191        debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
2192        debug!(?ident.span);
2193
2194        // Leave the responsibility to create the `LocalDefId` to lowering.
2195        let param = self.r.next_node_id();
2196        let res = LifetimeRes::Fresh { param, kind };
2197        self.record_lifetime_def(param, res);
2198
2199        // Record the created lifetime parameter so lowering can pick it up and add it to HIR.
2200        self.r
2201            .current_owner
2202            .extra_lifetime_params_map
2203            .entry(binder)
2204            .or_insert_with(Vec::new)
2205            .push((ident, param, kind));
2206        res
2207    }
2208
2209    {}
#[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("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2209u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("partial_res")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("partial_res");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path_span");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&partial_res)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path_span)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let proj_start = path.len() - partial_res.unresolved_segments();
            for (i, segment) in path.iter().enumerate() {
                if segment.has_lifetime_args { continue; }
                let Some(segment_id) = segment.id else { continue; };
                let type_def_id =
                    match partial_res.base_res() {
                        Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start =>
                            {
                            self.r.tcx.parent(def_id)
                        }
                        Res::Def(DefKind::Variant, def_id) if
                            i + 2 == proj_start && segment.has_generic_args => {
                            self.r.tcx.parent(def_id)
                        }
                        Res::Def(DefKind::Variant, def_id) if
                            i + 1 == proj_start &&
                                !i.checked_sub(1).is_some_and(|i| path[i].has_generic_args)
                            => {
                            self.r.tcx.parent(def_id)
                        }
                        Res::Def(DefKind::Struct, def_id) |
                            Res::Def(DefKind::Union, def_id) |
                            Res::Def(DefKind::Enum, def_id) |
                            Res::Def(DefKind::TyAlias, def_id) |
                            Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start => {
                            def_id
                        }
                        _ => continue,
                    };
                let expected_lifetimes =
                    self.r.item_generics_num_lifetimes(type_def_id);
                if expected_lifetimes == 0 { continue; }
                let node_ids = self.r.next_node_ids(expected_lifetimes);
                self.record_lifetime_use(segment_id,
                    LifetimeRes::ElidedAnchor {
                        start: node_ids.start,
                        end: node_ids.end,
                    }, LifetimeElisionCandidate::Ignore);
                let inferred =
                    match source {
                        PathSource::Trait(..) | PathSource::TraitItem(..) |
                            PathSource::Type | PathSource::PreciseCapturingArg(..) |
                            PathSource::ReturnTypeNotation | PathSource::Macro |
                            PathSource::Module => false,
                        PathSource::Expr(..) | PathSource::Pat |
                            PathSource::Struct(_) | PathSource::TupleStruct(..) |
                            PathSource::DefineOpaques | PathSource::Delegation |
                            PathSource::ExternItemImpl => true,
                    };
                if inferred {
                    for id in node_ids {
                        self.record_lifetime_use(id, LifetimeRes::Infer,
                            LifetimeElisionCandidate::Ignore);
                    }
                    continue;
                }
                let elided_lifetime_span =
                    if segment.has_generic_args {
                        segment.args_span.with_hi(segment.args_span.lo() +
                                BytePos(1))
                    } else {
                        segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
                    };
                let ident =
                    Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
                let kind =
                    if segment.has_generic_args {
                        MissingLifetimeKind::Comma
                    } else { MissingLifetimeKind::Brackets };
                let missing_lifetime =
                    MissingLifetime {
                        id: node_ids.start,
                        id_for_lint: segment_id,
                        span: elided_lifetime_span,
                        kind,
                        count: expected_lifetimes,
                    };
                let mut should_lint = true;
                for rib in self.lifetime_ribs.iter().rev() {
                    match rib.kind {
                        LifetimeRibKind::AnonymousCreateParameter {
                            report_in_path: true, .. } | LifetimeRibKind::Elided {
                            error_in_path: true, .. } => {
                            let sess = self.r.tcx.sess;
                            let subdiag =
                                elided_lifetime_in_path_suggestion(sess.source_map(),
                                    expected_lifetimes, path_span, !segment.has_generic_args,
                                    elided_lifetime_span);
                            let guar =
                                self.r.dcx().emit_err(crate::diagnostics::ImplicitElidedLifetimeNotAllowedHere {
                                        span: path_span,
                                        subdiag,
                                    });
                            should_lint = false;
                            for id in node_ids { self.record_lifetime_err(id, guar); }
                            break;
                        }
                        LifetimeRibKind::AnonymousCreateParameter { binder, .. } =>
                            {
                            let mut candidate =
                                LifetimeElisionCandidate::Missing(missing_lifetime);
                            for id in node_ids {
                                let res = self.create_fresh_lifetime(ident, binder, kind);
                                self.record_lifetime_use(id, res,
                                    replace(&mut candidate, LifetimeElisionCandidate::Ignore));
                            }
                            break;
                        }
                        LifetimeRibKind::Elided { res, error_in_path: false } => {
                            let mut candidate =
                                LifetimeElisionCandidate::Missing(missing_lifetime);
                            for id in node_ids {
                                self.record_lifetime_use(id, res,
                                    replace(&mut candidate, LifetimeElisionCandidate::Ignore));
                            }
                            break;
                        }
                        LifetimeRibKind::ElisionFailure => {
                            self.diag_metadata.current_elision_failures.push((missing_lifetime,
                                    Either::Right(node_ids)));
                            break;
                        }
                        LifetimeRibKind::AnonymousReportError |
                            LifetimeRibKind::Item => {
                            let guar =
                                self.report_missing_lifetime_specifiers([&missing_lifetime],
                                    None);
                            for id in node_ids { self.record_lifetime_err(id, guar); }
                            break;
                        }
                        LifetimeRibKind::Generics { .. } |
                            LifetimeRibKind::ConstParamTy | LifetimeRibKind::ImplTrait
                            => {}
                        LifetimeRibKind::ConcreteAnonConst(_) => {
                            ::rustc_middle::util::bug::span_bug_fmt(elided_lifetime_span,
                                format_args!("unexpected rib kind: {0:?}", rib.kind))
                        }
                    }
                }
                if should_lint {
                    let include_angle_bracket = !segment.has_generic_args;
                    self.r.lint_buffer.dyn_buffer_lint_any(ELIDED_LIFETIMES_IN_PATHS,
                        segment_id, elided_lifetime_span,
                        move |dcx, level, sess|
                            {
                                let source_map =
                                    sess.downcast_ref::<rustc_session::Session>().expect("expected a `Session`").source_map();
                                crate::diagnostics::ElidedLifetimesInPaths {
                                        subdiag: elided_lifetime_in_path_suggestion(source_map,
                                            expected_lifetimes, path_span, include_angle_bracket,
                                            elided_lifetime_span),
                                    }.into_diag(dcx, level)
                            });
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2210    fn resolve_elided_lifetimes_in_path(
2211        &mut self,
2212        partial_res: PartialRes,
2213        path: &[Segment],
2214        source: PathSource<'_, 'ast, 'ra>,
2215        path_span: Span,
2216    ) {
2217        let proj_start = path.len() - partial_res.unresolved_segments();
2218        for (i, segment) in path.iter().enumerate() {
2219            if segment.has_lifetime_args {
2220                continue;
2221            }
2222            let Some(segment_id) = segment.id else {
2223                continue;
2224            };
2225
2226            // Figure out if this is a type/trait segment,
2227            // which may need lifetime elision performed.
2228            let type_def_id = match partial_res.base_res() {
2229                Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2230                    self.r.tcx.parent(def_id)
2231                }
2232                Res::Def(DefKind::Variant, def_id)
2233                    if i + 2 == proj_start && segment.has_generic_args =>
2234                {
2235                    self.r.tcx.parent(def_id)
2236                }
2237                Res::Def(DefKind::Variant, def_id)
2238                    if i + 1 == proj_start
2239                        && !i.checked_sub(1).is_some_and(|i| path[i].has_generic_args) =>
2240                {
2241                    self.r.tcx.parent(def_id)
2242                }
2243                Res::Def(DefKind::Struct, def_id)
2244                | Res::Def(DefKind::Union, def_id)
2245                | Res::Def(DefKind::Enum, def_id)
2246                | Res::Def(DefKind::TyAlias, def_id)
2247                | Res::Def(DefKind::Trait, def_id)
2248                    if i + 1 == proj_start =>
2249                {
2250                    def_id
2251                }
2252                _ => continue,
2253            };
2254
2255            let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2256            if expected_lifetimes == 0 {
2257                continue;
2258            }
2259
2260            let node_ids = self.r.next_node_ids(expected_lifetimes);
2261            self.record_lifetime_use(
2262                segment_id,
2263                LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2264                LifetimeElisionCandidate::Ignore,
2265            );
2266
2267            let inferred = match source {
2268                PathSource::Trait(..)
2269                | PathSource::TraitItem(..)
2270                | PathSource::Type
2271                | PathSource::PreciseCapturingArg(..)
2272                | PathSource::ReturnTypeNotation
2273                | PathSource::Macro
2274                | PathSource::Module => false,
2275                PathSource::Expr(..)
2276                | PathSource::Pat
2277                | PathSource::Struct(_)
2278                | PathSource::TupleStruct(..)
2279                | PathSource::DefineOpaques
2280                | PathSource::Delegation
2281                | PathSource::ExternItemImpl => true,
2282            };
2283            if inferred {
2284                // Do not create a parameter for patterns and expressions: type checking can infer
2285                // the appropriate lifetime for us.
2286                for id in node_ids {
2287                    self.record_lifetime_use(
2288                        id,
2289                        LifetimeRes::Infer,
2290                        LifetimeElisionCandidate::Ignore,
2291                    );
2292                }
2293                continue;
2294            }
2295
2296            let elided_lifetime_span = if segment.has_generic_args {
2297                // If there are brackets, but not generic arguments, then use the opening bracket
2298                segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2299            } else {
2300                // If there are no brackets, use the identifier span.
2301                // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
2302                // originating from macros, since the segment's span might be from a macro arg.
2303                segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2304            };
2305            let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2306
2307            let kind = if segment.has_generic_args {
2308                MissingLifetimeKind::Comma
2309            } else {
2310                MissingLifetimeKind::Brackets
2311            };
2312            let missing_lifetime = MissingLifetime {
2313                id: node_ids.start,
2314                id_for_lint: segment_id,
2315                span: elided_lifetime_span,
2316                kind,
2317                count: expected_lifetimes,
2318            };
2319            let mut should_lint = true;
2320            for rib in self.lifetime_ribs.iter().rev() {
2321                match rib.kind {
2322                    // In create-parameter mode we error here because we don't want to support
2323                    // deprecated impl elision in new features like impl elision and `async fn`,
2324                    // both of which work using the `CreateParameter` mode:
2325                    //
2326                    //     impl Foo for std::cell::Ref<u32> // note lack of '_
2327                    //     async fn foo(_: std::cell::Ref<u32>) { ... }
2328                    LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2329                    | LifetimeRibKind::Elided { error_in_path: true, .. } => {
2330                        let sess = self.r.tcx.sess;
2331                        let subdiag = elided_lifetime_in_path_suggestion(
2332                            sess.source_map(),
2333                            expected_lifetimes,
2334                            path_span,
2335                            !segment.has_generic_args,
2336                            elided_lifetime_span,
2337                        );
2338                        let guar = self.r.dcx().emit_err(
2339                            crate::diagnostics::ImplicitElidedLifetimeNotAllowedHere {
2340                                span: path_span,
2341                                subdiag,
2342                            },
2343                        );
2344                        should_lint = false;
2345
2346                        for id in node_ids {
2347                            self.record_lifetime_err(id, guar);
2348                        }
2349                        break;
2350                    }
2351                    // Do not create a parameter for patterns and expressions.
2352                    LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2353                        // Group all suggestions into the first record.
2354                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2355                        for id in node_ids {
2356                            let res = self.create_fresh_lifetime(ident, binder, kind);
2357                            self.record_lifetime_use(
2358                                id,
2359                                res,
2360                                replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2361                            );
2362                        }
2363                        break;
2364                    }
2365                    LifetimeRibKind::Elided { res, error_in_path: false } => {
2366                        let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2367                        for id in node_ids {
2368                            self.record_lifetime_use(
2369                                id,
2370                                res,
2371                                replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2372                            );
2373                        }
2374                        break;
2375                    }
2376                    LifetimeRibKind::ElisionFailure => {
2377                        self.diag_metadata
2378                            .current_elision_failures
2379                            .push((missing_lifetime, Either::Right(node_ids)));
2380                        break;
2381                    }
2382                    // `LifetimeRes::Error`, which would usually be used in the case of
2383                    // `ReportError`, is unsuitable here, as we don't emit an error yet. Instead,
2384                    // we simply resolve to an implicit lifetime, which will be checked later, at
2385                    // which point a suitable error will be emitted.
2386                    LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2387                        let guar =
2388                            self.report_missing_lifetime_specifiers([&missing_lifetime], None);
2389                        for id in node_ids {
2390                            self.record_lifetime_err(id, guar);
2391                        }
2392                        break;
2393                    }
2394                    LifetimeRibKind::Generics { .. }
2395                    | LifetimeRibKind::ConstParamTy
2396                    | LifetimeRibKind::ImplTrait => {}
2397                    LifetimeRibKind::ConcreteAnonConst(_) => {
2398                        // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
2399                        span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2400                    }
2401                }
2402            }
2403
2404            if should_lint {
2405                let include_angle_bracket = !segment.has_generic_args;
2406                self.r.lint_buffer.dyn_buffer_lint_any(
2407                    ELIDED_LIFETIMES_IN_PATHS,
2408                    segment_id,
2409                    elided_lifetime_span,
2410                    move |dcx, level, sess| {
2411                        let source_map = sess
2412                            .downcast_ref::<rustc_session::Session>()
2413                            .expect("expected a `Session`")
2414                            .source_map();
2415                        crate::diagnostics::ElidedLifetimesInPaths {
2416                            subdiag: elided_lifetime_in_path_suggestion(
2417                                source_map,
2418                                expected_lifetimes,
2419                                path_span,
2420                                include_angle_bracket,
2421                                elided_lifetime_span,
2422                            ),
2423                        }
2424                        .into_diag(dcx, level)
2425                    },
2426                );
2427            }
2428        }
2429    }
2430
2431    /// Register a use of an already defined lifetime.
2432    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("record_lifetime_use",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2432u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("res")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("res");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("candidate")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("candidate");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidate)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.record_lifetime_def(id, res);
            match res {
                LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } |
                    LifetimeRes::Static { .. } => {
                    if let Some(ref mut candidates) =
                            self.lifetime_elision_candidates {
                        candidates.push((res, candidate));
                    }
                }
                LifetimeRes::Infer | LifetimeRes::Error(..) |
                    LifetimeRes::ElidedAnchor { .. } => {}
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
2433    fn record_lifetime_use(
2434        &mut self,
2435        id: NodeId,
2436        res: LifetimeRes,
2437        candidate: LifetimeElisionCandidate,
2438    ) {
2439        self.record_lifetime_def(id, res);
2440
2441        match res {
2442            LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2443                if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2444                    candidates.push((res, candidate));
2445                }
2446            }
2447            LifetimeRes::Infer | LifetimeRes::Error(..) | LifetimeRes::ElidedAnchor { .. } => {}
2448        }
2449    }
2450
2451    /// Can be used for both definitions and uses of lifetimes, as an error
2452    /// has already been reported.
2453    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("record_lifetime_err",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2453u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("guar")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("guar");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&guar)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        { self.record_lifetime_def(id, LifetimeRes::Error(guar)); }
    }
}#[instrument(level = "debug", skip(self))]
2454    fn record_lifetime_err(&mut self, id: NodeId, guar: ErrorGuaranteed) {
2455        self.record_lifetime_def(id, LifetimeRes::Error(guar));
2456    }
2457
2458    /// Define a new lifetime (e.g. in generics)
2459    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("record_lifetime_def",
                                    "rustc_resolve::late", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_resolve/src/late.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2459u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("res")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("res");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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