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::slice;
23
24use rustc_ast::LitKind;
25use rustc_data_structures::assert_matches;
26use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
27use rustc_errors::codes::*;
28use rustc_errors::{
29    Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, FatalError, struct_span_code_err,
30};
31use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
32use rustc_hir::def_id::{DefId, LocalDefId};
33use rustc_hir::{self as hir, AnonConst, GenericArg, GenericArgs, HirId};
34use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
35use rustc_infer::traits::DynCompatibilityViolation;
36use rustc_macros::{TypeFoldable, TypeVisitable};
37use rustc_middle::middle::stability::AllowUnstable;
38use rustc_middle::mir::interpret::LitToConstInput;
39use rustc_middle::ty::print::PrintPolyTraitRefExt as _;
40use rustc_middle::ty::{
41    self, Const, GenericArgKind, GenericArgsRef, GenericParamDefKind, Ty, TyCtxt,
42    TypeSuperFoldable, TypeVisitableExt, TypingMode, Upcast, 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::check_c_variadic_abi;
55use crate::errors::{AmbiguousLifetimeBound, BadReturnTypeNotation};
56use crate::hir_ty_lowering::errors::{GenericsArgsErrExtend, prohibit_assoc_item_constraint};
57use crate::hir_ty_lowering::generics::{check_generic_arg_count, lower_generic_args};
58use crate::middle::resolve_bound_vars as rbv;
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 =>
                ::core::fmt::Formatter::write_str(f, "ObjectLifetimeDefault"),
            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,
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
122/// A context which can lower type-system entities from the [HIR][hir] to
123/// the [`rustc_middle::ty`] representation.
124///
125/// This trait used to be called `AstConv`.
126pub trait HirTyLowerer<'tcx> {
127    fn tcx(&self) -> TyCtxt<'tcx>;
128
129    fn dcx(&self) -> DiagCtxtHandle<'_>;
130
131    /// Returns the [`LocalDefId`] of the overarching item whose constituents get lowered.
132    fn item_def_id(&self) -> LocalDefId;
133
134    /// Returns the region to use when a lifetime is omitted (and not elided).
135    fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx>;
136
137    /// Returns the type to use when a type is omitted.
138    fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
139
140    /// Returns the const to use when a const is omitted.
141    fn ct_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx>;
142
143    fn register_trait_ascription_bounds(
144        &self,
145        bounds: Vec<(ty::Clause<'tcx>, Span)>,
146        hir_id: HirId,
147        span: Span,
148    );
149
150    /// Probe bounds in scope where the bounded type coincides with the given type parameter.
151    ///
152    /// Rephrased, this returns bounds of the form `T: Trait`, where `T` is a type parameter
153    /// with the given `def_id`. This is a subset of the full set of bounds.
154    ///
155    /// This method may use the given `assoc_name` to disregard bounds whose trait reference
156    /// doesn't define an associated item with the provided name.
157    ///
158    /// This is used for one specific purpose: Resolving “short-hand” associated type references
159    /// like `T::Item` where `T` is a type parameter. In principle, we would do that by first
160    /// getting the full set of predicates in scope and then filtering down to find those that
161    /// apply to `T`, but this can lead to cycle errors. The problem is that we have to do this
162    /// resolution *in order to create the predicates in the first place*.
163    /// Hence, we have this “special pass”.
164    fn probe_ty_param_bounds(
165        &self,
166        span: Span,
167        def_id: LocalDefId,
168        assoc_ident: Ident,
169    ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]>;
170
171    fn select_inherent_assoc_candidates(
172        &self,
173        span: Span,
174        self_ty: Ty<'tcx>,
175        candidates: Vec<InherentAssocCandidate>,
176    ) -> (Vec<InherentAssocCandidate>, Vec<FulfillmentError<'tcx>>);
177
178    /// Lower a path to an associated item (of a trait) to a projection.
179    ///
180    /// This method has to be defined by the concrete lowering context because
181    /// dealing with higher-ranked trait references depends on its capabilities:
182    ///
183    /// If the context can make use of type inference, it can simply instantiate
184    /// any late-bound vars bound by the trait reference with inference variables.
185    /// If it doesn't support type inference, there is nothing reasonable it can
186    /// do except reject the associated type.
187    ///
188    /// The canonical example of this is associated type `T::P` where `T` is a type
189    /// param constrained by `T: for<'a> Trait<'a>` and where `Trait` defines `P`.
190    fn lower_assoc_item_path(
191        &self,
192        span: Span,
193        item_def_id: DefId,
194        item_segment: &hir::PathSegment<'tcx>,
195        poly_trait_ref: ty::PolyTraitRef<'tcx>,
196    ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed>;
197
198    fn lower_fn_sig(
199        &self,
200        decl: &hir::FnDecl<'tcx>,
201        generics: Option<&hir::Generics<'_>>,
202        hir_id: HirId,
203        hir_ty: Option<&hir::Ty<'_>>,
204    ) -> (Vec<Ty<'tcx>>, Ty<'tcx>);
205
206    /// Returns `AdtDef` if `ty` is an ADT.
207    ///
208    /// Note that `ty` might be a alias type that needs normalization.
209    /// This used to get the enum variants in scope of the type.
210    /// For example, `Self::A` could refer to an associated type
211    /// or to an enum variant depending on the result of this function.
212    fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>>;
213
214    /// Record the lowered type of a HIR node in this context.
215    fn record_ty(&self, hir_id: HirId, ty: Ty<'tcx>, span: Span);
216
217    /// The inference context of the lowering context if applicable.
218    fn infcx(&self) -> Option<&InferCtxt<'tcx>>;
219
220    /// Convenience method for coercing the lowering context into a trait object type.
221    ///
222    /// Most lowering routines are defined on the trait object type directly
223    /// necessitating a coercion step from the concrete lowering context.
224    fn lowerer(&self) -> &dyn HirTyLowerer<'tcx>
225    where
226        Self: Sized,
227    {
228        self
229    }
230
231    /// Performs minimalistic dyn compat checks outside of bodies, but full within bodies.
232    /// Outside of bodies we could end up in cycles, so we delay most checks to later phases.
233    fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation>;
234}
235
236/// The "qualified self" of an associated item path.
237///
238/// For diagnostic purposes only.
239enum AssocItemQSelf {
240    Trait(DefId),
241    TyParam(LocalDefId, Span),
242    SelfTyAlias,
243}
244
245impl AssocItemQSelf {
246    fn to_string(&self, tcx: TyCtxt<'_>) -> String {
247        match *self {
248            Self::Trait(def_id) => tcx.def_path_str(def_id),
249            Self::TyParam(def_id, _) => tcx.hir_ty_param_name(def_id).to_string(),
250            Self::SelfTyAlias => kw::SelfUpper.to_string(),
251        }
252    }
253}
254
255#[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)]
256enum LowerTypeRelativePathMode {
257    Type(PermitVariants),
258    Const,
259}
260
261impl LowerTypeRelativePathMode {
262    fn assoc_tag(self) -> ty::AssocTag {
263        match self {
264            Self::Type(_) => ty::AssocTag::Type,
265            Self::Const => ty::AssocTag::Const,
266        }
267    }
268
269    fn def_kind(self) -> DefKind {
270        match self {
271            Self::Type(_) => DefKind::AssocTy,
272            Self::Const => DefKind::AssocConst,
273        }
274    }
275
276    fn permit_variants(self) -> PermitVariants {
277        match self {
278            Self::Type(permit_variants) => permit_variants,
279            // FIXME(mgca): Support paths like `Option::<T>::None` or `Option::<T>::Some` which
280            // resolve to const ctors/fn items respectively.
281            Self::Const => PermitVariants::No,
282        }
283    }
284}
285
286/// Whether to permit a path to resolve to an enum variant.
287#[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)]
288pub enum PermitVariants {
289    Yes,
290    No,
291}
292
293#[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)]
294enum TypeRelativePath<'tcx> {
295    AssocItem(DefId, GenericArgsRef<'tcx>),
296    Variant { adt: Ty<'tcx>, variant_did: DefId },
297    Ctor { ctor_def_id: DefId, args: GenericArgsRef<'tcx> },
298}
299
300/// New-typed boolean indicating whether explicit late-bound lifetimes
301/// are present in a set of generic arguments.
302///
303/// For example if we have some method `fn f<'a>(&'a self)` implemented
304/// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
305/// is late-bound so should not be provided explicitly. Thus, if `f` is
306/// instantiated with some generic arguments providing `'a` explicitly,
307/// we taint those arguments with `ExplicitLateBound::Yes` so that we
308/// can provide an appropriate diagnostic later.
309#[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)]
310pub enum ExplicitLateBound {
311    Yes,
312    No,
313}
314
315#[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)]
316pub enum IsMethodCall {
317    Yes,
318    No,
319}
320
321/// Denotes the "position" of a generic argument, indicating if it is a generic type,
322/// generic function or generic method call.
323#[derive(#[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)]
324pub(crate) enum GenericArgPosition {
325    Type,
326    Value, // e.g., functions
327    MethodCall,
328}
329
330/// Whether to allow duplicate associated iten constraints in a trait ref, e.g.
331/// `Trait<Assoc = Ty, Assoc = Ty>`. This is forbidden in `dyn Trait<...>`
332/// but allowed everywhere else.
333#[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)]
334pub(crate) enum OverlappingAsssocItemConstraints {
335    Allowed,
336    Forbidden,
337}
338
339/// A marker denoting that the generic arguments that were
340/// provided did not match the respective generic parameters.
341#[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)]
342pub struct GenericArgCountMismatch {
343    pub reported: ErrorGuaranteed,
344    /// A list of indices of arguments provided that were not valid.
345    pub invalid_args: Vec<usize>,
346}
347
348/// Decorates the result of a generic argument count mismatch
349/// check with whether explicit late bounds were provided.
350#[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)]
351pub struct GenericArgCountResult {
352    pub explicit_late_bound: ExplicitLateBound,
353    pub correct: Result<(), GenericArgCountMismatch>,
354}
355
356/// A context which can lower HIR's [`GenericArg`] to `rustc_middle`'s [`ty::GenericArg`].
357///
358/// Its only consumer is [`generics::lower_generic_args`].
359/// Read its documentation to learn more.
360pub trait GenericArgsLowerer<'a, 'tcx> {
361    fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool);
362
363    fn provided_kind(
364        &mut self,
365        preceding_args: &[ty::GenericArg<'tcx>],
366        param: &ty::GenericParamDef,
367        arg: &GenericArg<'tcx>,
368    ) -> ty::GenericArg<'tcx>;
369
370    fn inferred_kind(
371        &mut self,
372        preceding_args: &[ty::GenericArg<'tcx>],
373        param: &ty::GenericParamDef,
374        infer_args: bool,
375    ) -> ty::GenericArg<'tcx>;
376}
377
378struct ForbidMCGParamUsesFolder<'tcx> {
379    tcx: TyCtxt<'tcx>,
380    anon_const_def_id: LocalDefId,
381    span: Span,
382    is_self_alias: bool,
383}
384
385impl<'tcx> ForbidMCGParamUsesFolder<'tcx> {
386    fn error(&self) -> ErrorGuaranteed {
387        let msg = if self.is_self_alias {
388            "generic `Self` types are currently not permitted in anonymous constants"
389        } else {
390            "generic parameters may not be used in const operations"
391        };
392        let mut diag = self.tcx.dcx().struct_span_err(self.span, msg);
393        if self.is_self_alias {
394            let anon_const_hir_id: HirId = HirId::make_owner(self.anon_const_def_id);
395            let parent_impl = self.tcx.hir_parent_owner_iter(anon_const_hir_id).find_map(
396                |(_, node)| match node {
397                    hir::OwnerNode::Item(hir::Item {
398                        kind: hir::ItemKind::Impl(impl_), ..
399                    }) => Some(impl_),
400                    _ => None,
401                },
402            );
403            if let Some(impl_) = parent_impl {
404                diag.span_note(impl_.self_ty.span, "not a concrete type");
405            }
406        }
407        diag.emit()
408    }
409}
410
411impl<'tcx> ty::TypeFolder<TyCtxt<'tcx>> for ForbidMCGParamUsesFolder<'tcx> {
412    fn cx(&self) -> TyCtxt<'tcx> {
413        self.tcx
414    }
415
416    fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
417        if #[allow(non_exhaustive_omitted_patterns)] match t.kind() {
    ty::Param(..) => true,
    _ => false,
}matches!(t.kind(), ty::Param(..)) {
418            return Ty::new_error(self.tcx, self.error());
419        }
420        t.super_fold_with(self)
421    }
422
423    fn fold_const(&mut self, c: Const<'tcx>) -> Const<'tcx> {
424        if #[allow(non_exhaustive_omitted_patterns)] match c.kind() {
    ty::ConstKind::Param(..) => true,
    _ => false,
}matches!(c.kind(), ty::ConstKind::Param(..)) {
425            return Const::new_error(self.tcx, self.error());
426        }
427        c.super_fold_with(self)
428    }
429
430    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
431        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(..)) {
432            return ty::Region::new_error(self.tcx, self.error());
433        }
434        r
435    }
436}
437
438impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
439    /// See `check_param_uses_if_mcg`.
440    ///
441    /// FIXME(mgca): this is pub only for instantiate_value_path and would be nice to avoid altogether
442    pub fn check_param_res_if_mcg_for_instantiate_value_path(
443        &self,
444        res: Res,
445        span: Span,
446    ) -> Result<(), ErrorGuaranteed> {
447        let tcx = self.tcx();
448        let parent_def_id = self.item_def_id();
449        if let Res::Def(DefKind::ConstParam, _) = res
450            && tcx.def_kind(parent_def_id) == DefKind::AnonConst
451            && let ty::AnonConstKind::MCG = tcx.anon_const_kind(parent_def_id)
452        {
453            let folder = ForbidMCGParamUsesFolder {
454                tcx,
455                anon_const_def_id: parent_def_id,
456                span,
457                is_self_alias: false,
458            };
459            return Err(folder.error());
460        }
461        Ok(())
462    }
463
464    /// Check for uses of generic parameters that are not in scope due to this being
465    /// in a non-generic anon const context.
466    #[must_use = "need to use transformed output"]
467    fn check_param_uses_if_mcg<T>(&self, term: T, span: Span, is_self_alias: bool) -> T
468    where
469        T: ty::TypeFoldable<TyCtxt<'tcx>>,
470    {
471        let tcx = self.tcx();
472        let parent_def_id = self.item_def_id();
473        if tcx.def_kind(parent_def_id) == DefKind::AnonConst
474            && let ty::AnonConstKind::MCG = tcx.anon_const_kind(parent_def_id)
475            // Fast path if contains no params/escaping bound vars.
476            && (term.has_param() || term.has_escaping_bound_vars())
477        {
478            let mut folder = ForbidMCGParamUsesFolder {
479                tcx,
480                anon_const_def_id: parent_def_id,
481                span,
482                is_self_alias,
483            };
484            term.fold_with(&mut folder)
485        } else {
486            term
487        }
488    }
489
490    /// Lower a lifetime from the HIR to our internal notion of a lifetime called a *region*.
491    x;#[instrument(level = "debug", skip(self), ret)]
492    pub fn lower_lifetime(
493        &self,
494        lifetime: &hir::Lifetime,
495        reason: RegionInferReason<'_>,
496    ) -> ty::Region<'tcx> {
497        if let Some(resolved) = self.tcx().named_bound_var(lifetime.hir_id) {
498            let region = self.lower_resolved_lifetime(resolved);
499            self.check_param_uses_if_mcg(region, lifetime.ident.span, false)
500        } else {
501            self.re_infer(lifetime.ident.span, reason)
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    fn lower_resolved_lifetime(&self, resolved: rbv::ResolvedArg) -> ty::Region<'tcx> {
508        let tcx = self.tcx();
509
510        match resolved {
511            rbv::ResolvedArg::StaticLifetime => tcx.lifetimes.re_static,
512
513            rbv::ResolvedArg::LateBound(debruijn, index, def_id) => {
514                let br = ty::BoundRegion {
515                    var: ty::BoundVar::from_u32(index),
516                    kind: ty::BoundRegionKind::Named(def_id.to_def_id()),
517                };
518                ty::Region::new_bound(tcx, debruijn, br)
519            }
520
521            rbv::ResolvedArg::EarlyBound(def_id) => {
522                let name = tcx.hir_ty_param_name(def_id);
523                let item_def_id = tcx.hir_ty_param_owner(def_id);
524                let generics = tcx.generics_of(item_def_id);
525                let index = generics.param_def_id_to_index[&def_id.to_def_id()];
526                ty::Region::new_early_param(tcx, ty::EarlyParamRegion { index, name })
527            }
528
529            rbv::ResolvedArg::Free(scope, id) => {
530                ty::Region::new_late_param(
531                    tcx,
532                    scope.to_def_id(),
533                    ty::LateParamRegionKind::Named(id.to_def_id()),
534                )
535
536                // (*) -- not late-bound, won't change
537            }
538
539            rbv::ResolvedArg::Error(guar) => ty::Region::new_error(tcx, guar),
540        }
541    }
542
543    pub fn lower_generic_args_of_path_segment(
544        &self,
545        span: Span,
546        def_id: DefId,
547        item_segment: &hir::PathSegment<'tcx>,
548    ) -> GenericArgsRef<'tcx> {
549        let (args, _) = self.lower_generic_args_of_path(span, def_id, &[], item_segment, None);
550        if let Some(c) = item_segment.args().constraints.first() {
551            prohibit_assoc_item_constraint(self, c, Some((def_id, item_segment, span)));
552        }
553        args
554    }
555
556    /// Lower the generic arguments provided to some path.
557    ///
558    /// If this is a trait reference, you also need to pass the self type `self_ty`.
559    /// The lowering process may involve applying defaulted type parameters.
560    ///
561    /// Associated item constraints are not handled here! They are either lowered via
562    /// `lower_assoc_item_constraint` or rejected via `prohibit_assoc_item_constraint`.
563    ///
564    /// ### Example
565    ///
566    /// ```ignore (illustrative)
567    ///    T: std::ops::Index<usize, Output = u32>
568    /// // ^1 ^^^^^^^^^^^^^^2 ^^^^3  ^^^^^^^^^^^4
569    /// ```
570    ///
571    /// 1. The `self_ty` here would refer to the type `T`.
572    /// 2. The path in question is the path to the trait `std::ops::Index`,
573    ///    which will have been resolved to a `def_id`
574    /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
575    ///    parameters are returned in the `GenericArgsRef`
576    /// 4. Associated item constraints like `Output = u32` are contained in `generic_args.constraints`.
577    ///
578    /// Note that the type listing given here is *exactly* what the user provided.
579    ///
580    /// For (generic) associated types
581    ///
582    /// ```ignore (illustrative)
583    /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
584    /// ```
585    ///
586    /// We have the parent args are the args for the parent trait:
587    /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
588    /// type itself: `['a]`. The returned `GenericArgsRef` concatenates these two
589    /// lists: `[Vec<u8>, u8, 'a]`.
590    x;#[instrument(level = "debug", skip(self, span), ret)]
591    fn lower_generic_args_of_path(
592        &self,
593        span: Span,
594        def_id: DefId,
595        parent_args: &[ty::GenericArg<'tcx>],
596        segment: &hir::PathSegment<'tcx>,
597        self_ty: Option<Ty<'tcx>>,
598    ) -> (GenericArgsRef<'tcx>, GenericArgCountResult) {
599        // If the type is parameterized by this region, then replace this
600        // region with the current anon region binding (in other words,
601        // whatever & would get replaced with).
602
603        let tcx = self.tcx();
604        let generics = tcx.generics_of(def_id);
605        debug!(?generics);
606
607        if generics.has_self {
608            if generics.parent.is_some() {
609                // The parent is a trait so it should have at least one
610                // generic parameter for the `Self` type.
611                assert!(!parent_args.is_empty())
612            } else {
613                // This item (presumably a trait) needs a self-type.
614                assert!(self_ty.is_some());
615            }
616        } else {
617            assert!(self_ty.is_none());
618        }
619
620        let arg_count = check_generic_arg_count(
621            self,
622            def_id,
623            segment,
624            generics,
625            GenericArgPosition::Type,
626            self_ty.is_some(),
627        );
628
629        // Skip processing if type has no generic parameters.
630        // Traits always have `Self` as a generic parameter, which means they will not return early
631        // here and so associated item constraints will be handled regardless of whether there are
632        // any non-`Self` generic parameters.
633        if generics.is_own_empty() {
634            return (tcx.mk_args(parent_args), arg_count);
635        }
636
637        struct GenericArgsCtxt<'a, 'tcx> {
638            lowerer: &'a dyn HirTyLowerer<'tcx>,
639            def_id: DefId,
640            generic_args: &'a GenericArgs<'tcx>,
641            span: Span,
642            infer_args: bool,
643            incorrect_args: &'a Result<(), GenericArgCountMismatch>,
644        }
645
646        impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for GenericArgsCtxt<'a, 'tcx> {
647            fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool) {
648                if did == self.def_id {
649                    (Some(self.generic_args), self.infer_args)
650                } else {
651                    // The last component of this tuple is unimportant.
652                    (None, false)
653                }
654            }
655
656            fn provided_kind(
657                &mut self,
658                preceding_args: &[ty::GenericArg<'tcx>],
659                param: &ty::GenericParamDef,
660                arg: &GenericArg<'tcx>,
661            ) -> ty::GenericArg<'tcx> {
662                let tcx = self.lowerer.tcx();
663
664                if let Err(incorrect) = self.incorrect_args {
665                    if incorrect.invalid_args.contains(&(param.index as usize)) {
666                        return param.to_error(tcx);
667                    }
668                }
669
670                let handle_ty_args = |has_default, ty: &hir::Ty<'tcx>| {
671                    if has_default {
672                        tcx.check_optional_stability(
673                            param.def_id,
674                            Some(arg.hir_id()),
675                            arg.span(),
676                            None,
677                            AllowUnstable::No,
678                            |_, _| {
679                                // Default generic parameters may not be marked
680                                // with stability attributes, i.e. when the
681                                // default parameter was defined at the same time
682                                // as the rest of the type. As such, we ignore missing
683                                // stability attributes.
684                            },
685                        );
686                    }
687                    self.lowerer.lower_ty(ty).into()
688                };
689
690                match (&param.kind, arg) {
691                    (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
692                        self.lowerer.lower_lifetime(lt, RegionInferReason::Param(param)).into()
693                    }
694                    (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
695                        // We handle the other parts of `Ty` in the match arm below
696                        handle_ty_args(has_default, ty.as_unambig_ty())
697                    }
698                    (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
699                        handle_ty_args(has_default, &inf.to_ty())
700                    }
701                    (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => self
702                        .lowerer
703                        // Ambig portions of `ConstArg` are handled in the match arm below
704                        .lower_const_arg(
705                            ct.as_unambig_ct(),
706                            tcx.type_of(param.def_id).instantiate(tcx, preceding_args),
707                        )
708                        .into(),
709                    (&GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
710                        self.lowerer.ct_infer(Some(param), inf.span).into()
711                    }
712                    (kind, arg) => span_bug!(
713                        self.span,
714                        "mismatched path argument for kind {kind:?}: found arg {arg:?}"
715                    ),
716                }
717            }
718
719            fn inferred_kind(
720                &mut self,
721                preceding_args: &[ty::GenericArg<'tcx>],
722                param: &ty::GenericParamDef,
723                infer_args: bool,
724            ) -> ty::GenericArg<'tcx> {
725                let tcx = self.lowerer.tcx();
726
727                if let Err(incorrect) = self.incorrect_args {
728                    if incorrect.invalid_args.contains(&(param.index as usize)) {
729                        return param.to_error(tcx);
730                    }
731                }
732                match param.kind {
733                    GenericParamDefKind::Lifetime => {
734                        self.lowerer.re_infer(self.span, RegionInferReason::Param(param)).into()
735                    }
736                    GenericParamDefKind::Type { has_default, .. } => {
737                        if !infer_args && has_default {
738                            // No type parameter provided, but a default exists.
739                            if let Some(prev) =
740                                preceding_args.iter().find_map(|arg| match arg.kind() {
741                                    GenericArgKind::Type(ty) => ty.error_reported().err(),
742                                    _ => None,
743                                })
744                            {
745                                // Avoid ICE #86756 when type error recovery goes awry.
746                                return Ty::new_error(tcx, prev).into();
747                            }
748                            tcx.at(self.span)
749                                .type_of(param.def_id)
750                                .instantiate(tcx, preceding_args)
751                                .into()
752                        } else if infer_args {
753                            self.lowerer.ty_infer(Some(param), self.span).into()
754                        } else {
755                            // We've already errored above about the mismatch.
756                            Ty::new_misc_error(tcx).into()
757                        }
758                    }
759                    GenericParamDefKind::Const { has_default, .. } => {
760                        let ty = tcx
761                            .at(self.span)
762                            .type_of(param.def_id)
763                            .instantiate(tcx, preceding_args);
764                        if let Err(guar) = ty.error_reported() {
765                            return ty::Const::new_error(tcx, guar).into();
766                        }
767                        if !infer_args && has_default {
768                            tcx.const_param_default(param.def_id)
769                                .instantiate(tcx, preceding_args)
770                                .into()
771                        } else if infer_args {
772                            self.lowerer.ct_infer(Some(param), self.span).into()
773                        } else {
774                            // We've already errored above about the mismatch.
775                            ty::Const::new_misc_error(tcx).into()
776                        }
777                    }
778                }
779            }
780        }
781
782        let mut args_ctx = GenericArgsCtxt {
783            lowerer: self,
784            def_id,
785            span,
786            generic_args: segment.args(),
787            infer_args: segment.infer_args,
788            incorrect_args: &arg_count.correct,
789        };
790        let args = lower_generic_args(
791            self,
792            def_id,
793            parent_args,
794            self_ty.is_some(),
795            self_ty,
796            &arg_count,
797            &mut args_ctx,
798        );
799
800        (args, arg_count)
801    }
802
803    #[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(803u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["span",
                                                    "item_def_id", "item_segment", "parent_args"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_segment)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_args)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: GenericArgsRef<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let (args, _) =
                self.lower_generic_args_of_path(span, item_def_id,
                    parent_args, item_segment, None);
            if let Some(c) = item_segment.args().constraints.first() {
                prohibit_assoc_item_constraint(self, c,
                    Some((item_def_id, item_segment, span)));
            }
            args
        }
    }
}#[instrument(level = "debug", skip(self))]
804    pub fn lower_generic_args_of_assoc_item(
805        &self,
806        span: Span,
807        item_def_id: DefId,
808        item_segment: &hir::PathSegment<'tcx>,
809        parent_args: GenericArgsRef<'tcx>,
810    ) -> GenericArgsRef<'tcx> {
811        let (args, _) =
812            self.lower_generic_args_of_path(span, item_def_id, parent_args, item_segment, None);
813        if let Some(c) = item_segment.args().constraints.first() {
814            prohibit_assoc_item_constraint(self, c, Some((item_def_id, item_segment, span)));
815        }
816        args
817    }
818
819    /// Lower a trait reference as found in an impl header as the implementee.
820    ///
821    /// The self type `self_ty` is the implementer of the trait.
822    pub fn lower_impl_trait_ref(
823        &self,
824        trait_ref: &hir::TraitRef<'tcx>,
825        self_ty: Ty<'tcx>,
826    ) -> ty::TraitRef<'tcx> {
827        let [leading_segments @ .., segment] = trait_ref.path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
828
829        let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
830
831        self.lower_mono_trait_ref(
832            trait_ref.path.span,
833            trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
834            self_ty,
835            segment,
836            true,
837        )
838    }
839
840    /// Lower a polymorphic trait reference given a self type into `bounds`.
841    ///
842    /// *Polymorphic* in the sense that it may bind late-bound vars.
843    ///
844    /// This may generate auxiliary bounds iff the trait reference contains associated item constraints.
845    ///
846    /// ### Example
847    ///
848    /// Given the trait ref `Iterator<Item = u32>` and the self type `Ty`, this will add the
849    ///
850    /// 1. *trait predicate* `<Ty as Iterator>` (known as `Ty: Iterator` in the surface syntax) and the
851    /// 2. *projection predicate* `<Ty as Iterator>::Item = u32`
852    ///
853    /// to `bounds`.
854    ///
855    /// ### A Note on Binders
856    ///
857    /// Against our usual convention, there is an implied binder around the `self_ty` and the
858    /// `trait_ref` here. So they may reference late-bound vars.
859    ///
860    /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
861    /// where `'a` is a bound region at depth 0. Similarly, the `trait_ref` would be `Bar<'a>`.
862    /// The lowered poly-trait-ref will track this binder explicitly, however.
863    #[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(863u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["bound_generic_params",
                                                    "constness", "polarity", "trait_ref", "span", "self_ty",
                                                    "predicate_filter", "overlapping_assoc_item_constraints"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bound_generic_params)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constness)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&polarity)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ref)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&predicate_filter)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&overlapping_assoc_item_constraints)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: GenericArgCountResult = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            let _ = bound_generic_params;
            let trait_def_id =
                trait_ref.trait_def_id().unwrap_or_else(||
                        FatalError.raise());
            let transient =
                match polarity {
                    hir::BoundPolarity::Positive => {
                        tcx.is_lang_item(trait_def_id, hir::LangItem::PointeeSized)
                    }
                    hir::BoundPolarity::Negative(_) => false,
                    hir::BoundPolarity::Maybe(_) => {
                        self.require_bound_to_relax_default_trait(trait_ref, span);
                        true
                    }
                };
            let bounds = if transient { &mut Vec::new() } else { bounds };
            let polarity =
                match polarity {
                    hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_)
                        => {
                        ty::PredicatePolarity::Positive
                    }
                    hir::BoundPolarity::Negative(_) =>
                        ty::PredicatePolarity::Negative,
                };
            let [leading_segments @ .., segment] =
                trait_ref.path.segments else {
                    ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
                };
            let _ =
                self.prohibit_generic_args(leading_segments.iter(),
                    GenericsArgsErrExtend::None);
            self.report_internal_fn_trait(span, trait_def_id, segment, false);
            let (generic_args, arg_count) =
                self.lower_generic_args_of_path(trait_ref.path.span,
                    trait_def_id, &[], segment, Some(self_ty));
            let constraints = segment.args().constraints;
            if transient &&
                    (!generic_args[1..].is_empty() || !constraints.is_empty()) {
                self.dcx().span_delayed_bug(span,
                    "transient bound should not have args or constraints");
            }
            let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:943",
                                    "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(943u32),
                                    ::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:950",
                                    "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(950u32),
                                    ::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))]
