Skip to main content

rustc_hir_analysis/hir_ty_lowering/
mod.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Const<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            let ty = if !ty.has_infer() { Some(ty) } else { None };
            if let LitKind::Err(guar) = *kind {
                return ty::Const::new_error(tcx, guar);
            }
            let input = LitToConstInput { lit: *kind, ty, neg };
            match tcx.at(span).lit_to_const(input) {
                Some(value) =>
                    ty::Const::new_value(tcx, value.valtree, value.ty),
                None => {
                    let e =
                        tcx.dcx().span_err(span,
                            "type annotations needed for the literal");
                    ty::Const::new_error(tcx, e)
                }
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
2896    fn lower_const_arg_literal(
2897        &self,
2898        kind: &LitKind,
2899        neg: bool,
2900        ty: Ty<'tcx>,
2901        span: Span,
2902    ) -> Const<'tcx> {
2903        let tcx = self.tcx();
2904
2905        let ty = if !ty.has_infer() { Some(ty) } else { None };
2906
2907        if let LitKind::Err(guar) = *kind {
2908            return ty::Const::new_error(tcx, guar);
2909        }
2910        let input = LitToConstInput { lit: *kind, ty, neg };
2911        match tcx.at(span).lit_to_const(input) {
2912            Some(value) => ty::Const::new_value(tcx, value.valtree, value.ty),
2913            None => {
2914                let e = tcx.dcx().span_err(span, "type annotations needed for the literal");
2915                ty::Const::new_error(tcx, e)
2916            }
2917        }
2918    }
2919
2920    #[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(2920u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
                                    ::tracing_core::field::FieldSet::new(&["ty", "expr"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<Const<'tcx>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx();
            let expr =
                match &expr.kind {
                    hir::ExprKind::Block(block, _) if
                        block.stmts.is_empty() && block.expr.is_some() => {
                        block.expr.as_ref().unwrap()
                    }
                    _ => expr,
                };
            let lit_input =
                match expr.kind {
                    hir::ExprKind::Lit(lit) => {
                        Some(LitToConstInput {
                                lit: lit.node,
                                ty: Some(ty),
                                neg: false,
                            })
                    }
                    hir::ExprKind::Unary(hir::UnOp::Neg, expr) =>
                        match expr.kind {
                            hir::ExprKind::Lit(lit) => {
                                Some(LitToConstInput {
                                        lit: lit.node,
                                        ty: Some(ty),
                                        neg: true,
                                    })
                            }
                            _ => None,
                        },
                    _ => None,
                };
            lit_input.and_then(|l|
                    {
                        if const_lit_matches_ty(tcx, &l.lit, ty, l.neg) {
                            tcx.at(expr.span).lit_to_const(l).map(|value|
                                    ty::Const::new_value(tcx, value.valtree, value.ty))
                        } else { None }
                    })
        }
    }
}#[instrument(skip(self), level = "debug")]
2921    fn try_lower_anon_const_lit(
2922        &self,
2923        ty: Ty<'tcx>,
2924        expr: &'tcx hir::Expr<'tcx>,
2925    ) -> Option<Const<'tcx>> {
2926        let tcx = self.tcx();
2927
2928        // Unwrap a block, so that e.g. `{ 1 }` is recognised as a literal. This makes the
2929        // performance optimisation of directly lowering anon consts occur more often.
2930        let expr = match &expr.kind {
2931            hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2932                block.expr.as_ref().unwrap()
2933            }
2934            _ => expr,
2935        };
2936
2937        let lit_input = match expr.kind {
2938            hir::ExprKind::Lit(lit) => {
2939                Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: false })
2940            }
2941            hir::ExprKind::Unary(hir::UnOp::Neg, expr) => match expr.kind {
2942                hir::ExprKind::Lit(lit) => {
2943                    Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: true })
2944                }
2945                _ => None,
2946            },
2947            _ => None,
2948        };
2949
2950        lit_input.and_then(|l| {
2951            if const_lit_matches_ty(tcx, &l.lit, ty, l.neg) {
2952                tcx.at(expr.span)
2953                    .lit_to_const(l)
2954                    .map(|value| ty::Const::new_value(tcx, value.valtree, value.ty))
2955            } else {
2956                None
2957            }
2958        })
2959    }
2960
2961    fn require_type_const_attribute(
2962        &self,
2963        def_id: DefId,
2964        span: Span,
2965    ) -> Result<(), ErrorGuaranteed> {
2966        let tcx = self.tcx();
2967        if tcx.is_type_const(def_id) {
2968            Ok(())
2969        } else {
2970            let mut err = self.dcx().struct_span_err(
2971                span,
2972                "use of `const` in the type system not defined as `type const`",
2973            );
2974            if def_id.is_local() {
2975                let name = tcx.def_path_str(def_id);
2976                err.span_suggestion_verbose(
2977                    tcx.def_span(def_id).shrink_to_lo(),
2978                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("add `type` before `const` for `{0}`",
                name))
    })format!("add `type` before `const` for `{name}`"),
2979                    ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("type ")) })format!("type "),
2980                    Applicability::MaybeIncorrect,
2981                );
2982            } else {
2983                err.note("only consts marked defined as `type const` may be used in types");
2984            }
2985            Err(err.emit())
2986        }
2987    }
2988
2989    fn lower_delegation_ty(&self, infer: hir::InferDelegation<'tcx>) -> Ty<'tcx> {
2990        match infer {
2991            hir::InferDelegation::DefId(def_id) => {
2992                self.tcx().type_of(def_id).instantiate_identity()
2993            }
2994            rustc_hir::InferDelegation::Sig(_, idx) => {
2995                let delegation_sig = self.tcx().inherit_sig_for_delegation_item(self.item_def_id());
2996
2997                match idx {
2998                    hir::InferDelegationSig::Input(idx) => delegation_sig[idx],
2999                    hir::InferDelegationSig::Output { .. } => *delegation_sig.last().unwrap(),
3000                }
3001            }
3002        }
3003    }
3004
3005    /// Lower a type from the HIR to our internal notion of a type.
3006    x;#[instrument(level = "debug", skip(self), ret)]
3007    pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
3008        let tcx = self.tcx();
3009
3010        let result_ty = match &hir_ty.kind {
3011            hir::TyKind::InferDelegation(infer) => self.lower_delegation_ty(*infer),
3012            hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)),
3013            hir::TyKind::Ptr(mt) => Ty::new_ptr(tcx, self.lower_ty(mt.ty), mt.mutbl),
3014            hir::TyKind::Ref(region, mt) => {
3015                let r = self.lower_lifetime(region, RegionInferReason::Reference);
3016                debug!(?r);
3017                let t = self.lower_ty(mt.ty);
3018                Ty::new_ref(tcx, r, t, mt.mutbl)
3019            }
3020            hir::TyKind::Never => tcx.types.never,
3021            hir::TyKind::Tup(fields) => {
3022                Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
3023            }
3024            hir::TyKind::FnPtr(bf) => {
3025                check_c_variadic_abi(tcx, bf.decl, bf.abi, hir_ty.span);
3026
3027                Ty::new_fn_ptr(
3028                    tcx,
3029                    self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)),
3030                )
3031            }
3032            hir::TyKind::UnsafeBinder(binder) => Ty::new_unsafe_binder(
3033                tcx,
3034                ty::Binder::bind_with_vars(
3035                    self.lower_ty(binder.inner_ty),
3036                    tcx.late_bound_vars(hir_ty.hir_id),
3037                ),
3038            ),
3039            hir::TyKind::TraitObject(bounds, tagged_ptr) => {
3040                let lifetime = tagged_ptr.pointer();
3041                let syntax = tagged_ptr.tag();
3042                self.lower_trait_object_ty(hir_ty.span, hir_ty.hir_id, bounds, lifetime, syntax)
3043            }
3044            // If we encounter a fully qualified path with RTN generics, then it must have
3045            // *not* gone through `lower_ty_maybe_return_type_notation`, and therefore
3046            // it's certainly in an illegal position.
3047            hir::TyKind::Path(hir::QPath::Resolved(_, path))
3048                if path.segments.last().and_then(|segment| segment.args).is_some_and(|args| {
3049                    matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3050                }) =>
3051            {
3052                let guar = self
3053                    .dcx()
3054                    .emit_err(BadReturnTypeNotation { span: hir_ty.span, suggestion: None });
3055                Ty::new_error(tcx, guar)
3056            }
3057            hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
3058                debug!(?maybe_qself, ?path);
3059                let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
3060                self.lower_resolved_ty_path(opt_self_ty, path, hir_ty.hir_id, PermitVariants::No)
3061            }
3062            &hir::TyKind::OpaqueDef(opaque_ty) => {
3063                // If this is an RPITIT and we are using the new RPITIT lowering scheme, we
3064                // generate the def_id of an associated type for the trait and return as
3065                // type a projection.
3066                let in_trait = match opaque_ty.origin {
3067                    hir::OpaqueTyOrigin::FnReturn {
3068                        parent,
3069                        in_trait_or_impl: Some(hir::RpitContext::Trait),
3070                        ..
3071                    }
3072                    | hir::OpaqueTyOrigin::AsyncFn {
3073                        parent,
3074                        in_trait_or_impl: Some(hir::RpitContext::Trait),
3075                        ..
3076                    } => Some(parent),
3077                    hir::OpaqueTyOrigin::FnReturn {
3078                        in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3079                        ..
3080                    }
3081                    | hir::OpaqueTyOrigin::AsyncFn {
3082                        in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3083                        ..
3084                    }
3085                    | hir::OpaqueTyOrigin::TyAlias { .. } => None,
3086                };
3087
3088                self.lower_opaque_ty(opaque_ty.def_id, in_trait)
3089            }
3090            hir::TyKind::TraitAscription(hir_bounds) => {
3091                // Impl trait in bindings lower as an infer var with additional
3092                // set of type bounds.
3093                let self_ty = self.ty_infer(None, hir_ty.span);
3094                let mut bounds = Vec::new();
3095                self.lower_bounds(
3096                    self_ty,
3097                    hir_bounds.iter(),
3098                    &mut bounds,
3099                    ty::List::empty(),
3100                    PredicateFilter::All,
3101                    OverlappingAsssocItemConstraints::Allowed,
3102                );
3103                self.add_implicit_sizedness_bounds(
3104                    &mut bounds,
3105                    self_ty,
3106                    hir_bounds,
3107                    ImpliedBoundsContext::AssociatedTypeOrImplTrait,
3108                    hir_ty.span,
3109                );
3110                self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span);
3111                self_ty
3112            }
3113            // If we encounter a type relative path with RTN generics, then it must have
3114            // *not* gone through `lower_ty_maybe_return_type_notation`, and therefore
3115            // it's certainly in an illegal position.
3116            hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment))
3117                if segment.args.is_some_and(|args| {
3118                    matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3119                }) =>
3120            {
3121                let guar = if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3122                    && let None = stmt.init
3123                    && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3124                        hir_self_ty.kind
3125                    && let Res::Def(DefKind::Enum | DefKind::Struct | DefKind::Union, def_id) =
3126                        self_ty_path.res
3127                    && let Some(_) = tcx
3128                        .inherent_impls(def_id)
3129                        .iter()
3130                        .flat_map(|imp| {
3131                            tcx.associated_items(*imp).filter_by_name_unhygienic(segment.ident.name)
3132                        })
3133                        .filter(|assoc| {
3134                            matches!(assoc.kind, ty::AssocKind::Fn { has_self: false, .. })
3135                        })
3136                        .next()
3137                {
3138                    // `let x: S::new(valid_in_ty_ctxt);` -> `let x = S::new(valid_in_ty_ctxt);`
3139                    let err = tcx
3140                        .dcx()
3141                        .struct_span_err(
3142                            hir_ty.span,
3143                            "expected type, found associated function call",
3144                        )
3145                        .with_span_suggestion_verbose(
3146                            stmt.pat.span.between(hir_ty.span),
3147                            "use `=` if you meant to assign",
3148                            " = ".to_string(),
3149                            Applicability::MaybeIncorrect,
3150                        );
3151                    self.dcx().try_steal_replace_and_emit_err(
3152                        hir_ty.span,
3153                        StashKey::ReturnTypeNotation,
3154                        err,
3155                    )
3156                } else if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3157                    && let None = stmt.init
3158                    && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3159                        hir_self_ty.kind
3160                    && let Res::PrimTy(_) = self_ty_path.res
3161                    && self.dcx().has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3162                {
3163                    // `let x: i32::something(valid_in_ty_ctxt);` -> `let x = i32::something(valid_in_ty_ctxt);`
3164                    // FIXME: Check that `something` is a valid function in `i32`.
3165                    let err = tcx
3166                        .dcx()
3167                        .struct_span_err(
3168                            hir_ty.span,
3169                            "expected type, found associated function call",
3170                        )
3171                        .with_span_suggestion_verbose(
3172                            stmt.pat.span.between(hir_ty.span),
3173                            "use `=` if you meant to assign",
3174                            " = ".to_string(),
3175                            Applicability::MaybeIncorrect,
3176                        );
3177                    self.dcx().try_steal_replace_and_emit_err(
3178                        hir_ty.span,
3179                        StashKey::ReturnTypeNotation,
3180                        err,
3181                    )
3182                } else {
3183                    let suggestion = if self
3184                        .dcx()
3185                        .has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3186                    {
3187                        // We already created a diagnostic complaining that `foo(bar)` is wrong and
3188                        // should have been `foo(..)`. Instead, emit only the current error and
3189                        // include that prior suggestion. Changes are that the problems go further,
3190                        // but keep the suggestion just in case. Either way, we want a single error
3191                        // instead of two.
3192                        Some(segment.ident.span.shrink_to_hi().with_hi(hir_ty.span.hi()))
3193                    } else {
3194                        None
3195                    };
3196                    let err = self
3197                        .dcx()
3198                        .create_err(BadReturnTypeNotation { span: hir_ty.span, suggestion });
3199                    self.dcx().try_steal_replace_and_emit_err(
3200                        hir_ty.span,
3201                        StashKey::ReturnTypeNotation,
3202                        err,
3203                    )
3204                };
3205                Ty::new_error(tcx, guar)
3206            }
3207            hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
3208                debug!(?hir_self_ty, ?segment);
3209                let self_ty = self.lower_ty(hir_self_ty);
3210                self.lower_type_relative_ty_path(
3211                    self_ty,
3212                    hir_self_ty,
3213                    segment,
3214                    hir_ty.hir_id,
3215                    hir_ty.span,
3216                    PermitVariants::No,
3217                )
3218                .map(|(ty, _, _)| ty)
3219                .unwrap_or_else(|guar| Ty::new_error(tcx, guar))
3220            }
3221            hir::TyKind::Array(ty, length) => {
3222                let length = self.lower_const_arg(length, tcx.types.usize);
3223                Ty::new_array_with_const_len(tcx, self.lower_ty(ty), length)
3224            }
3225            hir::TyKind::Infer(()) => {
3226                // Infer also appears as the type of arguments or return
3227                // values in an ExprKind::Closure, or as
3228                // the type of local variables. Both of these cases are
3229                // handled specially and will not descend into this routine.
3230                self.ty_infer(None, hir_ty.span)
3231            }
3232            hir::TyKind::Pat(ty, pat) => {
3233                let ty_span = ty.span;
3234                let ty = self.lower_ty(ty);
3235                let pat_ty = match self.lower_pat_ty_pat(ty, ty_span, pat) {
3236                    Ok(kind) => Ty::new_pat(tcx, ty, tcx.mk_pat(kind)),
3237                    Err(guar) => Ty::new_error(tcx, guar),
3238                };
3239                self.record_ty(pat.hir_id, ty, pat.span);
3240                pat_ty
3241            }
3242            hir::TyKind::FieldOf(ty, hir::TyFieldPath { variant, field }) => self.lower_field_of(
3243                self.lower_ty(ty),
3244                self.item_def_id(),
3245                ty.span,
3246                hir_ty.hir_id,
3247                *variant,
3248                *field,
3249            ),
3250            hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar),
3251        };
3252
3253        self.record_ty(hir_ty.hir_id, result_ty, hir_ty.span);
3254        result_ty
3255    }
3256
3257    fn lower_pat_ty_pat(
3258        &self,
3259        ty: Ty<'tcx>,
3260        ty_span: Span,
3261        pat: &hir::TyPat<'tcx>,
3262    ) -> Result<ty::PatternKind<'tcx>, ErrorGuaranteed> {
3263        let tcx = self.tcx();
3264        match pat.kind {
3265            hir::TyPatKind::Range(start, end) => {
3266                match ty.kind() {
3267                    // Keep this list of types in sync with the list of types that
3268                    // the `RangePattern` trait is implemented for.
3269                    ty::Int(_) | ty::Uint(_) | ty::Char => {
3270                        let start = self.lower_const_arg(start, ty);
3271                        let end = self.lower_const_arg(end, ty);
3272                        Ok(ty::PatternKind::Range { start, end })
3273                    }
3274                    _ => Err(self
3275                        .dcx()
3276                        .span_delayed_bug(ty_span, "invalid base type for range pattern")),
3277                }
3278            }
3279            hir::TyPatKind::NotNull => Ok(ty::PatternKind::NotNull),
3280            hir::TyPatKind::Or(patterns) => {
3281                self.tcx()
3282                    .mk_patterns_from_iter(patterns.iter().map(|pat| {
3283                        self.lower_pat_ty_pat(ty, ty_span, pat).map(|pat| tcx.mk_pat(pat))
3284                    }))
3285                    .map(ty::PatternKind::Or)
3286            }
3287            hir::TyPatKind::Err(e) => Err(e),
3288        }
3289    }
3290
3291    fn lower_field_of(
3292        &self,
3293        ty: Ty<'tcx>,
3294        item_def_id: LocalDefId,
3295        ty_span: Span,
3296        hir_id: HirId,
3297        variant: Option<Ident>,
3298        field: Ident,
3299    ) -> Ty<'tcx> {
3300        let dcx = self.dcx();
3301        let tcx = self.tcx();
3302        match ty.kind() {
3303            ty::Adt(def, _) => {
3304                let base_did = def.did();
3305                let kind_name = tcx.def_descr(base_did);
3306                let (variant_idx, variant) = if def.is_enum() {
3307                    let Some(variant) = variant else {
3308                        let err = dcx
3309                            .create_err(NoVariantNamed { span: field.span, ident: field, ty })
3310                            .with_span_help(
3311                                field.span.shrink_to_lo(),
3312                                "you might be missing a variant here: `Variant.`",
3313                            )
3314                            .emit();
3315                        return Ty::new_error(tcx, err);
3316                    };
3317
3318                    if let Some(res) = def
3319                        .variants()
3320                        .iter_enumerated()
3321                        .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == variant)
3322                    {
3323                        res
3324                    } else {
3325                        let err = dcx
3326                            .create_err(NoVariantNamed { span: variant.span, ident: variant, ty })
3327                            .emit();
3328                        return Ty::new_error(tcx, err);
3329                    }
3330                } else {
3331                    if let Some(variant) = variant {
3332                        let adt_path = tcx.def_path_str(base_did);
3333                        {
    dcx.struct_span_err(variant.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0} `{1}` does not have any variants",
                            kind_name, adt_path))
                })).with_code(E0609)
}struct_span_code_err!(
3334                            dcx,
3335                            variant.span,
3336                            E0609,
3337                            "{kind_name} `{adt_path}` does not have any variants",
3338                        )
3339                        .with_span_label(variant.span, "variant unknown")
3340                        .emit();
3341                    }
3342                    (FIRST_VARIANT, def.non_enum_variant())
3343                };
3344                let block = tcx.local_def_id_to_hir_id(item_def_id);
3345                let (ident, def_scope) = tcx.adjust_ident_and_get_scope(field, def.did(), block);
3346                if let Some((field_idx, field)) = variant
3347                    .fields
3348                    .iter_enumerated()
3349                    .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == ident)
3350                {
3351                    if field.vis.is_accessible_from(def_scope, tcx) {
3352                        tcx.check_stability(field.did, Some(hir_id), ident.span, None);
3353                    } else {
3354                        let adt_path = tcx.def_path_str(base_did);
3355                        {
    dcx.struct_span_err(ident.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("field `{0}` of {1} `{2}` is private",
                            ident, kind_name, adt_path))
                })).with_code(E0616)
}struct_span_code_err!(
3356                            dcx,
3357                            ident.span,
3358                            E0616,
3359                            "field `{ident}` of {kind_name} `{adt_path}` is private",
3360                        )
3361                        .with_span_label(ident.span, "private field")
3362                        .emit();
3363                    }
3364                    Ty::new_field_representing_type(tcx, ty, variant_idx, field_idx)
3365                } else {
3366                    let err =
3367                        dcx.create_err(NoFieldOnType { span: ident.span, field: ident, ty }).emit();
3368                    Ty::new_error(tcx, err)
3369                }
3370            }
3371            ty::Tuple(tys) => {
3372                let index = match field.as_str().parse::<usize>() {
3373                    Ok(idx) => idx,
3374                    Err(_) => {
3375                        let err =
3376                            dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3377                        return Ty::new_error(tcx, err);
3378                    }
3379                };
3380                if field.name != sym::integer(index) {
3381                    ::rustc_middle::util::bug::bug_fmt(format_args!("we parsed above, but now not equal?"));bug!("we parsed above, but now not equal?");
3382                }
3383                if tys.get(index).is_some() {
3384                    Ty::new_field_representing_type(tcx, ty, FIRST_VARIANT, index.into())
3385                } else {
3386                    let err = dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3387                    Ty::new_error(tcx, err)
3388                }
3389            }
3390            // FIXME(FRTs): support type aliases
3391            /*
3392            ty::Alias(AliasTyKind::Free, ty) => {
3393                return self.lower_field_of(
3394                    ty,
3395                    item_def_id,
3396                    ty_span,
3397                    hir_id,
3398                    variant,
3399                    field,
3400                );
3401            }*/
3402            ty::Alias(..) => Ty::new_error(
3403                tcx,
3404                dcx.span_err(ty_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("could not resolve fields of `{0}`",
                ty))
    })format!("could not resolve fields of `{ty}`")),
