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::{assert_matches, slice};
23
24use rustc_abi::FIRST_VARIANT;
25use rustc_ast::LitKind;
26use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
27use rustc_data_structures::sso::SsoHashSet;
28use rustc_errors::codes::*;
29use rustc_errors::{
30    Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, FatalError, StashKey,
31    struct_span_code_err,
32};
33use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
34use rustc_hir::def_id::{DefId, LocalDefId};
35use rustc_hir::{self as hir, AnonConst, GenericArg, GenericArgs, HirId};
36use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
37use rustc_infer::traits::DynCompatibilityViolation;
38use rustc_macros::{TypeFoldable, TypeVisitable};
39use rustc_middle::middle::stability::AllowUnstable;
40use rustc_middle::ty::{
41    self, Const, FnSigKind, GenericArgKind, GenericArgsRef, GenericParamDefKind, LitToConstInput,
42    Ty, TyCtxt, TypeSuperFoldable, TypeVisitableExt, TypingMode, Unnormalized, Upcast,
43    const_lit_matches_ty, fold_regions,
44};
45use rustc_middle::{bug, span_bug};
46use rustc_session::errors::feature_err;
47use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
48use rustc_span::{DUMMY_SP, Ident, Span, kw, sym};
49use rustc_trait_selection::infer::InferCtxtExt;
50use rustc_trait_selection::traits::{self, FulfillmentError};
51use tracing::{debug, instrument};
52
53use crate::check::check_abi;
54use crate::diagnostics::{self, BadReturnTypeNotation, NoFieldOnType};
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;
58use crate::{NoVariantNamed, check_c_variadic_abi};
59
60/// The context in which an implied bound is being added to a item being lowered (i.e. a sizedness
61/// trait or a default trait)
62#[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)]
63pub(crate) enum ImpliedBoundsContext<'tcx> {
64    /// An implied bound is added to a trait definition (i.e. a new supertrait), used when adding
65    /// a default `MetaSized` supertrait
66    TraitDef(LocalDefId),
67    /// An implied bound is added to a type parameter
68    TyParam(LocalDefId, &'tcx [hir::WherePredicate<'tcx>]),
69    /// An implied bound being added in any other context
70    AssociatedTypeOrImplTrait,
71}
72
73/// A path segment that is semantically allowed to have generic arguments.
74#[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)]
75pub struct GenericPathSegment(pub DefId, pub usize);
76
77#[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)]
78pub enum PredicateFilter {
79    /// All predicates may be implied by the trait.
80    All,
81
82    /// Only traits that reference `Self: ..` are implied by the trait.
83    SelfOnly,
84
85    /// Only traits that reference `Self: ..` and define an associated type
86    /// with the given ident are implied by the trait. This mode exists to
87    /// side-step query cycles when lowering associated types.
88    SelfTraitThatDefines(Ident),
89
90    /// Only traits that reference `Self: ..` and their associated type bounds.
91    /// For example, given `Self: Tr<A: B>`, this would expand to `Self: Tr`
92    /// and `<Self as Tr>::A: B`.
93    SelfAndAssociatedTypeBounds,
94
95    /// Filter only the `[const]` bounds, which are lowered into `HostEffect` clauses.
96    ConstIfConst,
97
98    /// Filter only the `[const]` bounds which are *also* in the supertrait position.
99    SelfConstIfConst,
100}
101
102#[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)]
103pub enum RegionInferReason<'a> {
104    /// Lifetime on a trait object that is spelled explicitly, e.g. `+ 'a` or `+ '_`.
105    ExplicitObjectLifetime,
106    /// A trait object's lifetime when it is elided, e.g. `dyn Any`.
107    ObjectLifetimeDefault(Span),
108    /// Generic lifetime parameter
109    Param(&'a ty::GenericParamDef),
110    RegionPredicate,
111    Reference,
112    OutlivesBound,
113}
114
115#[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)]
116pub struct InherentAssocCandidate {
117    pub impl_: DefId,
118    pub assoc_item: DefId,
119    pub scope: DefId,
120}
121
122pub struct ResolvedStructPath<'tcx> {
123    pub res: Result<Res, ErrorGuaranteed>,
124    pub ty: Ty<'tcx>,
125}
126
127/// A context which can lower type-system entities from the [HIR][hir] to
128/// the [`rustc_middle::ty`] representation.
129///
130/// This trait used to be called `AstConv`.
131pub trait HirTyLowerer<'tcx> {
132    fn tcx(&self) -> TyCtxt<'tcx>;
133
134    fn dcx(&self) -> DiagCtxtHandle<'_>;
135
136    /// Returns the [`LocalDefId`] of the overarching item whose constituents get lowered.
137    fn item_def_id(&self) -> LocalDefId;
138
139    /// Returns the region to use when a lifetime is omitted (and not elided).
140    fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx>;
141
142    /// Returns the type to use when a type is omitted.
143    fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
144
145    /// Returns the const to use when a const is omitted.
146    fn ct_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx>;
147
148    fn register_trait_ascription_bounds(
149        &self,
150        bounds: Vec<(ty::Clause<'tcx>, Span)>,
151        hir_id: HirId,
152        span: Span,
153    );
154
155    /// Probe bounds in scope where the bounded type coincides with the given type parameter.
156    ///
157    /// Rephrased, this returns bounds of the form `T: Trait`, where `T` is a type parameter
158    /// with the given `def_id`. This is a subset of the full set of bounds.
159    ///
160    /// This method may use the given `assoc_name` to disregard bounds whose trait reference
161    /// doesn't define an associated item with the provided name.
162    ///
163    /// This is used for one specific purpose: Resolving “short-hand” associated type references
164    /// like `T::Item` where `T` is a type parameter. In principle, we would do that by first
165    /// getting the full set of predicates in scope and then filtering down to find those that
166    /// apply to `T`, but this can lead to cycle errors. The problem is that we have to do this
167    /// resolution *in order to create the predicates in the first place*.
168    /// Hence, we have this “special pass”.
169    fn probe_ty_param_bounds(
170        &self,
171        span: Span,
172        def_id: LocalDefId,
173        assoc_ident: Ident,
174    ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]>;
175
176    fn select_inherent_assoc_candidates(
177        &self,
178        span: Span,
179        self_ty: Ty<'tcx>,
180        candidates: Vec<InherentAssocCandidate>,
181    ) -> (Vec<InherentAssocCandidate>, Vec<FulfillmentError<'tcx>>);
182
183    /// Lower a path to an associated item (of a trait) to a projection.
184    ///
185    /// This method has to be defined by the concrete lowering context because
186    /// dealing with higher-ranked trait references depends on its capabilities:
187    ///
188    /// If the context can make use of type inference, it can simply instantiate
189    /// any late-bound vars bound by the trait reference with inference variables.
190    /// If it doesn't support type inference, there is nothing reasonable it can
191    /// do except reject the associated type.
192    ///
193    /// The canonical example of this is associated type `T::P` where `T` is a type
194    /// param constrained by `T: for<'a> Trait<'a>` and where `Trait` defines `P`.
195    fn lower_assoc_item_path(
196        &self,
197        span: Span,
198        item_def_id: DefId,
199        item_segment: &hir::PathSegment<'tcx>,
200        poly_trait_ref: ty::PolyTraitRef<'tcx>,
201    ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed>;
202
203    fn lower_fn_sig(
204        &self,
205        decl: &hir::FnDecl<'tcx>,
206        generics: Option<&hir::Generics<'_>>,
207        hir_id: HirId,
208        hir_ty: Option<&hir::Ty<'_>>,
209    ) -> (Vec<Ty<'tcx>>, Ty<'tcx>);
210
211    /// Returns `AdtDef` if `ty` is an ADT.
212    ///
213    /// Note that `ty` might be a alias type that needs normalization.
214    /// This used to get the enum variants in scope of the type.
215    /// For example, `Self::A` could refer to an associated type
216    /// or to an enum variant depending on the result of this function.
217    fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>>;
218
219    /// Record the lowered type of a HIR node in this context.
220    fn record_ty(&self, hir_id: HirId, ty: Ty<'tcx>, span: Span);
221
222    /// The inference context of the lowering context if applicable.
223    fn infcx(&self) -> Option<&InferCtxt<'tcx>>;
224
225    /// Convenience method for coercing the lowering context into a trait object type.
226    ///
227    /// Most lowering routines are defined on the trait object type directly
228    /// necessitating a coercion step from the concrete lowering context.
229    fn lowerer(&self) -> &dyn HirTyLowerer<'tcx>
230    where
231        Self: Sized,
232    {
233        self
234    }
235
236    /// Performs minimalistic dyn compat checks outside of bodies, but full within bodies.
237    /// Outside of bodies we could end up in cycles, so we delay most checks to later phases.
238    fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation>;
239}
240
241/// The "qualified self" of an associated item path.
242///
243/// For diagnostic purposes only.
244enum AssocItemQSelf {
245    Trait(DefId),
246    TyParam(LocalDefId, Span),
247    SelfTyAlias,
248}
249
250impl AssocItemQSelf {
251    fn to_string(&self, tcx: TyCtxt<'_>) -> String {
252        match *self {
253            Self::Trait(def_id) => tcx.def_path_str(def_id),
254            Self::TyParam(def_id, _) => tcx.hir_ty_param_name(def_id).to_string(),
255            Self::SelfTyAlias => kw::SelfUpper.to_string(),
256        }
257    }
258}
259
260#[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)]
261enum LowerTypeRelativePathMode {
262    Type(PermitVariants),
263    Const,
264}
265
266impl LowerTypeRelativePathMode {
267    fn assoc_tag(self) -> ty::AssocTag {
268        match self {
269            Self::Type(_) => ty::AssocTag::Type,
270            Self::Const => ty::AssocTag::Const,
271        }
272    }
273
274    ///NOTE: use `assoc_tag` for any important logic
275    fn def_kind_for_diagnostics(self) -> DefKind {
276        match self {
277            Self::Type(_) => DefKind::AssocTy,
278            Self::Const => DefKind::AssocConst { is_type_const: false },
279        }
280    }
281
282    fn permit_variants(self) -> PermitVariants {
283        match self {
284            Self::Type(permit_variants) => permit_variants,
285            // FIXME(mgca): Support paths like `Option::<T>::None` or `Option::<T>::Some` which
286            // resolve to const ctors/fn items respectively.
287            Self::Const => PermitVariants::No,
288        }
289    }
290}
291
292/// Whether to permit a path to resolve to an enum variant.
293#[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)]
294pub enum PermitVariants {
295    Yes,
296    No,
297}
298
299#[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) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "AssocItem", &__self_0),
            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<ty::AliasTerm<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<DefId>;
        let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for TypeRelativePath<'tcx> { }Copy)]
300enum TypeRelativePath<'tcx> {
301    AssocItem(ty::AliasTerm<'tcx>),
302    Variant { adt: Ty<'tcx>, variant_did: DefId },
303    Ctor { ctor_def_id: DefId, args: GenericArgsRef<'tcx> },
304}
305
306/// New-typed boolean indicating whether explicit late-bound lifetimes
307/// are present in a set of generic arguments.
308///
309/// For example if we have some method `fn f<'a>(&'a self)` implemented
310/// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
311/// is late-bound so should not be provided explicitly. Thus, if `f` is
312/// instantiated with some generic arguments providing `'a` explicitly,
313/// we taint those arguments with `ExplicitLateBound::Yes` so that we
314/// can provide an appropriate diagnostic later.
315#[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)]
316pub enum ExplicitLateBound {
317    Yes,
318    No,
319}
320
321#[derive(#[automatically_derived]
impl ::core::fmt::Debug for IsMethodCall {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                IsMethodCall::Yes => "Yes",
                IsMethodCall::No => "No",
            })
    }
}Debug, #[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)]
322pub enum IsMethodCall {
323    Yes,
324    No,
325}
326
327/// Denotes the "position" of a generic argument, indicating if it is a generic type,
328/// generic function or generic method call.
329#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GenericArgPosition {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            GenericArgPosition::Type =>
                ::core::fmt::Formatter::write_str(f, "Type"),
            GenericArgPosition::Value(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Value",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for GenericArgPosition { }Copy, #[automatically_derived]
impl ::core::clone::Clone for GenericArgPosition {
    #[inline]
    fn clone(&self) -> GenericArgPosition {
        let _: ::core::clone::AssertParamIsClone<IsMethodCall>;
        *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 &&
            match (self, other) {
                (GenericArgPosition::Value(__self_0),
                    GenericArgPosition::Value(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
330pub(crate) enum GenericArgPosition {
331    Type,
332    Value(IsMethodCall),
333}
334
335/// Whether to allow duplicate associated iten constraints in a trait ref, e.g.
336/// `Trait<Assoc = Ty, Assoc = Ty>`. This is forbidden in `dyn Trait<...>`
337/// but allowed everywhere else.
338#[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)]
339pub(crate) enum OverlappingAsssocItemConstraints {
340    Allowed,
341    Forbidden,
342}
343
344/// A marker denoting that the generic arguments that were
345/// provided did not match the respective generic parameters.
346#[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)]
347pub struct GenericArgCountMismatch {
348    pub reported: ErrorGuaranteed,
349    /// A list of indices of arguments provided that were not valid.
350    pub invalid_args: Vec<usize>,
351}
352
353/// Decorates the result of a generic argument count mismatch
354/// check with whether explicit late bounds were provided.
355#[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)]
356pub struct GenericArgCountResult {
357    pub explicit_late_bound: ExplicitLateBound,
358    pub correct: Result<(), GenericArgCountMismatch>,
359}
360
361/// A context which can lower HIR's [`GenericArg`] to `rustc_middle`'s [`ty::GenericArg`].
362///
363/// Its only consumer is [`generics::lower_generic_args`].
364/// Read its documentation to learn more.
365pub trait GenericArgsLowerer<'a, 'tcx> {
366    fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool);
367
368    fn provided_kind(
369        &mut self,
370        preceding_args: &[ty::GenericArg<'tcx>],
371        param: &ty::GenericParamDef,
372        arg: &GenericArg<'tcx>,
373    ) -> ty::GenericArg<'tcx>;
374
375    fn inferred_kind(
376        &mut self,
377        preceding_args: &[ty::GenericArg<'tcx>],
378        param: &ty::GenericParamDef,
379        infer_args: bool,
380    ) -> ty::GenericArg<'tcx>;
381}
382
383/// Context in which `ForbidParamUsesFolder` is being used, to emit appropriate diagnostics.
384enum ForbidParamContext {
385    /// Anon const in a const argument position.
386    ConstArgument,
387    /// Enum discriminant expression.
388    EnumDiscriminant,
389}
390
391struct ForbidParamUsesFolder<'tcx> {
392    tcx: TyCtxt<'tcx>,
393    anon_const_def_id: LocalDefId,
394    span: Span,
395    is_self_alias: bool,
396    context: ForbidParamContext,
397}
398
399impl<'tcx> ForbidParamUsesFolder<'tcx> {
400    fn error(&self) -> ErrorGuaranteed {
401        let msg = match self.context {
402            ForbidParamContext::EnumDiscriminant if self.is_self_alias => {
403                "generic `Self` types are not permitted in enum discriminant values"
404            }
405            ForbidParamContext::EnumDiscriminant => {
406                "generic parameters may not be used in enum discriminant values"
407            }
408            ForbidParamContext::ConstArgument if self.is_self_alias => {
409                "generic `Self` types are currently not permitted in anonymous constants"
410            }
411            ForbidParamContext::ConstArgument => {
412                if self.tcx.features().generic_const_args() {
413                    "generic parameters in const blocks are not allowed; use a named `const` item instead"
414                } else {
415                    "generic parameters may not be used in const operations"
416                }
417            }
418        };
419        let mut diag = self.tcx.dcx().struct_span_err(self.span, msg);
420        if self.is_self_alias && #[allow(non_exhaustive_omitted_patterns)] match self.context {
    ForbidParamContext::ConstArgument => true,
    _ => false,
}matches!(self.context, ForbidParamContext::ConstArgument) {
421            let anon_const_hir_id: HirId = HirId::make_owner(self.anon_const_def_id);
422            let parent_impl = self.tcx.hir_parent_owner_iter(anon_const_hir_id).find_map(
423                |(_, node)| match node {
424                    hir::OwnerNode::Item(hir::Item {
425                        kind: hir::ItemKind::Impl(impl_), ..
426                    }) => Some(impl_),
427                    _ => None,
428                },
429            );
430            if let Some(impl_) = parent_impl {
431                diag.span_note(impl_.self_ty.span, "not a concrete type");
432            }
433        }
434        if #[allow(non_exhaustive_omitted_patterns)] match self.context {
    ForbidParamContext::ConstArgument => true,
    _ => false,
}matches!(self.context, ForbidParamContext::ConstArgument) {
435            if self.tcx.features().generic_const_args() {
436                diag.help("consider factoring the expression into a `type const` item and use it as the const argument instead");
437            } else if self.tcx.features().min_generic_const_args() {
438                diag.help("add `#![feature(generic_const_args)]` and extract the expression into a `type const` item");
439            } else if self.tcx.sess.is_nightly_build() {
440                diag.help(
441                    "add `#![feature(generic_const_exprs)]` to allow generic const expressions",
442                );
443                diag.help("alternatively, you can use `#![feature(generic_const_args)]` and extract the expression into a `type const` item");
444            }
445        }
446        diag.emit()
447    }
448}
449
450impl<'tcx> ty::TypeFolder<TyCtxt<'tcx>> for ForbidParamUsesFolder<'tcx> {
451    fn cx(&self) -> TyCtxt<'tcx> {
452        self.tcx
453    }
454
455    fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
456        if #[allow(non_exhaustive_omitted_patterns)] match t.kind() {
    ty::Param(..) => true,
    _ => false,
}matches!(t.kind(), ty::Param(..)) {
457            return Ty::new_error(self.tcx, self.error());
458        }
459        t.super_fold_with(self)
460    }
461
462    fn fold_const(&mut self, c: Const<'tcx>) -> Const<'tcx> {
463        if #[allow(non_exhaustive_omitted_patterns)] match c.kind() {
    ty::ConstKind::Param(..) => true,
    _ => false,
}matches!(c.kind(), ty::ConstKind::Param(..)) {
464            return Const::new_error(self.tcx, self.error());
465        }
466        c.super_fold_with(self)
467    }
468
469    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
470        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(..)) {
471            return ty::Region::new_error(self.tcx, self.error());
472        }
473        r
474    }
475}
476
477impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
478    /// See `check_param_uses_if_mcg`.
479    ///
480    /// FIXME(mgca): this is pub only for instantiate_value_path and would be nice to avoid altogether
481    pub fn check_param_res_if_mcg_for_instantiate_value_path(
482        &self,
483        res: Res,
484        span: Span,
485    ) -> Result<(), ErrorGuaranteed> {
486        let tcx = self.tcx();
487        let parent_def_id = self.item_def_id();
488        // In this path, `Some(context)` should be `ConstArgument`: enum
489        // discriminants are handled earlier by resolve. We still use the helper so
490        // nested inline consts are checked in the outer const-argument context.
491        if let Res::Def(DefKind::ConstParam, _) = res
492            && let Some(context) = self.anon_const_forbids_generic_params()
493        {
494            let folder = ForbidParamUsesFolder {
495                tcx,
496                anon_const_def_id: parent_def_id,
497                span,
498                is_self_alias: false,
499                context,
500            };
501            return Err(folder.error());
502        }
503        Ok(())
504    }
505
506    /// Returns the `ForbidParamContext` for the current anon const if it is a context that
507    /// forbids uses of generic parameters. `None` if the current item is not such a context.
508    ///
509    /// Name resolution handles most invalid generic parameter uses in these contexts, but it
510    /// cannot reject `Self` that aliases a generic type, nor generic parameters introduced by
511    /// type-dependent name resolution (e.g. `<Self as Trait>::Assoc` resolving to a type that
512    /// contains params). Those cases are handled by `check_param_uses_if_mcg`.
513    fn anon_const_forbids_generic_params(&self) -> Option<ForbidParamContext> {
514        let tcx = self.tcx();
515        let item_def_id = self.item_def_id();
516
517        // Inline consts and closures can be nested inside anon consts that forbid generic
518        // params (e.g. an enum discriminant). Walk up the def parent chain to find the
519        // nearest enclosing AnonConst and use that to determine the context.
520        let anon_const_def_id = tcx.typeck_root_def_id_local(item_def_id);
521
522        if tcx.def_kind(anon_const_def_id) != DefKind::AnonConst {
523            return None;
524        }
525
526        match tcx.anon_const_kind(anon_const_def_id) {
527            ty::AnonConstKind::MCG => Some(ForbidParamContext::ConstArgument),
528            ty::AnonConstKind::NonTypeSystemAnon => {
529                // NonTypeSystem anon consts only have accessible generic parameters in specific
530                // positions (ty patterns and field defaults — see `generics_of`). In all other
531                // positions (e.g. enum discriminants) generic parameters are not in scope.
532                if tcx.generics_of(anon_const_def_id).count() == 0 {
533                    Some(ForbidParamContext::EnumDiscriminant)
534                } else {
535                    None
536                }
537            }
538            ty::AnonConstKind::NonTypeSystemInline
539            | ty::AnonConstKind::GCE
540            | ty::AnonConstKind::RepeatExprCount => None,
541        }
542    }
543
544    /// Check for uses of generic parameters that are not in scope due to this being
545    /// in a non-generic anon const context (e.g. MCG or an enum discriminant).
546    ///
547    /// Name resolution rejects most invalid uses, but cannot handle `Self` aliasing a
548    /// generic type or generic parameters introduced by type-dependent name resolution.
549    #[must_use = "need to use transformed output"]
550    fn check_param_uses_if_mcg<T>(&self, term: T, span: Span, is_self_alias: bool) -> T
551    where
552        T: ty::TypeFoldable<TyCtxt<'tcx>>,
553    {
554        let tcx = self.tcx();
555        if let Some(context) = self.anon_const_forbids_generic_params()
556            // Fast path if contains no params/escaping bound vars.
557            && (term.has_param() || term.has_escaping_bound_vars())
558        {
559            let anon_const_def_id = self.item_def_id();
560            let mut folder =
561                ForbidParamUsesFolder { tcx, anon_const_def_id, span, is_self_alias, context };
562            term.fold_with(&mut folder)
563        } else {
564            term
565        }
566    }
567
568    /// Lower a lifetime from the HIR to our internal notion of a lifetime called a *region*.
569    x;#[instrument(level = "debug", skip(self), ret)]
570    pub fn lower_lifetime(
571        &self,
572        lifetime: &hir::Lifetime,
573        reason: RegionInferReason<'_>,
574    ) -> ty::Region<'tcx> {
575        if let Some(resolved) = self.tcx().named_bound_var(lifetime.hir_id) {
576            let region = self.lower_resolved_lifetime(resolved);
577            self.check_param_uses_if_mcg(region, lifetime.ident.span, false)
578        } else {
579            self.re_infer(lifetime.ident.span, reason)
580        }
581    }
582
583    /// Lower a lifetime from the HIR to our internal notion of a lifetime called a *region*.
584    x;#[instrument(level = "debug", skip(self), ret)]
585    fn lower_resolved_lifetime(&self, resolved: rbv::ResolvedArg) -> ty::Region<'tcx> {
586        let tcx = self.tcx();
587
588        match resolved {
589            rbv::ResolvedArg::StaticLifetime => tcx.lifetimes.re_static,
590
591            rbv::ResolvedArg::LateBound(debruijn, index, def_id) => {
592                let br = ty::BoundRegion {
593                    var: ty::BoundVar::from_u32(index),
594                    kind: ty::BoundRegionKind::Named(def_id.to_def_id()),
595                };
596                ty::Region::new_bound(tcx, debruijn, br)
597            }
598
599            rbv::ResolvedArg::EarlyBound(def_id) => {
600                let name = tcx.hir_ty_param_name(def_id);
601                let item_def_id = tcx.hir_ty_param_owner(def_id);
602                let generics = tcx.generics_of(item_def_id);
603                let index = generics.param_def_id_to_index[&def_id.to_def_id()];
604                ty::Region::new_early_param(tcx, ty::EarlyParamRegion { index, name })
605            }
606
607            rbv::ResolvedArg::Free(scope, id) => {
608                ty::Region::new_late_param(
609                    tcx,
610                    scope.to_def_id(),
611                    ty::LateParamRegionKind::Named(id.to_def_id()),
612                )
613
614                // (*) -- not late-bound, won't change
615            }
616
617            rbv::ResolvedArg::Error(guar) => ty::Region::new_error(tcx, guar),
618        }
619    }
620
621    pub fn lower_generic_args_of_path_segment(
622        &self,
623        span: Span,
624        def_id: DefId,
625        item_segment: &hir::PathSegment<'tcx>,
626    ) -> GenericArgsRef<'tcx> {
627        let (args, _) = self.lower_generic_args_of_path(span, def_id, &[], item_segment, None);
628        if let Some(c) = item_segment.args().constraints.first() {
629            prohibit_assoc_item_constraint(self, c, Some((def_id, item_segment, span)));
630        }
631        args
632    }
633
634    /// Lower the generic arguments provided to some path.
635    ///
636    /// If this is a trait reference, you also need to pass the self type `self_ty`.
637    /// The lowering process may involve applying defaulted type parameters.
638    ///
639    /// Associated item constraints are not handled here! They are either lowered via
640    /// `lower_assoc_item_constraint` or rejected via `prohibit_assoc_item_constraint`.
641    ///
642    /// ### Example
643    ///
644    /// ```ignore (illustrative)
645    ///    T: std::ops::Index<usize, Output = u32>
646    /// // ^1 ^^^^^^^^^^^^^^2 ^^^^3  ^^^^^^^^^^^4
647    /// ```
648    ///
649    /// 1. The `self_ty` here would refer to the type `T`.
650    /// 2. The path in question is the path to the trait `std::ops::Index`,
651    ///    which will have been resolved to a `def_id`
652    /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
653    ///    parameters are returned in the `GenericArgsRef`
654    /// 4. Associated item constraints like `Output = u32` are contained in `generic_args.constraints`.
655    ///
656    /// Note that the type listing given here is *exactly* what the user provided.
657    ///
658    /// For (generic) associated types
659    ///
660    /// ```ignore (illustrative)
661    /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
662    /// ```
663    ///
664    /// We have the parent args are the args for the parent trait:
665    /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
666    /// type itself: `['a]`. The returned `GenericArgsRef` concatenates these two
667    /// lists: `[Vec<u8>, u8, 'a]`.
668    x;#[instrument(level = "debug", skip(self, span), ret)]
669    pub(crate) fn lower_generic_args_of_path(
670        &self,
671        span: Span,
672        def_id: DefId,
673        parent_args: &[ty::GenericArg<'tcx>],
674        segment: &hir::PathSegment<'tcx>,
675        self_ty: Option<Ty<'tcx>>,
676    ) -> (GenericArgsRef<'tcx>, GenericArgCountResult) {
677        // If the type is parameterized by this region, then replace this
678        // region with the current anon region binding (in other words,
679        // whatever & would get replaced with).
680
681        let tcx = self.tcx();
682        let generics = tcx.generics_of(def_id);
683        debug!(?generics);
684
685        if generics.has_self {
686            if generics.parent.is_some() {
687                // The parent is a trait so it should have at least one
688                // generic parameter for the `Self` type.
689                assert!(!parent_args.is_empty())
690            } else {
691                // This item (presumably a trait) needs a self-type.
692                assert!(self_ty.is_some());
693            }
694        } else {
695            assert!(self_ty.is_none());
696        }
697
698        let arg_count = check_generic_arg_count(
699            self,
700            def_id,
701            segment,
702            generics,
703            GenericArgPosition::Type,
704            self_ty.is_some(),
705        );
706
707        // Skip processing if type has no generic parameters.
708        // Traits always have `Self` as a generic parameter, which means they will not return early
709        // here and so associated item constraints will be handled regardless of whether there are
710        // any non-`Self` generic parameters.
711        if generics.is_own_empty() {
712            return (tcx.mk_args(parent_args), arg_count);
713        }
714
715        struct GenericArgsCtxt<'a, 'tcx> {
716            lowerer: &'a dyn HirTyLowerer<'tcx>,
717            def_id: DefId,
718            generic_args: &'a GenericArgs<'tcx>,
719            span: Span,
720            infer_args: bool,
721            create_synth_args: bool,
722            incorrect_args: &'a Result<(), GenericArgCountMismatch>,
723        }
724
725        impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for GenericArgsCtxt<'a, 'tcx> {
726            fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool) {
727                if did == self.def_id {
728                    (Some(self.generic_args), self.infer_args)
729                } else {
730                    // The last component of this tuple is unimportant.
731                    (None, false)
732                }
733            }
734
735            fn provided_kind(
736                &mut self,
737                preceding_args: &[ty::GenericArg<'tcx>],
738                param: &ty::GenericParamDef,
739                arg: &GenericArg<'tcx>,
740            ) -> ty::GenericArg<'tcx> {
741                let tcx = self.lowerer.tcx();
742
743                if let Err(incorrect) = self.incorrect_args {
744                    if incorrect.invalid_args.contains(&(param.index as usize)) {
745                        return param.to_error(tcx);
746                    }
747                }
748
749                let handle_ty_args = |has_default, ty: &hir::Ty<'tcx>| {
750                    if has_default {
751                        tcx.check_optional_stability(
752                            param.def_id,
753                            Some(arg.hir_id()),
754                            arg.span(),
755                            None,
756                            AllowUnstable::No,
757                            |_, _| {
758                                // Default generic parameters may not be marked
759                                // with stability attributes, i.e. when the
760                                // default parameter was defined at the same time
761                                // as the rest of the type. As such, we ignore missing
762                                // stability attributes.
763                            },
764                        );
765                    }
766                    self.lowerer.lower_ty(ty).into()
767                };
768
769                match (&param.kind, arg) {
770                    (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
771                        self.lowerer.lower_lifetime(lt, RegionInferReason::Param(param)).into()
772                    }
773                    (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
774                        // We handle the other parts of `Ty` in the match arm below
775                        handle_ty_args(has_default, ty.as_unambig_ty())
776                    }
777                    (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
778                        handle_ty_args(has_default, &inf.to_ty())
779                    }
780                    (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => self
781                        .lowerer
782                        // Ambig portions of `ConstArg` are handled in the match arm below
783                        .lower_const_arg(
784                            ct.as_unambig_ct(),
785                            tcx.type_of(param.def_id)
786                                .instantiate(tcx, preceding_args)
787                                .skip_norm_wip(),
788                        )
789                        .into(),
790                    (&GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
791                        self.lowerer.ct_infer(Some(param), inf.span).into()
792                    }
793                    (kind, arg) => span_bug!(
794                        self.span,
795                        "mismatched path argument for kind {kind:?}: found arg {arg:?}"
796                    ),
797                }
798            }
799
800            fn inferred_kind(
801                &mut self,
802                preceding_args: &[ty::GenericArg<'tcx>],
803                param: &ty::GenericParamDef,
804                infer_args: bool,
805            ) -> ty::GenericArg<'tcx> {
806                let tcx = self.lowerer.tcx();
807
808                if let Err(incorrect) = self.incorrect_args {
809                    if incorrect.invalid_args.contains(&(param.index as usize)) {
810                        return param.to_error(tcx);
811                    }
812                }
813                match param.kind {
814                    GenericParamDefKind::Lifetime => {
815                        self.lowerer.re_infer(self.span, RegionInferReason::Param(param)).into()
816                    }
817                    GenericParamDefKind::Type { has_default, synthetic } => {
818                        if !infer_args && has_default {
819                            // No type parameter provided, but a default exists.
820                            if let Some(prev) =
821                                preceding_args.iter().find_map(|arg| match arg.kind() {
822                                    GenericArgKind::Type(ty) => ty.error_reported().err(),
823                                    _ => None,
824                                })
825                            {
826                                // Avoid ICE #86756 when type error recovery goes awry.
827                                return Ty::new_error(tcx, prev).into();
828                            }
829                            tcx.at(self.span)
830                                .type_of(param.def_id)
831                                .instantiate(tcx, preceding_args)
832                                .skip_norm_wip()
833                                .into()
834                        } else if self.create_synth_args && synthetic {
835                            Ty::new_param(tcx, param.index, param.name).into()
836                        } else if infer_args {
837                            self.lowerer.ty_infer(Some(param), self.span).into()
838                        } else {
839                            // We've already errored above about the mismatch.
840                            Ty::new_misc_error(tcx).into()
841                        }
842                    }
843                    GenericParamDefKind::Const { has_default, .. } => {
844                        let ty = tcx
845                            .at(self.span)
846                            .type_of(param.def_id)
847                            .instantiate(tcx, preceding_args)
848                            .skip_norm_wip();
849                        if let Err(guar) = ty.error_reported() {
850                            return ty::Const::new_error(tcx, guar).into();
851                        }
852                        if !infer_args && has_default {
853                            tcx.const_param_default(param.def_id)
854                                .instantiate(tcx, preceding_args)
855                                .skip_norm_wip()
856                                .into()
857                        } else if infer_args {
858                            self.lowerer.ct_infer(Some(param), self.span).into()
859                        } else {
860                            // We've already errored above about the mismatch.
861                            ty::Const::new_misc_error(tcx).into()
862                        }
863                    }
864                }
865            }
866        }
867
868        let mut args_ctx = GenericArgsCtxt {
869            lowerer: self,
870            def_id,
871            span,
872            generic_args: segment.args(),
873            infer_args: segment.infer_args,
874            create_synth_args: segment.delegation_child_segment,
875            incorrect_args: &arg_count.correct,
876        };
877
878        let args = lower_generic_args(
879            self,
880            def_id,
881            parent_args,
882            self_ty.is_some(),
883            self_ty,
884            &arg_count,
885            &mut args_ctx,
886        );
887
888        (args, arg_count)
889    }
890
891    #[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(891u32),
                                    ::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))]