864    pub(crate) fn lower_poly_trait_ref(
865        &self,
866        &hir::PolyTraitRef {
867            bound_generic_params,
868            modifiers: hir::TraitBoundModifiers { constness, polarity },
869            trait_ref,
870            span,
871        }: &hir::PolyTraitRef<'tcx>,
872        self_ty: Ty<'tcx>,
873        bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
874        predicate_filter: PredicateFilter,
875        overlapping_assoc_item_constraints: OverlappingAsssocItemConstraints,
876    ) -> GenericArgCountResult {
877        let tcx = self.tcx();
878
879        // We use the *resolved* bound vars later instead of the HIR ones since the former
880        // also include the bound vars of the overarching predicate if applicable.
881        let _ = bound_generic_params;
882
883        let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
884
885        // Relaxed bounds `?Trait` and `PointeeSized` bounds aren't represented in the middle::ty IR
886        // as they denote the *absence* of a default bound. However, we can't bail out early here since
887        // we still need to perform several validation steps (see below). Instead, simply "pour" all
888        // resulting bounds "down the drain", i.e., into a new `Vec` that just gets dropped at the end.
889        let transient = match polarity {
890            hir::BoundPolarity::Positive => {
891                // To elaborate on the comment directly above, regarding `PointeeSized` specifically,
892                // we don't "reify" such bounds to avoid trait system limitations -- namely,
893                // non-global where-clauses being preferred over item bounds (where `PointeeSized`
894                // bounds would be proven) -- which can result in errors when a `PointeeSized`
895                // supertrait / bound / predicate is added to some items.
896                tcx.is_lang_item(trait_def_id, hir::LangItem::PointeeSized)
897            }
898            hir::BoundPolarity::Negative(_) => false,
899            hir::BoundPolarity::Maybe(_) => {
900                self.require_bound_to_relax_default_trait(trait_ref, span);
901                true
902            }
903        };
904        let bounds = if transient { &mut Vec::new() } else { bounds };
905
906        let polarity = match polarity {
907            hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_) => {
908                ty::PredicatePolarity::Positive
909            }
910            hir::BoundPolarity::Negative(_) => ty::PredicatePolarity::Negative,
911        };
912
913        let [leading_segments @ .., segment] = trait_ref.path.segments else { bug!() };
914
915        let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
916        self.report_internal_fn_trait(span, trait_def_id, segment, false);
917
918        let (generic_args, arg_count) = self.lower_generic_args_of_path(
919            trait_ref.path.span,
920            trait_def_id,
921            &[],
922            segment,
923            Some(self_ty),
924        );
925
926        let constraints = segment.args().constraints;
927
928        if transient && (!generic_args[1..].is_empty() || !constraints.is_empty()) {
929            // Since the bound won't be present in the middle::ty IR as established above, any
930            // arguments or constraints won't be checked for well-formedness in later passes.
931            //
932            // This is only an issue if the trait ref is otherwise valid which can only happen if
933            // the corresponding default trait has generic parameters or associated items. Such a
934            // trait would be degenerate. We delay a bug to detect and guard us against these.
935            //
936            // E.g: Given `/*default*/ trait Bound<'a: 'static, T, const N: usize> {}`,
937            // `?Bound<Vec<str>, { panic!() }>` won't be wfchecked.
938            self.dcx()
939                .span_delayed_bug(span, "transient bound should not have args or constraints");
940        }
941
942        let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
943        debug!(?bound_vars);
944
945        let poly_trait_ref = ty::Binder::bind_with_vars(
946            ty::TraitRef::new_from_args(tcx, trait_def_id, generic_args),
947            bound_vars,
948        );
949
950        debug!(?poly_trait_ref);
951
952        // We deal with const conditions later.
953        match predicate_filter {
954            PredicateFilter::All
955            | PredicateFilter::SelfOnly
956            | PredicateFilter::SelfTraitThatDefines(..)
957            | PredicateFilter::SelfAndAssociatedTypeBounds => {
958                let bound = poly_trait_ref.map_bound(|trait_ref| {
959                    ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity })
960                });
961                let bound = (bound.upcast(tcx), span);
962                // FIXME(-Znext-solver): We can likely remove this hack once the
963                // new trait solver lands. This fixed an overflow in the old solver.
964                // This may have performance implications, so please check perf when
965                // removing it.
966                // This was added in <https://github.com/rust-lang/rust/pull/123302>.
967                if tcx.is_lang_item(trait_def_id, rustc_hir::LangItem::Sized) {
968                    bounds.insert(0, bound);
969                } else {
970                    bounds.push(bound);
971                }
972            }
973            PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
974        }
975
976        if let hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) = constness
977            && !tcx.is_const_trait(trait_def_id)
978        {
979            let (def_span, suggestion, suggestion_pre) =
980                match (trait_def_id.as_local(), tcx.sess.is_nightly_build()) {
981                    (Some(trait_def_id), true) => {
982                        let span = tcx.hir_expect_item(trait_def_id).vis_span;
983                        let span = tcx.sess.source_map().span_extend_while_whitespace(span);
984
985                        (
986                            None,
987                            Some(span.shrink_to_hi()),
988                            if self.tcx().features().const_trait_impl() {
989                                ""
990                            } else {
991                                "enable `#![feature(const_trait_impl)]` in your crate and "
992                            },
993                        )
994                    }
995                    (None, _) | (_, false) => (Some(tcx.def_span(trait_def_id)), None, ""),
996                };
997            self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait {
998                span,
999                modifier: constness.as_str(),
1000                def_span,
1001                trait_name: tcx.def_path_str(trait_def_id),
1002                suggestion,
1003                suggestion_pre,
1004            });
1005        } else {
1006            match predicate_filter {
1007                // This is only concerned with trait predicates.
1008                PredicateFilter::SelfTraitThatDefines(..) => {}
1009                PredicateFilter::All
1010                | PredicateFilter::SelfOnly
1011                | PredicateFilter::SelfAndAssociatedTypeBounds => {
1012                    match constness {
1013                        hir::BoundConstness::Always(_) => {
1014                            if polarity == ty::PredicatePolarity::Positive {
1015                                bounds.push((
1016                                    poly_trait_ref
1017                                        .to_host_effect_clause(tcx, ty::BoundConstness::Const),
1018                                    span,
1019                                ));
1020                            }
1021                        }
1022                        hir::BoundConstness::Maybe(_) => {
1023                            // We don't emit a const bound here, since that would mean that we
1024                            // unconditionally need to prove a `HostEffect` predicate, even when
1025                            // the predicates are being instantiated in a non-const context. This
1026                            // is instead handled in the `const_conditions` query.
1027                        }
1028                        hir::BoundConstness::Never => {}
1029                    }
1030                }
1031                // On the flip side, when filtering `ConstIfConst` bounds, we only need to convert
1032                // `[const]` bounds. All other predicates are handled in their respective queries.
1033                //
1034                // Note that like `PredicateFilter::SelfOnly`, we don't need to do any filtering
1035                // here because we only call this on self bounds, and deal with the recursive case
1036                // in `lower_assoc_item_constraint`.
1037                PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {
1038                    match constness {
1039                        hir::BoundConstness::Maybe(_) => {
1040                            if polarity == ty::PredicatePolarity::Positive {
1041                                bounds.push((
1042                                    poly_trait_ref
1043                                        .to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1044                                    span,
1045                                ));
1046                            }
1047                        }
1048                        hir::BoundConstness::Always(_) | hir::BoundConstness::Never => {}
1049                    }
1050                }
1051            }
1052        }
1053
1054        let mut dup_constraints = (overlapping_assoc_item_constraints
1055            == OverlappingAsssocItemConstraints::Forbidden)
1056            .then_some(FxIndexMap::default());
1057
1058        for constraint in constraints {
1059            // Don't register any associated item constraints for negative bounds,
1060            // since we should have emitted an error for them earlier, and they
1061            // would not be well-formed!
1062            if polarity == ty::PredicatePolarity::Negative {
1063                self.dcx().span_delayed_bug(
1064                    constraint.span,
1065                    "negative trait bounds should not have assoc item constraints",
1066                );
1067                break;
1068            }
1069
1070            // Specify type to assert that error was already reported in `Err` case.
1071            let _: Result<_, ErrorGuaranteed> = self.lower_assoc_item_constraint(
1072                trait_ref.hir_ref_id,
1073                poly_trait_ref,
1074                constraint,
1075                bounds,
1076                dup_constraints.as_mut(),
1077                constraint.span,
1078                predicate_filter,
1079            );
1080            // Okay to ignore `Err` because of `ErrorGuaranteed` (see above).
1081        }
1082
1083        arg_count
1084    }
1085
1086    /// Lower a monomorphic trait reference given a self type while prohibiting associated item bindings.
1087    ///
1088    /// *Monomorphic* in the sense that it doesn't bind any late-bound vars.
1089    fn lower_mono_trait_ref(
1090        &self,
1091        span: Span,
1092        trait_def_id: DefId,
1093        self_ty: Ty<'tcx>,
1094        trait_segment: &hir::PathSegment<'tcx>,
1095        is_impl: bool,
1096    ) -> ty::TraitRef<'tcx> {
1097        self.report_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
1098
1099        let (generic_args, _) =
1100            self.lower_generic_args_of_path(span, trait_def_id, &[], trait_segment, Some(self_ty));
1101        if let Some(c) = trait_segment.args().constraints.first() {
1102            prohibit_assoc_item_constraint(self, c, Some((trait_def_id, trait_segment, span)));
1103        }
1104        ty::TraitRef::new_from_args(self.tcx(), trait_def_id, generic_args)
1105    }
1106
1107    fn probe_trait_that_defines_assoc_item(
1108        &self,
1109        trait_def_id: DefId,
1110        assoc_tag: ty::AssocTag,
1111        assoc_ident: Ident,
1112    ) -> bool {
1113        self.tcx()
1114            .associated_items(trait_def_id)
1115            .find_by_ident_and_kind(self.tcx(), assoc_ident, assoc_tag, trait_def_id)
1116            .is_some()
1117    }
1118
1119    fn lower_path_segment(
1120        &self,
1121        span: Span,
1122        did: DefId,
1123        item_segment: &hir::PathSegment<'tcx>,
1124    ) -> Ty<'tcx> {
1125        let tcx = self.tcx();
1126        let args = self.lower_generic_args_of_path_segment(span, did, item_segment);
1127
1128        if let DefKind::TyAlias = tcx.def_kind(did)
1129            && tcx.type_alias_is_lazy(did)
1130        {
1131            // Type aliases defined in crates that have the
1132            // feature `lazy_type_alias` enabled get encoded as a type alias that normalization will
1133            // then actually instantiate the where bounds of.
1134            let alias_ty = ty::AliasTy::new_from_args(tcx, did, args);
1135            Ty::new_alias(tcx, ty::Free, alias_ty)
1136        } else {
1137            tcx.at(span).type_of(did).instantiate(tcx, args)
1138        }
1139    }
1140
1141    /// Search for a trait bound on a type parameter whose trait defines the associated item
1142    /// given by `assoc_ident` and `kind`.
1143    ///
1144    /// This fails if there is no such bound in the list of candidates or if there are multiple
1145    /// candidates in which case it reports ambiguity.
1146    ///
1147    /// `ty_param_def_id` is the `LocalDefId` of the type parameter.
1148    x;#[instrument(level = "debug", skip_all, ret)]
1149    fn probe_single_ty_param_bound_for_assoc_item(
1150        &self,
1151        ty_param_def_id: LocalDefId,
1152        ty_param_span: Span,
1153        assoc_tag: ty::AssocTag,
1154        assoc_ident: Ident,
1155        span: Span,
1156    ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1157        debug!(?ty_param_def_id, ?assoc_ident, ?span);
1158        let tcx = self.tcx();
1159
1160        let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_ident);
1161        debug!("predicates={:#?}", predicates);
1162
1163        self.probe_single_bound_for_assoc_item(
1164            || {
1165                let trait_refs = predicates
1166                    .iter_identity_copied()
1167                    .filter_map(|(p, _)| Some(p.as_trait_clause()?.map_bound(|t| t.trait_ref)));
1168                traits::transitive_bounds_that_define_assoc_item(tcx, trait_refs, assoc_ident)
1169            },
1170            AssocItemQSelf::TyParam(ty_param_def_id, ty_param_span),
1171            assoc_tag,
1172            assoc_ident,
1173            span,
1174            None,
1175        )
1176    }
1177
1178    /// Search for a single trait bound whose trait defines the associated item given by
1179    /// `assoc_ident`.
1180    ///
1181    /// This fails if there is no such bound in the list of candidates or if there are multiple
1182    /// candidates in which case it reports ambiguity.
1183    x;#[instrument(level = "debug", skip(self, all_candidates, qself, constraint), ret)]
1184    fn probe_single_bound_for_assoc_item<I>(
1185        &self,
1186        all_candidates: impl Fn() -> I,
1187        qself: AssocItemQSelf,
1188        assoc_tag: ty::AssocTag,
1189        assoc_ident: Ident,
1190        span: Span,
1191        constraint: Option<&hir::AssocItemConstraint<'tcx>>,
1192    ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1193    where
1194        I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1195    {
1196        let tcx = self.tcx();
1197
1198        let mut matching_candidates = all_candidates().filter(|r| {
1199            self.probe_trait_that_defines_assoc_item(r.def_id(), assoc_tag, assoc_ident)
1200        });
1201
1202        let Some(bound) = matching_candidates.next() else {
1203            return Err(self.report_unresolved_assoc_item(
1204                all_candidates,
1205                qself,
1206                assoc_tag,
1207                assoc_ident,
1208                span,
1209                constraint,
1210            ));
1211        };
1212        debug!(?bound);
1213
1214        if let Some(bound2) = matching_candidates.next() {
1215            debug!(?bound2);
1216
1217            let assoc_kind_str = errors::assoc_tag_str(assoc_tag);
1218            let qself_str = qself.to_string(tcx);
1219            let mut err = self.dcx().create_err(crate::errors::AmbiguousAssocItem {
1220                span,
1221                assoc_kind: assoc_kind_str,
1222                assoc_ident,
1223                qself: &qself_str,
1224            });
1225            // Provide a more specific error code index entry for equality bindings.
1226            err.code(
1227                if let Some(constraint) = constraint
1228                    && let hir::AssocItemConstraintKind::Equality { .. } = constraint.kind
1229                {
1230                    E0222
1231                } else {
1232                    E0221
1233                },
1234            );
1235
1236            // FIXME(#97583): Print associated item bindings properly (i.e., not as equality
1237            // predicates!).
1238            // FIXME: Turn this into a structured, translatable & more actionable suggestion.
1239            let mut where_bounds = vec![];
1240            for bound in [bound, bound2].into_iter().chain(matching_candidates) {
1241                let bound_id = bound.def_id();
1242                let assoc_item = tcx.associated_items(bound_id).find_by_ident_and_kind(
1243                    tcx,
1244                    assoc_ident,
1245                    assoc_tag,
1246                    bound_id,
1247                );
1248                let bound_span = assoc_item.and_then(|item| tcx.hir_span_if_local(item.def_id));
1249
1250                if let Some(bound_span) = bound_span {
1251                    err.span_label(
1252                        bound_span,
1253                        format!("ambiguous `{assoc_ident}` from `{}`", bound.print_trait_sugared(),),
1254                    );
1255                    if let Some(constraint) = constraint {
1256                        match constraint.kind {
1257                            hir::AssocItemConstraintKind::Equality { term } => {
1258                                let term: ty::Term<'_> = match term {
1259                                    hir::Term::Ty(ty) => self.lower_ty(ty).into(),
1260                                    hir::Term::Const(ct) => {
1261                                        let assoc_item =
1262                                            assoc_item.expect("assoc_item should be present");
1263                                        let projection_term = bound.map_bound(|trait_ref| {
1264                                            let item_segment = hir::PathSegment {
1265                                                ident: constraint.ident,
1266                                                hir_id: constraint.hir_id,
1267                                                res: Res::Err,
1268                                                args: Some(constraint.gen_args),
1269                                                infer_args: false,
1270                                            };
1271
1272                                            let alias_args = self.lower_generic_args_of_assoc_item(
1273                                                constraint.ident.span,
1274                                                assoc_item.def_id,
1275                                                &item_segment,
1276                                                trait_ref.args,
1277                                            );
1278                                            ty::AliasTerm::new_from_args(
1279                                                tcx,
1280                                                assoc_item.def_id,
1281                                                alias_args,
1282                                            )
1283                                        });
1284
1285                                        // FIXME(mgca): code duplication with other places we lower
1286                                        // the rhs' of associated const bindings
1287                                        let ty = projection_term.map_bound(|alias| {
1288                                            tcx.type_of(alias.def_id).instantiate(tcx, alias.args)
1289                                        });
1290                                        let ty = bounds::check_assoc_const_binding_type(
1291                                            self,
1292                                            constraint.ident,
1293                                            ty,
1294                                            constraint.hir_id,
1295                                        );
1296
1297                                        self.lower_const_arg(ct, ty).into()
1298                                    }
1299                                };
1300                                if term.references_error() {
1301                                    continue;
1302                                }
1303                                // FIXME(#97583): This isn't syntactically well-formed!
1304                                where_bounds.push(format!(
1305                                    "        T: {trait}::{assoc_ident} = {term}",
1306                                    trait = bound.print_only_trait_path(),
1307                                ));
1308                            }
1309                            // FIXME: Provide a suggestion.
1310                            hir::AssocItemConstraintKind::Bound { bounds: _ } => {}
1311                        }
1312                    } else {
1313                        err.span_suggestion_verbose(
1314                            span.with_hi(assoc_ident.span.lo()),
1315                            "use fully-qualified syntax to disambiguate",
1316                            format!("<{qself_str} as {}>::", bound.print_only_trait_path()),
1317                            Applicability::MaybeIncorrect,
1318                        );
1319                    }
1320                } else {
1321                    let trait_ =
1322                        tcx.short_string(bound.print_only_trait_path(), err.long_ty_path());
1323                    err.note(format!(
1324                        "associated {assoc_kind_str} `{assoc_ident}` could derive from `{trait_}`",
1325                    ));
1326                }
1327            }
1328            if !where_bounds.is_empty() {
1329                err.help(format!(
1330                    "consider introducing a new type parameter `T` and adding `where` constraints:\
1331                     \n    where\n        T: {qself_str},\n{}",
1332                    where_bounds.join(",\n"),
1333                ));
1334                let reported = err.emit();
1335                return Err(reported);
1336            }
1337            err.emit();
1338        }
1339
1340        Ok(bound)
1341    }
1342
1343    /// Lower a [type-relative](hir::QPath::TypeRelative) path in type position to a type.
1344    ///
1345    /// If the path refers to an enum variant and `permit_variants` holds,
1346    /// the returned type is simply the provided self type `qself_ty`.
1347    ///
1348    /// A path like `A::B::C::D` is understood as `<A::B::C>::D`. I.e.,
1349    /// `qself_ty` / `qself` is `A::B::C` and `assoc_segment` is `D`.
1350    /// We return the lowered type and the `DefId` for the whole path.
1351    ///
1352    /// We only support associated type paths whose self type is a type parameter or a `Self`
1353    /// type alias (in a trait impl) like `T::Ty` (where `T` is a ty param) or `Self::Ty`.
1354    /// We **don't** support paths whose self type is an arbitrary type like `Struct::Ty` where
1355    /// struct `Struct` impls an in-scope trait that defines an associated type called `Ty`.
1356    /// For the latter case, we report ambiguity.
1357    /// While desirable to support, the implementation would be non-trivial. Tracked in [#22519].
1358    ///
1359    /// At the time of writing, *inherent associated types* are also resolved here. This however
1360    /// is [problematic][iat]. A proper implementation would be as non-trivial as the one
1361    /// described in the previous paragraph and their modeling of projections would likely be
1362    /// very similar in nature.
1363    ///
1364    /// [#22519]: https://github.com/rust-lang/rust/issues/22519
1365    /// [iat]: https://github.com/rust-lang/rust/issues/8995#issuecomment-1569208403
1366    //
1367    // NOTE: When this function starts resolving `Trait::AssocTy` successfully
1368    // it should also start reporting the `BARE_TRAIT_OBJECTS` lint.
1369    x;#[instrument(level = "debug", skip_all, ret)]
1370    pub fn lower_type_relative_ty_path(
1371        &self,
1372        self_ty: Ty<'tcx>,
1373        hir_self_ty: &'tcx hir::Ty<'tcx>,
1374        segment: &'tcx hir::PathSegment<'tcx>,
1375        qpath_hir_id: HirId,
1376        span: Span,
1377        permit_variants: PermitVariants,
1378    ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1379        let tcx = self.tcx();
1380        match self.lower_type_relative_path(
1381            self_ty,
1382            hir_self_ty,
1383            segment,
1384            qpath_hir_id,
1385            span,
1386            LowerTypeRelativePathMode::Type(permit_variants),
1387        )? {
1388            TypeRelativePath::AssocItem(def_id, args) => {
1389                let alias_ty = ty::AliasTy::new_from_args(tcx, def_id, args);
1390                let ty = Ty::new_alias(tcx, alias_ty.kind(tcx), alias_ty);
1391                let ty = self.check_param_uses_if_mcg(ty, span, false);
1392                Ok((ty, tcx.def_kind(def_id), def_id))
1393            }
1394            TypeRelativePath::Variant { adt, variant_did } => {
1395                let adt = self.check_param_uses_if_mcg(adt, span, false);
1396                Ok((adt, DefKind::Variant, variant_did))
1397            }
1398            TypeRelativePath::Ctor { .. } => {
1399                let e = tcx.dcx().span_err(span, "expected type, found tuple constructor");
1400                Err(e)
1401            }
1402        }
1403    }
1404
1405    /// Lower a [type-relative][hir::QPath::TypeRelative] path to a (type-level) constant.
1406    x;#[instrument(level = "debug", skip_all, ret)]
1407    fn lower_type_relative_const_path(
1408        &self,
1409        self_ty: Ty<'tcx>,
1410        hir_self_ty: &'tcx hir::Ty<'tcx>,
1411        segment: &'tcx hir::PathSegment<'tcx>,
1412        qpath_hir_id: HirId,
1413        span: Span,
1414    ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1415        let tcx = self.tcx();
1416        match self.lower_type_relative_path(
1417            self_ty,
1418            hir_self_ty,
1419            segment,
1420            qpath_hir_id,
1421            span,
1422            LowerTypeRelativePathMode::Const,
1423        )? {
1424            TypeRelativePath::AssocItem(def_id, args) => {
1425                self.require_type_const_attribute(def_id, span)?;
1426                let ct = Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(def_id, args));
1427                let ct = self.check_param_uses_if_mcg(ct, span, false);
1428                Ok(ct)
1429            }
1430            TypeRelativePath::Ctor { ctor_def_id, args } => match tcx.def_kind(ctor_def_id) {
1431                DefKind::Ctor(_, CtorKind::Fn) => {
1432                    Ok(ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, ctor_def_id, args)))
1433                }
1434                DefKind::Ctor(ctor_of, CtorKind::Const) => {
1435                    Ok(self.construct_const_ctor_value(ctor_def_id, ctor_of, args))
1436                }
1437                _ => unreachable!(),
1438            },
1439            // FIXME(mgca): implement support for this once ready to support all adt ctor expressions,
1440            // not just const ctors
1441            TypeRelativePath::Variant { .. } => {
1442                span_bug!(span, "unexpected variant res for type associated const path")
1443            }
1444        }
1445    }
1446
1447    /// Lower a [type-relative][hir::QPath::TypeRelative] (and type-level) path.
1448    x;#[instrument(level = "debug", skip_all, ret)]
1449    fn lower_type_relative_path(
1450        &self,
1451        self_ty: Ty<'tcx>,
1452        hir_self_ty: &'tcx hir::Ty<'tcx>,
1453        segment: &'tcx hir::PathSegment<'tcx>,
1454        qpath_hir_id: HirId,
1455        span: Span,
1456        mode: LowerTypeRelativePathMode,
1457    ) -> Result<TypeRelativePath<'tcx>, ErrorGuaranteed> {
1458        debug!(%self_ty, ?segment.ident);
1459        let tcx = self.tcx();
1460
1461        // Check if we have an enum variant or an inherent associated type.
1462        let mut variant_def_id = None;
1463        if let Some(adt_def) = self.probe_adt(span, self_ty) {
1464            if adt_def.is_enum() {
1465                let variant_def = adt_def
1466                    .variants()
1467                    .iter()
1468                    .find(|vd| tcx.hygienic_eq(segment.ident, vd.ident(tcx), adt_def.did()));
1469                if let Some(variant_def) = variant_def {
1470                    // FIXME(mgca): do we want constructor resolutions to take priority over
1471                    // other possible resolutions?
1472                    if matches!(mode, LowerTypeRelativePathMode::Const)
1473                        && let Some((_, ctor_def_id)) = variant_def.ctor
1474                    {
1475                        tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1476                        let _ = self.prohibit_generic_args(
1477                            slice::from_ref(segment).iter(),
1478                            GenericsArgsErrExtend::EnumVariant {
1479                                qself: hir_self_ty,
1480                                assoc_segment: segment,
1481                                adt_def,
1482                            },
1483                        );
1484                        let ty::Adt(_, enum_args) = self_ty.kind() else { unreachable!() };
1485                        return Ok(TypeRelativePath::Ctor { ctor_def_id, args: enum_args });
1486                    }
1487                    if let PermitVariants::Yes = mode.permit_variants() {
1488                        tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1489                        let _ = self.prohibit_generic_args(
1490                            slice::from_ref(segment).iter(),
1491                            GenericsArgsErrExtend::EnumVariant {
1492                                qself: hir_self_ty,
1493                                assoc_segment: segment,
1494                                adt_def,
1495                            },
1496                        );
1497                        return Ok(TypeRelativePath::Variant {
1498                            adt: self_ty,
1499                            variant_did: variant_def.def_id,
1500                        });
1501                    } else {
1502                        variant_def_id = Some(variant_def.def_id);
1503                    }
1504                }
1505            }
1506
1507            // FIXME(inherent_associated_types, #106719): Support self types other than ADTs.
1508            if let Some((did, args)) = self.probe_inherent_assoc_item(
1509                segment,
1510                adt_def.did(),
1511                self_ty,
1512                qpath_hir_id,
1513                span,
1514                mode.assoc_tag(),
1515            )? {
1516                return Ok(TypeRelativePath::AssocItem(did, args));
1517            }
1518        }
1519
1520        let (item_def_id, bound) = self.resolve_type_relative_path(
1521            self_ty,
1522            hir_self_ty,
1523            mode.assoc_tag(),
1524            segment,
1525            qpath_hir_id,
1526            span,
1527            variant_def_id,
1528        )?;
1529
1530        let (item_def_id, args) = self.lower_assoc_item_path(span, item_def_id, segment, bound)?;
1531
1532        if let Some(variant_def_id) = variant_def_id {
1533            tcx.node_span_lint(AMBIGUOUS_ASSOCIATED_ITEMS, qpath_hir_id, span, |lint| {
1534                lint.primary_message("ambiguous associated item");
1535                let mut could_refer_to = |kind: DefKind, def_id, also| {
1536                    let note_msg = format!(
1537                        "`{}` could{} refer to the {} defined here",
1538                        segment.ident,
1539                        also,
1540                        tcx.def_kind_descr(kind, def_id)
1541                    );
1542                    lint.span_note(tcx.def_span(def_id), note_msg);
1543                };
1544
1545                could_refer_to(DefKind::Variant, variant_def_id, "");
1546                could_refer_to(mode.def_kind(), item_def_id, " also");
1547
1548                lint.span_suggestion(
1549                    span,
1550                    "use fully-qualified syntax",
1551                    format!(
1552                        "<{} as {}>::{}",
1553                        self_ty,
1554                        tcx.item_name(bound.def_id()),
1555                        segment.ident
1556                    ),
1557                    Applicability::MachineApplicable,
1558                );
1559            });
1560        }
1561
1562        Ok(TypeRelativePath::AssocItem(item_def_id, args))
1563    }
1564
1565    /// Resolve a [type-relative](hir::QPath::TypeRelative) (and type-level) path.
1566    fn resolve_type_relative_path(
1567        &self,
1568        self_ty: Ty<'tcx>,
1569        hir_self_ty: &'tcx hir::Ty<'tcx>,
1570        assoc_tag: ty::AssocTag,
1571        segment: &'tcx hir::PathSegment<'tcx>,
1572        qpath_hir_id: HirId,
1573        span: Span,
1574        variant_def_id: Option<DefId>,
1575    ) -> Result<(DefId, ty::PolyTraitRef<'tcx>), ErrorGuaranteed> {
1576        let tcx = self.tcx();
1577
1578        let self_ty_res = match hir_self_ty.kind {
1579            hir::TyKind::Path(hir::QPath::Resolved(_, path)) => path.res,
1580            _ => Res::Err,
1581        };
1582
1583        // Find the type of the assoc item, and the trait where the associated item is declared.
1584        let bound = match (self_ty.kind(), self_ty_res) {
1585            (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
1586                // `Self` in an impl of a trait -- we have a concrete self type and a
1587                // trait reference.
1588                let trait_ref = tcx.impl_trait_ref(impl_def_id);
1589
1590                self.probe_single_bound_for_assoc_item(
1591                    || {
1592                        let trait_ref = ty::Binder::dummy(trait_ref.instantiate_identity());
1593                        traits::supertraits(tcx, trait_ref)
1594                    },
1595                    AssocItemQSelf::SelfTyAlias,
1596                    assoc_tag,
1597                    segment.ident,
1598                    span,
1599                    None,
1600                )?
1601            }
1602            (
1603                &ty::Param(_),
1604                Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
1605            ) => self.probe_single_ty_param_bound_for_assoc_item(
1606                param_did.expect_local(),
1607                hir_self_ty.span,
1608                assoc_tag,
1609                segment.ident,
1610                span,
1611            )?,
1612            _ => {
1613                return Err(self.report_unresolved_type_relative_path(
1614                    self_ty,
1615                    hir_self_ty,
1616                    assoc_tag,
1617                    segment.ident,
1618                    qpath_hir_id,
1619                    span,
1620                    variant_def_id,
1621                ));
1622            }
1623        };
1624
1625        let assoc_item = self
1626            .probe_assoc_item(segment.ident, assoc_tag, qpath_hir_id, span, bound.def_id())
1627            .expect("failed to find associated item");
1628
1629        Ok((assoc_item.def_id, bound))
1630    }
1631
1632    /// Search for inherent associated items for use at the type level.
1633    fn probe_inherent_assoc_item(
1634        &self,
1635        segment: &hir::PathSegment<'tcx>,
1636        adt_did: DefId,
1637        self_ty: Ty<'tcx>,
1638        block: HirId,
1639        span: Span,
1640        assoc_tag: ty::AssocTag,
1641    ) -> Result<Option<(DefId, GenericArgsRef<'tcx>)>, ErrorGuaranteed> {
1642        let tcx = self.tcx();
1643
1644        if !tcx.features().inherent_associated_types() {
1645            match assoc_tag {
1646                // Don't attempt to look up inherent associated types when the feature is not
1647                // enabled. Theoretically it'd be fine to do so since we feature-gate their
1648                // definition site. However, the current implementation of inherent associated
1649                // items is somewhat brittle, so let's not run it by default.
1650                ty::AssocTag::Type => return Ok(None),
1651                ty::AssocTag::Const => {
1652                    // We also gate the mgca codepath for type-level uses of inherent consts
1653                    // with the inherent_associated_types feature gate since it relies on the
1654                    // same machinery and has similar rough edges.
1655                    return Err(feature_err(
1656                        &tcx.sess,
1657                        sym::inherent_associated_types,
1658                        span,
1659                        "inherent associated types are unstable",
1660                    )
1661                    .emit());
1662                }
1663                ty::AssocTag::Fn => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1664            }
1665        }
1666
1667        let name = segment.ident;
1668        let candidates: Vec<_> = tcx
1669            .inherent_impls(adt_did)
1670            .iter()
1671            .filter_map(|&impl_| {
1672                let (item, scope) =
1673                    self.probe_assoc_item_unchecked(name, assoc_tag, block, impl_)?;
1674                Some(InherentAssocCandidate { impl_, assoc_item: item.def_id, scope })
1675            })
1676            .collect();
1677
1678        // At the moment, we actually bail out with a hard error if the selection of an inherent
1679        // associated item fails (see below). This means we never consider trait associated items
1680        // as potential fallback candidates (#142006). To temporarily mask that issue, let's not
1681        // select at all if there are no early inherent candidates.
1682        if candidates.is_empty() {
1683            return Ok(None);
1684        }
1685
1686        let (applicable_candidates, fulfillment_errors) =
1687            self.select_inherent_assoc_candidates(span, self_ty, candidates.clone());
1688
1689        // FIXME(#142006): Don't eagerly error here, there might be applicable trait candidates.
1690        let InherentAssocCandidate { impl_, assoc_item, scope: def_scope } =
1691            match &applicable_candidates[..] {
1692                &[] => Err(self.report_unresolved_inherent_assoc_item(
1693                    name,
1694                    self_ty,
1695                    candidates,
1696                    fulfillment_errors,
1697                    span,
1698                    assoc_tag,
1699                )),
1700
1701                &[applicable_candidate] => Ok(applicable_candidate),
1702
1703                &[_, ..] => Err(self.report_ambiguous_inherent_assoc_item(
1704                    name,
1705                    candidates.into_iter().map(|cand| cand.assoc_item).collect(),
1706                    span,
1707                )),
1708            }?;
1709
1710        // FIXME(#142006): Don't eagerly validate here, there might be trait candidates that are
1711        // accessible (visible and stable) contrary to the inherent candidate.
1712        self.check_assoc_item(assoc_item, name, def_scope, block, span);
1713
1714        // FIXME(fmease): Currently creating throwaway `parent_args` to please
1715        // `lower_generic_args_of_assoc_item`. Modify the latter instead (or sth. similar) to
1716        // not require the parent args logic.
1717        let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
1718        let args = self.lower_generic_args_of_assoc_item(span, assoc_item, segment, parent_args);
1719        let args = tcx.mk_args_from_iter(
1720            std::iter::once(ty::GenericArg::from(self_ty))
1721                .chain(args.into_iter().skip(parent_args.len())),
1722        );
1723
1724        Ok(Some((assoc_item, args)))
1725    }
1726
1727    /// Given name and kind search for the assoc item in the provided scope and check if it's accessible[^1].
1728    ///
1729    /// [^1]: I.e., accessible in the provided scope wrt. visibility and stability.
1730    fn probe_assoc_item(
1731        &self,
1732        ident: Ident,
1733        assoc_tag: ty::AssocTag,
1734        block: HirId,
1735        span: Span,
1736        scope: DefId,
1737    ) -> Option<ty::AssocItem> {
1738        let (item, scope) = self.probe_assoc_item_unchecked(ident, assoc_tag, block, scope)?;
1739        self.check_assoc_item(item.def_id, ident, scope, block, span);
1740        Some(item)
1741    }
1742
1743    /// Given name and kind search for the assoc item in the provided scope
1744    /// *without* checking if it's accessible[^1].
1745    ///
1746    /// [^1]: I.e., accessible in the provided scope wrt. visibility and stability.
1747    fn probe_assoc_item_unchecked(
1748        &self,
1749        ident: Ident,
1750        assoc_tag: ty::AssocTag,
1751        block: HirId,
1752        scope: DefId,
1753    ) -> Option<(ty::AssocItem, /*scope*/ DefId)> {
1754        let tcx = self.tcx();
1755
1756        let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block);
1757        // We have already adjusted the item name above, so compare with `.normalize_to_macros_2_0()`
1758        // instead of calling `filter_by_name_and_kind` which would needlessly normalize the
1759        // `ident` again and again.
1760        let item = tcx
1761            .associated_items(scope)
1762            .filter_by_name_unhygienic(ident.name)
1763            .find(|i| i.tag() == assoc_tag && i.ident(tcx).normalize_to_macros_2_0() == ident)?;
1764
1765        Some((*item, def_scope))
1766    }
1767
1768    /// Check if the given assoc item is accessible in the provided scope wrt. visibility and stability.
1769    fn check_assoc_item(
1770        &self,
1771        item_def_id: DefId,
1772        ident: Ident,
1773        scope: DefId,
1774        block: HirId,
1775        span: Span,
1776    ) {
1777        let tcx = self.tcx();
1778
1779        if !tcx.visibility(item_def_id).is_accessible_from(scope, tcx) {
1780            self.dcx().emit_err(crate::errors::AssocItemIsPrivate {
1781                span,
1782                kind: tcx.def_descr(item_def_id),
1783                name: ident,
1784                defined_here_label: tcx.def_span(item_def_id),
1785            });
1786        }
1787
1788        tcx.check_stability(item_def_id, Some(block), span, None);
1789    }
1790
1791    fn probe_traits_that_match_assoc_ty(
1792        &self,
1793        qself_ty: Ty<'tcx>,
1794        assoc_ident: Ident,
1795    ) -> Vec<String> {
1796        let tcx = self.tcx();
1797
1798        // In contexts that have no inference context, just make a new one.
1799        // We do need a local variable to store it, though.
1800        let infcx_;
1801        let infcx = if let Some(infcx) = self.infcx() {
1802            infcx
1803        } else {
1804            if !!qself_ty.has_infer() {
    ::core::panicking::panic("assertion failed: !qself_ty.has_infer()")
};assert!(!qself_ty.has_infer());
1805            infcx_ = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1806            &infcx_
1807        };
1808
1809        tcx.all_traits_including_private()
1810            .filter(|trait_def_id| {
1811                // Consider only traits with the associated type
1812                tcx.associated_items(*trait_def_id)
1813                        .in_definition_order()
1814                        .any(|i| {
1815                            i.is_type()
1816                                && !i.is_impl_trait_in_trait()
1817                                && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1818                        })
1819                    // Consider only accessible traits
1820                    && tcx.visibility(*trait_def_id)
1821                        .is_accessible_from(self.item_def_id(), tcx)
1822                    && tcx.all_impls(*trait_def_id)
1823                        .any(|impl_def_id| {
1824                            let header = tcx.impl_trait_header(impl_def_id);
1825                            let trait_ref = header.trait_ref.instantiate(
1826                                tcx,
1827                                infcx.fresh_args_for_item(DUMMY_SP, impl_def_id),
1828                            );
1829
1830                            let value = fold_regions(tcx, qself_ty, |_, _| tcx.lifetimes.re_erased);
1831                            // FIXME: Don't bother dealing with non-lifetime binders here...
1832                            if value.has_escaping_bound_vars() {
1833                                return false;
1834                            }
1835                            infcx
1836                                .can_eq(
1837                                    ty::ParamEnv::empty(),
1838                                    trait_ref.self_ty(),
1839                                    value,
1840                                ) && header.polarity != ty::ImplPolarity::Negative
1841                        })
1842            })
1843            .map(|trait_def_id| tcx.def_path_str(trait_def_id))
1844            .collect()
1845    }
1846
1847    /// Lower a [resolved][hir::QPath::Resolved] associated type path to a projection.
1848    #[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(1848u32),
                                    ::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)]
