Skip to main content

rustc_hir_analysis/hir_ty_lowering/
mod.rs

1//! HIR ty lowering: Lowers type-system entities[^1] from the [HIR][hir] to
2//! the [`rustc_middle::ty`] representation.
3//!
4//! Not to be confused with *AST lowering* which lowers AST constructs to HIR ones
5//! or with *THIR* / *MIR* *lowering* / *building* which lowers HIR *bodies*
6//! (i.e., “executable code”) to THIR / MIR.
7//!
8//! Most lowering routines are defined on [`dyn HirTyLowerer`](HirTyLowerer) directly,
9//! like the main routine of this module, `lower_ty`.
10//!
11//! This module used to be called `astconv`.
12//!
13//! [^1]: This includes types, lifetimes / regions, constants in type positions,
14//! trait references and bounds.
15
16mod bounds;
17mod cmse;
18mod dyn_trait;
19pub mod errors;
20pub mod generics;
21
22use std::slice;
23
24use rustc_ast::LitKind;
25use rustc_data_structures::assert_matches;
26use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
27use rustc_errors::codes::*;
28use rustc_errors::{
29    Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, FatalError, struct_span_code_err,
30};
31use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
32use rustc_hir::def_id::{DefId, LocalDefId};
33use rustc_hir::{self as hir, AnonConst, GenericArg, GenericArgs, HirId};
34use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
35use rustc_infer::traits::DynCompatibilityViolation;
36use rustc_macros::{TypeFoldable, TypeVisitable};
37use rustc_middle::middle::stability::AllowUnstable;
38use rustc_middle::ty::print::PrintPolyTraitRefExt as _;
39use rustc_middle::ty::{
40    self, Const, GenericArgKind, GenericArgsRef, GenericParamDefKind, LitToConstInput, Ty, TyCtxt,
41    TypeSuperFoldable, TypeVisitableExt, TypingMode, Upcast, const_lit_matches_ty, fold_regions,
42};
43use rustc_middle::{bug, span_bug};
44use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
45use rustc_session::parse::feature_err;
46use rustc_span::{DUMMY_SP, Ident, Span, kw, sym};
47use rustc_trait_selection::infer::InferCtxtExt;
48use rustc_trait_selection::traits::wf::object_region_bounds;
49use rustc_trait_selection::traits::{self, FulfillmentError};
50use tracing::{debug, instrument};
51
52use crate::check::check_abi;
53use crate::check_c_variadic_abi;
54use crate::errors::{AmbiguousLifetimeBound, BadReturnTypeNotation};
55use crate::hir_ty_lowering::errors::{GenericsArgsErrExtend, prohibit_assoc_item_constraint};
56use crate::hir_ty_lowering::generics::{check_generic_arg_count, lower_generic_args};
57use crate::middle::resolve_bound_vars as rbv;
58
59/// The context in which an implied bound is being added to a item being lowered (i.e. a sizedness
60/// trait or a default trait)
61#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ImpliedBoundsContext<'tcx> {
    #[inline]
    fn clone(&self) -> ImpliedBoundsContext<'tcx> {
        let _: ::core::clone::AssertParamIsClone<LocalDefId>;
        let _:
                ::core::clone::AssertParamIsClone<&'tcx [hir::WherePredicate<'tcx>]>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ImpliedBoundsContext<'tcx> { }Copy)]