892    pub fn lower_generic_args_of_assoc_item(
893        &self,
894        span: Span,
895        item_def_id: DefId,
896        item_segment: &hir::PathSegment<'tcx>,
897        parent_args: GenericArgsRef<'tcx>,
898    ) -> GenericArgsRef<'tcx> {
899        let (args, _) =
900            self.lower_generic_args_of_path(span, item_def_id, parent_args, item_segment, None);
901        if let Some(c) = item_segment.args().constraints.first() {
902            prohibit_assoc_item_constraint(self, c, Some((item_def_id, item_segment, span)));
903        }
904        args
905    }
906
907    /// Lower a trait reference as found in an impl header as the implementee.
908    ///
909    /// The self type `self_ty` is the implementer of the trait.
910    pub fn lower_impl_trait_ref(
911        &self,
912        trait_ref: &hir::TraitRef<'tcx>,
913        self_ty: Ty<'tcx>,
914    ) -> ty::TraitRef<'tcx> {
915        let [leading_segments @ .., segment] = trait_ref.path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
916
917        let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
918
919        self.lower_mono_trait_ref(
920            trait_ref.path.span,
921            trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
922            self_ty,
923            segment,
924            true,
925        )
926    }
927
928    /// Lower a polymorphic trait reference given a self type into `bounds`.
929    ///
930    /// *Polymorphic* in the sense that it may bind late-bound vars.
931    ///
932    /// This may generate auxiliary bounds iff the trait reference contains associated item constraints.
933    ///
934    /// ### Example
935    ///
936    /// Given the trait ref `Iterator<Item = u32>` and the self type `Ty`, this will add the
937    ///
938    /// 1. *trait predicate* `<Ty as Iterator>` (known as `Ty: Iterator` in the surface syntax) and the
939    /// 2. *projection predicate* `<Ty as Iterator>::Item = u32`
940    ///
941    /// to `bounds`.
942    ///
943    /// ### A Note on Binders
944    ///
945    /// Against our usual convention, there is an implied binder around the `self_ty` and the
946    /// `trait_ref` here. So they may reference late-bound vars.
947    ///
948    /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
949    /// where `'a` is a bound region at depth 0. Similarly, the `trait_ref` would be `Bar<'a>`.
950    /// The lowered poly-trait-ref will track this binder explicitly, however.
951    #[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(951u32),
                                    ::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:1031",
                                    "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(1031u32),
                                    ::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:1038",
                                    "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(1038u32),
                                    ::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::diagnostics::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))]