1849    fn lower_resolved_assoc_ty_path(
1850        &self,
1851        span: Span,
1852        opt_self_ty: Option<Ty<'tcx>>,
1853        item_def_id: DefId,
1854        trait_segment: Option<&hir::PathSegment<'tcx>>,
1855        item_segment: &hir::PathSegment<'tcx>,
1856    ) -> Ty<'tcx> {
1857        match self.lower_resolved_assoc_item_path(
1858            span,
1859            opt_self_ty,
1860            item_def_id,
1861            trait_segment,
1862            item_segment,
1863            ty::AssocTag::Type,
1864        ) {
1865            Ok((item_def_id, item_args)) => {
1866                Ty::new_projection_from_args(self.tcx(), item_def_id, item_args)
1867            }
1868            Err(guar) => Ty::new_error(self.tcx(), guar),
1869        }
1870    }
1871
1872    /// Lower a [resolved][hir::QPath::Resolved] associated const path to a (type-level) constant.
1873    #[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(1873u32),
                                    ::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)]
1874    fn lower_resolved_assoc_const_path(
1875        &self,
1876        span: Span,
1877        opt_self_ty: Option<Ty<'tcx>>,
1878        item_def_id: DefId,
1879        trait_segment: Option<&hir::PathSegment<'tcx>>,
1880        item_segment: &hir::PathSegment<'tcx>,
1881    ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1882        let (item_def_id, item_args) = self.lower_resolved_assoc_item_path(
1883            span,
1884            opt_self_ty,
1885            item_def_id,
1886            trait_segment,
1887            item_segment,
1888            ty::AssocTag::Const,
1889        )?;
1890        self.require_type_const_attribute(item_def_id, span)?;
1891        let uv = ty::UnevaluatedConst::new(item_def_id, item_args);
1892        Ok(Const::new_unevaluated(self.tcx(), uv))
1893    }
1894
1895    /// Lower a [resolved][hir::QPath::Resolved] (type-level) associated item path.
1896    #[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(1896u32),
                                    ::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:1909",
                                    "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(1909u32),
                                    ::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:1919",
                                    "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(&["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:1923",
                                    "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(1923u32),
                                    ::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)]