62pub(crate) enum ImpliedBoundsContext<'tcx> {
63    /// An implied bound is added to a trait definition (i.e. a new supertrait), used when adding
64    /// a default `MetaSized` supertrait
65    TraitDef(LocalDefId),
66    /// An implied bound is added to a type parameter
67    TyParam(LocalDefId, &'tcx [hir::WherePredicate<'tcx>]),
68    /// An implied bound being added in any other context
69    AssociatedTypeOrImplTrait,
70}
71
72/// A path segment that is semantically allowed to have generic arguments.
73#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GenericPathSegment {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field2_finish(f,
            "GenericPathSegment", &self.0, &&self.1)
    }
}Debug)]
74pub struct GenericPathSegment(pub DefId, pub usize);
75
76#[derive(#[automatically_derived]
impl ::core::marker::Copy for PredicateFilter { }Copy, #[automatically_derived]
impl ::core::clone::Clone for PredicateFilter {
    #[inline]
    fn clone(&self) -> PredicateFilter {
        let _: ::core::clone::AssertParamIsClone<Ident>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for PredicateFilter {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            PredicateFilter::All =>
                ::core::fmt::Formatter::write_str(f, "All"),
            PredicateFilter::SelfOnly =>
                ::core::fmt::Formatter::write_str(f, "SelfOnly"),
            PredicateFilter::SelfTraitThatDefines(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "SelfTraitThatDefines", &__self_0),
            PredicateFilter::SelfAndAssociatedTypeBounds =>
                ::core::fmt::Formatter::write_str(f,
                    "SelfAndAssociatedTypeBounds"),
            PredicateFilter::ConstIfConst =>
                ::core::fmt::Formatter::write_str(f, "ConstIfConst"),
            PredicateFilter::SelfConstIfConst =>
                ::core::fmt::Formatter::write_str(f, "SelfConstIfConst"),
        }
    }
}Debug)]
77pub enum PredicateFilter {
78    /// All predicates may be implied by the trait.
79    All,
80
81    /// Only traits that reference `Self: ..` are implied by the trait.
82    SelfOnly,
83
84    /// Only traits that reference `Self: ..` and define an associated type
85    /// with the given ident are implied by the trait. This mode exists to
86    /// side-step query cycles when lowering associated types.
87    SelfTraitThatDefines(Ident),
88
89    /// Only traits that reference `Self: ..` and their associated type bounds.
90    /// For example, given `Self: Tr<A: B>`, this would expand to `Self: Tr`
91    /// and `<Self as Tr>::A: B`.
92    SelfAndAssociatedTypeBounds,
93
94    /// Filter only the `[const]` bounds, which are lowered into `HostEffect` clauses.
95    ConstIfConst,
96
97    /// Filter only the `[const]` bounds which are *also* in the supertrait position.
98    SelfConstIfConst,
99}
100
101#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for RegionInferReason<'a> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            RegionInferReason::ExplicitObjectLifetime =>
                ::core::fmt::Formatter::write_str(f,
                    "ExplicitObjectLifetime"),
            RegionInferReason::ObjectLifetimeDefault(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ObjectLifetimeDefault", &__self_0),
            RegionInferReason::Param(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Param",
                    &__self_0),
            RegionInferReason::RegionPredicate =>
                ::core::fmt::Formatter::write_str(f, "RegionPredicate"),
            RegionInferReason::Reference =>
                ::core::fmt::Formatter::write_str(f, "Reference"),
            RegionInferReason::OutlivesBound =>
                ::core::fmt::Formatter::write_str(f, "OutlivesBound"),
        }
    }
}Debug)]
102pub enum RegionInferReason<'a> {
103    /// Lifetime on a trait object that is spelled explicitly, e.g. `+ 'a` or `+ '_`.
104    ExplicitObjectLifetime,
105    /// A trait object's lifetime when it is elided, e.g. `dyn Any`.
106    ObjectLifetimeDefault(Span),
107    /// Generic lifetime parameter
108    Param(&'a ty::GenericParamDef),
109    RegionPredicate,
110    Reference,
111    OutlivesBound,
112}
113
114#[derive(#[automatically_derived]
impl ::core::marker::Copy for InherentAssocCandidate { }Copy, #[automatically_derived]
impl ::core::clone::Clone for InherentAssocCandidate {
    #[inline]
    fn clone(&self) -> InherentAssocCandidate {
        let _: ::core::clone::AssertParamIsClone<DefId>;
        *self
    }
}Clone, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for InherentAssocCandidate {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        InherentAssocCandidate {
                            impl_: __binding_0,
                            assoc_item: __binding_1,
                            scope: __binding_2 } => {
                            InherentAssocCandidate {
                                impl_: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                assoc_item: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                scope: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    InherentAssocCandidate {
                        impl_: __binding_0,
                        assoc_item: __binding_1,
                        scope: __binding_2 } => {
                        InherentAssocCandidate {
                            impl_: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            assoc_item: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            scope: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for InherentAssocCandidate {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    InherentAssocCandidate {
                        impl_: ref __binding_0,
                        assoc_item: ref __binding_1,
                        scope: ref __binding_2 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable, #[automatically_derived]
impl ::core::fmt::Debug for InherentAssocCandidate {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "InherentAssocCandidate", "impl_", &self.impl_, "assoc_item",
            &self.assoc_item, "scope", &&self.scope)
    }
}Debug)]
115pub struct InherentAssocCandidate {
116    pub impl_: DefId,
117    pub assoc_item: DefId,
118    pub scope: DefId,
119}
120
121/// A context which can lower type-system entities from the [HIR][hir] to
122/// the [`rustc_middle::ty`] representation.
123///
124/// This trait used to be called `AstConv`.
125pub trait HirTyLowerer<'tcx> {
126    fn tcx(&self) -> TyCtxt<'tcx>;
127
128    fn dcx(&self) -> DiagCtxtHandle<'_>;
129
130    /// Returns the [`LocalDefId`] of the overarching item whose constituents get lowered.
131    fn item_def_id(&self) -> LocalDefId;
132
133    /// Returns the region to use when a lifetime is omitted (and not elided).
134    fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx>;
135
136    /// Returns the type to use when a type is omitted.
137    fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
138
139    /// Returns the const to use when a const is omitted.
140    fn ct_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx>;
141
142    fn register_trait_ascription_bounds(
143        &self,
144        bounds: Vec<(ty::Clause<'tcx>, Span)>,
145        hir_id: HirId,
146        span: Span,
147    );
148
149    /// Probe bounds in scope where the bounded type coincides with the given type parameter.
150    ///
151    /// Rephrased, this returns bounds of the form `T: Trait`, where `T` is a type parameter
152    /// with the given `def_id`. This is a subset of the full set of bounds.
153    ///
154    /// This method may use the given `assoc_name` to disregard bounds whose trait reference
155    /// doesn't define an associated item with the provided name.
156    ///
157    /// This is used for one specific purpose: Resolving “short-hand” associated type references
158    /// like `T::Item` where `T` is a type parameter. In principle, we would do that by first
159    /// getting the full set of predicates in scope and then filtering down to find those that
160    /// apply to `T`, but this can lead to cycle errors. The problem is that we have to do this
161    /// resolution *in order to create the predicates in the first place*.
162    /// Hence, we have this “special pass”.
163    fn probe_ty_param_bounds(
164        &self,
165        span: Span,
166        def_id: LocalDefId,
167        assoc_ident: Ident,
168    ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]>;
169
170    fn select_inherent_assoc_candidates(
171        &self,
172        span: Span,
173        self_ty: Ty<'tcx>,
174        candidates: Vec<InherentAssocCandidate>,
175    ) -> (Vec<InherentAssocCandidate>, Vec<FulfillmentError<'tcx>>);
176
177    /// Lower a path to an associated item (of a trait) to a projection.
178    ///
179    /// This method has to be defined by the concrete lowering context because
180    /// dealing with higher-ranked trait references depends on its capabilities:
181    ///
182    /// If the context can make use of type inference, it can simply instantiate
183    /// any late-bound vars bound by the trait reference with inference variables.
184    /// If it doesn't support type inference, there is nothing reasonable it can
185    /// do except reject the associated type.
186    ///
187    /// The canonical example of this is associated type `T::P` where `T` is a type
188    /// param constrained by `T: for<'a> Trait<'a>` and where `Trait` defines `P`.
189    fn lower_assoc_item_path(
190        &self,
191        span: Span,
192        item_def_id: DefId,
193        item_segment: &hir::PathSegment<'tcx>,
194        poly_trait_ref: ty::PolyTraitRef<'tcx>,
195    ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed>;
196
197    fn lower_fn_sig(
198        &self,
199        decl: &hir::FnDecl<'tcx>,
200        generics: Option<&hir::Generics<'_>>,
201        hir_id: HirId,
202        hir_ty: Option<&hir::Ty<'_>>,
203    ) -> (Vec<Ty<'tcx>>, Ty<'tcx>);
204
205    /// Returns `AdtDef` if `ty` is an ADT.
206    ///
207    /// Note that `ty` might be a alias type that needs normalization.
208    /// This used to get the enum variants in scope of the type.
209    /// For example, `Self::A` could refer to an associated type
210    /// or to an enum variant depending on the result of this function.
211    fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>>;
212
213    /// Record the lowered type of a HIR node in this context.
214    fn record_ty(&self, hir_id: HirId, ty: Ty<'tcx>, span: Span);
215
216    /// The inference context of the lowering context if applicable.
217    fn infcx(&self) -> Option<&InferCtxt<'tcx>>;
218
219    /// Convenience method for coercing the lowering context into a trait object type.
220    ///
221    /// Most lowering routines are defined on the trait object type directly
222    /// necessitating a coercion step from the concrete lowering context.
223    fn lowerer(&self) -> &dyn HirTyLowerer<'tcx>
224    where
225        Self: Sized,
226    {
227        self
228    }
229
230    /// Performs minimalistic dyn compat checks outside of bodies, but full within bodies.
231    /// Outside of bodies we could end up in cycles, so we delay most checks to later phases.
232    fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation>;
233}
234
235/// The "qualified self" of an associated item path.
236///
237/// For diagnostic purposes only.
238enum AssocItemQSelf {
239    Trait(DefId),
240    TyParam(LocalDefId, Span),
241    SelfTyAlias,
242}
243
244impl AssocItemQSelf {
245    fn to_string(&self, tcx: TyCtxt<'_>) -> String {
246        match *self {
247            Self::Trait(def_id) => tcx.def_path_str(def_id),
248            Self::TyParam(def_id, _) => tcx.hir_ty_param_name(def_id).to_string(),
249            Self::SelfTyAlias => kw::SelfUpper.to_string(),
250        }
251    }
252}
253
254#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LowerTypeRelativePathMode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LowerTypeRelativePathMode::Type(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Type",
                    &__self_0),
            LowerTypeRelativePathMode::Const =>
                ::core::fmt::Formatter::write_str(f, "Const"),
        }
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for LowerTypeRelativePathMode {
    #[inline]
    fn clone(&self) -> LowerTypeRelativePathMode {
        let _: ::core::clone::AssertParamIsClone<PermitVariants>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for LowerTypeRelativePathMode { }Copy)]
255enum LowerTypeRelativePathMode {
256    Type(PermitVariants),
257    Const,
258}
259
260impl LowerTypeRelativePathMode {
261    fn assoc_tag(self) -> ty::AssocTag {
262        match self {
263            Self::Type(_) => ty::AssocTag::Type,
264            Self::Const => ty::AssocTag::Const,
265        }
266    }
267
268    fn def_kind(self) -> DefKind {
269        match self {
270            Self::Type(_) => DefKind::AssocTy,
271            Self::Const => DefKind::AssocConst,
272        }
273    }
274
275    fn permit_variants(self) -> PermitVariants {
276        match self {
277            Self::Type(permit_variants) => permit_variants,
278            // FIXME(mgca): Support paths like `Option::<T>::None` or `Option::<T>::Some` which
279            // resolve to const ctors/fn items respectively.
280            Self::Const => PermitVariants::No,
281        }
282    }
283}
284
285/// Whether to permit a path to resolve to an enum variant.
286#[derive(#[automatically_derived]
impl ::core::fmt::Debug for PermitVariants {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                PermitVariants::Yes => "Yes",
                PermitVariants::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for PermitVariants {
    #[inline]
    fn clone(&self) -> PermitVariants { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for PermitVariants { }Copy)]
287pub enum PermitVariants {
288    Yes,
289    No,
290}
291
292#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TypeRelativePath<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            TypeRelativePath::AssocItem(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "AssocItem", __self_0, &__self_1),
            TypeRelativePath::Variant { adt: __self_0, variant_did: __self_1 }
                =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Variant", "adt", __self_0, "variant_did", &__self_1),
            TypeRelativePath::Ctor { ctor_def_id: __self_0, args: __self_1 }
                =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f, "Ctor",
                    "ctor_def_id", __self_0, "args", &__self_1),
        }
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for TypeRelativePath<'tcx> {
    #[inline]
    fn clone(&self) -> TypeRelativePath<'tcx> {
        let _: ::core::clone::AssertParamIsClone<DefId>;
        let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for TypeRelativePath<'tcx> { }Copy)]
293enum TypeRelativePath<'tcx> {
294    AssocItem(DefId, GenericArgsRef<'tcx>),
295    Variant { adt: Ty<'tcx>, variant_did: DefId },
296    Ctor { ctor_def_id: DefId, args: GenericArgsRef<'tcx> },
297}
298
299/// New-typed boolean indicating whether explicit late-bound lifetimes
300/// are present in a set of generic arguments.
301///
302/// For example if we have some method `fn f<'a>(&'a self)` implemented
303/// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
304/// is late-bound so should not be provided explicitly. Thus, if `f` is
305/// instantiated with some generic arguments providing `'a` explicitly,
306/// we taint those arguments with `ExplicitLateBound::Yes` so that we
307/// can provide an appropriate diagnostic later.
308#[derive(#[automatically_derived]
impl ::core::marker::Copy for ExplicitLateBound { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ExplicitLateBound {
    #[inline]
    fn clone(&self) -> ExplicitLateBound { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ExplicitLateBound {
    #[inline]
    fn eq(&self, other: &ExplicitLateBound) -> 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::fmt::Debug for ExplicitLateBound {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ExplicitLateBound::Yes => "Yes",
                ExplicitLateBound::No => "No",
            })
    }
}Debug)]
309pub enum ExplicitLateBound {
310    Yes,
311    No,
312}
313
314#[derive(#[automatically_derived]
impl ::core::marker::Copy for IsMethodCall { }Copy, #[automatically_derived]
impl ::core::clone::Clone for IsMethodCall {
    #[inline]
    fn clone(&self) -> IsMethodCall { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for IsMethodCall {
    #[inline]
    fn eq(&self, other: &IsMethodCall) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
315pub enum IsMethodCall {
316    Yes,
317    No,
318}
319
320/// Denotes the "position" of a generic argument, indicating if it is a generic type,
321/// generic function or generic method call.
322#[derive(#[automatically_derived]
impl ::core::marker::Copy for GenericArgPosition { }Copy, #[automatically_derived]
impl ::core::clone::Clone for GenericArgPosition {
    #[inline]
    fn clone(&self) -> GenericArgPosition { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for GenericArgPosition {
    #[inline]
    fn eq(&self, other: &GenericArgPosition) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
323pub(crate) enum GenericArgPosition {
324    Type,
325    Value, // e.g., functions
326    MethodCall,
327}
328
329/// Whether to allow duplicate associated iten constraints in a trait ref, e.g.
330/// `Trait<Assoc = Ty, Assoc = Ty>`. This is forbidden in `dyn Trait<...>`
331/// but allowed everywhere else.
332#[derive(#[automatically_derived]
impl ::core::clone::Clone for OverlappingAsssocItemConstraints {
    #[inline]
    fn clone(&self) -> OverlappingAsssocItemConstraints { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for OverlappingAsssocItemConstraints { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for OverlappingAsssocItemConstraints {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                OverlappingAsssocItemConstraints::Allowed => "Allowed",
                OverlappingAsssocItemConstraints::Forbidden => "Forbidden",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for OverlappingAsssocItemConstraints {
    #[inline]
    fn eq(&self, other: &OverlappingAsssocItemConstraints) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
333pub(crate) enum OverlappingAsssocItemConstraints {
334    Allowed,
335    Forbidden,
336}
337
338/// A marker denoting that the generic arguments that were
339/// provided did not match the respective generic parameters.
340#[derive(#[automatically_derived]
impl ::core::clone::Clone for GenericArgCountMismatch {
    #[inline]
    fn clone(&self) -> GenericArgCountMismatch {
        GenericArgCountMismatch {
            reported: ::core::clone::Clone::clone(&self.reported),
            invalid_args: ::core::clone::Clone::clone(&self.invalid_args),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for GenericArgCountMismatch {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "GenericArgCountMismatch", "reported", &self.reported,
            "invalid_args", &&self.invalid_args)
    }
}Debug)]
341pub struct GenericArgCountMismatch {
342    pub reported: ErrorGuaranteed,
343    /// A list of indices of arguments provided that were not valid.
344    pub invalid_args: Vec<usize>,
345}
346
347/// Decorates the result of a generic argument count mismatch
348/// check with whether explicit late bounds were provided.
349#[derive(#[automatically_derived]
impl ::core::clone::Clone for GenericArgCountResult {
    #[inline]
    fn clone(&self) -> GenericArgCountResult {
        GenericArgCountResult {
            explicit_late_bound: ::core::clone::Clone::clone(&self.explicit_late_bound),
            correct: ::core::clone::Clone::clone(&self.correct),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for GenericArgCountResult {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "GenericArgCountResult", "explicit_late_bound",
            &self.explicit_late_bound, "correct", &&self.correct)
    }
}Debug)]
350pub struct GenericArgCountResult {
351    pub explicit_late_bound: ExplicitLateBound,
352    pub correct: Result<(), GenericArgCountMismatch>,
353}
354
355/// A context which can lower HIR's [`GenericArg`] to `rustc_middle`'s [`ty::GenericArg`].
356///
357/// Its only consumer is [`generics::lower_generic_args`].
358/// Read its documentation to learn more.
359pub trait GenericArgsLowerer<'a, 'tcx> {
360    fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool);
361
362    fn provided_kind(
363        &mut self,
364        preceding_args: &[ty::GenericArg<'tcx>],
365        param: &ty::GenericParamDef,
366        arg: &GenericArg<'tcx>,
367    ) -> ty::GenericArg<'tcx>;
368
369    fn inferred_kind(
370        &mut self,
371        preceding_args: &[ty::GenericArg<'tcx>],
372        param: &ty::GenericParamDef,
373        infer_args: bool,
374    ) -> ty::GenericArg<'tcx>;
375}
376
377struct ForbidMCGParamUsesFolder<'tcx> {
378    tcx: TyCtxt<'tcx>,
379    anon_const_def_id: LocalDefId,
380    span: Span,
381    is_self_alias: bool,
382}
383
384impl<'tcx> ForbidMCGParamUsesFolder<'tcx> {
385    fn error(&self) -> ErrorGuaranteed {
386        let msg = if self.is_self_alias {
387            "generic `Self` types are currently not permitted in anonymous constants"
388        } else {
389            "generic parameters may not be used in const operations"
390        };
391        let mut diag = self.tcx.dcx().struct_span_err(self.span, msg);
392        if self.is_self_alias {
393            let anon_const_hir_id: HirId = HirId::make_owner(self.anon_const_def_id);
394            let parent_impl = self.tcx.hir_parent_owner_iter(anon_const_hir_id).find_map(
395                |(_, node)| match node {
396                    hir::OwnerNode::Item(hir::Item {
397                        kind: hir::ItemKind::Impl(impl_), ..
398                    }) => Some(impl_),
399                    _ => None,
400                },
401            );
402            if let Some(impl_) = parent_impl {
403                diag.span_note(impl_.self_ty.span, "not a concrete type");
404            }
405        }
406        if self.tcx.features().min_generic_const_args()
407            && !self.tcx.features().opaque_generic_const_args()
408        {
409            diag.help("add `#![feature(opaque_generic_const_args)]` to allow generic expressions as the RHS of const items");
410        }
411        diag.emit()
412    }
413}
414
415impl<'tcx> ty::TypeFolder<TyCtxt<'tcx>> for ForbidMCGParamUsesFolder<'tcx> {
416    fn cx(&self) -> TyCtxt<'tcx> {
417        self.tcx
418    }
419
420    fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
421        if #[allow(non_exhaustive_omitted_patterns)] match t.kind() {
    ty::Param(..) => true,
    _ => false,
}matches!(t.kind(), ty::Param(..)) {
422            return Ty::new_error(self.tcx, self.error());
423        }
424        t.super_fold_with(self)
425    }
426
427    fn fold_const(&mut self, c: Const<'tcx>) -> Const<'tcx> {
428        if #[allow(non_exhaustive_omitted_patterns)] match c.kind() {
    ty::ConstKind::Param(..) => true,
    _ => false,
}matches!(c.kind(), ty::ConstKind::Param(..)) {
429            return Const::new_error(self.tcx, self.error());
430        }
431        c.super_fold_with(self)
432    }
433
434    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
435        if #[allow(non_exhaustive_omitted_patterns)] match r.kind() {
    ty::RegionKind::ReEarlyParam(..) | ty::RegionKind::ReLateParam(..) =>
        true,
    _ => false,
}matches!(r.kind(), ty::RegionKind::ReEarlyParam(..) | ty::RegionKind::ReLateParam(..)) {
436            return ty::Region::new_error(self.tcx, self.error());
437        }
438        r
439    }
440}
441
442impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
443    /// See `check_param_uses_if_mcg`.
444    ///
445    /// FIXME(mgca): this is pub only for instantiate_value_path and would be nice to avoid altogether
446    pub fn check_param_res_if_mcg_for_instantiate_value_path(
447        &self,
448        res: Res,
449        span: Span,
450    ) -> Result<(), ErrorGuaranteed> {
451        let tcx = self.tcx();
452        let parent_def_id = self.item_def_id();
453        if let Res::Def(DefKind::ConstParam, _) = res
454            && tcx.def_kind(parent_def_id) == DefKind::AnonConst
455            && let ty::AnonConstKind::MCG = tcx.anon_const_kind(parent_def_id)
456        {
457            let folder = ForbidMCGParamUsesFolder {
458                tcx,
459                anon_const_def_id: parent_def_id,
460                span,
461                is_self_alias: false,
462            };
463            return Err(folder.error());
464        }
465        Ok(())
466    }
467
468    /// Check for uses of generic parameters that are not in scope due to this being
469    /// in a non-generic anon const context.
470    #[must_use = "need to use transformed output"]
471    fn check_param_uses_if_mcg<T>(&self, term: T, span: Span, is_self_alias: bool) -> T
472    where
473        T: ty::TypeFoldable<TyCtxt<'tcx>>,
474    {
475        let tcx = self.tcx();
476        let parent_def_id = self.item_def_id();
477        if tcx.def_kind(parent_def_id) == DefKind::AnonConst
478            && let ty::AnonConstKind::MCG = tcx.anon_const_kind(parent_def_id)
479            // Fast path if contains no params/escaping bound vars.
480            && (term.has_param() || term.has_escaping_bound_vars())
481        {
482            let mut folder = ForbidMCGParamUsesFolder {
483                tcx,
484                anon_const_def_id: parent_def_id,
485                span,
486                is_self_alias,
487            };
488            term.fold_with(&mut folder)
489        } else {
490            term
491        }
492    }
493
494    /// Lower a lifetime from the HIR to our internal notion of a lifetime called a *region*.
495    x;#[instrument(level = "debug", skip(self), ret)]
496    pub fn lower_lifetime(
497        &self,
498        lifetime: &hir::Lifetime,
499        reason: RegionInferReason<'_>,
500    ) -> ty::Region<'tcx> {
501        if let Some(resolved) = self.tcx().named_bound_var(lifetime.hir_id) {
502            let region = self.lower_resolved_lifetime(resolved);
503            self.check_param_uses_if_mcg(region, lifetime.ident.span, false)
504        } else {
505            self.re_infer(lifetime.ident.span, reason)
506        }
507    }
508
509    /// Lower a lifetime from the HIR to our internal notion of a lifetime called a *region*.
510    x;#[instrument(level = "debug", skip(self), ret)]
511    fn lower_resolved_lifetime(&self, resolved: rbv::ResolvedArg) -> ty::Region<'tcx> {
512        let tcx = self.tcx();
513
514        match resolved {
515            rbv::ResolvedArg::StaticLifetime => tcx.lifetimes.re_static,
516
517            rbv::ResolvedArg::LateBound(debruijn, index, def_id) => {
518                let br = ty::BoundRegion {
519                    var: ty::BoundVar::from_u32(index),
520                    kind: ty::BoundRegionKind::Named(def_id.to_def_id()),
521                };
522                ty::Region::new_bound(tcx, debruijn, br)
523            }
524
525            rbv::ResolvedArg::EarlyBound(def_id) => {
526                let name = tcx.hir_ty_param_name(def_id);
527                let item_def_id = tcx.hir_ty_param_owner(def_id);
528                let generics = tcx.generics_of(item_def_id);
529                let index = generics.param_def_id_to_index[&def_id.to_def_id()];
530                ty::Region::new_early_param(tcx, ty::EarlyParamRegion { index, name })
531            }
532
533            rbv::ResolvedArg::Free(scope, id) => {
534                ty::Region::new_late_param(
535                    tcx,
536                    scope.to_def_id(),
537                    ty::LateParamRegionKind::Named(id.to_def_id()),
538                )
539
540                // (*) -- not late-bound, won't change
541            }
542
543            rbv::ResolvedArg::Error(guar) => ty::Region::new_error(tcx, guar),
544        }
545    }
546
547    pub fn lower_generic_args_of_path_segment(
548        &self,
549        span: Span,
550        def_id: DefId,
551        item_segment: &hir::PathSegment<'tcx>,
552    ) -> GenericArgsRef<'tcx> {
553        let (args, _) = self.lower_generic_args_of_path(span, def_id, &[], item_segment, None);
554        if let Some(c) = item_segment.args().constraints.first() {
555            prohibit_assoc_item_constraint(self, c, Some((def_id, item_segment, span)));
556        }
557        args
558    }
559
560    /// Lower the generic arguments provided to some path.
561    ///
562    /// If this is a trait reference, you also need to pass the self type `self_ty`.
563    /// The lowering process may involve applying defaulted type parameters.
564    ///
565    /// Associated item constraints are not handled here! They are either lowered via
566    /// `lower_assoc_item_constraint` or rejected via `prohibit_assoc_item_constraint`.
567    ///
568    /// ### Example
569    ///
570    /// ```ignore (illustrative)
571    ///    T: std::ops::Index<usize, Output = u32>
572    /// // ^1 ^^^^^^^^^^^^^^2 ^^^^3  ^^^^^^^^^^^4
573    /// ```
574    ///
575    /// 1. The `self_ty` here would refer to the type `T`.
576    /// 2. The path in question is the path to the trait `std::ops::Index`,
577    ///    which will have been resolved to a `def_id`
578    /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
579    ///    parameters are returned in the `GenericArgsRef`
580    /// 4. Associated item constraints like `Output = u32` are contained in `generic_args.constraints`.
581    ///
582    /// Note that the type listing given here is *exactly* what the user provided.
583    ///
584    /// For (generic) associated types
585    ///
586    /// ```ignore (illustrative)
587    /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
588    /// ```
589    ///
590    /// We have the parent args are the args for the parent trait:
591    /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
592    /// type itself: `['a]`. The returned `GenericArgsRef` concatenates these two
593    /// lists: `[Vec<u8>, u8, 'a]`.
594    x;#[instrument(level = "debug", skip(self, span), ret)]
595    fn lower_generic_args_of_path(
596        &self,
597        span: Span,
598        def_id: DefId,
599        parent_args: &[ty::GenericArg<'tcx>],
600        segment: &hir::PathSegment<'tcx>,
601        self_ty: Option<Ty<'tcx>>,
602    ) -> (GenericArgsRef<'tcx>, GenericArgCountResult) {
603        // If the type is parameterized by this region, then replace this
604        // region with the current anon region binding (in other words,
605        // whatever & would get replaced with).
606
607        let tcx = self.tcx();
608        let generics = tcx.generics_of(def_id);
609        debug!(?generics);
610
611        if generics.has_self {
612            if generics.parent.is_some() {
613                // The parent is a trait so it should have at least one
614                // generic parameter for the `Self` type.
615                assert!(!parent_args.is_empty())
616            } else {
617                // This item (presumably a trait) needs a self-type.
618                assert!(self_ty.is_some());
619            }
620        } else {
621            assert!(self_ty.is_none());
622        }
623
624        let arg_count = check_generic_arg_count(
625            self,
626            def_id,
627            segment,
628            generics,
629            GenericArgPosition::Type,
630            self_ty.is_some(),
631        );
632
633        // Skip processing if type has no generic parameters.
634        // Traits always have `Self` as a generic parameter, which means they will not return early
635        // here and so associated item constraints will be handled regardless of whether there are
636        // any non-`Self` generic parameters.
637        if generics.is_own_empty() {
638            return (tcx.mk_args(parent_args), arg_count);
639        }
640
641        struct GenericArgsCtxt<'a, 'tcx> {
642            lowerer: &'a dyn HirTyLowerer<'tcx>,
643            def_id: DefId,
644            generic_args: &'a GenericArgs<'tcx>,
645            span: Span,
646            infer_args: bool,
647            incorrect_args: &'a Result<(), GenericArgCountMismatch>,
648        }
649
650        impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for GenericArgsCtxt<'a, 'tcx> {
651            fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool) {
652                if did == self.def_id {
653                    (Some(self.generic_args), self.infer_args)
654                } else {
655                    // The last component of this tuple is unimportant.
656                    (None, false)
657                }
658            }
659
660            fn provided_kind(
661                &mut self,
662                preceding_args: &[ty::GenericArg<'tcx>],
663                param: &ty::GenericParamDef,
664                arg: &GenericArg<'tcx>,
665            ) -> ty::GenericArg<'tcx> {
666                let tcx = self.lowerer.tcx();
667
668                if let Err(incorrect) = self.incorrect_args {
669                    if incorrect.invalid_args.contains(&(param.index as usize)) {
670                        return param.to_error(tcx);
671                    }
672                }
673
674                let handle_ty_args = |has_default, ty: &hir::Ty<'tcx>| {
675                    if has_default {
676                        tcx.check_optional_stability(
677                            param.def_id,
678                            Some(arg.hir_id()),
679                            arg.span(),
680                            None,
681                            AllowUnstable::No,
682                            |_, _| {
683                                // Default generic parameters may not be marked
684                                // with stability attributes, i.e. when the
685                                // default parameter was defined at the same time
686                                // as the rest of the type. As such, we ignore missing
687                                // stability attributes.
688                            },
689                        );
690                    }
691                    self.lowerer.lower_ty(ty).into()
692                };
693
694                match (&param.kind, arg) {
695                    (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
696                        self.lowerer.lower_lifetime(lt, RegionInferReason::Param(param)).into()
697                    }
698                    (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
699                        // We handle the other parts of `Ty` in the match arm below
700                        handle_ty_args(has_default, ty.as_unambig_ty())
701                    }
702                    (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
703                        handle_ty_args(has_default, &inf.to_ty())
704                    }
705                    (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => self
706                        .lowerer
707                        // Ambig portions of `ConstArg` are handled in the match arm below
708                        .lower_const_arg(
709                            ct.as_unambig_ct(),
710                            tcx.type_of(param.def_id).instantiate(tcx, preceding_args),
711                        )
712                        .into(),
713                    (&GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
714                        self.lowerer.ct_infer(Some(param), inf.span).into()
715                    }
716                    (kind, arg) => span_bug!(
717                        self.span,
718                        "mismatched path argument for kind {kind:?}: found arg {arg:?}"
719                    ),
720                }
721            }
722
723            fn inferred_kind(
724                &mut self,
725                preceding_args: &[ty::GenericArg<'tcx>],
726                param: &ty::GenericParamDef,
727                infer_args: bool,
728            ) -> ty::GenericArg<'tcx> {
729                let tcx = self.lowerer.tcx();
730
731                if let Err(incorrect) = self.incorrect_args {
732                    if incorrect.invalid_args.contains(&(param.index as usize)) {
733                        return param.to_error(tcx);
734                    }
735                }
736                match param.kind {
737                    GenericParamDefKind::Lifetime => {
738                        self.lowerer.re_infer(self.span, RegionInferReason::Param(param)).into()
739                    }
740                    GenericParamDefKind::Type { has_default, .. } => {
741                        if !infer_args && has_default {
742                            // No type parameter provided, but a default exists.
743                            if let Some(prev) =
744                                preceding_args.iter().find_map(|arg| match arg.kind() {
745                                    GenericArgKind::Type(ty) => ty.error_reported().err(),
746                                    _ => None,
747                                })
748                            {
749                                // Avoid ICE #86756 when type error recovery goes awry.
750                                return Ty::new_error(tcx, prev).into();
751                            }
752                            tcx.at(self.span)
753                                .type_of(param.def_id)
754                                .instantiate(tcx, preceding_args)
755                                .into()
756                        } else if infer_args {
757                            self.lowerer.ty_infer(Some(param), self.span).into()
758                        } else {
759                            // We've already errored above about the mismatch.
760                            Ty::new_misc_error(tcx).into()
761                        }
762                    }
763                    GenericParamDefKind::Const { has_default, .. } => {
764                        let ty = tcx
765                            .at(self.span)
766                            .type_of(param.def_id)
767                            .instantiate(tcx, preceding_args);
768                        if let Err(guar) = ty.error_reported() {
769                            return ty::Const::new_error(tcx, guar).into();
770                        }
771                        if !infer_args && has_default {
772                            tcx.const_param_default(param.def_id)
773                                .instantiate(tcx, preceding_args)
774                                .into()
775                        } else if infer_args {
776                            self.lowerer.ct_infer(Some(param), self.span).into()
777                        } else {
778                            // We've already errored above about the mismatch.
779                            ty::Const::new_misc_error(tcx).into()
780                        }
781                    }
782                }
783            }
784        }
785
786        let mut args_ctx = GenericArgsCtxt {
787            lowerer: self,
788            def_id,
789            span,
790            generic_args: segment.args(),
791            infer_args: segment.infer_args,
792            incorrect_args: &arg_count.correct,
793        };
794        let args = lower_generic_args(
795            self,
796            def_id,
797            parent_args,
798            self_ty.is_some(),
799            self_ty,
800            &arg_count,
801            &mut args_ctx,
802        );
803
804        (args, arg_count)
805    }
806
807    #[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("lower_generic_args_of_assoc_item",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(807u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["span",
                                                    "item_def_id", "item_segment", "parent_args"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_segment)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_args)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: GenericArgsRef<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (args, _) =
                self.lower_generic_args_of_path(span, item_def_id,
                    parent_args, item_segment, None);
            if let Some(c) = item_segment.args().constraints.first() {
                prohibit_assoc_item_constraint(self, c,
                    Some((item_def_id, item_segment, span)));
            }
            args
        }
    }
}#[instrument(level = "debug", skip(self))]
808    pub fn lower_generic_args_of_assoc_item(
809        &self,
810        span: Span,
811        item_def_id: DefId,
812        item_segment: &hir::PathSegment<'tcx>,
813        parent_args: GenericArgsRef<'tcx>,
814    ) -> GenericArgsRef<'tcx> {
815        let (args, _) =
816            self.lower_generic_args_of_path(span, item_def_id, parent_args, item_segment, None);
817        if let Some(c) = item_segment.args().constraints.first() {
818            prohibit_assoc_item_constraint(self, c, Some((item_def_id, item_segment, span)));
819        }
820        args
821    }
822
823    /// Lower a trait reference as found in an impl header as the implementee.
824    ///
825    /// The self type `self_ty` is the implementer of the trait.
826    pub fn lower_impl_trait_ref(
827        &self,
828        trait_ref: &hir::TraitRef<'tcx>,
829        self_ty: Ty<'tcx>,
830    ) -> ty::TraitRef<'tcx> {
831        let [leading_segments @ .., segment] = trait_ref.path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
832
833        let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
834
835        self.lower_mono_trait_ref(
836            trait_ref.path.span,
837            trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
838            self_ty,
839            segment,
840            true,
841        )
842    }
843
844    /// Lower a polymorphic trait reference given a self type into `bounds`.
845    ///
846    /// *Polymorphic* in the sense that it may bind late-bound vars.
847    ///
848    /// This may generate auxiliary bounds iff the trait reference contains associated item constraints.
849    ///
850    /// ### Example
851    ///
852    /// Given the trait ref `Iterator<Item = u32>` and the self type `Ty`, this will add the
853    ///
854    /// 1. *trait predicate* `<Ty as Iterator>` (known as `Ty: Iterator` in the surface syntax) and the
855    /// 2. *projection predicate* `<Ty as Iterator>::Item = u32`
856    ///
857    /// to `bounds`.
858    ///
859    /// ### A Note on Binders
860    ///
861    /// Against our usual convention, there is an implied binder around the `self_ty` and the
862    /// `trait_ref` here. So they may reference late-bound vars.
863    ///
864    /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
865    /// where `'a` is a bound region at depth 0. Similarly, the `trait_ref` would be `Bar<'a>`.
866    /// The lowered poly-trait-ref will track this binder explicitly, however.
867    #[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("lower_poly_trait_ref",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(867u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["bound_generic_params",
                                                    "constness", "polarity", "trait_ref", "span", "self_ty",
                                                    "predicate_filter", "overlapping_assoc_item_constraints"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bound_generic_params)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constness)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&polarity)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ref)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&predicate_filter)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&overlapping_assoc_item_constraints)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: GenericArgCountResult = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            let _ = bound_generic_params;
            let trait_def_id =
                trait_ref.trait_def_id().unwrap_or_else(||
                        FatalError.raise());
            let transient =
                match polarity {
                    hir::BoundPolarity::Positive => {
                        tcx.is_lang_item(trait_def_id, hir::LangItem::PointeeSized)
                    }
                    hir::BoundPolarity::Negative(_) => false,
                    hir::BoundPolarity::Maybe(_) => {
                        self.require_bound_to_relax_default_trait(trait_ref, span);
                        true
                    }
                };
            let bounds = if transient { &mut Vec::new() } else { bounds };
            let polarity =
                match polarity {
                    hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_)
                        => {
                        ty::PredicatePolarity::Positive
                    }
                    hir::BoundPolarity::Negative(_) =>
                        ty::PredicatePolarity::Negative,
                };
            let [leading_segments @ .., segment] =
                trait_ref.path.segments else {
                    ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
                };
            let _ =
                self.prohibit_generic_args(leading_segments.iter(),
                    GenericsArgsErrExtend::None);
            self.report_internal_fn_trait(span, trait_def_id, segment, false);
            let (generic_args, arg_count) =
                self.lower_generic_args_of_path(trait_ref.path.span,
                    trait_def_id, &[], segment, Some(self_ty));
            let constraints = segment.args().constraints;
            if transient &&
                    (!generic_args[1..].is_empty() || !constraints.is_empty()) {
                self.dcx().span_delayed_bug(span,
                    "transient bound should not have args or constraints");
            }
            let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:947",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(947u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["bound_vars"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&bound_vars)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let poly_trait_ref =
                ty::Binder::bind_with_vars(ty::TraitRef::new_from_args(tcx,
                        trait_def_id, generic_args), bound_vars);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:954",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(954u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["poly_trait_ref"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&poly_trait_ref)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            match predicate_filter {
                PredicateFilter::All | PredicateFilter::SelfOnly |
                    PredicateFilter::SelfTraitThatDefines(..) |
                    PredicateFilter::SelfAndAssociatedTypeBounds => {
                    let bound =
                        poly_trait_ref.map_bound(|trait_ref|
                                {
                                    ty::ClauseKind::Trait(ty::TraitPredicate {
                                            trait_ref,
                                            polarity,
                                        })
                                });
                    let bound = (bound.upcast(tcx), span);
                    if tcx.is_lang_item(trait_def_id,
                            rustc_hir::LangItem::Sized) {
                        bounds.insert(0, bound);
                    } else { bounds.push(bound); }
                }
                PredicateFilter::ConstIfConst |
                    PredicateFilter::SelfConstIfConst => {}
            }
            if let hir::BoundConstness::Always(span) |
                        hir::BoundConstness::Maybe(span) = constness &&
                    !tcx.is_const_trait(trait_def_id) {
                let (def_span, suggestion, suggestion_pre) =
                    match (trait_def_id.as_local(), tcx.sess.is_nightly_build())
                        {
                        (Some(trait_def_id), true) => {
                            let span = tcx.hir_expect_item(trait_def_id).vis_span;
                            let span =
                                tcx.sess.source_map().span_extend_while_whitespace(span);
                            (None, Some(span.shrink_to_hi()),
                                if self.tcx().features().const_trait_impl() {
                                    ""
                                } else {
                                    "enable `#![feature(const_trait_impl)]` in your crate and "
                                })
                        }
                        (None, _) | (_, false) =>
                            (Some(tcx.def_span(trait_def_id)), None, ""),
                    };
                self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait {
                        span,
                        modifier: constness.as_str(),
                        def_span,
                        trait_name: tcx.def_path_str(trait_def_id),
                        suggestion,
                        suggestion_pre,
                    });
            } else {
                match predicate_filter {
                    PredicateFilter::SelfTraitThatDefines(..) => {}
                    PredicateFilter::All | PredicateFilter::SelfOnly |
                        PredicateFilter::SelfAndAssociatedTypeBounds => {
                        match constness {
                            hir::BoundConstness::Always(_) => {
                                if polarity == ty::PredicatePolarity::Positive {
                                    bounds.push((poly_trait_ref.to_host_effect_clause(tcx,
                                                ty::BoundConstness::Const), span));
                                }
                            }
                            hir::BoundConstness::Maybe(_) => {}
                            hir::BoundConstness::Never => {}
                        }
                    }
                    PredicateFilter::ConstIfConst |
                        PredicateFilter::SelfConstIfConst => {
                        match constness {
                            hir::BoundConstness::Maybe(_) => {
                                if polarity == ty::PredicatePolarity::Positive {
                                    bounds.push((poly_trait_ref.to_host_effect_clause(tcx,
                                                ty::BoundConstness::Maybe), span));
                                }
                            }
                            hir::BoundConstness::Always(_) | hir::BoundConstness::Never
                                => {}
                        }
                    }
                }
            }
            let mut dup_constraints =
                (overlapping_assoc_item_constraints ==
                            OverlappingAsssocItemConstraints::Forbidden).then_some(FxIndexMap::default());
            for constraint in constraints {
                if polarity == ty::PredicatePolarity::Negative {
                    self.dcx().span_delayed_bug(constraint.span,
                        "negative trait bounds should not have assoc item constraints");
                    break;
                }
                let _: Result<_, ErrorGuaranteed> =
                    self.lower_assoc_item_constraint(trait_ref.hir_ref_id,
                        poly_trait_ref, constraint, bounds,
                        dup_constraints.as_mut(), constraint.span,
                        predicate_filter);
            }
            arg_count
        }
    }
}#[instrument(level = "debug", skip(self, bounds))]
868    pub(crate) fn lower_poly_trait_ref(
869        &self,
870        &hir::PolyTraitRef {
871            bound_generic_params,
872            modifiers: hir::TraitBoundModifiers { constness, polarity },
873            trait_ref,
874            span,
875        }: &hir::PolyTraitRef<'tcx>,
876        self_ty: Ty<'tcx>,
877        bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
878        predicate_filter: PredicateFilter,
879        overlapping_assoc_item_constraints: OverlappingAsssocItemConstraints,
880    ) -> GenericArgCountResult {
881        let tcx = self.tcx();
882
883        // We use the *resolved* bound vars later instead of the HIR ones since the former
884        // also include the bound vars of the overarching predicate if applicable.
885        let _ = bound_generic_params;
886
887        let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
888
889        // Relaxed bounds `?Trait` and `PointeeSized` bounds aren't represented in the middle::ty IR
890        // as they denote the *absence* of a default bound. However, we can't bail out early here since
891        // we still need to perform several validation steps (see below). Instead, simply "pour" all
892        // resulting bounds "down the drain", i.e., into a new `Vec` that just gets dropped at the end.
893        let transient = match polarity {
894            hir::BoundPolarity::Positive => {
895                // To elaborate on the comment directly above, regarding `PointeeSized` specifically,
896                // we don't "reify" such bounds to avoid trait system limitations -- namely,
897                // non-global where-clauses being preferred over item bounds (where `PointeeSized`
898                // bounds would be proven) -- which can result in errors when a `PointeeSized`
899                // supertrait / bound / predicate is added to some items.
900                tcx.is_lang_item(trait_def_id, hir::LangItem::PointeeSized)
901            }
902            hir::BoundPolarity::Negative(_) => false,
903            hir::BoundPolarity::Maybe(_) => {
904                self.require_bound_to_relax_default_trait(trait_ref, span);
905                true
906            }
907        };
908        let bounds = if transient { &mut Vec::new() } else { bounds };
909
910        let polarity = match polarity {
911            hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_) => {
912                ty::PredicatePolarity::Positive
913            }
914            hir::BoundPolarity::Negative(_) => ty::PredicatePolarity::Negative,
915        };
916
917        let [leading_segments @ .., segment] = trait_ref.path.segments else { bug!() };
918
919        let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
920        self.report_internal_fn_trait(span, trait_def_id, segment, false);
921
922        let (generic_args, arg_count) = self.lower_generic_args_of_path(
923            trait_ref.path.span,
924            trait_def_id,
925            &[],
926            segment,
927            Some(self_ty),
928        );
929
930        let constraints = segment.args().constraints;
931
932        if transient && (!generic_args[1..].is_empty() || !constraints.is_empty()) {
933            // Since the bound won't be present in the middle::ty IR as established above, any
934            // arguments or constraints won't be checked for well-formedness in later passes.
935            //
936            // This is only an issue if the trait ref is otherwise valid which can only happen if
937            // the corresponding default trait has generic parameters or associated items. Such a
938            // trait would be degenerate. We delay a bug to detect and guard us against these.
939            //
940            // E.g: Given `/*default*/ trait Bound<'a: 'static, T, const N: usize> {}`,
941            // `?Bound<Vec<str>, { panic!() }>` won't be wfchecked.
942            self.dcx()
943                .span_delayed_bug(span, "transient bound should not have args or constraints");
944        }
945
946        let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
947        debug!(?bound_vars);
948
949        let poly_trait_ref = ty::Binder::bind_with_vars(
950            ty::TraitRef::new_from_args(tcx, trait_def_id, generic_args),
951            bound_vars,
952        );
953
954        debug!(?poly_trait_ref);
955
956        // We deal with const conditions later.
957        match predicate_filter {
958            PredicateFilter::All
959            | PredicateFilter::SelfOnly
960            | PredicateFilter::SelfTraitThatDefines(..)
961            | PredicateFilter::SelfAndAssociatedTypeBounds => {
962                let bound = poly_trait_ref.map_bound(|trait_ref| {
963                    ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity })
964                });
965                let bound = (bound.upcast(tcx), span);
966                // FIXME(-Znext-solver): We can likely remove this hack once the
967                // new trait solver lands. This fixed an overflow in the old solver.
968                // This may have performance implications, so please check perf when
969                // removing it.
970                // This was added in <https://github.com/rust-lang/rust/pull/123302>.
971                if tcx.is_lang_item(trait_def_id, rustc_hir::LangItem::Sized) {
972                    bounds.insert(0, bound);
973                } else {
974                    bounds.push(bound);
975                }
976            }
977            PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
978        }
979
980        if let hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) = constness
981            && !tcx.is_const_trait(trait_def_id)
982        {
983            let (def_span, suggestion, suggestion_pre) =
984                match (trait_def_id.as_local(), tcx.sess.is_nightly_build()) {
985                    (Some(trait_def_id), true) => {
986                        let span = tcx.hir_expect_item(trait_def_id).vis_span;
987                        let span = tcx.sess.source_map().span_extend_while_whitespace(span);
988
989                        (
990                            None,
991                            Some(span.shrink_to_hi()),
992                            if self.tcx().features().const_trait_impl() {
993                                ""
994                            } else {
995                                "enable `#![feature(const_trait_impl)]` in your crate and "
996                            },
997                        )
998                    }
999                    (None, _) | (_, false) => (Some(tcx.def_span(trait_def_id)), None, ""),
1000                };
1001            self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait {
1002                span,
1003                modifier: constness.as_str(),
1004                def_span,
1005                trait_name: tcx.def_path_str(trait_def_id),
1006                suggestion,
1007                suggestion_pre,
1008            });
1009        } else {
1010            match predicate_filter {
1011                // This is only concerned with trait predicates.
1012                PredicateFilter::SelfTraitThatDefines(..) => {}
1013                PredicateFilter::All
1014                | PredicateFilter::SelfOnly
1015                | PredicateFilter::SelfAndAssociatedTypeBounds => {
1016                    match constness {
1017                        hir::BoundConstness::Always(_) => {
1018                            if polarity == ty::PredicatePolarity::Positive {
1019                                bounds.push((
1020                                    poly_trait_ref
1021                                        .to_host_effect_clause(tcx, ty::BoundConstness::Const),
1022                                    span,
1023                                ));
1024                            }
1025                        }
1026                        hir::BoundConstness::Maybe(_) => {
1027                            // We don't emit a const bound here, since that would mean that we
1028                            // unconditionally need to prove a `HostEffect` predicate, even when
1029                            // the predicates are being instantiated in a non-const context. This
1030                            // is instead handled in the `const_conditions` query.
1031                        }
1032                        hir::BoundConstness::Never => {}
1033                    }
1034                }
1035                // On the flip side, when filtering `ConstIfConst` bounds, we only need to convert
1036                // `[const]` bounds. All other predicates are handled in their respective queries.
1037                //
1038                // Note that like `PredicateFilter::SelfOnly`, we don't need to do any filtering
1039                // here because we only call this on self bounds, and deal with the recursive case
1040                // in `lower_assoc_item_constraint`.
1041                PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {
1042                    match constness {
1043                        hir::BoundConstness::Maybe(_) => {
1044                            if polarity == ty::PredicatePolarity::Positive {
1045                                bounds.push((
1046                                    poly_trait_ref
1047                                        .to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1048                                    span,
1049                                ));
1050                            }
1051                        }
1052                        hir::BoundConstness::Always(_) | hir::BoundConstness::Never => {}
1053                    }
1054                }
1055            }
1056        }
1057
1058        let mut dup_constraints = (overlapping_assoc_item_constraints
1059            == OverlappingAsssocItemConstraints::Forbidden)
1060            .then_some(FxIndexMap::default());
1061
1062        for constraint in constraints {
1063            // Don't register any associated item constraints for negative bounds,
1064            // since we should have emitted an error for them earlier, and they
1065            // would not be well-formed!
1066            if polarity == ty::PredicatePolarity::Negative {
1067                self.dcx().span_delayed_bug(
1068                    constraint.span,
1069                    "negative trait bounds should not have assoc item constraints",
1070                );
1071                break;
1072            }
1073
1074            // Specify type to assert that error was already reported in `Err` case.
1075            let _: Result<_, ErrorGuaranteed> = self.lower_assoc_item_constraint(
1076                trait_ref.hir_ref_id,
1077                poly_trait_ref,
1078                constraint,
1079                bounds,
1080                dup_constraints.as_mut(),
1081                constraint.span,
1082                predicate_filter,
1083            );
1084            // Okay to ignore `Err` because of `ErrorGuaranteed` (see above).
1085        }
1086
1087        arg_count
1088    }
1089
1090    /// Lower a monomorphic trait reference given a self type while prohibiting associated item bindings.
1091    ///
1092    /// *Monomorphic* in the sense that it doesn't bind any late-bound vars.
1093    fn lower_mono_trait_ref(
1094        &self,
1095        span: Span,
1096        trait_def_id: DefId,
1097        self_ty: Ty<'tcx>,
1098        trait_segment: &hir::PathSegment<'tcx>,
1099        is_impl: bool,
1100    ) -> ty::TraitRef<'tcx> {
1101        self.report_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
1102
1103        let (generic_args, _) =
1104            self.lower_generic_args_of_path(span, trait_def_id, &[], trait_segment, Some(self_ty));
1105        if let Some(c) = trait_segment.args().constraints.first() {
1106            prohibit_assoc_item_constraint(self, c, Some((trait_def_id, trait_segment, span)));
1107        }
1108        ty::TraitRef::new_from_args(self.tcx(), trait_def_id, generic_args)
1109    }
1110
1111    fn probe_trait_that_defines_assoc_item(
1112        &self,
1113        trait_def_id: DefId,
1114        assoc_tag: ty::AssocTag,
1115        assoc_ident: Ident,
1116    ) -> bool {
1117        self.tcx()
1118            .associated_items(trait_def_id)
1119            .find_by_ident_and_kind(self.tcx(), assoc_ident, assoc_tag, trait_def_id)
1120            .is_some()
1121    }
1122
1123    fn lower_path_segment(
1124        &self,
1125        span: Span,
1126        did: DefId,
1127        item_segment: &hir::PathSegment<'tcx>,
1128    ) -> Ty<'tcx> {
1129        let tcx = self.tcx();
1130        let args = self.lower_generic_args_of_path_segment(span, did, item_segment);
1131
1132        if let DefKind::TyAlias = tcx.def_kind(did)
1133            && tcx.type_alias_is_lazy(did)
1134        {
1135            // Type aliases defined in crates that have the
1136            // feature `lazy_type_alias` enabled get encoded as a type alias that normalization will
1137            // then actually instantiate the where bounds of.
1138            let alias_ty = ty::AliasTy::new_from_args(tcx, did, args);
1139            Ty::new_alias(tcx, ty::Free, alias_ty)
1140        } else {
1141            tcx.at(span).type_of(did).instantiate(tcx, args)
1142        }
1143    }
1144
1145    /// Search for a trait bound on a type parameter whose trait defines the associated item
1146    /// given by `assoc_ident` and `kind`.
1147    ///
1148    /// This fails if there is no such bound in the list of candidates or if there are multiple
1149    /// candidates in which case it reports ambiguity.
1150    ///
1151    /// `ty_param_def_id` is the `LocalDefId` of the type parameter.
1152    x;#[instrument(level = "debug", skip_all, ret)]
1153    fn probe_single_ty_param_bound_for_assoc_item(
1154        &self,
1155        ty_param_def_id: LocalDefId,
1156        ty_param_span: Span,
1157        assoc_tag: ty::AssocTag,
1158        assoc_ident: Ident,
1159        span: Span,
1160    ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1161        debug!(?ty_param_def_id, ?assoc_ident, ?span);
1162        let tcx = self.tcx();
1163
1164        let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_ident);
1165        debug!("predicates={:#?}", predicates);
1166
1167        self.probe_single_bound_for_assoc_item(
1168            || {
1169                let trait_refs = predicates
1170                    .iter_identity_copied()
1171                    .filter_map(|(p, _)| Some(p.as_trait_clause()?.map_bound(|t| t.trait_ref)));
1172                traits::transitive_bounds_that_define_assoc_item(tcx, trait_refs, assoc_ident)
1173            },
1174            AssocItemQSelf::TyParam(ty_param_def_id, ty_param_span),
1175            assoc_tag,
1176            assoc_ident,
1177            span,
1178            None,
1179        )
1180    }
1181
1182    /// Search for a single trait bound whose trait defines the associated item given by
1183    /// `assoc_ident`.
1184    ///
1185    /// This fails if there is no such bound in the list of candidates or if there are multiple
1186    /// candidates in which case it reports ambiguity.
1187    x;#[instrument(level = "debug", skip(self, all_candidates, qself, constraint), ret)]
1188    fn probe_single_bound_for_assoc_item<I>(
1189        &self,
1190        all_candidates: impl Fn() -> I,
1191        qself: AssocItemQSelf,
1192        assoc_tag: ty::AssocTag,
1193        assoc_ident: Ident,
1194        span: Span,
1195        constraint: Option<&hir::AssocItemConstraint<'tcx>>,
1196    ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1197    where
1198        I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1199    {
1200        let tcx = self.tcx();
1201
1202        let mut matching_candidates = all_candidates().filter(|r| {
1203            self.probe_trait_that_defines_assoc_item(r.def_id(), assoc_tag, assoc_ident)
1204        });
1205
1206        let Some(bound) = matching_candidates.next() else {
1207            return Err(self.report_unresolved_assoc_item(
1208                all_candidates,
1209                qself,
1210                assoc_tag,
1211                assoc_ident,
1212                span,
1213                constraint,
1214            ));
1215        };
1216        debug!(?bound);
1217
1218        if let Some(bound2) = matching_candidates.next() {
1219            debug!(?bound2);
1220
1221            let assoc_kind_str = errors::assoc_tag_str(assoc_tag);
1222            let qself_str = qself.to_string(tcx);
1223            let mut err = self.dcx().create_err(crate::errors::AmbiguousAssocItem {
1224                span,
1225                assoc_kind: assoc_kind_str,
1226                assoc_ident,
1227                qself: &qself_str,
1228            });
1229            // Provide a more specific error code index entry for equality bindings.
1230            err.code(
1231                if let Some(constraint) = constraint
1232                    && let hir::AssocItemConstraintKind::Equality { .. } = constraint.kind
1233                {
1234                    E0222
1235                } else {
1236                    E0221
1237                },
1238            );
1239
1240            // FIXME(#97583): Print associated item bindings properly (i.e., not as equality
1241            // predicates!).
1242            // FIXME: Turn this into a structured, translatable & more actionable suggestion.
1243            let mut where_bounds = vec![];
1244            for bound in [bound, bound2].into_iter().chain(matching_candidates) {
1245                let bound_id = bound.def_id();
1246                let assoc_item = tcx.associated_items(bound_id).find_by_ident_and_kind(
1247                    tcx,
1248                    assoc_ident,
1249                    assoc_tag,
1250                    bound_id,
1251                );
1252                let bound_span = assoc_item.and_then(|item| tcx.hir_span_if_local(item.def_id));
1253
1254                if let Some(bound_span) = bound_span {
1255                    err.span_label(
1256                        bound_span,
1257                        format!("ambiguous `{assoc_ident}` from `{}`", bound.print_trait_sugared(),),
1258                    );
1259                    if let Some(constraint) = constraint {
1260                        match constraint.kind {
1261                            hir::AssocItemConstraintKind::Equality { term } => {
1262                                let term: ty::Term<'_> = match term {
1263                                    hir::Term::Ty(ty) => self.lower_ty(ty).into(),
1264                                    hir::Term::Const(ct) => {
1265                                        let assoc_item =
1266                                            assoc_item.expect("assoc_item should be present");
1267                                        let projection_term = bound.map_bound(|trait_ref| {
1268                                            let item_segment = hir::PathSegment {
1269                                                ident: constraint.ident,
1270                                                hir_id: constraint.hir_id,
1271                                                res: Res::Err,
1272                                                args: Some(constraint.gen_args),
1273                                                infer_args: false,
1274                                            };
1275
1276                                            let alias_args = self.lower_generic_args_of_assoc_item(
1277                                                constraint.ident.span,
1278                                                assoc_item.def_id,
1279                                                &item_segment,
1280                                                trait_ref.args,
1281                                            );
1282                                            ty::AliasTerm::new_from_args(
1283                                                tcx,
1284                                                assoc_item.def_id,
1285                                                alias_args,
1286                                            )
1287                                        });
1288
1289                                        // FIXME(mgca): code duplication with other places we lower
1290                                        // the rhs' of associated const bindings
1291                                        let ty = projection_term.map_bound(|alias| {
1292                                            tcx.type_of(alias.def_id).instantiate(tcx, alias.args)
1293                                        });
1294                                        let ty = bounds::check_assoc_const_binding_type(
1295                                            self,
1296                                            constraint.ident,
1297                                            ty,
1298                                            constraint.hir_id,
1299                                        );
1300
1301                                        self.lower_const_arg(ct, ty).into()
1302                                    }
1303                                };
1304                                if term.references_error() {
1305                                    continue;
1306                                }
1307                                // FIXME(#97583): This isn't syntactically well-formed!
1308                                where_bounds.push(format!(
1309                                    "        T: {trait}::{assoc_ident} = {term}",
1310                                    trait = bound.print_only_trait_path(),
1311                                ));
1312                            }
1313                            // FIXME: Provide a suggestion.
1314                            hir::AssocItemConstraintKind::Bound { bounds: _ } => {}
1315                        }
1316                    } else {
1317                        err.span_suggestion_verbose(
1318                            span.with_hi(assoc_ident.span.lo()),
1319                            "use fully-qualified syntax to disambiguate",
1320                            format!("<{qself_str} as {}>::", bound.print_only_trait_path()),
1321                            Applicability::MaybeIncorrect,
1322                        );
1323                    }
1324                } else {
1325                    let trait_ =
1326                        tcx.short_string(bound.print_only_trait_path(), err.long_ty_path());
1327                    err.note(format!(
1328                        "associated {assoc_kind_str} `{assoc_ident}` could derive from `{trait_}`",
1329                    ));
1330                }
1331            }
1332            if !where_bounds.is_empty() {
1333                err.help(format!(
1334                    "consider introducing a new type parameter `T` and adding `where` constraints:\
1335                     \n    where\n        T: {qself_str},\n{}",
1336                    where_bounds.join(",\n"),
1337                ));
1338                let reported = err.emit();
1339                return Err(reported);
1340            }
1341            err.emit();
1342        }
1343
1344        Ok(bound)
1345    }
1346
1347    /// Lower a [type-relative](hir::QPath::TypeRelative) path in type position to a type.
1348    ///
1349    /// If the path refers to an enum variant and `permit_variants` holds,
1350    /// the returned type is simply the provided self type `qself_ty`.
1351    ///
1352    /// A path like `A::B::C::D` is understood as `<A::B::C>::D`. I.e.,
1353    /// `qself_ty` / `qself` is `A::B::C` and `assoc_segment` is `D`.
1354    /// We return the lowered type and the `DefId` for the whole path.
1355    ///
1356    /// We only support associated type paths whose self type is a type parameter or a `Self`
1357    /// type alias (in a trait impl) like `T::Ty` (where `T` is a ty param) or `Self::Ty`.
1358    /// We **don't** support paths whose self type is an arbitrary type like `Struct::Ty` where
1359    /// struct `Struct` impls an in-scope trait that defines an associated type called `Ty`.
1360    /// For the latter case, we report ambiguity.
1361    /// While desirable to support, the implementation would be non-trivial. Tracked in [#22519].
1362    ///
1363    /// At the time of writing, *inherent associated types* are also resolved here. This however
1364    /// is [problematic][iat]. A proper implementation would be as non-trivial as the one
1365    /// described in the previous paragraph and their modeling of projections would likely be
1366    /// very similar in nature.
1367    ///
1368    /// [#22519]: https://github.com/rust-lang/rust/issues/22519
1369    /// [iat]: https://github.com/rust-lang/rust/issues/8995#issuecomment-1569208403
1370    //
1371    // NOTE: When this function starts resolving `Trait::AssocTy` successfully
1372    // it should also start reporting the `BARE_TRAIT_OBJECTS` lint.
1373    x;#[instrument(level = "debug", skip_all, ret)]
1374    pub fn lower_type_relative_ty_path(
1375        &self,
1376        self_ty: Ty<'tcx>,
1377        hir_self_ty: &'tcx hir::Ty<'tcx>,
1378        segment: &'tcx hir::PathSegment<'tcx>,
1379        qpath_hir_id: HirId,
1380        span: Span,
1381        permit_variants: PermitVariants,
1382    ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1383        let tcx = self.tcx();
1384        match self.lower_type_relative_path(
1385            self_ty,
1386            hir_self_ty,
1387            segment,
1388            qpath_hir_id,
1389            span,
1390            LowerTypeRelativePathMode::Type(permit_variants),
1391        )? {
1392            TypeRelativePath::AssocItem(def_id, args) => {
1393                let alias_ty = ty::AliasTy::new_from_args(tcx, def_id, args);
1394                let ty = Ty::new_alias(tcx, alias_ty.kind(tcx), alias_ty);
1395                let ty = self.check_param_uses_if_mcg(ty, span, false);
1396                Ok((ty, tcx.def_kind(def_id), def_id))
1397            }
1398            TypeRelativePath::Variant { adt, variant_did } => {
1399                let adt = self.check_param_uses_if_mcg(adt, span, false);
1400                Ok((adt, DefKind::Variant, variant_did))
1401            }
1402            TypeRelativePath::Ctor { .. } => {
1403                let e = tcx.dcx().span_err(span, "expected type, found tuple constructor");
1404                Err(e)
1405            }
1406        }
1407    }
1408
1409    /// Lower a [type-relative][hir::QPath::TypeRelative] path to a (type-level) constant.
1410    x;#[instrument(level = "debug", skip_all, ret)]
1411    fn lower_type_relative_const_path(
1412        &self,
1413        self_ty: Ty<'tcx>,
1414        hir_self_ty: &'tcx hir::Ty<'tcx>,
1415        segment: &'tcx hir::PathSegment<'tcx>,
1416        qpath_hir_id: HirId,
1417        span: Span,
1418    ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1419        let tcx = self.tcx();
1420        match self.lower_type_relative_path(
1421            self_ty,
1422            hir_self_ty,
1423            segment,
1424            qpath_hir_id,
1425            span,
1426            LowerTypeRelativePathMode::Const,
1427        )? {
1428            TypeRelativePath::AssocItem(def_id, args) => {
1429                self.require_type_const_attribute(def_id, span)?;
1430                let ct = Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(def_id, args));
1431                let ct = self.check_param_uses_if_mcg(ct, span, false);
1432                Ok(ct)
1433            }
1434            TypeRelativePath::Ctor { ctor_def_id, args } => match tcx.def_kind(ctor_def_id) {
1435                DefKind::Ctor(_, CtorKind::Fn) => {
1436                    Ok(ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, ctor_def_id, args)))
1437                }
1438                DefKind::Ctor(ctor_of, CtorKind::Const) => {
1439                    Ok(self.construct_const_ctor_value(ctor_def_id, ctor_of, args))
1440                }
1441                _ => unreachable!(),
1442            },
1443            // FIXME(mgca): implement support for this once ready to support all adt ctor expressions,
1444            // not just const ctors
1445            TypeRelativePath::Variant { .. } => {
1446                span_bug!(span, "unexpected variant res for type associated const path")
1447            }
1448        }
1449    }
1450
1451    /// Lower a [type-relative][hir::QPath::TypeRelative] (and type-level) path.
1452    x;#[instrument(level = "debug", skip_all, ret)]
1453    fn lower_type_relative_path(
1454        &self,
1455        self_ty: Ty<'tcx>,
1456        hir_self_ty: &'tcx hir::Ty<'tcx>,
1457        segment: &'tcx hir::PathSegment<'tcx>,
1458        qpath_hir_id: HirId,
1459        span: Span,
1460        mode: LowerTypeRelativePathMode,
1461    ) -> Result<TypeRelativePath<'tcx>, ErrorGuaranteed> {
1462        debug!(%self_ty, ?segment.ident);
1463        let tcx = self.tcx();
1464
1465        // Check if we have an enum variant or an inherent associated type.
1466        let mut variant_def_id = None;
1467        if let Some(adt_def) = self.probe_adt(span, self_ty) {
1468            if adt_def.is_enum() {
1469                let variant_def = adt_def
1470                    .variants()
1471                    .iter()
1472                    .find(|vd| tcx.hygienic_eq(segment.ident, vd.ident(tcx), adt_def.did()));
1473                if let Some(variant_def) = variant_def {
1474                    // FIXME(mgca): do we want constructor resolutions to take priority over
1475                    // other possible resolutions?
1476                    if matches!(mode, LowerTypeRelativePathMode::Const)
1477                        && let Some((_, ctor_def_id)) = variant_def.ctor
1478                    {
1479                        tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1480                        let _ = self.prohibit_generic_args(
1481                            slice::from_ref(segment).iter(),
1482                            GenericsArgsErrExtend::EnumVariant {
1483                                qself: hir_self_ty,
1484                                assoc_segment: segment,
1485                                adt_def,
1486                            },
1487                        );
1488                        let ty::Adt(_, enum_args) = self_ty.kind() else { unreachable!() };
1489                        return Ok(TypeRelativePath::Ctor { ctor_def_id, args: enum_args });
1490                    }
1491                    if let PermitVariants::Yes = mode.permit_variants() {
1492                        tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1493                        let _ = self.prohibit_generic_args(
1494                            slice::from_ref(segment).iter(),
1495                            GenericsArgsErrExtend::EnumVariant {
1496                                qself: hir_self_ty,
1497                                assoc_segment: segment,
1498                                adt_def,
1499                            },
1500                        );
1501                        return Ok(TypeRelativePath::Variant {
1502                            adt: self_ty,
1503                            variant_did: variant_def.def_id,
1504                        });
1505                    } else {
1506                        variant_def_id = Some(variant_def.def_id);
1507                    }
1508                }
1509            }
1510
1511            // FIXME(inherent_associated_types, #106719): Support self types other than ADTs.
1512            if let Some((did, args)) = self.probe_inherent_assoc_item(
1513                segment,
1514                adt_def.did(),
1515                self_ty,
1516                qpath_hir_id,
1517                span,
1518                mode.assoc_tag(),
1519            )? {
1520                return Ok(TypeRelativePath::AssocItem(did, args));
1521            }
1522        }
1523
1524        let (item_def_id, bound) = self.resolve_type_relative_path(
1525            self_ty,
1526            hir_self_ty,
1527            mode.assoc_tag(),
1528            segment,
1529            qpath_hir_id,
1530            span,
1531            variant_def_id,
1532        )?;
1533
1534        let (item_def_id, args) = self.lower_assoc_item_path(span, item_def_id, segment, bound)?;
1535
1536        if let Some(variant_def_id) = variant_def_id {
1537            tcx.node_span_lint(AMBIGUOUS_ASSOCIATED_ITEMS, qpath_hir_id, span, |lint| {
1538                lint.primary_message("ambiguous associated item");
1539                let mut could_refer_to = |kind: DefKind, def_id, also| {
1540                    let note_msg = format!(
1541                        "`{}` could{} refer to the {} defined here",
1542                        segment.ident,
1543                        also,
1544                        tcx.def_kind_descr(kind, def_id)
1545                    );
1546                    lint.span_note(tcx.def_span(def_id), note_msg);
1547                };
1548
1549                could_refer_to(DefKind::Variant, variant_def_id, "");
1550                could_refer_to(mode.def_kind(), item_def_id, " also");
1551
1552                lint.span_suggestion(
1553                    span,
1554                    "use fully-qualified syntax",
1555                    format!(
1556                        "<{} as {}>::{}",
1557                        self_ty,
1558                        tcx.item_name(bound.def_id()),
1559                        segment.ident
1560                    ),
1561                    Applicability::MachineApplicable,
1562                );
1563            });
1564        }
1565
1566        Ok(TypeRelativePath::AssocItem(item_def_id, args))
1567    }
1568
1569    /// Resolve a [type-relative](hir::QPath::TypeRelative) (and type-level) path.
1570    fn resolve_type_relative_path(
1571        &self,
1572        self_ty: Ty<'tcx>,
1573        hir_self_ty: &'tcx hir::Ty<'tcx>,
1574        assoc_tag: ty::AssocTag,
1575        segment: &'tcx hir::PathSegment<'tcx>,
1576        qpath_hir_id: HirId,
1577        span: Span,
1578        variant_def_id: Option<DefId>,
1579    ) -> Result<(DefId, ty::PolyTraitRef<'tcx>), ErrorGuaranteed> {
1580        let tcx = self.tcx();
1581
1582        let self_ty_res = match hir_self_ty.kind {
1583            hir::TyKind::Path(hir::QPath::Resolved(_, path)) => path.res,
1584            _ => Res::Err,
1585        };
1586
1587        // Find the type of the assoc item, and the trait where the associated item is declared.
1588        let bound = match (self_ty.kind(), self_ty_res) {
1589            (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
1590                // `Self` in an impl of a trait -- we have a concrete self type and a
1591                // trait reference.
1592                let trait_ref = tcx.impl_trait_ref(impl_def_id);
1593
1594                self.probe_single_bound_for_assoc_item(
1595                    || {
1596                        let trait_ref = ty::Binder::dummy(trait_ref.instantiate_identity());
1597                        traits::supertraits(tcx, trait_ref)
1598                    },
1599                    AssocItemQSelf::SelfTyAlias,
1600                    assoc_tag,
1601                    segment.ident,
1602                    span,
1603                    None,
1604                )?
1605            }
1606            (
1607                &ty::Param(_),
1608                Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
1609            ) => self.probe_single_ty_param_bound_for_assoc_item(
1610                param_did.expect_local(),
1611                hir_self_ty.span,
1612                assoc_tag,
1613                segment.ident,
1614                span,
1615            )?,
1616            _ => {
1617                return Err(self.report_unresolved_type_relative_path(
1618                    self_ty,
1619                    hir_self_ty,
1620                    assoc_tag,
1621                    segment.ident,
1622                    qpath_hir_id,
1623                    span,
1624                    variant_def_id,
1625                ));
1626            }
1627        };
1628
1629        let assoc_item = self
1630            .probe_assoc_item(segment.ident, assoc_tag, qpath_hir_id, span, bound.def_id())
1631            .expect("failed to find associated item");
1632
1633        Ok((assoc_item.def_id, bound))
1634    }
1635
1636    /// Search for inherent associated items for use at the type level.
1637    fn probe_inherent_assoc_item(
1638        &self,
1639        segment: &hir::PathSegment<'tcx>,
1640        adt_did: DefId,
1641        self_ty: Ty<'tcx>,
1642        block: HirId,
1643        span: Span,
1644        assoc_tag: ty::AssocTag,
1645    ) -> Result<Option<(DefId, GenericArgsRef<'tcx>)>, ErrorGuaranteed> {
1646        let tcx = self.tcx();
1647
1648        if !tcx.features().inherent_associated_types() {
1649            match assoc_tag {
1650                // Don't attempt to look up inherent associated types when the feature is not
1651                // enabled. Theoretically it'd be fine to do so since we feature-gate their
1652                // definition site. However, the current implementation of inherent associated
1653                // items is somewhat brittle, so let's not run it by default.
1654                ty::AssocTag::Type => return Ok(None),
1655                ty::AssocTag::Const => {
1656                    // We also gate the mgca codepath for type-level uses of inherent consts
1657                    // with the inherent_associated_types feature gate since it relies on the
1658                    // same machinery and has similar rough edges.
1659                    return Err(feature_err(
1660                        &tcx.sess,
1661                        sym::inherent_associated_types,
1662                        span,
1663                        "inherent associated types are unstable",
1664                    )
1665                    .emit());
1666                }
1667                ty::AssocTag::Fn => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1668            }
1669        }
1670
1671        let name = segment.ident;
1672        let candidates: Vec<_> = tcx
1673            .inherent_impls(adt_did)
1674            .iter()
1675            .filter_map(|&impl_| {
1676                let (item, scope) =
1677                    self.probe_assoc_item_unchecked(name, assoc_tag, block, impl_)?;
1678                Some(InherentAssocCandidate { impl_, assoc_item: item.def_id, scope })
1679            })
1680            .collect();
1681
1682        // At the moment, we actually bail out with a hard error if the selection of an inherent
1683        // associated item fails (see below). This means we never consider trait associated items
1684        // as potential fallback candidates (#142006). To temporarily mask that issue, let's not
1685        // select at all if there are no early inherent candidates.
1686        if candidates.is_empty() {
1687            return Ok(None);
1688        }
1689
1690        let (applicable_candidates, fulfillment_errors) =
1691            self.select_inherent_assoc_candidates(span, self_ty, candidates.clone());
1692
1693        // FIXME(#142006): Don't eagerly error here, there might be applicable trait candidates.
1694        let InherentAssocCandidate { impl_, assoc_item, scope: def_scope } =
1695            match &applicable_candidates[..] {
1696                &[] => Err(self.report_unresolved_inherent_assoc_item(
1697                    name,
1698                    self_ty,
1699                    candidates,
1700                    fulfillment_errors,
1701                    span,
1702                    assoc_tag,
1703                )),
1704
1705                &[applicable_candidate] => Ok(applicable_candidate),
1706
1707                &[_, ..] => Err(self.report_ambiguous_inherent_assoc_item(
1708                    name,
1709                    candidates.into_iter().map(|cand| cand.assoc_item).collect(),
1710                    span,
1711                )),
1712            }?;
1713
1714        // FIXME(#142006): Don't eagerly validate here, there might be trait candidates that are
1715        // accessible (visible and stable) contrary to the inherent candidate.
1716        self.check_assoc_item(assoc_item, name, def_scope, block, span);
1717
1718        // FIXME(fmease): Currently creating throwaway `parent_args` to please
1719        // `lower_generic_args_of_assoc_item`. Modify the latter instead (or sth. similar) to
1720        // not require the parent args logic.
1721        let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
1722        let args = self.lower_generic_args_of_assoc_item(span, assoc_item, segment, parent_args);
1723        let args = tcx.mk_args_from_iter(
1724            std::iter::once(ty::GenericArg::from(self_ty))
1725                .chain(args.into_iter().skip(parent_args.len())),
1726        );
1727
1728        Ok(Some((assoc_item, args)))
1729    }
1730
1731    /// Given name and kind search for the assoc item in the provided scope and check if it's accessible[^1].
1732    ///
1733    /// [^1]: I.e., accessible in the provided scope wrt. visibility and stability.
1734    fn probe_assoc_item(
1735        &self,
1736        ident: Ident,
1737        assoc_tag: ty::AssocTag,
1738        block: HirId,
1739        span: Span,
1740        scope: DefId,
1741    ) -> Option<ty::AssocItem> {
1742        let (item, scope) = self.probe_assoc_item_unchecked(ident, assoc_tag, block, scope)?;
1743        self.check_assoc_item(item.def_id, ident, scope, block, span);
1744        Some(item)
1745    }
1746
1747    /// Given name and kind search for the assoc item in the provided scope
1748    /// *without* checking if it's accessible[^1].
1749    ///
1750    /// [^1]: I.e., accessible in the provided scope wrt. visibility and stability.
1751    fn probe_assoc_item_unchecked(
1752        &self,
1753        ident: Ident,
1754        assoc_tag: ty::AssocTag,
1755        block: HirId,
1756        scope: DefId,
1757    ) -> Option<(ty::AssocItem, /*scope*/ DefId)> {
1758        let tcx = self.tcx();
1759
1760        let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block);
1761        // We have already adjusted the item name above, so compare with `.normalize_to_macros_2_0()`
1762        // instead of calling `filter_by_name_and_kind` which would needlessly normalize the
1763        // `ident` again and again.
1764        let item = tcx
1765            .associated_items(scope)
1766            .filter_by_name_unhygienic(ident.name)
1767            .find(|i| i.tag() == assoc_tag && i.ident(tcx).normalize_to_macros_2_0() == ident)?;
1768
1769        Some((*item, def_scope))
1770    }
1771
1772    /// Check if the given assoc item is accessible in the provided scope wrt. visibility and stability.
1773    fn check_assoc_item(
1774        &self,
1775        item_def_id: DefId,
1776        ident: Ident,
1777        scope: DefId,
1778        block: HirId,
1779        span: Span,
1780    ) {
1781        let tcx = self.tcx();
1782
1783        if !tcx.visibility(item_def_id).is_accessible_from(scope, tcx) {
1784            self.dcx().emit_err(crate::errors::AssocItemIsPrivate {
1785                span,
1786                kind: tcx.def_descr(item_def_id),
1787                name: ident,
1788                defined_here_label: tcx.def_span(item_def_id),
1789            });
1790        }
1791
1792        tcx.check_stability(item_def_id, Some(block), span, None);
1793    }
1794
1795    fn probe_traits_that_match_assoc_ty(
1796        &self,
1797        qself_ty: Ty<'tcx>,
1798        assoc_ident: Ident,
1799    ) -> Vec<String> {
1800        let tcx = self.tcx();
1801
1802        // In contexts that have no inference context, just make a new one.
1803        // We do need a local variable to store it, though.
1804        let infcx_;
1805        let infcx = if let Some(infcx) = self.infcx() {
1806            infcx
1807        } else {
1808            if !!qself_ty.has_infer() {
    ::core::panicking::panic("assertion failed: !qself_ty.has_infer()")
};assert!(!qself_ty.has_infer());
1809            infcx_ = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1810            &infcx_
1811        };
1812
1813        tcx.all_traits_including_private()
1814            .filter(|trait_def_id| {
1815                // Consider only traits with the associated type
1816                tcx.associated_items(*trait_def_id)
1817                        .in_definition_order()
1818                        .any(|i| {
1819                            i.is_type()
1820                                && !i.is_impl_trait_in_trait()
1821                                && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1822                        })
1823                    // Consider only accessible traits
1824                    && tcx.visibility(*trait_def_id)
1825                        .is_accessible_from(self.item_def_id(), tcx)
1826                    && tcx.all_impls(*trait_def_id)
1827                        .any(|impl_def_id| {
1828                            let header = tcx.impl_trait_header(impl_def_id);
1829                            let trait_ref = header.trait_ref.instantiate(
1830                                tcx,
1831                                infcx.fresh_args_for_item(DUMMY_SP, impl_def_id),
1832                            );
1833
1834                            let value = fold_regions(tcx, qself_ty, |_, _| tcx.lifetimes.re_erased);
1835                            // FIXME: Don't bother dealing with non-lifetime binders here...
1836                            if value.has_escaping_bound_vars() {
1837                                return false;
1838                            }
1839                            infcx
1840                                .can_eq(
1841                                    ty::ParamEnv::empty(),
1842                                    trait_ref.self_ty(),
1843                                    value,
1844                                ) && header.polarity != ty::ImplPolarity::Negative
1845                        })
1846            })
1847            .map(|trait_def_id| tcx.def_path_str(trait_def_id))
1848            .collect()
1849    }
1850
1851    /// Lower a [resolved][hir::QPath::Resolved] associated type path to a projection.
1852    #[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("lower_resolved_assoc_ty_path",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1852u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set(&[]) })
                } 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: Ty<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match self.lower_resolved_assoc_item_path(span, opt_self_ty,
                    item_def_id, trait_segment, item_segment,
                    ty::AssocTag::Type) {
                Ok((item_def_id, item_args)) => {
                    Ty::new_projection_from_args(self.tcx(), item_def_id,
                        item_args)
                }
                Err(guar) => Ty::new_error(self.tcx(), guar),
            }
        }
    }
}#[instrument(level = "debug", skip_all)]
1853    fn lower_resolved_assoc_ty_path(
1854        &self,
1855        span: Span,
1856        opt_self_ty: Option<Ty<'tcx>>,
1857        item_def_id: DefId,
1858        trait_segment: Option<&hir::PathSegment<'tcx>>,
1859        item_segment: &hir::PathSegment<'tcx>,
1860    ) -> Ty<'tcx> {
1861        match self.lower_resolved_assoc_item_path(
1862            span,
1863            opt_self_ty,
1864            item_def_id,
1865            trait_segment,
1866            item_segment,
1867            ty::AssocTag::Type,
1868        ) {
1869            Ok((item_def_id, item_args)) => {
1870                Ty::new_projection_from_args(self.tcx(), item_def_id, item_args)
1871            }
1872            Err(guar) => Ty::new_error(self.tcx(), guar),
1873        }
1874    }
1875
1876    /// Lower a [resolved][hir::QPath::Resolved] associated const path to a (type-level) constant.
1877    #[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("lower_resolved_assoc_const_path",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1877u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set(&[]) })
                } 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:
                    Result<Const<'tcx>, ErrorGuaranteed> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (item_def_id, item_args) =
                self.lower_resolved_assoc_item_path(span, opt_self_ty,
                        item_def_id, trait_segment, item_segment,
                        ty::AssocTag::Const)?;
            self.require_type_const_attribute(item_def_id, span)?;
            let uv = ty::UnevaluatedConst::new(item_def_id, item_args);
            Ok(Const::new_unevaluated(self.tcx(), uv))
        }
    }
}#[instrument(level = "debug", skip_all)]
1878    fn lower_resolved_assoc_const_path(
1879        &self,
1880        span: Span,
1881        opt_self_ty: Option<Ty<'tcx>>,
1882        item_def_id: DefId,
1883        trait_segment: Option<&hir::PathSegment<'tcx>>,
1884        item_segment: &hir::PathSegment<'tcx>,
1885    ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1886        let (item_def_id, item_args) = self.lower_resolved_assoc_item_path(
1887            span,
1888            opt_self_ty,
1889            item_def_id,
1890            trait_segment,
1891            item_segment,
1892            ty::AssocTag::Const,
1893        )?;
1894        self.require_type_const_attribute(item_def_id, span)?;
1895        let uv = ty::UnevaluatedConst::new(item_def_id, item_args);
1896        Ok(Const::new_unevaluated(self.tcx(), uv))
1897    }
1898
1899    /// Lower a [resolved][hir::QPath::Resolved] (type-level) associated item path.
1900    #[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("lower_resolved_assoc_item_path",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1900u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set(&[]) })
                } 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:
                    Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            let trait_def_id = tcx.parent(item_def_id);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:1913",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1913u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["trait_def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&trait_def_id)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let Some(self_ty) =
                opt_self_ty else {
                    return Err(self.report_missing_self_ty_for_resolved_path(trait_def_id,
                                span, item_segment, assoc_tag));
                };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:1923",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1923u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["self_ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&self_ty) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            let trait_ref =
                self.lower_mono_trait_ref(span, trait_def_id, self_ty,
                    trait_segment.unwrap(), false);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:1927",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1927u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["trait_ref"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&trait_ref)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let item_args =
                self.lower_generic_args_of_assoc_item(span, item_def_id,
                    item_segment, trait_ref.args);
            Ok((item_def_id, item_args))
        }
    }
}#[instrument(level = "debug", skip_all)]
1901    fn lower_resolved_assoc_item_path(
1902        &self,
1903        span: Span,
1904        opt_self_ty: Option<Ty<'tcx>>,
1905        item_def_id: DefId,
1906        trait_segment: Option<&hir::PathSegment<'tcx>>,
1907        item_segment: &hir::PathSegment<'tcx>,
1908        assoc_tag: ty::AssocTag,
1909    ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> {
1910        let tcx = self.tcx();
1911
1912        let trait_def_id = tcx.parent(item_def_id);
1913        debug!(?trait_def_id);
1914
1915        let Some(self_ty) = opt_self_ty else {
1916            return Err(self.report_missing_self_ty_for_resolved_path(
1917                trait_def_id,
1918                span,
1919                item_segment,
1920                assoc_tag,
1921            ));
1922        };
1923        debug!(?self_ty);
1924
1925        let trait_ref =
1926            self.lower_mono_trait_ref(span, trait_def_id, self_ty, trait_segment.unwrap(), false);
1927        debug!(?trait_ref);
1928
1929        let item_args =
1930            self.lower_generic_args_of_assoc_item(span, item_def_id, item_segment, trait_ref.args);
1931
1932        Ok((item_def_id, item_args))
1933    }
1934
1935    pub fn prohibit_generic_args<'a>(
1936        &self,
1937        segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
1938        err_extend: GenericsArgsErrExtend<'a>,
1939    ) -> Result<(), ErrorGuaranteed> {
1940        let args_visitors = segments.clone().flat_map(|segment| segment.args().args);
1941        let mut result = Ok(());
1942        if let Some(_) = args_visitors.clone().next() {
1943            result = Err(self.report_prohibited_generic_args(
1944                segments.clone(),
1945                args_visitors,
1946                err_extend,
1947            ));
1948        }
1949
1950        for segment in segments {
1951            // Only emit the first error to avoid overloading the user with error messages.
1952            if let Some(c) = segment.args().constraints.first() {
1953                return Err(prohibit_assoc_item_constraint(self, c, None));
1954            }
1955        }
1956
1957        result
1958    }
1959
1960    /// Probe path segments that are semantically allowed to have generic arguments.
1961    ///
1962    /// ### Example
1963    ///
1964    /// ```ignore (illustrative)
1965    ///    Option::None::<()>
1966    /// //         ^^^^ permitted to have generic args
1967    ///
1968    /// // ==> [GenericPathSegment(Option_def_id, 1)]
1969    ///
1970    ///    Option::<()>::None
1971    /// // ^^^^^^        ^^^^ *not* permitted to have generic args
1972    /// // permitted to have generic args
1973    ///
1974    /// // ==> [GenericPathSegment(Option_def_id, 0)]
1975    /// ```
1976    // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
1977    pub fn probe_generic_path_segments(
1978        &self,
1979        segments: &[hir::PathSegment<'_>],
1980        self_ty: Option<Ty<'tcx>>,
1981        kind: DefKind,
1982        def_id: DefId,
1983        span: Span,
1984    ) -> Vec<GenericPathSegment> {
1985        // We need to extract the generic arguments supplied by the user in
1986        // the path `path`. Due to the current setup, this is a bit of a
1987        // tricky process; the problem is that resolve only tells us the
1988        // end-point of the path resolution, and not the intermediate steps.
1989        // Luckily, we can (at least for now) deduce the intermediate steps
1990        // just from the end-point.
1991        //
1992        // There are basically five cases to consider:
1993        //
1994        // 1. Reference to a constructor of a struct:
1995        //
1996        //        struct Foo<T>(...)
1997        //
1998        //    In this case, the generic arguments are declared in the type space.
1999        //
2000        // 2. Reference to a constructor of an enum variant:
2001        //
2002        //        enum E<T> { Foo(...) }
2003        //
2004        //    In this case, the generic arguments are defined in the type space,
2005        //    but may be specified either on the type or the variant.
2006        //
2007        // 3. Reference to a free function or constant:
2008        //
2009        //        fn foo<T>() {}
2010        //
2011        //    In this case, the path will again always have the form
2012        //    `a::b::foo::<T>` where only the final segment should have generic
2013        //    arguments. However, in this case, those arguments are declared on
2014        //    a value, and hence are in the value space.
2015        //
2016        // 4. Reference to an associated function or constant:
2017        //
2018        //        impl<A> SomeStruct<A> {
2019        //            fn foo<B>(...) {}
2020        //        }
2021        //
2022        //    Here we can have a path like `a::b::SomeStruct::<A>::foo::<B>`,
2023        //    in which case generic arguments may appear in two places. The
2024        //    penultimate segment, `SomeStruct::<A>`, contains generic arguments
2025        //    in the type space, and the final segment, `foo::<B>` contains
2026        //    generic arguments in value space.
2027        //
2028        // The first step then is to categorize the segments appropriately.
2029
2030        let tcx = self.tcx();
2031
2032        if !!segments.is_empty() {
    ::core::panicking::panic("assertion failed: !segments.is_empty()")
};assert!(!segments.is_empty());
2033        let last = segments.len() - 1;
2034
2035        let mut generic_segments = ::alloc::vec::Vec::new()vec![];
2036
2037        match kind {
2038            // Case 1. Reference to a struct constructor.
2039            DefKind::Ctor(CtorOf::Struct, ..) => {
2040                // Everything but the final segment should have no
2041                // parameters at all.
2042                let generics = tcx.generics_of(def_id);
2043                // Variant and struct constructors use the
2044                // generics of their parent type definition.
2045                let generics_def_id = generics.parent.unwrap_or(def_id);
2046                generic_segments.push(GenericPathSegment(generics_def_id, last));
2047            }
2048
2049            // Case 2. Reference to a variant constructor.
2050            DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2051                let (generics_def_id, index) = if let Some(self_ty) = self_ty {
2052                    let adt_def = self.probe_adt(span, self_ty).unwrap();
2053                    if true {
    if !adt_def.is_enum() {
        ::core::panicking::panic("assertion failed: adt_def.is_enum()")
    };
};debug_assert!(adt_def.is_enum());
2054                    (adt_def.did(), last)
2055                } else if last >= 1 && segments[last - 1].args.is_some() {
2056                    // Everything but the penultimate segment should have no
2057                    // parameters at all.
2058                    let mut def_id = def_id;
2059
2060                    // `DefKind::Ctor` -> `DefKind::Variant`
2061                    if let DefKind::Ctor(..) = kind {
2062                        def_id = tcx.parent(def_id);
2063                    }
2064
2065                    // `DefKind::Variant` -> `DefKind::Enum`
2066                    let enum_def_id = tcx.parent(def_id);
2067                    (enum_def_id, last - 1)
2068                } else {
2069                    // FIXME: lint here recommending `Enum::<...>::Variant` form
2070                    // instead of `Enum::Variant::<...>` form.
2071
2072                    // Everything but the final segment should have no
2073                    // parameters at all.
2074                    let generics = tcx.generics_of(def_id);
2075                    // Variant and struct constructors use the
2076                    // generics of their parent type definition.
2077                    (generics.parent.unwrap_or(def_id), last)
2078                };
2079                generic_segments.push(GenericPathSegment(generics_def_id, index));
2080            }
2081
2082            // Case 3. Reference to a top-level value.
2083            DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static { .. } => {
2084                generic_segments.push(GenericPathSegment(def_id, last));
2085            }
2086
2087            // Case 4. Reference to a method or associated const.
2088            DefKind::AssocFn | DefKind::AssocConst => {
2089                if segments.len() >= 2 {
2090                    let generics = tcx.generics_of(def_id);
2091                    generic_segments.push(GenericPathSegment(generics.parent.unwrap(), last - 1));
2092                }
2093                generic_segments.push(GenericPathSegment(def_id, last));
2094            }
2095
2096            kind => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected definition kind {0:?} for {1:?}",
        kind, def_id))bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2097        }