952    pub(crate) fn lower_poly_trait_ref(
953        &self,
954        &hir::PolyTraitRef {
955            bound_generic_params,
956            modifiers: hir::TraitBoundModifiers { constness, polarity },
957            trait_ref,
958            span,
959        }: &hir::PolyTraitRef<'tcx>,
960        self_ty: Ty<'tcx>,
961        bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
962        predicate_filter: PredicateFilter,
963        overlapping_assoc_item_constraints: OverlappingAsssocItemConstraints,
964    ) -> GenericArgCountResult {
965        let tcx = self.tcx();
966
967        // We use the *resolved* bound vars later instead of the HIR ones since the former
968        // also include the bound vars of the overarching predicate if applicable.
969        let _ = bound_generic_params;
970
971        let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
972
973        // Relaxed bounds `?Trait` and `PointeeSized` bounds aren't represented in the middle::ty IR
974        // as they denote the *absence* of a default bound. However, we can't bail out early here since
975        // we still need to perform several validation steps (see below). Instead, simply "pour" all
976        // resulting bounds "down the drain", i.e., into a new `Vec` that just gets dropped at the end.
977        let transient = match polarity {
978            hir::BoundPolarity::Positive => {
979                // To elaborate on the comment directly above, regarding `PointeeSized` specifically,
980                // we don't "reify" such bounds to avoid trait system limitations -- namely,
981                // non-global where-clauses being preferred over item bounds (where `PointeeSized`
982                // bounds would be proven) -- which can result in errors when a `PointeeSized`
983                // supertrait / bound / predicate is added to some items.
984                tcx.is_lang_item(trait_def_id, hir::LangItem::PointeeSized)
985            }
986            hir::BoundPolarity::Negative(_) => false,
987            hir::BoundPolarity::Maybe(_) => {
988                self.require_bound_to_relax_default_trait(trait_ref, span);
989                true
990            }
991        };
992        let bounds = if transient { &mut Vec::new() } else { bounds };
993
994        let polarity = match polarity {
995            hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_) => {
996                ty::PredicatePolarity::Positive
997            }
998            hir::BoundPolarity::Negative(_) => ty::PredicatePolarity::Negative,
999        };
1000
1001        let [leading_segments @ .., segment] = trait_ref.path.segments else { bug!() };
1002
1003        let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
1004        self.report_internal_fn_trait(span, trait_def_id, segment, false);
1005
1006        let (generic_args, arg_count) = self.lower_generic_args_of_path(
1007            trait_ref.path.span,
1008            trait_def_id,
1009            &[],
1010            segment,
1011            Some(self_ty),
1012        );
1013
1014        let constraints = segment.args().constraints;
1015
1016        if transient && (!generic_args[1..].is_empty() || !constraints.is_empty()) {
1017            // Since the bound won't be present in the middle::ty IR as established above, any
1018            // arguments or constraints won't be checked for well-formedness in later passes.
1019            //
1020            // This is only an issue if the trait ref is otherwise valid which can only happen if
1021            // the corresponding default trait has generic parameters or associated items. Such a
1022            // trait would be degenerate. We delay a bug to detect and guard us against these.
1023            //
1024            // E.g: Given `/*default*/ trait Bound<'a: 'static, T, const N: usize> {}`,
1025            // `?Bound<Vec<str>, { panic!() }>` won't be wfchecked.
1026            self.dcx()
1027                .span_delayed_bug(span, "transient bound should not have args or constraints");
1028        }
1029
1030        let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
1031        debug!(?bound_vars);
1032
1033        let poly_trait_ref = ty::Binder::bind_with_vars(
1034            ty::TraitRef::new_from_args(tcx, trait_def_id, generic_args),
1035            bound_vars,
1036        );
1037
1038        debug!(?poly_trait_ref);
1039
1040        // We deal with const conditions later.
1041        match predicate_filter {
1042            PredicateFilter::All
1043            | PredicateFilter::SelfOnly
1044            | PredicateFilter::SelfTraitThatDefines(..)
1045            | PredicateFilter::SelfAndAssociatedTypeBounds => {
1046                let bound = poly_trait_ref.map_bound(|trait_ref| {
1047                    ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity })
1048                });
1049                let bound = (bound.upcast(tcx), span);
1050                // FIXME(-Znext-solver): We can likely remove this hack once the
1051                // new trait solver lands. This fixed an overflow in the old solver.
1052                // This may have performance implications, so please check perf when
1053                // removing it.
1054                // This was added in <https://github.com/rust-lang/rust/pull/123302>.
1055                if tcx.is_lang_item(trait_def_id, rustc_hir::LangItem::Sized) {
1056                    bounds.insert(0, bound);
1057                } else {
1058                    bounds.push(bound);
1059                }
1060            }
1061            PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
1062        }
1063
1064        if let hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) = constness
1065            && !tcx.is_const_trait(trait_def_id)
1066        {
1067            let (def_span, suggestion, suggestion_pre) =
1068                match (trait_def_id.as_local(), tcx.sess.is_nightly_build()) {
1069                    (Some(trait_def_id), true) => {
1070                        let span = tcx.hir_expect_item(trait_def_id).vis_span;
1071                        let span = tcx.sess.source_map().span_extend_while_whitespace(span);
1072
1073                        (
1074                            None,
1075                            Some(span.shrink_to_hi()),
1076                            if self.tcx().features().const_trait_impl() {
1077                                ""
1078                            } else {
1079                                "enable `#![feature(const_trait_impl)]` in your crate and "
1080                            },
1081                        )
1082                    }
1083                    (None, _) | (_, false) => (Some(tcx.def_span(trait_def_id)), None, ""),
1084                };
1085            self.dcx().emit_err(crate::diagnostics::ConstBoundForNonConstTrait {
1086                span,
1087                modifier: constness.as_str(),
1088                def_span,
1089                trait_name: tcx.def_path_str(trait_def_id),
1090                suggestion,
1091                suggestion_pre,
1092            });
1093        } else {
1094            match predicate_filter {
1095                // This is only concerned with trait predicates.
1096                PredicateFilter::SelfTraitThatDefines(..) => {}
1097                PredicateFilter::All
1098                | PredicateFilter::SelfOnly
1099                | PredicateFilter::SelfAndAssociatedTypeBounds => {
1100                    match constness {
1101                        hir::BoundConstness::Always(_) => {
1102                            if polarity == ty::PredicatePolarity::Positive {
1103                                bounds.push((
1104                                    poly_trait_ref
1105                                        .to_host_effect_clause(tcx, ty::BoundConstness::Const),
1106                                    span,
1107                                ));
1108                            }
1109                        }
1110                        hir::BoundConstness::Maybe(_) => {
1111                            // We don't emit a const bound here, since that would mean that we
1112                            // unconditionally need to prove a `HostEffect` predicate, even when
1113                            // the predicates are being instantiated in a non-const context. This
1114                            // is instead handled in the `const_conditions` query.
1115                        }
1116                        hir::BoundConstness::Never => {}
1117                    }
1118                }
1119                // On the flip side, when filtering `ConstIfConst` bounds, we only need to convert
1120                // `[const]` bounds. All other predicates are handled in their respective queries.
1121                //
1122                // Note that like `PredicateFilter::SelfOnly`, we don't need to do any filtering
1123                // here because we only call this on self bounds, and deal with the recursive case
1124                // in `lower_assoc_item_constraint`.
1125                PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {
1126                    match constness {
1127                        hir::BoundConstness::Maybe(_) => {
1128                            if polarity == ty::PredicatePolarity::Positive {
1129                                bounds.push((
1130                                    poly_trait_ref
1131                                        .to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1132                                    span,
1133                                ));
1134                            }
1135                        }
1136                        hir::BoundConstness::Always(_) | hir::BoundConstness::Never => {}
1137                    }
1138                }
1139            }
1140        }
1141
1142        let mut dup_constraints = (overlapping_assoc_item_constraints
1143            == OverlappingAsssocItemConstraints::Forbidden)
1144            .then_some(FxIndexMap::default());
1145
1146        for constraint in constraints {
1147            // Don't register any associated item constraints for negative bounds,
1148            // since we should have emitted an error for them earlier, and they
1149            // would not be well-formed!
1150            if polarity == ty::PredicatePolarity::Negative {
1151                self.dcx().span_delayed_bug(
1152                    constraint.span,
1153                    "negative trait bounds should not have assoc item constraints",
1154                );
1155                break;
1156            }
1157
1158            // Specify type to assert that error was already reported in `Err` case.
1159            let _: Result<_, ErrorGuaranteed> = self.lower_assoc_item_constraint(
1160                trait_ref.hir_ref_id,
1161                poly_trait_ref,
1162                constraint,
1163                bounds,
1164                dup_constraints.as_mut(),
1165                constraint.span,
1166                predicate_filter,
1167            );
1168            // Okay to ignore `Err` because of `ErrorGuaranteed` (see above).
1169        }
1170
1171        arg_count
1172    }
1173
1174    /// Lower a monomorphic trait reference given a self type while prohibiting associated item bindings.
1175    ///
1176    /// *Monomorphic* in the sense that it doesn't bind any late-bound vars.
1177    fn lower_mono_trait_ref(
1178        &self,
1179        span: Span,
1180        trait_def_id: DefId,
1181        self_ty: Ty<'tcx>,
1182        trait_segment: &hir::PathSegment<'tcx>,
1183        is_impl: bool,
1184    ) -> ty::TraitRef<'tcx> {
1185        self.report_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
1186
1187        let (generic_args, _) =
1188            self.lower_generic_args_of_path(span, trait_def_id, &[], trait_segment, Some(self_ty));
1189        if let Some(c) = trait_segment.args().constraints.first() {
1190            prohibit_assoc_item_constraint(self, c, Some((trait_def_id, trait_segment, span)));
1191        }
1192        ty::TraitRef::new_from_args(self.tcx(), trait_def_id, generic_args)
1193    }
1194
1195    fn probe_trait_that_defines_assoc_item(
1196        &self,
1197        trait_def_id: DefId,
1198        assoc_tag: ty::AssocTag,
1199        assoc_ident: Ident,
1200    ) -> bool {
1201        self.tcx()
1202            .associated_items(trait_def_id)
1203            .find_by_ident_and_kind(self.tcx(), assoc_ident, assoc_tag, trait_def_id)
1204            .is_some()
1205    }
1206
1207    fn lower_path_segment(
1208        &self,
1209        span: Span,
1210        def_id: DefId,
1211        item_segment: &hir::PathSegment<'tcx>,
1212    ) -> Ty<'tcx> {
1213        let tcx = self.tcx();
1214        let args = self.lower_generic_args_of_path_segment(span, def_id, item_segment);
1215
1216        if let DefKind::TyAlias = tcx.def_kind(def_id)
1217            && tcx.type_alias_is_lazy(def_id)
1218        {
1219            // Type aliases defined in crates that have the
1220            // feature `lazy_type_alias` enabled get encoded as a type alias that normalization will
1221            // then actually instantiate the where bounds of.
1222            let alias_ty = ty::AliasTy::new_from_args(tcx, ty::Free { def_id }, args);
1223            Ty::new_alias(tcx, ty::IsRigid::No, alias_ty)
1224        } else {
1225            tcx.at(span).type_of(def_id).instantiate(tcx, args).skip_norm_wip()
1226        }
1227    }
1228
1229    /// Search for a trait bound on a type parameter whose trait defines the associated item
1230    /// given by `assoc_ident` and `kind`.
1231    ///
1232    /// This fails if there is no such bound in the list of candidates or if there are multiple
1233    /// candidates in which case it reports ambiguity.
1234    ///
1235    /// `ty_param_def_id` is the `LocalDefId` of the type parameter.
1236    x;#[instrument(level = "debug", skip_all, ret)]
1237    fn probe_single_ty_param_bound_for_assoc_item(
1238        &self,
1239        ty_param_def_id: LocalDefId,
1240        ty_param_span: Span,
1241        assoc_tag: ty::AssocTag,
1242        assoc_ident: Ident,
1243        span: Span,
1244    ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1245        debug!(?ty_param_def_id, ?assoc_ident, ?span);
1246        let tcx = self.tcx();
1247
1248        let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_ident);
1249        debug!("predicates={:#?}", predicates);
1250
1251        self.probe_single_bound_for_assoc_item(
1252            || {
1253                let trait_refs = predicates
1254                    .iter_identity_copied()
1255                    .map(Unnormalized::skip_norm_wip)
1256                    .filter_map(|(p, _)| Some(p.as_trait_clause()?.map_bound(|t| t.trait_ref)));
1257                traits::transitive_bounds_that_define_assoc_item(tcx, trait_refs, assoc_ident)
1258            },
1259            AssocItemQSelf::TyParam(ty_param_def_id, ty_param_span),
1260            assoc_tag,
1261            assoc_ident,
1262            span,
1263            None,
1264        )
1265    }
1266
1267    /// When there are multiple traits which contain an identically named
1268    /// associated item, this function eliminates any traits which are a
1269    /// supertrait of another candidate trait.
1270    ///
1271    /// This is the type-level analogue of
1272    /// `rustc_hir_typeck::method::probe::ProbeContext::collapse_candidates_to_subtrait_pick`;
1273    /// keep both implementations in sync.
1274    ///
1275    /// This implements RFC #3624.
1276    fn collapse_candidates_to_subtrait_pick(
1277        &self,
1278        matching_candidates: &[ty::PolyTraitRef<'tcx>],
1279    ) -> Option<ty::PolyTraitRef<'tcx>> {
1280        if !self.tcx().features().supertrait_item_shadowing() {
1281            return None;
1282        }
1283
1284        let mut child_trait = matching_candidates[0];
1285        let mut supertraits: SsoHashSet<_> =
1286            traits::supertrait_def_ids(self.tcx(), child_trait.def_id()).collect();
1287
1288        let mut remaining_candidates: Vec<_> = matching_candidates[1..].iter().copied().collect();
1289        while !remaining_candidates.is_empty() {
1290            let mut made_progress = false;
1291            let mut next_round = ::alloc::vec::Vec::new()vec![];
1292
1293            for remaining_trait in remaining_candidates {
1294                if supertraits.contains(&remaining_trait.def_id()) {
1295                    made_progress = true;
1296                    continue;
1297                }
1298
1299                // This candidate is not a supertrait of the `child_trait`.
1300                // Check if it's a subtrait of the `child_trait`, instead.
1301                // If it is, then it must have been a subtrait of every
1302                // other pick we've eliminated at this point. It will
1303                // take over at this point.
1304                let remaining_trait_supertraits: SsoHashSet<_> =
1305                    traits::supertrait_def_ids(self.tcx(), remaining_trait.def_id()).collect();
1306                if remaining_trait_supertraits.contains(&child_trait.def_id()) {
1307                    child_trait = remaining_trait;
1308                    supertraits = remaining_trait_supertraits;
1309                    made_progress = true;
1310                    continue;
1311                }
1312
1313                // Neither `child_trait` or the current candidate are
1314                // supertraits of each other.
1315                // Don't bail here, since we may be comparing two supertraits
1316                // of a common subtrait. These two supertraits won't be related
1317                // at all, but we will pick them up next round when we find their
1318                // child as we continue iterating in this round.
1319                next_round.push(remaining_trait);
1320            }
1321
1322            if made_progress {
1323                // If we've made progress, iterate again.
1324                remaining_candidates = next_round;
1325            } else {
1326                // Otherwise, we must have at least two candidates which
1327                // are not related to each other at all.
1328                return None;
1329            }
1330        }
1331
1332        Some(child_trait)
1333    }
1334
1335    /// Search for a single trait bound whose trait defines the associated item given by
1336    /// `assoc_ident`.
1337    ///
1338    /// This fails if there is no such bound in the list of candidates or if there are multiple
1339    /// candidates in which case it reports ambiguity.
1340    x;#[instrument(level = "debug", skip(self, all_candidates, qself, constraint), ret)]
1341    fn probe_single_bound_for_assoc_item<I>(
1342        &self,
1343        all_candidates: impl Fn() -> I,
1344        qself: AssocItemQSelf,
1345        assoc_tag: ty::AssocTag,
1346        assoc_ident: Ident,
1347        span: Span,
1348        constraint: Option<&hir::AssocItemConstraint<'tcx>>,
1349    ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1350    where
1351        I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1352    {
1353        let mut matching_candidates = all_candidates().filter(|r| {
1354            self.probe_trait_that_defines_assoc_item(r.def_id(), assoc_tag, assoc_ident)
1355        });
1356
1357        let Some(bound1) = matching_candidates.next() else {
1358            return Err(self.report_unresolved_assoc_item(
1359                all_candidates,
1360                qself,
1361                assoc_tag,
1362                assoc_ident,
1363                span,
1364                constraint,
1365            ));
1366        };
1367
1368        if let Some(bound2) = matching_candidates.next() {
1369            let all_matching_candidates: Vec<_> =
1370                [bound1, bound2].into_iter().chain(matching_candidates).collect();
1371            if let Some(bound) = self.collapse_candidates_to_subtrait_pick(&all_matching_candidates)
1372            {
1373                return Ok(bound);
1374            }
1375
1376            return Err(self.report_ambiguous_assoc_item(
1377                &all_matching_candidates,
1378                qself,
1379                assoc_tag,
1380                assoc_ident,
1381                span,
1382                constraint,
1383            ));
1384        }
1385
1386        Ok(bound1)
1387    }
1388
1389    /// Lower a [type-relative](hir::QPath::TypeRelative) path in type position to a type.
1390    ///
1391    /// If the path refers to an enum variant and `permit_variants` holds,
1392    /// the returned type is simply the provided self type `qself_ty`.
1393    ///
1394    /// A path like `A::B::C::D` is understood as `<A::B::C>::D`. I.e.,
1395    /// `qself_ty` / `qself` is `A::B::C` and `assoc_segment` is `D`.
1396    /// We return the lowered type and the `DefId` for the whole path.
1397    ///
1398    /// We only support associated type paths whose self type is a type parameter or a `Self`
1399    /// type alias (in a trait impl) like `T::Ty` (where `T` is a ty param) or `Self::Ty`.
1400    /// We **don't** support paths whose self type is an arbitrary type like `Struct::Ty` where
1401    /// struct `Struct` impls an in-scope trait that defines an associated type called `Ty`.
1402    /// For the latter case, we report ambiguity.
1403    /// While desirable to support, the implementation would be non-trivial. Tracked in [#22519].
1404    ///
1405    /// At the time of writing, *inherent associated types* are also resolved here. This however
1406    /// is [problematic][iat]. A proper implementation would be as non-trivial as the one
1407    /// described in the previous paragraph and their modeling of projections would likely be
1408    /// very similar in nature.
1409    ///
1410    /// [#22519]: https://github.com/rust-lang/rust/issues/22519
1411    /// [iat]: https://github.com/rust-lang/rust/issues/8995#issuecomment-1569208403
1412    //
1413    // NOTE: When this function starts resolving `Trait::AssocTy` successfully
1414    // it should also start reporting the `BARE_TRAIT_OBJECTS` lint.
1415    x;#[instrument(level = "debug", skip_all, ret)]
1416    pub fn lower_type_relative_ty_path(
1417        &self,
1418        self_ty: Ty<'tcx>,
1419        hir_self_ty: &'tcx hir::Ty<'tcx>,
1420        segment: &'tcx hir::PathSegment<'tcx>,
1421        qpath_hir_id: HirId,
1422        span: Span,
1423        permit_variants: PermitVariants,
1424    ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1425        let tcx = self.tcx();
1426        match self.lower_type_relative_path(
1427            self_ty,
1428            hir_self_ty,
1429            segment,
1430            qpath_hir_id,
1431            span,
1432            LowerTypeRelativePathMode::Type(permit_variants),
1433        )? {
1434            TypeRelativePath::AssocItem(alias_term) => {
1435                let alias_ty = alias_term.expect_ty();
1436                let def_id = match alias_ty.kind {
1437                    ty::AliasTyKind::Projection { def_id } => def_id,
1438                    ty::AliasTyKind::Inherent { def_id } => def_id,
1439                    kind => bug!("expected projection or inherent alias, got {kind:?}"),
1440                };
1441                let ty = alias_ty.to_ty(tcx, ty::IsRigid::No);
1442                let ty = self.check_param_uses_if_mcg(ty, span, false);
1443                Ok((ty, tcx.def_kind(def_id), def_id))
1444            }
1445            TypeRelativePath::Variant { adt, variant_did } => {
1446                let adt = self.check_param_uses_if_mcg(adt, span, false);
1447                Ok((adt, DefKind::Variant, variant_did))
1448            }
1449            TypeRelativePath::Ctor { .. } => {
1450                let e = tcx.dcx().span_err(span, "expected type, found tuple constructor");
1451                Err(e)
1452            }
1453        }
1454    }
1455
1456    /// Lower a [type-relative][hir::QPath::TypeRelative] path to a (type-level) constant.
1457    x;#[instrument(level = "debug", skip_all, ret)]
1458    fn lower_type_relative_const_path(
1459        &self,
1460        self_ty: Ty<'tcx>,
1461        hir_self_ty: &'tcx hir::Ty<'tcx>,
1462        segment: &'tcx hir::PathSegment<'tcx>,
1463        qpath_hir_id: HirId,
1464        span: Span,
1465    ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1466        let tcx = self.tcx();
1467        match self.lower_type_relative_path(
1468            self_ty,
1469            hir_self_ty,
1470            segment,
1471            qpath_hir_id,
1472            span,
1473            LowerTypeRelativePathMode::Const,
1474        )? {
1475            TypeRelativePath::AssocItem(alias_term) => {
1476                let alias_ct = alias_term.expect_ct();
1477                if let Some(def_id) = alias_ct.kind.opt_def_id() {
1478                    self.require_type_const_attribute(def_id, span)?;
1479                }
1480                let ct = Const::new_alias(tcx, ty::IsRigid::No, alias_ct);
1481                let ct = self.check_param_uses_if_mcg(ct, span, false);
1482                Ok(ct)
1483            }
1484            TypeRelativePath::Ctor { ctor_def_id, args } => match tcx.def_kind(ctor_def_id) {
1485                DefKind::Ctor(_, CtorKind::Fn) => {
1486                    Ok(ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, ctor_def_id, args)))
1487                }
1488                DefKind::Ctor(ctor_of, CtorKind::Const) => {
1489                    Ok(self.construct_const_ctor_value(ctor_def_id, ctor_of, args))
1490                }
1491                _ => unreachable!(),
1492            },
1493            // FIXME(mgca): implement support for this once ready to support all adt ctor expressions,
1494            // not just const ctors
1495            TypeRelativePath::Variant { .. } => {
1496                span_bug!(span, "unexpected variant res for type associated const path")
1497            }
1498        }
1499    }
1500
1501    /// Lower a [type-relative][hir::QPath::TypeRelative] (and type-level) path.
1502    x;#[instrument(level = "debug", skip_all, ret)]
1503    fn lower_type_relative_path(
1504        &self,
1505        self_ty: Ty<'tcx>,
1506        hir_self_ty: &'tcx hir::Ty<'tcx>,
1507        segment: &'tcx hir::PathSegment<'tcx>,
1508        qpath_hir_id: HirId,
1509        span: Span,
1510        mode: LowerTypeRelativePathMode,
1511    ) -> Result<TypeRelativePath<'tcx>, ErrorGuaranteed> {
1512        debug!(%self_ty, ?segment.ident);
1513        let tcx = self.tcx();
1514
1515        // Check if we have an enum variant or an inherent associated type.
1516        let mut variant_def_id = None;
1517        if let Some(adt_def) = self.probe_adt(span, self_ty) {
1518            if adt_def.is_enum() {
1519                let variant_def = adt_def
1520                    .variants()
1521                    .iter()
1522                    .find(|vd| tcx.hygienic_eq(segment.ident, vd.ident(tcx), adt_def.did()));
1523                if let Some(variant_def) = variant_def {
1524                    // FIXME(mgca): do we want constructor resolutions to take priority over
1525                    // other possible resolutions?
1526                    if matches!(mode, LowerTypeRelativePathMode::Const)
1527                        && let Some((_, ctor_def_id)) = variant_def.ctor
1528                    {
1529                        tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1530                        let _ = self.prohibit_generic_args(
1531                            slice::from_ref(segment).iter(),
1532                            GenericsArgsErrExtend::EnumVariant {
1533                                qself: hir_self_ty,
1534                                assoc_segment: segment,
1535                                adt_def,
1536                            },
1537                        );
1538                        let ty::Adt(_, enum_args) = self_ty.kind() else { unreachable!() };
1539                        return Ok(TypeRelativePath::Ctor { ctor_def_id, args: enum_args });
1540                    }
1541                    if let PermitVariants::Yes = mode.permit_variants() {
1542                        tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1543                        let _ = self.prohibit_generic_args(
1544                            slice::from_ref(segment).iter(),
1545                            GenericsArgsErrExtend::EnumVariant {
1546                                qself: hir_self_ty,
1547                                assoc_segment: segment,
1548                                adt_def,
1549                            },
1550                        );
1551                        return Ok(TypeRelativePath::Variant {
1552                            adt: self_ty,
1553                            variant_did: variant_def.def_id,
1554                        });
1555                    } else {
1556                        variant_def_id = Some(variant_def.def_id);
1557                    }
1558                }
1559            }
1560
1561            // FIXME(inherent_associated_types, #106719): Support self types other than ADTs.
1562            if let Some(alias_term) = self.probe_inherent_assoc_item(
1563                segment,
1564                adt_def.did(),
1565                self_ty,
1566                qpath_hir_id,
1567                span,
1568                mode.assoc_tag(),
1569            )? {
1570                return Ok(TypeRelativePath::AssocItem(alias_term));
1571            }
1572        }
1573
1574        let (item_def_id, bound) = self.resolve_type_relative_path(
1575            self_ty,
1576            hir_self_ty,
1577            mode.assoc_tag(),
1578            segment,
1579            qpath_hir_id,
1580            span,
1581            variant_def_id,
1582        )?;
1583
1584        let (item_def_id, args) = self.lower_assoc_item_path(span, item_def_id, segment, bound)?;
1585
1586        if let Some(variant_def_id) = variant_def_id {
1587            tcx.emit_node_span_lint(
1588                AMBIGUOUS_ASSOCIATED_ITEMS,
1589                qpath_hir_id,
1590                span,
1591                errors::AmbiguityBetweenVariantAndAssocItem {
1592                    variant_def_id,
1593                    item_def_id,
1594                    span,
1595                    segment_ident: segment.ident,
1596                    bound_def_id: bound.def_id(),
1597                    self_ty,
1598                    tcx,
1599                    mode,
1600                },
1601            );
1602        }
1603
1604        Ok(TypeRelativePath::AssocItem(ty::AliasTerm::new_from_def_id(tcx, item_def_id, args)))
1605    }
1606
1607    /// Resolve a [type-relative](hir::QPath::TypeRelative) (and type-level) path.
1608    fn resolve_type_relative_path(
1609        &self,
1610        self_ty: Ty<'tcx>,
1611        hir_self_ty: &'tcx hir::Ty<'tcx>,
1612        assoc_tag: ty::AssocTag,
1613        segment: &'tcx hir::PathSegment<'tcx>,
1614        qpath_hir_id: HirId,
1615        span: Span,
1616        variant_def_id: Option<DefId>,
1617    ) -> Result<(DefId, ty::PolyTraitRef<'tcx>), ErrorGuaranteed> {
1618        let tcx = self.tcx();
1619
1620        let self_ty_res = match hir_self_ty.kind {
1621            hir::TyKind::Path(hir::QPath::Resolved(_, path)) => path.res,
1622            _ => Res::Err,
1623        };
1624
1625        // Find the type of the assoc item, and the trait where the associated item is declared.
1626        let bound = match (self_ty.kind(), self_ty_res) {
1627            (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
1628                // `Self` in an impl of a trait -- we have a concrete self type and a
1629                // trait reference.
1630                let trait_ref = tcx.impl_trait_ref(impl_def_id);
1631
1632                self.probe_single_bound_for_assoc_item(
1633                    || {
1634                        let trait_ref =
1635                            ty::Binder::dummy(trait_ref.instantiate_identity().skip_norm_wip());
1636                        traits::supertraits(tcx, trait_ref)
1637                    },
1638                    AssocItemQSelf::SelfTyAlias,
1639                    assoc_tag,
1640                    segment.ident,
1641                    span,
1642                    None,
1643                )?
1644            }
1645            (
1646                &ty::Param(_),
1647                Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
1648            ) => self.probe_single_ty_param_bound_for_assoc_item(
1649                param_did.expect_local(),
1650                hir_self_ty.span,
1651                assoc_tag,
1652                segment.ident,
1653                span,
1654            )?,
1655            _ => {
1656                return Err(self.report_unresolved_type_relative_path(
1657                    self_ty,
1658                    hir_self_ty,
1659                    assoc_tag,
1660                    segment.ident,
1661                    qpath_hir_id,
1662                    span,
1663                    variant_def_id,
1664                ));
1665            }
1666        };
1667
1668        let assoc_item = self
1669            .probe_assoc_item(segment.ident, assoc_tag, qpath_hir_id, span, bound.def_id())
1670            .expect("failed to find associated item");
1671
1672        Ok((assoc_item.def_id, bound))
1673    }
1674
1675    /// Search for inherent associated items for use at the type level.
1676    fn probe_inherent_assoc_item(
1677        &self,
1678        segment: &hir::PathSegment<'tcx>,
1679        adt_did: DefId,
1680        self_ty: Ty<'tcx>,
1681        block: HirId,
1682        span: Span,
1683        assoc_tag: ty::AssocTag,
1684    ) -> Result<Option<ty::AliasTerm<'tcx>>, ErrorGuaranteed> {
1685        let tcx = self.tcx();
1686
1687        if !tcx.features().inherent_associated_types() {
1688            match assoc_tag {
1689                // Don't attempt to look up inherent associated types when the feature is not
1690                // enabled. Theoretically it'd be fine to do so since we feature-gate their
1691                // definition site. However, the current implementation of inherent associated
1692                // items is somewhat brittle, so let's not run it by default.
1693                ty::AssocTag::Type => return Ok(None),
1694                ty::AssocTag::Const => {
1695                    // We also gate the mgca codepath for type-level uses of inherent consts
1696                    // with the inherent_associated_types feature gate since it relies on the
1697                    // same machinery and has similar rough edges.
1698                    return Err(feature_err(
1699                        &tcx.sess,
1700                        sym::inherent_associated_types,
1701                        span,
1702                        "inherent associated types are unstable",
1703                    )
1704                    .emit());
1705                }
1706                ty::AssocTag::Fn => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1707            }
1708        }
1709
1710        let name = segment.ident;
1711        let candidates: Vec<_> = tcx
1712            .inherent_impls(adt_did)
1713            .iter()
1714            .filter_map(|&impl_| {
1715                let (item, scope) = self.probe_assoc_item_unchecked(name, assoc_tag, impl_)?;
1716                Some(InherentAssocCandidate { impl_, assoc_item: item.def_id, scope })
1717            })
1718            .collect();
1719
1720        // At the moment, we actually bail out with a hard error if the selection of an inherent
1721        // associated item fails (see below). This means we never consider trait associated items
1722        // as potential fallback candidates (#142006). To temporarily mask that issue, let's not
1723        // select at all if there are no early inherent candidates.
1724        if candidates.is_empty() {
1725            return Ok(None);
1726        }
1727
1728        let (applicable_candidates, fulfillment_errors) =
1729            self.select_inherent_assoc_candidates(span, self_ty, candidates.clone());
1730
1731        // FIXME(#142006): Don't eagerly error here, there might be applicable trait candidates.
1732        let InherentAssocCandidate { impl_, assoc_item, scope: def_scope } =
1733            match &applicable_candidates[..] {
1734                &[] => Err(self.report_unresolved_inherent_assoc_item(
1735                    name,
1736                    self_ty,
1737                    candidates,
1738                    fulfillment_errors,
1739                    span,
1740                    assoc_tag,
1741                )),
1742
1743                &[applicable_candidate] => Ok(applicable_candidate),
1744
1745                &[_, ..] => Err(self.report_ambiguous_inherent_assoc_item(
1746                    name,
1747                    candidates.into_iter().map(|cand| cand.assoc_item).collect(),
1748                    span,
1749                )),
1750            }?;
1751
1752        // FIXME(#142006): Don't eagerly validate here, there might be trait candidates that are
1753        // accessible (visible and stable) contrary to the inherent candidate.
1754        self.check_assoc_item(assoc_item, name, def_scope, block, span);
1755
1756        // FIXME(fmease): Currently creating throwaway `parent_args` to please
1757        // `lower_generic_args_of_assoc_item`. Modify the latter instead (or sth. similar) to
1758        // not require the parent args logic.
1759        let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
1760        let args = self.lower_generic_args_of_assoc_item(span, assoc_item, segment, parent_args);
1761        let args = tcx.mk_args_from_iter(
1762            std::iter::once(ty::GenericArg::from(self_ty))
1763                .chain(args.into_iter().skip(parent_args.len())),
1764        );
1765
1766        let kind = match assoc_tag {
1767            ty::AssocTag::Type => ty::AliasTermKind::InherentTy { def_id: assoc_item },
1768            ty::AssocTag::Const => {
1769                // FIXME(mgca): drop once `InherentConst` accepts IAC-shaped args (issue #156181)
1770                // without this, `new_from_args` errors (#155341).
1771                self.require_type_const_attribute(assoc_item, span)?;
1772                ty::AliasTermKind::InherentConst { def_id: assoc_item }
1773            }
1774            ty::AssocTag::Fn => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1775        };
1776
1777        Ok(Some(ty::AliasTerm::new_from_args(tcx, kind, args)))
1778    }
1779
1780    /// Given name and kind search for the assoc item in the provided scope and check if it's accessible[^1].
1781    ///
1782    /// [^1]: I.e., accessible in the provided scope wrt. visibility and stability.
1783    fn probe_assoc_item(
1784        &self,
1785        ident: Ident,
1786        assoc_tag: ty::AssocTag,
1787        block: HirId,
1788        span: Span,
1789        scope: DefId,
1790    ) -> Option<ty::AssocItem> {
1791        let (item, scope) = self.probe_assoc_item_unchecked(ident, assoc_tag, scope)?;
1792        self.check_assoc_item(item.def_id, ident, scope, block, span);
1793        Some(item)
1794    }
1795
1796    /// Given name and kind search for the assoc item in the provided scope
1797    /// *without* checking if it's accessible[^1].
1798    ///
1799    /// [^1]: I.e., accessible in the provided scope wrt. visibility and stability.
1800    fn probe_assoc_item_unchecked(
1801        &self,
1802        ident: Ident,
1803        assoc_tag: ty::AssocTag,
1804        scope: DefId,
1805    ) -> Option<(ty::AssocItem, /*scope*/ DefId)> {
1806        let tcx = self.tcx();
1807
1808        let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, self.item_def_id());
1809        // We have already adjusted the item name above, so compare with `.normalize_to_macros_2_0()`
1810        // instead of calling `filter_by_name_and_kind` which would needlessly normalize the
1811        // `ident` again and again.
1812        let item = tcx
1813            .associated_items(scope)
1814            .filter_by_name_unhygienic(ident.name)
1815            .find(|i| i.tag() == assoc_tag && i.ident(tcx).normalize_to_macros_2_0() == ident)?;
1816
1817        Some((*item, def_scope))
1818    }
1819
1820    /// Check if the given assoc item is accessible in the provided scope wrt. visibility and stability.
1821    fn check_assoc_item(
1822        &self,
1823        item_def_id: DefId,
1824        ident: Ident,
1825        scope: DefId,
1826        block: HirId,
1827        span: Span,
1828    ) {
1829        let tcx = self.tcx();
1830
1831        if !tcx.visibility(item_def_id).is_accessible_from(scope, tcx) {
1832            self.dcx().emit_err(crate::diagnostics::AssocItemIsPrivate {
1833                span,
1834                kind: tcx.def_descr(item_def_id),
1835                name: ident,
1836                defined_here_label: tcx.def_span(item_def_id),
1837            });
1838        }
1839
1840        tcx.check_stability(item_def_id, Some(block), span, None);
1841    }
1842
1843    fn probe_traits_that_match_assoc_ty(
1844        &self,
1845        qself_ty: Ty<'tcx>,
1846        assoc_ident: Ident,
1847    ) -> Vec<String> {
1848        let tcx = self.tcx();
1849
1850        // In contexts that have no inference context, just make a new one.
1851        // We do need a local variable to store it, though.
1852        let infcx_;
1853        let infcx = if let Some(infcx) = self.infcx() {
1854            infcx
1855        } else {
1856            if !!qself_ty.has_infer() {
    ::core::panicking::panic("assertion failed: !qself_ty.has_infer()")
};assert!(!qself_ty.has_infer());
1857            infcx_ = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1858            &infcx_
1859        };
1860
1861        tcx.all_traits_including_private()
1862            .filter(|trait_def_id| {
1863                // Consider only traits with the associated type
1864                tcx.associated_items(*trait_def_id)
1865                        .in_definition_order()
1866                        .any(|i| {
1867                            i.is_type()
1868                                && !i.is_impl_trait_in_trait()
1869                                && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1870                        })
1871                    // Consider only accessible traits
1872                    && tcx.visibility(*trait_def_id)
1873                        .is_accessible_from(self.item_def_id(), tcx)
1874                    && tcx.all_impls(*trait_def_id)
1875                        .any(|impl_def_id| {
1876                            let header = tcx.impl_trait_header(impl_def_id);
1877                            let trait_ref = header.trait_ref.instantiate(tcx, infcx.fresh_args_for_item(DUMMY_SP, impl_def_id)).skip_norm_wip();
1878
1879                            let value = fold_regions(tcx, qself_ty, |_, _| tcx.lifetimes.re_erased);
1880                            // FIXME: Don't bother dealing with non-lifetime binders here...
1881                            if value.has_escaping_bound_vars() {
1882                                return false;
1883                            }
1884                            infcx
1885                                .can_eq(
1886                                    ty::ParamEnv::empty(),
1887                                    trait_ref.self_ty(),
1888                                    value,
1889                                ) && header.polarity != ty::ImplPolarity::Negative
1890                        })
1891            })
1892            .map(|trait_def_id| tcx.def_path_str(trait_def_id))
1893            .collect()
1894    }
1895
1896    /// Lower a [resolved][hir::QPath::Resolved] associated type path to a projection.
1897    #[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(1897u32),
                                    ::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(), ty::IsRigid::No,
                        item_def_id, item_args)
                }
                Err(guar) => Ty::new_error(self.tcx(), guar),
            }
        }
    }
}#[instrument(level = "debug", skip_all)]
1898    fn lower_resolved_assoc_ty_path(
1899        &self,
1900        span: Span,
1901        opt_self_ty: Option<Ty<'tcx>>,
1902        item_def_id: DefId,
1903        trait_segment: Option<&hir::PathSegment<'tcx>>,
1904        item_segment: &hir::PathSegment<'tcx>,
1905    ) -> Ty<'tcx> {
1906        match self.lower_resolved_assoc_item_path(
1907            span,
1908            opt_self_ty,
1909            item_def_id,
1910            trait_segment,
1911            item_segment,
1912            ty::AssocTag::Type,
1913        ) {
1914            Ok((item_def_id, item_args)) => {
1915                Ty::new_projection_from_args(self.tcx(), ty::IsRigid::No, item_def_id, item_args)
1916            }
1917            Err(guar) => Ty::new_error(self.tcx(), guar),
1918        }
1919    }
1920
1921    /// Lower a [resolved][hir::QPath::Resolved] associated const path to a (type-level) constant.
1922    #[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(1922u32),
                                    ::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 tcx = self.tcx();
            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 alias_const =
                ty::AliasConst::new(tcx,
                    ty::AliasConstKind::new_from_def_id(tcx, item_def_id),
                    item_args);
            Ok(Const::new_alias(tcx, ty::IsRigid::No, alias_const))
        }
    }
}#[instrument(level = "debug", skip_all)]
1923    fn lower_resolved_assoc_const_path(
1924        &self,
1925        span: Span,
1926        opt_self_ty: Option<Ty<'tcx>>,
1927        item_def_id: DefId,
1928        trait_segment: Option<&hir::PathSegment<'tcx>>,
1929        item_segment: &hir::PathSegment<'tcx>,
1930    ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1931        let tcx = self.tcx();
1932        let (item_def_id, item_args) = self.lower_resolved_assoc_item_path(
1933            span,
1934            opt_self_ty,
1935            item_def_id,
1936            trait_segment,
1937            item_segment,
1938            ty::AssocTag::Const,
1939        )?;
1940        self.require_type_const_attribute(item_def_id, span)?;
1941        let alias_const = ty::AliasConst::new(
1942            tcx,
1943            ty::AliasConstKind::new_from_def_id(tcx, item_def_id),
1944            item_args,
1945        );
1946        Ok(Const::new_alias(tcx, ty::IsRigid::No, alias_const))
1947    }
1948
1949    /// Lower a [resolved][hir::QPath::Resolved] (type-level) associated item path.
1950    #[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(1950u32),
                                    ::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:1963",
                                    "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(1963u32),
                                    ::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:1973",
                                    "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(1973u32),
                                    ::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:1977",
                                    "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(1977u32),
                                    ::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)]