1897    fn lower_resolved_assoc_item_path(
1898        &self,
1899        span: Span,
1900        opt_self_ty: Option<Ty<'tcx>>,
1901        item_def_id: DefId,
1902        trait_segment: Option<&hir::PathSegment<'tcx>>,
1903        item_segment: &hir::PathSegment<'tcx>,
1904        assoc_tag: ty::AssocTag,
1905    ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> {
1906        let tcx = self.tcx();
1907
1908        let trait_def_id = tcx.parent(item_def_id);
1909        debug!(?trait_def_id);
1910
1911        let Some(self_ty) = opt_self_ty else {
1912            return Err(self.report_missing_self_ty_for_resolved_path(
1913                trait_def_id,
1914                span,
1915                item_segment,
1916                assoc_tag,
1917            ));
1918        };
1919        debug!(?self_ty);
1920
1921        let trait_ref =
1922            self.lower_mono_trait_ref(span, trait_def_id, self_ty, trait_segment.unwrap(), false);
1923        debug!(?trait_ref);
1924
1925        let item_args =
1926            self.lower_generic_args_of_assoc_item(span, item_def_id, item_segment, trait_ref.args);
1927
1928        Ok((item_def_id, item_args))
1929    }
1930
1931    pub fn prohibit_generic_args<'a>(
1932        &self,
1933        segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
1934        err_extend: GenericsArgsErrExtend<'a>,
1935    ) -> Result<(), ErrorGuaranteed> {
1936        let args_visitors = segments.clone().flat_map(|segment| segment.args().args);
1937        let mut result = Ok(());
1938        if let Some(_) = args_visitors.clone().next() {
1939            result = Err(self.report_prohibited_generic_args(
1940                segments.clone(),
1941                args_visitors,
1942                err_extend,
1943            ));
1944        }
1945
1946        for segment in segments {
1947            // Only emit the first error to avoid overloading the user with error messages.
1948            if let Some(c) = segment.args().constraints.first() {
1949                return Err(prohibit_assoc_item_constraint(self, c, None));
1950            }
1951        }
1952
1953        result
1954    }
1955
1956    /// Probe path segments that are semantically allowed to have generic arguments.
1957    ///
1958    /// ### Example
1959    ///
1960    /// ```ignore (illustrative)
1961    ///    Option::None::<()>
1962    /// //         ^^^^ permitted to have generic args
1963    ///
1964    /// // ==> [GenericPathSegment(Option_def_id, 1)]
1965    ///
1966    ///    Option::<()>::None
1967    /// // ^^^^^^        ^^^^ *not* permitted to have generic args
1968    /// // permitted to have generic args
1969    ///
1970    /// // ==> [GenericPathSegment(Option_def_id, 0)]
1971    /// ```
1972    // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
1973    pub fn probe_generic_path_segments(
1974        &self,
1975        segments: &[hir::PathSegment<'_>],
1976        self_ty: Option<Ty<'tcx>>,
1977        kind: DefKind,
1978        def_id: DefId,
1979        span: Span,
1980    ) -> Vec<GenericPathSegment> {
1981        // We need to extract the generic arguments supplied by the user in
1982        // the path `path`. Due to the current setup, this is a bit of a
1983        // tricky process; the problem is that resolve only tells us the
1984        // end-point of the path resolution, and not the intermediate steps.
1985        // Luckily, we can (at least for now) deduce the intermediate steps
1986        // just from the end-point.
1987        //
1988        // There are basically five cases to consider:
1989        //
1990        // 1. Reference to a constructor of a struct:
1991        //
1992        //        struct Foo<T>(...)
1993        //
1994        //    In this case, the generic arguments are declared in the type space.
1995        //
1996        // 2. Reference to a constructor of an enum variant:
1997        //
1998        //        enum E<T> { Foo(...) }
1999        //
2000        //    In this case, the generic arguments are defined in the type space,
2001        //    but may be specified either on the type or the variant.
2002        //
2003        // 3. Reference to a free function or constant:
2004        //
2005        //        fn foo<T>() {}
2006        //
2007        //    In this case, the path will again always have the form
2008        //    `a::b::foo::<T>` where only the final segment should have generic
2009        //    arguments. However, in this case, those arguments are declared on
2010        //    a value, and hence are in the value space.
2011        //
2012        // 4. Reference to an associated function or constant:
2013        //
2014        //        impl<A> SomeStruct<A> {
2015        //            fn foo<B>(...) {}
2016        //        }
2017        //
2018        //    Here we can have a path like `a::b::SomeStruct::<A>::foo::<B>`,
2019        //    in which case generic arguments may appear in two places. The
2020        //    penultimate segment, `SomeStruct::<A>`, contains generic arguments
2021        //    in the type space, and the final segment, `foo::<B>` contains
2022        //    generic arguments in value space.
2023        //
2024        // The first step then is to categorize the segments appropriately.
2025
2026        let tcx = self.tcx();
2027
2028        if !!segments.is_empty() {
    ::core::panicking::panic("assertion failed: !segments.is_empty()")
};assert!(!segments.is_empty());
2029        let last = segments.len() - 1;
2030
2031        let mut generic_segments = ::alloc::vec::Vec::new()vec![];
2032
2033        match kind {
2034            // Case 1. Reference to a struct constructor.
2035            DefKind::Ctor(CtorOf::Struct, ..) => {
2036                // Everything but the final segment should have no
2037                // parameters at all.
2038                let generics = tcx.generics_of(def_id);
2039                // Variant and struct constructors use the
2040                // generics of their parent type definition.
2041                let generics_def_id = generics.parent.unwrap_or(def_id);
2042                generic_segments.push(GenericPathSegment(generics_def_id, last));
2043            }
2044
2045            // Case 2. Reference to a variant constructor.
2046            DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2047                let (generics_def_id, index) = if let Some(self_ty) = self_ty {
2048                    let adt_def = self.probe_adt(span, self_ty).unwrap();
2049                    if true {
    if !adt_def.is_enum() {
        ::core::panicking::panic("assertion failed: adt_def.is_enum()")
    };
};debug_assert!(adt_def.is_enum());
2050                    (adt_def.did(), last)
2051                } else if last >= 1 && segments[last - 1].args.is_some() {
2052                    // Everything but the penultimate segment should have no
2053                    // parameters at all.
2054                    let mut def_id = def_id;
2055
2056                    // `DefKind::Ctor` -> `DefKind::Variant`
2057                    if let DefKind::Ctor(..) = kind {
2058                        def_id = tcx.parent(def_id);
2059                    }
2060
2061                    // `DefKind::Variant` -> `DefKind::Enum`
2062                    let enum_def_id = tcx.parent(def_id);
2063                    (enum_def_id, last - 1)
2064                } else {
2065                    // FIXME: lint here recommending `Enum::<...>::Variant` form
2066                    // instead of `Enum::Variant::<...>` form.
2067
2068                    // Everything but the final segment should have no
2069                    // parameters at all.
2070                    let generics = tcx.generics_of(def_id);
2071                    // Variant and struct constructors use the
2072                    // generics of their parent type definition.
2073                    (generics.parent.unwrap_or(def_id), last)
2074                };
2075                generic_segments.push(GenericPathSegment(generics_def_id, index));
2076            }
2077
2078            // Case 3. Reference to a top-level value.
2079            DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static { .. } => {
2080                generic_segments.push(GenericPathSegment(def_id, last));
2081            }
2082
2083            // Case 4. Reference to a method or associated const.
2084            DefKind::AssocFn | DefKind::AssocConst => {
2085                if segments.len() >= 2 {
2086                    let generics = tcx.generics_of(def_id);
2087                    generic_segments.push(GenericPathSegment(generics.parent.unwrap(), last - 1));
2088                }
2089                generic_segments.push(GenericPathSegment(def_id, last));
2090            }
2091
2092            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),
2093        }
2094
2095        {
    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:2095",
                        "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(2095u32),
                        ::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);
