Skip to main content

rustc_hir_analysis/hir_ty_lowering/
mod.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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