2098
2099        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2099",
                        "rustc_hir_analysis::hir_ty_lowering",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2099u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                        ::tracing_core::field::FieldSet::new(&["generic_segments"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&generic_segments)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?generic_segments);
2100
2101        generic_segments
2102    }
2103
2104    /// Lower a [resolved][hir::QPath::Resolved] path to a type.
2105    #[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("lower_resolved_ty_path",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2105u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set(&[]) })
                } 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: Ty<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2113",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2113u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["path.res",
                                                    "opt_self_ty", "path.segments"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&path.res)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&opt_self_ty)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&path.segments)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let tcx = self.tcx();
            let span = path.span;
            match path.res {
                Res::Def(DefKind::OpaqueTy, did) => {
                    match tcx.opaque_ty_origin(did) {
                        hir::OpaqueTyOrigin::TyAlias { .. } => {}
                        ref left_val => {
                            ::core::panicking::assert_matches_failed(left_val,
                                "hir::OpaqueTyOrigin::TyAlias { .. }",
                                ::core::option::Option::None);
                        }
                    };
                    let [leading_segments @ .., segment] =
                        path.segments else {
                            ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
                        };
                    let _ =
                        self.prohibit_generic_args(leading_segments.iter(),
                            GenericsArgsErrExtend::OpaqueTy);
                    let args =
                        self.lower_generic_args_of_path_segment(span, did, segment);
                    Ty::new_opaque(tcx, did, args)
                }
                Res::Def(DefKind::Enum | DefKind::TyAlias | DefKind::Struct |
                    DefKind::Union | DefKind::ForeignTy, did) => {
                    match (&opt_self_ty, &None) {
                        (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 [leading_segments @ .., segment] =
                        path.segments else {
                            ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
                        };
                    let _ =
                        self.prohibit_generic_args(leading_segments.iter(),
                            GenericsArgsErrExtend::None);
                    self.lower_path_segment(span, did, segment)
                }
                Res::Def(kind @ DefKind::Variant, def_id) if
                    let PermitVariants::Yes = permit_variants => {
                    match (&opt_self_ty, &None) {
                        (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 generic_segments =
                        self.probe_generic_path_segments(path.segments, None, kind,
                            def_id, span);
                    let indices: FxHashSet<_> =
                        generic_segments.iter().map(|GenericPathSegment(_, index)|
                                    index).collect();
                    let _ =
                        self.prohibit_generic_args(path.segments.iter().enumerate().filter_map(|(index,
                                        seg)|
                                    {
                                        if !indices.contains(&index) { Some(seg) } else { None }
                                    }), GenericsArgsErrExtend::DefVariant(&path.segments));
                    let &GenericPathSegment(def_id, index) =
                        generic_segments.last().unwrap();
                    self.lower_path_segment(span, def_id, &path.segments[index])
                }
                Res::Def(DefKind::TyParam, def_id) => {
                    match (&opt_self_ty, &None) {
                        (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 _ =
                        self.prohibit_generic_args(path.segments.iter(),
                            GenericsArgsErrExtend::Param(def_id));
                    self.lower_ty_param(hir_id)
                }
                Res::SelfTyParam { .. } => {
                    match (&opt_self_ty, &None) {
                        (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 _ =
                        self.prohibit_generic_args(path.segments.iter(),
                            if let [hir::PathSegment { args: Some(args), ident, .. }] =
                                    &path.segments {
                                GenericsArgsErrExtend::SelfTyParam(ident.span.shrink_to_hi().to(args.span_ext))
                            } else { GenericsArgsErrExtend::None });
                    self.check_param_uses_if_mcg(tcx.types.self_param, span,
                        false)
                }
                Res::SelfTyAlias { alias_to: def_id, .. } => {
                    match (&opt_self_ty, &None) {
                        (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 ty =
                        tcx.at(span).type_of(def_id).instantiate_identity();
                    let _ =
                        self.prohibit_generic_args(path.segments.iter(),
                            GenericsArgsErrExtend::SelfTyAlias { def_id, span });
                    self.check_param_uses_if_mcg(ty, span, true)
                }
                Res::Def(DefKind::AssocTy, def_id) => {
                    let trait_segment =
                        if let [modules @ .., trait_, _item] = path.segments {
                            let _ =
                                self.prohibit_generic_args(modules.iter(),
                                    GenericsArgsErrExtend::None);
                            Some(trait_)
                        } else { None };
                    self.lower_resolved_assoc_ty_path(span, opt_self_ty, def_id,
                        trait_segment, path.segments.last().unwrap())
                }
                Res::PrimTy(prim_ty) => {
                    match (&opt_self_ty, &None) {
                        (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 _ =
                        self.prohibit_generic_args(path.segments.iter(),
                            GenericsArgsErrExtend::PrimTy(prim_ty));
                    match prim_ty {
                        hir::PrimTy::Bool => tcx.types.bool,
                        hir::PrimTy::Char => tcx.types.char,
                        hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
                        hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
                        hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
                        hir::PrimTy::Str => tcx.types.str_,
                    }
                }
                Res::Err => {
                    let e =
                        self.tcx().dcx().span_delayed_bug(path.span,
                            "path with `Res::Err` but no error emitted");
                    Ty::new_error(tcx, e)
                }
                Res::Def(..) => {
                    match (&path.segments.get(0).map(|seg| seg.ident.name),
                            &Some(kw::SelfUpper)) {
                        (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::Some(format_args!("only expected incorrect resolution for `Self`")));
                            }
                        }
                    };
                    Ty::new_error(self.tcx(),
                        self.dcx().span_delayed_bug(span,
                            "incorrect resolution for `Self`"))
                }
                _ =>
                    ::rustc_middle::util::bug::span_bug_fmt(span,
                        format_args!("unexpected resolution: {0:?}", path.res)),
            }
        }
    }
}#[instrument(level = "debug", skip_all)]
2106    pub fn lower_resolved_ty_path(
2107        &self,
2108        opt_self_ty: Option<Ty<'tcx>>,
2109        path: &hir::Path<'tcx>,
2110        hir_id: HirId,
2111        permit_variants: PermitVariants,
2112    ) -> Ty<'tcx> {
2113        debug!(?path.res, ?opt_self_ty, ?path.segments);
2114        let tcx = self.tcx();
2115
2116        let span = path.span;
2117        match path.res {
2118            Res::Def(DefKind::OpaqueTy, did) => {
2119                // Check for desugared `impl Trait`.
2120                assert_matches!(tcx.opaque_ty_origin(did), hir::OpaqueTyOrigin::TyAlias { .. });
2121                let [leading_segments @ .., segment] = path.segments else { bug!() };
2122                let _ = self.prohibit_generic_args(
2123                    leading_segments.iter(),
2124                    GenericsArgsErrExtend::OpaqueTy,
2125                );
2126                let args = self.lower_generic_args_of_path_segment(span, did, segment);
2127                Ty::new_opaque(tcx, did, args)
2128            }
2129            Res::Def(
2130                DefKind::Enum
2131                | DefKind::TyAlias
2132                | DefKind::Struct
2133                | DefKind::Union
2134                | DefKind::ForeignTy,
2135                did,
2136            ) => {
2137                assert_eq!(opt_self_ty, None);
2138                let [leading_segments @ .., segment] = path.segments else { bug!() };
2139                let _ = self
2140                    .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2141                self.lower_path_segment(span, did, segment)
2142            }
2143            Res::Def(kind @ DefKind::Variant, def_id)
2144                if let PermitVariants::Yes = permit_variants =>
2145            {
2146                // Lower "variant type" as if it were a real type.
2147                // The resulting `Ty` is type of the variant's enum for now.
2148                assert_eq!(opt_self_ty, None);
2149
2150                let generic_segments =
2151                    self.probe_generic_path_segments(path.segments, None, kind, def_id, span);
2152                let indices: FxHashSet<_> =
2153                    generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2154                let _ = self.prohibit_generic_args(
2155                    path.segments.iter().enumerate().filter_map(|(index, seg)| {
2156                        if !indices.contains(&index) { Some(seg) } else { None }
2157                    }),
2158                    GenericsArgsErrExtend::DefVariant(&path.segments),
2159                );
2160
2161                let &GenericPathSegment(def_id, index) = generic_segments.last().unwrap();
2162                self.lower_path_segment(span, def_id, &path.segments[index])
2163            }
2164            Res::Def(DefKind::TyParam, def_id) => {
2165                assert_eq!(opt_self_ty, None);
2166                let _ = self.prohibit_generic_args(
2167                    path.segments.iter(),
2168                    GenericsArgsErrExtend::Param(def_id),
2169                );
2170                self.lower_ty_param(hir_id)
2171            }
2172            Res::SelfTyParam { .. } => {
2173                // `Self` in trait or type alias.
2174                assert_eq!(opt_self_ty, None);
2175                let _ = self.prohibit_generic_args(
2176                    path.segments.iter(),
2177                    if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments {
2178                        GenericsArgsErrExtend::SelfTyParam(
2179                            ident.span.shrink_to_hi().to(args.span_ext),
2180                        )
2181                    } else {
2182                        GenericsArgsErrExtend::None
2183                    },
2184                );
2185                self.check_param_uses_if_mcg(tcx.types.self_param, span, false)
2186            }
2187            Res::SelfTyAlias { alias_to: def_id, .. } => {
2188                // `Self` in impl (we know the concrete type).
2189                assert_eq!(opt_self_ty, None);
2190                // Try to evaluate any array length constants.
2191                let ty = tcx.at(span).type_of(def_id).instantiate_identity();
2192                let _ = self.prohibit_generic_args(
2193                    path.segments.iter(),
2194                    GenericsArgsErrExtend::SelfTyAlias { def_id, span },
2195                );
2196                self.check_param_uses_if_mcg(ty, span, true)
2197            }
2198            Res::Def(DefKind::AssocTy, def_id) => {
2199                let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2200                    let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2201                    Some(trait_)
2202                } else {
2203                    None
2204                };
2205                self.lower_resolved_assoc_ty_path(
2206                    span,
2207                    opt_self_ty,
2208                    def_id,
2209                    trait_segment,
2210                    path.segments.last().unwrap(),
2211                )
2212            }
2213            Res::PrimTy(prim_ty) => {
2214                assert_eq!(opt_self_ty, None);
2215                let _ = self.prohibit_generic_args(
2216                    path.segments.iter(),
2217                    GenericsArgsErrExtend::PrimTy(prim_ty),
2218                );
2219                match prim_ty {
2220                    hir::PrimTy::Bool => tcx.types.bool,
2221                    hir::PrimTy::Char => tcx.types.char,
2222                    hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
2223                    hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
2224                    hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
2225                    hir::PrimTy::Str => tcx.types.str_,
2226                }
2227            }
2228            Res::Err => {
2229                let e = self
2230                    .tcx()
2231                    .dcx()
2232                    .span_delayed_bug(path.span, "path with `Res::Err` but no error emitted");
2233                Ty::new_error(tcx, e)
2234            }
2235            Res::Def(..) => {
2236                assert_eq!(
2237                    path.segments.get(0).map(|seg| seg.ident.name),
2238                    Some(kw::SelfUpper),
2239                    "only expected incorrect resolution for `Self`"
2240                );
2241                Ty::new_error(
2242                    self.tcx(),
2243                    self.dcx().span_delayed_bug(span, "incorrect resolution for `Self`"),
2244                )
2245            }
2246            _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2247        }
2248    }
2249
2250    /// Lower a type parameter from the HIR to our internal notion of a type.
2251    ///
2252    /// Early-bound type parameters get lowered to [`ty::Param`]
2253    /// and late-bound ones to [`ty::Bound`].
2254    pub(crate) fn lower_ty_param(&self, hir_id: HirId) -> Ty<'tcx> {
2255        let tcx = self.tcx();
2256
2257        let ty = match tcx.named_bound_var(hir_id) {
2258            Some(rbv::ResolvedArg::LateBound(debruijn, index, def_id)) => {
2259                let br = ty::BoundTy {
2260                    var: ty::BoundVar::from_u32(index),
2261                    kind: ty::BoundTyKind::Param(def_id.to_def_id()),
2262                };
2263                Ty::new_bound(tcx, debruijn, br)
2264            }
2265            Some(rbv::ResolvedArg::EarlyBound(def_id)) => {
2266                let item_def_id = tcx.hir_ty_param_owner(def_id);
2267                let generics = tcx.generics_of(item_def_id);
2268                let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2269                Ty::new_param(tcx, index, tcx.hir_ty_param_name(def_id))
2270            }
2271            Some(rbv::ResolvedArg::Error(guar)) => Ty::new_error(tcx, guar),
2272            arg => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected bound var resolution for {0:?}: {1:?}",
        hir_id, arg))bug!("unexpected bound var resolution for {hir_id:?}: {arg:?}"),
2273        };
2274        self.check_param_uses_if_mcg(ty, tcx.hir_span(hir_id), false)
2275    }
2276
2277    /// Lower a const parameter from the HIR to our internal notion of a constant.
2278    ///
2279    /// Early-bound const parameters get lowered to [`ty::ConstKind::Param`]
2280    /// and late-bound ones to [`ty::ConstKind::Bound`].
2281    pub(crate) fn lower_const_param(&self, param_def_id: DefId, path_hir_id: HirId) -> Const<'tcx> {
2282        let tcx = self.tcx();
2283
2284        let ct = match tcx.named_bound_var(path_hir_id) {
2285            Some(rbv::ResolvedArg::EarlyBound(_)) => {
2286                // Find the name and index of the const parameter by indexing the generics of
2287                // the parent item and construct a `ParamConst`.
2288                let item_def_id = tcx.parent(param_def_id);
2289                let generics = tcx.generics_of(item_def_id);
2290                let index = generics.param_def_id_to_index[&param_def_id];
2291                let name = tcx.item_name(param_def_id);
2292                ty::Const::new_param(tcx, ty::ParamConst::new(index, name))
2293            }
2294            Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => ty::Const::new_bound(
2295                tcx,
2296                debruijn,
2297                ty::BoundConst::new(ty::BoundVar::from_u32(index)),
2298            ),
2299            Some(rbv::ResolvedArg::Error(guar)) => ty::Const::new_error(tcx, guar),
2300            arg => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected bound var resolution for {0:?}: {1:?}",
        path_hir_id, arg))bug!("unexpected bound var resolution for {:?}: {arg:?}", path_hir_id),
2301        };
2302        self.check_param_uses_if_mcg(ct, tcx.hir_span(path_hir_id), false)
2303    }
2304
2305    /// Lower a [`hir::ConstArg`] to a (type-level) [`ty::Const`](Const).
2306    #[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("lower_const_arg",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2306u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["const_arg", "ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&const_arg)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Const<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
                if tcx.features().generic_const_parameter_types() &&
                        (ty.has_free_regions() || ty.has_erased_regions()) {
                    let e =
                        self.dcx().span_err(const_arg.span,
                            "anonymous constants with lifetimes in their type are not yet supported");
                    tcx.feed_anon_const_type(anon.def_id,
                        ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
                    return ty::Const::new_error(tcx, e);
                }
                if ty.has_non_region_infer() {
                    let e =
                        self.dcx().span_err(const_arg.span,
                            "anonymous constants with inferred types are not yet supported");
                    tcx.feed_anon_const_type(anon.def_id,
                        ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
                    return ty::Const::new_error(tcx, e);
                }
                if ty.has_non_region_param() {
                    let e =
                        self.dcx().span_err(const_arg.span,
                            "anonymous constants referencing generics are not yet supported");
                    tcx.feed_anon_const_type(anon.def_id,
                        ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
                    return ty::Const::new_error(tcx, e);
                }
                tcx.feed_anon_const_type(anon.def_id,
                    ty::EarlyBinder::bind(ty));
            }
            let hir_id = const_arg.hir_id;
            match const_arg.kind {
                hir::ConstArgKind::Tup(exprs) =>
                    self.lower_const_arg_tup(exprs, ty, const_arg.span),
                hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself,
                    path)) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2358",
                                            "rustc_hir_analysis::hir_ty_lowering",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(2358u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                            ::tracing_core::field::FieldSet::new(&["maybe_qself",
                                                            "path"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&maybe_qself)
                                                                as &dyn Value)),
                                                    (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&path) as
                                                                &dyn Value))])
                                });
                        } else { ; }
                    };
                    let opt_self_ty =
                        maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
                    self.lower_resolved_const_path(opt_self_ty, path, hir_id)
                }
                hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty,
                    segment)) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2363",
                                            "rustc_hir_analysis::hir_ty_lowering",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(2363u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                            ::tracing_core::field::FieldSet::new(&["hir_self_ty",
                                                            "segment"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&hir_self_ty)
                                                                as &dyn Value)),
                                                    (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&segment) as
                                                                &dyn Value))])
                                });
                        } else { ; }
                    };
                    let self_ty = self.lower_ty(hir_self_ty);
                    self.lower_type_relative_const_path(self_ty, hir_self_ty,
                            segment, hir_id,
                            const_arg.span).unwrap_or_else(|guar|
                            Const::new_error(tcx, guar))
                }
                hir::ConstArgKind::Struct(qpath, inits) => {
                    self.lower_const_arg_struct(hir_id, qpath, inits,
                        const_arg.span)
                }
                hir::ConstArgKind::TupleCall(qpath, args) => {
                    self.lower_const_arg_tuple_call(hir_id, qpath, args,
                        const_arg.span)
                }
                hir::ConstArgKind::Array(array_expr) =>
                    self.lower_const_arg_array(array_expr, ty),
                hir::ConstArgKind::Anon(anon) =>
                    self.lower_const_arg_anon(anon),
                hir::ConstArgKind::Infer(()) =>
                    self.ct_infer(None, const_arg.span),
                hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
                hir::ConstArgKind::Literal { lit, negated } => {
                    self.lower_const_arg_literal(&lit, negated, ty,
                        const_arg.span)
                }
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
2307    pub fn lower_const_arg(&self, const_arg: &hir::ConstArg<'tcx>, ty: Ty<'tcx>) -> Const<'tcx> {
2308        let tcx = self.tcx();
2309
2310        if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
2311            // FIXME(generic_const_parameter_types): Ideally we remove these errors below when
2312            // we have the ability to intermix typeck of anon const const args with the parent
2313            // bodies typeck.
2314
2315            // We also error if the type contains any regions as effectively any region will wind
2316            // up as a region variable in mir borrowck. It would also be somewhat concerning if
2317            // hir typeck was using equality but mir borrowck wound up using subtyping as that could
2318            // result in a non-infer in hir typeck but a region variable in borrowck.
2319            if tcx.features().generic_const_parameter_types()
2320                && (ty.has_free_regions() || ty.has_erased_regions())
2321            {
2322                let e = self.dcx().span_err(
2323                    const_arg.span,
2324                    "anonymous constants with lifetimes in their type are not yet supported",
2325                );
2326                tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2327                return ty::Const::new_error(tcx, e);
2328            }
2329            // We must error if the instantiated type has any inference variables as we will
2330            // use this type to feed the `type_of` and query results must not contain inference
2331            // variables otherwise we will ICE.
2332            if ty.has_non_region_infer() {
2333                let e = self.dcx().span_err(
2334                    const_arg.span,
2335                    "anonymous constants with inferred types are not yet supported",
2336                );
2337                tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2338                return ty::Const::new_error(tcx, e);
2339            }
2340            // We error when the type contains unsubstituted generics since we do not currently
2341            // give the anon const any of the generics from the parent.
2342            if ty.has_non_region_param() {
2343                let e = self.dcx().span_err(
2344                    const_arg.span,
2345                    "anonymous constants referencing generics are not yet supported",
2346                );
2347                tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2348                return ty::Const::new_error(tcx, e);
2349            }
2350
2351            tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(ty));
2352        }
2353
2354        let hir_id = const_arg.hir_id;
2355        match const_arg.kind {
2356            hir::ConstArgKind::Tup(exprs) => self.lower_const_arg_tup(exprs, ty, const_arg.span),
2357            hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2358                debug!(?maybe_qself, ?path);
2359                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2360                self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2361            }
2362            hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2363                debug!(?hir_self_ty, ?segment);
2364                let self_ty = self.lower_ty(hir_self_ty);
2365                self.lower_type_relative_const_path(
2366                    self_ty,
2367                    hir_self_ty,
2368                    segment,
2369                    hir_id,
2370                    const_arg.span,
2371                )
2372                .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2373            }
2374            hir::ConstArgKind::Struct(qpath, inits) => {
2375                self.lower_const_arg_struct(hir_id, qpath, inits, const_arg.span)
2376            }
2377            hir::ConstArgKind::TupleCall(qpath, args) => {
2378                self.lower_const_arg_tuple_call(hir_id, qpath, args, const_arg.span)
2379            }
2380            hir::ConstArgKind::Array(array_expr) => self.lower_const_arg_array(array_expr, ty),
2381            hir::ConstArgKind::Anon(anon) => self.lower_const_arg_anon(anon),
2382            hir::ConstArgKind::Infer(()) => self.ct_infer(None, const_arg.span),
2383            hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
2384            hir::ConstArgKind::Literal { lit, negated } => {
2385                self.lower_const_arg_literal(&lit, negated, ty, const_arg.span)
2386            }
2387        }
2388    }
2389
2390    fn lower_const_arg_array(
2391        &self,
2392        array_expr: &'tcx hir::ConstArgArrayExpr<'tcx>,
2393        ty: Ty<'tcx>,
2394    ) -> Const<'tcx> {
2395        let tcx = self.tcx();
2396
2397        let ty::Array(elem_ty, _) = ty.kind() else {
2398            let e = tcx
2399                .dcx()
2400                .span_err(array_expr.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}`, found const array",
                ty))
    })format!("expected `{}`, found const array", ty));
2401            return Const::new_error(tcx, e);
2402        };
2403
2404        let elems = array_expr
2405            .elems
2406            .iter()
2407            .map(|elem| self.lower_const_arg(elem, *elem_ty))
2408            .collect::<Vec<_>>();
2409
2410        let valtree = ty::ValTree::from_branches(tcx, elems);
2411
2412        ty::Const::new_value(tcx, valtree, ty)
2413    }
2414
2415    fn lower_const_arg_tuple_call(
2416        &self,
2417        hir_id: HirId,
2418        qpath: hir::QPath<'tcx>,
2419        args: &'tcx [&'tcx hir::ConstArg<'tcx>],
2420        span: Span,
2421    ) -> Const<'tcx> {
2422        let tcx = self.tcx();
2423
2424        let non_adt_or_variant_res = || {
2425            let e = tcx.dcx().span_err(span, "tuple constructor with invalid base path");
2426            ty::Const::new_error(tcx, e)
2427        };
2428
2429        let ctor_const = match qpath {
2430            hir::QPath::Resolved(maybe_qself, path) => {
2431                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2432                self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2433            }
2434            hir::QPath::TypeRelative(hir_self_ty, segment) => {
2435                let self_ty = self.lower_ty(hir_self_ty);
2436                match self.lower_type_relative_const_path(
2437                    self_ty,
2438                    hir_self_ty,
2439                    segment,
2440                    hir_id,
2441                    span,
2442                ) {
2443                    Ok(c) => c,
2444                    Err(_) => return non_adt_or_variant_res(),
2445                }
2446            }
2447        };
2448
2449        let Some(value) = ctor_const.try_to_value() else {
2450            return non_adt_or_variant_res();
2451        };
2452
2453        let (adt_def, adt_args, variant_did) = match value.ty.kind() {
2454            ty::FnDef(def_id, fn_args)
2455                if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(*def_id) =>
2456            {
2457                let parent_did = tcx.parent(*def_id);
2458                let enum_did = tcx.parent(parent_did);
2459                (tcx.adt_def(enum_did), fn_args, parent_did)
2460            }
2461            ty::FnDef(def_id, fn_args)
2462                if let DefKind::Ctor(CtorOf::Struct, _) = tcx.def_kind(*def_id) =>
2463            {
2464                let parent_did = tcx.parent(*def_id);
2465                (tcx.adt_def(parent_did), fn_args, parent_did)
2466            }
2467            _ => {
2468                let e = self.dcx().span_err(
2469                    span,
2470                    "complex const arguments must be placed inside of a `const` block",
2471                );
2472                return Const::new_error(tcx, e);
2473            }
2474        };
2475
2476        let variant_def = adt_def.variant_with_id(variant_did);
2477        let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2478
2479        if args.len() != variant_def.fields.len() {
2480            let e = tcx.dcx().span_err(
2481                span,
2482                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("tuple constructor has {0} arguments but {1} were provided",
                variant_def.fields.len(), args.len()))
    })format!(
2483                    "tuple constructor has {} arguments but {} were provided",
2484                    variant_def.fields.len(),
2485                    args.len()
2486                ),
2487            );
2488            return ty::Const::new_error(tcx, e);
2489        }
2490
2491        let fields = variant_def
2492            .fields
2493            .iter()
2494            .zip(args)
2495            .map(|(field_def, arg)| {
2496                self.lower_const_arg(arg, tcx.type_of(field_def.did).instantiate(tcx, adt_args))
2497            })
2498            .collect::<Vec<_>>();
2499
2500        let opt_discr_const = if adt_def.is_enum() {
2501            let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2502            Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2503        } else {
2504            None
2505        };
2506
2507        let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2508        let adt_ty = Ty::new_adt(tcx, adt_def, adt_args);
2509        ty::Const::new_value(tcx, valtree, adt_ty)
2510    }
2511
2512    fn lower_const_arg_tup(
2513        &self,
2514        exprs: &'tcx [&'tcx hir::ConstArg<'tcx>],
2515        ty: Ty<'tcx>,
2516        span: Span,
2517    ) -> Const<'tcx> {
2518        let tcx = self.tcx();
2519
2520        let ty::Tuple(tys) = ty.kind() else {
2521            let e = tcx.dcx().span_err(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}`, found const tuple",
                ty))
    })format!("expected `{}`, found const tuple", ty));