2096
2097        generic_segments
2098    }
2099
2100    /// Lower a [resolved][hir::QPath::Resolved] path to a type.
2101    #[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(2101u32),
                                    ::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:2109",
                                    "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(2109u32),
                                    ::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)]
2102    pub fn lower_resolved_ty_path(
2103        &self,
2104        opt_self_ty: Option<Ty<'tcx>>,
2105        path: &hir::Path<'tcx>,
2106        hir_id: HirId,
2107        permit_variants: PermitVariants,
2108    ) -> Ty<'tcx> {
2109        debug!(?path.res, ?opt_self_ty, ?path.segments);
2110        let tcx = self.tcx();
2111
2112        let span = path.span;
2113        match path.res {
2114            Res::Def(DefKind::OpaqueTy, did) => {
2115                // Check for desugared `impl Trait`.
2116                assert_matches!(tcx.opaque_ty_origin(did), hir::OpaqueTyOrigin::TyAlias { .. });
2117                let [leading_segments @ .., segment] = path.segments else { bug!() };
2118                let _ = self.prohibit_generic_args(
2119                    leading_segments.iter(),
2120                    GenericsArgsErrExtend::OpaqueTy,
2121                );
2122                let args = self.lower_generic_args_of_path_segment(span, did, segment);
2123                Ty::new_opaque(tcx, did, args)
2124            }
2125            Res::Def(
2126                DefKind::Enum
2127                | DefKind::TyAlias
2128                | DefKind::Struct
2129                | DefKind::Union
2130                | DefKind::ForeignTy,
2131                did,
2132            ) => {
2133                assert_eq!(opt_self_ty, None);
2134                let [leading_segments @ .., segment] = path.segments else { bug!() };
2135                let _ = self
2136                    .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2137                self.lower_path_segment(span, did, segment)
2138            }
2139            Res::Def(kind @ DefKind::Variant, def_id)
2140                if let PermitVariants::Yes = permit_variants =>
2141            {
2142                // Lower "variant type" as if it were a real type.
2143                // The resulting `Ty` is type of the variant's enum for now.
2144                assert_eq!(opt_self_ty, None);
2145
2146                let generic_segments =
2147                    self.probe_generic_path_segments(path.segments, None, kind, def_id, span);
2148                let indices: FxHashSet<_> =
2149                    generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2150                let _ = self.prohibit_generic_args(
2151                    path.segments.iter().enumerate().filter_map(|(index, seg)| {
2152                        if !indices.contains(&index) { Some(seg) } else { None }
2153                    }),
2154                    GenericsArgsErrExtend::DefVariant(&path.segments),
2155                );
2156
2157                let &GenericPathSegment(def_id, index) = generic_segments.last().unwrap();
2158                self.lower_path_segment(span, def_id, &path.segments[index])
2159            }
2160            Res::Def(DefKind::TyParam, def_id) => {
2161                assert_eq!(opt_self_ty, None);
2162                let _ = self.prohibit_generic_args(
2163                    path.segments.iter(),
2164                    GenericsArgsErrExtend::Param(def_id),
2165                );
2166                self.lower_ty_param(hir_id)
2167            }
2168            Res::SelfTyParam { .. } => {
2169                // `Self` in trait or type alias.
2170                assert_eq!(opt_self_ty, None);
2171                let _ = self.prohibit_generic_args(
2172                    path.segments.iter(),
2173                    if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments {
2174                        GenericsArgsErrExtend::SelfTyParam(
2175                            ident.span.shrink_to_hi().to(args.span_ext),
2176                        )
2177                    } else {
2178                        GenericsArgsErrExtend::None
2179                    },
2180                );
2181                self.check_param_uses_if_mcg(tcx.types.self_param, span, false)
2182            }
2183            Res::SelfTyAlias { alias_to: def_id, .. } => {
2184                // `Self` in impl (we know the concrete type).
2185                assert_eq!(opt_self_ty, None);
2186                // Try to evaluate any array length constants.
2187                let ty = tcx.at(span).type_of(def_id).instantiate_identity();
2188                let _ = self.prohibit_generic_args(
2189                    path.segments.iter(),
2190                    GenericsArgsErrExtend::SelfTyAlias { def_id, span },
2191                );
2192                self.check_param_uses_if_mcg(ty, span, true)
2193            }
2194            Res::Def(DefKind::AssocTy, def_id) => {
2195                let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2196                    let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2197                    Some(trait_)
2198                } else {
2199                    None
2200                };
2201                self.lower_resolved_assoc_ty_path(
2202                    span,
2203                    opt_self_ty,
2204                    def_id,
2205                    trait_segment,
2206                    path.segments.last().unwrap(),
2207                )
2208            }
2209            Res::PrimTy(prim_ty) => {
2210                assert_eq!(opt_self_ty, None);
2211                let _ = self.prohibit_generic_args(
2212                    path.segments.iter(),
2213                    GenericsArgsErrExtend::PrimTy(prim_ty),
2214                );
2215                match prim_ty {
2216                    hir::PrimTy::Bool => tcx.types.bool,
2217                    hir::PrimTy::Char => tcx.types.char,
2218                    hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
2219                    hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
2220                    hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
2221                    hir::PrimTy::Str => tcx.types.str_,
2222                }
2223            }
2224            Res::Err => {
2225                let e = self
2226                    .tcx()
2227                    .dcx()
2228                    .span_delayed_bug(path.span, "path with `Res::Err` but no error emitted");
2229                Ty::new_error(tcx, e)
2230            }
2231            Res::Def(..) => {
2232                assert_eq!(
2233                    path.segments.get(0).map(|seg| seg.ident.name),
2234                    Some(kw::SelfUpper),
2235                    "only expected incorrect resolution for `Self`"
2236                );
2237                Ty::new_error(
2238                    self.tcx(),
2239                    self.dcx().span_delayed_bug(span, "incorrect resolution for `Self`"),
2240                )
2241            }
2242            _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2243        }
2244    }
2245
2246    /// Lower a type parameter from the HIR to our internal notion of a type.
2247    ///
2248    /// Early-bound type parameters get lowered to [`ty::Param`]
2249    /// and late-bound ones to [`ty::Bound`].
2250    pub(crate) fn lower_ty_param(&self, hir_id: HirId) -> Ty<'tcx> {
2251        let tcx = self.tcx();
2252
2253        let ty = match tcx.named_bound_var(hir_id) {
2254            Some(rbv::ResolvedArg::LateBound(debruijn, index, def_id)) => {
2255                let br = ty::BoundTy {
2256                    var: ty::BoundVar::from_u32(index),
2257                    kind: ty::BoundTyKind::Param(def_id.to_def_id()),
2258                };
2259                Ty::new_bound(tcx, debruijn, br)
2260            }
2261            Some(rbv::ResolvedArg::EarlyBound(def_id)) => {
2262                let item_def_id = tcx.hir_ty_param_owner(def_id);
2263                let generics = tcx.generics_of(item_def_id);
2264                let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2265                Ty::new_param(tcx, index, tcx.hir_ty_param_name(def_id))
2266            }
2267            Some(rbv::ResolvedArg::Error(guar)) => Ty::new_error(tcx, guar),
2268            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:?}"),
2269        };
2270        self.check_param_uses_if_mcg(ty, tcx.hir_span(hir_id), false)
2271    }
2272
2273    /// Lower a const parameter from the HIR to our internal notion of a constant.
2274    ///
2275    /// Early-bound const parameters get lowered to [`ty::ConstKind::Param`]
2276    /// and late-bound ones to [`ty::ConstKind::Bound`].
2277    pub(crate) fn lower_const_param(&self, param_def_id: DefId, path_hir_id: HirId) -> Const<'tcx> {
2278        let tcx = self.tcx();
2279
2280        let ct = match tcx.named_bound_var(path_hir_id) {
2281            Some(rbv::ResolvedArg::EarlyBound(_)) => {
2282                // Find the name and index of the const parameter by indexing the generics of
2283                // the parent item and construct a `ParamConst`.
2284                let item_def_id = tcx.parent(param_def_id);
2285                let generics = tcx.generics_of(item_def_id);
2286                let index = generics.param_def_id_to_index[&param_def_id];
2287                let name = tcx.item_name(param_def_id);
2288                ty::Const::new_param(tcx, ty::ParamConst::new(index, name))
2289            }
2290            Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => ty::Const::new_bound(
2291                tcx,
2292                debruijn,
2293                ty::BoundConst::new(ty::BoundVar::from_u32(index)),
2294            ),
2295            Some(rbv::ResolvedArg::Error(guar)) => ty::Const::new_error(tcx, guar),
2296            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),
2297        };
2298        self.check_param_uses_if_mcg(ct, tcx.hir_span(path_hir_id), false)
2299    }
2300
2301    /// Lower a [`hir::ConstArg`] to a (type-level) [`ty::Const`](Const).
2302    #[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(2302u32),
                                    ::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:2354",
                                            "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(2354u32),
                                            ::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:2359",
                                            "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(2359u32),
                                            ::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")]