3405            ),
3406            ty::Error(err) => Ty::new_error(tcx, *err),
3407            ty::Bool
3408            | ty::Char
3409            | ty::Int(_)
3410            | ty::Uint(_)
3411            | ty::Float(_)
3412            | ty::Foreign(_)
3413            | ty::Str
3414            | ty::RawPtr(_, _)
3415            | ty::Ref(_, _, _)
3416            | ty::FnDef(_, _)
3417            | ty::FnPtr(_, _)
3418            | ty::UnsafeBinder(_)
3419            | ty::Dynamic(_, _)
3420            | ty::Closure(_, _)
3421            | ty::CoroutineClosure(_, _)
3422            | ty::Coroutine(_, _)
3423            | ty::CoroutineWitness(_, _)
3424            | ty::Never
3425            | ty::Param(_)
3426            | ty::Bound(_, _)
3427            | ty::Placeholder(_)
3428            | ty::Slice(..) => Ty::new_error(
3429                tcx,
3430                dcx.span_err(ty_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type `{0}` doesn\'t have fields",
                ty))
    })format!("type `{ty}` doesn't have fields")),
3431            ),
3432            ty::Infer(_) => Ty::new_error(
3433                tcx,
3434                dcx.span_err(ty_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot use `{0}` in this position",
                ty))
    })format!("cannot use `{ty}` in this position")),