1951    fn lower_resolved_assoc_item_path(
1952        &self,
1953        span: Span,
1954        opt_self_ty: Option<Ty<'tcx>>,
1955        item_def_id: DefId,
1956        trait_segment: Option<&hir::PathSegment<'tcx>>,
1957        item_segment: &hir::PathSegment<'tcx>,
1958        assoc_tag: ty::AssocTag,
1959    ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> {
1960        let tcx = self.tcx();
1961
1962        let trait_def_id = tcx.parent(item_def_id);
1963        debug!(?trait_def_id);
1964
1965        let Some(self_ty) = opt_self_ty else {
1966            return Err(self.report_missing_self_ty_for_resolved_path(
1967                trait_def_id,
1968                span,
1969                item_segment,
1970                assoc_tag,
1971            ));
1972        };
1973        debug!(?self_ty);
1974
1975        let trait_ref =
1976            self.lower_mono_trait_ref(span, trait_def_id, self_ty, trait_segment.unwrap(), false);
1977        debug!(?trait_ref);
1978
1979        let item_args =
1980            self.lower_generic_args_of_assoc_item(span, item_def_id, item_segment, trait_ref.args);
1981
1982        Ok((item_def_id, item_args))
1983    }
1984
1985    pub fn prohibit_generic_args<'a>(
1986        &self,
1987        segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
1988        err_extend: GenericsArgsErrExtend<'a>,
1989    ) -> Result<(), ErrorGuaranteed> {
1990        let args_visitors = segments.clone().flat_map(|segment| segment.args().args);
1991        let mut result = Ok(());
1992        if let Some(_) = args_visitors.clone().next() {
1993            result = Err(self.report_prohibited_generic_args(
1994                segments.clone(),
1995                args_visitors,
1996                err_extend,
1997            ));
1998        }
1999
2000        for segment in segments {
2001            // Only emit the first error to avoid overloading the user with error messages.
2002            if let Some(c) = segment.args().constraints.first() {
2003                return Err(prohibit_assoc_item_constraint(self, c, None));
2004            }
2005        }
2006
2007        result
2008    }
2009
2010    /// Probe path segments that are semantically allowed to have generic arguments.
2011    ///
2012    /// ### Example
2013    ///
2014    /// ```ignore (illustrative)
2015    ///    Option::None::<()>
2016    /// //         ^^^^ permitted to have generic args
2017    ///
2018    /// // ==> [GenericPathSegment(Option_def_id, 1)]
2019    ///
2020    ///    Option::<()>::None
2021    /// // ^^^^^^        ^^^^ *not* permitted to have generic args
2022    /// // permitted to have generic args
2023    ///
2024    /// // ==> [GenericPathSegment(Option_def_id, 0)]
2025    /// ```
2026    // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2027    pub fn probe_generic_path_segments(
2028        &self,
2029        segments: &[hir::PathSegment<'_>],
2030        self_ty: Option<Ty<'tcx>>,
2031        kind: DefKind,
2032        def_id: DefId,
2033        span: Span,
2034    ) -> Vec<GenericPathSegment> {
2035        // We need to extract the generic arguments supplied by the user in
2036        // the path `path`. Due to the current setup, this is a bit of a
2037        // tricky process; the problem is that resolve only tells us the
2038        // end-point of the path resolution, and not the intermediate steps.
2039        // Luckily, we can (at least for now) deduce the intermediate steps
2040        // just from the end-point.
2041        //
2042        // There are basically five cases to consider:
2043        //
2044        // 1. Reference to a constructor of a struct:
2045        //
2046        //        struct Foo<T>(...)
2047        //
2048        //    In this case, the generic arguments are declared in the type space.
2049        //
2050        // 2. Reference to a constructor of an enum variant:
2051        //
2052        //        enum E<T> { Foo(...) }
2053        //
2054        //    In this case, the generic arguments are defined in the type space,
2055        //    but may be specified either on the type or the variant.
2056        //
2057        // 3. Reference to a free function or constant:
2058        //
2059        //        fn foo<T>() {}
2060        //
2061        //    In this case, the path will again always have the form
2062        //    `a::b::foo::<T>` where only the final segment should have generic
2063        //    arguments. However, in this case, those arguments are declared on
2064        //    a value, and hence are in the value space.
2065        //
2066        // 4. Reference to an associated function or constant:
2067        //
2068        //        impl<A> SomeStruct<A> {
2069        //            fn foo<B>(...) {}
2070        //        }
2071        //
2072        //    Here we can have a path like `a::b::SomeStruct::<A>::foo::<B>`,
2073        //    in which case generic arguments may appear in two places. The
2074        //    penultimate segment, `SomeStruct::<A>`, contains generic arguments
2075        //    in the type space, and the final segment, `foo::<B>` contains
2076        //    generic arguments in value space.
2077        //
2078        // The first step then is to categorize the segments appropriately.
2079
2080        let tcx = self.tcx();
2081
2082        if !!segments.is_empty() {
    ::core::panicking::panic("assertion failed: !segments.is_empty()")
};assert!(!segments.is_empty());
2083        let last = segments.len() - 1;
2084
2085        let mut generic_segments = ::alloc::vec::Vec::new()vec![];
2086
2087        match kind {
2088            // Case 1. Reference to a struct constructor.
2089            DefKind::Ctor(CtorOf::Struct, ..) => {
2090                // Everything but the final segment should have no
2091                // parameters at all.
2092                let generics = tcx.generics_of(def_id);
2093                // Variant and struct constructors use the
2094                // generics of their parent type definition.
2095                let generics_def_id = generics.parent.unwrap_or(def_id);
2096                generic_segments.push(GenericPathSegment(generics_def_id, last));
2097            }
2098
2099            // Case 2. Reference to a variant constructor.
2100            DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2101                let (generics_def_id, index) = if let Some(self_ty) = self_ty {
2102                    // We have something like `<module::Enum>::Variant`.
2103
2104                    let adt_def = self.probe_adt(span, self_ty).unwrap();
2105                    if true {
    if !adt_def.is_enum() {
        ::core::panicking::panic("assertion failed: adt_def.is_enum()")
    };
};debug_assert!(adt_def.is_enum());
2106
2107                    // FIXME: Stating that the last segment (here: `Variant`) is allowed to have
2108                    // generic args is a lie! We should set the index to `None` instead as it's
2109                    // the *self type* that's allowed to have args.
2110                    // HIR typeck's `instantiate_value_path` actually contains a special case to
2111                    // reject args on `DefKind::Ctor` segments (see `is_alias_variant_ctor`).
2112                    // Using `None` here for this should allow us to get rid of that workaround.
2113                    //
2114                    // (For additional context, `DefKind::Variant` segments never actually reach
2115                    // this branch as they're interpreted as `TypeRelative` paths whose lowering
2116                    // routines manually reject args on them).
2117
2118                    (adt_def.did(), last)
2119                } else if let [.., second_to_last, _] = segments
2120                    && second_to_last.args.is_some()
2121                    && let Res::Def(DefKind::Enum, _) = second_to_last.res
2122                {
2123                    // We have something like `module::Enum::<…>::Variant`.
2124                    // No segment other than the penultimate one is allowed to have generic args.
2125
2126                    // We had to check that the second to last segment actually referred to an enum
2127                    // since at this stage it could very well refer to a module in which case we
2128                    // certainly don't want to allow generic args on it!
2129
2130                    // `DefKind::Ctor` -> `DefKind::Variant`
2131                    let def_id = match kind {
2132                        DefKind::Ctor(..) => tcx.parent(def_id),
2133                        _ => def_id,
2134                    };
2135
2136                    // `DefKind::Variant` -> `DefKind::Enum`
2137                    let enum_def_id = tcx.parent(def_id);
2138
2139                    (enum_def_id, last - 1)
2140                } else {
2141                    // We have something like `module::Enum::Variant` or `module::Variant`.
2142                    // No segment other than the final one is allowed to have generic args.
2143
2144                    // FIXME: lint here recommending `Enum::<...>::Variant` form
2145                    // instead of `Enum::Variant::<...>` form.
2146
2147                    let generics = tcx.generics_of(def_id);
2148                    // Variant and struct constructors use the
2149                    // generics of their parent type definition.
2150                    (generics.parent.unwrap_or(def_id), last)
2151                };
2152                generic_segments.push(GenericPathSegment(generics_def_id, index));
2153            }
2154
2155            // Case 3. Reference to a top-level value.
2156            DefKind::Fn | DefKind::Const { .. } | DefKind::ConstParam | DefKind::Static { .. } => {
2157                generic_segments.push(GenericPathSegment(def_id, last));
2158            }
2159
2160            // Case 4. Reference to a method or associated const.
2161            DefKind::AssocFn | DefKind::AssocConst { .. } => {
2162                if segments.len() >= 2 {
2163                    let generics = tcx.generics_of(def_id);
2164                    generic_segments.push(GenericPathSegment(generics.parent.unwrap(), last - 1));
2165                }
2166                generic_segments.push(GenericPathSegment(def_id, last));
2167            }
2168
2169            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),
2170        }
2171
2172        {
    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:2172",
                        "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(2172u32),
                        ::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);