2303    pub fn lower_const_arg(&self, const_arg: &hir::ConstArg<'tcx>, ty: Ty<'tcx>) -> Const<'tcx> {
2304        let tcx = self.tcx();
2305
2306        if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
2307            // FIXME(generic_const_parameter_types): Ideally we remove these errors below when
2308            // we have the ability to intermix typeck of anon const const args with the parent
2309            // bodies typeck.
2310
2311            // We also error if the type contains any regions as effectively any region will wind
2312            // up as a region variable in mir borrowck. It would also be somewhat concerning if
2313            // hir typeck was using equality but mir borrowck wound up using subtyping as that could
2314            // result in a non-infer in hir typeck but a region variable in borrowck.
2315            if tcx.features().generic_const_parameter_types()
2316                && (ty.has_free_regions() || ty.has_erased_regions())
2317            {
2318                let e = self.dcx().span_err(
2319                    const_arg.span,
2320                    "anonymous constants with lifetimes in their type are not yet supported",
2321                );
2322                tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2323                return ty::Const::new_error(tcx, e);
2324            }
2325            // We must error if the instantiated type has any inference variables as we will
2326            // use this type to feed the `type_of` and query results must not contain inference
2327            // variables otherwise we will ICE.
2328            if ty.has_non_region_infer() {
2329                let e = self.dcx().span_err(
2330                    const_arg.span,
2331                    "anonymous constants with inferred types are not yet supported",
2332                );
2333                tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2334                return ty::Const::new_error(tcx, e);
2335            }
2336            // We error when the type contains unsubstituted generics since we do not currently
2337            // give the anon const any of the generics from the parent.
2338            if ty.has_non_region_param() {
2339                let e = self.dcx().span_err(
2340                    const_arg.span,
2341                    "anonymous constants referencing generics are not yet supported",
2342                );
2343                tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2344                return ty::Const::new_error(tcx, e);
2345            }
2346
2347            tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(ty));
2348        }
2349
2350        let hir_id = const_arg.hir_id;
2351        match const_arg.kind {
2352            hir::ConstArgKind::Tup(exprs) => self.lower_const_arg_tup(exprs, ty, const_arg.span),
2353            hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2354                debug!(?maybe_qself, ?path);
2355                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2356                self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2357            }
2358            hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2359                debug!(?hir_self_ty, ?segment);
2360                let self_ty = self.lower_ty(hir_self_ty);
2361                self.lower_type_relative_const_path(
2362                    self_ty,
2363                    hir_self_ty,
2364                    segment,
2365                    hir_id,
2366                    const_arg.span,
2367                )
2368                .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2369            }
2370            hir::ConstArgKind::Struct(qpath, inits) => {
2371                self.lower_const_arg_struct(hir_id, qpath, inits, const_arg.span)
2372            }
2373            hir::ConstArgKind::TupleCall(qpath, args) => {
2374                self.lower_const_arg_tuple_call(hir_id, qpath, args, const_arg.span)
2375            }
2376            hir::ConstArgKind::Array(array_expr) => self.lower_const_arg_array(array_expr, ty),
2377            hir::ConstArgKind::Anon(anon) => self.lower_const_arg_anon(anon),
2378            hir::ConstArgKind::Infer(()) => self.ct_infer(None, const_arg.span),
2379            hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
2380            hir::ConstArgKind::Literal { lit, negated } => {
2381                self.lower_const_arg_literal(&lit, negated, ty, const_arg.span)
2382            }
2383        }
2384    }
2385
2386    fn lower_const_arg_array(
2387        &self,
2388        array_expr: &'tcx hir::ConstArgArrayExpr<'tcx>,
2389        ty: Ty<'tcx>,
2390    ) -> Const<'tcx> {
2391        let tcx = self.tcx();
2392
2393        let ty::Array(elem_ty, _) = ty.kind() else {
2394            let e = tcx
2395                .dcx()
2396                .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));
2397            return Const::new_error(tcx, e);
2398        };
2399
2400        let elems = array_expr
2401            .elems
2402            .iter()
2403            .map(|elem| self.lower_const_arg(elem, *elem_ty))
2404            .collect::<Vec<_>>();
2405
2406        let valtree = ty::ValTree::from_branches(tcx, elems);
2407
2408        ty::Const::new_value(tcx, valtree, ty)
2409    }
2410
2411    fn lower_const_arg_tuple_call(
2412        &self,
2413        hir_id: HirId,
2414        qpath: hir::QPath<'tcx>,
2415        args: &'tcx [&'tcx hir::ConstArg<'tcx>],
2416        span: Span,
2417    ) -> Const<'tcx> {
2418        let tcx = self.tcx();
2419
2420        let non_adt_or_variant_res = || {
2421            let e = tcx.dcx().span_err(span, "tuple constructor with invalid base path");
2422            ty::Const::new_error(tcx, e)
2423        };
2424
2425        let ctor_const = match qpath {
2426            hir::QPath::Resolved(maybe_qself, path) => {
2427                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2428                self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2429            }
2430            hir::QPath::TypeRelative(hir_self_ty, segment) => {
2431                let self_ty = self.lower_ty(hir_self_ty);
2432                match self.lower_type_relative_const_path(
2433                    self_ty,
2434                    hir_self_ty,
2435                    segment,
2436                    hir_id,
2437                    span,
2438                ) {
2439                    Ok(c) => c,
2440                    Err(_) => return non_adt_or_variant_res(),
2441                }
2442            }
2443        };
2444
2445        let Some(value) = ctor_const.try_to_value() else {
2446            return non_adt_or_variant_res();
2447        };
2448
2449        let (adt_def, adt_args, variant_did) = match value.ty.kind() {
2450            ty::FnDef(def_id, fn_args)
2451                if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(*def_id) =>
2452            {
2453                let parent_did = tcx.parent(*def_id);
2454                let enum_did = tcx.parent(parent_did);
2455                (tcx.adt_def(enum_did), fn_args, parent_did)
2456            }
2457            ty::FnDef(def_id, fn_args)
2458                if let DefKind::Ctor(CtorOf::Struct, _) = tcx.def_kind(*def_id) =>
2459            {
2460                let parent_did = tcx.parent(*def_id);
2461                (tcx.adt_def(parent_did), fn_args, parent_did)
2462            }
2463            _ => return non_adt_or_variant_res(),
2464        };
2465
2466        let variant_def = adt_def.variant_with_id(variant_did);
2467        let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2468
2469        if args.len() != variant_def.fields.len() {
2470            let e = tcx.dcx().span_err(
2471                span,
2472                ::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!(
2473                    "tuple constructor has {} arguments but {} were provided",
2474                    variant_def.fields.len(),
2475                    args.len()
2476                ),
2477            );
2478            return ty::Const::new_error(tcx, e);
2479        }
2480
2481        let fields = variant_def
2482            .fields
2483            .iter()
2484            .zip(args)
2485            .map(|(field_def, arg)| {
2486                self.lower_const_arg(arg, tcx.type_of(field_def.did).instantiate(tcx, adt_args))
2487            })
2488            .collect::<Vec<_>>();
2489
2490        let opt_discr_const = if adt_def.is_enum() {
2491            let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2492            Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2493        } else {
2494            None
2495        };
2496
2497        let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2498        let adt_ty = Ty::new_adt(tcx, adt_def, adt_args);
2499        ty::Const::new_value(tcx, valtree, adt_ty)
2500    }
2501
2502    fn lower_const_arg_tup(
2503        &self,
2504        exprs: &'tcx [&'tcx hir::ConstArg<'tcx>],
2505        ty: Ty<'tcx>,
2506        span: Span,
2507    ) -> Const<'tcx> {
2508        let tcx = self.tcx();
2509
2510        let ty::Tuple(tys) = ty.kind() else {
2511            let e = tcx.dcx().span_err(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}`, found const tuple",
                ty))
    })format!("expected `{}`, found const tuple", ty));
2512            return Const::new_error(tcx, e);
2513        };
2514
2515        let exprs = exprs
2516            .iter()
2517            .zip(tys.iter())
2518            .map(|(expr, ty)| self.lower_const_arg(expr, ty))
2519            .collect::<Vec<_>>();
2520
2521        let valtree = ty::ValTree::from_branches(tcx, exprs);
2522        ty::Const::new_value(tcx, valtree, ty)
2523    }
2524
2525    fn lower_const_arg_struct(
2526        &self,
2527        hir_id: HirId,
2528        qpath: hir::QPath<'tcx>,
2529        inits: &'tcx [&'tcx hir::ConstArgExprField<'tcx>],
2530        span: Span,
2531    ) -> Const<'tcx> {
2532        // FIXME(mgca): try to deduplicate this function with
2533        // the equivalent HIR typeck logic.
2534        let tcx = self.tcx();
2535
2536        let non_adt_or_variant_res = || {
2537            let e = tcx.dcx().span_err(span, "struct expression with invalid base path");
2538            ty::Const::new_error(tcx, e)
2539        };
2540
2541        let (ty, variant_did) = match qpath {
2542            hir::QPath::Resolved(maybe_qself, path) => {
2543                {
    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:2543",
                        "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(2543u32),
                        ::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);
2544                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2545                let ty =
2546                    self.lower_resolved_ty_path(opt_self_ty, path, hir_id, PermitVariants::Yes);
2547                let variant_did = match path.res {
2548                    Res::Def(DefKind::Variant | DefKind::Struct, did) => did,
2549                    _ => return non_adt_or_variant_res(),
2550                };
2551
2552                (ty, variant_did)
2553            }
2554            hir::QPath::TypeRelative(hir_self_ty, segment) => {
2555                {
    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:2555",
                        "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(2555u32),
                        ::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);
2556                let self_ty = self.lower_ty(hir_self_ty);
2557                let opt_res = self.lower_type_relative_ty_path(
2558                    self_ty,
2559                    hir_self_ty,
2560                    segment,
2561                    hir_id,
2562                    span,
2563                    PermitVariants::Yes,
2564                );
2565
2566                let (ty, _, res_def_id) = match opt_res {
2567                    Ok(r @ (_, DefKind::Variant | DefKind::Struct, _)) => r,
2568                    Ok(_) => return non_adt_or_variant_res(),
2569                    Err(e) => return ty::Const::new_error(tcx, e),
2570                };
2571
2572                (ty, res_def_id)
2573            }
2574        };
2575
2576        let ty::Adt(adt_def, adt_args) = ty.kind() else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2577
2578        let variant_def = adt_def.variant_with_id(variant_did);
2579        let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2580
2581        let fields = variant_def
2582            .fields
2583            .iter()
2584            .map(|field_def| {
2585                // FIXME(mgca): we aren't really handling privacy, stability,
2586                // or macro hygeniene but we should.
2587                let mut init_expr =
2588                    inits.iter().filter(|init_expr| init_expr.field.name == field_def.name);
2589
2590                match init_expr.next() {
2591                    Some(expr) => {
2592                        if let Some(expr) = init_expr.next() {
2593                            let e = tcx.dcx().span_err(
2594                                expr.span,
2595                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("struct expression with multiple initialisers for `{0}`",
                field_def.name))
    })format!(
2596                                    "struct expression with multiple initialisers for `{}`",
2597                                    field_def.name,
2598                                ),
2599                            );
2600                            return ty::Const::new_error(tcx, e);
2601                        }
2602
2603                        self.lower_const_arg(
2604                            expr.expr,
2605                            tcx.type_of(field_def.did).instantiate(tcx, adt_args),
2606                        )
2607                    }
2608                    None => {
2609                        let e = tcx.dcx().span_err(
2610                            span,
2611                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("struct expression with missing field initialiser for `{0}`",
                field_def.name))
    })format!(
2612                                "struct expression with missing field initialiser for `{}`",
2613                                field_def.name
2614                            ),
2615                        );
2616                        ty::Const::new_error(tcx, e)
2617                    }
2618                }
2619            })
2620            .collect::<Vec<_>>();
2621
2622        let opt_discr_const = if adt_def.is_enum() {
2623            let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2624            Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2625        } else {
2626            None
2627        };
2628
2629        let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2630        ty::Const::new_value(tcx, valtree, ty)
2631    }
2632
2633    /// Lower a [resolved][hir::QPath::Resolved] path to a (type-level) constant.
2634    fn lower_resolved_const_path(
2635        &self,
2636        opt_self_ty: Option<Ty<'tcx>>,
2637        path: &hir::Path<'tcx>,
2638        hir_id: HirId,
2639    ) -> Const<'tcx> {
2640        let tcx = self.tcx();
2641        let span = path.span;
2642        let ct = match path.res {
2643            Res::Def(DefKind::ConstParam, def_id) => {
2644                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);
2645                let _ = self.prohibit_generic_args(
2646                    path.segments.iter(),
2647                    GenericsArgsErrExtend::Param(def_id),
2648                );
2649                self.lower_const_param(def_id, hir_id)
2650            }
2651            Res::Def(DefKind::Const, did) => {
2652                if let Err(guar) = self.require_type_const_attribute(did, span) {
2653                    return Const::new_error(self.tcx(), guar);
2654                }
2655
2656                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);
2657                let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2658                let _ = self
2659                    .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2660                let args = self.lower_generic_args_of_path_segment(span, did, segment);
2661                ty::Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(did, args))
2662            }
2663            Res::Def(DefKind::Ctor(ctor_of, CtorKind::Const), did) => {
2664                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);
2665                let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2666                let _ = self
2667                    .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2668
2669                let parent_did = tcx.parent(did);
2670                let generics_did = match ctor_of {
2671                    CtorOf::Variant => tcx.parent(parent_did),
2672                    CtorOf::Struct => parent_did,
2673                };
2674                let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2675
2676                self.construct_const_ctor_value(did, ctor_of, args)
2677            }
2678            Res::Def(DefKind::Ctor(_, CtorKind::Fn), did) => {
2679                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);
2680                let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2681                let _ = self
2682                    .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2683                let parent_did = tcx.parent(did);
2684                let generics_did = if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(did) {
2685                    tcx.parent(parent_did)
2686                } else {
2687                    parent_did
2688                };
2689                let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2690                ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2691            }
2692            Res::Def(DefKind::AssocConst, did) => {
2693                let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2694                    let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2695                    Some(trait_)
2696                } else {
2697                    None
2698                };
2699                self.lower_resolved_assoc_const_path(
2700                    span,
2701                    opt_self_ty,
2702                    did,
2703                    trait_segment,
2704                    path.segments.last().unwrap(),
2705                )
2706                .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2707            }
2708            Res::Def(DefKind::Static { .. }, _) => {
2709                ::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")
2710            }
2711            // FIXME(const_generics): create real const to allow fn items as const paths
2712            Res::Def(DefKind::Fn | DefKind::AssocFn, did) => {
2713                self.dcx().span_delayed_bug(span, "function items cannot be used as const args");
2714                let args = self.lower_generic_args_of_path_segment(
2715                    span,
2716                    did,
2717                    path.segments.last().unwrap(),
2718                );
2719                ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2720            }
2721
2722            // Exhaustive match to be clear about what exactly we're considering to be
2723            // an invalid Res for a const path.
2724            res @ (Res::Def(
2725                DefKind::Mod
2726                | DefKind::Enum
2727                | DefKind::Variant
2728                | DefKind::Struct
2729                | DefKind::OpaqueTy
2730                | DefKind::TyAlias
2731                | DefKind::TraitAlias
2732                | DefKind::AssocTy
2733                | DefKind::Union
2734                | DefKind::Trait
2735                | DefKind::ForeignTy
2736                | DefKind::TyParam
2737                | DefKind::Macro(_)
2738                | DefKind::LifetimeParam
2739                | DefKind::Use
2740                | DefKind::ForeignMod
2741                | DefKind::AnonConst
2742                | DefKind::InlineConst
2743                | DefKind::Field
2744                | DefKind::Impl { .. }
2745                | DefKind::Closure
2746                | DefKind::ExternCrate
2747                | DefKind::GlobalAsm
2748                | DefKind::SyntheticCoroutineBody,
2749                _,
2750            )
2751            | Res::PrimTy(_)
2752            | Res::SelfTyParam { .. }
2753            | Res::SelfTyAlias { .. }
2754            | Res::SelfCtor(_)
2755            | Res::Local(_)
2756            | Res::ToolMod
2757            | Res::NonMacroAttr(_)
2758            | Res::Err) => Const::new_error_with_message(
2759                tcx,
2760                span,
2761                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("invalid Res {0:?} for const path",
                res))
    })format!("invalid Res {res:?} for const path"),
2762            ),
2763        };
2764        self.check_param_uses_if_mcg(ct, span, false)
2765    }
2766
2767    /// Literals are eagerly converted to a constant, everything else becomes `Unevaluated`.
2768    #[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(2768u32),
                                    ::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:2773",
                                    "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(2773u32),
                                    ::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")]
2769    fn lower_const_arg_anon(&self, anon: &AnonConst) -> Const<'tcx> {
2770        let tcx = self.tcx();
2771
2772        let expr = &tcx.hir_body(anon.body).value;
2773        debug!(?expr);
2774
2775        // FIXME(generic_const_parameter_types): We should use the proper generic args
2776        // here. It's only used as a hint for literals so doesn't matter too much to use the right
2777        // generic arguments, just weaker type inference.
2778        let ty = tcx.type_of(anon.def_id).instantiate_identity();
2779
2780        match self.try_lower_anon_const_lit(ty, expr) {
2781            Some(v) => v,
2782            None => ty::Const::new_unevaluated(
2783                tcx,
2784                ty::UnevaluatedConst {
2785                    def: anon.def_id.to_def_id(),
2786                    args: ty::GenericArgs::identity_for_item(tcx, anon.def_id.to_def_id()),
2787                },
2788            ),
2789        }
2790    }
2791
2792    #[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(2792u32),
                                    ::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 input = LitToConstInput { lit: *kind, ty, neg };
            tcx.at(span).lit_to_const(input)
        }
    }
}#[instrument(skip(self), level = "debug")]
2793    fn lower_const_arg_literal(
2794        &self,
2795        kind: &LitKind,
2796        neg: bool,
2797        ty: Ty<'tcx>,
2798        span: Span,
2799    ) -> Const<'tcx> {
2800        let tcx = self.tcx();
2801        let input = LitToConstInput { lit: *kind, ty, neg };
2802        tcx.at(span).lit_to_const(input)
2803    }
2804
2805    #[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(2805u32),
                                    ::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, neg: false }),
                    hir::ExprKind::Unary(hir::UnOp::Neg, expr) =>
                        match expr.kind {
                            hir::ExprKind::Lit(lit) =>
                                Some(LitToConstInput { lit: lit.node, ty, neg: true }),
                            _ => None,
                        },
                    _ => None,
                };
            lit_input.filter(|l|
                        !l.ty.has_aliases()).map(|l|
                    tcx.at(expr.span).lit_to_const(l))
        }
    }
}#[instrument(skip(self), level = "debug")]
2806    fn try_lower_anon_const_lit(
2807        &self,
2808        ty: Ty<'tcx>,
2809        expr: &'tcx hir::Expr<'tcx>,
2810    ) -> Option<Const<'tcx>> {
2811        let tcx = self.tcx();
2812
2813        // Unwrap a block, so that e.g. `{ 1 }` is recognised as a literal. This makes the
2814        // performance optimisation of directly lowering anon consts occur more often.
2815        let expr = match &expr.kind {
2816            hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2817                block.expr.as_ref().unwrap()
2818            }
2819            _ => expr,
2820        };
2821
2822        let lit_input = match expr.kind {
2823            hir::ExprKind::Lit(lit) => Some(LitToConstInput { lit: lit.node, ty, neg: false }),
2824            hir::ExprKind::Unary(hir::UnOp::Neg, expr) => match expr.kind {
2825                hir::ExprKind::Lit(lit) => Some(LitToConstInput { lit: lit.node, ty, neg: true }),
2826                _ => None,
2827            },
2828            _ => None,
2829        };
2830
2831        lit_input
2832            // Allow the `ty` to be an alias type, though we cannot handle it here, we just go through
2833            // the more expensive anon const code path.
2834            .filter(|l| !l.ty.has_aliases())
2835            .map(|l| tcx.at(expr.span).lit_to_const(l))
2836    }
2837
2838    fn require_type_const_attribute(
2839        &self,
2840        def_id: DefId,
2841        span: Span,
2842    ) -> Result<(), ErrorGuaranteed> {
2843        let tcx = self.tcx();
2844        if tcx.is_type_const(def_id) {
2845            Ok(())
2846        } else {
2847            let mut err = self
2848                .dcx()
2849                .struct_span_err(span, "use of `const` in the type system without `#[type_const]`");
2850            if def_id.is_local() {
2851                let name = tcx.def_path_str(def_id);
2852                err.span_suggestion(
2853                    tcx.def_span(def_id).shrink_to_lo(),
2854                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("add `#[type_const]` attribute to `{0}`",
                name))
    })format!("add `#[type_const]` attribute to `{name}`"),