3435            ),
3436            // FIXME(FRTs): support these types?
3437            ty::Array(..) | ty::Pat(..) => Ty::new_error(
3438                tcx,
3439                dcx.span_err(ty_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type `{0}` is not yet supported in `field_of!`",
                ty))
    })format!("type `{ty}` is not yet supported in `field_of!`")),
3440            ),
3441        }
3442    }
3443
3444    /// Lower an opaque type (i.e., an existential impl-Trait type) from the HIR.
3445    x;#[instrument(level = "debug", skip(self), ret)]
3446    fn lower_opaque_ty(&self, def_id: LocalDefId, in_trait: Option<LocalDefId>) -> Ty<'tcx> {
3447        let tcx = self.tcx();
3448
3449        let lifetimes = tcx.opaque_captured_lifetimes(def_id);
3450        debug!(?lifetimes);
3451
3452        // If this is an RPITIT and we are using the new RPITIT lowering scheme,
3453        // do a linear search to map this to the synthetic associated type that
3454        // it will be lowered to.
3455        let def_id = if let Some(parent_def_id) = in_trait {
3456            *tcx.associated_types_for_impl_traits_in_associated_fn(parent_def_id.to_def_id())
3457                .iter()
3458                .find(|rpitit| match tcx.opt_rpitit_info(**rpitit) {
3459                    Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
3460                        opaque_def_id.expect_local() == def_id
3461                    }
3462                    _ => unreachable!(),
3463                })
3464                .unwrap()
3465        } else {
3466            def_id.to_def_id()
3467        };
3468
3469        let generics = tcx.generics_of(def_id);
3470        debug!(?generics);
3471
3472        // We use `generics.count() - lifetimes.len()` here instead of `generics.parent_count`
3473        // since return-position impl trait in trait squashes all of the generics from its source fn
3474        // into its own generics, so the opaque's "own" params isn't always just lifetimes.
3475        let offset = generics.count() - lifetimes.len();
3476
3477        let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| {
3478            if let Some(i) = (param.index as usize).checked_sub(offset) {
3479                let (lifetime, _) = lifetimes[i];
3480                // FIXME(mgca): should we be calling self.check_params_use_if_mcg here too?
3481                self.lower_resolved_lifetime(lifetime).into()
3482            } else {
3483                tcx.mk_param_from_def(param)
3484            }
3485        });
3486        debug!(?args);
3487
3488        if in_trait.is_some() {
3489            Ty::new_projection_from_args(tcx, def_id, args)
3490        } else {
3491            Ty::new_opaque(tcx, def_id, args)
3492        }
3493    }
3494
3495    /// Lower a function type from the HIR to our internal notion of a function signature.
3496    x;#[instrument(level = "debug", skip(self, hir_id, safety, abi, decl, generics, hir_ty), ret)]
3497    pub fn lower_fn_ty(
3498        &self,
3499        hir_id: HirId,
3500        safety: hir::Safety,
3501        abi: rustc_abi::ExternAbi,
3502        decl: &hir::FnDecl<'tcx>,
3503        generics: Option<&hir::Generics<'_>>,
3504        hir_ty: Option<&hir::Ty<'_>>,
3505    ) -> ty::PolyFnSig<'tcx> {
3506        let tcx = self.tcx();
3507        let bound_vars = tcx.late_bound_vars(hir_id);
3508        debug!(?bound_vars);
3509
3510        let (input_tys, output_ty) = self.lower_fn_sig(decl, generics, hir_id, hir_ty);
3511
3512        debug!(?output_ty);
3513
3514        let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, safety, abi);
3515        let fn_ptr_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3516
3517        if let hir::Node::Ty(hir::Ty { kind: hir::TyKind::FnPtr(fn_ptr_ty), span, .. }) =
3518            tcx.hir_node(hir_id)
3519        {
3520            check_abi(tcx, hir_id, *span, fn_ptr_ty.abi);
3521        }
3522
3523        // reject function types that violate cmse ABI requirements
3524        cmse::validate_cmse_abi(self.tcx(), self.dcx(), hir_id, abi, fn_ptr_ty);
3525
3526        if !fn_ptr_ty.references_error() {
3527            // Find any late-bound regions declared in return type that do
3528            // not appear in the arguments. These are not well-formed.
3529            //
3530            // Example:
3531            //     for<'a> fn() -> &'a str <-- 'a is bad
3532            //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
3533            let inputs = fn_ptr_ty.inputs();
3534            let late_bound_in_args =
3535                tcx.collect_constrained_late_bound_regions(inputs.map_bound(|i| i.to_owned()));
3536            let output = fn_ptr_ty.output();
3537            let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(output);
3538
3539            self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3540                struct_span_code_err!(
3541                    self.dcx(),
3542                    decl.output.span(),
3543                    E0581,
3544                    "return type references {}, which is not constrained by the fn input types",
3545                    br_name
3546                )
3547            });
3548        }
3549
3550        fn_ptr_ty
3551    }
3552
3553    /// Given a fn_hir_id for a impl function, suggest the type that is found on the
3554    /// corresponding function in the trait that the impl implements, if it exists.
3555    /// If arg_idx is Some, then it corresponds to an input type index, otherwise it
3556    /// corresponds to the return type.
3557    pub(super) fn suggest_trait_fn_ty_for_impl_fn_infer(
3558        &self,
3559        fn_hir_id: HirId,
3560        arg_idx: Option<usize>,
3561    ) -> Option<Ty<'tcx>> {
3562        let tcx = self.tcx();
3563        let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3564            tcx.hir_node(fn_hir_id)
3565        else {
3566            return None;
3567        };
3568        let i = tcx.parent_hir_node(fn_hir_id).expect_item().expect_impl();
3569
3570        let trait_ref = self.lower_impl_trait_ref(&i.of_trait?.trait_ref, self.lower_ty(i.self_ty));
3571
3572        let assoc = tcx.associated_items(trait_ref.def_id).find_by_ident_and_kind(
3573            tcx,
3574            *ident,
3575            ty::AssocTag::Fn,
3576            trait_ref.def_id,
3577        )?;
3578
3579        let fn_sig = tcx.fn_sig(assoc.def_id).instantiate(
3580            tcx,
3581            trait_ref.args.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3582        );
3583        let fn_sig = tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), fn_sig);
3584
3585        Some(if let Some(arg_idx) = arg_idx {
3586            *fn_sig.inputs().get(arg_idx)?
3587        } else {
3588            fn_sig.output()
3589        })
3590    }
3591
3592    #[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(3592u32),
                                    ::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))]