2522            return Const::new_error(tcx, e);
2523        };
2524
2525        let exprs = exprs
2526            .iter()
2527            .zip(tys.iter())
2528            .map(|(expr, ty)| self.lower_const_arg(expr, ty))
2529            .collect::<Vec<_>>();
2530
2531        let valtree = ty::ValTree::from_branches(tcx, exprs);
2532        ty::Const::new_value(tcx, valtree, ty)
2533    }
2534
2535    fn lower_const_arg_struct(
2536        &self,
2537        hir_id: HirId,
2538        qpath: hir::QPath<'tcx>,
2539        inits: &'tcx [&'tcx hir::ConstArgExprField<'tcx>],
2540        span: Span,
2541    ) -> Const<'tcx> {
2542        // FIXME(mgca): try to deduplicate this function with
2543        // the equivalent HIR typeck logic.
2544        let tcx = self.tcx();
2545
2546        let non_adt_or_variant_res = || {
2547            let e = tcx.dcx().span_err(span, "struct expression with invalid base path");
2548            ty::Const::new_error(tcx, e)
2549        };
2550
2551        let (ty, variant_did) = match qpath {
2552            hir::QPath::Resolved(maybe_qself, path) => {
2553                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2553",
                        "rustc_hir_analysis::hir_ty_lowering",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2553u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                        ::tracing_core::field::FieldSet::new(&["maybe_qself",
                                        "path"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&maybe_qself)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&path) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?maybe_qself, ?path);
2554                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2555                let ty =
2556                    self.lower_resolved_ty_path(opt_self_ty, path, hir_id, PermitVariants::Yes);
2557                let variant_did = match path.res {
2558                    Res::Def(DefKind::Variant | DefKind::Struct, did) => did,
2559                    _ => return non_adt_or_variant_res(),
2560                };
2561
2562                (ty, variant_did)
2563            }
2564            hir::QPath::TypeRelative(hir_self_ty, segment) => {
2565                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2565",
                        "rustc_hir_analysis::hir_ty_lowering",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2565u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                        ::tracing_core::field::FieldSet::new(&["hir_self_ty",
                                        "segment"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&hir_self_ty)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&segment) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?hir_self_ty, ?segment);
