Skip to main content

rustc_hir_analysis/hir_ty_lowering/
mod.rs

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