2173
2174        generic_segments
2175    }
2176
2177    /// Lower a [resolved][hir::QPath::Resolved] path to a type.
2178    #[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(2178u32),
                                    ::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:2186",
                                    "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(2186u32),
                                    ::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, ty::IsRigid::No, 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().skip_norm_wip();
                    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)]
2179    pub fn lower_resolved_ty_path(
2180        &self,
2181        opt_self_ty: Option<Ty<'tcx>>,
2182        path: &hir::Path<'tcx>,
2183        hir_id: HirId,
2184        permit_variants: PermitVariants,
2185    ) -> Ty<'tcx> {
2186        debug!(?path.res, ?opt_self_ty, ?path.segments);
2187        let tcx = self.tcx();
2188
2189        let span = path.span;
2190        match path.res {
2191            Res::Def(DefKind::OpaqueTy, did) => {
2192                // Check for desugared `impl Trait`.
2193                assert_matches!(tcx.opaque_ty_origin(did), hir::OpaqueTyOrigin::TyAlias { .. });
2194                let [leading_segments @ .., segment] = path.segments else { bug!() };
2195                let _ = self.prohibit_generic_args(
2196                    leading_segments.iter(),
2197                    GenericsArgsErrExtend::OpaqueTy,
2198                );
2199                let args = self.lower_generic_args_of_path_segment(span, did, segment);
2200                Ty::new_opaque(tcx, ty::IsRigid::No, did, args)
2201            }
2202            Res::Def(
2203                DefKind::Enum
2204                | DefKind::TyAlias
2205                | DefKind::Struct
2206                | DefKind::Union
2207                | DefKind::ForeignTy,
2208                did,
2209            ) => {
2210                assert_eq!(opt_self_ty, None);
2211                let [leading_segments @ .., segment] = path.segments else { bug!() };
2212                let _ = self
2213                    .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2214                self.lower_path_segment(span, did, segment)
2215            }
2216            Res::Def(kind @ DefKind::Variant, def_id)
2217                if let PermitVariants::Yes = permit_variants =>
2218            {
2219                // Lower "variant type" as if it were a real type.
2220                // The resulting `Ty` is type of the variant's enum for now.
2221                assert_eq!(opt_self_ty, None);
2222
2223                let generic_segments =
2224                    self.probe_generic_path_segments(path.segments, None, kind, def_id, span);
2225                let indices: FxHashSet<_> =
2226                    generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2227                let _ = self.prohibit_generic_args(
2228                    path.segments.iter().enumerate().filter_map(|(index, seg)| {
2229                        if !indices.contains(&index) { Some(seg) } else { None }
2230                    }),
2231                    GenericsArgsErrExtend::DefVariant(&path.segments),
2232                );
2233
2234                let &GenericPathSegment(def_id, index) = generic_segments.last().unwrap();
2235                self.lower_path_segment(span, def_id, &path.segments[index])
2236            }
2237            Res::Def(DefKind::TyParam, def_id) => {
2238                assert_eq!(opt_self_ty, None);
2239                let _ = self.prohibit_generic_args(
2240                    path.segments.iter(),
2241                    GenericsArgsErrExtend::Param(def_id),
2242                );
2243                self.lower_ty_param(hir_id)
2244            }
2245            Res::SelfTyParam { .. } => {
2246                // `Self` in trait or type alias.
2247                assert_eq!(opt_self_ty, None);
2248                let _ = self.prohibit_generic_args(
2249                    path.segments.iter(),
2250                    if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments {
2251                        GenericsArgsErrExtend::SelfTyParam(
2252                            ident.span.shrink_to_hi().to(args.span_ext),
2253                        )
2254                    } else {
2255                        GenericsArgsErrExtend::None
2256                    },
2257                );
2258                self.check_param_uses_if_mcg(tcx.types.self_param, span, false)
2259            }
2260            Res::SelfTyAlias { alias_to: def_id, .. } => {
2261                // `Self` in impl (we know the concrete type).
2262                assert_eq!(opt_self_ty, None);
2263                // Try to evaluate any array length constants.
2264                let ty = tcx.at(span).type_of(def_id).instantiate_identity().skip_norm_wip();
2265                let _ = self.prohibit_generic_args(
2266                    path.segments.iter(),
2267                    GenericsArgsErrExtend::SelfTyAlias { def_id, span },
2268                );
2269                self.check_param_uses_if_mcg(ty, span, true)
2270            }
2271            Res::Def(DefKind::AssocTy, def_id) => {
2272                let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2273                    let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2274                    Some(trait_)
2275                } else {
2276                    None
2277                };
2278                self.lower_resolved_assoc_ty_path(
2279                    span,
2280                    opt_self_ty,
2281                    def_id,
2282                    trait_segment,
2283                    path.segments.last().unwrap(),
2284                )
2285            }
2286            Res::PrimTy(prim_ty) => {
2287                assert_eq!(opt_self_ty, None);
2288                let _ = self.prohibit_generic_args(
2289                    path.segments.iter(),
2290                    GenericsArgsErrExtend::PrimTy(prim_ty),
2291                );
2292                match prim_ty {
2293                    hir::PrimTy::Bool => tcx.types.bool,
2294                    hir::PrimTy::Char => tcx.types.char,
2295                    hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
2296                    hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
2297                    hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
2298                    hir::PrimTy::Str => tcx.types.str_,
2299                }
2300            }
2301            Res::Err => {
2302                let e = self
2303                    .tcx()
2304                    .dcx()
2305                    .span_delayed_bug(path.span, "path with `Res::Err` but no error emitted");
2306                Ty::new_error(tcx, e)
2307            }
2308            Res::Def(..) => {
2309                assert_eq!(
2310                    path.segments.get(0).map(|seg| seg.ident.name),
2311                    Some(kw::SelfUpper),
2312                    "only expected incorrect resolution for `Self`"
2313                );
2314                Ty::new_error(
2315                    self.tcx(),
2316                    self.dcx().span_delayed_bug(span, "incorrect resolution for `Self`"),
2317                )
2318            }
2319            _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2320        }
2321    }
2322
2323    /// Lower a type parameter from the HIR to our internal notion of a type.
2324    ///
2325    /// Early-bound type parameters get lowered to [`ty::Param`]
2326    /// and late-bound ones to [`ty::Bound`].
2327    pub(crate) fn lower_ty_param(&self, hir_id: HirId) -> Ty<'tcx> {
2328        let tcx = self.tcx();
2329
2330        let ty = match tcx.named_bound_var(hir_id) {
2331            Some(rbv::ResolvedArg::LateBound(debruijn, index, def_id)) => {
2332                let br = ty::BoundTy {
2333                    var: ty::BoundVar::from_u32(index),
2334                    kind: ty::BoundTyKind::Param(def_id.to_def_id()),
2335                };
2336                Ty::new_bound(tcx, debruijn, br)
2337            }
2338            Some(rbv::ResolvedArg::EarlyBound(def_id)) => {
2339                let item_def_id = tcx.hir_ty_param_owner(def_id);
2340                let generics = tcx.generics_of(item_def_id);
2341                let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2342                Ty::new_param(tcx, index, tcx.hir_ty_param_name(def_id))
2343            }
2344            Some(rbv::ResolvedArg::Error(guar)) => Ty::new_error(tcx, guar),
2345            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:?}"),
2346        };
2347        self.check_param_uses_if_mcg(ty, tcx.hir_span(hir_id), false)
2348    }
2349
2350    /// Lower a const parameter from the HIR to our internal notion of a constant.
2351    ///
2352    /// Early-bound const parameters get lowered to [`ty::ConstKind::Param`]
2353    /// and late-bound ones to [`ty::ConstKind::Bound`].
2354    pub(crate) fn lower_const_param(&self, param_def_id: DefId, path_hir_id: HirId) -> Const<'tcx> {
2355        let tcx = self.tcx();
2356
2357        let ct = match tcx.named_bound_var(path_hir_id) {
2358            Some(rbv::ResolvedArg::EarlyBound(_)) => {
2359                // Find the name and index of the const parameter by indexing the generics of
2360                // the parent item and construct a `ParamConst`.
2361                let item_def_id = tcx.parent(param_def_id);
2362                let generics = tcx.generics_of(item_def_id);
2363                let index = generics.param_def_id_to_index[&param_def_id];
2364                let name = tcx.item_name(param_def_id);
2365                ty::Const::new_param(tcx, ty::ParamConst::new(index, name))
2366            }
2367            Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => ty::Const::new_bound(
2368                tcx,
2369                debruijn,
2370                ty::BoundConst::new(ty::BoundVar::from_u32(index)),
2371            ),
2372            Some(rbv::ResolvedArg::Error(guar)) => ty::Const::new_error(tcx, guar),
2373            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),
2374        };
2375        self.check_param_uses_if_mcg(ct, tcx.hir_span(path_hir_id), false)
2376    }
2377
2378    /// Lower a [`hir::ConstArg`] to a (type-level) [`ty::Const`].
2379    #[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(2379u32),
                                    ::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(tcx, 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(tcx, 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(tcx, Ty::new_error(tcx, e)));
                    return ty::Const::new_error(tcx, e);
                }
                tcx.feed_anon_const_type(anon.def_id,
                    ty::EarlyBinder::bind(tcx, 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:2440",
                                            "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(2440u32),
                                            ::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:2445",
                                            "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(2445u32),
                                            ::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")]
2380    pub fn lower_const_arg(&self, const_arg: &hir::ConstArg<'tcx>, ty: Ty<'tcx>) -> Const<'tcx> {
2381        let tcx = self.tcx();
2382
2383        if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
2384            // FIXME(generic_const_parameter_types): Ideally we remove these errors below when
2385            // we have the ability to intermix typeck of anon const const args with the parent
2386            // bodies typeck.
2387
2388            // We also error if the type contains any regions as effectively any region will wind
2389            // up as a region variable in mir borrowck. It would also be somewhat concerning if
2390            // hir typeck was using equality but mir borrowck wound up using subtyping as that could
2391            // result in a non-infer in hir typeck but a region variable in borrowck.
2392            if tcx.features().generic_const_parameter_types()
2393                && (ty.has_free_regions() || ty.has_erased_regions())
2394            {
2395                let e = self.dcx().span_err(
2396                    const_arg.span,
2397                    "anonymous constants with lifetimes in their type are not yet supported",
2398                );
2399                tcx.feed_anon_const_type(
2400                    anon.def_id,
2401                    ty::EarlyBinder::bind(tcx, Ty::new_error(tcx, e)),
2402                );
2403                return ty::Const::new_error(tcx, e);
2404            }
2405            // We must error if the instantiated type has any inference variables as we will
2406            // use this type to feed the `type_of` and query results must not contain inference
2407            // variables otherwise we will ICE.
2408            if ty.has_non_region_infer() {
2409                let e = self.dcx().span_err(
2410                    const_arg.span,
2411                    "anonymous constants with inferred types are not yet supported",
2412                );
2413                tcx.feed_anon_const_type(
2414                    anon.def_id,
2415                    ty::EarlyBinder::bind(tcx, Ty::new_error(tcx, e)),
2416                );
2417                return ty::Const::new_error(tcx, e);
2418            }
2419            // We error when the type contains unsubstituted generics since we do not currently
2420            // give the anon const any of the generics from the parent.
2421            if ty.has_non_region_param() {
2422                let e = self.dcx().span_err(
2423                    const_arg.span,
2424                    "anonymous constants referencing generics are not yet supported",
2425                );
2426                tcx.feed_anon_const_type(
2427                    anon.def_id,
2428                    ty::EarlyBinder::bind(tcx, Ty::new_error(tcx, e)),
2429                );
2430                return ty::Const::new_error(tcx, e);
2431            }
2432
2433            tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(tcx, ty));
2434        }
2435
2436        let hir_id = const_arg.hir_id;
2437        match const_arg.kind {
2438            hir::ConstArgKind::Tup(exprs) => self.lower_const_arg_tup(exprs, ty, const_arg.span),
2439            hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2440                debug!(?maybe_qself, ?path);
2441                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2442                self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2443            }
2444            hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2445                debug!(?hir_self_ty, ?segment);
2446                let self_ty = self.lower_ty(hir_self_ty);
2447                self.lower_type_relative_const_path(
2448                    self_ty,
2449                    hir_self_ty,
2450                    segment,
2451                    hir_id,
2452                    const_arg.span,
2453                )
2454                .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2455            }
2456            hir::ConstArgKind::Struct(qpath, inits) => {
2457                self.lower_const_arg_struct(hir_id, qpath, inits, const_arg.span)
2458            }
2459            hir::ConstArgKind::TupleCall(qpath, args) => {
2460                self.lower_const_arg_tuple_call(hir_id, qpath, args, const_arg.span)
2461            }
2462            hir::ConstArgKind::Array(array_expr) => self.lower_const_arg_array(array_expr, ty),
2463            hir::ConstArgKind::Anon(anon) => self.lower_const_arg_anon(anon),
2464            hir::ConstArgKind::Infer(()) => self.ct_infer(None, const_arg.span),
2465            hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
2466            hir::ConstArgKind::Literal { lit, negated } => {
2467                self.lower_const_arg_literal(&lit, negated, ty, const_arg.span)
2468            }
2469        }
2470    }
2471
2472    fn lower_const_arg_array(
2473        &self,
2474        array_expr: &'tcx hir::ConstArgArrayExpr<'tcx>,
2475        ty: Ty<'tcx>,
2476    ) -> Const<'tcx> {
2477        let tcx = self.tcx();
2478
2479        let elem_ty = match ty.kind() {
2480            ty::Array(elem_ty, _) => elem_ty,
2481            ty::Error(e) => return Const::new_error(tcx, *e),
2482            _ => {
2483                let e = tcx
2484                    .dcx()
2485                    .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));
2486                return Const::new_error(tcx, e);
2487            }
2488        };
2489
2490        let elems = array_expr
2491            .elems
2492            .iter()
2493            .map(|elem| self.lower_const_arg(elem, *elem_ty))
2494            .collect::<Vec<_>>();
2495
2496        let valtree = ty::ValTree::from_branches(tcx, elems);
2497
2498        ty::Const::new_value(tcx, valtree, ty)
2499    }
2500
2501    fn lower_const_arg_tuple_call(
2502        &self,
2503        hir_id: HirId,
2504        qpath: hir::QPath<'tcx>,
2505        args: &'tcx [&'tcx hir::ConstArg<'tcx>],
2506        span: Span,
2507    ) -> Const<'tcx> {
2508        let tcx = self.tcx();
2509
2510        let non_adt_or_variant_res = || {
2511            let e = tcx.dcx().span_err(span, "tuple constructor with invalid base path");
2512            ty::Const::new_error(tcx, e)
2513        };
2514
2515        let ctor_const = match qpath {
2516            hir::QPath::Resolved(maybe_qself, path) => {
2517                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2518                self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2519            }
2520            hir::QPath::TypeRelative(hir_self_ty, segment) => {
2521                let self_ty = self.lower_ty(hir_self_ty);
2522                match self.lower_type_relative_const_path(
2523                    self_ty,
2524                    hir_self_ty,
2525                    segment,
2526                    hir_id,
2527                    span,
2528                ) {
2529                    Ok(c) => c,
2530                    Err(_) => return non_adt_or_variant_res(),
2531                }
2532            }
2533        };
2534
2535        let Some(value) = ctor_const.try_to_value() else {
2536            return non_adt_or_variant_res();
2537        };
2538
2539        let (adt_def, adt_args, variant_did) = match value.ty.kind() {
2540            ty::FnDef(def_id, fn_args)
2541                if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(*def_id) =>
2542            {
2543                let parent_did = tcx.parent(*def_id);
2544                let enum_did = tcx.parent(parent_did);
2545                (tcx.adt_def(enum_did), fn_args, parent_did)
2546            }
2547            ty::FnDef(def_id, fn_args)
2548                if let DefKind::Ctor(CtorOf::Struct, _) = tcx.def_kind(*def_id) =>
2549            {
2550                let parent_did = tcx.parent(*def_id);
2551                (tcx.adt_def(parent_did), fn_args, parent_did)
2552            }
2553            _ => {
2554                let e = self.dcx().span_err(
2555                    span,
2556                    "complex const arguments must be placed inside of a `const` block",
2557                );
2558                return Const::new_error(tcx, e);
2559            }
2560        };
2561
2562        let variant_def = adt_def.variant_with_id(variant_did);
2563        let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2564
2565        if args.len() != variant_def.fields.len() {
2566            let e = tcx.dcx().span_err(
2567                span,
2568                ::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!(
2569                    "tuple constructor has {} arguments but {} were provided",
2570                    variant_def.fields.len(),
2571                    args.len()
2572                ),
2573            );
2574            return ty::Const::new_error(tcx, e);
2575        }
2576
2577        let fields = variant_def
2578            .fields
2579            .iter()
2580            .zip(args)
2581            .map(|(field_def, arg)| {
2582                self.lower_const_arg(
2583                    arg,
2584                    tcx.type_of(field_def.did).instantiate(tcx, adt_args).skip_norm_wip(),
2585                )
2586            })
2587            .collect::<Vec<_>>();
2588
2589        let opt_discr_const = if adt_def.is_enum() {
2590            let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2591            Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2592        } else {
2593            None
2594        };
2595
2596        let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2597        let adt_ty = Ty::new_adt(tcx, adt_def, adt_args);
2598        ty::Const::new_value(tcx, valtree, adt_ty)
2599    }
2600
2601    fn lower_const_arg_tup(
2602        &self,
2603        exprs: &'tcx [&'tcx hir::ConstArg<'tcx>],
2604        ty: Ty<'tcx>,
2605        span: Span,
2606    ) -> Const<'tcx> {
2607        let tcx = self.tcx();
2608
2609        let found_tuple = || {
2610            tcx.sess
2611                .source_map()
2612                .span_to_snippet(span)
2613                .map(|snippet| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", snippet))
    })format!("`{snippet}`"))
