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