2855                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#[type_const]\n"))
    })format!("#[type_const]\n"),
2856                    Applicability::MaybeIncorrect,
2857                );
2858            } else {
2859                err.note("only consts marked with `#[type_const]` may be used in types");
2860            }
2861            Err(err.emit())
2862        }
2863    }
2864
2865    fn lower_delegation_ty(&self, idx: hir::InferDelegationKind) -> Ty<'tcx> {
2866        let delegation_sig = self.tcx().inherit_sig_for_delegation_item(self.item_def_id());
2867        match idx {
2868            hir::InferDelegationKind::Input(idx) => delegation_sig[idx],
2869            hir::InferDelegationKind::Output => *delegation_sig.last().unwrap(),
2870        }
2871    }
2872
2873    /// Lower a type from the HIR to our internal notion of a type.
2874    x;#[instrument(level = "debug", skip(self), ret)]
2875    pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
2876        let tcx = self.tcx();
2877
2878        let result_ty = match &hir_ty.kind {
2879            hir::TyKind::InferDelegation(_, idx) => self.lower_delegation_ty(*idx),
2880            hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)),
2881            hir::TyKind::Ptr(mt) => Ty::new_ptr(tcx, self.lower_ty(mt.ty), mt.mutbl),
2882            hir::TyKind::Ref(region, mt) => {
2883                let r = self.lower_lifetime(region, RegionInferReason::Reference);
2884                debug!(?r);
2885                let t = self.lower_ty(mt.ty);
2886                Ty::new_ref(tcx, r, t, mt.mutbl)
2887            }
2888            hir::TyKind::Never => tcx.types.never,
2889            hir::TyKind::Tup(fields) => {
2890                Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
2891            }
2892            hir::TyKind::FnPtr(bf) => {
2893                check_c_variadic_abi(tcx, bf.decl, bf.abi, hir_ty.span);
2894
2895                Ty::new_fn_ptr(
2896                    tcx,
2897                    self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)),
2898                )
2899            }
2900            hir::TyKind::UnsafeBinder(binder) => Ty::new_unsafe_binder(
2901                tcx,
2902                ty::Binder::bind_with_vars(
2903                    self.lower_ty(binder.inner_ty),
2904                    tcx.late_bound_vars(hir_ty.hir_id),
2905                ),
2906            ),
2907            hir::TyKind::TraitObject(bounds, tagged_ptr) => {
2908                let lifetime = tagged_ptr.pointer();
2909                let syntax = tagged_ptr.tag();
2910                self.lower_trait_object_ty(hir_ty.span, hir_ty.hir_id, bounds, lifetime, syntax)
2911            }
2912            // If we encounter a fully qualified path with RTN generics, then it must have
2913            // *not* gone through `lower_ty_maybe_return_type_notation`, and therefore
2914            // it's certainly in an illegal position.
2915            hir::TyKind::Path(hir::QPath::Resolved(_, path))
2916                if path.segments.last().and_then(|segment| segment.args).is_some_and(|args| {
2917                    matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
2918                }) =>
2919            {
2920                let guar = self.dcx().emit_err(BadReturnTypeNotation { span: hir_ty.span });
2921                Ty::new_error(tcx, guar)
2922            }
2923            hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2924                debug!(?maybe_qself, ?path);
2925                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2926                self.lower_resolved_ty_path(opt_self_ty, path, hir_ty.hir_id, PermitVariants::No)
2927            }
2928            &hir::TyKind::OpaqueDef(opaque_ty) => {
2929                // If this is an RPITIT and we are using the new RPITIT lowering scheme, we
2930                // generate the def_id of an associated type for the trait and return as
2931                // type a projection.
2932                let in_trait = match opaque_ty.origin {
2933                    hir::OpaqueTyOrigin::FnReturn {
2934                        parent,
2935                        in_trait_or_impl: Some(hir::RpitContext::Trait),
2936                        ..
2937                    }
2938                    | hir::OpaqueTyOrigin::AsyncFn {
2939                        parent,
2940                        in_trait_or_impl: Some(hir::RpitContext::Trait),
2941                        ..
2942                    } => Some(parent),
2943                    hir::OpaqueTyOrigin::FnReturn {
2944                        in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
2945                        ..
2946                    }
2947                    | hir::OpaqueTyOrigin::AsyncFn {
2948                        in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
2949                        ..
2950                    }
2951                    | hir::OpaqueTyOrigin::TyAlias { .. } => None,
2952                };
2953
2954                self.lower_opaque_ty(opaque_ty.def_id, in_trait)
2955            }
2956            hir::TyKind::TraitAscription(hir_bounds) => {
2957                // Impl trait in bindings lower as an infer var with additional
2958                // set of type bounds.
2959                let self_ty = self.ty_infer(None, hir_ty.span);
2960                let mut bounds = Vec::new();
2961                self.lower_bounds(
2962                    self_ty,
2963                    hir_bounds.iter(),
2964                    &mut bounds,
2965                    ty::List::empty(),
2966                    PredicateFilter::All,
2967                    OverlappingAsssocItemConstraints::Allowed,
2968                );
2969                self.add_implicit_sizedness_bounds(
2970                    &mut bounds,
2971                    self_ty,
2972                    hir_bounds,
2973                    ImpliedBoundsContext::AssociatedTypeOrImplTrait,
2974                    hir_ty.span,
2975                );
2976                self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span);
2977                self_ty
2978            }
2979            // If we encounter a type relative path with RTN generics, then it must have
2980            // *not* gone through `lower_ty_maybe_return_type_notation`, and therefore
2981            // it's certainly in an illegal position.
2982            hir::TyKind::Path(hir::QPath::TypeRelative(_, segment))
2983                if segment.args.is_some_and(|args| {
2984                    matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
2985                }) =>
2986            {
2987                let guar = self.dcx().emit_err(BadReturnTypeNotation { span: hir_ty.span });
2988                Ty::new_error(tcx, guar)
2989            }
2990            hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2991                debug!(?hir_self_ty, ?segment);
2992                let self_ty = self.lower_ty(hir_self_ty);
2993                self.lower_type_relative_ty_path(
2994                    self_ty,
2995                    hir_self_ty,
2996                    segment,
2997                    hir_ty.hir_id,
2998                    hir_ty.span,
2999                    PermitVariants::No,
3000                )
3001                .map(|(ty, _, _)| ty)
3002                .unwrap_or_else(|guar| Ty::new_error(tcx, guar))
3003            }
3004            hir::TyKind::Array(ty, length) => {
3005                let length = self.lower_const_arg(length, tcx.types.usize);
3006                Ty::new_array_with_const_len(tcx, self.lower_ty(ty), length)
3007            }
3008            hir::TyKind::Infer(()) => {
3009                // Infer also appears as the type of arguments or return
3010                // values in an ExprKind::Closure, or as
3011                // the type of local variables. Both of these cases are
3012                // handled specially and will not descend into this routine.
3013                self.ty_infer(None, hir_ty.span)
3014            }
3015            hir::TyKind::Pat(ty, pat) => {
3016                let ty_span = ty.span;
3017                let ty = self.lower_ty(ty);
3018                let pat_ty = match self.lower_pat_ty_pat(ty, ty_span, pat) {
3019                    Ok(kind) => Ty::new_pat(tcx, ty, tcx.mk_pat(kind)),
3020                    Err(guar) => Ty::new_error(tcx, guar),
3021                };
3022                self.record_ty(pat.hir_id, ty, pat.span);
3023                pat_ty
3024            }
3025            hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar),
3026        };
3027
3028        self.record_ty(hir_ty.hir_id, result_ty, hir_ty.span);
3029        result_ty
3030    }
3031
3032    fn lower_pat_ty_pat(
3033        &self,
3034        ty: Ty<'tcx>,
3035        ty_span: Span,
3036        pat: &hir::TyPat<'tcx>,
3037    ) -> Result<ty::PatternKind<'tcx>, ErrorGuaranteed> {
3038        let tcx = self.tcx();
3039        match pat.kind {
3040            hir::TyPatKind::Range(start, end) => {
3041                match ty.kind() {
3042                    // Keep this list of types in sync with the list of types that
3043                    // the `RangePattern` trait is implemented for.
3044                    ty::Int(_) | ty::Uint(_) | ty::Char => {
3045                        let start = self.lower_const_arg(start, ty);
3046                        let end = self.lower_const_arg(end, ty);
3047                        Ok(ty::PatternKind::Range { start, end })
3048                    }
3049                    _ => Err(self
3050                        .dcx()
3051                        .span_delayed_bug(ty_span, "invalid base type for range pattern")),
3052                }
3053            }
3054            hir::TyPatKind::NotNull => Ok(ty::PatternKind::NotNull),
3055            hir::TyPatKind::Or(patterns) => {
3056                self.tcx()
3057                    .mk_patterns_from_iter(patterns.iter().map(|pat| {
3058                        self.lower_pat_ty_pat(ty, ty_span, pat).map(|pat| tcx.mk_pat(pat))
3059                    }))
3060                    .map(ty::PatternKind::Or)
3061            }
3062            hir::TyPatKind::Err(e) => Err(e),
3063        }
3064    }
3065
3066    /// Lower an opaque type (i.e., an existential impl-Trait type) from the HIR.
3067    x;#[instrument(level = "debug", skip(self), ret)]
3068    fn lower_opaque_ty(&self, def_id: LocalDefId, in_trait: Option<LocalDefId>) -> Ty<'tcx> {
3069        let tcx = self.tcx();
3070
3071        let lifetimes = tcx.opaque_captured_lifetimes(def_id);
3072        debug!(?lifetimes);
3073
3074        // If this is an RPITIT and we are using the new RPITIT lowering scheme,
3075        // do a linear search to map this to the synthetic associated type that
3076        // it will be lowered to.
3077        let def_id = if let Some(parent_def_id) = in_trait {
3078            *tcx.associated_types_for_impl_traits_in_associated_fn(parent_def_id.to_def_id())
3079                .iter()
3080                .find(|rpitit| match tcx.opt_rpitit_info(**rpitit) {
3081                    Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
3082                        opaque_def_id.expect_local() == def_id
3083                    }
3084                    _ => unreachable!(),
3085                })
3086                .unwrap()
3087        } else {
3088            def_id.to_def_id()
3089        };
3090
3091        let generics = tcx.generics_of(def_id);
3092        debug!(?generics);
3093
3094        // We use `generics.count() - lifetimes.len()` here instead of `generics.parent_count`
3095        // since return-position impl trait in trait squashes all of the generics from its source fn
3096        // into its own generics, so the opaque's "own" params isn't always just lifetimes.
3097        let offset = generics.count() - lifetimes.len();
3098
3099        let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| {
3100            if let Some(i) = (param.index as usize).checked_sub(offset) {
3101                let (lifetime, _) = lifetimes[i];
3102                // FIXME(mgca): should we be calling self.check_params_use_if_mcg here too?
3103                self.lower_resolved_lifetime(lifetime).into()
3104            } else {
3105                tcx.mk_param_from_def(param)
3106            }
3107        });
3108        debug!(?args);
3109
3110        if in_trait.is_some() {
3111            Ty::new_projection_from_args(tcx, def_id, args)
3112        } else {
3113            Ty::new_opaque(tcx, def_id, args)
3114        }
3115    }
3116
3117    /// Lower a function type from the HIR to our internal notion of a function signature.
3118    x;#[instrument(level = "debug", skip(self, hir_id, safety, abi, decl, generics, hir_ty), ret)]
3119    pub fn lower_fn_ty(
3120        &self,
3121        hir_id: HirId,
3122        safety: hir::Safety,
3123        abi: rustc_abi::ExternAbi,
3124        decl: &hir::FnDecl<'tcx>,
3125        generics: Option<&hir::Generics<'_>>,
3126        hir_ty: Option<&hir::Ty<'_>>,
3127    ) -> ty::PolyFnSig<'tcx> {
3128        let tcx = self.tcx();
3129        let bound_vars = tcx.late_bound_vars(hir_id);
3130        debug!(?bound_vars);
3131
3132        let (input_tys, output_ty) = self.lower_fn_sig(decl, generics, hir_id, hir_ty);
3133
3134        debug!(?output_ty);
3135
3136        let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, safety, abi);
3137        let fn_ptr_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3138
3139        if let hir::Node::Ty(hir::Ty { kind: hir::TyKind::FnPtr(fn_ptr_ty), span, .. }) =
3140            tcx.hir_node(hir_id)
3141        {
3142            check_abi(tcx, hir_id, *span, fn_ptr_ty.abi);
3143        }
3144
3145        // reject function types that violate cmse ABI requirements
3146        cmse::validate_cmse_abi(self.tcx(), self.dcx(), hir_id, abi, fn_ptr_ty);
3147
3148        if !fn_ptr_ty.references_error() {
3149            // Find any late-bound regions declared in return type that do
3150            // not appear in the arguments. These are not well-formed.
3151            //
3152            // Example:
3153            //     for<'a> fn() -> &'a str <-- 'a is bad
3154            //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
3155            let inputs = fn_ptr_ty.inputs();
3156            let late_bound_in_args =
3157                tcx.collect_constrained_late_bound_regions(inputs.map_bound(|i| i.to_owned()));
3158            let output = fn_ptr_ty.output();
3159            let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(output);
3160
3161            self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3162                struct_span_code_err!(
3163                    self.dcx(),
3164                    decl.output.span(),
3165                    E0581,
3166                    "return type references {}, which is not constrained by the fn input types",
3167                    br_name
3168                )
3169            });
3170        }
3171
3172        fn_ptr_ty
3173    }
3174
3175    /// Given a fn_hir_id for a impl function, suggest the type that is found on the
3176    /// corresponding function in the trait that the impl implements, if it exists.
3177    /// If arg_idx is Some, then it corresponds to an input type index, otherwise it
3178    /// corresponds to the return type.
3179    pub(super) fn suggest_trait_fn_ty_for_impl_fn_infer(
3180        &self,
3181        fn_hir_id: HirId,
3182        arg_idx: Option<usize>,
3183    ) -> Option<Ty<'tcx>> {
3184        let tcx = self.tcx();
3185        let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3186            tcx.hir_node(fn_hir_id)
3187        else {
3188            return None;
3189        };
3190        let i = tcx.parent_hir_node(fn_hir_id).expect_item().expect_impl();
3191
3192        let trait_ref = self.lower_impl_trait_ref(&i.of_trait?.trait_ref, self.lower_ty(i.self_ty));
3193
3194        let assoc = tcx.associated_items(trait_ref.def_id).find_by_ident_and_kind(
3195            tcx,
3196            *ident,
3197            ty::AssocTag::Fn,
3198            trait_ref.def_id,
3199        )?;
3200
3201        let fn_sig = tcx.fn_sig(assoc.def_id).instantiate(
3202            tcx,
3203            trait_ref.args.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3204        );
3205        let fn_sig = tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), fn_sig);
3206
3207        Some(if let Some(arg_idx) = arg_idx {
3208            *fn_sig.inputs().get(arg_idx)?
3209        } else {
3210            fn_sig.output()
3211        })
3212    }
3213
3214    #[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(3214u32),
                                    ::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))]