2614                .unwrap_or_else(|_| "const tuple".to_string())
2615        };
2616
2617        let tys = match ty.kind() {
2618            ty::Tuple(tys) => tys,
2619            ty::Error(e) => return Const::new_error(tcx, *e),
2620            _ => {
2621                let e =
2622                    tcx.dcx().span_err(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}`, found {1}", ty,
                found_tuple()))
    })format!("expected `{}`, found {}", ty, found_tuple()));
2623                return Const::new_error(tcx, e);
2624            }
2625        };
2626
2627        if exprs.len() != tys.len() {
2628            let e = tcx.dcx().span_err(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}`, found {1}", ty,
                found_tuple()))
    })format!("expected `{}`, found {}", ty, found_tuple()));
2629            return Const::new_error(tcx, e);
2630        }
2631
2632        let exprs = exprs
2633            .iter()
2634            .zip(tys.iter())
2635            .map(|(expr, ty)| self.lower_const_arg(expr, ty))
2636            .collect::<Vec<_>>();
2637
2638        let valtree = ty::ValTree::from_branches(tcx, exprs);
2639        ty::Const::new_value(tcx, valtree, ty)
2640    }
2641
2642    fn lower_const_arg_struct(
2643        &self,
2644        hir_id: HirId,
2645        qpath: hir::QPath<'tcx>,
2646        inits: &'tcx [&'tcx hir::ConstArgExprField<'tcx>],
2647        span: Span,
2648    ) -> Const<'tcx> {
2649        // FIXME(mgca): try to deduplicate this function with
2650        // the equivalent HIR typeck logic.
2651        let tcx = self.tcx();
2652
2653        let non_adt_or_variant_res = || {
2654            let e = tcx.dcx().span_err(span, "struct expression with invalid base path");
2655            ty::Const::new_error(tcx, e)
2656        };
2657
2658        let ResolvedStructPath { res: opt_res, ty } =
2659            self.lower_path_for_struct_expr(qpath, span, hir_id);
2660
2661        let variant_did = match qpath {
2662            hir::QPath::Resolved(maybe_qself, path) => {
2663                {
    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:2663",
                        "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(2663u32),
                        ::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);
2664                let variant_did = match path.res {
2665                    Res::Def(DefKind::Variant | DefKind::Struct, did) => did,
2666                    _ => return non_adt_or_variant_res(),
2667                };
2668
2669                variant_did
2670            }
2671            hir::QPath::TypeRelative(hir_self_ty, segment) => {
2672                {
    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:2672",
                        "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(2672u32),
                        ::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);
2673
2674                let res_def_id = match opt_res {
2675                    Ok(r)
2676                        if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(r.def_id()) {
    DefKind::Variant | DefKind::Struct => true,
    _ => false,
}matches!(
2677                            tcx.def_kind(r.def_id()),
2678                            DefKind::Variant | DefKind::Struct
2679                        ) =>
2680                    {
2681                        r.def_id()
2682                    }
2683                    Ok(_) => return non_adt_or_variant_res(),
2684                    Err(e) => return ty::Const::new_error(tcx, e),
2685                };
2686
2687                res_def_id
2688            }
2689        };
2690
2691        let ty::Adt(adt_def, adt_args) = ty.kind() else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2692
2693        let variant_def = adt_def.variant_with_id(variant_did);
2694        let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2695
2696        for init in inits {
2697            if !variant_def.fields.iter().any(|field_def| field_def.name == init.field.name) {
2698                let mut err = if adt_def.is_enum() {
2699                    {
    tcx.dcx().struct_span_err(init.field.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("variant `{0}::{1}` has no field named `{2}`",
                            ty, variant_def.name, init.field))
                })).with_code(E0559)
}struct_span_code_err!(
2700                        tcx.dcx(),
2701                        init.field.span,
2702                        E0559,
2703                        "variant `{}::{}` has no field named `{}`",
2704                        ty,
2705                        variant_def.name,
2706                        init.field
2707                    )
2708                } else {
2709                    {
    tcx.dcx().struct_span_err(init.field.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("struct `{0}` has no field named `{1}`",
                            variant_def.name, init.field))
                })).with_code(E0560)
}struct_span_code_err!(
2710                        tcx.dcx(),
2711                        init.field.span,
2712                        E0560,
2713                        "struct `{}` has no field named `{}`",
2714                        variant_def.name,
2715                        init.field
2716                    )
2717                };
2718                if adt_def.is_enum() {
2719                    err.span_label(
2720                        init.field.span,
2721                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}::{1}` does not have this field",
                ty, variant_def.name))
    })format!("`{}::{}` does not have this field", ty, variant_def.name),
2722                    );
2723                } else {
2724                    err.span_label(
2725                        init.field.span,
2726                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` does not have this field",
                variant_def.name))
    })format!("`{}` does not have this field", variant_def.name),
2727                    );
2728                }
2729                return ty::Const::new_error(tcx, err.emit());
2730            }
2731        }
2732
2733        let fields = variant_def
2734            .fields
2735            .iter()
2736            .map(|field_def| {
2737                // FIXME(mgca): we aren't really handling privacy, stability,
2738                // or macro hygeniene but we should.
2739                let mut init_expr =
2740                    inits.iter().filter(|init_expr| init_expr.field.name == field_def.name);
2741
2742                match init_expr.next() {
2743                    Some(expr) => {
2744                        if let Some(expr) = init_expr.next() {
2745                            let e = tcx.dcx().span_err(
2746                                expr.span,
2747                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("struct expression with multiple initialisers for `{0}`",
                field_def.name))
    })format!(
2748                                    "struct expression with multiple initialisers for `{}`",
2749                                    field_def.name,
2750                                ),
2751                            );
2752                            return ty::Const::new_error(tcx, e);
2753                        }
2754
2755                        self.lower_const_arg(
2756                            expr.expr,
2757                            tcx.type_of(field_def.did).instantiate(tcx, adt_args).skip_norm_wip(),
2758                        )
2759                    }
2760                    None => {
2761                        let e = tcx.dcx().span_err(
2762                            span,
2763                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("struct expression with missing field initialiser for `{0}`",
                field_def.name))
    })format!(
2764                                "struct expression with missing field initialiser for `{}`",
2765                                field_def.name
2766                            ),
2767                        );
2768                        ty::Const::new_error(tcx, e)
2769                    }
2770                }
2771            })
2772            .collect::<Vec<_>>();
2773
2774        let opt_discr_const = if adt_def.is_enum() {
2775            let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2776            Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2777        } else {
2778            None
2779        };
2780
2781        let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2782        ty::Const::new_value(tcx, valtree, ty)
2783    }
2784
2785    pub fn lower_path_for_struct_expr(
2786        &self,
2787        qpath: hir::QPath<'tcx>,
2788        path_span: Span,
2789        hir_id: HirId,
2790    ) -> ResolvedStructPath<'tcx> {
2791        match qpath {
2792            hir::QPath::Resolved(ref maybe_qself, path) => {
2793                let self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2794                let ty = self.lower_resolved_ty_path(self_ty, path, hir_id, PermitVariants::Yes);
2795                ResolvedStructPath { res: Ok(path.res), ty }
2796            }
2797            hir::QPath::TypeRelative(hir_self_ty, segment) => {
2798                let self_ty = self.lower_ty(hir_self_ty);
2799
2800                let result = self.lower_type_relative_ty_path(
2801                    self_ty,
2802                    hir_self_ty,
2803                    segment,
2804                    hir_id,
2805                    path_span,
2806                    PermitVariants::Yes,
2807                );
2808                let ty = result
2809                    .map(|(ty, _, _)| ty)
2810                    .unwrap_or_else(|guar| Ty::new_error(self.tcx(), guar));
2811
2812                ResolvedStructPath {
2813                    res: result.map(|(_, kind, def_id)| Res::Def(kind, def_id)),
2814                    ty,
2815                }
2816            }
2817        }
2818    }
2819
2820    /// Lower a [resolved][hir::QPath::Resolved] path to a (type-level) constant.
2821    fn lower_resolved_const_path(
2822        &self,
2823        opt_self_ty: Option<Ty<'tcx>>,
2824        path: &hir::Path<'tcx>,
2825        hir_id: HirId,
2826    ) -> Const<'tcx> {
2827        let tcx = self.tcx();
2828        let span = path.span;
2829        let ct = match path.res {
2830            Res::Def(DefKind::ConstParam, def_id) => {
2831                {
    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);
2832                let _ = self.prohibit_generic_args(
2833                    path.segments.iter(),
2834                    GenericsArgsErrExtend::Param(def_id),
2835                );
2836                self.lower_const_param(def_id, hir_id)
2837            }
2838            Res::Def(DefKind::Const { .. }, did) => {
2839                if let Err(guar) = self.require_type_const_attribute(did, span) {
2840                    return Const::new_error(self.tcx(), guar);
2841                }
2842
2843                {
    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);
2844                let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2845                let _ = self
2846                    .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2847                let args = self.lower_generic_args_of_path_segment(span, did, segment);
2848                ty::Const::new_alias(
2849                    tcx,
2850                    ty::IsRigid::No,
2851                    ty::AliasConst::new(tcx, ty::AliasConstKind::new_from_def_id(tcx, did), args),
2852                )
2853            }
2854            Res::Def(kind @ DefKind::Ctor(ctor_of, CtorKind::Const), did) => {
2855                {
    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);
2856                let generic_segments =
2857                    self.probe_generic_path_segments(path.segments, opt_self_ty, kind, did, span);
2858                let indices: FxHashSet<_> =
2859                    generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2860                let _ = self.prohibit_generic_args(
2861                    path.segments.iter().enumerate().filter_map(|(index, seg)| {
2862                        if !indices.contains(&index) { Some(seg) } else { None }
2863                    }),
2864                    GenericsArgsErrExtend::DefVariant(&path.segments),
2865                );
2866
2867                let parent_did = tcx.parent(did);
2868                let generics_did = match ctor_of {
2869                    CtorOf::Variant => tcx.parent(parent_did),
2870                    CtorOf::Struct => parent_did,
2871                };
2872                let args = self.lower_generic_args_of_path_segment(
2873                    span,
2874                    generics_did,
2875                    &path.segments[generic_segments[0].1],
2876                );
2877                self.construct_const_ctor_value(did, ctor_of, args)
2878            }
2879            Res::Def(DefKind::Ctor(ctor_of, CtorKind::Fn), did) => {
2880                {
    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);
2881                let generic_segments = self.probe_generic_path_segments(
2882                    path.segments,
2883                    opt_self_ty,
2884                    DefKind::Ctor(ctor_of, CtorKind::Const),
2885                    did,
2886                    span,
2887                );
2888                let indices: FxHashSet<_> =
2889                    generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2890                let _ = self.prohibit_generic_args(
2891                    path.segments.iter().enumerate().filter_map(|(index, seg)| {
2892                        if !indices.contains(&index) { Some(seg) } else { None }
2893                    }),
2894                    GenericsArgsErrExtend::DefVariant(&path.segments),
2895                );
2896
2897                let parent_did = tcx.parent(did);
2898                let generics_did = if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(did) {
2899                    tcx.parent(parent_did)
2900                } else {
2901                    parent_did
2902                };
2903                let args = self.lower_generic_args_of_path_segment(
2904                    span,
2905                    generics_did,
2906                    &path.segments[generic_segments[0].1],
2907                );
2908
2909                ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2910            }
2911            Res::Def(DefKind::AssocConst { .. }, did) => {
2912                let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2913                    let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2914                    Some(trait_)
2915                } else {
2916                    None
2917                };
2918                self.lower_resolved_assoc_const_path(
2919                    span,
2920                    opt_self_ty,
2921                    did,
2922                    trait_segment,
2923                    path.segments.last().unwrap(),
2924                )
2925                .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2926            }
2927            Res::Def(DefKind::Static { .. }, _) => {
2928                ::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")
2929            }
2930            // FIXME(const_generics): create real const to allow fn items as const paths
2931            Res::Def(DefKind::Fn | DefKind::AssocFn, did) => {
2932                self.dcx().span_delayed_bug(span, "function items cannot be used as const args");
2933                let args = self.lower_generic_args_of_path_segment(
2934                    span,
2935                    did,
2936                    path.segments.last().unwrap(),
2937                );
2938
2939                if self.tcx().generics_of(did).own_synthetic_params_count() == 0 {
2940                    ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2941                } else {
2942                    let tcx = self.tcx();
2943                    let generics = tcx.generics_of(did);
2944
2945                    // Use infer tys for synthetic params; otherwise the impl header's trait ref may
2946                    // contain callee-owned synthetic params and fail when instantiated with impl args.
2947                    // See issue #155834
2948                    let args = args.iter().enumerate().map(|(index, arg)| {
2949                        let param = generics.param_at(index, tcx);
2950                        if param.kind.is_synthetic() {
2951                            self.ty_infer(Some(param), span).into()
2952                        } else {
2953                            arg
2954                        }
2955                    });
2956
2957                    ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2958                }
2959            }
2960
2961            // Exhaustive match to be clear about what exactly we're considering to be
2962            // an invalid Res for a const path.
2963            res @ (Res::Def(
2964                DefKind::Mod
2965                | DefKind::Enum
2966                | DefKind::Variant
2967                | DefKind::Struct
2968                | DefKind::OpaqueTy
2969                | DefKind::TyAlias
2970                | DefKind::TraitAlias
2971                | DefKind::AssocTy
2972                | DefKind::Union
2973                | DefKind::Trait
2974                | DefKind::ForeignTy
2975                | DefKind::TyParam
2976                | DefKind::Macro(_)
2977                | DefKind::LifetimeParam
2978                | DefKind::Use
2979                | DefKind::ForeignMod
2980                | DefKind::AnonConst
2981                | DefKind::Field
2982                | DefKind::Impl { .. }
2983                | DefKind::Closure
2984                | DefKind::ExternCrate
2985                | DefKind::GlobalAsm
2986                | DefKind::SyntheticCoroutineBody,
2987                _,
2988            )
2989            | Res::PrimTy(_)
2990            | Res::SelfTyParam { .. }
2991            | Res::SelfTyAlias { .. }
2992            | Res::SelfCtor(_)
2993            | Res::Local(_)
2994            | Res::ToolMod
2995            | Res::OpenMod(..)
2996            | Res::NonMacroAttr(_)
2997            | Res::Err) => Const::new_error_with_message(
2998                tcx,
2999                span,
3000                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("invalid Res {0:?} for const path",
                res))
    })format!("invalid Res {res:?} for const path"),
