Skip to main content

rustc_hir_analysis/hir_ty_lowering/
mod.rs

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