3215    fn validate_late_bound_regions<'cx>(
3216        &'cx self,
3217        constrained_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3218        referenced_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3219        generate_err: impl Fn(&str) -> Diag<'cx>,
3220    ) {
3221        for br in referenced_regions.difference(&constrained_regions) {
3222            let br_name = if let Some(name) = br.get_name(self.tcx()) {
3223                format!("lifetime `{name}`")
3224            } else {
3225                "an anonymous lifetime".to_string()
3226            };
3227
3228            let mut err = generate_err(&br_name);
3229
3230            if !br.is_named(self.tcx()) {
3231                // The only way for an anonymous lifetime to wind up
3232                // in the return type but **also** be unconstrained is
3233                // if it only appears in "associated types" in the
3234                // input. See #47511 and #62200 for examples. In this case,
3235                // though we can easily give a hint that ought to be
3236                // relevant.
3237                err.note(
3238                    "lifetimes appearing in an associated or opaque type are not considered constrained",
3239                );
3240                err.note("consider introducing a named lifetime parameter");
3241            }
3242
3243            err.emit();
3244        }
3245    }
3246
3247    /// Given the bounds on an object, determines what single region bound (if any) we can
3248    /// use to summarize this type.
3249    ///
3250    /// The basic idea is that we will use the bound the user
3251    /// provided, if they provided one, and otherwise search the supertypes of trait bounds
3252    /// for region bounds. It may be that we can derive no bound at all, in which case
3253    /// we return `None`.
3254    x;#[instrument(level = "debug", skip(self, span), ret)]
3255    fn compute_object_lifetime_bound(
3256        &self,
3257        span: Span,
3258        existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3259    ) -> Option<ty::Region<'tcx>> // if None, use the default
3260    {
3261        let tcx = self.tcx();
3262
3263        // No explicit region bound specified. Therefore, examine trait
3264        // bounds and see if we can derive region bounds from those.
3265        let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3266
3267        // If there are no derived region bounds, then report back that we
3268        // can find no region bound. The caller will use the default.
3269        if derived_region_bounds.is_empty() {
3270            return None;
3271        }
3272
3273        // If any of the derived region bounds are 'static, that is always
3274        // the best choice.
3275        if derived_region_bounds.iter().any(|r| r.is_static()) {
3276            return Some(tcx.lifetimes.re_static);
3277        }
3278
3279        // Determine whether there is exactly one unique region in the set
3280        // of derived region bounds. If so, use that. Otherwise, report an
3281        // error.
3282        let r = derived_region_bounds[0];
3283        if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3284            self.dcx().emit_err(AmbiguousLifetimeBound { span });
3285        }
3286        Some(r)
3287    }
3288
3289    fn construct_const_ctor_value(
3290        &self,
3291        ctor_def_id: DefId,
3292        ctor_of: CtorOf,
3293        args: GenericArgsRef<'tcx>,
3294    ) -> Const<'tcx> {
3295        let tcx = self.tcx();
3296        let parent_did = tcx.parent(ctor_def_id);
3297
3298        let adt_def = tcx.adt_def(match ctor_of {
3299            CtorOf::Variant => tcx.parent(parent_did),
3300            CtorOf::Struct => parent_did,
3301        });
3302
3303        let variant_idx = adt_def.variant_index_with_id(parent_did);
3304
3305        let valtree = if adt_def.is_enum() {
3306            let discr = ty::ValTree::from_scalar_int(tcx, variant_idx.as_u32().into());
3307            ty::ValTree::from_branches(tcx, [ty::Const::new_value(tcx, discr, tcx.types.u32)])
3308        } else {
3309            ty::ValTree::zst(tcx)
3310        };
3311
3312        let adt_ty = Ty::new_adt(tcx, adt_def, args);
3313        ty::Const::new_value(tcx, valtree, adt_ty)
3314    }
3315}