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, Diagnostic, ErrorGuaranteed, FatalError, Level, 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::print::PrintPolyTraitRefExt as _;
40use rustc_middle::ty::{
41    self, Const, GenericArgKind, GenericArgsRef, GenericParamDefKind, LitToConstInput, Ty, TyCtxt,
42    TypeSuperFoldable, TypeVisitableExt, TypingMode, Upcast, const_lit_matches_ty, fold_regions,
43};
44use rustc_middle::{bug, span_bug};
45use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
46use rustc_session::parse::feature_err;
47use rustc_span::{DUMMY_SP, Ident, Span, kw, sym};
48use rustc_trait_selection::infer::InferCtxtExt;
49use rustc_trait_selection::traits::wf::object_region_bounds;
50use rustc_trait_selection::traits::{self, FulfillmentError};
51use tracing::{debug, instrument};
52
53use crate::check::check_abi;
54use crate::errors::{AmbiguousLifetimeBound, BadReturnTypeNotation, NoFieldOnType};
55use crate::hir_ty_lowering::errors::{GenericsArgsErrExtend, prohibit_assoc_item_constraint};
56use crate::hir_ty_lowering::generics::{check_generic_arg_count, lower_generic_args};
57use crate::middle::resolve_bound_vars as rbv;
58use crate::{NoVariantNamed, check_c_variadic_abi};
59
60/// The context in which an implied bound is being added to a item being lowered (i.e. a sizedness
61/// trait or a default trait)
62#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ImpliedBoundsContext<'tcx> {
    #[inline]
    fn clone(&self) -> ImpliedBoundsContext<'tcx> {
        let _: ::core::clone::AssertParamIsClone<LocalDefId>;
        let _:
                ::core::clone::AssertParamIsClone<&'tcx [hir::WherePredicate<'tcx>]>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ImpliedBoundsContext<'tcx> { }Copy)]