3593    fn validate_late_bound_regions<'cx>(
3594        &'cx self,
3595        constrained_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3596        referenced_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3597        generate_err: impl Fn(&str) -> Diag<'cx>,
3598    ) {
3599        for br in referenced_regions.difference(&constrained_regions) {
3600            let br_name = if let Some(name) = br.get_name(self.tcx()) {
3601                format!("lifetime `{name}`")
3602            } else {
3603                "an anonymous lifetime".to_string()
3604            };
3605
3606            let mut err = generate_err(&br_name);
3607
3608            if !br.is_named(self.tcx()) {
3609                // The only way for an anonymous lifetime to wind up
3610                // in the return type but **also** be unconstrained is
3611                // if it only appears in "associated types" in the
3612                // input. See #47511 and #62200 for examples. In this case,
3613                // though we can easily give a hint that ought to be
3614                // relevant.
3615                err.note(
3616                    "lifetimes appearing in an associated or opaque type are not considered constrained",
3617                );
3618                err.note("consider introducing a named lifetime parameter");
3619            }
3620
3621            err.emit();
3622        }
3623    }
3624
3625    /// Given the bounds on an object, determines what single region bound (if any) we can
3626    /// use to summarize this type.
3627    ///
3628    /// The basic idea is that we will use the bound the user
3629    /// provided, if they provided one, and otherwise search the supertypes of trait bounds
3630    /// for region bounds. It may be that we can derive no bound at all, in which case
3631    /// we return `None`.
3632    x;#[instrument(level = "debug", skip(self, span), ret)]
3633    fn compute_object_lifetime_bound(
3634        &self,
3635        span: Span,
3636        existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3637    ) -> Option<ty::Region<'tcx>> // if None, use the default
3638    {
3639        let tcx = self.tcx();
3640
3641        // No explicit region bound specified. Therefore, examine trait
3642        // bounds and see if we can derive region bounds from those.
3643        let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3644
3645        // If there are no derived region bounds, then report back that we
3646        // can find no region bound. The caller will use the default.
3647        if derived_region_bounds.is_empty() {
3648            return None;
3649        }
3650
3651        // If any of the derived region bounds are 'static, that is always
3652        // the best choice.
3653        if derived_region_bounds.iter().any(|r| r.is_static()) {
3654            return Some(tcx.lifetimes.re_static);
3655        }
3656
3657        // Determine whether there is exactly one unique region in the set
3658        // of derived region bounds. If so, use that. Otherwise, report an
3659        // error.
3660        let r = derived_region_bounds[0];
3661        if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3662            self.dcx().emit_err(AmbiguousLifetimeBound { span });
3663        }
3664        Some(r)
3665    }
3666
3667    fn construct_const_ctor_value(
3668        &self,
3669        ctor_def_id: DefId,
3670        ctor_of: CtorOf,
3671        args: GenericArgsRef<'tcx>,
3672    ) -> Const<'tcx> {
3673        let tcx = self.tcx();
3674        let parent_did = tcx.parent(ctor_def_id);
3675
3676        let adt_def = tcx.adt_def(match ctor_of {
3677            CtorOf::Variant => tcx.parent(parent_did),
3678            CtorOf::Struct => parent_did,
3679        });
3680
3681        let variant_idx = adt_def.variant_index_with_id(parent_did);
3682
3683        let valtree = if adt_def.is_enum() {
3684            let discr = ty::ValTree::from_scalar_int(tcx, variant_idx.as_u32().into());
3685            ty::ValTree::from_branches(tcx, [ty::Const::new_value(tcx, discr, tcx.types.u32)])
3686        } else {
3687            ty::ValTree::zst(tcx)
3688        };
3689
3690        let adt_ty = Ty::new_adt(tcx, adt_def, args);
3691        ty::Const::new_value(tcx, valtree, adt_ty)
3692    }
3693}