3001            ),
3002        };
3003        self.check_param_uses_if_mcg(ct, span, false)
3004    }
3005
3006    /// Literals are eagerly converted to a constant, everything else becomes `ConstKind::Alias`.
3007    #[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(3007u32),
                                    ::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:3012",
                                    "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(3012u32),
                                    ::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().skip_norm_wip();
            match self.try_lower_anon_const_lit(ty, expr) {
                Some(v) => v,
                None =>
                    ty::Const::new_alias(tcx, ty::IsRigid::No,
                        ty::AliasConst::new(tcx,
                            ty::AliasConstKind::Anon {
                                def_id: anon.def_id.to_def_id(),
                            },
                            ty::GenericArgs::identity_for_item(tcx,
                                anon.def_id.to_def_id()))),
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
3008    fn lower_const_arg_anon(&self, anon: &AnonConst) -> Const<'tcx> {
3009        let tcx = self.tcx();
3010
3011        let expr = &tcx.hir_body(anon.body).value;
3012        debug!(?expr);
3013
3014        // FIXME(generic_const_parameter_types): We should use the proper generic args
3015        // here. It's only used as a hint for literals so doesn't matter too much to use the right
3016        // generic arguments, just weaker type inference.
3017        let ty = tcx.type_of(anon.def_id).instantiate_identity().skip_norm_wip();
3018
3019        match self.try_lower_anon_const_lit(ty, expr) {
3020            Some(v) => v,
3021            None => ty::Const::new_alias(
3022                tcx,
3023                ty::IsRigid::No,
3024                ty::AliasConst::new(
3025                    tcx,
3026                    ty::AliasConstKind::Anon { def_id: anon.def_id.to_def_id() },
3027                    ty::GenericArgs::identity_for_item(tcx, anon.def_id.to_def_id()),
3028                ),
3029            ),
3030        }
3031    }
3032
3033    #[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(3033u32),
                                    ::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();
            let ty = if !ty.has_infer() { Some(ty) } else { None };
            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")]
3034    fn lower_const_arg_literal(
3035        &self,
3036        kind: &LitKind,
3037        neg: bool,
3038        ty: Ty<'tcx>,
3039        span: Span,
3040    ) -> Const<'tcx> {
3041        let tcx = self.tcx();
3042
3043        let ty = if !ty.has_infer() { Some(ty) } else { None };
3044
3045        if let LitKind::Err(guar) = *kind {
3046            return ty::Const::new_error(tcx, guar);
3047        }
3048        let input = LitToConstInput { lit: *kind, ty, neg };
3049        match tcx.at(span).lit_to_const(input) {
3050            Some(value) => ty::Const::new_value(tcx, value.valtree, value.ty),
3051            None => {
3052                let e = tcx.dcx().span_err(span, "type annotations needed for the literal");
3053                ty::Const::new_error(tcx, e)
3054            }
3055        }
3056    }
3057
3058    #[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(3058u32),
                                    ::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: Some(ty),
                                neg: false,
                            })
                    }
                    hir::ExprKind::Unary(hir::UnOp::Neg, expr) =>
                        match expr.kind {
                            hir::ExprKind::Lit(lit) => {
                                Some(LitToConstInput {
                                        lit: lit.node,
                                        ty: Some(ty),
                                        neg: true,
                                    })
                            }
                            _ => None,
                        },
                    _ => None,
                };
            lit_input.and_then(|l|
                    {
                        if const_lit_matches_ty(tcx, &l.lit, 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")]
3059    fn try_lower_anon_const_lit(
3060        &self,
3061        ty: Ty<'tcx>,
3062        expr: &'tcx hir::Expr<'tcx>,
3063    ) -> Option<Const<'tcx>> {
3064        let tcx = self.tcx();
3065
3066        // Unwrap a block, so that e.g. `{ 1 }` is recognised as a literal. This makes the
3067        // performance optimisation of directly lowering anon consts occur more often.
3068        let expr = match &expr.kind {
3069            hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
3070                block.expr.as_ref().unwrap()
3071            }
3072            _ => expr,
3073        };
3074
3075        let lit_input = match expr.kind {
3076            hir::ExprKind::Lit(lit) => {
3077                Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: false })
3078            }
3079            hir::ExprKind::Unary(hir::UnOp::Neg, expr) => match expr.kind {
3080                hir::ExprKind::Lit(lit) => {
3081                    Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: true })
3082                }
3083                _ => None,
3084            },
3085            _ => None,
3086        };
3087
3088        lit_input.and_then(|l| {
3089            if const_lit_matches_ty(tcx, &l.lit, ty, l.neg) {
3090                tcx.at(expr.span)
3091                    .lit_to_const(l)
3092                    .map(|value| ty::Const::new_value(tcx, value.valtree, value.ty))
3093            } else {
3094                None
3095            }
3096        })
3097    }
3098
3099    fn require_type_const_attribute(
3100        &self,
3101        def_id: DefId,
3102        span: Span,
3103    ) -> Result<(), ErrorGuaranteed> {
3104        let tcx = self.tcx();
3105        // FIXME(gca): Intentionally disallowing paths to inherent associated non-type constants
3106        // until a refactoring for how generic args for IACs are represented has been landed.
3107        let is_inherent_assoc_const = tcx.def_kind(def_id)
3108            == DefKind::AssocConst { is_type_const: false }
3109            && tcx.def_kind(tcx.parent(def_id)) == DefKind::Impl { of_trait: false };
3110        if tcx.is_type_const(def_id)
3111            || tcx.features().generic_const_args() && !is_inherent_assoc_const
3112        {
3113            Ok(())
3114        } else {
3115            let mut err = self.dcx().struct_span_err(
3116                span,
3117                "use of `const` in the type system not defined as `type const`",
3118            );
3119            if let Some(local_def_id) = def_id.as_local() {
3120                let name = tcx.def_path_str(def_id);
3121                let (insertion_span, sugg) = match tcx.hir_node_by_def_id(local_def_id) {
3122                    hir::Node::Item(item) if !item.vis_span.is_empty() => {
3123                        (item.vis_span.shrink_to_hi(), " type")
3124                    }
3125                    hir::Node::ImplItem(impl_item)
3126                        if let Some(vis_span) =
3127                            impl_item.vis_span().filter(|span| !span.is_empty()) =>
3128                    {
3129                        (vis_span.shrink_to_hi(), " type")
3130                    }
3131                    _ => (tcx.def_span(def_id).shrink_to_lo(), "type "),
3132                };
3133
3134                err.span_suggestion_verbose(
3135                    insertion_span,
3136                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("add `type` before `const` for `{0}`",
                name))
    })format!("add `type` before `const` for `{name}`"),
3137                    sugg,
3138                    Applicability::MaybeIncorrect,
3139                );
3140            } else {
3141                err.note("only consts marked defined as `type const` may be used in types");
3142            }
3143            Err(err.emit())
3144        }
3145    }
3146
3147    fn lower_delegation_ty(&self, infer: hir::InferDelegation<'tcx>) -> Ty<'tcx> {
3148        match infer {
3149            hir::InferDelegation::DefId(def_id) => {
3150                self.tcx().type_of(def_id).instantiate_identity().skip_norm_wip()
3151            }
3152            rustc_hir::InferDelegation::Sig(_, idx) => {
3153                let delegation_sig = self.tcx().inherit_sig_for_delegation_item(self.item_def_id());
3154
3155                match idx {
3156                    hir::InferDelegationSig::Input(idx) => delegation_sig[idx],
3157                    hir::InferDelegationSig::Output { .. } => *delegation_sig.last().unwrap(),
3158                }
3159            }
3160        }
3161    }
3162
3163    /// Lower a type from the HIR to our internal notion of a type.
3164    x;#[instrument(level = "debug", skip(self), ret)]
3165    pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
3166        let tcx = self.tcx();
3167
3168        let result_ty = match &hir_ty.kind {
3169            hir::TyKind::InferDelegation(infer) => self.lower_delegation_ty(*infer),
3170            hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)),
3171            hir::TyKind::Ptr(mt) => Ty::new_ptr(tcx, self.lower_ty(mt.ty), mt.mutbl),
3172            hir::TyKind::Ref(region, mt) => {
3173                let r = self.lower_lifetime(region, RegionInferReason::Reference);
3174                debug!(?r);
3175                let t = self.lower_ty(mt.ty);
3176                Ty::new_ref(tcx, r, t, mt.mutbl)
3177            }
3178            hir::TyKind::Never => tcx.types.never,
3179            hir::TyKind::Tup(fields) => {
3180                Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
3181            }
3182            hir::TyKind::FnPtr(bf) => {
3183                check_c_variadic_abi(tcx, bf.decl, bf.abi, hir_ty.span);
3184
3185                Ty::new_fn_ptr(
3186                    tcx,
3187                    self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)),
3188                )
3189            }
3190            hir::TyKind::UnsafeBinder(binder) => Ty::new_unsafe_binder(
3191                tcx,
3192                ty::Binder::bind_with_vars(
3193                    self.lower_ty(binder.inner_ty),
3194                    tcx.late_bound_vars(hir_ty.hir_id),
3195                ),
3196            ),
3197            hir::TyKind::TraitObject(bounds, tagged_ptr) => {
3198                let lifetime = tagged_ptr.pointer();
3199                let syntax = tagged_ptr.tag();
3200                self.lower_trait_object_ty(hir_ty.span, hir_ty.hir_id, bounds, lifetime, syntax)
3201            }
3202            // If we encounter a fully qualified path with RTN generics, then it must have
3203            // *not* gone through `lower_ty_maybe_return_type_notation`, and therefore
3204            // it's certainly in an illegal position.
3205            hir::TyKind::Path(hir::QPath::Resolved(_, path))
3206                if path.segments.last().and_then(|segment| segment.args).is_some_and(|args| {
3207                    matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3208                }) =>
3209            {
3210                let guar = self
3211                    .dcx()
3212                    .emit_err(BadReturnTypeNotation { span: hir_ty.span, suggestion: None });
3213                Ty::new_error(tcx, guar)
3214            }
3215            hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
3216                debug!(?maybe_qself, ?path);
3217                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
3218                self.lower_resolved_ty_path(opt_self_ty, path, hir_ty.hir_id, PermitVariants::No)
3219            }
3220            &hir::TyKind::OpaqueDef(opaque_ty) => {
3221                // If this is an RPITIT and we are using the new RPITIT lowering scheme, we
3222                // generate the def_id of an associated type for the trait and return as
3223                // type a projection.
3224                let in_trait = match opaque_ty.origin {
3225                    hir::OpaqueTyOrigin::FnReturn {
3226                        parent,
3227                        in_trait_or_impl: Some(hir::RpitContext::Trait),
3228                        ..
3229                    }
3230                    | hir::OpaqueTyOrigin::AsyncFn {
3231                        parent,
3232                        in_trait_or_impl: Some(hir::RpitContext::Trait),
3233                        ..
3234                    } => Some(parent),
3235                    hir::OpaqueTyOrigin::FnReturn {
3236                        in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3237                        ..
3238                    }
3239                    | hir::OpaqueTyOrigin::AsyncFn {
3240                        in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3241                        ..
3242                    }
3243                    | hir::OpaqueTyOrigin::TyAlias { .. } => None,
3244                };
3245
3246                self.lower_opaque_ty(opaque_ty.def_id, in_trait)
3247            }
3248            hir::TyKind::TraitAscription(hir_bounds) => {
3249                // Impl trait in bindings lower as an infer var with additional
3250                // set of type bounds.
3251                let self_ty = self.ty_infer(None, hir_ty.span);
3252                let mut bounds = Vec::new();
3253                self.lower_bounds(
3254                    self_ty,
3255                    hir_bounds.iter(),
3256                    &mut bounds,
3257                    ty::List::empty(),
3258                    PredicateFilter::All,
3259                    OverlappingAsssocItemConstraints::Allowed,
3260                );
3261                self.add_implicit_sizedness_bounds(
3262                    &mut bounds,
3263                    self_ty,
3264                    hir_bounds,
3265                    ImpliedBoundsContext::AssociatedTypeOrImplTrait,
3266                    hir_ty.span,
3267                );
3268                self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span);
3269                self_ty
3270            }
3271            // If we encounter a type relative path with RTN generics, then it must have
3272            // *not* gone through `lower_ty_maybe_return_type_notation`, and therefore
3273            // it's certainly in an illegal position.
3274            hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment))
3275                if segment.args.is_some_and(|args| {
3276                    matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3277                }) =>
3278            {
3279                let guar = if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3280                    && let None = stmt.init
3281                    && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3282                        hir_self_ty.kind
3283                    && let Res::Def(DefKind::Enum | DefKind::Struct | DefKind::Union, def_id) =
3284                        self_ty_path.res
3285                    && let Some(_) = tcx
3286                        .inherent_impls(def_id)
3287                        .iter()
3288                        .flat_map(|imp| {
3289                            tcx.associated_items(*imp).filter_by_name_unhygienic(segment.ident.name)
3290                        })
3291                        .filter(|assoc| {
3292                            matches!(assoc.kind, ty::AssocKind::Fn { has_self: false, .. })
3293                        })
3294                        .next()
3295                {
3296                    // `let x: S::new(valid_in_ty_ctxt);` -> `let x = S::new(valid_in_ty_ctxt);`
3297                    let err = tcx
3298                        .dcx()
3299                        .struct_span_err(
3300                            hir_ty.span,
3301                            "expected type, found associated function call",
3302                        )
3303                        .with_span_suggestion_verbose(
3304                            stmt.pat.span.between(hir_ty.span),
3305                            "use `=` if you meant to assign",
3306                            " = ".to_string(),
3307                            Applicability::MaybeIncorrect,
3308                        );
3309                    self.dcx().try_steal_replace_and_emit_err(
3310                        hir_ty.span,
3311                        StashKey::ReturnTypeNotation,
3312                        err,
3313                    )
3314                } else if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3315                    && let None = stmt.init
3316                    && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3317                        hir_self_ty.kind
3318                    && let Res::PrimTy(_) = self_ty_path.res
3319                    && self.dcx().has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3320                {
3321                    // `let x: i32::something(valid_in_ty_ctxt);` -> `let x = i32::something(valid_in_ty_ctxt);`
3322                    // FIXME: Check that `something` is a valid function in `i32`.
3323                    let err = tcx
3324                        .dcx()
3325                        .struct_span_err(
3326                            hir_ty.span,
3327                            "expected type, found associated function call",
3328                        )
3329                        .with_span_suggestion_verbose(
3330                            stmt.pat.span.between(hir_ty.span),
3331                            "use `=` if you meant to assign",
3332                            " = ".to_string(),
3333                            Applicability::MaybeIncorrect,
3334                        );
3335                    self.dcx().try_steal_replace_and_emit_err(
3336                        hir_ty.span,
3337                        StashKey::ReturnTypeNotation,
3338                        err,
3339                    )
3340                } else {
3341                    let suggestion = if self
3342                        .dcx()
3343                        .has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3344                    {
3345                        // We already created a diagnostic complaining that `foo(bar)` is wrong and
3346                        // should have been `foo(..)`. Instead, emit only the current error and
3347                        // include that prior suggestion. Changes are that the problems go further,
3348                        // but keep the suggestion just in case. Either way, we want a single error
3349                        // instead of two.
3350                        Some(segment.ident.span.shrink_to_hi().with_hi(hir_ty.span.hi()))
3351                    } else {
3352                        None
3353                    };
3354                    let err = self
3355                        .dcx()
3356                        .create_err(BadReturnTypeNotation { span: hir_ty.span, suggestion });
3357                    self.dcx().try_steal_replace_and_emit_err(
3358                        hir_ty.span,
3359                        StashKey::ReturnTypeNotation,
3360                        err,
3361                    )
3362                };
3363                Ty::new_error(tcx, guar)
3364            }
3365            hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
3366                debug!(?hir_self_ty, ?segment);
3367                let self_ty = self.lower_ty(hir_self_ty);
3368                self.lower_type_relative_ty_path(
3369                    self_ty,
3370                    hir_self_ty,
3371                    segment,
3372                    hir_ty.hir_id,
3373                    hir_ty.span,
3374                    PermitVariants::No,
3375                )
3376                .map(|(ty, _, _)| ty)
3377                .unwrap_or_else(|guar| Ty::new_error(tcx, guar))
3378            }
3379            hir::TyKind::Array(ty, length) => {
3380                let length = self.lower_const_arg(length, tcx.types.usize);
3381                Ty::new_array_with_const_len(tcx, self.lower_ty(ty), length)
3382            }
3383            hir::TyKind::Infer(()) => {
3384                // Infer also appears as the type of arguments or return
3385                // values in an ExprKind::Closure, or as
3386                // the type of local variables. Both of these cases are
3387                // handled specially and will not descend into this routine.
3388                self.ty_infer(None, hir_ty.span)
3389            }
3390            hir::TyKind::Pat(ty, pat) => {
3391                let ty_span = ty.span;
3392                let ty = self.lower_ty(ty);
3393                let pat_ty = match self.lower_pat_ty_pat(ty, ty_span, pat) {
3394                    Ok(kind) => Ty::new_pat(tcx, ty, tcx.mk_pat(kind)),
3395                    Err(guar) => Ty::new_error(tcx, guar),
3396                };
3397                self.record_ty(pat.hir_id, ty, pat.span);
3398                pat_ty
3399            }
3400            hir::TyKind::FieldOf(ty, hir::TyFieldPath { variant, field }) => self.lower_field_of(
3401                self.lower_ty(ty),
3402                self.item_def_id(),
3403                ty.span,
3404                hir_ty.hir_id,
3405                *variant,
3406                *field,
3407            ),
3408            hir::TyKind::View(ty, fields) => {
3409                self.lower_view(self.lower_ty(ty), fields, hir_ty.span)
3410            }
3411
3412            hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar),
3413        };
3414
3415        self.record_ty(hir_ty.hir_id, result_ty, hir_ty.span);
3416        result_ty
3417    }
3418
3419    fn lower_pat_ty_pat(
3420        &self,
3421        ty: Ty<'tcx>,
3422        ty_span: Span,
3423        pat: &hir::TyPat<'tcx>,
3424    ) -> Result<ty::PatternKind<'tcx>, ErrorGuaranteed> {
3425        let tcx = self.tcx();
3426        match pat.kind {
3427            hir::TyPatKind::Range(start, end) => {
3428                match ty.kind() {
3429                    // Keep this list of types in sync with the list of types that
3430                    // the `RangePattern` trait is implemented for.
3431                    ty::Int(_) | ty::Uint(_) | ty::Char => {
3432                        let start = self.lower_const_arg(start, ty);
3433                        let end = self.lower_const_arg(end, ty);
3434                        Ok(ty::PatternKind::Range { start, end })
3435                    }
3436                    _ => Err(self
3437                        .dcx()
3438                        .span_delayed_bug(ty_span, "invalid base type for range pattern")),
3439                }
3440            }
3441            hir::TyPatKind::NotNull => Ok(ty::PatternKind::NotNull),
3442            hir::TyPatKind::Or(patterns) => {
3443                self.tcx()
3444                    .mk_patterns_from_iter(patterns.iter().map(|pat| {
3445                        self.lower_pat_ty_pat(ty, ty_span, pat).map(|pat| tcx.mk_pat(pat))
3446                    }))
3447                    .map(ty::PatternKind::Or)
3448            }
3449            hir::TyPatKind::Err(e) => Err(e),
3450        }
3451    }
3452
3453    fn lower_field_of(
3454        &self,
3455        ty: Ty<'tcx>,
3456        item_def_id: LocalDefId,
3457        ty_span: Span,
3458        hir_id: HirId,
3459        variant: Option<Ident>,
3460        field: Ident,
3461    ) -> Ty<'tcx> {
3462        let dcx = self.dcx();
3463        let tcx = self.tcx();
3464        match ty.kind() {
3465            ty::Adt(def, _) => {
3466                let base_did = def.did();
3467                let kind_name = tcx.def_descr(base_did);
3468                let (variant_idx, variant) = if def.is_enum() {
3469                    let Some(variant) = variant else {
3470                        let err = dcx
3471                            .create_err(NoVariantNamed { span: field.span, ident: field, ty })
3472                            .with_span_help(
3473                                field.span.shrink_to_lo(),
3474                                "you might be missing a variant here: `Variant.`",
3475                            )
3476                            .emit();
3477                        return Ty::new_error(tcx, err);
3478                    };
3479
3480                    if let Some(res) = def
3481                        .variants()
3482                        .iter_enumerated()
3483                        .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == variant)
3484                    {
3485                        res
3486                    } else {
3487                        let err = dcx
3488                            .create_err(NoVariantNamed { span: variant.span, ident: variant, ty })
3489                            .emit();
3490                        return Ty::new_error(tcx, err);
3491                    }
3492                } else {
3493                    if let Some(variant) = variant {
3494                        let adt_path = tcx.def_path_str(base_did);
3495                        {
    dcx.struct_span_err(variant.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0} `{1}` does not have any variants",
                            kind_name, adt_path))
                })).with_code(E0609)
}struct_span_code_err!(
3496                            dcx,
3497                            variant.span,
3498                            E0609,
3499                            "{kind_name} `{adt_path}` does not have any variants",
3500                        )
3501                        .with_span_label(variant.span, "variant unknown")
3502                        .emit();
3503                    }
3504                    (FIRST_VARIANT, def.non_enum_variant())
3505                };
3506                let (ident, def_scope) =
3507                    tcx.adjust_ident_and_get_scope(field, def.did(), item_def_id);
3508                if let Some((field_idx, field)) = variant
3509                    .fields
3510                    .iter_enumerated()
3511                    .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == ident)
3512                {
3513                    if field.vis.is_accessible_from(def_scope, tcx) {
3514                        tcx.check_stability(field.did, Some(hir_id), ident.span, None);
3515                    } else {
3516                        let adt_path = tcx.def_path_str(base_did);
3517                        {
    dcx.struct_span_err(ident.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("field `{0}` of {1} `{2}` is private",
                            ident, kind_name, adt_path))
                })).with_code(E0616)
}struct_span_code_err!(
3518                            dcx,
3519                            ident.span,
3520                            E0616,
3521                            "field `{ident}` of {kind_name} `{adt_path}` is private",
3522                        )
3523                        .with_span_label(ident.span, "private field")
3524                        .emit();
3525                    }
3526                    Ty::new_field_representing_type(tcx, ty, variant_idx, field_idx)
3527                } else {
3528                    let err =
3529                        dcx.create_err(NoFieldOnType { span: ident.span, field: ident, ty }).emit();
3530                    Ty::new_error(tcx, err)
3531                }
3532            }
3533            ty::Tuple(tys) => {
3534                let index = match field.as_str().parse::<usize>() {
3535                    Ok(idx) => idx,
3536                    Err(_) => {
3537                        let err =
3538                            dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3539                        return Ty::new_error(tcx, err);
3540                    }
3541                };
3542                if field.name != sym::integer(index) {
3543                    ::rustc_middle::util::bug::bug_fmt(format_args!("we parsed above, but now not equal?"));bug!("we parsed above, but now not equal?");
3544                }
3545                if tys.get(index).is_some() {
3546                    Ty::new_field_representing_type(tcx, ty, FIRST_VARIANT, index.into())
3547                } else {
3548                    let err = dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3549                    Ty::new_error(tcx, err)
3550                }
3551            }
3552            // FIXME(FRTs): support type aliases
3553            /*
3554            ty::Alias(AliasTyKind::Free, ty) => {
3555                return self.lower_field_of(
3556                    ty,
3557                    item_def_id,
3558                    ty_span,
3559                    hir_id,
3560                    variant,
3561                    field,
3562                );
3563            }*/
3564            ty::Alias(..) => Ty::new_error(
3565                tcx,
3566                dcx.span_err(ty_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("could not resolve fields of `{0}`",
                ty))
    })format!("could not resolve fields of `{ty}`")),