63pub(crate) enum ImpliedBoundsContext<'tcx> {
64    /// An implied bound is added to a trait definition (i.e. a new supertrait), used when adding
65    /// a default `MetaSized` supertrait
66    TraitDef(LocalDefId),
67    /// An implied bound is added to a type parameter
68    TyParam(LocalDefId, &'tcx [hir::WherePredicate<'tcx>]),
69    /// An implied bound being added in any other context
70    AssociatedTypeOrImplTrait,
71}
72
73/// A path segment that is semantically allowed to have generic arguments.
74#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GenericPathSegment {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field2_finish(f,
            "GenericPathSegment", &self.0, &&self.1)
    }
}Debug)]
75pub struct GenericPathSegment(pub DefId, pub usize);
76
77#[derive(#[automatically_derived]
impl ::core::marker::Copy for PredicateFilter { }Copy, #[automatically_derived]
impl ::core::clone::Clone for PredicateFilter {
    #[inline]
    fn clone(&self) -> PredicateFilter {
        let _: ::core::clone::AssertParamIsClone<Ident>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for PredicateFilter {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            PredicateFilter::All =>
                ::core::fmt::Formatter::write_str(f, "All"),
            PredicateFilter::SelfOnly =>
                ::core::fmt::Formatter::write_str(f, "SelfOnly"),
            PredicateFilter::SelfTraitThatDefines(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "SelfTraitThatDefines", &__self_0),
            PredicateFilter::SelfAndAssociatedTypeBounds =>
                ::core::fmt::Formatter::write_str(f,
                    "SelfAndAssociatedTypeBounds"),
            PredicateFilter::ConstIfConst =>
                ::core::fmt::Formatter::write_str(f, "ConstIfConst"),
            PredicateFilter::SelfConstIfConst =>
                ::core::fmt::Formatter::write_str(f, "SelfConstIfConst"),
        }
    }
}Debug)]
78pub enum PredicateFilter {
79    /// All predicates may be implied by the trait.
80    All,
81
82    /// Only traits that reference `Self: ..` are implied by the trait.
83    SelfOnly,
84
85    /// Only traits that reference `Self: ..` and define an associated type
86    /// with the given ident are implied by the trait. This mode exists to
87    /// side-step query cycles when lowering associated types.
88    SelfTraitThatDefines(Ident),
89
90    /// Only traits that reference `Self: ..` and their associated type bounds.
91    /// For example, given `Self: Tr<A: B>`, this would expand to `Self: Tr`
92    /// and `<Self as Tr>::A: B`.
93    SelfAndAssociatedTypeBounds,
94
95    /// Filter only the `[const]` bounds, which are lowered into `HostEffect` clauses.
96    ConstIfConst,
97
98    /// Filter only the `[const]` bounds which are *also* in the supertrait position.
99    SelfConstIfConst,
100}
101
102#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for RegionInferReason<'a> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            RegionInferReason::ExplicitObjectLifetime =>
                ::core::fmt::Formatter::write_str(f,
                    "ExplicitObjectLifetime"),
            RegionInferReason::ObjectLifetimeDefault(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ObjectLifetimeDefault", &__self_0),
            RegionInferReason::Param(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Param",
                    &__self_0),
            RegionInferReason::RegionPredicate =>
                ::core::fmt::Formatter::write_str(f, "RegionPredicate"),
            RegionInferReason::Reference =>
                ::core::fmt::Formatter::write_str(f, "Reference"),
            RegionInferReason::OutlivesBound =>
                ::core::fmt::Formatter::write_str(f, "OutlivesBound"),
        }
    }
}Debug)]
103pub enum RegionInferReason<'a> {
104    /// Lifetime on a trait object that is spelled explicitly, e.g. `+ 'a` or `+ '_`.
105    ExplicitObjectLifetime,
106    /// A trait object's lifetime when it is elided, e.g. `dyn Any`.
107    ObjectLifetimeDefault(Span),
108    /// Generic lifetime parameter
109    Param(&'a ty::GenericParamDef),
110    RegionPredicate,
111    Reference,
112    OutlivesBound,
113}
114
115#[derive(#[automatically_derived]
impl ::core::marker::Copy for InherentAssocCandidate { }Copy, #[automatically_derived]
impl ::core::clone::Clone for InherentAssocCandidate {
    #[inline]
    fn clone(&self) -> InherentAssocCandidate {
        let _: ::core::clone::AssertParamIsClone<DefId>;
        *self
    }
}Clone, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for InherentAssocCandidate {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        InherentAssocCandidate {
                            impl_: __binding_0,
                            assoc_item: __binding_1,
                            scope: __binding_2 } => {
                            InherentAssocCandidate {
                                impl_: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                assoc_item: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                scope: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    InherentAssocCandidate {
                        impl_: __binding_0,
                        assoc_item: __binding_1,
                        scope: __binding_2 } => {
                        InherentAssocCandidate {
                            impl_: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            assoc_item: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            scope: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for InherentAssocCandidate {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    InherentAssocCandidate {
                        impl_: ref __binding_0,
                        assoc_item: ref __binding_1,
                        scope: ref __binding_2 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable, #[automatically_derived]
impl ::core::fmt::Debug for InherentAssocCandidate {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "InherentAssocCandidate", "impl_", &self.impl_, "assoc_item",
            &self.assoc_item, "scope", &&self.scope)
    }
}Debug)]
116pub struct InherentAssocCandidate {
117    pub impl_: DefId,
118    pub assoc_item: DefId,
119    pub scope: DefId,
120}
121
122pub struct ResolvedStructPath<'tcx> {
123    pub res: Result<Res, ErrorGuaranteed>,
124    pub ty: Ty<'tcx>,
125}
126
127/// A context which can lower type-system entities from the [HIR][hir] to
128/// the [`rustc_middle::ty`] representation.
129///
130/// This trait used to be called `AstConv`.
131pub trait HirTyLowerer<'tcx> {
132    fn tcx(&self) -> TyCtxt<'tcx>;
133
134    fn dcx(&self) -> DiagCtxtHandle<'_>;
135
136    /// Returns the [`LocalDefId`] of the overarching item whose constituents get lowered.
137    fn item_def_id(&self) -> LocalDefId;
138
139    /// Returns the region to use when a lifetime is omitted (and not elided).
140    fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx>;
141
142    /// Returns the type to use when a type is omitted.
143    fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
144
145    /// Returns the const to use when a const is omitted.
146    fn ct_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx>;
147
148    fn register_trait_ascription_bounds(
149        &self,
150        bounds: Vec<(ty::Clause<'tcx>, Span)>,
151        hir_id: HirId,
152        span: Span,
153    );
154
155    /// Probe bounds in scope where the bounded type coincides with the given type parameter.
156    ///
157    /// Rephrased, this returns bounds of the form `T: Trait`, where `T` is a type parameter
158    /// with the given `def_id`. This is a subset of the full set of bounds.
159    ///
160    /// This method may use the given `assoc_name` to disregard bounds whose trait reference
161    /// doesn't define an associated item with the provided name.
162    ///
163    /// This is used for one specific purpose: Resolving “short-hand” associated type references
164    /// like `T::Item` where `T` is a type parameter. In principle, we would do that by first
165    /// getting the full set of predicates in scope and then filtering down to find those that
166    /// apply to `T`, but this can lead to cycle errors. The problem is that we have to do this
167    /// resolution *in order to create the predicates in the first place*.
168    /// Hence, we have this “special pass”.
169    fn probe_ty_param_bounds(
170        &self,
171        span: Span,
172        def_id: LocalDefId,
173        assoc_ident: Ident,
174    ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]>;
175
176    fn select_inherent_assoc_candidates(
177        &self,
178        span: Span,
179        self_ty: Ty<'tcx>,
180        candidates: Vec<InherentAssocCandidate>,
181    ) -> (Vec<InherentAssocCandidate>, Vec<FulfillmentError<'tcx>>);
182
183    /// Lower a path to an associated item (of a trait) to a projection.
184    ///
185    /// This method has to be defined by the concrete lowering context because
186    /// dealing with higher-ranked trait references depends on its capabilities:
187    ///
188    /// If the context can make use of type inference, it can simply instantiate
189    /// any late-bound vars bound by the trait reference with inference variables.
190    /// If it doesn't support type inference, there is nothing reasonable it can
191    /// do except reject the associated type.
192    ///
193    /// The canonical example of this is associated type `T::P` where `T` is a type
194    /// param constrained by `T: for<'a> Trait<'a>` and where `Trait` defines `P`.
195    fn lower_assoc_item_path(
196        &self,
197        span: Span,
198        item_def_id: DefId,
199        item_segment: &hir::PathSegment<'tcx>,
200        poly_trait_ref: ty::PolyTraitRef<'tcx>,
201    ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed>;
202
203    fn lower_fn_sig(
204        &self,
205        decl: &hir::FnDecl<'tcx>,
206        generics: Option<&hir::Generics<'_>>,
207        hir_id: HirId,
208        hir_ty: Option<&hir::Ty<'_>>,
209    ) -> (Vec<Ty<'tcx>>, Ty<'tcx>);
210
211    /// Returns `AdtDef` if `ty` is an ADT.
212    ///
213    /// Note that `ty` might be a alias type that needs normalization.
214    /// This used to get the enum variants in scope of the type.
215    /// For example, `Self::A` could refer to an associated type
216    /// or to an enum variant depending on the result of this function.
217    fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>>;
218
219    /// Record the lowered type of a HIR node in this context.
220    fn record_ty(&self, hir_id: HirId, ty: Ty<'tcx>, span: Span);
221
222    /// The inference context of the lowering context if applicable.
223    fn infcx(&self) -> Option<&InferCtxt<'tcx>>;
224
225    /// Convenience method for coercing the lowering context into a trait object type.
226    ///
227    /// Most lowering routines are defined on the trait object type directly
228    /// necessitating a coercion step from the concrete lowering context.
229    fn lowerer(&self) -> &dyn HirTyLowerer<'tcx>
230    where
231        Self: Sized,
232    {
233        self
234    }
235
236    /// Performs minimalistic dyn compat checks outside of bodies, but full within bodies.
237    /// Outside of bodies we could end up in cycles, so we delay most checks to later phases.
238    fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation>;
239}
240
241/// The "qualified self" of an associated item path.
242///
243/// For diagnostic purposes only.
244enum AssocItemQSelf {
245    Trait(DefId),
246    TyParam(LocalDefId, Span),
247    SelfTyAlias,
248}
249
250impl AssocItemQSelf {
251    fn to_string(&self, tcx: TyCtxt<'_>) -> String {
252        match *self {
253            Self::Trait(def_id) => tcx.def_path_str(def_id),
254            Self::TyParam(def_id, _) => tcx.hir_ty_param_name(def_id).to_string(),
255            Self::SelfTyAlias => kw::SelfUpper.to_string(),
256        }
257    }
258}
259
260#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LowerTypeRelativePathMode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LowerTypeRelativePathMode::Type(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Type",
                    &__self_0),
            LowerTypeRelativePathMode::Const =>
                ::core::fmt::Formatter::write_str(f, "Const"),
        }
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for LowerTypeRelativePathMode {
    #[inline]
    fn clone(&self) -> LowerTypeRelativePathMode {
        let _: ::core::clone::AssertParamIsClone<PermitVariants>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for LowerTypeRelativePathMode { }Copy)]
261enum LowerTypeRelativePathMode {
262    Type(PermitVariants),
263    Const,
264}
265
266impl LowerTypeRelativePathMode {
267    fn assoc_tag(self) -> ty::AssocTag {
268        match self {
269            Self::Type(_) => ty::AssocTag::Type,
270            Self::Const => ty::AssocTag::Const,
271        }
272    }
273
274    ///NOTE: use `assoc_tag` for any important logic
275    fn def_kind_for_diagnostics(self) -> DefKind {
276        match self {
277            Self::Type(_) => DefKind::AssocTy,
278            Self::Const => DefKind::AssocConst { is_type_const: false },
279        }
280    }
281
282    fn permit_variants(self) -> PermitVariants {
283        match self {
284            Self::Type(permit_variants) => permit_variants,
285            // FIXME(mgca): Support paths like `Option::<T>::None` or `Option::<T>::Some` which
286            // resolve to const ctors/fn items respectively.
287            Self::Const => PermitVariants::No,
288        }
289    }
290}
291
292/// Whether to permit a path to resolve to an enum variant.
293#[derive(#[automatically_derived]
impl ::core::fmt::Debug for PermitVariants {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                PermitVariants::Yes => "Yes",
                PermitVariants::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for PermitVariants {
    #[inline]
    fn clone(&self) -> PermitVariants { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for PermitVariants { }Copy)]
294pub enum PermitVariants {
295    Yes,
296    No,
297}
298
299#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TypeRelativePath<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            TypeRelativePath::AssocItem(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "AssocItem", __self_0, &__self_1),
            TypeRelativePath::Variant { adt: __self_0, variant_did: __self_1 }
                =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Variant", "adt", __self_0, "variant_did", &__self_1),
            TypeRelativePath::Ctor { ctor_def_id: __self_0, args: __self_1 }
                =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f, "Ctor",
                    "ctor_def_id", __self_0, "args", &__self_1),
        }
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for TypeRelativePath<'tcx> {
    #[inline]
    fn clone(&self) -> TypeRelativePath<'tcx> {
        let _: ::core::clone::AssertParamIsClone<DefId>;
        let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for TypeRelativePath<'tcx> { }Copy)]
300enum TypeRelativePath<'tcx> {
301    AssocItem(DefId, GenericArgsRef<'tcx>),
302    Variant { adt: Ty<'tcx>, variant_did: DefId },
303    Ctor { ctor_def_id: DefId, args: GenericArgsRef<'tcx> },
304}
305
306/// New-typed boolean indicating whether explicit late-bound lifetimes
307/// are present in a set of generic arguments.
308///
309/// For example if we have some method `fn f<'a>(&'a self)` implemented
310/// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
311/// is late-bound so should not be provided explicitly. Thus, if `f` is
312/// instantiated with some generic arguments providing `'a` explicitly,
313/// we taint those arguments with `ExplicitLateBound::Yes` so that we
314/// can provide an appropriate diagnostic later.
315#[derive(#[automatically_derived]
impl ::core::marker::Copy for ExplicitLateBound { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ExplicitLateBound {
    #[inline]
    fn clone(&self) -> ExplicitLateBound { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ExplicitLateBound {
    #[inline]
    fn eq(&self, other: &ExplicitLateBound) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for ExplicitLateBound {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ExplicitLateBound::Yes => "Yes",
                ExplicitLateBound::No => "No",
            })
    }
}Debug)]
316pub enum ExplicitLateBound {
317    Yes,
318    No,
319}
320
321#[derive(#[automatically_derived]
impl ::core::fmt::Debug for IsMethodCall {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                IsMethodCall::Yes => "Yes",
                IsMethodCall::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for IsMethodCall { }Copy, #[automatically_derived]
impl ::core::clone::Clone for IsMethodCall {
    #[inline]
    fn clone(&self) -> IsMethodCall { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for IsMethodCall {
    #[inline]
    fn eq(&self, other: &IsMethodCall) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
322pub enum IsMethodCall {
323    Yes,
324    No,
325}
326
327/// Denotes the "position" of a generic argument, indicating if it is a generic type,
328/// generic function or generic method call.
329#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GenericArgPosition {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            GenericArgPosition::Type =>
                ::core::fmt::Formatter::write_str(f, "Type"),
            GenericArgPosition::Value(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Value",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for GenericArgPosition { }Copy, #[automatically_derived]
impl ::core::clone::Clone for GenericArgPosition {
    #[inline]
    fn clone(&self) -> GenericArgPosition {
        let _: ::core::clone::AssertParamIsClone<IsMethodCall>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for GenericArgPosition {
    #[inline]
    fn eq(&self, other: &GenericArgPosition) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (GenericArgPosition::Value(__self_0),
                    GenericArgPosition::Value(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
330pub(crate) enum GenericArgPosition {
331    Type,
332    Value(IsMethodCall),
333}
334
335/// Whether to allow duplicate associated iten constraints in a trait ref, e.g.
336/// `Trait<Assoc = Ty, Assoc = Ty>`. This is forbidden in `dyn Trait<...>`
337/// but allowed everywhere else.
338#[derive(#[automatically_derived]
impl ::core::clone::Clone for OverlappingAsssocItemConstraints {
    #[inline]
    fn clone(&self) -> OverlappingAsssocItemConstraints { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for OverlappingAsssocItemConstraints { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for OverlappingAsssocItemConstraints {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                OverlappingAsssocItemConstraints::Allowed => "Allowed",
                OverlappingAsssocItemConstraints::Forbidden => "Forbidden",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for OverlappingAsssocItemConstraints {
    #[inline]
    fn eq(&self, other: &OverlappingAsssocItemConstraints) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
339pub(crate) enum OverlappingAsssocItemConstraints {
340    Allowed,
341    Forbidden,
342}
343
344/// A marker denoting that the generic arguments that were
345/// provided did not match the respective generic parameters.
346#[derive(#[automatically_derived]
impl ::core::clone::Clone for GenericArgCountMismatch {
    #[inline]
    fn clone(&self) -> GenericArgCountMismatch {
        GenericArgCountMismatch {
            reported: ::core::clone::Clone::clone(&self.reported),
            invalid_args: ::core::clone::Clone::clone(&self.invalid_args),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for GenericArgCountMismatch {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "GenericArgCountMismatch", "reported", &self.reported,
            "invalid_args", &&self.invalid_args)
    }
}Debug)]
347pub struct GenericArgCountMismatch {
348    pub reported: ErrorGuaranteed,
349    /// A list of indices of arguments provided that were not valid.
350    pub invalid_args: Vec<usize>,
351}
352
353/// Decorates the result of a generic argument count mismatch
354/// check with whether explicit late bounds were provided.
355#[derive(#[automatically_derived]
impl ::core::clone::Clone for GenericArgCountResult {
    #[inline]
    fn clone(&self) -> GenericArgCountResult {
        GenericArgCountResult {
            explicit_late_bound: ::core::clone::Clone::clone(&self.explicit_late_bound),
            correct: ::core::clone::Clone::clone(&self.correct),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for GenericArgCountResult {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "GenericArgCountResult", "explicit_late_bound",
            &self.explicit_late_bound, "correct", &&self.correct)
    }
}Debug)]
356pub struct GenericArgCountResult {
357    pub explicit_late_bound: ExplicitLateBound,
358    pub correct: Result<(), GenericArgCountMismatch>,
359}
360
361/// A context which can lower HIR's [`GenericArg`] to `rustc_middle`'s [`ty::GenericArg`].
362///
363/// Its only consumer is [`generics::lower_generic_args`].
364/// Read its documentation to learn more.
365pub trait GenericArgsLowerer<'a, 'tcx> {
366    fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool);
367
368    fn provided_kind(
369        &mut self,
370        preceding_args: &[ty::GenericArg<'tcx>],
371        param: &ty::GenericParamDef,
372        arg: &GenericArg<'tcx>,
373    ) -> ty::GenericArg<'tcx>;
374
375    fn inferred_kind(
376        &mut self,
377        preceding_args: &[ty::GenericArg<'tcx>],
378        param: &ty::GenericParamDef,
379        infer_args: bool,
380    ) -> ty::GenericArg<'tcx>;
381}
382
383/// Context in which `ForbidParamUsesFolder` is being used, to emit appropriate diagnostics.
384enum ForbidParamContext {
385    /// Anon const in a const argument position.
386    ConstArgument,
387    /// Enum discriminant expression.
388    EnumDiscriminant,
389}
390
391struct ForbidParamUsesFolder<'tcx> {
392    tcx: TyCtxt<'tcx>,
393    anon_const_def_id: LocalDefId,
394    span: Span,
395    is_self_alias: bool,
396    context: ForbidParamContext,
397}
398
399impl<'tcx> ForbidParamUsesFolder<'tcx> {
400    fn error(&self) -> ErrorGuaranteed {
401        let msg = match self.context {
402            ForbidParamContext::EnumDiscriminant if self.is_self_alias => {
403                "generic `Self` types are not permitted in enum discriminant values"
404            }
405            ForbidParamContext::EnumDiscriminant => {
406                "generic parameters may not be used in enum discriminant values"
407            }
408            ForbidParamContext::ConstArgument if self.is_self_alias => {
409                "generic `Self` types are currently not permitted in anonymous constants"
410            }
411            ForbidParamContext::ConstArgument => {
412                if self.tcx.features().generic_const_args() {
413                    "generic parameters in const blocks are only allowed as the direct value of a `type const`"
414                } else {
415                    "generic parameters may not be used in const operations"
416                }
417            }
418        };
419        let mut diag = self.tcx.dcx().struct_span_err(self.span, msg);
420        if self.is_self_alias && #[allow(non_exhaustive_omitted_patterns)] match self.context {
    ForbidParamContext::ConstArgument => true,
    _ => false,
}matches!(self.context, ForbidParamContext::ConstArgument) {
421            let anon_const_hir_id: HirId = HirId::make_owner(self.anon_const_def_id);
422            let parent_impl = self.tcx.hir_parent_owner_iter(anon_const_hir_id).find_map(
423                |(_, node)| match node {
424                    hir::OwnerNode::Item(hir::Item {
425                        kind: hir::ItemKind::Impl(impl_), ..
426                    }) => Some(impl_),
427                    _ => None,
428                },
429            );
430            if let Some(impl_) = parent_impl {
431                diag.span_note(impl_.self_ty.span, "not a concrete type");
432            }
433        }
434        if #[allow(non_exhaustive_omitted_patterns)] match self.context {
    ForbidParamContext::ConstArgument => true,
    _ => false,
}matches!(self.context, ForbidParamContext::ConstArgument)
435            && self.tcx.features().min_generic_const_args()
436        {
437            if !self.tcx.features().generic_const_args() {
438                diag.help("add `#![feature(generic_const_args)]` to allow generic expressions as the RHS of const items");
439            } else {
440                diag.help("consider factoring the expression into a `type const` item and use it as the const argument instead");
441            }
442        }
443        diag.emit()
444    }
445}
446
447impl<'tcx> ty::TypeFolder<TyCtxt<'tcx>> for ForbidParamUsesFolder<'tcx> {
448    fn cx(&self) -> TyCtxt<'tcx> {
449        self.tcx
450    }
451
452    fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
453        if #[allow(non_exhaustive_omitted_patterns)] match t.kind() {
    ty::Param(..) => true,
    _ => false,
}matches!(t.kind(), ty::Param(..)) {
454            return Ty::new_error(self.tcx, self.error());
455        }
456        t.super_fold_with(self)
457    }
458
459    fn fold_const(&mut self, c: Const<'tcx>) -> Const<'tcx> {
460        if #[allow(non_exhaustive_omitted_patterns)] match c.kind() {
    ty::ConstKind::Param(..) => true,
    _ => false,
}matches!(c.kind(), ty::ConstKind::Param(..)) {
461            return Const::new_error(self.tcx, self.error());
462        }
463        c.super_fold_with(self)
464    }
465
466    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
467        if #[allow(non_exhaustive_omitted_patterns)] match r.kind() {
    ty::RegionKind::ReEarlyParam(..) | ty::RegionKind::ReLateParam(..) =>
        true,
    _ => false,
}matches!(r.kind(), ty::RegionKind::ReEarlyParam(..) | ty::RegionKind::ReLateParam(..)) {
468            return ty::Region::new_error(self.tcx, self.error());
469        }
470        r
471    }
472}
473
474impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
475    /// See `check_param_uses_if_mcg`.
476    ///
477    /// FIXME(mgca): this is pub only for instantiate_value_path and would be nice to avoid altogether
478    pub fn check_param_res_if_mcg_for_instantiate_value_path(
479        &self,
480        res: Res,
481        span: Span,
482    ) -> Result<(), ErrorGuaranteed> {
483        let tcx = self.tcx();
484        let parent_def_id = self.item_def_id();
485        if let Res::Def(DefKind::ConstParam, _) = res
486            && tcx.def_kind(parent_def_id) == DefKind::AnonConst
487            && let ty::AnonConstKind::MCG = tcx.anon_const_kind(parent_def_id)
488        {
489            let folder = ForbidParamUsesFolder {
490                tcx,
491                anon_const_def_id: parent_def_id,
492                span,
493                is_self_alias: false,
494                context: ForbidParamContext::ConstArgument,
495            };
496            return Err(folder.error());
497        }
498        Ok(())
499    }
500
501    /// Returns the `ForbidParamContext` for the current anon const if it is a context that
502    /// forbids uses of generic parameters. `None` if the current item is not such a context.
503    ///
504    /// Name resolution handles most invalid generic parameter uses in these contexts, but it
505    /// cannot reject `Self` that aliases a generic type, nor generic parameters introduced by
506    /// type-dependent name resolution (e.g. `<Self as Trait>::Assoc` resolving to a type that
507    /// contains params). Those cases are handled by `check_param_uses_if_mcg`.
508    fn anon_const_forbids_generic_params(&self) -> Option<ForbidParamContext> {
509        let tcx = self.tcx();
510        let parent_def_id = self.item_def_id();
511
512        // Inline consts and closures can be nested inside anon consts that forbid generic
513        // params (e.g. an enum discriminant). Walk up the def parent chain to find the
514        // nearest enclosing AnonConst and use that to determine the context.
515        let anon_const_def_id = match tcx.def_kind(parent_def_id) {
516            DefKind::AnonConst => parent_def_id,
517            DefKind::InlineConst | DefKind::Closure => {
518                let root = tcx.typeck_root_def_id(parent_def_id.into());
519                match tcx.def_kind(root) {
520                    DefKind::AnonConst => root.expect_local(),
521                    _ => return None,
522                }
523            }
524            _ => return None,
525        };
526
527        match tcx.anon_const_kind(anon_const_def_id) {
528            ty::AnonConstKind::MCG => Some(ForbidParamContext::ConstArgument),
529            ty::AnonConstKind::NonTypeSystem => {
530                // NonTypeSystem anon consts only have accessible generic parameters in specific
531                // positions (ty patterns and field defaults — see `generics_of`). In all other
532                // positions (e.g. enum discriminants) generic parameters are not in scope.
533                if tcx.generics_of(anon_const_def_id).count() == 0 {
534                    Some(ForbidParamContext::EnumDiscriminant)
535                } else {
536                    None
537                }
538            }
539            ty::AnonConstKind::GCE
540            | ty::AnonConstKind::GCA
541            | ty::AnonConstKind::RepeatExprCount => None,
542        }
543    }
544
545    /// Check for uses of generic parameters that are not in scope due to this being
546    /// in a non-generic anon const context (e.g. MCG or an enum discriminant).
547    ///
548    /// Name resolution rejects most invalid uses, but cannot handle `Self` aliasing a
549    /// generic type or generic parameters introduced by type-dependent name resolution.
550    #[must_use = "need to use transformed output"]
551    fn check_param_uses_if_mcg<T>(&self, term: T, span: Span, is_self_alias: bool) -> T
552    where
553        T: ty::TypeFoldable<TyCtxt<'tcx>>,
554    {
555        let tcx = self.tcx();
556        if let Some(context) = self.anon_const_forbids_generic_params()
557            // Fast path if contains no params/escaping bound vars.
558            && (term.has_param() || term.has_escaping_bound_vars())
559        {
560            let anon_const_def_id = self.item_def_id();
561            let mut folder =
562                ForbidParamUsesFolder { tcx, anon_const_def_id, span, is_self_alias, context };
563            term.fold_with(&mut folder)
564        } else {
565            term
566        }
567    }
568
569    /// Lower a lifetime from the HIR to our internal notion of a lifetime called a *region*.
570    x;#[instrument(level = "debug", skip(self), ret)]
571    pub fn lower_lifetime(
572        &self,
573        lifetime: &hir::Lifetime,
574        reason: RegionInferReason<'_>,
575    ) -> ty::Region<'tcx> {
576        if let Some(resolved) = self.tcx().named_bound_var(lifetime.hir_id) {
577            let region = self.lower_resolved_lifetime(resolved);
578            self.check_param_uses_if_mcg(region, lifetime.ident.span, false)
579        } else {
580            self.re_infer(lifetime.ident.span, reason)
581        }
582    }
583
584    /// Lower a lifetime from the HIR to our internal notion of a lifetime called a *region*.
585    x;#[instrument(level = "debug", skip(self), ret)]
586    fn lower_resolved_lifetime(&self, resolved: rbv::ResolvedArg) -> ty::Region<'tcx> {
587        let tcx = self.tcx();
588
589        match resolved {
590            rbv::ResolvedArg::StaticLifetime => tcx.lifetimes.re_static,
591
592            rbv::ResolvedArg::LateBound(debruijn, index, def_id) => {
593                let br = ty::BoundRegion {
594                    var: ty::BoundVar::from_u32(index),
595                    kind: ty::BoundRegionKind::Named(def_id.to_def_id()),
596                };
597                ty::Region::new_bound(tcx, debruijn, br)
598            }
599
600            rbv::ResolvedArg::EarlyBound(def_id) => {
601                let name = tcx.hir_ty_param_name(def_id);
602                let item_def_id = tcx.hir_ty_param_owner(def_id);
603                let generics = tcx.generics_of(item_def_id);
604                let index = generics.param_def_id_to_index[&def_id.to_def_id()];
605                ty::Region::new_early_param(tcx, ty::EarlyParamRegion { index, name })
606            }
607
608            rbv::ResolvedArg::Free(scope, id) => {
609                ty::Region::new_late_param(
610                    tcx,
611                    scope.to_def_id(),
612                    ty::LateParamRegionKind::Named(id.to_def_id()),
613                )
614
615                // (*) -- not late-bound, won't change
616            }
617
618            rbv::ResolvedArg::Error(guar) => ty::Region::new_error(tcx, guar),
619        }
620    }
621
622    pub fn lower_generic_args_of_path_segment(
623        &self,
624        span: Span,
625        def_id: DefId,
626        item_segment: &hir::PathSegment<'tcx>,
627    ) -> GenericArgsRef<'tcx> {
628        let (args, _) = self.lower_generic_args_of_path(span, def_id, &[], item_segment, None);
629        if let Some(c) = item_segment.args().constraints.first() {
630            prohibit_assoc_item_constraint(self, c, Some((def_id, item_segment, span)));
631        }
632        args
633    }
634
635    /// Lower the generic arguments provided to some path.
636    ///
637    /// If this is a trait reference, you also need to pass the self type `self_ty`.
638    /// The lowering process may involve applying defaulted type parameters.
639    ///
640    /// Associated item constraints are not handled here! They are either lowered via
641    /// `lower_assoc_item_constraint` or rejected via `prohibit_assoc_item_constraint`.
642    ///
643    /// ### Example
644    ///
645    /// ```ignore (illustrative)
646    ///    T: std::ops::Index<usize, Output = u32>
647    /// // ^1 ^^^^^^^^^^^^^^2 ^^^^3  ^^^^^^^^^^^4
648    /// ```
649    ///
650    /// 1. The `self_ty` here would refer to the type `T`.
651    /// 2. The path in question is the path to the trait `std::ops::Index`,
652    ///    which will have been resolved to a `def_id`
653    /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
654    ///    parameters are returned in the `GenericArgsRef`
655    /// 4. Associated item constraints like `Output = u32` are contained in `generic_args.constraints`.
656    ///
657    /// Note that the type listing given here is *exactly* what the user provided.
658    ///
659    /// For (generic) associated types
660    ///
661    /// ```ignore (illustrative)
662    /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
663    /// ```
664    ///
665    /// We have the parent args are the args for the parent trait:
666    /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
667    /// type itself: `['a]`. The returned `GenericArgsRef` concatenates these two
668    /// lists: `[Vec<u8>, u8, 'a]`.
669    x;#[instrument(level = "debug", skip(self, span), ret)]
670    pub(crate) fn lower_generic_args_of_path(
671        &self,
672        span: Span,
673        def_id: DefId,
674        parent_args: &[ty::GenericArg<'tcx>],
675        segment: &hir::PathSegment<'tcx>,
676        self_ty: Option<Ty<'tcx>>,
677    ) -> (GenericArgsRef<'tcx>, GenericArgCountResult) {
678        // If the type is parameterized by this region, then replace this
679        // region with the current anon region binding (in other words,
680        // whatever & would get replaced with).
681
682        let tcx = self.tcx();
683        let generics = tcx.generics_of(def_id);
684        debug!(?generics);
685
686        if generics.has_self {
687            if generics.parent.is_some() {
688                // The parent is a trait so it should have at least one
689                // generic parameter for the `Self` type.
690                assert!(!parent_args.is_empty())
691            } else {
692                // This item (presumably a trait) needs a self-type.
693                assert!(self_ty.is_some());
694            }
695        } else {
696            assert!(self_ty.is_none());
697        }
698
699        let arg_count = check_generic_arg_count(
700            self,
701            def_id,
702            segment,
703            generics,
704            GenericArgPosition::Type,
705            self_ty.is_some(),
706        );
707
708        // Skip processing if type has no generic parameters.
709        // Traits always have `Self` as a generic parameter, which means they will not return early
710        // here and so associated item constraints will be handled regardless of whether there are
711        // any non-`Self` generic parameters.
712        if generics.is_own_empty() {
713            return (tcx.mk_args(parent_args), arg_count);
714        }
715
716        struct GenericArgsCtxt<'a, 'tcx> {
717            lowerer: &'a dyn HirTyLowerer<'tcx>,
718            def_id: DefId,
719            generic_args: &'a GenericArgs<'tcx>,
720            span: Span,
721            infer_args: bool,
722            incorrect_args: &'a Result<(), GenericArgCountMismatch>,
723        }
724
725        impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for GenericArgsCtxt<'a, 'tcx> {
726            fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool) {
727                if did == self.def_id {
728                    (Some(self.generic_args), self.infer_args)
729                } else {
730                    // The last component of this tuple is unimportant.
731                    (None, false)
732                }
733            }
734
735            fn provided_kind(
736                &mut self,
737                preceding_args: &[ty::GenericArg<'tcx>],
738                param: &ty::GenericParamDef,
739                arg: &GenericArg<'tcx>,
740            ) -> ty::GenericArg<'tcx> {
741                let tcx = self.lowerer.tcx();
742
743                if let Err(incorrect) = self.incorrect_args {
744                    if incorrect.invalid_args.contains(&(param.index as usize)) {
745                        return param.to_error(tcx);
746                    }
747                }
748
749                let handle_ty_args = |has_default, ty: &hir::Ty<'tcx>| {
750                    if has_default {
751                        tcx.check_optional_stability(
752                            param.def_id,
753                            Some(arg.hir_id()),
754                            arg.span(),
755                            None,
756                            AllowUnstable::No,
757                            |_, _| {
758                                // Default generic parameters may not be marked
759                                // with stability attributes, i.e. when the
760                                // default parameter was defined at the same time
761                                // as the rest of the type. As such, we ignore missing
762                                // stability attributes.
763                            },
764                        );
765                    }
766                    self.lowerer.lower_ty(ty).into()
767                };
768
769                match (&param.kind, arg) {
770                    (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
771                        self.lowerer.lower_lifetime(lt, RegionInferReason::Param(param)).into()
772                    }
773                    (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
774                        // We handle the other parts of `Ty` in the match arm below
775                        handle_ty_args(has_default, ty.as_unambig_ty())
776                    }
777                    (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
778                        handle_ty_args(has_default, &inf.to_ty())
779                    }
780                    (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => self
781                        .lowerer
782                        // Ambig portions of `ConstArg` are handled in the match arm below
783                        .lower_const_arg(
784                            ct.as_unambig_ct(),
785                            tcx.type_of(param.def_id).instantiate(tcx, preceding_args),
786                        )
787                        .into(),
788                    (&GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
789                        self.lowerer.ct_infer(Some(param), inf.span).into()
790                    }
791                    (kind, arg) => span_bug!(
792                        self.span,
793                        "mismatched path argument for kind {kind:?}: found arg {arg:?}"
794                    ),
795                }
796            }
797
798            fn inferred_kind(
799                &mut self,
800                preceding_args: &[ty::GenericArg<'tcx>],
801                param: &ty::GenericParamDef,
802                infer_args: bool,
803            ) -> ty::GenericArg<'tcx> {
804                let tcx = self.lowerer.tcx();
805
806                if let Err(incorrect) = self.incorrect_args {
807                    if incorrect.invalid_args.contains(&(param.index as usize)) {
808                        return param.to_error(tcx);
809                    }
810                }
811                match param.kind {
812                    GenericParamDefKind::Lifetime => {
813                        self.lowerer.re_infer(self.span, RegionInferReason::Param(param)).into()
814                    }
815                    GenericParamDefKind::Type { has_default, synthetic } => {
816                        if !infer_args && has_default {
817                            // No type parameter provided, but a default exists.
818                            if let Some(prev) =
819                                preceding_args.iter().find_map(|arg| match arg.kind() {
820                                    GenericArgKind::Type(ty) => ty.error_reported().err(),
821                                    _ => None,
822                                })
823                            {
824                                // Avoid ICE #86756 when type error recovery goes awry.
825                                return Ty::new_error(tcx, prev).into();
826                            }
827                            tcx.at(self.span)
828                                .type_of(param.def_id)
829                                .instantiate(tcx, preceding_args)
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                        if let Err(guar) = ty.error_reported() {
846                            return ty::Const::new_error(tcx, guar).into();
847                        }
848                        if !infer_args && has_default {
849                            tcx.const_param_default(param.def_id)
850                                .instantiate(tcx, preceding_args)
851                                .into()
852                        } else if infer_args {
853                            self.lowerer.ct_infer(Some(param), self.span).into()
854                        } else {
855                            // We've already errored above about the mismatch.
856                            ty::Const::new_misc_error(tcx).into()
857                        }
858                    }
859                }
860            }
861        }
862
863        let mut args_ctx = GenericArgsCtxt {
864            lowerer: self,
865            def_id,
866            span,
867            generic_args: segment.args(),
868            infer_args: segment.infer_args,
869            incorrect_args: &arg_count.correct,
870        };
871
872        let args = lower_generic_args(
873            self,
874            def_id,
875            parent_args,
876            self_ty.is_some(),
877            self_ty,
878            &arg_count,
879            &mut args_ctx,
880        );
881
882        (args, arg_count)
883    }
884
885    #[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(885u32),
                                    ::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))]
886    pub fn lower_generic_args_of_assoc_item(
887        &self,
888        span: Span,
889        item_def_id: DefId,
890        item_segment: &hir::PathSegment<'tcx>,
891        parent_args: GenericArgsRef<'tcx>,
892    ) -> GenericArgsRef<'tcx> {
893        let (args, _) =
894            self.lower_generic_args_of_path(span, item_def_id, parent_args, item_segment, None);
895        if let Some(c) = item_segment.args().constraints.first() {
896            prohibit_assoc_item_constraint(self, c, Some((item_def_id, item_segment, span)));
897        }
898        args
899    }
900
901    /// Lower a trait reference as found in an impl header as the implementee.
902    ///
903    /// The self type `self_ty` is the implementer of the trait.
904    pub fn lower_impl_trait_ref(
905        &self,
906        trait_ref: &hir::TraitRef<'tcx>,
907        self_ty: Ty<'tcx>,
908    ) -> ty::TraitRef<'tcx> {
909        let [leading_segments @ .., segment] = trait_ref.path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
910
911        let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
912
913        self.lower_mono_trait_ref(
914            trait_ref.path.span,
915            trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
916            self_ty,
917            segment,
918            true,
919        )
920    }
921
922    /// Lower a polymorphic trait reference given a self type into `bounds`.
923    ///
924    /// *Polymorphic* in the sense that it may bind late-bound vars.
925    ///
926    /// This may generate auxiliary bounds iff the trait reference contains associated item constraints.
927    ///
928    /// ### Example
929    ///
930    /// Given the trait ref `Iterator<Item = u32>` and the self type `Ty`, this will add the
931    ///
932    /// 1. *trait predicate* `<Ty as Iterator>` (known as `Ty: Iterator` in the surface syntax) and the
933    /// 2. *projection predicate* `<Ty as Iterator>::Item = u32`
934    ///
935    /// to `bounds`.
936    ///
937    /// ### A Note on Binders
938    ///
939    /// Against our usual convention, there is an implied binder around the `self_ty` and the
940    /// `trait_ref` here. So they may reference late-bound vars.
941    ///
942    /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
943    /// where `'a` is a bound region at depth 0. Similarly, the `trait_ref` would be `Bar<'a>`.
944    /// The lowered poly-trait-ref will track this binder explicitly, however.
945    #[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(945u32),
                                    ::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:1025",
                                    "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(1025u32),
                                    ::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:1032",
                                    "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(1032u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["poly_trait_ref"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&poly_trait_ref)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            match predicate_filter {
                PredicateFilter::All | PredicateFilter::SelfOnly |
                    PredicateFilter::SelfTraitThatDefines(..) |
                    PredicateFilter::SelfAndAssociatedTypeBounds => {
                    let bound =
                        poly_trait_ref.map_bound(|trait_ref|
                                {
                                    ty::ClauseKind::Trait(ty::TraitPredicate {
                                            trait_ref,
                                            polarity,
                                        })
                                });
                    let bound = (bound.upcast(tcx), span);
                    if tcx.is_lang_item(trait_def_id,
                            rustc_hir::LangItem::Sized) {
                        bounds.insert(0, bound);
                    } else { bounds.push(bound); }
                }
                PredicateFilter::ConstIfConst |
                    PredicateFilter::SelfConstIfConst => {}
            }
            if let hir::BoundConstness::Always(span) |
                        hir::BoundConstness::Maybe(span) = constness &&
                    !tcx.is_const_trait(trait_def_id) {
                let (def_span, suggestion, suggestion_pre) =
                    match (trait_def_id.as_local(), tcx.sess.is_nightly_build())
                        {
                        (Some(trait_def_id), true) => {
                            let span = tcx.hir_expect_item(trait_def_id).vis_span;
                            let span =
                                tcx.sess.source_map().span_extend_while_whitespace(span);
                            (None, Some(span.shrink_to_hi()),
                                if self.tcx().features().const_trait_impl() {
                                    ""
                                } else {
                                    "enable `#![feature(const_trait_impl)]` in your crate and "
                                })
                        }
                        (None, _) | (_, false) =>
                            (Some(tcx.def_span(trait_def_id)), None, ""),
                    };
                self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait {
                        span,
                        modifier: constness.as_str(),
                        def_span,
                        trait_name: tcx.def_path_str(trait_def_id),
                        suggestion,
                        suggestion_pre,
                    });
            } else {
                match predicate_filter {
                    PredicateFilter::SelfTraitThatDefines(..) => {}
                    PredicateFilter::All | PredicateFilter::SelfOnly |
                        PredicateFilter::SelfAndAssociatedTypeBounds => {
                        match constness {
                            hir::BoundConstness::Always(_) => {
                                if polarity == ty::PredicatePolarity::Positive {
                                    bounds.push((poly_trait_ref.to_host_effect_clause(tcx,
                                                ty::BoundConstness::Const), span));
                                }
                            }
                            hir::BoundConstness::Maybe(_) => {}
                            hir::BoundConstness::Never => {}
                        }
                    }
                    PredicateFilter::ConstIfConst |
                        PredicateFilter::SelfConstIfConst => {
                        match constness {
                            hir::BoundConstness::Maybe(_) => {
                                if polarity == ty::PredicatePolarity::Positive {
                                    bounds.push((poly_trait_ref.to_host_effect_clause(tcx,
                                                ty::BoundConstness::Maybe), span));
                                }
                            }
                            hir::BoundConstness::Always(_) | hir::BoundConstness::Never
                                => {}
                        }
                    }
                }
            }
            let mut dup_constraints =
                (overlapping_assoc_item_constraints ==
                            OverlappingAsssocItemConstraints::Forbidden).then_some(FxIndexMap::default());
            for constraint in constraints {
                if polarity == ty::PredicatePolarity::Negative {
                    self.dcx().span_delayed_bug(constraint.span,
                        "negative trait bounds should not have assoc item constraints");
                    break;
                }
                let _: Result<_, ErrorGuaranteed> =
                    self.lower_assoc_item_constraint(trait_ref.hir_ref_id,
                        poly_trait_ref, constraint, bounds,
                        dup_constraints.as_mut(), constraint.span,
                        predicate_filter);
            }
            arg_count
        }
    }
}#[instrument(level = "debug", skip(self, bounds))]
946    pub(crate) fn lower_poly_trait_ref(
947        &self,
948        &hir::PolyTraitRef {
949            bound_generic_params,
950            modifiers: hir::TraitBoundModifiers { constness, polarity },
951            trait_ref,
952            span,
953        }: &hir::PolyTraitRef<'tcx>,
954        self_ty: Ty<'tcx>,
955        bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
956        predicate_filter: PredicateFilter,
957        overlapping_assoc_item_constraints: OverlappingAsssocItemConstraints,
958    ) -> GenericArgCountResult {
959        let tcx = self.tcx();
960
961        // We use the *resolved* bound vars later instead of the HIR ones since the former
962        // also include the bound vars of the overarching predicate if applicable.
963        let _ = bound_generic_params;
964
965        let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
966
967        // Relaxed bounds `?Trait` and `PointeeSized` bounds aren't represented in the middle::ty IR
968        // as they denote the *absence* of a default bound. However, we can't bail out early here since
969        // we still need to perform several validation steps (see below). Instead, simply "pour" all
970        // resulting bounds "down the drain", i.e., into a new `Vec` that just gets dropped at the end.
971        let transient = match polarity {
972            hir::BoundPolarity::Positive => {
973                // To elaborate on the comment directly above, regarding `PointeeSized` specifically,
974                // we don't "reify" such bounds to avoid trait system limitations -- namely,
975                // non-global where-clauses being preferred over item bounds (where `PointeeSized`
976                // bounds would be proven) -- which can result in errors when a `PointeeSized`
977                // supertrait / bound / predicate is added to some items.
978                tcx.is_lang_item(trait_def_id, hir::LangItem::PointeeSized)
979            }
980            hir::BoundPolarity::Negative(_) => false,
981            hir::BoundPolarity::Maybe(_) => {
982                self.require_bound_to_relax_default_trait(trait_ref, span);
983                true
984            }
985        };
986        let bounds = if transient { &mut Vec::new() } else { bounds };
987
988        let polarity = match polarity {
989            hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_) => {
990                ty::PredicatePolarity::Positive
991            }
992            hir::BoundPolarity::Negative(_) => ty::PredicatePolarity::Negative,
993        };
994
995        let [leading_segments @ .., segment] = trait_ref.path.segments else { bug!() };
996
997        let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
998        self.report_internal_fn_trait(span, trait_def_id, segment, false);
999
1000        let (generic_args, arg_count) = self.lower_generic_args_of_path(
1001            trait_ref.path.span,
1002            trait_def_id,
1003            &[],
1004            segment,
1005            Some(self_ty),
1006        );
1007
1008        let constraints = segment.args().constraints;
1009
1010        if transient && (!generic_args[1..].is_empty() || !constraints.is_empty()) {
1011            // Since the bound won't be present in the middle::ty IR as established above, any
1012            // arguments or constraints won't be checked for well-formedness in later passes.
1013            //
1014            // This is only an issue if the trait ref is otherwise valid which can only happen if
1015            // the corresponding default trait has generic parameters or associated items. Such a
1016            // trait would be degenerate. We delay a bug to detect and guard us against these.
1017            //
1018            // E.g: Given `/*default*/ trait Bound<'a: 'static, T, const N: usize> {}`,
1019            // `?Bound<Vec<str>, { panic!() }>` won't be wfchecked.
1020            self.dcx()
1021                .span_delayed_bug(span, "transient bound should not have args or constraints");
1022        }
1023
1024        let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
1025        debug!(?bound_vars);
1026
1027        let poly_trait_ref = ty::Binder::bind_with_vars(
1028            ty::TraitRef::new_from_args(tcx, trait_def_id, generic_args),
1029            bound_vars,
1030        );
1031
1032        debug!(?poly_trait_ref);
1033
1034        // We deal with const conditions later.
1035        match predicate_filter {
1036            PredicateFilter::All
1037            | PredicateFilter::SelfOnly
1038            | PredicateFilter::SelfTraitThatDefines(..)
1039            | PredicateFilter::SelfAndAssociatedTypeBounds => {
1040                let bound = poly_trait_ref.map_bound(|trait_ref| {
1041                    ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity })
1042                });
1043                let bound = (bound.upcast(tcx), span);
1044                // FIXME(-Znext-solver): We can likely remove this hack once the
1045                // new trait solver lands. This fixed an overflow in the old solver.
1046                // This may have performance implications, so please check perf when
1047                // removing it.
1048                // This was added in <https://github.com/rust-lang/rust/pull/123302>.
1049                if tcx.is_lang_item(trait_def_id, rustc_hir::LangItem::Sized) {
1050                    bounds.insert(0, bound);
1051                } else {
1052                    bounds.push(bound);
1053                }
1054            }
1055            PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
1056        }
1057
1058        if let hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) = constness
1059            && !tcx.is_const_trait(trait_def_id)
1060        {
1061            let (def_span, suggestion, suggestion_pre) =
1062                match (trait_def_id.as_local(), tcx.sess.is_nightly_build()) {
1063                    (Some(trait_def_id), true) => {
1064                        let span = tcx.hir_expect_item(trait_def_id).vis_span;
1065                        let span = tcx.sess.source_map().span_extend_while_whitespace(span);
1066
1067                        (
1068                            None,
1069                            Some(span.shrink_to_hi()),
1070                            if self.tcx().features().const_trait_impl() {
1071                                ""
1072                            } else {
1073                                "enable `#![feature(const_trait_impl)]` in your crate and "
1074                            },
1075                        )
1076                    }
1077                    (None, _) | (_, false) => (Some(tcx.def_span(trait_def_id)), None, ""),
1078                };
1079            self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait {
1080                span,
1081                modifier: constness.as_str(),
1082                def_span,
1083                trait_name: tcx.def_path_str(trait_def_id),
1084                suggestion,
1085                suggestion_pre,
1086            });
1087        } else {
1088            match predicate_filter {
1089                // This is only concerned with trait predicates.
1090                PredicateFilter::SelfTraitThatDefines(..) => {}
1091                PredicateFilter::All
1092                | PredicateFilter::SelfOnly
1093                | PredicateFilter::SelfAndAssociatedTypeBounds => {
1094                    match constness {
1095                        hir::BoundConstness::Always(_) => {
1096                            if polarity == ty::PredicatePolarity::Positive {
1097                                bounds.push((
1098                                    poly_trait_ref
1099                                        .to_host_effect_clause(tcx, ty::BoundConstness::Const),
1100                                    span,
1101                                ));
1102                            }
1103                        }
1104                        hir::BoundConstness::Maybe(_) => {
1105                            // We don't emit a const bound here, since that would mean that we
1106                            // unconditionally need to prove a `HostEffect` predicate, even when
1107                            // the predicates are being instantiated in a non-const context. This
1108                            // is instead handled in the `const_conditions` query.
1109                        }
1110                        hir::BoundConstness::Never => {}
1111                    }
1112                }
1113                // On the flip side, when filtering `ConstIfConst` bounds, we only need to convert
1114                // `[const]` bounds. All other predicates are handled in their respective queries.
1115                //
1116                // Note that like `PredicateFilter::SelfOnly`, we don't need to do any filtering
1117                // here because we only call this on self bounds, and deal with the recursive case
1118                // in `lower_assoc_item_constraint`.
1119                PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {
1120                    match constness {
1121                        hir::BoundConstness::Maybe(_) => {
1122                            if polarity == ty::PredicatePolarity::Positive {
1123                                bounds.push((
1124                                    poly_trait_ref
1125                                        .to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1126                                    span,
1127                                ));
1128                            }
1129                        }
1130                        hir::BoundConstness::Always(_) | hir::BoundConstness::Never => {}
1131                    }
1132                }
1133            }
1134        }
1135
1136        let mut dup_constraints = (overlapping_assoc_item_constraints
1137            == OverlappingAsssocItemConstraints::Forbidden)
1138            .then_some(FxIndexMap::default());
1139
1140        for constraint in constraints {
1141            // Don't register any associated item constraints for negative bounds,
1142            // since we should have emitted an error for them earlier, and they
1143            // would not be well-formed!
1144            if polarity == ty::PredicatePolarity::Negative {
1145                self.dcx().span_delayed_bug(
1146                    constraint.span,
1147                    "negative trait bounds should not have assoc item constraints",
1148                );
1149                break;
1150            }
1151
1152            // Specify type to assert that error was already reported in `Err` case.
1153            let _: Result<_, ErrorGuaranteed> = self.lower_assoc_item_constraint(
1154                trait_ref.hir_ref_id,
1155                poly_trait_ref,
1156                constraint,
1157                bounds,
1158                dup_constraints.as_mut(),
1159                constraint.span,
1160                predicate_filter,
1161            );
1162            // Okay to ignore `Err` because of `ErrorGuaranteed` (see above).
1163        }
1164
1165        arg_count
1166    }
1167
1168    /// Lower a monomorphic trait reference given a self type while prohibiting associated item bindings.
1169    ///
1170    /// *Monomorphic* in the sense that it doesn't bind any late-bound vars.
1171    fn lower_mono_trait_ref(
1172        &self,
1173        span: Span,
1174        trait_def_id: DefId,
1175        self_ty: Ty<'tcx>,
1176        trait_segment: &hir::PathSegment<'tcx>,
1177        is_impl: bool,
1178    ) -> ty::TraitRef<'tcx> {
1179        self.report_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
1180
1181        let (generic_args, _) =
1182            self.lower_generic_args_of_path(span, trait_def_id, &[], trait_segment, Some(self_ty));
1183        if let Some(c) = trait_segment.args().constraints.first() {
1184            prohibit_assoc_item_constraint(self, c, Some((trait_def_id, trait_segment, span)));
1185        }
1186        ty::TraitRef::new_from_args(self.tcx(), trait_def_id, generic_args)
1187    }
1188
1189    fn probe_trait_that_defines_assoc_item(
1190        &self,
1191        trait_def_id: DefId,
1192        assoc_tag: ty::AssocTag,
1193        assoc_ident: Ident,
1194    ) -> bool {
1195        self.tcx()
1196            .associated_items(trait_def_id)
1197            .find_by_ident_and_kind(self.tcx(), assoc_ident, assoc_tag, trait_def_id)
1198            .is_some()
1199    }
1200
1201    fn lower_path_segment(
1202        &self,
1203        span: Span,
1204        def_id: DefId,
1205        item_segment: &hir::PathSegment<'tcx>,
1206    ) -> Ty<'tcx> {
1207        let tcx = self.tcx();
1208        let args = self.lower_generic_args_of_path_segment(span, def_id, item_segment);
1209
1210        if let DefKind::TyAlias = tcx.def_kind(def_id)
1211            && tcx.type_alias_is_lazy(def_id)
1212        {
1213            // Type aliases defined in crates that have the
1214            // feature `lazy_type_alias` enabled get encoded as a type alias that normalization will
1215            // then actually instantiate the where bounds of.
1216            let alias_ty = ty::AliasTy::new_from_args(tcx, ty::Free { def_id }, args);
1217            Ty::new_alias(tcx, alias_ty)
1218        } else {
1219            tcx.at(span).type_of(def_id).instantiate(tcx, args)
1220        }
1221    }
1222
1223    /// Search for a trait bound on a type parameter whose trait defines the associated item
1224    /// given by `assoc_ident` and `kind`.
1225    ///
1226    /// This fails if there is no such bound in the list of candidates or if there are multiple
1227    /// candidates in which case it reports ambiguity.
1228    ///
1229    /// `ty_param_def_id` is the `LocalDefId` of the type parameter.
1230    x;#[instrument(level = "debug", skip_all, ret)]
1231    fn probe_single_ty_param_bound_for_assoc_item(
1232        &self,
1233        ty_param_def_id: LocalDefId,
1234        ty_param_span: Span,
1235        assoc_tag: ty::AssocTag,
1236        assoc_ident: Ident,
1237        span: Span,
1238    ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1239        debug!(?ty_param_def_id, ?assoc_ident, ?span);
1240        let tcx = self.tcx();
1241
1242        let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_ident);
1243        debug!("predicates={:#?}", predicates);
1244
1245        self.probe_single_bound_for_assoc_item(
1246            || {
1247                let trait_refs = predicates
1248                    .iter_identity_copied()
1249                    .filter_map(|(p, _)| Some(p.as_trait_clause()?.map_bound(|t| t.trait_ref)));
1250                traits::transitive_bounds_that_define_assoc_item(tcx, trait_refs, assoc_ident)
1251            },
1252            AssocItemQSelf::TyParam(ty_param_def_id, ty_param_span),
1253            assoc_tag,
1254            assoc_ident,
1255            span,
1256            None,
1257        )
1258    }
1259
1260    /// Search for a single trait bound whose trait defines the associated item given by
1261    /// `assoc_ident`.
1262    ///
1263    /// This fails if there is no such bound in the list of candidates or if there are multiple
1264    /// candidates in which case it reports ambiguity.
1265    x;#[instrument(level = "debug", skip(self, all_candidates, qself, constraint), ret)]
1266    fn probe_single_bound_for_assoc_item<I>(
1267        &self,
1268        all_candidates: impl Fn() -> I,
1269        qself: AssocItemQSelf,
1270        assoc_tag: ty::AssocTag,
1271        assoc_ident: Ident,
1272        span: Span,
1273        constraint: Option<&hir::AssocItemConstraint<'tcx>>,
1274    ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1275    where
1276        I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1277    {
1278        let tcx = self.tcx();
1279
1280        let mut matching_candidates = all_candidates().filter(|r| {
1281            self.probe_trait_that_defines_assoc_item(r.def_id(), assoc_tag, assoc_ident)
1282        });
1283
1284        let Some(bound) = matching_candidates.next() else {
1285            return Err(self.report_unresolved_assoc_item(
1286                all_candidates,
1287                qself,
1288                assoc_tag,
1289                assoc_ident,
1290                span,
1291                constraint,
1292            ));
1293        };
1294        debug!(?bound);
1295
1296        if let Some(bound2) = matching_candidates.next() {
1297            debug!(?bound2);
1298
1299            let assoc_kind_str = errors::assoc_tag_str(assoc_tag);
1300            let qself_str = qself.to_string(tcx);
1301            let mut err = self.dcx().create_err(crate::errors::AmbiguousAssocItem {
1302                span,
1303                assoc_kind: assoc_kind_str,
1304                assoc_ident,
1305                qself: &qself_str,
1306            });
1307            // Provide a more specific error code index entry for equality bindings.
1308            err.code(
1309                if let Some(constraint) = constraint
1310                    && let hir::AssocItemConstraintKind::Equality { .. } = constraint.kind
1311                {
1312                    E0222
1313                } else {
1314                    E0221
1315                },
1316            );
1317
1318            // FIXME(#97583): Print associated item bindings properly (i.e., not as equality
1319            // predicates!).
1320            // FIXME: Turn this into a structured, translatable & more actionable suggestion.
1321            let mut where_bounds = vec![];
1322            for bound in [bound, bound2].into_iter().chain(matching_candidates) {
1323                let bound_id = bound.def_id();
1324                let assoc_item = tcx.associated_items(bound_id).find_by_ident_and_kind(
1325                    tcx,
1326                    assoc_ident,
1327                    assoc_tag,
1328                    bound_id,
1329                );
1330                let bound_span = assoc_item.and_then(|item| tcx.hir_span_if_local(item.def_id));
1331
1332                if let Some(bound_span) = bound_span {
1333                    err.span_label(
1334                        bound_span,
1335                        format!("ambiguous `{assoc_ident}` from `{}`", bound.print_trait_sugared(),),
1336                    );
1337                    if let Some(constraint) = constraint {
1338                        match constraint.kind {
1339                            hir::AssocItemConstraintKind::Equality { term } => {
1340                                let term: ty::Term<'_> = match term {
1341                                    hir::Term::Ty(ty) => self.lower_ty(ty).into(),
1342                                    hir::Term::Const(ct) => {
1343                                        let assoc_item =
1344                                            assoc_item.expect("assoc_item should be present");
1345                                        let projection_term = bound.map_bound(|trait_ref| {
1346                                            let item_segment = hir::PathSegment {
1347                                                ident: constraint.ident,
1348                                                hir_id: constraint.hir_id,
1349                                                res: Res::Err,
1350                                                args: Some(constraint.gen_args),
1351                                                infer_args: false,
1352                                            };
1353
1354                                            let alias_args = self.lower_generic_args_of_assoc_item(
1355                                                constraint.ident.span,
1356                                                assoc_item.def_id,
1357                                                &item_segment,
1358                                                trait_ref.args,
1359                                            );
1360                                            ty::AliasTerm::new_from_args(
1361                                                tcx,
1362                                                assoc_item.def_id,
1363                                                alias_args,
1364                                            )
1365                                        });
1366
1367                                        // FIXME(mgca): code duplication with other places we lower
1368                                        // the rhs' of associated const bindings
1369                                        let ty = projection_term.map_bound(|alias| {
1370                                            tcx.type_of(alias.def_id).instantiate(tcx, alias.args)
1371                                        });
1372                                        let ty = bounds::check_assoc_const_binding_type(
1373                                            self,
1374                                            constraint.ident,
1375                                            ty,
1376                                            constraint.hir_id,
1377                                        );
1378
1379                                        self.lower_const_arg(ct, ty).into()
1380                                    }
1381                                };
1382                                if term.references_error() {
1383                                    continue;
1384                                }
1385                                // FIXME(#97583): This isn't syntactically well-formed!
1386                                where_bounds.push(format!(
1387                                    "        T: {trait}::{assoc_ident} = {term}",
1388                                    trait = bound.print_only_trait_path(),
1389                                ));
1390                            }
1391                            // FIXME: Provide a suggestion.
1392                            hir::AssocItemConstraintKind::Bound { bounds: _ } => {}
1393                        }
1394                    } else {
1395                        err.span_suggestion_verbose(
1396                            span.with_hi(assoc_ident.span.lo()),
1397                            "use fully-qualified syntax to disambiguate",
1398                            format!("<{qself_str} as {}>::", bound.print_only_trait_path()),
1399                            Applicability::MaybeIncorrect,
1400                        );
1401                    }
1402                } else {
1403                    let trait_ =
1404                        tcx.short_string(bound.print_only_trait_path(), err.long_ty_path());
1405                    err.note(format!(
1406                        "associated {assoc_kind_str} `{assoc_ident}` could derive from `{trait_}`",
1407                    ));
1408                }
1409            }
1410            if !where_bounds.is_empty() {
1411                err.help(format!(
1412                    "consider introducing a new type parameter `T` and adding `where` constraints:\
1413                     \n    where\n        T: {qself_str},\n{}",
1414                    where_bounds.join(",\n"),
1415                ));
1416                let reported = err.emit();
1417                return Err(reported);
1418            }
1419            err.emit();
1420        }
1421
1422        Ok(bound)
1423    }
1424
1425    /// Lower a [type-relative](hir::QPath::TypeRelative) path in type position to a type.
1426    ///
1427    /// If the path refers to an enum variant and `permit_variants` holds,
1428    /// the returned type is simply the provided self type `qself_ty`.
1429    ///
1430    /// A path like `A::B::C::D` is understood as `<A::B::C>::D`. I.e.,
1431    /// `qself_ty` / `qself` is `A::B::C` and `assoc_segment` is `D`.
1432    /// We return the lowered type and the `DefId` for the whole path.
1433    ///
1434    /// We only support associated type paths whose self type is a type parameter or a `Self`
1435    /// type alias (in a trait impl) like `T::Ty` (where `T` is a ty param) or `Self::Ty`.
1436    /// We **don't** support paths whose self type is an arbitrary type like `Struct::Ty` where
1437    /// struct `Struct` impls an in-scope trait that defines an associated type called `Ty`.
1438    /// For the latter case, we report ambiguity.
1439    /// While desirable to support, the implementation would be non-trivial. Tracked in [#22519].
1440    ///
1441    /// At the time of writing, *inherent associated types* are also resolved here. This however
1442    /// is [problematic][iat]. A proper implementation would be as non-trivial as the one
1443    /// described in the previous paragraph and their modeling of projections would likely be
1444    /// very similar in nature.
1445    ///
1446    /// [#22519]: https://github.com/rust-lang/rust/issues/22519
1447    /// [iat]: https://github.com/rust-lang/rust/issues/8995#issuecomment-1569208403
1448    //
1449    // NOTE: When this function starts resolving `Trait::AssocTy` successfully
1450    // it should also start reporting the `BARE_TRAIT_OBJECTS` lint.
1451    x;#[instrument(level = "debug", skip_all, ret)]
1452    pub fn lower_type_relative_ty_path(
1453        &self,
1454        self_ty: Ty<'tcx>,
1455        hir_self_ty: &'tcx hir::Ty<'tcx>,
1456        segment: &'tcx hir::PathSegment<'tcx>,
1457        qpath_hir_id: HirId,
1458        span: Span,
1459        permit_variants: PermitVariants,
1460    ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1461        let tcx = self.tcx();
1462        match self.lower_type_relative_path(
1463            self_ty,
1464            hir_self_ty,
1465            segment,
1466            qpath_hir_id,
1467            span,
1468            LowerTypeRelativePathMode::Type(permit_variants),
1469        )? {
1470            TypeRelativePath::AssocItem(def_id, args) => {
1471                let alias_ty = ty::AliasTy::new_from_args(
1472                    tcx,
1473                    ty::AliasTyKind::new_from_def_id(tcx, def_id),
1474                    args,
1475                );
1476                let ty = Ty::new_alias(tcx, alias_ty);
1477                let ty = self.check_param_uses_if_mcg(ty, span, false);
1478                Ok((ty, tcx.def_kind(def_id), def_id))
1479            }
1480            TypeRelativePath::Variant { adt, variant_did } => {
1481                let adt = self.check_param_uses_if_mcg(adt, span, false);
1482                Ok((adt, DefKind::Variant, variant_did))
1483            }
1484            TypeRelativePath::Ctor { .. } => {
1485                let e = tcx.dcx().span_err(span, "expected type, found tuple constructor");
1486                Err(e)
1487            }
1488        }
1489    }
1490
1491    /// Lower a [type-relative][hir::QPath::TypeRelative] path to a (type-level) constant.
1492    x;#[instrument(level = "debug", skip_all, ret)]
1493    fn lower_type_relative_const_path(
1494        &self,
1495        self_ty: Ty<'tcx>,
1496        hir_self_ty: &'tcx hir::Ty<'tcx>,
1497        segment: &'tcx hir::PathSegment<'tcx>,
1498        qpath_hir_id: HirId,
1499        span: Span,
1500    ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1501        let tcx = self.tcx();
1502        match self.lower_type_relative_path(
1503            self_ty,
1504            hir_self_ty,
1505            segment,
1506            qpath_hir_id,
1507            span,
1508            LowerTypeRelativePathMode::Const,
1509        )? {
1510            TypeRelativePath::AssocItem(def_id, args) => {
1511                self.require_type_const_attribute(def_id, span)?;
1512                let ct = Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(def_id, args));
1513                let ct = self.check_param_uses_if_mcg(ct, span, false);
1514                Ok(ct)
1515            }
1516            TypeRelativePath::Ctor { ctor_def_id, args } => match tcx.def_kind(ctor_def_id) {
1517                DefKind::Ctor(_, CtorKind::Fn) => {
1518                    Ok(ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, ctor_def_id, args)))
1519                }
1520                DefKind::Ctor(ctor_of, CtorKind::Const) => {
1521                    Ok(self.construct_const_ctor_value(ctor_def_id, ctor_of, args))
1522                }
1523                _ => unreachable!(),
1524            },
1525            // FIXME(mgca): implement support for this once ready to support all adt ctor expressions,
1526            // not just const ctors
1527            TypeRelativePath::Variant { .. } => {
1528                span_bug!(span, "unexpected variant res for type associated const path")
1529            }
1530        }
1531    }
1532
1533    /// Lower a [type-relative][hir::QPath::TypeRelative] (and type-level) path.
1534    x;#[instrument(level = "debug", skip_all, ret)]
1535    fn lower_type_relative_path(
1536        &self,
1537        self_ty: Ty<'tcx>,
1538        hir_self_ty: &'tcx hir::Ty<'tcx>,
1539        segment: &'tcx hir::PathSegment<'tcx>,
1540        qpath_hir_id: HirId,
1541        span: Span,
1542        mode: LowerTypeRelativePathMode,
1543    ) -> Result<TypeRelativePath<'tcx>, ErrorGuaranteed> {
1544        struct AmbiguousAssocItem<'tcx> {
1545            variant_def_id: DefId,
1546            item_def_id: DefId,
1547            span: Span,
1548            segment_ident: Ident,
1549            bound_def_id: DefId,
1550            self_ty: Ty<'tcx>,
1551            tcx: TyCtxt<'tcx>,
1552            mode: LowerTypeRelativePathMode,
1553        }
1554
1555        impl<'a, 'tcx> Diagnostic<'a, ()> for AmbiguousAssocItem<'tcx> {
1556            fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
1557                let Self {
1558                    variant_def_id,
1559                    item_def_id,
1560                    span,
1561                    segment_ident,
1562                    bound_def_id,
1563                    self_ty,
1564                    tcx,
1565                    mode,
1566                } = self;
1567                let mut lint = Diag::new(dcx, level, "ambiguous associated item");
1568
1569                let mut could_refer_to = |kind: DefKind, def_id, also| {
1570                    let note_msg = format!(
1571                        "`{}` could{} refer to the {} defined here",
1572                        segment_ident,
1573                        also,
1574                        tcx.def_kind_descr(kind, def_id)
1575                    );
1576                    lint.span_note(tcx.def_span(def_id), note_msg);
1577                };
1578
1579                could_refer_to(DefKind::Variant, variant_def_id, "");
1580                could_refer_to(mode.def_kind_for_diagnostics(), item_def_id, " also");
1581
1582                lint.span_suggestion(
1583                    span,
1584                    "use fully-qualified syntax",
1585                    format!("<{} as {}>::{}", self_ty, tcx.item_name(bound_def_id), segment_ident),
1586                    Applicability::MachineApplicable,
1587                );
1588                lint
1589            }
1590        }
1591
1592        debug!(%self_ty, ?segment.ident);
1593        let tcx = self.tcx();
1594
1595        // Check if we have an enum variant or an inherent associated type.
1596        let mut variant_def_id = None;
1597        if let Some(adt_def) = self.probe_adt(span, self_ty) {
1598            if adt_def.is_enum() {
1599                let variant_def = adt_def
1600                    .variants()
1601                    .iter()
1602                    .find(|vd| tcx.hygienic_eq(segment.ident, vd.ident(tcx), adt_def.did()));
1603                if let Some(variant_def) = variant_def {
1604                    // FIXME(mgca): do we want constructor resolutions to take priority over
1605                    // other possible resolutions?
1606                    if matches!(mode, LowerTypeRelativePathMode::Const)
1607                        && let Some((_, ctor_def_id)) = variant_def.ctor
1608                    {
1609                        tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1610                        let _ = self.prohibit_generic_args(
1611                            slice::from_ref(segment).iter(),
1612                            GenericsArgsErrExtend::EnumVariant {
1613                                qself: hir_self_ty,
1614                                assoc_segment: segment,
1615                                adt_def,
1616                            },
1617                        );
1618                        let ty::Adt(_, enum_args) = self_ty.kind() else { unreachable!() };
1619                        return Ok(TypeRelativePath::Ctor { ctor_def_id, args: enum_args });
1620                    }
1621                    if let PermitVariants::Yes = mode.permit_variants() {
1622                        tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1623                        let _ = self.prohibit_generic_args(
1624                            slice::from_ref(segment).iter(),
1625                            GenericsArgsErrExtend::EnumVariant {
1626                                qself: hir_self_ty,
1627                                assoc_segment: segment,
1628                                adt_def,
1629                            },
1630                        );
1631                        return Ok(TypeRelativePath::Variant {
1632                            adt: self_ty,
1633                            variant_did: variant_def.def_id,
1634                        });
1635                    } else {
1636                        variant_def_id = Some(variant_def.def_id);
1637                    }
1638                }
1639            }
1640
1641            // FIXME(inherent_associated_types, #106719): Support self types other than ADTs.
1642            if let Some((did, args)) = self.probe_inherent_assoc_item(
1643                segment,
1644                adt_def.did(),
1645                self_ty,
1646                qpath_hir_id,
1647                span,
1648                mode.assoc_tag(),
1649            )? {
1650                return Ok(TypeRelativePath::AssocItem(did, args));
1651            }
1652        }
1653
1654        let (item_def_id, bound) = self.resolve_type_relative_path(
1655            self_ty,
1656            hir_self_ty,
1657            mode.assoc_tag(),
1658            segment,
1659            qpath_hir_id,
1660            span,
1661            variant_def_id,
1662        )?;
1663
1664        let (item_def_id, args) = self.lower_assoc_item_path(span, item_def_id, segment, bound)?;
1665
1666        if let Some(variant_def_id) = variant_def_id {
1667            tcx.emit_node_span_lint(
1668                AMBIGUOUS_ASSOCIATED_ITEMS,
1669                qpath_hir_id,
1670                span,
1671                AmbiguousAssocItem {
1672                    variant_def_id,
1673                    item_def_id,
1674                    span,
1675                    segment_ident: segment.ident,
1676                    bound_def_id: bound.def_id(),
1677                    self_ty,
1678                    tcx,
1679                    mode,
1680                },
1681            );
1682        }
1683
1684        Ok(TypeRelativePath::AssocItem(item_def_id, args))
1685    }
1686
1687    /// Resolve a [type-relative](hir::QPath::TypeRelative) (and type-level) path.
1688    fn resolve_type_relative_path(
1689        &self,
1690        self_ty: Ty<'tcx>,
1691        hir_self_ty: &'tcx hir::Ty<'tcx>,
1692        assoc_tag: ty::AssocTag,
1693        segment: &'tcx hir::PathSegment<'tcx>,
1694        qpath_hir_id: HirId,
1695        span: Span,
1696        variant_def_id: Option<DefId>,
1697    ) -> Result<(DefId, ty::PolyTraitRef<'tcx>), ErrorGuaranteed> {
1698        let tcx = self.tcx();
1699
1700        let self_ty_res = match hir_self_ty.kind {
1701            hir::TyKind::Path(hir::QPath::Resolved(_, path)) => path.res,
1702            _ => Res::Err,
1703        };
1704
1705        // Find the type of the assoc item, and the trait where the associated item is declared.
1706        let bound = match (self_ty.kind(), self_ty_res) {
1707            (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
1708                // `Self` in an impl of a trait -- we have a concrete self type and a
1709                // trait reference.
1710                let trait_ref = tcx.impl_trait_ref(impl_def_id);
1711
1712                self.probe_single_bound_for_assoc_item(
1713                    || {
1714                        let trait_ref = ty::Binder::dummy(trait_ref.instantiate_identity());
1715                        traits::supertraits(tcx, trait_ref)
1716                    },
1717                    AssocItemQSelf::SelfTyAlias,
1718                    assoc_tag,
1719                    segment.ident,
1720                    span,
1721                    None,
1722                )?
1723            }
1724            (
1725                &ty::Param(_),
1726                Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
1727            ) => self.probe_single_ty_param_bound_for_assoc_item(
1728                param_did.expect_local(),
1729                hir_self_ty.span,
1730                assoc_tag,
1731                segment.ident,
1732                span,
1733            )?,
1734            _ => {
1735                return Err(self.report_unresolved_type_relative_path(
1736                    self_ty,
1737                    hir_self_ty,
1738                    assoc_tag,
1739                    segment.ident,
1740                    qpath_hir_id,
1741                    span,
1742                    variant_def_id,
1743                ));
1744            }
1745        };
1746
1747        let assoc_item = self
1748            .probe_assoc_item(segment.ident, assoc_tag, qpath_hir_id, span, bound.def_id())
1749            .expect("failed to find associated item");
1750
1751        Ok((assoc_item.def_id, bound))
1752    }
1753
1754    /// Search for inherent associated items for use at the type level.
1755    fn probe_inherent_assoc_item(
1756        &self,
1757        segment: &hir::PathSegment<'tcx>,
1758        adt_did: DefId,
1759        self_ty: Ty<'tcx>,
1760        block: HirId,
1761        span: Span,
1762        assoc_tag: ty::AssocTag,
1763    ) -> Result<Option<(DefId, GenericArgsRef<'tcx>)>, ErrorGuaranteed> {
1764        let tcx = self.tcx();
1765
1766        if !tcx.features().inherent_associated_types() {
1767            match assoc_tag {
1768                // Don't attempt to look up inherent associated types when the feature is not
1769                // enabled. Theoretically it'd be fine to do so since we feature-gate their
1770                // definition site. However, the current implementation of inherent associated
1771                // items is somewhat brittle, so let's not run it by default.
1772                ty::AssocTag::Type => return Ok(None),
1773                ty::AssocTag::Const => {
1774                    // We also gate the mgca codepath for type-level uses of inherent consts
1775                    // with the inherent_associated_types feature gate since it relies on the
1776                    // same machinery and has similar rough edges.
1777                    return Err(feature_err(
1778                        &tcx.sess,
1779                        sym::inherent_associated_types,
1780                        span,
1781                        "inherent associated types are unstable",
1782                    )
1783                    .emit());
1784                }
1785                ty::AssocTag::Fn => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1786            }
1787        }
1788
1789        let name = segment.ident;
1790        let candidates: Vec<_> = tcx
1791            .inherent_impls(adt_did)
1792            .iter()
1793            .filter_map(|&impl_| {
1794                let (item, scope) =
1795                    self.probe_assoc_item_unchecked(name, assoc_tag, block, impl_)?;
1796                Some(InherentAssocCandidate { impl_, assoc_item: item.def_id, scope })
1797            })
1798            .collect();
1799
1800        // At the moment, we actually bail out with a hard error if the selection of an inherent
1801        // associated item fails (see below). This means we never consider trait associated items
1802        // as potential fallback candidates (#142006). To temporarily mask that issue, let's not
1803        // select at all if there are no early inherent candidates.
1804        if candidates.is_empty() {
1805            return Ok(None);
1806        }
1807
1808        let (applicable_candidates, fulfillment_errors) =
1809            self.select_inherent_assoc_candidates(span, self_ty, candidates.clone());
1810
1811        // FIXME(#142006): Don't eagerly error here, there might be applicable trait candidates.
1812        let InherentAssocCandidate { impl_, assoc_item, scope: def_scope } =
1813            match &applicable_candidates[..] {
1814                &[] => Err(self.report_unresolved_inherent_assoc_item(
1815                    name,
1816                    self_ty,
1817                    candidates,
1818                    fulfillment_errors,
1819                    span,
1820                    assoc_tag,
1821                )),
1822
1823                &[applicable_candidate] => Ok(applicable_candidate),
1824
1825                &[_, ..] => Err(self.report_ambiguous_inherent_assoc_item(
1826                    name,
1827                    candidates.into_iter().map(|cand| cand.assoc_item).collect(),
1828                    span,
1829                )),
1830            }?;
1831
1832        // FIXME(#142006): Don't eagerly validate here, there might be trait candidates that are
1833        // accessible (visible and stable) contrary to the inherent candidate.
1834        self.check_assoc_item(assoc_item, name, def_scope, block, span);
1835
1836        // FIXME(fmease): Currently creating throwaway `parent_args` to please
1837        // `lower_generic_args_of_assoc_item`. Modify the latter instead (or sth. similar) to
1838        // not require the parent args logic.
1839        let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
1840        let args = self.lower_generic_args_of_assoc_item(span, assoc_item, segment, parent_args);
1841        let args = tcx.mk_args_from_iter(
1842            std::iter::once(ty::GenericArg::from(self_ty))
1843                .chain(args.into_iter().skip(parent_args.len())),
1844        );
1845
1846        Ok(Some((assoc_item, args)))
1847    }
1848
1849    /// Given name and kind search for the assoc item in the provided scope and check if it's accessible[^1].
1850    ///
1851    /// [^1]: I.e., accessible in the provided scope wrt. visibility and stability.
1852    fn probe_assoc_item(
1853        &self,
1854        ident: Ident,
1855        assoc_tag: ty::AssocTag,
1856        block: HirId,
1857        span: Span,
1858        scope: DefId,
1859    ) -> Option<ty::AssocItem> {
1860        let (item, scope) = self.probe_assoc_item_unchecked(ident, assoc_tag, block, scope)?;
1861        self.check_assoc_item(item.def_id, ident, scope, block, span);
1862        Some(item)
1863    }
1864
1865    /// Given name and kind search for the assoc item in the provided scope
1866    /// *without* checking if it's accessible[^1].
1867    ///
1868    /// [^1]: I.e., accessible in the provided scope wrt. visibility and stability.
1869    fn probe_assoc_item_unchecked(
1870        &self,
1871        ident: Ident,
1872        assoc_tag: ty::AssocTag,
1873        block: HirId,
1874        scope: DefId,
1875    ) -> Option<(ty::AssocItem, /*scope*/ DefId)> {
1876        let tcx = self.tcx();
1877
1878        let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block);
1879        // We have already adjusted the item name above, so compare with `.normalize_to_macros_2_0()`
1880        // instead of calling `filter_by_name_and_kind` which would needlessly normalize the
1881        // `ident` again and again.
1882        let item = tcx
1883            .associated_items(scope)
1884            .filter_by_name_unhygienic(ident.name)
1885            .find(|i| i.tag() == assoc_tag && i.ident(tcx).normalize_to_macros_2_0() == ident)?;
1886
1887        Some((*item, def_scope))
1888    }
1889
1890    /// Check if the given assoc item is accessible in the provided scope wrt. visibility and stability.
1891    fn check_assoc_item(
1892        &self,
1893        item_def_id: DefId,
1894        ident: Ident,
1895        scope: DefId,
1896        block: HirId,
1897        span: Span,
1898    ) {
1899        let tcx = self.tcx();
1900
1901        if !tcx.visibility(item_def_id).is_accessible_from(scope, tcx) {
1902            self.dcx().emit_err(crate::errors::AssocItemIsPrivate {
1903                span,
1904                kind: tcx.def_descr(item_def_id),
1905                name: ident,
1906                defined_here_label: tcx.def_span(item_def_id),
1907            });
1908        }
1909
1910        tcx.check_stability(item_def_id, Some(block), span, None);
1911    }
1912
1913    fn probe_traits_that_match_assoc_ty(
1914        &self,
1915        qself_ty: Ty<'tcx>,
1916        assoc_ident: Ident,
1917    ) -> Vec<String> {
1918        let tcx = self.tcx();
1919
1920        // In contexts that have no inference context, just make a new one.
1921        // We do need a local variable to store it, though.
1922        let infcx_;
1923        let infcx = if let Some(infcx) = self.infcx() {
1924            infcx
1925        } else {
1926            if !!qself_ty.has_infer() {
    ::core::panicking::panic("assertion failed: !qself_ty.has_infer()")
};assert!(!qself_ty.has_infer());
1927            infcx_ = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1928            &infcx_
1929        };
1930
1931        tcx.all_traits_including_private()
1932            .filter(|trait_def_id| {
1933                // Consider only traits with the associated type
1934                tcx.associated_items(*trait_def_id)
1935                        .in_definition_order()
1936                        .any(|i| {
1937                            i.is_type()
1938                                && !i.is_impl_trait_in_trait()
1939                                && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1940                        })
1941                    // Consider only accessible traits
1942                    && tcx.visibility(*trait_def_id)
1943                        .is_accessible_from(self.item_def_id(), tcx)
1944                    && tcx.all_impls(*trait_def_id)
1945                        .any(|impl_def_id| {
1946                            let header = tcx.impl_trait_header(impl_def_id);
1947                            let trait_ref = header.trait_ref.instantiate(
1948                                tcx,
1949                                infcx.fresh_args_for_item(DUMMY_SP, impl_def_id),
1950                            );
1951
1952                            let value = fold_regions(tcx, qself_ty, |_, _| tcx.lifetimes.re_erased);
1953                            // FIXME: Don't bother dealing with non-lifetime binders here...
1954                            if value.has_escaping_bound_vars() {
1955                                return false;
1956                            }
1957                            infcx
1958                                .can_eq(
1959                                    ty::ParamEnv::empty(),
1960                                    trait_ref.self_ty(),
1961                                    value,
1962                                ) && header.polarity != ty::ImplPolarity::Negative
1963                        })
1964            })
1965            .map(|trait_def_id| tcx.def_path_str(trait_def_id))
1966            .collect()
1967    }
1968
1969    /// Lower a [resolved][hir::QPath::Resolved] associated type path to a projection.
1970    #[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(1970u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Ty<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match self.lower_resolved_assoc_item_path(span, opt_self_ty,
                    item_def_id, trait_segment, item_segment,
                    ty::AssocTag::Type) {
                Ok((item_def_id, item_args)) => {
                    Ty::new_projection_from_args(self.tcx(), item_def_id,
                        item_args)
                }
                Err(guar) => Ty::new_error(self.tcx(), guar),
            }
        }
    }
}#[instrument(level = "debug", skip_all)]
1971    fn lower_resolved_assoc_ty_path(
1972        &self,
1973        span: Span,
1974        opt_self_ty: Option<Ty<'tcx>>,
1975        item_def_id: DefId,
1976        trait_segment: Option<&hir::PathSegment<'tcx>>,
1977        item_segment: &hir::PathSegment<'tcx>,
1978    ) -> Ty<'tcx> {
1979        match self.lower_resolved_assoc_item_path(
1980            span,
1981            opt_self_ty,
1982            item_def_id,
1983            trait_segment,
1984            item_segment,
1985            ty::AssocTag::Type,
1986        ) {
1987            Ok((item_def_id, item_args)) => {
1988                Ty::new_projection_from_args(self.tcx(), item_def_id, item_args)
1989            }
1990            Err(guar) => Ty::new_error(self.tcx(), guar),
1991        }
1992    }
1993
1994    /// Lower a [resolved][hir::QPath::Resolved] associated const path to a (type-level) constant.
1995    #[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(1995u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<Const<'tcx>, ErrorGuaranteed> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (item_def_id, item_args) =
                self.lower_resolved_assoc_item_path(span, opt_self_ty,
                        item_def_id, trait_segment, item_segment,
                        ty::AssocTag::Const)?;
            self.require_type_const_attribute(item_def_id, span)?;
            let uv = ty::UnevaluatedConst::new(item_def_id, item_args);
            Ok(Const::new_unevaluated(self.tcx(), uv))
        }
    }
}#[instrument(level = "debug", skip_all)]
1996    fn lower_resolved_assoc_const_path(
1997        &self,
1998        span: Span,
1999        opt_self_ty: Option<Ty<'tcx>>,
2000        item_def_id: DefId,
2001        trait_segment: Option<&hir::PathSegment<'tcx>>,
2002        item_segment: &hir::PathSegment<'tcx>,
2003    ) -> Result<Const<'tcx>, ErrorGuaranteed> {
2004        let (item_def_id, item_args) = self.lower_resolved_assoc_item_path(
2005            span,
2006            opt_self_ty,
2007            item_def_id,
2008            trait_segment,
2009            item_segment,
2010            ty::AssocTag::Const,
2011        )?;
2012        self.require_type_const_attribute(item_def_id, span)?;
2013        let uv = ty::UnevaluatedConst::new(item_def_id, item_args);
2014        Ok(Const::new_unevaluated(self.tcx(), uv))
2015    }
2016
2017    /// Lower a [resolved][hir::QPath::Resolved] (type-level) associated item path.
2018    #[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(2018u32),
                                    ::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:2031",
                                    "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(2031u32),
                                    ::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:2041",
                                    "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(2041u32),
                                    ::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:2045",
                                    "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(2045u32),
                                    ::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)]