2566                let self_ty = self.lower_ty(hir_self_ty);
2567                let opt_res = self.lower_type_relative_ty_path(
2568                    self_ty,
2569                    hir_self_ty,
2570                    segment,
2571                    hir_id,
2572                    span,
2573                    PermitVariants::Yes,
2574                );
2575
2576                let (ty, _, res_def_id) = match opt_res {
2577                    Ok(r @ (_, DefKind::Variant | DefKind::Struct, _)) => r,
2578                    Ok(_) => return non_adt_or_variant_res(),
2579                    Err(e) => return ty::Const::new_error(tcx, e),
2580                };
2581
2582                (ty, res_def_id)
2583            }
2584        };
2585
2586        let ty::Adt(adt_def, adt_args) = ty.kind() else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2587
2588        let variant_def = adt_def.variant_with_id(variant_did);
2589        let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2590
2591        let fields = variant_def
2592            .fields
2593            .iter()
2594            .map(|field_def| {
2595                // FIXME(mgca): we aren't really handling privacy, stability,
2596                // or macro hygeniene but we should.
2597                let mut init_expr =
2598                    inits.iter().filter(|init_expr| init_expr.field.name == field_def.name);
2599
2600                match init_expr.next() {
2601                    Some(expr) => {
2602                        if let Some(expr) = init_expr.next() {
2603                            let e = tcx.dcx().span_err(
2604                                expr.span,
2605                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("struct expression with multiple initialisers for `{0}`",
                field_def.name))
    })format!(
2606                                    "struct expression with multiple initialisers for `{}`",
2607                                    field_def.name,
2608                                ),
2609                            );
2610                            return ty::Const::new_error(tcx, e);
2611                        }
2612
2613                        self.lower_const_arg(
2614                            expr.expr,
2615                            tcx.type_of(field_def.did).instantiate(tcx, adt_args),
2616                        )
2617                    }
2618                    None => {
2619                        let e = tcx.dcx().span_err(
2620                            span,
2621                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("struct expression with missing field initialiser for `{0}`",
                field_def.name))
    })format!(
2622                                "struct expression with missing field initialiser for `{}`",
2623                                field_def.name
2624                            ),
2625                        );
2626                        ty::Const::new_error(tcx, e)
2627                    }
2628                }
2629            })
2630            .collect::<Vec<_>>();
2631
2632        let opt_discr_const = if adt_def.is_enum() {
2633            let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2634            Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2635        } else {
2636            None
2637        };
2638
2639        let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2640        ty::Const::new_value(tcx, valtree, ty)
2641    }
2642
2643    /// Lower a [resolved][hir::QPath::Resolved] path to a (type-level) constant.
2644    fn lower_resolved_const_path(
2645        &self,
2646        opt_self_ty: Option<Ty<'tcx>>,
2647        path: &hir::Path<'tcx>,
2648        hir_id: HirId,
2649    ) -> Const<'tcx> {
2650        let tcx = self.tcx();
2651        let span = path.span;
2652        let ct = match path.res {
2653            Res::Def(DefKind::ConstParam, def_id) => {
2654                match (&opt_self_ty, &None) {
    (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);
        }
    }
};assert_eq!(opt_self_ty, None);
2655                let _ = self.prohibit_generic_args(
2656                    path.segments.iter(),
2657                    GenericsArgsErrExtend::Param(def_id),
2658                );
2659                self.lower_const_param(def_id, hir_id)
2660            }
2661            Res::Def(DefKind::Const, did) => {
2662                if let Err(guar) = self.require_type_const_attribute(did, span) {
2663                    return Const::new_error(self.tcx(), guar);
2664                }
2665
2666                match (&opt_self_ty, &None) {
    (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);
        }
    }
};assert_eq!(opt_self_ty, None);
2667                let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2668                let _ = self
2669                    .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2670                let args = self.lower_generic_args_of_path_segment(span, did, segment);
2671                ty::Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(did, args))
2672            }
2673            Res::Def(DefKind::Ctor(ctor_of, CtorKind::Const), did) => {
2674                match (&opt_self_ty, &None) {
    (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);
        }
    }
};assert_eq!(opt_self_ty, None);
2675                let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2676                let _ = self
2677                    .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2678
2679                let parent_did = tcx.parent(did);
2680                let generics_did = match ctor_of {
2681                    CtorOf::Variant => tcx.parent(parent_did),
2682                    CtorOf::Struct => parent_did,
2683                };
2684                let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2685
2686                self.construct_const_ctor_value(did, ctor_of, args)
2687            }
2688            Res::Def(DefKind::Ctor(_, CtorKind::Fn), did) => {
2689                match (&opt_self_ty, &None) {
    (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);
        }
    }
};assert_eq!(opt_self_ty, None);
2690                let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2691                let _ = self
2692                    .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2693                let parent_did = tcx.parent(did);
2694                let generics_did = if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(did) {
2695                    tcx.parent(parent_did)
2696                } else {
2697                    parent_did
2698                };
2699                let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2700                ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2701            }
2702            Res::Def(DefKind::AssocConst, did) => {
2703                let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2704                    let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2705                    Some(trait_)
2706                } else {
2707                    None
2708                };
2709                self.lower_resolved_assoc_const_path(
2710                    span,
2711                    opt_self_ty,
2712                    did,
2713                    trait_segment,
2714                    path.segments.last().unwrap(),
2715                )
2716                .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2717            }
2718            Res::Def(DefKind::Static { .. }, _) => {
2719                ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("use of bare `static` ConstArgKind::Path\'s not yet supported"))span_bug!(span, "use of bare `static` ConstArgKind::Path's not yet supported")
2720            }
2721            // FIXME(const_generics): create real const to allow fn items as const paths
2722            Res::Def(DefKind::Fn | DefKind::AssocFn, did) => {
2723                self.dcx().span_delayed_bug(span, "function items cannot be used as const args");
2724                let args = self.lower_generic_args_of_path_segment(
2725                    span,
2726                    did,
2727                    path.segments.last().unwrap(),
2728                );
2729                ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2730            }
2731
2732            // Exhaustive match to be clear about what exactly we're considering to be
2733            // an invalid Res for a const path.
2734            res @ (Res::Def(
2735                DefKind::Mod
2736                | DefKind::Enum
2737                | DefKind::Variant
2738                | DefKind::Struct
2739                | DefKind::OpaqueTy
2740                | DefKind::TyAlias
2741                | DefKind::TraitAlias
2742                | DefKind::AssocTy
2743                | DefKind::Union
2744                | DefKind::Trait
2745                | DefKind::ForeignTy
2746                | DefKind::TyParam
2747                | DefKind::Macro(_)
2748                | DefKind::LifetimeParam
2749                | DefKind::Use
2750                | DefKind::ForeignMod
2751                | DefKind::AnonConst
2752                | DefKind::InlineConst
2753                | DefKind::Field
2754                | DefKind::Impl { .. }
2755                | DefKind::Closure
2756                | DefKind::ExternCrate
2757                | DefKind::GlobalAsm
2758                | DefKind::SyntheticCoroutineBody,
2759                _,
2760            )
2761            | Res::PrimTy(_)
2762            | Res::SelfTyParam { .. }
2763            | Res::SelfTyAlias { .. }
2764            | Res::SelfCtor(_)
2765            | Res::Local(_)
2766            | Res::ToolMod
2767            | Res::NonMacroAttr(_)
2768            | Res::Err) => Const::new_error_with_message(
2769                tcx,
2770                span,
2771                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("invalid Res {0:?} for const path",
                res))
    })format!("invalid Res {res:?} for const path"),
