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