2019    fn lower_resolved_assoc_item_path(
2020        &self,
2021        span: Span,
2022        opt_self_ty: Option<Ty<'tcx>>,
2023        item_def_id: DefId,
2024        trait_segment: Option<&hir::PathSegment<'tcx>>,
2025        item_segment: &hir::PathSegment<'tcx>,
2026        assoc_tag: ty::AssocTag,
2027    ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> {
2028        let tcx = self.tcx();
2029
2030        let trait_def_id = tcx.parent(item_def_id);
2031        debug!(?trait_def_id);
2032
2033        let Some(self_ty) = opt_self_ty else {
2034            return Err(self.report_missing_self_ty_for_resolved_path(
2035                trait_def_id,
2036                span,
2037                item_segment,
2038                assoc_tag,
2039            ));
2040        };
2041        debug!(?self_ty);
2042
2043        let trait_ref =
2044            self.lower_mono_trait_ref(span, trait_def_id, self_ty, trait_segment.unwrap(), false);
2045        debug!(?trait_ref);
2046
2047        let item_args =
2048            self.lower_generic_args_of_assoc_item(span, item_def_id, item_segment, trait_ref.args);
2049
2050        Ok((item_def_id, item_args))
2051    }
2052
2053    pub fn prohibit_generic_args<'a>(
2054        &self,
2055        segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
2056        err_extend: GenericsArgsErrExtend<'a>,
2057    ) -> Result<(), ErrorGuaranteed> {
2058        let args_visitors = segments.clone().flat_map(|segment| segment.args().args);
2059        let mut result = Ok(());
2060        if let Some(_) = args_visitors.clone().next() {
2061            result = Err(self.report_prohibited_generic_args(
2062                segments.clone(),
2063                args_visitors,
2064                err_extend,
2065            ));
2066        }
2067
2068        for segment in segments {
2069            // Only emit the first error to avoid overloading the user with error messages.
2070            if let Some(c) = segment.args().constraints.first() {
2071                return Err(prohibit_assoc_item_constraint(self, c, None));
2072            }
2073        }
2074
2075        result
2076    }
2077
2078    /// Probe path segments that are semantically allowed to have generic arguments.
2079    ///
2080    /// ### Example
2081    ///
2082    /// ```ignore (illustrative)
2083    ///    Option::None::<()>
2084    /// //         ^^^^ permitted to have generic args
2085    ///
2086    /// // ==> [GenericPathSegment(Option_def_id, 1)]
2087    ///
2088    ///    Option::<()>::None
2089    /// // ^^^^^^        ^^^^ *not* permitted to have generic args
2090    /// // permitted to have generic args
2091    ///
2092    /// // ==> [GenericPathSegment(Option_def_id, 0)]
2093    /// ```
2094    // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2095    pub fn probe_generic_path_segments(
2096        &self,
2097        segments: &[hir::PathSegment<'_>],
2098        self_ty: Option<Ty<'tcx>>,
2099        kind: DefKind,
2100        def_id: DefId,
2101        span: Span,
2102    ) -> Vec<GenericPathSegment> {
2103        // We need to extract the generic arguments supplied by the user in
2104        // the path `path`. Due to the current setup, this is a bit of a
2105        // tricky process; the problem is that resolve only tells us the
2106        // end-point of the path resolution, and not the intermediate steps.
2107        // Luckily, we can (at least for now) deduce the intermediate steps
2108        // just from the end-point.
2109        //
2110        // There are basically five cases to consider:
2111        //
2112        // 1. Reference to a constructor of a struct:
2113        //
2114        //        struct Foo<T>(...)
2115        //
2116        //    In this case, the generic arguments are declared in the type space.
2117        //
2118        // 2. Reference to a constructor of an enum variant:
2119        //
2120        //        enum E<T> { Foo(...) }
2121        //
2122        //    In this case, the generic arguments are defined in the type space,
2123        //    but may be specified either on the type or the variant.
2124        //
2125        // 3. Reference to a free function or constant:
2126        //
2127        //        fn foo<T>() {}
2128        //
2129        //    In this case, the path will again always have the form
2130        //    `a::b::foo::<T>` where only the final segment should have generic
2131        //    arguments. However, in this case, those arguments are declared on
2132        //    a value, and hence are in the value space.
2133        //
2134        // 4. Reference to an associated function or constant:
2135        //
2136        //        impl<A> SomeStruct<A> {
2137        //            fn foo<B>(...) {}
2138        //        }
2139        //
2140        //    Here we can have a path like `a::b::SomeStruct::<A>::foo::<B>`,
2141        //    in which case generic arguments may appear in two places. The
2142        //    penultimate segment, `SomeStruct::<A>`, contains generic arguments
2143        //    in the type space, and the final segment, `foo::<B>` contains
2144        //    generic arguments in value space.
2145        //
2146        // The first step then is to categorize the segments appropriately.
2147
2148        let tcx = self.tcx();
2149
2150        if !!segments.is_empty() {
    ::core::panicking::panic("assertion failed: !segments.is_empty()")
};assert!(!segments.is_empty());
2151        let last = segments.len() - 1;
2152
2153        let mut generic_segments = ::alloc::vec::Vec::new()vec![];
2154
2155        match kind {
2156            // Case 1. Reference to a struct constructor.
2157            DefKind::Ctor(CtorOf::Struct, ..) => {
2158                // Everything but the final segment should have no
2159                // parameters at all.
2160                let generics = tcx.generics_of(def_id);
2161                // Variant and struct constructors use the
2162                // generics of their parent type definition.
2163                let generics_def_id = generics.parent.unwrap_or(def_id);
2164                generic_segments.push(GenericPathSegment(generics_def_id, last));
2165            }
2166
2167            // Case 2. Reference to a variant constructor.
2168            DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2169                let (generics_def_id, index) = if let Some(self_ty) = self_ty {
2170                    let adt_def = self.probe_adt(span, self_ty).unwrap();
2171                    if true {
    if !adt_def.is_enum() {
        ::core::panicking::panic("assertion failed: adt_def.is_enum()")
    };
};debug_assert!(adt_def.is_enum());
2172                    (adt_def.did(), last)
2173                } else if last >= 1 && segments[last - 1].args.is_some() {
2174                    // Everything but the penultimate segment should have no
2175                    // parameters at all.
2176                    let mut def_id = def_id;
2177
2178                    // `DefKind::Ctor` -> `DefKind::Variant`
2179                    if let DefKind::Ctor(..) = kind {
2180                        def_id = tcx.parent(def_id);
2181                    }
2182
2183                    // `DefKind::Variant` -> `DefKind::Enum`
2184                    let enum_def_id = tcx.parent(def_id);
2185                    (enum_def_id, last - 1)
2186                } else {
2187                    // FIXME: lint here recommending `Enum::<...>::Variant` form
2188                    // instead of `Enum::Variant::<...>` form.
2189
2190                    // Everything but the final segment should have no
2191                    // parameters at all.
2192                    let generics = tcx.generics_of(def_id);
2193                    // Variant and struct constructors use the
2194                    // generics of their parent type definition.
2195                    (generics.parent.unwrap_or(def_id), last)
2196                };
2197                generic_segments.push(GenericPathSegment(generics_def_id, index));
2198            }
2199
2200            // Case 3. Reference to a top-level value.
2201            DefKind::Fn | DefKind::Const { .. } | DefKind::ConstParam | DefKind::Static { .. } => {
2202                generic_segments.push(GenericPathSegment(def_id, last));
2203            }
2204
2205            // Case 4. Reference to a method or associated const.
2206            DefKind::AssocFn | DefKind::AssocConst { .. } => {
2207                if segments.len() >= 2 {
2208                    let generics = tcx.generics_of(def_id);
2209                    generic_segments.push(GenericPathSegment(generics.parent.unwrap(), last - 1));
2210                }
2211                generic_segments.push(GenericPathSegment(def_id, last));
2212            }
2213
2214            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),
2215        }
2216
2217        {
    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:2217",
                        "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(2217u32),
                        ::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);
