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