2772            ),
2773        };
2774        self.check_param_uses_if_mcg(ct, span, false)
2775    }
2776
2777    /// Literals are eagerly converted to a constant, everything else becomes `Unevaluated`.
2778    #[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("lower_const_arg_anon",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2778u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["anon"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&anon)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Const<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            let expr = &tcx.hir_body(anon.body).value;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2783",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2783u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["expr"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&expr) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            let ty = tcx.type_of(anon.def_id).instantiate_identity();
            match self.try_lower_anon_const_lit(ty, expr) {
                Some(v) => v,
                None =>
                    ty::Const::new_unevaluated(tcx,
                        ty::UnevaluatedConst {
                            def: anon.def_id.to_def_id(),
                            args: ty::GenericArgs::identity_for_item(tcx,
                                anon.def_id.to_def_id()),
                        }),
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
2779    fn lower_const_arg_anon(&self, anon: &AnonConst) -> Const<'tcx> {
2780        let tcx = self.tcx();
2781
2782        let expr = &tcx.hir_body(anon.body).value;
2783        debug!(?expr);
2784
2785        // FIXME(generic_const_parameter_types): We should use the proper generic args
2786        // here. It's only used as a hint for literals so doesn't matter too much to use the right
2787        // generic arguments, just weaker type inference.
2788        let ty = tcx.type_of(anon.def_id).instantiate_identity();
2789
2790        match self.try_lower_anon_const_lit(ty, expr) {
2791            Some(v) => v,
2792            None => ty::Const::new_unevaluated(
2793                tcx,
2794                ty::UnevaluatedConst {
2795                    def: anon.def_id.to_def_id(),
2796                    args: ty::GenericArgs::identity_for_item(tcx, anon.def_id.to_def_id()),
2797                },
2798            ),
2799        }
2800    }
2801
2802    #[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("lower_const_arg_literal",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2802u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["kind", "neg", "ty",
                                                    "span"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&neg as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Const<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            if let LitKind::Err(guar) = *kind {
                return ty::Const::new_error(tcx, guar);
            }
            let input = LitToConstInput { lit: *kind, ty, neg };
            match tcx.at(span).lit_to_const(input) {
                Some(value) =>
                    ty::Const::new_value(tcx, value.valtree, value.ty),
                None => {
                    let e =
                        tcx.dcx().span_err(span,
                            "type annotations needed for the literal");
                    ty::Const::new_error(tcx, e)
                }
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
2803    fn lower_const_arg_literal(
2804        &self,
2805        kind: &LitKind,
2806        neg: bool,
2807        ty: Ty<'tcx>,
2808        span: Span,
2809    ) -> Const<'tcx> {
2810        let tcx = self.tcx();
2811        if let LitKind::Err(guar) = *kind {
2812            return ty::Const::new_error(tcx, guar);
2813        }
2814        let input = LitToConstInput { lit: *kind, ty, neg };
2815        match tcx.at(span).lit_to_const(input) {
2816            Some(value) => ty::Const::new_value(tcx, value.valtree, value.ty),
2817            None => {
2818                let e = tcx.dcx().span_err(span, "type annotations needed for the literal");
2819                ty::Const::new_error(tcx, e)
2820            }
2821        }
2822    }
2823
2824    #[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("try_lower_anon_const_lit",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2824u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["ty", "expr"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<Const<'tcx>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            let expr =
                match &expr.kind {
                    hir::ExprKind::Block(block, _) if
                        block.stmts.is_empty() && block.expr.is_some() => {
                        block.expr.as_ref().unwrap()
                    }
                    _ => expr,
                };
            let lit_input =
                match expr.kind {
                    hir::ExprKind::Lit(lit) =>
                        Some(LitToConstInput { lit: lit.node, ty, neg: false }),
                    hir::ExprKind::Unary(hir::UnOp::Neg, expr) =>
                        match expr.kind {
                            hir::ExprKind::Lit(lit) =>
                                Some(LitToConstInput { lit: lit.node, ty, neg: true }),
                            _ => None,
                        },
                    _ => None,
                };
            lit_input.and_then(|l|
                    {
                        if const_lit_matches_ty(tcx, &l.lit, l.ty, l.neg) {
                            tcx.at(expr.span).lit_to_const(l).map(|value|
                                    ty::Const::new_value(tcx, value.valtree, value.ty))
                        } else { None }
                    })
        }
    }
}#[instrument(skip(self), level = "debug")]
2825    fn try_lower_anon_const_lit(
2826        &self,
2827        ty: Ty<'tcx>,
2828        expr: &'tcx hir::Expr<'tcx>,
2829    ) -> Option<Const<'tcx>> {
2830        let tcx = self.tcx();
2831
2832        // Unwrap a block, so that e.g. `{ 1 }` is recognised as a literal. This makes the
2833        // performance optimisation of directly lowering anon consts occur more often.
2834        let expr = match &expr.kind {
2835            hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2836                block.expr.as_ref().unwrap()
2837            }
2838            _ => expr,
2839        };
2840
2841        let lit_input = match expr.kind {
2842            hir::ExprKind::Lit(lit) => Some(LitToConstInput { lit: lit.node, ty, neg: false }),
2843            hir::ExprKind::Unary(hir::UnOp::Neg, expr) => match expr.kind {
2844                hir::ExprKind::Lit(lit) => Some(LitToConstInput { lit: lit.node, ty, neg: true }),
2845                _ => None,
2846            },
2847            _ => None,
2848        };
2849
2850        lit_input.and_then(|l| {
2851            if const_lit_matches_ty(tcx, &l.lit, l.ty, l.neg) {
2852                tcx.at(expr.span)
2853                    .lit_to_const(l)
2854                    .map(|value| ty::Const::new_value(tcx, value.valtree, value.ty))
2855            } else {
2856                None
2857            }
2858        })
2859    }
2860
2861    fn require_type_const_attribute(
2862        &self,
2863        def_id: DefId,
2864        span: Span,
2865    ) -> Result<(), ErrorGuaranteed> {
2866        let tcx = self.tcx();
2867        if tcx.is_type_const(def_id) {
2868            Ok(())
2869        } else {
2870            let mut err = self.dcx().struct_span_err(
2871                span,
2872                "use of `const` in the type system not defined as `type const`",
2873            );
2874            if def_id.is_local() {
2875                let name = tcx.def_path_str(def_id);
2876                err.span_suggestion(
2877                    tcx.def_span(def_id).shrink_to_lo(),
2878                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("add `type` before `const` for `{0}`",
                name))
    })format!("add `type` before `const` for `{name}`"),
2879                    ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("type ")) })format!("type "),
2880                    Applicability::MaybeIncorrect,
2881                );
2882            } else {
2883                err.note("only consts marked defined as `type const` may be used in types");
2884            }
2885            Err(err.emit())
2886        }
2887    }
2888
2889    fn lower_delegation_ty(&self, idx: hir::InferDelegationKind) -> Ty<'tcx> {
2890        let delegation_sig = self.tcx().inherit_sig_for_delegation_item(self.item_def_id());
2891        match idx {
2892            hir::InferDelegationKind::Input(idx) => delegation_sig[idx],
2893            hir::InferDelegationKind::Output => *delegation_sig.last().unwrap(),
2894        }
2895    }
2896
2897    /// Lower a type from the HIR to our internal notion of a type.
2898    x;#[instrument(level = "debug", skip(self), ret)]
2899    pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
2900        let tcx = self.tcx();
2901
2902        let result_ty = match &hir_ty.kind {
2903            hir::TyKind::InferDelegation(_, idx) => self.lower_delegation_ty(*idx),
2904            hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)),
2905            hir::TyKind::Ptr(mt) => Ty::new_ptr(tcx, self.lower_ty(mt.ty), mt.mutbl),
2906            hir::TyKind::Ref(region, mt) => {
2907                let r = self.lower_lifetime(region, RegionInferReason::Reference);
2908                debug!(?r);
2909                let t = self.lower_ty(mt.ty);
2910                Ty::new_ref(tcx, r, t, mt.mutbl)
2911            }
2912            hir::TyKind::Never => tcx.types.never,
2913            hir::TyKind::Tup(fields) => {
2914                Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
2915            }
2916            hir::TyKind::FnPtr(bf) => {
2917                check_c_variadic_abi(tcx, bf.decl, bf.abi, hir_ty.span);
2918
2919                Ty::new_fn_ptr(
2920                    tcx,
2921                    self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)),
2922                )
2923            }
2924            hir::TyKind::UnsafeBinder(binder) => Ty::new_unsafe_binder(
2925                tcx,
2926                ty::Binder::bind_with_vars(
2927                    self.lower_ty(binder.inner_ty),
2928                    tcx.late_bound_vars(hir_ty.hir_id),
2929                ),
2930            ),
2931            hir::TyKind::TraitObject(bounds, tagged_ptr) => {
2932                let lifetime = tagged_ptr.pointer();
2933                let syntax = tagged_ptr.tag();
2934                self.lower_trait_object_ty(hir_ty.span, hir_ty.hir_id, bounds, lifetime, syntax)
2935            }
2936            // If we encounter a fully qualified path with RTN generics, then it must have
2937            // *not* gone through `lower_ty_maybe_return_type_notation`, and therefore
2938            // it's certainly in an illegal position.
2939            hir::TyKind::Path(hir::QPath::Resolved(_, path))
2940                if path.segments.last().and_then(|segment| segment.args).is_some_and(|args| {
2941                    matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
2942                }) =>
2943            {
2944                let guar = self.dcx().emit_err(BadReturnTypeNotation { span: hir_ty.span });
2945                Ty::new_error(tcx, guar)
2946            }
2947            hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2948                debug!(?maybe_qself, ?path);
2949                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2950                self.lower_resolved_ty_path(opt_self_ty, path, hir_ty.hir_id, PermitVariants::No)
2951            }
2952            &hir::TyKind::OpaqueDef(opaque_ty) => {
2953                // If this is an RPITIT and we are using the new RPITIT lowering scheme, we
2954                // generate the def_id of an associated type for the trait and return as
2955                // type a projection.
2956                let in_trait = match opaque_ty.origin {
2957                    hir::OpaqueTyOrigin::FnReturn {
2958                        parent,
2959                        in_trait_or_impl: Some(hir::RpitContext::Trait),
2960                        ..
2961                    }
2962                    | hir::OpaqueTyOrigin::AsyncFn {
2963                        parent,
2964                        in_trait_or_impl: Some(hir::RpitContext::Trait),
2965                        ..
2966                    } => Some(parent),
2967                    hir::OpaqueTyOrigin::FnReturn {
2968                        in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
2969                        ..
2970                    }
2971                    | hir::OpaqueTyOrigin::AsyncFn {
2972                        in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
2973                        ..
2974                    }
2975                    | hir::OpaqueTyOrigin::TyAlias { .. } => None,
2976                };
2977
2978                self.lower_opaque_ty(opaque_ty.def_id, in_trait)
2979            }
2980            hir::TyKind::TraitAscription(hir_bounds) => {
2981                // Impl trait in bindings lower as an infer var with additional
2982                // set of type bounds.
2983                let self_ty = self.ty_infer(None, hir_ty.span);
2984                let mut bounds = Vec::new();
2985                self.lower_bounds(
2986                    self_ty,
2987                    hir_bounds.iter(),
2988                    &mut bounds,
2989                    ty::List::empty(),
2990                    PredicateFilter::All,
2991                    OverlappingAsssocItemConstraints::Allowed,
2992                );
2993                self.add_implicit_sizedness_bounds(
2994                    &mut bounds,
2995                    self_ty,
2996                    hir_bounds,
2997                    ImpliedBoundsContext::AssociatedTypeOrImplTrait,
2998                    hir_ty.span,
2999                );
3000                self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span);
3001                self_ty
3002            }
3003            // If we encounter a type relative path with RTN generics, then it must have
3004            // *not* gone through `lower_ty_maybe_return_type_notation`, and therefore
3005            // it's certainly in an illegal position.
3006            hir::TyKind::Path(hir::QPath::TypeRelative(_, segment))
3007                if segment.args.is_some_and(|args| {
3008                    matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3009                }) =>
3010            {
3011                let guar = self.dcx().emit_err(BadReturnTypeNotation { span: hir_ty.span });
3012                Ty::new_error(tcx, guar)
3013            }
3014            hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
3015                debug!(?hir_self_ty, ?segment);
3016                let self_ty = self.lower_ty(hir_self_ty);
3017                self.lower_type_relative_ty_path(
3018                    self_ty,
3019                    hir_self_ty,
3020                    segment,
3021                    hir_ty.hir_id,
3022                    hir_ty.span,
3023                    PermitVariants::No,
3024                )
3025                .map(|(ty, _, _)| ty)
3026                .unwrap_or_else(|guar| Ty::new_error(tcx, guar))
3027            }
3028            hir::TyKind::Array(ty, length) => {
3029                let length = self.lower_const_arg(length, tcx.types.usize);
3030                Ty::new_array_with_const_len(tcx, self.lower_ty(ty), length)
3031            }
3032            hir::TyKind::Infer(()) => {
3033                // Infer also appears as the type of arguments or return
3034                // values in an ExprKind::Closure, or as
3035                // the type of local variables. Both of these cases are
3036                // handled specially and will not descend into this routine.
3037                self.ty_infer(None, hir_ty.span)
3038            }
3039            hir::TyKind::Pat(ty, pat) => {
3040                let ty_span = ty.span;
3041                let ty = self.lower_ty(ty);
3042                let pat_ty = match self.lower_pat_ty_pat(ty, ty_span, pat) {
3043                    Ok(kind) => Ty::new_pat(tcx, ty, tcx.mk_pat(kind)),
3044                    Err(guar) => Ty::new_error(tcx, guar),
3045                };
3046                self.record_ty(pat.hir_id, ty, pat.span);
3047                pat_ty
3048            }
3049            hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar),
3050        };
3051
3052        self.record_ty(hir_ty.hir_id, result_ty, hir_ty.span);
3053        result_ty
3054    }
3055
3056    fn lower_pat_ty_pat(
3057        &self,
3058        ty: Ty<'tcx>,
3059        ty_span: Span,
3060        pat: &hir::TyPat<'tcx>,
3061    ) -> Result<ty::PatternKind<'tcx>, ErrorGuaranteed> {
3062        let tcx = self.tcx();
3063        match pat.kind {
3064            hir::TyPatKind::Range(start, end) => {
3065                match ty.kind() {
3066                    // Keep this list of types in sync with the list of types that
3067                    // the `RangePattern` trait is implemented for.
3068                    ty::Int(_) | ty::Uint(_) | ty::Char => {
3069                        let start = self.lower_const_arg(start, ty);
3070                        let end = self.lower_const_arg(end, ty);
3071                        Ok(ty::PatternKind::Range { start, end })
3072                    }
3073                    _ => Err(self
3074                        .dcx()
3075                        .span_delayed_bug(ty_span, "invalid base type for range pattern")),
3076                }
3077            }
3078            hir::TyPatKind::NotNull => Ok(ty::PatternKind::NotNull),
3079            hir::TyPatKind::Or(patterns) => {
3080                self.tcx()
3081                    .mk_patterns_from_iter(patterns.iter().map(|pat| {
3082                        self.lower_pat_ty_pat(ty, ty_span, pat).map(|pat| tcx.mk_pat(pat))
3083                    }))
3084                    .map(ty::PatternKind::Or)
3085            }
3086            hir::TyPatKind::Err(e) => Err(e),
3087        }
3088    }
3089
3090    /// Lower an opaque type (i.e., an existential impl-Trait type) from the HIR.
3091    x;#[instrument(level = "debug", skip(self), ret)]
3092    fn lower_opaque_ty(&self, def_id: LocalDefId, in_trait: Option<LocalDefId>) -> Ty<'tcx> {
3093        let tcx = self.tcx();
3094
3095        let lifetimes = tcx.opaque_captured_lifetimes(def_id);
3096        debug!(?lifetimes);
3097
3098        // If this is an RPITIT and we are using the new RPITIT lowering scheme,
3099        // do a linear search to map this to the synthetic associated type that
3100        // it will be lowered to.
3101        let def_id = if let Some(parent_def_id) = in_trait {
3102            *tcx.associated_types_for_impl_traits_in_associated_fn(parent_def_id.to_def_id())
3103                .iter()
3104                .find(|rpitit| match tcx.opt_rpitit_info(**rpitit) {
3105                    Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
3106                        opaque_def_id.expect_local() == def_id
3107                    }
3108                    _ => unreachable!(),
3109                })
3110                .unwrap()
3111        } else {
3112            def_id.to_def_id()
3113        };
3114
3115        let generics = tcx.generics_of(def_id);
3116        debug!(?generics);
3117
3118        // We use `generics.count() - lifetimes.len()` here instead of `generics.parent_count`
3119        // since return-position impl trait in trait squashes all of the generics from its source fn
3120        // into its own generics, so the opaque's "own" params isn't always just lifetimes.
3121        let offset = generics.count() - lifetimes.len();
3122
3123        let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| {
3124            if let Some(i) = (param.index as usize).checked_sub(offset) {
3125                let (lifetime, _) = lifetimes[i];
3126                // FIXME(mgca): should we be calling self.check_params_use_if_mcg here too?
3127                self.lower_resolved_lifetime(lifetime).into()
3128            } else {
3129                tcx.mk_param_from_def(param)
3130            }
3131        });
3132        debug!(?args);
3133
3134        if in_trait.is_some() {
3135            Ty::new_projection_from_args(tcx, def_id, args)
3136        } else {
3137            Ty::new_opaque(tcx, def_id, args)
3138        }
3139    }
3140
3141    /// Lower a function type from the HIR to our internal notion of a function signature.
3142    x;#[instrument(level = "debug", skip(self, hir_id, safety, abi, decl, generics, hir_ty), ret)]
3143    pub fn lower_fn_ty(
3144        &self,
3145        hir_id: HirId,
3146        safety: hir::Safety,
3147        abi: rustc_abi::ExternAbi,
3148        decl: &hir::FnDecl<'tcx>,
3149        generics: Option<&hir::Generics<'_>>,
3150        hir_ty: Option<&hir::Ty<'_>>,
3151    ) -> ty::PolyFnSig<'tcx> {
3152        let tcx = self.tcx();
3153        let bound_vars = tcx.late_bound_vars(hir_id);
3154        debug!(?bound_vars);
3155
3156        let (input_tys, output_ty) = self.lower_fn_sig(decl, generics, hir_id, hir_ty);
3157
3158        debug!(?output_ty);
3159
3160        let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, safety, abi);
3161        let fn_ptr_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3162
3163        if let hir::Node::Ty(hir::Ty { kind: hir::TyKind::FnPtr(fn_ptr_ty), span, .. }) =
3164            tcx.hir_node(hir_id)
3165        {
3166            check_abi(tcx, hir_id, *span, fn_ptr_ty.abi);
3167        }
3168
3169        // reject function types that violate cmse ABI requirements
3170        cmse::validate_cmse_abi(self.tcx(), self.dcx(), hir_id, abi, fn_ptr_ty);
3171
3172        if !fn_ptr_ty.references_error() {
3173            // Find any late-bound regions declared in return type that do
3174            // not appear in the arguments. These are not well-formed.
3175            //
3176            // Example:
3177            //     for<'a> fn() -> &'a str <-- 'a is bad
3178            //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
3179            let inputs = fn_ptr_ty.inputs();
3180            let late_bound_in_args =
3181                tcx.collect_constrained_late_bound_regions(inputs.map_bound(|i| i.to_owned()));
3182            let output = fn_ptr_ty.output();
3183            let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(output);
3184
3185            self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3186                struct_span_code_err!(
3187                    self.dcx(),
3188                    decl.output.span(),
3189                    E0581,
3190                    "return type references {}, which is not constrained by the fn input types",
3191                    br_name
3192                )
3193            });
3194        }
3195
3196        fn_ptr_ty
3197    }
3198
3199    /// Given a fn_hir_id for a impl function, suggest the type that is found on the
3200    /// corresponding function in the trait that the impl implements, if it exists.
3201    /// If arg_idx is Some, then it corresponds to an input type index, otherwise it
3202    /// corresponds to the return type.
3203    pub(super) fn suggest_trait_fn_ty_for_impl_fn_infer(
3204        &self,
3205        fn_hir_id: HirId,
3206        arg_idx: Option<usize>,
3207    ) -> Option<Ty<'tcx>> {
3208        let tcx = self.tcx();
3209        let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3210            tcx.hir_node(fn_hir_id)
3211        else {
3212            return None;
3213        };
3214        let i = tcx.parent_hir_node(fn_hir_id).expect_item().expect_impl();
3215
3216        let trait_ref = self.lower_impl_trait_ref(&i.of_trait?.trait_ref, self.lower_ty(i.self_ty));
3217
3218        let assoc = tcx.associated_items(trait_ref.def_id).find_by_ident_and_kind(
3219            tcx,
3220            *ident,
3221            ty::AssocTag::Fn,
3222            trait_ref.def_id,
3223        )?;
3224
3225        let fn_sig = tcx.fn_sig(assoc.def_id).instantiate(
3226            tcx,
3227            trait_ref.args.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3228        );
3229        let fn_sig = tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), fn_sig);
3230
3231        Some(if let Some(arg_idx) = arg_idx {
3232            *fn_sig.inputs().get(arg_idx)?
3233        } else {
3234            fn_sig.output()
3235        })
3236    }
3237
3238    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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("validate_late_bound_regions",
                                    "rustc_hir_analysis::hir_ty_lowering",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3238u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["constrained_regions",
                                                    "referenced_regions"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constrained_regions)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&referenced_regions)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            for br in referenced_regions.difference(&constrained_regions) {
                let br_name =
                    if let Some(name) = br.get_name(self.tcx()) {
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("lifetime `{0}`", name))
                            })
                    } else { "an anonymous lifetime".to_string() };
                let mut err = generate_err(&br_name);
                if !br.is_named(self.tcx()) {
                    err.note("lifetimes appearing in an associated or opaque type are not considered constrained");
                    err.note("consider introducing a named lifetime parameter");
                }
                err.emit();
            }
        }
    }
}#[instrument(level = "trace", skip(self, generate_err))]
3239    fn validate_late_bound_regions<'cx>(
3240        &'cx self,
3241        constrained_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3242        referenced_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3243        generate_err: impl Fn(&str) -> Diag<'cx>,
3244    ) {
3245        for br in referenced_regions.difference(&constrained_regions) {
3246            let br_name = if let Some(name) = br.get_name(self.tcx()) {
3247                format!("lifetime `{name}`")
3248            } else {
3249                "an anonymous lifetime".to_string()
3250            };
3251
3252            let mut err = generate_err(&br_name);
3253
3254            if !br.is_named(self.tcx()) {
3255                // The only way for an anonymous lifetime to wind up
3256                // in the return type but **also** be unconstrained is
3257                // if it only appears in "associated types" in the
3258                // input. See #47511 and #62200 for examples. In this case,
3259                // though we can easily give a hint that ought to be
3260                // relevant.
3261                err.note(
3262                    "lifetimes appearing in an associated or opaque type are not considered constrained",
3263                );
3264                err.note("consider introducing a named lifetime parameter");
3265            }
3266
3267            err.emit();
3268        }
3269    }
3270
3271    /// Given the bounds on an object, determines what single region bound (if any) we can
3272    /// use to summarize this type.
3273    ///
3274    /// The basic idea is that we will use the bound the user
3275    /// provided, if they provided one, and otherwise search the supertypes of trait bounds
3276    /// for region bounds. It may be that we can derive no bound at all, in which case
3277    /// we return `None`.
3278    x;#[instrument(level = "debug", skip(self, span), ret)]
3279    fn compute_object_lifetime_bound(
3280        &self,
3281        span: Span,
3282        existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3283    ) -> Option<ty::Region<'tcx>> // if None, use the default
3284    {
3285        let tcx = self.tcx();
3286
3287        // No explicit region bound specified. Therefore, examine trait
3288        // bounds and see if we can derive region bounds from those.
3289        let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3290
3291        // If there are no derived region bounds, then report back that we
3292        // can find no region bound. The caller will use the default.
3293        if derived_region_bounds.is_empty() {
3294            return None;
3295        }
3296
3297        // If any of the derived region bounds are 'static, that is always
3298        // the best choice.
3299        if derived_region_bounds.iter().any(|r| r.is_static()) {
3300            return Some(tcx.lifetimes.re_static);
3301        }
3302
3303        // Determine whether there is exactly one unique region in the set
3304        // of derived region bounds. If so, use that. Otherwise, report an
3305        // error.
3306        let r = derived_region_bounds[0];
3307        if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3308            self.dcx().emit_err(AmbiguousLifetimeBound { span });
3309        }
3310        Some(r)
3311    }
3312
3313    fn construct_const_ctor_value(
3314        &self,
3315        ctor_def_id: DefId,
3316        ctor_of: CtorOf,
3317        args: GenericArgsRef<'tcx>,
3318    ) -> Const<'tcx> {
3319        let tcx = self.tcx();
3320        let parent_did = tcx.parent(ctor_def_id);
3321
3322        let adt_def = tcx.adt_def(match ctor_of {
3323            CtorOf::Variant => tcx.parent(parent_did),
3324            CtorOf::Struct => parent_did,
3325        });
3326
3327        let variant_idx = adt_def.variant_index_with_id(parent_did);
3328
3329        let valtree = if adt_def.is_enum() {
3330            let discr = ty::ValTree::from_scalar_int(tcx, variant_idx.as_u32().into());
3331            ty::ValTree::from_branches(tcx, [ty::Const::new_value(tcx, discr, tcx.types.u32)])
3332        } else {
3333            ty::ValTree::zst(tcx)
3334        };
3335
3336        let adt_ty = Ty::new_adt(tcx, adt_def, args);
3337        ty::Const::new_value(tcx, valtree, adt_ty)
3338    }
3339}