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