3567            ),
3568            ty::Error(err) => Ty::new_error(tcx, *err),
3569            ty::Bool
3570            | ty::Char
3571            | ty::Int(_)
3572            | ty::Uint(_)
3573            | ty::Float(_)
3574            | ty::Foreign(_)
3575            | ty::Str
3576            | ty::RawPtr(_, _)
3577            | ty::Ref(_, _, _)
3578            | ty::FnDef(_, _)
3579            | ty::FnPtr(_, _)
3580            | ty::UnsafeBinder(_)
3581            | ty::Dynamic(_, _)
3582            | ty::Closure(_, _)
3583            | ty::CoroutineClosure(_, _)
3584            | ty::Coroutine(_, _)
3585            | ty::CoroutineWitness(_, _)
3586            | ty::Never
3587            | ty::Param(_)
3588            | ty::Bound(_, _)
3589            | ty::Placeholder(_)
3590            | ty::Slice(..) => Ty::new_error(
3591                tcx,
3592                dcx.span_err(ty_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type `{0}` doesn\'t have fields",
                ty))
    })format!("type `{ty}` doesn't have fields")),
3593            ),
3594            ty::Infer(_) => Ty::new_error(
3595                tcx,
3596                dcx.span_err(ty_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot use `{0}` in this position",
                ty))
    })format!("cannot use `{ty}` in this position")),
3597            ),
3598            // FIXME(FRTs): support these types?
3599            ty::Array(..) | ty::Pat(..) => Ty::new_error(
3600                tcx,
3601                dcx.span_err(ty_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type `{0}` is not yet supported in `field_of!`",
                ty))
    })format!("type `{ty}` is not yet supported in `field_of!`")),
3602            ),
3603        }
3604    }
3605
3606    /// Lower an opaque type (i.e., an existential impl-Trait type) from the HIR.
3607    x;#[instrument(level = "debug", skip(self), ret)]
3608    fn lower_opaque_ty(&self, def_id: LocalDefId, in_trait: Option<LocalDefId>) -> Ty<'tcx> {
3609        let tcx = self.tcx();
3610
3611        let lifetimes = tcx.opaque_captured_lifetimes(def_id);
3612        debug!(?lifetimes);
3613
3614        // If this is an RPITIT and we are using the new RPITIT lowering scheme,
3615        // do a linear search to map this to the synthetic associated type that
3616        // it will be lowered to.
3617        let def_id = if let Some(parent_def_id) = in_trait {
3618            *tcx.associated_types_for_impl_traits_in_associated_fn(parent_def_id.to_def_id())
3619                .iter()
3620                .find(|rpitit| match tcx.opt_rpitit_info(**rpitit) {
3621                    Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
3622                        opaque_def_id.expect_local() == def_id
3623                    }
3624                    _ => unreachable!(),
3625                })
3626                .unwrap()
3627        } else {
3628            def_id.to_def_id()
3629        };
3630
3631        let generics = tcx.generics_of(def_id);
3632        debug!(?generics);
3633
3634        // We use `generics.count() - lifetimes.len()` here instead of `generics.parent_count`
3635        // since return-position impl trait in trait squashes all of the generics from its source fn
3636        // into its own generics, so the opaque's "own" params isn't always just lifetimes.
3637        let offset = generics.count() - lifetimes.len();
3638
3639        let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| {
3640            if let Some(i) = (param.index as usize).checked_sub(offset) {
3641                let (lifetime, _) = lifetimes[i];
3642                // FIXME(mgca): should we be calling self.check_params_use_if_mcg here too?
3643                self.lower_resolved_lifetime(lifetime).into()
3644            } else {
3645                tcx.mk_param_from_def(param)
3646            }
3647        });
3648        debug!(?args);
3649
3650        if in_trait.is_some() {
3651            Ty::new_projection_from_args(tcx, ty::IsRigid::No, def_id, args)
3652        } else {
3653            Ty::new_opaque(tcx, ty::IsRigid::No, def_id, args)
3654        }
3655    }
3656
3657    /// Lower a function type from the HIR to our internal notion of a function signature.
3658    x;#[instrument(level = "debug", skip(self, hir_id, safety, abi, decl, generics, hir_ty), ret)]
3659    pub fn lower_fn_ty(
3660        &self,
3661        hir_id: HirId,
3662        safety: hir::Safety,
3663        abi: rustc_abi::ExternAbi,
3664        decl: &hir::FnDecl<'tcx>,
3665        generics: Option<&hir::Generics<'_>>,
3666        hir_ty: Option<&hir::Ty<'_>>,
3667    ) -> ty::PolyFnSig<'tcx> {
3668        let tcx = self.tcx();
3669        let bound_vars = tcx.late_bound_vars(hir_id);
3670        debug!(?bound_vars);
3671
3672        let (input_tys, output_ty) = self.lower_fn_sig(decl, generics, hir_id, hir_ty);
3673
3674        debug!(?output_ty);
3675
3676        debug!(?abi, ?safety, ?decl.fn_decl_kind, input_tys_len = ?input_tys.len());
3677        let fn_sig_kind = FnSigKind::default()
3678            .set_abi(abi)
3679            .set_safety(safety)
3680            .set_c_variadic(decl.fn_decl_kind.c_variadic())
3681            .set_splatted(decl.splatted(), input_tys.len())
3682            .unwrap();
3683        let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, fn_sig_kind);
3684        let fn_ptr_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3685
3686        if let Some(hir::Ty { kind: hir::TyKind::FnPtr(fn_ptr_ty), span, .. }) = hir_ty {
3687            check_abi(tcx, hir_id, *span, fn_ptr_ty.abi);
3688        }
3689
3690        // reject function types that violate cmse ABI requirements
3691        cmse::validate_cmse_abi(self.tcx(), self.dcx(), hir_id, abi, fn_ptr_ty);
3692
3693        if !fn_ptr_ty.references_error() {
3694            // Find any late-bound regions declared in return type that do
3695            // not appear in the arguments. These are not well-formed.
3696            //
3697            // Example:
3698            //     for<'a> fn() -> &'a str <-- 'a is bad
3699            //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
3700            let inputs = fn_ptr_ty.inputs();
3701            let late_bound_in_args =
3702                tcx.collect_constrained_late_bound_regions(inputs.map_bound(|i| i.to_owned()));
3703            let output = fn_ptr_ty.output();
3704            let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(output);
3705
3706            self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3707                struct_span_code_err!(
3708                    self.dcx(),
3709                    decl.output.span(),
3710                    E0581,
3711                    "return type references {}, which is not constrained by the fn input types",
3712                    br_name
3713                )
3714            });
3715        }
3716
3717        fn_ptr_ty
3718    }
3719
3720    /// Given a fn_hir_id for a impl function, suggest the type that is found on the
3721    /// corresponding function in the trait that the impl implements, if it exists.
3722    /// If arg_idx is Some, then it corresponds to an input type index, otherwise it
3723    /// corresponds to the return type.
3724    pub(super) fn suggest_trait_fn_ty_for_impl_fn_infer(
3725        &self,
3726        fn_hir_id: HirId,
3727        arg_idx: Option<usize>,
3728    ) -> Option<Ty<'tcx>> {
3729        let tcx = self.tcx();
3730        let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3731            tcx.hir_node(fn_hir_id)
3732        else {
3733            return None;
3734        };
3735        let i = tcx.parent_hir_node(fn_hir_id).expect_item().expect_impl();
3736
3737        let trait_ref = self.lower_impl_trait_ref(&i.of_trait?.trait_ref, self.lower_ty(i.self_ty));
3738
3739        let assoc = tcx.associated_items(trait_ref.def_id).find_by_ident_and_kind(
3740            tcx,
3741            *ident,
3742            ty::AssocTag::Fn,
3743            trait_ref.def_id,
3744        )?;
3745
3746        let fn_sig = tcx
3747            .fn_sig(assoc.def_id)
3748            .instantiate(
3749                tcx,
3750                trait_ref
3751                    .args
3752                    .extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3753            )
3754            .skip_norm_wip();
3755        let fn_sig = tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), fn_sig);
3756
3757        Some(if let Some(arg_idx) = arg_idx {
3758            *fn_sig.inputs().get(arg_idx)?
3759        } else {
3760            fn_sig.output()
3761        })
3762    }
3763
3764    #[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(3764u32),
                                    ::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))]
3765    fn validate_late_bound_regions<'cx>(
3766        &'cx self,
3767        constrained_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3768        referenced_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3769        generate_err: impl Fn(&str) -> Diag<'cx>,
3770    ) {
3771        for br in referenced_regions.difference(&constrained_regions) {
3772            let br_name = if let Some(name) = br.get_name(self.tcx()) {
3773                format!("lifetime `{name}`")
3774            } else {
3775                "an anonymous lifetime".to_string()
3776            };
3777
3778            let mut err = generate_err(&br_name);
3779
3780            if !br.is_named(self.tcx()) {
3781                // The only way for an anonymous lifetime to wind up
3782                // in the return type but **also** be unconstrained is
3783                // if it only appears in "associated types" in the
3784                // input. See #47511 and #62200 for examples. In this case,
3785                // though we can easily give a hint that ought to be
3786                // relevant.
3787                err.note(
3788                    "lifetimes appearing in an associated or opaque type are not considered constrained",
3789                );
3790                err.note("consider introducing a named lifetime parameter");
3791            }
3792
3793            err.emit();
3794        }
3795    }
3796
3797    fn construct_const_ctor_value(
3798        &self,
3799        ctor_def_id: DefId,
3800        ctor_of: CtorOf,
3801        args: GenericArgsRef<'tcx>,
3802    ) -> Const<'tcx> {
3803        let tcx = self.tcx();
3804        let parent_did = tcx.parent(ctor_def_id);
3805
3806        let adt_def = tcx.adt_def(match ctor_of {
3807            CtorOf::Variant => tcx.parent(parent_did),
3808            CtorOf::Struct => parent_did,
3809        });
3810
3811        let variant_idx = adt_def.variant_index_with_id(parent_did);
3812
3813        let valtree = if adt_def.is_enum() {
3814            let discr = ty::ValTree::from_scalar_int(tcx, variant_idx.as_u32().into());
3815            ty::ValTree::from_branches(tcx, [ty::Const::new_value(tcx, discr, tcx.types.u32)])
3816        } else {
3817            ty::ValTree::zst(tcx)
3818        };
3819
3820        let adt_ty = Ty::new_adt(tcx, adt_def, args);
3821        ty::Const::new_value(tcx, valtree, adt_ty)
3822    }
3823
3824    fn lower_view(&self, inner_ty: Ty<'tcx>, fields: &[Ident], ty_span: Span) -> Ty<'tcx> {
3825        // Step 1: check that every field is unique, and keep a list of field that we know are
3826        // unique.
3827        let mut viewed_fields = Vec::<Ident>::with_capacity(fields.len());
3828
3829        for f in fields {
3830            let f = f.normalize_to_macros_2_0();
3831            // PERF: this is quadratic, but ~fine since the amount of fields is very low.
3832            if let Some(previous_field_span) =
3833                viewed_fields.iter().find_map(|f_| (*f_ == f).then_some(f_.span))
3834            {
3835                self.dcx().emit_err(diagnostics::ViewedFieldIsAlreadyPartOfTheView {
3836                    name: f.name,
3837                    span: f.span,
3838                    previous_field_span,
3839                });
3840                continue;
3841            }
3842            viewed_fields.push(f);
3843        }
3844
3845        // Step 2: check that the viewed type is a struct.
3846        let variant = match inner_ty.kind() {
3847            ty::Adt(def, _) if def.is_struct() => def.non_enum_variant(),
3848
3849            ty::Adt(def, _) => {
3850                let guar = self.dcx().emit_err(diagnostics::OnlyStructsCanBeViewedAdt {
3851                    ty: inner_ty,
3852                    span: ty_span,
3853                    article: def.article(),
3854                    kind: def.descr(),
3855                });
3856                return Ty::new_error(self.tcx(), guar);
3857            }
3858
3859            _ => {
3860                let guar = self.dcx().emit_err(diagnostics::OnlyStructsCanBeViewedNonAdt {
3861                    ty: inner_ty,
3862                    span: ty_span,
3863                });
3864                return Ty::new_error(self.tcx(), guar);
3865            }
3866        };
3867
3868        // Step 3: check that every viewed field exists.
3869        let mut viewed_indices = Vec::with_capacity(viewed_fields.len());
3870        let mut error = None;
3871        for field in viewed_fields {
3872            let Some((_, field)) = variant
3873                .fields
3874                .iter_enumerated()
3875                .find(|(_, f)| f.ident(self.tcx()).normalize_to_macros_2_0() == field)
3876            else {
3877                let err =
3878                    self.dcx().emit_err(NoFieldOnType { span: field.span, field, ty: inner_ty });
3879                error = Some(err);
3880                continue;
3881            };
3882
3883            viewed_indices.push(field);
3884        }
3885        if let Some(guar) = error {
3886            return Ty::new_error(self.tcx(), guar);
3887        }
3888
3889        // FIXME(scrabsha): actually lower view types.
3890        inner_ty
3891    }
3892}