Skip to main content

rustc_hir_analysis/hir_ty_lowering/
mod.rs

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