2218
2219        generic_segments
2220    }
2221
2222    /// Lower a [resolved][hir::QPath::Resolved] path to a type.
2223    #[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(2223u32),
                                    ::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:2231",
                                    "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(2231u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["path.res",
                                                    "opt_self_ty", "path.segments"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&path.res)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&opt_self_ty)
                                                        as &dyn Value)),
                                            (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&path.segments)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let tcx = self.tcx();
            let span = path.span;
            match path.res {
                Res::Def(DefKind::OpaqueTy, did) => {
                    match tcx.opaque_ty_origin(did) {
                        hir::OpaqueTyOrigin::TyAlias { .. } => {}
                        ref left_val => {
                            ::core::panicking::assert_matches_failed(left_val,
                                "hir::OpaqueTyOrigin::TyAlias { .. }",
                                ::core::option::Option::None);
                        }
                    };
                    let [leading_segments @ .., segment] =
                        path.segments else {
                            ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
                        };
                    let _ =
                        self.prohibit_generic_args(leading_segments.iter(),
                            GenericsArgsErrExtend::OpaqueTy);
                    let args =
                        self.lower_generic_args_of_path_segment(span, did, segment);
                    Ty::new_opaque(tcx, did, args)
                }
                Res::Def(DefKind::Enum | DefKind::TyAlias | DefKind::Struct |
                    DefKind::Union | DefKind::ForeignTy, did) => {
                    match (&opt_self_ty, &None) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    };
                    let [leading_segments @ .., segment] =
                        path.segments else {
                            ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
                        };
                    let _ =
                        self.prohibit_generic_args(leading_segments.iter(),
                            GenericsArgsErrExtend::None);
                    self.lower_path_segment(span, did, segment)
                }
                Res::Def(kind @ DefKind::Variant, def_id) if
                    let PermitVariants::Yes = permit_variants => {
                    match (&opt_self_ty, &None) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    };
                    let generic_segments =
                        self.probe_generic_path_segments(path.segments, None, kind,
                            def_id, span);
                    let indices: FxHashSet<_> =
                        generic_segments.iter().map(|GenericPathSegment(_, index)|
                                    index).collect();
                    let _ =
                        self.prohibit_generic_args(path.segments.iter().enumerate().filter_map(|(index,
                                        seg)|
                                    {
                                        if !indices.contains(&index) { Some(seg) } else { None }
                                    }), GenericsArgsErrExtend::DefVariant(&path.segments));
                    let &GenericPathSegment(def_id, index) =
                        generic_segments.last().unwrap();
                    self.lower_path_segment(span, def_id, &path.segments[index])
                }
                Res::Def(DefKind::TyParam, def_id) => {
                    match (&opt_self_ty, &None) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    };
                    let _ =
                        self.prohibit_generic_args(path.segments.iter(),
                            GenericsArgsErrExtend::Param(def_id));
                    self.lower_ty_param(hir_id)
                }
                Res::SelfTyParam { .. } => {
                    match (&opt_self_ty, &None) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    };
                    let _ =
                        self.prohibit_generic_args(path.segments.iter(),
                            if let [hir::PathSegment { args: Some(args), ident, .. }] =
                                    &path.segments {
                                GenericsArgsErrExtend::SelfTyParam(ident.span.shrink_to_hi().to(args.span_ext))
                            } else { GenericsArgsErrExtend::None });
                    self.check_param_uses_if_mcg(tcx.types.self_param, span,
                        false)
                }
                Res::SelfTyAlias { alias_to: def_id, .. } => {
                    match (&opt_self_ty, &None) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    };
                    let ty =
                        tcx.at(span).type_of(def_id).instantiate_identity();
                    let _ =
                        self.prohibit_generic_args(path.segments.iter(),
                            GenericsArgsErrExtend::SelfTyAlias { def_id, span });
                    self.check_param_uses_if_mcg(ty, span, true)
                }
                Res::Def(DefKind::AssocTy, def_id) => {
                    let trait_segment =
                        if let [modules @ .., trait_, _item] = path.segments {
                            let _ =
                                self.prohibit_generic_args(modules.iter(),
                                    GenericsArgsErrExtend::None);
                            Some(trait_)
                        } else { None };
                    self.lower_resolved_assoc_ty_path(span, opt_self_ty, def_id,
                        trait_segment, path.segments.last().unwrap())
                }
                Res::PrimTy(prim_ty) => {
                    match (&opt_self_ty, &None) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    };
                    let _ =
                        self.prohibit_generic_args(path.segments.iter(),
                            GenericsArgsErrExtend::PrimTy(prim_ty));
                    match prim_ty {
                        hir::PrimTy::Bool => tcx.types.bool,
                        hir::PrimTy::Char => tcx.types.char,
                        hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
                        hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
                        hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
                        hir::PrimTy::Str => tcx.types.str_,
                    }
                }
                Res::Err => {
                    let e =
                        self.tcx().dcx().span_delayed_bug(path.span,
                            "path with `Res::Err` but no error emitted");
                    Ty::new_error(tcx, e)
                }
                Res::Def(..) => {
                    match (&path.segments.get(0).map(|seg| seg.ident.name),
                            &Some(kw::SelfUpper)) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val,
                                    ::core::option::Option::Some(format_args!("only expected incorrect resolution for `Self`")));
                            }
                        }
                    };
                    Ty::new_error(self.tcx(),
                        self.dcx().span_delayed_bug(span,
                            "incorrect resolution for `Self`"))
                }
                _ =>
                    ::rustc_middle::util::bug::span_bug_fmt(span,
                        format_args!("unexpected resolution: {0:?}", path.res)),
            }
        }
    }
}#[instrument(level = "debug", skip_all)]
2224    pub fn lower_resolved_ty_path(
2225        &self,
2226        opt_self_ty: Option<Ty<'tcx>>,
2227        path: &hir::Path<'tcx>,
2228        hir_id: HirId,
2229        permit_variants: PermitVariants,
2230    ) -> Ty<'tcx> {
2231        debug!(?path.res, ?opt_self_ty, ?path.segments);
2232        let tcx = self.tcx();
2233
2234        let span = path.span;
2235        match path.res {
2236            Res::Def(DefKind::OpaqueTy, did) => {
2237                // Check for desugared `impl Trait`.
2238                assert_matches!(tcx.opaque_ty_origin(did), hir::OpaqueTyOrigin::TyAlias { .. });
2239                let [leading_segments @ .., segment] = path.segments else { bug!() };
2240                let _ = self.prohibit_generic_args(
2241                    leading_segments.iter(),
2242                    GenericsArgsErrExtend::OpaqueTy,
2243                );
2244                let args = self.lower_generic_args_of_path_segment(span, did, segment);
2245                Ty::new_opaque(tcx, did, args)
2246            }
2247            Res::Def(
2248                DefKind::Enum
2249                | DefKind::TyAlias
2250                | DefKind::Struct
2251                | DefKind::Union
2252                | DefKind::ForeignTy,
2253                did,
2254            ) => {
2255                assert_eq!(opt_self_ty, None);
2256                let [leading_segments @ .., segment] = path.segments else { bug!() };
2257                let _ = self
2258                    .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2259                self.lower_path_segment(span, did, segment)
2260            }
2261            Res::Def(kind @ DefKind::Variant, def_id)
2262                if let PermitVariants::Yes = permit_variants =>
2263            {
2264                // Lower "variant type" as if it were a real type.
2265                // The resulting `Ty` is type of the variant's enum for now.
2266                assert_eq!(opt_self_ty, None);
2267
2268                let generic_segments =
2269                    self.probe_generic_path_segments(path.segments, None, kind, def_id, span);
2270                let indices: FxHashSet<_> =
2271                    generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2272                let _ = self.prohibit_generic_args(
2273                    path.segments.iter().enumerate().filter_map(|(index, seg)| {
2274                        if !indices.contains(&index) { Some(seg) } else { None }
2275                    }),
2276                    GenericsArgsErrExtend::DefVariant(&path.segments),
2277                );
2278
2279                let &GenericPathSegment(def_id, index) = generic_segments.last().unwrap();
2280                self.lower_path_segment(span, def_id, &path.segments[index])
2281            }
2282            Res::Def(DefKind::TyParam, def_id) => {
2283                assert_eq!(opt_self_ty, None);
2284                let _ = self.prohibit_generic_args(
2285                    path.segments.iter(),
2286                    GenericsArgsErrExtend::Param(def_id),
2287                );
2288                self.lower_ty_param(hir_id)
2289            }
2290            Res::SelfTyParam { .. } => {
2291                // `Self` in trait or type alias.
2292                assert_eq!(opt_self_ty, None);
2293                let _ = self.prohibit_generic_args(
2294                    path.segments.iter(),
2295                    if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments {
2296                        GenericsArgsErrExtend::SelfTyParam(
2297                            ident.span.shrink_to_hi().to(args.span_ext),
2298                        )
2299                    } else {
2300                        GenericsArgsErrExtend::None
2301                    },
2302                );
2303                self.check_param_uses_if_mcg(tcx.types.self_param, span, false)
2304            }
2305            Res::SelfTyAlias { alias_to: def_id, .. } => {
2306                // `Self` in impl (we know the concrete type).
2307                assert_eq!(opt_self_ty, None);
2308                // Try to evaluate any array length constants.
2309                let ty = tcx.at(span).type_of(def_id).instantiate_identity();
2310                let _ = self.prohibit_generic_args(
2311                    path.segments.iter(),
2312                    GenericsArgsErrExtend::SelfTyAlias { def_id, span },
2313                );
2314                self.check_param_uses_if_mcg(ty, span, true)
2315            }
2316            Res::Def(DefKind::AssocTy, def_id) => {
2317                let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2318                    let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2319                    Some(trait_)
2320                } else {
2321                    None
2322                };
2323                self.lower_resolved_assoc_ty_path(
2324                    span,
2325                    opt_self_ty,
2326                    def_id,
2327                    trait_segment,
2328                    path.segments.last().unwrap(),
2329                )
2330            }
2331            Res::PrimTy(prim_ty) => {
2332                assert_eq!(opt_self_ty, None);
2333                let _ = self.prohibit_generic_args(
2334                    path.segments.iter(),
2335                    GenericsArgsErrExtend::PrimTy(prim_ty),
2336                );
2337                match prim_ty {
2338                    hir::PrimTy::Bool => tcx.types.bool,
2339                    hir::PrimTy::Char => tcx.types.char,
2340                    hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
2341                    hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
2342                    hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
2343                    hir::PrimTy::Str => tcx.types.str_,
2344                }
2345            }
2346            Res::Err => {
2347                let e = self
2348                    .tcx()
2349                    .dcx()
2350                    .span_delayed_bug(path.span, "path with `Res::Err` but no error emitted");
2351                Ty::new_error(tcx, e)
2352            }
2353            Res::Def(..) => {
2354                assert_eq!(
2355                    path.segments.get(0).map(|seg| seg.ident.name),
2356                    Some(kw::SelfUpper),
2357                    "only expected incorrect resolution for `Self`"
2358                );
2359                Ty::new_error(
2360                    self.tcx(),
2361                    self.dcx().span_delayed_bug(span, "incorrect resolution for `Self`"),
2362                )
2363            }
2364            _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2365        }
2366    }
2367
2368    /// Lower a type parameter from the HIR to our internal notion of a type.
2369    ///
2370    /// Early-bound type parameters get lowered to [`ty::Param`]
2371    /// and late-bound ones to [`ty::Bound`].
2372    pub(crate) fn lower_ty_param(&self, hir_id: HirId) -> Ty<'tcx> {
2373        let tcx = self.tcx();
2374
2375        let ty = match tcx.named_bound_var(hir_id) {
2376            Some(rbv::ResolvedArg::LateBound(debruijn, index, def_id)) => {
2377                let br = ty::BoundTy {
2378                    var: ty::BoundVar::from_u32(index),
2379                    kind: ty::BoundTyKind::Param(def_id.to_def_id()),
2380                };
2381                Ty::new_bound(tcx, debruijn, br)
2382            }
2383            Some(rbv::ResolvedArg::EarlyBound(def_id)) => {
2384                let item_def_id = tcx.hir_ty_param_owner(def_id);
2385                let generics = tcx.generics_of(item_def_id);
2386                let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2387                Ty::new_param(tcx, index, tcx.hir_ty_param_name(def_id))
2388            }
2389            Some(rbv::ResolvedArg::Error(guar)) => Ty::new_error(tcx, guar),
2390            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:?}"),
2391        };
2392        self.check_param_uses_if_mcg(ty, tcx.hir_span(hir_id), false)
2393    }
2394
2395    /// Lower a const parameter from the HIR to our internal notion of a constant.
2396    ///
2397    /// Early-bound const parameters get lowered to [`ty::ConstKind::Param`]
2398    /// and late-bound ones to [`ty::ConstKind::Bound`].
2399    pub(crate) fn lower_const_param(&self, param_def_id: DefId, path_hir_id: HirId) -> Const<'tcx> {
2400        let tcx = self.tcx();
2401
2402        let ct = match tcx.named_bound_var(path_hir_id) {
2403            Some(rbv::ResolvedArg::EarlyBound(_)) => {
2404                // Find the name and index of the const parameter by indexing the generics of
2405                // the parent item and construct a `ParamConst`.
2406                let item_def_id = tcx.parent(param_def_id);
2407                let generics = tcx.generics_of(item_def_id);
2408                let index = generics.param_def_id_to_index[&param_def_id];
2409                let name = tcx.item_name(param_def_id);
2410                ty::Const::new_param(tcx, ty::ParamConst::new(index, name))
2411            }
2412            Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => ty::Const::new_bound(
2413                tcx,
2414                debruijn,
2415                ty::BoundConst::new(ty::BoundVar::from_u32(index)),
2416            ),
2417            Some(rbv::ResolvedArg::Error(guar)) => ty::Const::new_error(tcx, guar),
2418            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),
2419        };
2420        self.check_param_uses_if_mcg(ct, tcx.hir_span(path_hir_id), false)
2421    }
2422
2423    /// Lower a [`hir::ConstArg`] to a (type-level) [`ty::Const`](Const).
2424    #[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(2424u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["const_arg", "ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&const_arg)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Const<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
                if tcx.features().generic_const_parameter_types() &&
                        (ty.has_free_regions() || ty.has_erased_regions()) {
                    let e =
                        self.dcx().span_err(const_arg.span,
                            "anonymous constants with lifetimes in their type are not yet supported");
                    tcx.feed_anon_const_type(anon.def_id,
                        ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
                    return ty::Const::new_error(tcx, e);
                }
                if ty.has_non_region_infer() {
                    let e =
                        self.dcx().span_err(const_arg.span,
                            "anonymous constants with inferred types are not yet supported");
                    tcx.feed_anon_const_type(anon.def_id,
                        ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
                    return ty::Const::new_error(tcx, e);
                }
                if ty.has_non_region_param() {
                    let e =
                        self.dcx().span_err(const_arg.span,
                            "anonymous constants referencing generics are not yet supported");
                    tcx.feed_anon_const_type(anon.def_id,
                        ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
                    return ty::Const::new_error(tcx, e);
                }
                tcx.feed_anon_const_type(anon.def_id,
                    ty::EarlyBinder::bind(ty));
            }
            let hir_id = const_arg.hir_id;
            match const_arg.kind {
                hir::ConstArgKind::Tup(exprs) =>
                    self.lower_const_arg_tup(exprs, ty, const_arg.span),
                hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself,
                    path)) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2476",
                                            "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(2476u32),
                                            ::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:2481",
                                            "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(2481u32),
                                            ::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")]
2425    pub fn lower_const_arg(&self, const_arg: &hir::ConstArg<'tcx>, ty: Ty<'tcx>) -> Const<'tcx> {
2426        let tcx = self.tcx();
2427
2428        if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
2429            // FIXME(generic_const_parameter_types): Ideally we remove these errors below when
2430            // we have the ability to intermix typeck of anon const const args with the parent
2431            // bodies typeck.
2432
2433            // We also error if the type contains any regions as effectively any region will wind
2434            // up as a region variable in mir borrowck. It would also be somewhat concerning if
2435            // hir typeck was using equality but mir borrowck wound up using subtyping as that could
2436            // result in a non-infer in hir typeck but a region variable in borrowck.
2437            if tcx.features().generic_const_parameter_types()
2438                && (ty.has_free_regions() || ty.has_erased_regions())
2439            {
2440                let e = self.dcx().span_err(
2441                    const_arg.span,
2442                    "anonymous constants with lifetimes in their type are not yet supported",
2443                );
2444                tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2445                return ty::Const::new_error(tcx, e);
2446            }
2447            // We must error if the instantiated type has any inference variables as we will
2448            // use this type to feed the `type_of` and query results must not contain inference
2449            // variables otherwise we will ICE.
2450            if ty.has_non_region_infer() {
2451                let e = self.dcx().span_err(
2452                    const_arg.span,
2453                    "anonymous constants with inferred types are not yet supported",
2454                );
2455                tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2456                return ty::Const::new_error(tcx, e);
2457            }
2458            // We error when the type contains unsubstituted generics since we do not currently
2459            // give the anon const any of the generics from the parent.
2460            if ty.has_non_region_param() {
2461                let e = self.dcx().span_err(
2462                    const_arg.span,
2463                    "anonymous constants referencing generics are not yet supported",
2464                );
2465                tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2466                return ty::Const::new_error(tcx, e);
2467            }
2468
2469            tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(ty));
2470        }
2471
2472        let hir_id = const_arg.hir_id;
2473        match const_arg.kind {
2474            hir::ConstArgKind::Tup(exprs) => self.lower_const_arg_tup(exprs, ty, const_arg.span),
2475            hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2476                debug!(?maybe_qself, ?path);
2477                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2478                self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2479            }
2480            hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2481                debug!(?hir_self_ty, ?segment);
2482                let self_ty = self.lower_ty(hir_self_ty);
2483                self.lower_type_relative_const_path(
2484                    self_ty,
2485                    hir_self_ty,
2486                    segment,
2487                    hir_id,
2488                    const_arg.span,
2489                )
2490                .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2491            }
2492            hir::ConstArgKind::Struct(qpath, inits) => {
2493                self.lower_const_arg_struct(hir_id, qpath, inits, const_arg.span)
2494            }
2495            hir::ConstArgKind::TupleCall(qpath, args) => {
2496                self.lower_const_arg_tuple_call(hir_id, qpath, args, const_arg.span)
2497            }
2498            hir::ConstArgKind::Array(array_expr) => self.lower_const_arg_array(array_expr, ty),
2499            hir::ConstArgKind::Anon(anon) => self.lower_const_arg_anon(anon),
2500            hir::ConstArgKind::Infer(()) => self.ct_infer(None, const_arg.span),
2501            hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
2502            hir::ConstArgKind::Literal { lit, negated } => {
2503                self.lower_const_arg_literal(&lit, negated, ty, const_arg.span)
2504            }
2505        }
2506    }
2507
2508    fn lower_const_arg_array(
2509        &self,
2510        array_expr: &'tcx hir::ConstArgArrayExpr<'tcx>,
2511        ty: Ty<'tcx>,
2512    ) -> Const<'tcx> {
2513        let tcx = self.tcx();
2514
2515        let elem_ty = match ty.kind() {
2516            ty::Array(elem_ty, _) => elem_ty,
2517            ty::Error(e) => return Const::new_error(tcx, *e),
2518            _ => {
2519                let e = tcx
2520                    .dcx()
2521                    .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));
2522                return Const::new_error(tcx, e);
2523            }
2524        };
2525
2526        let elems = array_expr
2527            .elems
2528            .iter()
2529            .map(|elem| self.lower_const_arg(elem, *elem_ty))
2530            .collect::<Vec<_>>();
2531
2532        let valtree = ty::ValTree::from_branches(tcx, elems);
2533
2534        ty::Const::new_value(tcx, valtree, ty)
2535    }
2536
2537    fn lower_const_arg_tuple_call(
2538        &self,
2539        hir_id: HirId,
2540        qpath: hir::QPath<'tcx>,
2541        args: &'tcx [&'tcx hir::ConstArg<'tcx>],
2542        span: Span,
2543    ) -> Const<'tcx> {
2544        let tcx = self.tcx();
2545
2546        let non_adt_or_variant_res = || {
2547            let e = tcx.dcx().span_err(span, "tuple constructor with invalid base path");
2548            ty::Const::new_error(tcx, e)
2549        };
2550
2551        let ctor_const = match qpath {
2552            hir::QPath::Resolved(maybe_qself, path) => {
2553                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2554                self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2555            }
2556            hir::QPath::TypeRelative(hir_self_ty, segment) => {
2557                let self_ty = self.lower_ty(hir_self_ty);
2558                match self.lower_type_relative_const_path(
2559                    self_ty,
2560                    hir_self_ty,
2561                    segment,
2562                    hir_id,
2563                    span,
2564                ) {
2565                    Ok(c) => c,
2566                    Err(_) => return non_adt_or_variant_res(),
2567                }
2568            }
2569        };
2570
2571        let Some(value) = ctor_const.try_to_value() else {
2572            return non_adt_or_variant_res();
2573        };
2574
2575        let (adt_def, adt_args, variant_did) = match value.ty.kind() {
2576            ty::FnDef(def_id, fn_args)
2577                if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(*def_id) =>
2578            {
2579                let parent_did = tcx.parent(*def_id);
2580                let enum_did = tcx.parent(parent_did);
2581                (tcx.adt_def(enum_did), fn_args, parent_did)
2582            }
2583            ty::FnDef(def_id, fn_args)
2584                if let DefKind::Ctor(CtorOf::Struct, _) = tcx.def_kind(*def_id) =>
2585            {
2586                let parent_did = tcx.parent(*def_id);
2587                (tcx.adt_def(parent_did), fn_args, parent_did)
2588            }
2589            _ => {
2590                let e = self.dcx().span_err(
2591                    span,
2592                    "complex const arguments must be placed inside of a `const` block",
2593                );
2594                return Const::new_error(tcx, e);
2595            }
2596        };
2597
2598        let variant_def = adt_def.variant_with_id(variant_did);
2599        let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2600
2601        if args.len() != variant_def.fields.len() {
2602            let e = tcx.dcx().span_err(
2603                span,
2604                ::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!(
2605                    "tuple constructor has {} arguments but {} were provided",
2606                    variant_def.fields.len(),
2607                    args.len()
2608                ),
2609            );
2610            return ty::Const::new_error(tcx, e);
2611        }
2612
2613        let fields = variant_def
2614            .fields
2615            .iter()
2616            .zip(args)
2617            .map(|(field_def, arg)| {
2618                self.lower_const_arg(arg, tcx.type_of(field_def.did).instantiate(tcx, adt_args))
2619            })
2620            .collect::<Vec<_>>();
2621
2622        let opt_discr_const = if adt_def.is_enum() {
2623            let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2624            Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2625        } else {
2626            None
2627        };
2628
2629        let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2630        let adt_ty = Ty::new_adt(tcx, adt_def, adt_args);
2631        ty::Const::new_value(tcx, valtree, adt_ty)
2632    }
2633
2634    fn lower_const_arg_tup(
2635        &self,
2636        exprs: &'tcx [&'tcx hir::ConstArg<'tcx>],
2637        ty: Ty<'tcx>,
2638        span: Span,
2639    ) -> Const<'tcx> {
2640        let tcx = self.tcx();
2641
2642        let tys = match ty.kind() {
2643            ty::Tuple(tys) => tys,
2644            ty::Error(e) => return Const::new_error(tcx, *e),
2645            _ => {
2646                let e = tcx.dcx().span_err(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}`, found const tuple",
                ty))
    })format!("expected `{}`, found const tuple", ty));
2647                return Const::new_error(tcx, e);
2648            }
2649        };
2650
2651        let exprs = exprs
2652            .iter()
2653            .zip(tys.iter())
2654            .map(|(expr, ty)| self.lower_const_arg(expr, ty))
2655            .collect::<Vec<_>>();
2656
2657        let valtree = ty::ValTree::from_branches(tcx, exprs);
2658        ty::Const::new_value(tcx, valtree, ty)
2659    }
2660
2661    fn lower_const_arg_struct(
2662        &self,
2663        hir_id: HirId,
2664        qpath: hir::QPath<'tcx>,
2665        inits: &'tcx [&'tcx hir::ConstArgExprField<'tcx>],
2666        span: Span,
2667    ) -> Const<'tcx> {
2668        // FIXME(mgca): try to deduplicate this function with
2669        // the equivalent HIR typeck logic.
2670        let tcx = self.tcx();
2671
2672        let non_adt_or_variant_res = || {
2673            let e = tcx.dcx().span_err(span, "struct expression with invalid base path");
2674            ty::Const::new_error(tcx, e)
2675        };
2676
2677        let ResolvedStructPath { res: opt_res, ty } =
2678            self.lower_path_for_struct_expr(qpath, span, hir_id);
2679
2680        let variant_did = match qpath {
2681            hir::QPath::Resolved(maybe_qself, path) => {
2682                {
    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:2682",
                        "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(2682u32),
                        ::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);
2683                let variant_did = match path.res {
2684                    Res::Def(DefKind::Variant | DefKind::Struct, did) => did,
2685                    _ => return non_adt_or_variant_res(),
2686                };
2687
2688                variant_did
2689            }
2690            hir::QPath::TypeRelative(hir_self_ty, segment) => {
2691                {
    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:2691",
                        "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(2691u32),
                        ::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);
2692
2693                let res_def_id = match opt_res {
2694                    Ok(r)
2695                        if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(r.def_id()) {
    DefKind::Variant | DefKind::Struct => true,
    _ => false,
}matches!(
2696                            tcx.def_kind(r.def_id()),
2697                            DefKind::Variant | DefKind::Struct
2698                        ) =>
2699                    {
2700                        r.def_id()
2701                    }
2702                    Ok(_) => return non_adt_or_variant_res(),
2703                    Err(e) => return ty::Const::new_error(tcx, e),
2704                };
2705
2706                res_def_id
2707            }
2708        };
2709
2710        let ty::Adt(adt_def, adt_args) = ty.kind() else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2711
2712        let variant_def = adt_def.variant_with_id(variant_did);
2713        let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2714
2715        let fields = variant_def
2716            .fields
2717            .iter()
2718            .map(|field_def| {
2719                // FIXME(mgca): we aren't really handling privacy, stability,
2720                // or macro hygeniene but we should.
2721                let mut init_expr =
2722                    inits.iter().filter(|init_expr| init_expr.field.name == field_def.name);
2723
2724                match init_expr.next() {
2725                    Some(expr) => {
2726                        if let Some(expr) = init_expr.next() {
2727                            let e = tcx.dcx().span_err(
2728                                expr.span,
2729                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("struct expression with multiple initialisers for `{0}`",
                field_def.name))
    })format!(
2730                                    "struct expression with multiple initialisers for `{}`",
2731                                    field_def.name,
2732                                ),
2733                            );
2734                            return ty::Const::new_error(tcx, e);
2735                        }
2736
2737                        self.lower_const_arg(
2738                            expr.expr,
2739                            tcx.type_of(field_def.did).instantiate(tcx, adt_args),
2740                        )
2741                    }
2742                    None => {
2743                        let e = tcx.dcx().span_err(
2744                            span,
2745                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("struct expression with missing field initialiser for `{0}`",
                field_def.name))
    })format!(
2746                                "struct expression with missing field initialiser for `{}`",
2747                                field_def.name
2748                            ),
2749                        );
2750                        ty::Const::new_error(tcx, e)
2751                    }
2752                }
2753            })
2754            .collect::<Vec<_>>();
2755
2756        let opt_discr_const = if adt_def.is_enum() {
2757            let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2758            Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2759        } else {
2760            None
2761        };
2762
2763        let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2764        ty::Const::new_value(tcx, valtree, ty)
2765    }
2766
2767    pub fn lower_path_for_struct_expr(
2768        &self,
2769        qpath: hir::QPath<'tcx>,
2770        path_span: Span,
2771        hir_id: HirId,
2772    ) -> ResolvedStructPath<'tcx> {
2773        match qpath {
2774            hir::QPath::Resolved(ref maybe_qself, path) => {
2775                let self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2776                let ty = self.lower_resolved_ty_path(self_ty, path, hir_id, PermitVariants::Yes);
2777                ResolvedStructPath { res: Ok(path.res), ty }
2778            }
2779            hir::QPath::TypeRelative(hir_self_ty, segment) => {
2780                let self_ty = self.lower_ty(hir_self_ty);
2781
2782                let result = self.lower_type_relative_ty_path(
2783                    self_ty,
2784                    hir_self_ty,
2785                    segment,
2786                    hir_id,
2787                    path_span,
2788                    PermitVariants::Yes,
2789                );
2790                let ty = result
2791                    .map(|(ty, _, _)| ty)
2792                    .unwrap_or_else(|guar| Ty::new_error(self.tcx(), guar));
2793
2794                ResolvedStructPath {
2795                    res: result.map(|(_, kind, def_id)| Res::Def(kind, def_id)),
2796                    ty,
2797                }
2798            }
2799        }
2800    }
2801
2802    /// Lower a [resolved][hir::QPath::Resolved] path to a (type-level) constant.
2803    fn lower_resolved_const_path(
2804        &self,
2805        opt_self_ty: Option<Ty<'tcx>>,
2806        path: &hir::Path<'tcx>,
2807        hir_id: HirId,
2808    ) -> Const<'tcx> {
2809        let tcx = self.tcx();
2810        let span = path.span;
2811        let ct = match path.res {
2812            Res::Def(DefKind::ConstParam, def_id) => {
2813                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);
2814                let _ = self.prohibit_generic_args(
2815                    path.segments.iter(),
2816                    GenericsArgsErrExtend::Param(def_id),
2817                );
2818                self.lower_const_param(def_id, hir_id)
2819            }
2820            Res::Def(DefKind::Const { .. }, did) => {
2821                if let Err(guar) = self.require_type_const_attribute(did, span) {
2822                    return Const::new_error(self.tcx(), guar);
2823                }
2824
2825                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);
2826                let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2827                let _ = self
2828                    .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2829                let args = self.lower_generic_args_of_path_segment(span, did, segment);
2830                ty::Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(did, args))
2831            }
2832            Res::Def(DefKind::Ctor(ctor_of, CtorKind::Const), did) => {
2833                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);
2834                let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2835                let _ = self
2836                    .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2837
2838                let parent_did = tcx.parent(did);
2839                let generics_did = match ctor_of {
2840                    CtorOf::Variant => tcx.parent(parent_did),
2841                    CtorOf::Struct => parent_did,
2842                };
2843                let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2844
2845                self.construct_const_ctor_value(did, ctor_of, args)
2846            }
2847            Res::Def(DefKind::Ctor(_, CtorKind::Fn), did) => {
2848                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);
2849                let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2850                let _ = self
2851                    .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2852                let parent_did = tcx.parent(did);
2853                let generics_did = if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(did) {
2854                    tcx.parent(parent_did)
2855                } else {
2856                    parent_did
2857                };
2858                let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2859                ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2860            }
2861            Res::Def(DefKind::AssocConst { .. }, did) => {
2862                let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2863                    let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2864                    Some(trait_)
2865                } else {
2866                    None
2867                };
2868                self.lower_resolved_assoc_const_path(
2869                    span,
2870                    opt_self_ty,
2871                    did,
2872                    trait_segment,
2873                    path.segments.last().unwrap(),
2874                )
2875                .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2876            }
2877            Res::Def(DefKind::Static { .. }, _) => {
2878                ::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")
2879            }
2880            // FIXME(const_generics): create real const to allow fn items as const paths
2881            Res::Def(DefKind::Fn | DefKind::AssocFn, did) => {
2882                self.dcx().span_delayed_bug(span, "function items cannot be used as const args");
2883                let args = self.lower_generic_args_of_path_segment(
2884                    span,
2885                    did,
2886                    path.segments.last().unwrap(),
2887                );
2888                ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2889            }
2890
2891            // Exhaustive match to be clear about what exactly we're considering to be
2892            // an invalid Res for a const path.
2893            res @ (Res::Def(
2894                DefKind::Mod
2895                | DefKind::Enum
2896                | DefKind::Variant
2897                | DefKind::Struct
2898                | DefKind::OpaqueTy
2899                | DefKind::TyAlias
2900                | DefKind::TraitAlias
2901                | DefKind::AssocTy
2902                | DefKind::Union
2903                | DefKind::Trait
2904                | DefKind::ForeignTy
2905                | DefKind::TyParam
2906                | DefKind::Macro(_)
2907                | DefKind::LifetimeParam
2908                | DefKind::Use
2909                | DefKind::ForeignMod
2910                | DefKind::AnonConst
2911                | DefKind::InlineConst
2912                | DefKind::Field
2913                | DefKind::Impl { .. }
2914                | DefKind::Closure
2915                | DefKind::ExternCrate
2916                | DefKind::GlobalAsm
2917                | DefKind::SyntheticCoroutineBody,
2918                _,
2919            )
2920            | Res::PrimTy(_)
2921            | Res::SelfTyParam { .. }
2922            | Res::SelfTyAlias { .. }
2923            | Res::SelfCtor(_)
2924            | Res::Local(_)
2925            | Res::ToolMod
2926            | Res::OpenMod(..)
2927            | Res::NonMacroAttr(_)
2928            | Res::Err) => Const::new_error_with_message(
2929                tcx,
2930                span,
2931                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("invalid Res {0:?} for const path",
                res))
    })format!("invalid Res {res:?} for const path"),
2932            ),
2933        };
2934        self.check_param_uses_if_mcg(ct, span, false)
2935    }
2936
2937    /// Literals are eagerly converted to a constant, everything else becomes `Unevaluated`.
2938    #[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(2938u32),
                                    ::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:2943",
                                    "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(&["expr"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&expr) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            let ty = tcx.type_of(anon.def_id).instantiate_identity();
            match self.try_lower_anon_const_lit(ty, expr) {
                Some(v) => v,
                None =>
                    ty::Const::new_unevaluated(tcx,
                        ty::UnevaluatedConst {
                            def: anon.def_id.to_def_id(),
                            args: ty::GenericArgs::identity_for_item(tcx,
                                anon.def_id.to_def_id()),
                        }),
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
2939    fn lower_const_arg_anon(&self, anon: &AnonConst) -> Const<'tcx> {
2940        let tcx = self.tcx();
2941
2942        let expr = &tcx.hir_body(anon.body).value;
2943        debug!(?expr);
2944
2945        // FIXME(generic_const_parameter_types): We should use the proper generic args
2946        // here. It's only used as a hint for literals so doesn't matter too much to use the right
2947        // generic arguments, just weaker type inference.
2948        let ty = tcx.type_of(anon.def_id).instantiate_identity();
2949
2950        match self.try_lower_anon_const_lit(ty, expr) {
2951            Some(v) => v,
2952            None => ty::Const::new_unevaluated(
2953                tcx,
2954                ty::UnevaluatedConst {
2955                    def: anon.def_id.to_def_id(),
2956                    args: ty::GenericArgs::identity_for_item(tcx, anon.def_id.to_def_id()),
2957                },
2958            ),
2959        }
2960    }
2961
2962    #[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(2962u32),
                                    ::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")]
2963    fn lower_const_arg_literal(
2964        &self,
2965        kind: &LitKind,
2966        neg: bool,
2967        ty: Ty<'tcx>,
2968        span: Span,
2969    ) -> Const<'tcx> {
2970        let tcx = self.tcx();
2971
2972        let ty = if !ty.has_infer() { Some(ty) } else { None };
2973
2974        if let LitKind::Err(guar) = *kind {
2975            return ty::Const::new_error(tcx, guar);
2976        }
2977        let input = LitToConstInput { lit: *kind, ty, neg };
2978        match tcx.at(span).lit_to_const(input) {
2979            Some(value) => ty::Const::new_value(tcx, value.valtree, value.ty),
2980            None => {
2981                let e = tcx.dcx().span_err(span, "type annotations needed for the literal");
2982                ty::Const::new_error(tcx, e)
2983            }
2984        }
2985    }
2986
2987    #[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(2987u32),
                                    ::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")]
2988    fn try_lower_anon_const_lit(
2989        &self,
2990        ty: Ty<'tcx>,
2991        expr: &'tcx hir::Expr<'tcx>,
2992    ) -> Option<Const<'tcx>> {
2993        let tcx = self.tcx();
2994
2995        // Unwrap a block, so that e.g. `{ 1 }` is recognised as a literal. This makes the
2996        // performance optimisation of directly lowering anon consts occur more often.
2997        let expr = match &expr.kind {
2998            hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2999                block.expr.as_ref().unwrap()
3000            }
3001            _ => expr,
3002        };
3003
3004        let lit_input = match expr.kind {
3005            hir::ExprKind::Lit(lit) => {
3006                Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: false })
3007            }
3008            hir::ExprKind::Unary(hir::UnOp::Neg, expr) => match expr.kind {
3009                hir::ExprKind::Lit(lit) => {
3010                    Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: true })
3011                }
3012                _ => None,
3013            },
3014            _ => None,
3015        };
3016
3017        lit_input.and_then(|l| {
3018            if const_lit_matches_ty(tcx, &l.lit, ty, l.neg) {
3019                tcx.at(expr.span)
3020                    .lit_to_const(l)
3021                    .map(|value| ty::Const::new_value(tcx, value.valtree, value.ty))
3022            } else {
3023                None
3024            }
3025        })
3026    }
3027
3028    fn require_type_const_attribute(
3029        &self,
3030        def_id: DefId,
3031        span: Span,
3032    ) -> Result<(), ErrorGuaranteed> {
3033        let tcx = self.tcx();
3034        if tcx.is_type_const(def_id) {
3035            Ok(())
3036        } else {
3037            let mut err = self.dcx().struct_span_err(
3038                span,
3039                "use of `const` in the type system not defined as `type const`",
3040            );
3041            if def_id.is_local() {
3042                let name = tcx.def_path_str(def_id);
3043                err.span_suggestion_verbose(
3044                    tcx.def_span(def_id).shrink_to_lo(),
3045                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("add `type` before `const` for `{0}`",
                name))
    })format!("add `type` before `const` for `{name}`"),
3046                    ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("type ")) })format!("type "),
3047                    Applicability::MaybeIncorrect,
3048                );
3049            } else {
3050                err.note("only consts marked defined as `type const` may be used in types");
3051            }
3052            Err(err.emit())
3053        }
3054    }
3055
3056    fn lower_delegation_ty(&self, infer: hir::InferDelegation<'tcx>) -> Ty<'tcx> {
3057        match infer {
3058            hir::InferDelegation::DefId(def_id) => {
3059                self.tcx().type_of(def_id).instantiate_identity()
3060            }
3061            rustc_hir::InferDelegation::Sig(_, idx) => {
3062                let delegation_sig = self.tcx().inherit_sig_for_delegation_item(self.item_def_id());
3063
3064                match idx {
3065                    hir::InferDelegationSig::Input(idx) => delegation_sig[idx],
3066                    hir::InferDelegationSig::Output { .. } => *delegation_sig.last().unwrap(),
3067                }
3068            }
3069        }
3070    }
3071
3072    /// Lower a type from the HIR to our internal notion of a type.
3073    x;#[instrument(level = "debug", skip(self), ret)]
3074    pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
3075        let tcx = self.tcx();
3076
3077        let result_ty = match &hir_ty.kind {
3078            hir::TyKind::InferDelegation(infer) => self.lower_delegation_ty(*infer),
3079            hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)),
3080            hir::TyKind::Ptr(mt) => Ty::new_ptr(tcx, self.lower_ty(mt.ty), mt.mutbl),
3081            hir::TyKind::Ref(region, mt) => {
3082                let r = self.lower_lifetime(region, RegionInferReason::Reference);
3083                debug!(?r);
3084                let t = self.lower_ty(mt.ty);
3085                Ty::new_ref(tcx, r, t, mt.mutbl)
3086            }
3087            hir::TyKind::Never => tcx.types.never,
3088            hir::TyKind::Tup(fields) => {
3089                Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
3090            }
3091            hir::TyKind::FnPtr(bf) => {
3092                check_c_variadic_abi(tcx, bf.decl, bf.abi, hir_ty.span);
3093
3094                Ty::new_fn_ptr(
3095                    tcx,
3096                    self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)),
3097                )
3098            }
3099            hir::TyKind::UnsafeBinder(binder) => Ty::new_unsafe_binder(
3100                tcx,
3101                ty::Binder::bind_with_vars(
3102                    self.lower_ty(binder.inner_ty),
3103                    tcx.late_bound_vars(hir_ty.hir_id),
3104                ),
3105            ),
3106            hir::TyKind::TraitObject(bounds, tagged_ptr) => {
3107                let lifetime = tagged_ptr.pointer();
3108                let syntax = tagged_ptr.tag();
3109                self.lower_trait_object_ty(hir_ty.span, hir_ty.hir_id, bounds, lifetime, syntax)
3110            }
3111            // If we encounter a fully qualified path with RTN generics, then it must have
3112            // *not* gone through `lower_ty_maybe_return_type_notation`, and therefore
3113            // it's certainly in an illegal position.
3114            hir::TyKind::Path(hir::QPath::Resolved(_, path))
3115                if path.segments.last().and_then(|segment| segment.args).is_some_and(|args| {
3116                    matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3117                }) =>
3118            {
3119                let guar = self
3120                    .dcx()
3121                    .emit_err(BadReturnTypeNotation { span: hir_ty.span, suggestion: None });
3122                Ty::new_error(tcx, guar)
3123            }
3124            hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
3125                debug!(?maybe_qself, ?path);
3126                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
3127                self.lower_resolved_ty_path(opt_self_ty, path, hir_ty.hir_id, PermitVariants::No)
3128            }
3129            &hir::TyKind::OpaqueDef(opaque_ty) => {
3130                // If this is an RPITIT and we are using the new RPITIT lowering scheme, we
3131                // generate the def_id of an associated type for the trait and return as
3132                // type a projection.
3133                let in_trait = match opaque_ty.origin {
3134                    hir::OpaqueTyOrigin::FnReturn {
3135                        parent,
3136                        in_trait_or_impl: Some(hir::RpitContext::Trait),
3137                        ..
3138                    }
3139                    | hir::OpaqueTyOrigin::AsyncFn {
3140                        parent,
3141                        in_trait_or_impl: Some(hir::RpitContext::Trait),
3142                        ..
3143                    } => Some(parent),
3144                    hir::OpaqueTyOrigin::FnReturn {
3145                        in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3146                        ..
3147                    }
3148                    | hir::OpaqueTyOrigin::AsyncFn {
3149                        in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3150                        ..
3151                    }
3152                    | hir::OpaqueTyOrigin::TyAlias { .. } => None,
3153                };
3154
3155                self.lower_opaque_ty(opaque_ty.def_id, in_trait)
3156            }
3157            hir::TyKind::TraitAscription(hir_bounds) => {
3158                // Impl trait in bindings lower as an infer var with additional
3159                // set of type bounds.
3160                let self_ty = self.ty_infer(None, hir_ty.span);
3161                let mut bounds = Vec::new();
3162                self.lower_bounds(
3163                    self_ty,
3164                    hir_bounds.iter(),
3165                    &mut bounds,
3166                    ty::List::empty(),
3167                    PredicateFilter::All,
3168                    OverlappingAsssocItemConstraints::Allowed,
3169                );
3170                self.add_implicit_sizedness_bounds(
3171                    &mut bounds,
3172                    self_ty,
3173                    hir_bounds,
3174                    ImpliedBoundsContext::AssociatedTypeOrImplTrait,
3175                    hir_ty.span,
3176                );
3177                self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span);
3178                self_ty
3179            }
3180            // If we encounter a type relative path with RTN generics, then it must have
3181            // *not* gone through `lower_ty_maybe_return_type_notation`, and therefore
3182            // it's certainly in an illegal position.
3183            hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment))
3184                if segment.args.is_some_and(|args| {
3185                    matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3186                }) =>
3187            {
3188                let guar = if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3189                    && let None = stmt.init
3190                    && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3191                        hir_self_ty.kind
3192                    && let Res::Def(DefKind::Enum | DefKind::Struct | DefKind::Union, def_id) =
3193                        self_ty_path.res
3194                    && let Some(_) = tcx
3195                        .inherent_impls(def_id)
3196                        .iter()
3197                        .flat_map(|imp| {
3198                            tcx.associated_items(*imp).filter_by_name_unhygienic(segment.ident.name)
3199                        })
3200                        .filter(|assoc| {
3201                            matches!(assoc.kind, ty::AssocKind::Fn { has_self: false, .. })
3202                        })
3203                        .next()
3204                {
3205                    // `let x: S::new(valid_in_ty_ctxt);` -> `let x = S::new(valid_in_ty_ctxt);`
3206                    let err = tcx
3207                        .dcx()
3208                        .struct_span_err(
3209                            hir_ty.span,
3210                            "expected type, found associated function call",
3211                        )
3212                        .with_span_suggestion_verbose(
3213                            stmt.pat.span.between(hir_ty.span),
3214                            "use `=` if you meant to assign",
3215                            " = ".to_string(),
3216                            Applicability::MaybeIncorrect,
3217                        );
3218                    self.dcx().try_steal_replace_and_emit_err(
3219                        hir_ty.span,
3220                        StashKey::ReturnTypeNotation,
3221                        err,
3222                    )
3223                } else if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3224                    && let None = stmt.init
3225                    && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3226                        hir_self_ty.kind
3227                    && let Res::PrimTy(_) = self_ty_path.res
3228                    && self.dcx().has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3229                {
3230                    // `let x: i32::something(valid_in_ty_ctxt);` -> `let x = i32::something(valid_in_ty_ctxt);`
3231                    // FIXME: Check that `something` is a valid function in `i32`.
3232                    let err = tcx
3233                        .dcx()
3234                        .struct_span_err(
3235                            hir_ty.span,
3236                            "expected type, found associated function call",
3237                        )
3238                        .with_span_suggestion_verbose(
3239                            stmt.pat.span.between(hir_ty.span),
3240                            "use `=` if you meant to assign",
3241                            " = ".to_string(),
3242                            Applicability::MaybeIncorrect,
3243                        );
3244                    self.dcx().try_steal_replace_and_emit_err(
3245                        hir_ty.span,
3246                        StashKey::ReturnTypeNotation,
3247                        err,
3248                    )
3249                } else {
3250                    let suggestion = if self
3251                        .dcx()
3252                        .has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3253                    {
3254                        // We already created a diagnostic complaining that `foo(bar)` is wrong and
3255                        // should have been `foo(..)`. Instead, emit only the current error and
3256                        // include that prior suggestion. Changes are that the problems go further,
3257                        // but keep the suggestion just in case. Either way, we want a single error
3258                        // instead of two.
3259                        Some(segment.ident.span.shrink_to_hi().with_hi(hir_ty.span.hi()))
3260                    } else {
3261                        None
3262                    };
3263                    let err = self
3264                        .dcx()
3265                        .create_err(BadReturnTypeNotation { span: hir_ty.span, suggestion });
3266                    self.dcx().try_steal_replace_and_emit_err(
3267                        hir_ty.span,
3268                        StashKey::ReturnTypeNotation,
3269                        err,
3270                    )
3271                };
3272                Ty::new_error(tcx, guar)
3273            }
3274            hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
3275                debug!(?hir_self_ty, ?segment);
3276                let self_ty = self.lower_ty(hir_self_ty);
3277                self.lower_type_relative_ty_path(
3278                    self_ty,
3279                    hir_self_ty,
3280                    segment,
3281                    hir_ty.hir_id,
3282                    hir_ty.span,
3283                    PermitVariants::No,
3284                )
3285                .map(|(ty, _, _)| ty)
3286                .unwrap_or_else(|guar| Ty::new_error(tcx, guar))
3287            }
3288            hir::TyKind::Array(ty, length) => {
3289                let length = self.lower_const_arg(length, tcx.types.usize);
3290                Ty::new_array_with_const_len(tcx, self.lower_ty(ty), length)
3291            }
3292            hir::TyKind::Infer(()) => {
3293                // Infer also appears as the type of arguments or return
3294                // values in an ExprKind::Closure, or as
3295                // the type of local variables. Both of these cases are
3296                // handled specially and will not descend into this routine.
3297                self.ty_infer(None, hir_ty.span)
3298            }
3299            hir::TyKind::Pat(ty, pat) => {
3300                let ty_span = ty.span;
3301                let ty = self.lower_ty(ty);
3302                let pat_ty = match self.lower_pat_ty_pat(ty, ty_span, pat) {
3303                    Ok(kind) => Ty::new_pat(tcx, ty, tcx.mk_pat(kind)),
3304                    Err(guar) => Ty::new_error(tcx, guar),
3305                };
3306                self.record_ty(pat.hir_id, ty, pat.span);
3307                pat_ty
3308            }
3309            hir::TyKind::FieldOf(ty, hir::TyFieldPath { variant, field }) => self.lower_field_of(
3310                self.lower_ty(ty),
3311                self.item_def_id(),
3312                ty.span,
3313                hir_ty.hir_id,
3314                *variant,
3315                *field,
3316            ),
3317            hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar),
3318        };
3319
3320        self.record_ty(hir_ty.hir_id, result_ty, hir_ty.span);
3321        result_ty
3322    }
3323
3324    fn lower_pat_ty_pat(
3325        &self,
3326        ty: Ty<'tcx>,
3327        ty_span: Span,
3328        pat: &hir::TyPat<'tcx>,
3329    ) -> Result<ty::PatternKind<'tcx>, ErrorGuaranteed> {
3330        let tcx = self.tcx();
3331        match pat.kind {
3332            hir::TyPatKind::Range(start, end) => {
3333                match ty.kind() {
3334                    // Keep this list of types in sync with the list of types that
3335                    // the `RangePattern` trait is implemented for.
3336                    ty::Int(_) | ty::Uint(_) | ty::Char => {
3337                        let start = self.lower_const_arg(start, ty);
3338                        let end = self.lower_const_arg(end, ty);
3339                        Ok(ty::PatternKind::Range { start, end })
3340                    }
3341                    _ => Err(self
3342                        .dcx()
3343                        .span_delayed_bug(ty_span, "invalid base type for range pattern")),
3344                }
3345            }
3346            hir::TyPatKind::NotNull => Ok(ty::PatternKind::NotNull),
3347            hir::TyPatKind::Or(patterns) => {
3348                self.tcx()
3349                    .mk_patterns_from_iter(patterns.iter().map(|pat| {
3350                        self.lower_pat_ty_pat(ty, ty_span, pat).map(|pat| tcx.mk_pat(pat))
3351                    }))
3352                    .map(ty::PatternKind::Or)
3353            }
3354            hir::TyPatKind::Err(e) => Err(e),
3355        }
3356    }
3357
3358    fn lower_field_of(
3359        &self,
3360        ty: Ty<'tcx>,
3361        item_def_id: LocalDefId,
3362        ty_span: Span,
3363        hir_id: HirId,
3364        variant: Option<Ident>,
3365        field: Ident,
3366    ) -> Ty<'tcx> {
3367        let dcx = self.dcx();
3368        let tcx = self.tcx();
3369        match ty.kind() {
3370            ty::Adt(def, _) => {
3371                let base_did = def.did();
3372                let kind_name = tcx.def_descr(base_did);
3373                let (variant_idx, variant) = if def.is_enum() {
3374                    let Some(variant) = variant else {
3375                        let err = dcx
3376                            .create_err(NoVariantNamed { span: field.span, ident: field, ty })
3377                            .with_span_help(
3378                                field.span.shrink_to_lo(),
3379                                "you might be missing a variant here: `Variant.`",
3380                            )
3381                            .emit();
3382                        return Ty::new_error(tcx, err);
3383                    };
3384
3385                    if let Some(res) = def
3386                        .variants()
3387                        .iter_enumerated()
3388                        .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == variant)
3389                    {
3390                        res
3391                    } else {
3392                        let err = dcx
3393                            .create_err(NoVariantNamed { span: variant.span, ident: variant, ty })
3394                            .emit();
3395                        return Ty::new_error(tcx, err);
3396                    }
3397                } else {
3398                    if let Some(variant) = variant {
3399                        let adt_path = tcx.def_path_str(base_did);
3400                        {
    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!(
3401                            dcx,
3402                            variant.span,
3403                            E0609,
3404                            "{kind_name} `{adt_path}` does not have any variants",
3405                        )
3406                        .with_span_label(variant.span, "variant unknown")
3407                        .emit();
3408                    }
3409                    (FIRST_VARIANT, def.non_enum_variant())
3410                };
3411                let block = tcx.local_def_id_to_hir_id(item_def_id);
3412                let (ident, def_scope) = tcx.adjust_ident_and_get_scope(field, def.did(), block);
3413                if let Some((field_idx, field)) = variant
3414                    .fields
3415                    .iter_enumerated()
3416                    .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == ident)
3417                {
3418                    if field.vis.is_accessible_from(def_scope, tcx) {
3419                        tcx.check_stability(field.did, Some(hir_id), ident.span, None);
3420                    } else {
3421                        let adt_path = tcx.def_path_str(base_did);
3422                        {
    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!(
3423                            dcx,
3424                            ident.span,
3425                            E0616,
3426                            "field `{ident}` of {kind_name} `{adt_path}` is private",
3427                        )
3428                        .with_span_label(ident.span, "private field")
3429                        .emit();
3430                    }
3431                    Ty::new_field_representing_type(tcx, ty, variant_idx, field_idx)
3432                } else {
3433                    let err =
3434                        dcx.create_err(NoFieldOnType { span: ident.span, field: ident, ty }).emit();
3435                    Ty::new_error(tcx, err)
3436                }
3437            }
3438            ty::Tuple(tys) => {
3439                let index = match field.as_str().parse::<usize>() {
3440                    Ok(idx) => idx,
3441                    Err(_) => {
3442                        let err =
3443                            dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3444                        return Ty::new_error(tcx, err);
3445                    }
3446                };
3447                if field.name != sym::integer(index) {
3448                    ::rustc_middle::util::bug::bug_fmt(format_args!("we parsed above, but now not equal?"));bug!("we parsed above, but now not equal?");
3449                }
3450                if tys.get(index).is_some() {
3451                    Ty::new_field_representing_type(tcx, ty, FIRST_VARIANT, index.into())
3452                } else {
3453                    let err = dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3454                    Ty::new_error(tcx, err)
3455                }
3456            }
3457            // FIXME(FRTs): support type aliases
3458            /*
3459            ty::Alias(AliasTyKind::Free, ty) => {
3460                return self.lower_field_of(
3461                    ty,
3462                    item_def_id,
3463                    ty_span,
3464                    hir_id,
3465                    variant,
3466                    field,
3467                );
3468            }*/
3469            ty::Alias(..) => Ty::new_error(
3470                tcx,
3471                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}`")),
3472            ),
3473            ty::Error(err) => Ty::new_error(tcx, *err),
3474            ty::Bool
3475            | ty::Char
3476            | ty::Int(_)
3477            | ty::Uint(_)
3478            | ty::Float(_)
3479            | ty::Foreign(_)
3480            | ty::Str
3481            | ty::RawPtr(_, _)
3482            | ty::Ref(_, _, _)
3483            | ty::FnDef(_, _)
3484            | ty::FnPtr(_, _)
3485            | ty::UnsafeBinder(_)
3486            | ty::Dynamic(_, _)
3487            | ty::Closure(_, _)
3488            | ty::CoroutineClosure(_, _)
3489            | ty::Coroutine(_, _)
3490            | ty::CoroutineWitness(_, _)
3491            | ty::Never
3492            | ty::Param(_)
3493            | ty::Bound(_, _)
3494            | ty::Placeholder(_)
3495            | ty::Slice(..) => Ty::new_error(
3496                tcx,
3497                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")),
3498            ),
3499            ty::Infer(_) => Ty::new_error(
3500                tcx,
3501                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")),
3502            ),
3503            // FIXME(FRTs): support these types?
3504            ty::Array(..) | ty::Pat(..) => Ty::new_error(
3505                tcx,
3506                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!`")),
3507            ),
3508        }
3509    }
3510
3511    /// Lower an opaque type (i.e., an existential impl-Trait type) from the HIR.
3512    x;#[instrument(level = "debug", skip(self), ret)]
3513    fn lower_opaque_ty(&self, def_id: LocalDefId, in_trait: Option<LocalDefId>) -> Ty<'tcx> {
3514        let tcx = self.tcx();
3515
3516        let lifetimes = tcx.opaque_captured_lifetimes(def_id);
3517        debug!(?lifetimes);
3518
3519        // If this is an RPITIT and we are using the new RPITIT lowering scheme,
3520        // do a linear search to map this to the synthetic associated type that
3521        // it will be lowered to.
3522        let def_id = if let Some(parent_def_id) = in_trait {
3523            *tcx.associated_types_for_impl_traits_in_associated_fn(parent_def_id.to_def_id())
3524                .iter()
3525                .find(|rpitit| match tcx.opt_rpitit_info(**rpitit) {
3526                    Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
3527                        opaque_def_id.expect_local() == def_id
3528                    }
3529                    _ => unreachable!(),
3530                })
3531                .unwrap()
3532        } else {
3533            def_id.to_def_id()
3534        };
3535
3536        let generics = tcx.generics_of(def_id);
3537        debug!(?generics);
3538
3539        // We use `generics.count() - lifetimes.len()` here instead of `generics.parent_count`
3540        // since return-position impl trait in trait squashes all of the generics from its source fn
3541        // into its own generics, so the opaque's "own" params isn't always just lifetimes.
3542        let offset = generics.count() - lifetimes.len();
3543
3544        let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| {
3545            if let Some(i) = (param.index as usize).checked_sub(offset) {
3546                let (lifetime, _) = lifetimes[i];
3547                // FIXME(mgca): should we be calling self.check_params_use_if_mcg here too?
3548                self.lower_resolved_lifetime(lifetime).into()
3549            } else {
3550                tcx.mk_param_from_def(param)
3551            }
3552        });
3553        debug!(?args);
3554
3555        if in_trait.is_some() {
3556            Ty::new_projection_from_args(tcx, def_id, args)
3557        } else {
3558            Ty::new_opaque(tcx, def_id, args)
3559        }
3560    }
3561
3562    /// Lower a function type from the HIR to our internal notion of a function signature.
3563    x;#[instrument(level = "debug", skip(self, hir_id, safety, abi, decl, generics, hir_ty), ret)]
3564    pub fn lower_fn_ty(
3565        &self,
3566        hir_id: HirId,
3567        safety: hir::Safety,
3568        abi: rustc_abi::ExternAbi,
3569        decl: &hir::FnDecl<'tcx>,
3570        generics: Option<&hir::Generics<'_>>,
3571        hir_ty: Option<&hir::Ty<'_>>,
3572    ) -> ty::PolyFnSig<'tcx> {
3573        let tcx = self.tcx();
3574        let bound_vars = tcx.late_bound_vars(hir_id);
3575        debug!(?bound_vars);
3576
3577        let (input_tys, output_ty) = self.lower_fn_sig(decl, generics, hir_id, hir_ty);
3578
3579        debug!(?output_ty);
3580
3581        let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, safety, abi);
3582        let fn_ptr_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3583
3584        if let hir::Node::Ty(hir::Ty { kind: hir::TyKind::FnPtr(fn_ptr_ty), span, .. }) =
3585            tcx.hir_node(hir_id)
3586        {
3587            check_abi(tcx, hir_id, *span, fn_ptr_ty.abi);
3588        }
3589
3590        // reject function types that violate cmse ABI requirements
3591        cmse::validate_cmse_abi(self.tcx(), self.dcx(), hir_id, abi, fn_ptr_ty);
3592
3593        if !fn_ptr_ty.references_error() {
3594            // Find any late-bound regions declared in return type that do
3595            // not appear in the arguments. These are not well-formed.
3596            //
3597            // Example:
3598            //     for<'a> fn() -> &'a str <-- 'a is bad
3599            //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
3600            let inputs = fn_ptr_ty.inputs();
3601            let late_bound_in_args =
3602                tcx.collect_constrained_late_bound_regions(inputs.map_bound(|i| i.to_owned()));
3603            let output = fn_ptr_ty.output();
3604            let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(output);
3605
3606            self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3607                struct_span_code_err!(
3608                    self.dcx(),
3609                    decl.output.span(),
3610                    E0581,
3611                    "return type references {}, which is not constrained by the fn input types",
3612                    br_name
3613                )
3614            });
3615        }
3616
3617        fn_ptr_ty
3618    }
3619
3620    /// Given a fn_hir_id for a impl function, suggest the type that is found on the
3621    /// corresponding function in the trait that the impl implements, if it exists.
3622    /// If arg_idx is Some, then it corresponds to an input type index, otherwise it
3623    /// corresponds to the return type.
3624    pub(super) fn suggest_trait_fn_ty_for_impl_fn_infer(
3625        &self,
3626        fn_hir_id: HirId,
3627        arg_idx: Option<usize>,
3628    ) -> Option<Ty<'tcx>> {
3629        let tcx = self.tcx();
3630        let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3631            tcx.hir_node(fn_hir_id)
3632        else {
3633            return None;
3634        };
3635        let i = tcx.parent_hir_node(fn_hir_id).expect_item().expect_impl();
3636
3637        let trait_ref = self.lower_impl_trait_ref(&i.of_trait?.trait_ref, self.lower_ty(i.self_ty));
3638
3639        let assoc = tcx.associated_items(trait_ref.def_id).find_by_ident_and_kind(
3640            tcx,
3641            *ident,
3642            ty::AssocTag::Fn,
3643            trait_ref.def_id,
3644        )?;
3645
3646        let fn_sig = tcx.fn_sig(assoc.def_id).instantiate(
3647            tcx,
3648            trait_ref.args.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3649        );
3650        let fn_sig = tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), fn_sig);
3651
3652        Some(if let Some(arg_idx) = arg_idx {
3653            *fn_sig.inputs().get(arg_idx)?
3654        } else {
3655            fn_sig.output()
3656        })
3657    }
3658
3659    #[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(3659u32),
                                    ::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))]
3660    fn validate_late_bound_regions<'cx>(
3661        &'cx self,
3662        constrained_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3663        referenced_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3664        generate_err: impl Fn(&str) -> Diag<'cx>,
3665    ) {
3666        for br in referenced_regions.difference(&constrained_regions) {
3667            let br_name = if let Some(name) = br.get_name(self.tcx()) {
3668                format!("lifetime `{name}`")
3669            } else {
3670                "an anonymous lifetime".to_string()
3671            };
3672
3673            let mut err = generate_err(&br_name);
3674
3675            if !br.is_named(self.tcx()) {
3676                // The only way for an anonymous lifetime to wind up
3677                // in the return type but **also** be unconstrained is
3678                // if it only appears in "associated types" in the
3679                // input. See #47511 and #62200 for examples. In this case,
3680                // though we can easily give a hint that ought to be
3681                // relevant.
3682                err.note(
3683                    "lifetimes appearing in an associated or opaque type are not considered constrained",
3684                );
3685                err.note("consider introducing a named lifetime parameter");
3686            }
3687
3688            err.emit();
3689        }
3690    }
3691
3692    /// Given the bounds on an object, determines what single region bound (if any) we can
3693    /// use to summarize this type.
3694    ///
3695    /// The basic idea is that we will use the bound the user
3696    /// provided, if they provided one, and otherwise search the supertypes of trait bounds
3697    /// for region bounds. It may be that we can derive no bound at all, in which case
3698    /// we return `None`.
3699    x;#[instrument(level = "debug", skip(self, span), ret)]
3700    fn compute_object_lifetime_bound(
3701        &self,
3702        span: Span,
3703        existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3704    ) -> Option<ty::Region<'tcx>> // if None, use the default
3705    {
3706        let tcx = self.tcx();
3707
3708        // No explicit region bound specified. Therefore, examine trait
3709        // bounds and see if we can derive region bounds from those.
3710        let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3711
3712        // If there are no derived region bounds, then report back that we
3713        // can find no region bound. The caller will use the default.
3714        if derived_region_bounds.is_empty() {
3715            return None;
3716        }
3717
3718        // If any of the derived region bounds are 'static, that is always
3719        // the best choice.
3720        if derived_region_bounds.iter().any(|r| r.is_static()) {
3721            return Some(tcx.lifetimes.re_static);
3722        }
3723
3724        // Determine whether there is exactly one unique region in the set
3725        // of derived region bounds. If so, use that. Otherwise, report an
3726        // error.
3727        let r = derived_region_bounds[0];
3728        if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3729            self.dcx().emit_err(AmbiguousLifetimeBound { span });
3730        }
3731        Some(r)
3732    }
3733
3734    fn construct_const_ctor_value(
3735        &self,
3736        ctor_def_id: DefId,
3737        ctor_of: CtorOf,
3738        args: GenericArgsRef<'tcx>,
3739    ) -> Const<'tcx> {
3740        let tcx = self.tcx();
3741        let parent_did = tcx.parent(ctor_def_id);
3742
3743        let adt_def = tcx.adt_def(match ctor_of {
3744            CtorOf::Variant => tcx.parent(parent_did),
3745            CtorOf::Struct => parent_did,
3746        });
3747
3748        let variant_idx = adt_def.variant_index_with_id(parent_did);
3749
3750        let valtree = if adt_def.is_enum() {
3751            let discr = ty::ValTree::from_scalar_int(tcx, variant_idx.as_u32().into());
3752            ty::ValTree::from_branches(tcx, [ty::Const::new_value(tcx, discr, tcx.types.u32)])
3753        } else {
3754            ty::ValTree::zst(tcx)
3755        };
3756
3757        let adt_ty = Ty::new_adt(tcx, adt_def, args);
3758        ty::Const::new_value(tcx, valtree, adt_ty)
3759    }
3760}