Skip to main content

rustc_middle/ty/
sty.rs

1//! This module contains `TyKind` and its major components.
2
3#![allow(rustc::usage_of_ty_tykind)]
4
5use std::borrow::Cow;
6use std::debug_assert_matches;
7use std::ops::{ControlFlow, Range};
8
9use hir::def::{CtorKind, DefKind};
10use rustc_abi::{FIRST_VARIANT, FieldIdx, NumScalableVectors, ScalableElt, VariantIdx};
11use rustc_errors::{ErrorGuaranteed, MultiSpan};
12use rustc_hir as hir;
13use rustc_hir::attrs::lang_items::LangItem;
14use rustc_hir::def_id::DefId;
15use rustc_macros::{StableHash, TyDecodable, TyEncodable, TypeFoldable, extension};
16use rustc_span::{DUMMY_SP, Span, Symbol, kw, sym};
17use rustc_type_ir::TyKind::*;
18use rustc_type_ir::solve::SizedTraitKind;
19use rustc_type_ir::walk::TypeWalker;
20use rustc_type_ir::{
21    self as ir, BoundVar, CollectAndApply, MayBeErased, TypeVisitableExt, elaborate,
22};
23use tracing::instrument;
24use ty::util::IntTypeExt;
25
26use super::{AdtFlags, GenericParamDefKind};
27use crate::infer::canonical::Canonical;
28use crate::traits::ObligationCause;
29use crate::ty::InferTy::*;
30use crate::ty::{
31    self, AdtDef, Const, Discr, GenericArg, GenericArgs, GenericArgsRef, List, ParamEnv, Region,
32    Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, UintTy, ValTree,
33};
34
35// Re-export and re-parameterize some `I = TyCtxt<'tcx>` types here
36#[rustc_diagnostic_item = "TyKind"]
37pub type TyKind<'tcx> = ir::TyKind<TyCtxt<'tcx>>;
38pub type TypeAndMut<'tcx> = ir::TypeAndMut<TyCtxt<'tcx>>;
39pub type AliasTy<'tcx> = ir::AliasTy<TyCtxt<'tcx>>;
40pub type AliasTyKind<'tcx> = ir::AliasTyKind<TyCtxt<'tcx>>;
41pub type Alias<'tcx, K> = ir::Alias<TyCtxt<'tcx>, K>;
42pub type ProjectionAliasTy<'tcx> = ir::ProjectionAliasTy<TyCtxt<'tcx>>;
43pub type InherentAliasTy<'tcx> = ir::InherentAliasTy<TyCtxt<'tcx>>;
44pub type OpaqueAliasTy<'tcx> = ir::OpaqueAliasTy<TyCtxt<'tcx>>;
45pub type FreeAliasTy<'tcx> = ir::FreeAliasTy<TyCtxt<'tcx>>;
46pub type FnSig<'tcx> = ir::FnSig<TyCtxt<'tcx>>;
47pub type FnSigKind<'tcx> = ir::FnSigKind<TyCtxt<'tcx>>;
48pub type Binder<'tcx, T> = ir::Binder<TyCtxt<'tcx>, T>;
49pub type EarlyBinder<'tcx, T> = ir::EarlyBinder<TyCtxt<'tcx>, T>;
50pub type Unnormalized<'tcx, T> = ir::Unnormalized<TyCtxt<'tcx>, T>;
51pub type TypingMode<'tcx, S = MayBeErased> = ir::TypingMode<TyCtxt<'tcx>, S>;
52pub type TypingModeEqWrapper<'tcx> = ir::TypingModeEqWrapper<TyCtxt<'tcx>>;
53pub type Placeholder<'tcx, T> = ir::Placeholder<TyCtxt<'tcx>, T>;
54pub type PlaceholderRegion<'tcx> = ir::PlaceholderRegion<TyCtxt<'tcx>>;
55pub type PlaceholderType<'tcx> = ir::PlaceholderType<TyCtxt<'tcx>>;
56pub type PlaceholderConst<'tcx> = ir::PlaceholderConst<TyCtxt<'tcx>>;
57pub type BoundTy<'tcx> = ir::BoundTy<TyCtxt<'tcx>>;
58pub type BoundConst<'tcx> = ir::BoundConst<TyCtxt<'tcx>>;
59pub type BoundRegion<'tcx> = ir::BoundRegion<TyCtxt<'tcx>>;
60pub type BoundVariableKind<'tcx> = ir::BoundVariableKind<TyCtxt<'tcx>>;
61pub type BoundRegionKind<'tcx> = ir::BoundRegionKind<TyCtxt<'tcx>>;
62pub type BoundTyKind<'tcx> = ir::BoundTyKind<TyCtxt<'tcx>>;
63
64pub trait Article {
65    fn article(&self) -> &'static str;
66}
67
68impl<'tcx> Article for TyKind<'tcx> {
69    /// Get the article ("a" or "an") to use with this type.
70    fn article(&self) -> &'static str {
71        match self {
72            Int(_) | Float(_) | Array(_, _) => "an",
73            Adt(def, _) if def.is_enum() => "an",
74            // This should never happen, but ICEing and causing the user's code
75            // to not compile felt too harsh.
76            Error(_) => "a",
77            _ => "a",
78        }
79    }
80}
81
82pub trait CoroutineArgsExt<'tcx> {
    #[doc = " Coroutine has not been resumed yet."]
    const UNRESUMED: usize;
    #[doc = " Coroutine has returned or is completed."]
    const RETURNED: usize;
    #[doc = " Coroutine has been poisoned."]
    const POISONED: usize;
    #[doc =
    " Number of variants to reserve in coroutine state. Corresponds to"]
    #[doc =
    " `UNRESUMED` (beginning of a coroutine) and `RETURNED`/`POISONED`"]
    #[doc = " (end of a coroutine) states."]
    const RESERVED_VARIANTS: usize;
    const UNRESUMED_NAME: &'static str;
    const RETURNED_NAME: &'static str;
    const POISONED_NAME: &'static str;
    #[doc = " The valid variant indices of this coroutine."]
    fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>)
    -> Range<VariantIdx>;
    #[doc =
    " The discriminant for the given variant. Panics if the `variant_index` is"]
    #[doc = " out of range."]
    fn discriminant_for_variant(&self, def_id: DefId, tcx: TyCtxt<'tcx>,
    variant_index: VariantIdx)
    -> Discr<'tcx>;
    #[doc =
    " The set of all discriminants for the coroutine, enumerated with their"]
    #[doc = " variant indices."]
    fn discriminants(self, def_id: DefId, tcx: TyCtxt<'tcx>)
    -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)>;
    #[doc =
    " Calls `f` with a reference to the name of the enumerator for the given"]
    #[doc = " variant `v`."]
    fn variant_name(v: VariantIdx)
    -> Cow<'static, str>;
    #[doc = " The type of the state discriminant used in the coroutine type."]
    fn discr_ty(&self, tcx: TyCtxt<'tcx>)
    -> Ty<'tcx>;
    #[doc =
    " This returns the types of the MIR locals which had to be stored across suspension points."]
    #[doc =
    " It is calculated in rustc_mir_transform::coroutine::StateTransform."]
    #[doc = " All the types here must be in the tuple in CoroutineInterior."]
    #[doc = ""]
    #[doc =
    " The locals are grouped by their variant number. Note that some locals may"]
    #[doc = " be repeated in multiple variants."]
    fn state_tys(self, def_id: DefId, tcx: TyCtxt<'tcx>)
    -> impl Iterator<Item : Iterator<Item = Ty<'tcx>>>;
}
impl<'tcx> CoroutineArgsExt<'tcx> for ty::CoroutineArgs<TyCtxt<'tcx>> {
    #[doc = " Coroutine has not been resumed yet."]
    const UNRESUMED: usize = 0;
    #[doc = " Coroutine has returned or is completed."]
    const RETURNED: usize = 1;
    #[doc = " Coroutine has been poisoned."]
    const POISONED: usize = 2;
    #[doc =
    " Number of variants to reserve in coroutine state. Corresponds to"]
    #[doc =
    " `UNRESUMED` (beginning of a coroutine) and `RETURNED`/`POISONED`"]
    #[doc = " (end of a coroutine) states."]
    const RESERVED_VARIANTS: usize = 3;
    const UNRESUMED_NAME: &'static str = "Unresumed";
    const RETURNED_NAME: &'static str = "Returned";
    const POISONED_NAME: &'static str = "Panicked";
    #[doc = " The valid variant indices of this coroutine."]
    #[inline]
    fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>)
        -> Range<VariantIdx> {
        FIRST_VARIANT..tcx.coroutine_layout(def_id,
                            self.args).unwrap().variant_fields.next_index()
    }
    #[doc =
    " The discriminant for the given variant. Panics if the `variant_index` is"]
    #[doc = " out of range."]
    #[inline]
    fn discriminant_for_variant(&self, def_id: DefId, tcx: TyCtxt<'tcx>,
        variant_index: VariantIdx) -> Discr<'tcx> {
        if !self.variant_range(def_id, tcx).contains(&variant_index) {
            ::core::panicking::panic("assertion failed: self.variant_range(def_id, tcx).contains(&variant_index)")
        };
        Discr {
            val: variant_index.as_usize() as u128,
            ty: self.discr_ty(tcx),
        }
    }
    #[doc =
    " The set of all discriminants for the coroutine, enumerated with their"]
    #[doc = " variant indices."]
    #[inline]
    fn discriminants(self, def_id: DefId, tcx: TyCtxt<'tcx>)
        -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> {
        self.variant_range(def_id,
                tcx).map(move |index|
                {
                    (index,
                        Discr {
                            val: index.as_usize() as u128,
                            ty: self.discr_ty(tcx),
                        })
                })
    }
    #[doc =
    " Calls `f` with a reference to the name of the enumerator for the given"]
    #[doc = " variant `v`."]
    fn variant_name(v: VariantIdx) -> Cow<'static, str> {
        match v.as_usize() {
            Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
            Self::RETURNED => Cow::from(Self::RETURNED_NAME),
            Self::POISONED => Cow::from(Self::POISONED_NAME),
            _ =>
                Cow::from(::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("Suspend{0}",
                                    v.as_usize() - Self::RESERVED_VARIANTS))
                        })),
        }
    }
    #[doc = " The type of the state discriminant used in the coroutine type."]
    #[inline]
    fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { tcx.types.u32 }
    #[doc =
    " This returns the types of the MIR locals which had to be stored across suspension points."]
    #[doc =
    " It is calculated in rustc_mir_transform::coroutine::StateTransform."]
    #[doc = " All the types here must be in the tuple in CoroutineInterior."]
    #[doc = ""]
    #[doc =
    " The locals are grouped by their variant number. Note that some locals may"]
    #[doc = " be repeated in multiple variants."]
    #[inline]
    fn state_tys(self, def_id: DefId, tcx: TyCtxt<'tcx>)
        -> impl Iterator<Item : Iterator<Item = Ty<'tcx>>> {
        let layout = tcx.coroutine_layout(def_id, self.args).unwrap();
        layout.variant_fields.iter().map(move |variant|
                {
                    variant.iter().map(move |field|
                            {
                                if tcx.is_async_drop_in_place_coroutine(def_id) {
                                    layout.field_tys[*field].ty
                                } else {
                                    ty::EarlyBinder::bind(tcx,
                                                layout.field_tys[*field].ty).instantiate(tcx,
                                            self.args).skip_norm_wip()
                                }
                            })
                })
    }
}#[extension(pub trait CoroutineArgsExt<'tcx>)]
83impl<'tcx> ty::CoroutineArgs<TyCtxt<'tcx>> {
84    /// Coroutine has not been resumed yet.
85    const UNRESUMED: usize = 0;
86    /// Coroutine has returned or is completed.
87    const RETURNED: usize = 1;
88    /// Coroutine has been poisoned.
89    const POISONED: usize = 2;
90    /// Number of variants to reserve in coroutine state. Corresponds to
91    /// `UNRESUMED` (beginning of a coroutine) and `RETURNED`/`POISONED`
92    /// (end of a coroutine) states.
93    const RESERVED_VARIANTS: usize = 3;
94
95    const UNRESUMED_NAME: &'static str = "Unresumed";
96    const RETURNED_NAME: &'static str = "Returned";
97    const POISONED_NAME: &'static str = "Panicked";
98
99    /// The valid variant indices of this coroutine.
100    #[inline]
101    fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
102        // FIXME requires optimized MIR
103        FIRST_VARIANT..tcx.coroutine_layout(def_id, self.args).unwrap().variant_fields.next_index()
104    }
105
106    /// The discriminant for the given variant. Panics if the `variant_index` is
107    /// out of range.
108    #[inline]
109    fn discriminant_for_variant(
110        &self,
111        def_id: DefId,
112        tcx: TyCtxt<'tcx>,
113        variant_index: VariantIdx,
114    ) -> Discr<'tcx> {
115        // Coroutines don't support explicit discriminant values, so they are
116        // the same as the variant index.
117        assert!(self.variant_range(def_id, tcx).contains(&variant_index));
118        Discr { val: variant_index.as_usize() as u128, ty: self.discr_ty(tcx) }
119    }
120
121    /// The set of all discriminants for the coroutine, enumerated with their
122    /// variant indices.
123    #[inline]
124    fn discriminants(
125        self,
126        def_id: DefId,
127        tcx: TyCtxt<'tcx>,
128    ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> {
129        self.variant_range(def_id, tcx).map(move |index| {
130            (index, Discr { val: index.as_usize() as u128, ty: self.discr_ty(tcx) })
131        })
132    }
133
134    /// Calls `f` with a reference to the name of the enumerator for the given
135    /// variant `v`.
136    fn variant_name(v: VariantIdx) -> Cow<'static, str> {
137        match v.as_usize() {
138            Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
139            Self::RETURNED => Cow::from(Self::RETURNED_NAME),
140            Self::POISONED => Cow::from(Self::POISONED_NAME),
141            _ => Cow::from(format!("Suspend{}", v.as_usize() - Self::RESERVED_VARIANTS)),
142        }
143    }
144
145    /// The type of the state discriminant used in the coroutine type.
146    #[inline]
147    fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
148        tcx.types.u32
149    }
150
151    /// This returns the types of the MIR locals which had to be stored across suspension points.
152    /// It is calculated in rustc_mir_transform::coroutine::StateTransform.
153    /// All the types here must be in the tuple in CoroutineInterior.
154    ///
155    /// The locals are grouped by their variant number. Note that some locals may
156    /// be repeated in multiple variants.
157    #[inline]
158    fn state_tys(
159        self,
160        def_id: DefId,
161        tcx: TyCtxt<'tcx>,
162    ) -> impl Iterator<Item: Iterator<Item = Ty<'tcx>>> {
163        let layout = tcx.coroutine_layout(def_id, self.args).unwrap();
164        layout.variant_fields.iter().map(move |variant| {
165            variant.iter().map(move |field| {
166                if tcx.is_async_drop_in_place_coroutine(def_id) {
167                    layout.field_tys[*field].ty
168                } else {
169                    ty::EarlyBinder::bind(tcx, layout.field_tys[*field].ty)
170                        .instantiate(tcx, self.args)
171                        .skip_norm_wip()
172                }
173            })
174        })
175    }
176}
177
178#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for UpvarArgs<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            UpvarArgs::Closure(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Closure", &__self_0),
            UpvarArgs::Coroutine(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Coroutine", &__self_0),
            UpvarArgs::CoroutineClosure(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "CoroutineClosure", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for UpvarArgs<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for UpvarArgs<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for UpvarArgs<'tcx> {
    #[inline]
    fn clone(&self) -> UpvarArgs<'tcx> {
        let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
        *self
    }
}Clone, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            UpvarArgs<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    UpvarArgs::Closure(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    UpvarArgs::Coroutine(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    UpvarArgs::CoroutineClosure(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for UpvarArgs<'tcx> {
            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 {
                        UpvarArgs::Closure(__binding_0) => {
                            UpvarArgs::Closure(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                        UpvarArgs::Coroutine(__binding_0) => {
                            UpvarArgs::Coroutine(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                        UpvarArgs::CoroutineClosure(__binding_0) => {
                            UpvarArgs::CoroutineClosure(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    UpvarArgs::Closure(__binding_0) => {
                        UpvarArgs::Closure(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                    UpvarArgs::Coroutine(__binding_0) => {
                        UpvarArgs::Coroutine(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                    UpvarArgs::CoroutineClosure(__binding_0) => {
                        UpvarArgs::CoroutineClosure(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for UpvarArgs<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    UpvarArgs::Closure(ref __binding_0) => {
                        {
                            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);
                                }
                            }
                        }
                    }
                    UpvarArgs::Coroutine(ref __binding_0) => {
                        {
                            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);
                                }
                            }
                        }
                    }
                    UpvarArgs::CoroutineClosure(ref __binding_0) => {
                        {
                            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);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
179pub enum UpvarArgs<'tcx> {
180    Closure(GenericArgsRef<'tcx>),
181    Coroutine(GenericArgsRef<'tcx>),
182    CoroutineClosure(GenericArgsRef<'tcx>),
183}
184
185impl<'tcx> UpvarArgs<'tcx> {
186    /// Returns an iterator over the list of types of captured paths by the closure/coroutine.
187    /// In case there was a type error in figuring out the types of the captured path, an
188    /// empty iterator is returned.
189    #[inline]
190    pub fn upvar_tys(self) -> &'tcx List<Ty<'tcx>> {
191        match self.tupled_upvars_ty().kind() {
192            TyKind::Error(_) => ty::List::empty(),
193            TyKind::Tuple(args) => args,
194            TyKind::Infer(_) => crate::util::bug::bug_fmt(format_args!("upvar_tys called before capture types are inferred"))bug!("upvar_tys called before capture types are inferred"),
195            ty => crate::util::bug::bug_fmt(format_args!("Unexpected representation of upvar types tuple {0:?}",
        ty))bug!("Unexpected representation of upvar types tuple {:?}", ty),
196        }
197    }
198
199    #[inline]
200    pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
201        match self {
202            UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(),
203            UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(),
204            UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().tupled_upvars_ty(),
205        }
206    }
207}
208
209/// An inline const is modeled like
210/// ```ignore (illustrative)
211/// const InlineConst<'l0...'li, T0...Tj, R>: R;
212/// ```
213/// where:
214///
215/// - 'l0...'li and T0...Tj are the generic parameters
216///   inherited from the item that defined the inline const,
217/// - R represents the type of the constant.
218///
219/// When the inline const is instantiated, `R` is instantiated as the actual inferred
220/// type of the constant. The reason that `R` is represented as an extra type parameter
221/// is the same reason that [`ty::ClosureArgs`] have `CS` and `U` as type parameters:
222/// inline const can reference lifetimes that are internal to the creating function.
223#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for InlineConstArgs<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for InlineConstArgs<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for InlineConstArgs<'tcx> {
    #[inline]
    fn clone(&self) -> InlineConstArgs<'tcx> {
        let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for InlineConstArgs<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "InlineConstArgs", "args", &&self.args)
    }
}Debug)]
224pub struct InlineConstArgs<'tcx> {
225    /// Generic parameters from the enclosing item,
226    /// concatenated with the inferred type of the constant.
227    pub args: GenericArgsRef<'tcx>,
228}
229
230/// Struct returned by `split()`.
231pub struct InlineConstArgsParts<'tcx, T> {
232    pub parent_args: &'tcx [GenericArg<'tcx>],
233    pub ty: T,
234}
235
236impl<'tcx> InlineConstArgs<'tcx> {
237    /// Construct `InlineConstArgs` from `InlineConstArgsParts`.
238    pub fn new(
239        tcx: TyCtxt<'tcx>,
240        parts: InlineConstArgsParts<'tcx, Ty<'tcx>>,
241    ) -> InlineConstArgs<'tcx> {
242        InlineConstArgs {
243            args: tcx.mk_args_from_iter(
244                parts.parent_args.iter().copied().chain(std::iter::once(parts.ty.into())),
245            ),
246        }
247    }
248
249    /// Divides the inline const args into their respective components.
250    /// The ordering assumed here must match that used by `InlineConstArgs::new` above.
251    fn split(self) -> InlineConstArgsParts<'tcx, GenericArg<'tcx>> {
252        match self.args[..] {
253            [ref parent_args @ .., ty] => InlineConstArgsParts { parent_args, ty },
254            _ => crate::util::bug::bug_fmt(format_args!("inline const args missing synthetics"))bug!("inline const args missing synthetics"),
255        }
256    }
257
258    /// Returns the generic parameters of the inline const's parent.
259    pub fn parent_args(self) -> &'tcx [GenericArg<'tcx>] {
260        self.split().parent_args
261    }
262
263    /// Returns the type of this inline const.
264    pub fn ty(self) -> Ty<'tcx> {
265        self.split().ty.expect_ty()
266    }
267}
268
269pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>;
270pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>;
271
272#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ParamTy { }
#[automatically_derived]
impl ::core::clone::Clone for ParamTy {
    #[inline]
    fn clone(&self) -> ParamTy {
        let _: ::core::clone::AssertParamIsClone<u32>;
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ParamTy { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ParamTy { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ParamTy {
    #[inline]
    fn eq(&self, other: &ParamTy) -> bool {
        self.index == other.index && self.name == other.name
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ParamTy {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<u32>;
        let _: ::core::cmp::AssertParamIsEq<Symbol>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for ParamTy {
    #[inline]
    fn partial_cmp(&self, other: &ParamTy)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for ParamTy {
    #[inline]
    fn cmp(&self, other: &ParamTy) -> ::core::cmp::Ordering {
        match ::core::cmp::Ord::cmp(&self.index, &other.index) {
            ::core::cmp::Ordering::Equal =>
                ::core::cmp::Ord::cmp(&self.name, &other.name),
            cmp => cmp,
        }
    }
}Ord, #[automatically_derived]
impl ::core::hash::Hash for ParamTy {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.index, state);
        ::core::hash::Hash::hash(&self.name, state)
    }
}Hash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for ParamTy {
            fn encode(&self, __encoder: &mut __E) {
                let ParamTy { index: ref __binding_0, name: ref __binding_1
                        } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                    __encoder);
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for ParamTy {
            fn decode(__decoder: &mut __D) -> Self {
                ParamTy {
                    index: ::rustc_serialize::Decodable::decode(__decoder),
                    name: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable)]
273#[derive(const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for ParamTy {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    ParamTy { index: ref __binding_0, name: ref __binding_1 } =>
                        {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
274pub struct ParamTy {
275    pub index: u32,
276    pub name: Symbol,
277}
278
279impl rustc_type_ir::inherent::ParamLike for ParamTy {
280    fn index(self) -> u32 {
281        self.index
282    }
283}
284
285impl<'tcx> ParamTy {
286    pub fn new(index: u32, name: Symbol) -> ParamTy {
287        ParamTy { index, name }
288    }
289
290    pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
291        ParamTy::new(def.index, def.name)
292    }
293
294    #[inline]
295    pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
296        Ty::new_param(tcx, self.index, self.name)
297    }
298
299    pub fn span_from_generics(self, tcx: TyCtxt<'tcx>, item_with_generics: DefId) -> Span {
300        let generics = tcx.generics_of(item_with_generics);
301        let type_param = generics.type_param(self, tcx);
302        tcx.def_span(type_param.def_id)
303    }
304}
305
306#[derive(#[automatically_derived]
impl ::core::marker::Copy for ParamConst { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ParamConst { }
#[automatically_derived]
impl ::core::clone::Clone for ParamConst {
    #[inline]
    fn clone(&self) -> ParamConst {
        let _: ::core::clone::AssertParamIsClone<u32>;
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::hash::Hash for ParamConst {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.index, state);
        ::core::hash::Hash::hash(&self.name, state)
    }
}Hash, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for ParamConst {
            fn encode(&self, __encoder: &mut __E) {
                let ParamConst { index: ref __binding_0, name: ref __binding_1
                        } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                    __encoder);
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for ParamConst {
            fn decode(__decoder: &mut __D) -> Self {
                ParamConst {
                    index: ::rustc_serialize::Decodable::decode(__decoder),
                    name: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable, #[automatically_derived]
impl ::core::cmp::Eq for ParamConst {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<u32>;
        let _: ::core::cmp::AssertParamIsEq<Symbol>;
    }
}Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ParamConst { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ParamConst {
    #[inline]
    fn eq(&self, other: &ParamConst) -> bool {
        self.index == other.index && self.name == other.name
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Ord for ParamConst {
    #[inline]
    fn cmp(&self, other: &ParamConst) -> ::core::cmp::Ordering {
        match ::core::cmp::Ord::cmp(&self.index, &other.index) {
            ::core::cmp::Ordering::Equal =>
                ::core::cmp::Ord::cmp(&self.name, &other.name),
            cmp => cmp,
        }
    }
}Ord, #[automatically_derived]
impl ::core::cmp::PartialOrd for ParamConst {
    #[inline]
    fn partial_cmp(&self, other: &ParamConst)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd)]
307#[derive(const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for ParamConst {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    ParamConst { index: ref __binding_0, name: ref __binding_1 }
                        => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
308pub struct ParamConst {
309    pub index: u32,
310    pub name: Symbol,
311}
312
313impl rustc_type_ir::inherent::ParamLike for ParamConst {
314    fn index(self) -> u32 {
315        self.index
316    }
317}
318
319impl ParamConst {
320    pub fn new(index: u32, name: Symbol) -> ParamConst {
321        ParamConst { index, name }
322    }
323
324    pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
325        ParamConst::new(def.index, def.name)
326    }
327
328    {}
#[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("find_const_ty_from_env",
                                    "rustc_middle::ty::sty", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_middle/src/ty/sty.rs"),
                                    ::tracing_core::__macro_support::Option::Some(328u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("env")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("env");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&env)
                                                            as &dyn ::tracing::field::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: Ty<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut candidates =
                env.caller_bounds().filter_map(|clause|
                        {
                            match clause.kind().skip_binder() {
                                ty::ClauseKind::ConstArgHasType(param_ct, ty) => {
                                    if !!(param_ct, ty).has_escaping_bound_vars() {
                                        ::core::panicking::panic("assertion failed: !(param_ct, ty).has_escaping_bound_vars()")
                                    };
                                    match param_ct.kind() {
                                        ty::ConstKind::Param(param_ct) if
                                            param_ct.index == self.index => Some(ty),
                                        _ => None,
                                    }
                                }
                                _ => None,
                            }
                        });
            let ty =
                candidates.next().unwrap_or_else(||
                        {
                            crate::util::bug::bug_fmt(format_args!("cannot find `{0:?}` in param-env: {1:#?}",
                                    self, env));
                        });
            if !candidates.next().is_none() {
                {
                    ::core::panicking::panic_fmt(format_args!("did not expect duplicate `ConstParamHasTy` for `{0:?}` in param-env: {1:#?}",
                            self, env));
                }
            };
            ty
        }
    }
}#[instrument(level = "debug")]
329    pub fn find_const_ty_from_env<'tcx>(self, env: ParamEnv<'tcx>) -> Ty<'tcx> {
330        let mut candidates = env.caller_bounds().filter_map(|clause| {
331            // `ConstArgHasType` are never desugared to be higher ranked.
332            match clause.kind().skip_binder() {
333                ty::ClauseKind::ConstArgHasType(param_ct, ty) => {
334                    assert!(!(param_ct, ty).has_escaping_bound_vars());
335
336                    match param_ct.kind() {
337                        ty::ConstKind::Param(param_ct) if param_ct.index == self.index => Some(ty),
338                        _ => None,
339                    }
340                }
341                _ => None,
342            }
343        });
344
345        // N.B. it may be tempting to fix ICEs by making this function return
346        // `Option<Ty<'tcx>>` instead of `Ty<'tcx>`; however, this is generally
347        // considered to be a bandaid solution, since it hides more important
348        // underlying issues with how we construct generics and predicates of
349        // items. It's advised to fix the underlying issue rather than trying
350        // to modify this function.
351        let ty = candidates.next().unwrap_or_else(|| {
352            bug!("cannot find `{self:?}` in param-env: {env:#?}");
353        });
354        assert!(
355            candidates.next().is_none(),
356            "did not expect duplicate `ConstParamHasTy` for `{self:?}` in param-env: {env:#?}"
357        );
358        ty
359    }
360}
361
362/// Constructors for `Ty`
363impl<'tcx> Ty<'tcx> {
364    /// Avoid using this in favour of more specific `new_*` methods, where possible.
365    /// The more specific methods will often optimize their creation.
366    #[inline]
367    fn new(tcx: TyCtxt<'tcx>, st: TyKind<'tcx>) -> Ty<'tcx> {
368        tcx.mk_ty_from_kind(st)
369    }
370
371    #[inline]
372    pub fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Ty<'tcx> {
373        Ty::new(tcx, TyKind::Infer(infer))
374    }
375
376    #[inline]
377    pub fn new_var(tcx: TyCtxt<'tcx>, v: ty::TyVid) -> Ty<'tcx> {
378        // Use a pre-interned one when possible.
379        tcx.types
380            .ty_vars
381            .get(v.as_usize())
382            .copied()
383            .unwrap_or_else(|| Ty::new(tcx, Infer(TyVar(v))))
384    }
385
386    #[inline]
387    pub fn new_int_var(tcx: TyCtxt<'tcx>, v: ty::IntVid) -> Ty<'tcx> {
388        Ty::new_infer(tcx, IntVar(v))
389    }
390
391    #[inline]
392    pub fn new_float_var(tcx: TyCtxt<'tcx>, v: ty::FloatVid) -> Ty<'tcx> {
393        Ty::new_infer(tcx, FloatVar(v))
394    }
395
396    #[inline]
397    pub fn new_fresh(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
398        // Use a pre-interned one when possible.
399        tcx.types
400            .fresh_tys
401            .get(n as usize)
402            .copied()
403            .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshTy(n)))
404    }
405
406    #[inline]
407    pub fn new_fresh_int(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
408        // Use a pre-interned one when possible.
409        tcx.types
410            .fresh_int_tys
411            .get(n as usize)
412            .copied()
413            .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshIntTy(n)))
414    }
415
416    #[inline]
417    pub fn new_fresh_float(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
418        // Use a pre-interned one when possible.
419        tcx.types
420            .fresh_float_tys
421            .get(n as usize)
422            .copied()
423            .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshFloatTy(n)))
424    }
425
426    #[inline]
427    pub fn new_param(tcx: TyCtxt<'tcx>, index: u32, name: Symbol) -> Ty<'tcx> {
428        Ty::new(tcx, Param(ParamTy { index, name }))
429    }
430
431    #[inline]
432    pub fn new_bound(
433        tcx: TyCtxt<'tcx>,
434        index: ty::DebruijnIndex,
435        bound_ty: ty::BoundTy<'tcx>,
436    ) -> Ty<'tcx> {
437        // Use a pre-interned one when possible.
438        if let ty::BoundTy { var, kind: ty::BoundTyKind::Anon } = bound_ty
439            && let Some(inner) = tcx.types.anon_bound_tys.get(index.as_usize())
440            && let Some(ty) = inner.get(var.as_usize()).copied()
441        {
442            ty
443        } else {
444            Ty::new(tcx, Bound(ty::BoundVarIndexKind::Bound(index), bound_ty))
445        }
446    }
447
448    #[inline]
449    pub fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: BoundVar) -> Ty<'tcx> {
450        // Use a pre-interned one when possible.
451        if let Some(ty) = tcx.types.anon_canonical_bound_tys.get(var.as_usize()).copied() {
452            ty
453        } else {
454            Ty::new(
455                tcx,
456                Bound(
457                    ty::BoundVarIndexKind::Canonical,
458                    ty::BoundTy { var, kind: ty::BoundTyKind::Anon },
459                ),
460            )
461        }
462    }
463
464    #[inline]
465    pub fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType<'tcx>) -> Ty<'tcx> {
466        Ty::new(tcx, Placeholder(placeholder))
467    }
468
469    #[inline]
470    pub fn new_alias(
471        tcx: TyCtxt<'tcx>,
472        is_rigid: ty::IsRigid,
473        alias_ty: ty::AliasTy<'tcx>,
474    ) -> Ty<'tcx> {
475        Ty::new(tcx, Alias(is_rigid, alias_ty))
476    }
477
478    #[inline]
479    pub fn new_pat(tcx: TyCtxt<'tcx>, base: Ty<'tcx>, pat: ty::Pattern<'tcx>) -> Ty<'tcx> {
480        Ty::new(tcx, Pat(base, pat))
481    }
482
483    #[inline]
484    pub fn new_field_representing_type(
485        tcx: TyCtxt<'tcx>,
486        base: Ty<'tcx>,
487        variant: VariantIdx,
488        field: FieldIdx,
489    ) -> Ty<'tcx> {
490        let Some(did) = tcx.lang_items().field_representing_type() else {
491            crate::util::bug::bug_fmt(format_args!("could not locate the `FieldRepresentingType` lang item"))bug!("could not locate the `FieldRepresentingType` lang item")
492        };
493        let def = tcx.adt_def(did);
494        let args = tcx.mk_args(&[
495            base.into(),
496            Const::new_value(
497                tcx,
498                ValTree::from_scalar_int(tcx, variant.as_u32().into()),
499                tcx.types.u32,
500            )
501            .into(),
502            Const::new_value(
503                tcx,
504                ValTree::from_scalar_int(tcx, field.as_u32().into()),
505                tcx.types.u32,
506            )
507            .into(),
508        ]);
509        Ty::new_adt(tcx, def, args)
510    }
511
512    #[inline]
513    {}
#[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("new_opaque",
                                    "rustc_middle::ty::sty", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_middle/src/ty/sty.rs"),
                                    ::tracing_core::__macro_support::Option::Some(513u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("is_rigid")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("is_rigid");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("args");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&is_rigid)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn ::tracing::field::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: Ty<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            Ty::new_alias(tcx, is_rigid,
                AliasTy::new_from_args(tcx, ty::Opaque { def_id }, args))
        }
    }
}#[instrument(level = "debug", skip(tcx))]
514    pub fn new_opaque(
515        tcx: TyCtxt<'tcx>,
516        is_rigid: ty::IsRigid,
517        def_id: DefId,
518        args: GenericArgsRef<'tcx>,
519    ) -> Ty<'tcx> {
520        Ty::new_alias(tcx, is_rigid, AliasTy::new_from_args(tcx, ty::Opaque { def_id }, args))
521    }
522
523    /// Constructs a `TyKind::Error` type with current `ErrorGuaranteed`
524    pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Ty<'tcx> {
525        Ty::new(tcx, Error(guar))
526    }
527
528    /// Constructs a `TyKind::Error` type and registers a `span_delayed_bug` to ensure it gets used.
529    #[track_caller]
530    pub fn new_misc_error(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
531        Ty::new_error_with_message(tcx, DUMMY_SP, "TyKind::Error constructed but no error reported")
532    }
533
534    /// Constructs a `TyKind::Error` type and registers a `span_delayed_bug` with the given `msg` to
535    /// ensure it gets used.
536    #[track_caller]
537    pub fn new_error_with_message<S: Into<MultiSpan>>(
538        tcx: TyCtxt<'tcx>,
539        span: S,
540        msg: impl Into<Cow<'static, str>>,
541    ) -> Ty<'tcx> {
542        let reported = tcx.dcx().span_delayed_bug(span, msg);
543        Ty::new(tcx, Error(reported))
544    }
545
546    #[inline]
547    pub fn new_int(tcx: TyCtxt<'tcx>, i: ty::IntTy) -> Ty<'tcx> {
548        use ty::IntTy::*;
549        match i {
550            Isize => tcx.types.isize,
551            I8 => tcx.types.i8,
552            I16 => tcx.types.i16,
553            I32 => tcx.types.i32,
554            I64 => tcx.types.i64,
555            I128 => tcx.types.i128,
556        }
557    }
558
559    #[inline]
560    pub fn new_uint(tcx: TyCtxt<'tcx>, ui: ty::UintTy) -> Ty<'tcx> {
561        use ty::UintTy::*;
562        match ui {
563            Usize => tcx.types.usize,
564            U8 => tcx.types.u8,
565            U16 => tcx.types.u16,
566            U32 => tcx.types.u32,
567            U64 => tcx.types.u64,
568            U128 => tcx.types.u128,
569        }
570    }
571
572    #[inline]
573    pub fn new_float(tcx: TyCtxt<'tcx>, f: ty::FloatTy) -> Ty<'tcx> {
574        use ty::FloatTy::*;
575        match f {
576            F16 => tcx.types.f16,
577            F32 => tcx.types.f32,
578            F64 => tcx.types.f64,
579            F128 => tcx.types.f128,
580        }
581    }
582
583    #[inline]
584    pub fn new_ref(
585        tcx: TyCtxt<'tcx>,
586        r: Region<'tcx>,
587        ty: Ty<'tcx>,
588        mutbl: ty::Mutability,
589    ) -> Ty<'tcx> {
590        Ty::new(tcx, Ref(r, ty, mutbl))
591    }
592
593    #[inline]
594    pub fn new_mut_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
595        Ty::new_ref(tcx, r, ty, hir::Mutability::Mut)
596    }
597
598    #[inline]
599    pub fn new_imm_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
600        Ty::new_ref(tcx, r, ty, hir::Mutability::Not)
601    }
602
603    pub fn new_pinned_ref(
604        tcx: TyCtxt<'tcx>,
605        r: Region<'tcx>,
606        ty: Ty<'tcx>,
607        mutbl: ty::Mutability,
608    ) -> Ty<'tcx> {
609        let pin = tcx.adt_def(tcx.require_lang_item(LangItem::Pin, DUMMY_SP));
610        Ty::new_adt(tcx, pin, tcx.mk_args(&[Ty::new_ref(tcx, r, ty, mutbl).into()]))
611    }
612
613    #[inline]
614    pub fn new_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, mutbl: ty::Mutability) -> Ty<'tcx> {
615        Ty::new(tcx, ty::RawPtr(ty, mutbl))
616    }
617
618    #[inline]
619    pub fn new_mut_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
620        Ty::new_ptr(tcx, ty, hir::Mutability::Mut)
621    }
622
623    #[inline]
624    pub fn new_imm_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
625        Ty::new_ptr(tcx, ty, hir::Mutability::Not)
626    }
627
628    #[inline]
629    pub fn new_adt(tcx: TyCtxt<'tcx>, def: AdtDef<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
630        tcx.debug_assert_args_compatible(def.did(), args);
631        if truecfg!(debug_assertions) {
632            match tcx.def_kind(def.did()) {
633                DefKind::Struct | DefKind::Union | DefKind::Enum => {}
634                DefKind::Mod
635                | DefKind::Variant
636                | DefKind::Trait
637                | DefKind::TyAlias
638                | DefKind::ForeignTy
639                | DefKind::TraitAlias
640                | DefKind::AssocTy
641                | DefKind::TyParam
642                | DefKind::Fn
643                | DefKind::Const
644                | DefKind::ConstParam
645                | DefKind::Static { .. }
646                | DefKind::Ctor(..)
647                | DefKind::AssocFn
648                | DefKind::AssocConst
649                | DefKind::Macro(..)
650                | DefKind::ExternCrate
651                | DefKind::Use
652                | DefKind::ForeignMod
653                | DefKind::AnonConst
654                | DefKind::OpaqueTy
655                | DefKind::Field
656                | DefKind::LifetimeParam
657                | DefKind::GlobalAsm
658                | DefKind::Impl { .. }
659                | DefKind::Closure
660                | DefKind::SyntheticCoroutineBody
661                | DefKind::TestBinderConstraints => {
662                    crate::util::bug::bug_fmt(format_args!("not an adt: {1:?} ({0:?})",
        tcx.def_kind(def.did()), def))bug!("not an adt: {def:?} ({:?})", tcx.def_kind(def.did()))
663                }
664            }
665        }
666        Ty::new(tcx, Adt(def, args))
667    }
668
669    #[inline]
670    pub fn new_foreign(tcx: TyCtxt<'tcx>, def_id: DefId) -> Ty<'tcx> {
671        Ty::new(tcx, Foreign(def_id))
672    }
673
674    #[inline]
675    pub fn new_array(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
676        Ty::new(tcx, Array(ty, ty::Const::from_target_usize(tcx, n)))
677    }
678
679    #[inline]
680    pub fn new_array_with_const_len(
681        tcx: TyCtxt<'tcx>,
682        ty: Ty<'tcx>,
683        ct: ty::Const<'tcx>,
684    ) -> Ty<'tcx> {
685        Ty::new(tcx, Array(ty, ct))
686    }
687
688    #[inline]
689    pub fn new_slice(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
690        Ty::new(tcx, Slice(ty))
691    }
692
693    #[inline]
694    pub fn new_tup(tcx: TyCtxt<'tcx>, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
695        if ts.is_empty() { tcx.types.unit } else { Ty::new(tcx, Tuple(tcx.mk_type_list(ts))) }
696    }
697
698    pub fn new_tup_from_iter<I, T>(tcx: TyCtxt<'tcx>, iter: I) -> T::Output
699    where
700        I: Iterator<Item = T>,
701        T: CollectAndApply<Ty<'tcx>, Ty<'tcx>>,
702    {
703        T::collect_and_apply(iter, |ts| Ty::new_tup(tcx, ts))
704    }
705
706    /// Prefer using the [TyCtxt::type_of] query over this, that makes it easier to get all the pieces correct
707    #[inline]
708    pub fn new_fn_def(
709        tcx: TyCtxt<'tcx>,
710        def_id: DefId,
711        args: ty::Binder<'tcx, impl IntoIterator<Item: Into<GenericArg<'tcx>>>>,
712    ) -> Ty<'tcx> {
713        if true {
    {
        match tcx.def_kind(def_id) {
            DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) =>
                {}
            ref left_val => {
                ::core::panicking::assert_matches_failed(left_val,
                    "DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)",
                    ::core::option::Option::None);
            }
        }
    };
};debug_assert_matches!(
714            tcx.def_kind(def_id),
715            DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)
716        );
717        let args = args.map_bound(|args| tcx.check_and_mk_args(def_id, args));
718        Ty::new(tcx, FnDef(def_id, args))
719    }
720
721    #[inline]
722    pub fn new_fn_ptr(tcx: TyCtxt<'tcx>, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
723        let (sig_tys, hdr) = fty.split();
724        Ty::new(tcx, FnPtr(sig_tys, hdr))
725    }
726
727    #[inline]
728    pub fn new_unsafe_binder(tcx: TyCtxt<'tcx>, b: Binder<'tcx, Ty<'tcx>>) -> Ty<'tcx> {
729        Ty::new(tcx, UnsafeBinder(b.into()))
730    }
731
732    #[inline]
733    pub fn new_dynamic(
734        tcx: TyCtxt<'tcx>,
735        obj: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
736        reg: ty::Region<'tcx>,
737    ) -> Ty<'tcx> {
738        if truecfg!(debug_assertions) {
739            let projection_count = obj
740                .projection_bounds()
741                .filter(|item| !tcx.generics_require_sized_self(item.item_def_id()))
742                .count();
743            let expected_count: usize = obj.principal_def_id().map_or(0, |principal_def_id| {
744                // IMPORTANT: This has to agree with HIR ty lowering of dyn trait!
745                elaborate::supertraits(
746                    tcx,
747                    ty::Binder::dummy(ty::TraitRef::identity(tcx, principal_def_id)),
748                )
749                .map(|principal| {
750                    tcx.associated_items(principal.def_id())
751                        .in_definition_order()
752                        .filter(|item| item.can_have_equality_constraint(tcx))
753                        .filter(|item| !item.is_impl_trait_in_trait())
754                        .filter(|item| !tcx.generics_require_sized_self(item.def_id))
755                        .count()
756                })
757                .sum()
758            });
759            {
    match (&projection_count, &expected_count) {
        (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!("expected {0:?} to have {1} projections, but it has {2}",
                            obj, expected_count, projection_count)));
            }
        }
    }
};assert_eq!(
760                projection_count, expected_count,
761                "expected {obj:?} to have {expected_count} projections, \
762                but it has {projection_count}"
763            );
764        }
765        Ty::new(tcx, Dynamic(obj, reg))
766    }
767
768    #[inline]
769    pub fn new_projection_from_args(
770        tcx: TyCtxt<'tcx>,
771        is_rigid: ty::IsRigid,
772        item_def_id: DefId,
773        args: ty::GenericArgsRef<'tcx>,
774    ) -> Ty<'tcx> {
775        Ty::new_alias(
776            tcx,
777            is_rigid,
778            AliasTy::new_from_args(tcx, ty::Projection { def_id: item_def_id }, args),
779        )
780    }
781
782    #[inline]
783    pub fn new_projection(
784        tcx: TyCtxt<'tcx>,
785        is_rigid: ty::IsRigid,
786        item_def_id: DefId,
787        args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
788    ) -> Ty<'tcx> {
789        Ty::new_alias(
790            tcx,
791            is_rigid,
792            AliasTy::new(tcx, ty::Projection { def_id: item_def_id }, args),
793        )
794    }
795
796    #[inline]
797    pub fn new_closure(
798        tcx: TyCtxt<'tcx>,
799        def_id: DefId,
800        closure_args: GenericArgsRef<'tcx>,
801    ) -> Ty<'tcx> {
802        tcx.debug_assert_args_compatible(def_id, closure_args);
803        Ty::new(tcx, Closure(def_id, closure_args))
804    }
805
806    #[inline]
807    pub fn new_coroutine_closure(
808        tcx: TyCtxt<'tcx>,
809        def_id: DefId,
810        closure_args: GenericArgsRef<'tcx>,
811    ) -> Ty<'tcx> {
812        tcx.debug_assert_args_compatible(def_id, closure_args);
813        Ty::new(tcx, CoroutineClosure(def_id, closure_args))
814    }
815
816    #[inline]
817    pub fn new_coroutine(
818        tcx: TyCtxt<'tcx>,
819        def_id: DefId,
820        coroutine_args: GenericArgsRef<'tcx>,
821    ) -> Ty<'tcx> {
822        tcx.debug_assert_args_compatible(def_id, coroutine_args);
823        Ty::new(tcx, Coroutine(def_id, coroutine_args))
824    }
825
826    #[inline]
827    pub fn new_coroutine_witness(
828        tcx: TyCtxt<'tcx>,
829        def_id: DefId,
830        args: GenericArgsRef<'tcx>,
831    ) -> Ty<'tcx> {
832        if truecfg!(debug_assertions) {
833            tcx.debug_assert_args_compatible(tcx.typeck_root_def_id(def_id), args);
834        }
835        Ty::new(tcx, CoroutineWitness(def_id, args))
836    }
837
838    pub fn new_coroutine_witness_for_coroutine(
839        tcx: TyCtxt<'tcx>,
840        def_id: DefId,
841        coroutine_args: GenericArgsRef<'tcx>,
842    ) -> Ty<'tcx> {
843        tcx.debug_assert_args_compatible(def_id, coroutine_args);
844        // HACK: Coroutine witness types are lifetime erased, so they
845        // never reference any lifetime args from the coroutine. We erase
846        // the regions here since we may get into situations where a
847        // coroutine is recursively contained within itself, leading to
848        // witness types that differ by region args. This means that
849        // cycle detection in fulfillment will not kick in, which leads
850        // to unnecessary overflows in async code. See the issue:
851        // <https://github.com/rust-lang/rust/issues/145151>.
852        let args =
853            ty::GenericArgs::for_item(tcx, tcx.typeck_root_def_id(def_id), |def, _| {
854                match def.kind {
855                    ty::GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
856                    ty::GenericParamDefKind::Type { .. }
857                    | ty::GenericParamDefKind::Const { .. } => coroutine_args[def.index as usize],
858                }
859            });
860        Ty::new_coroutine_witness(tcx, def_id, args)
861    }
862
863    // misc
864
865    #[inline]
866    pub fn new_static_str(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
867        Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, tcx.types.str_)
868    }
869
870    // lang and diagnostic tys
871
872    fn new_generic_adt(tcx: TyCtxt<'tcx>, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
873        let adt_def = tcx.adt_def(wrapper_def_id);
874        let args = GenericArgs::for_item(tcx, wrapper_def_id, |param, args| match param.kind {
875            GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => crate::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
876            GenericParamDefKind::Type { has_default, .. } => {
877                if param.index == 0 {
878                    ty_param.into()
879                } else {
880                    if !has_default { ::core::panicking::panic("assertion failed: has_default") };assert!(has_default);
881                    tcx.type_of(param.def_id).instantiate(tcx, args).skip_norm_wip().into()
882                }
883            }
884        });
885        Ty::new_adt(tcx, adt_def, args)
886    }
887
888    #[inline]
889    pub fn new_lang_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, item: LangItem) -> Option<Ty<'tcx>> {
890        let def_id = tcx.lang_items().get(item)?;
891        Some(Ty::new_generic_adt(tcx, def_id, ty))
892    }
893
894    #[inline]
895    pub fn new_diagnostic_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
896        let def_id = tcx.get_diagnostic_item(name)?;
897        Some(Ty::new_generic_adt(tcx, def_id, ty))
898    }
899
900    #[inline]
901    pub fn new_box(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
902        let def_id = tcx.require_lang_item(LangItem::OwnedBox, DUMMY_SP);
903        Ty::new_generic_adt(tcx, def_id, ty)
904    }
905
906    #[inline]
907    pub fn new_option(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
908        let def_id = tcx.require_lang_item(LangItem::Option, DUMMY_SP);
909        Ty::new_generic_adt(tcx, def_id, ty)
910    }
911
912    #[inline]
913    pub fn new_maybe_uninit(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
914        let def_id = tcx.require_lang_item(LangItem::MaybeUninit, DUMMY_SP);
915        Ty::new_generic_adt(tcx, def_id, ty)
916    }
917
918    /// Creates a `&mut Context<'_>` [`Ty`] with erased lifetimes.
919    pub fn new_task_context(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
920        let context_did = tcx.require_lang_item(LangItem::Context, DUMMY_SP);
921        let context_adt_ref = tcx.adt_def(context_did);
922        let context_args = tcx.mk_args(&[tcx.lifetimes.re_erased.into()]);
923        let context_ty = Ty::new_adt(tcx, context_adt_ref, context_args);
924        Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, context_ty)
925    }
926}
927
928impl<'tcx> rustc_type_ir::inherent::Ty<TyCtxt<'tcx>> for Ty<'tcx> {
929    fn new_bool(tcx: TyCtxt<'tcx>) -> Self {
930        tcx.types.bool
931    }
932
933    fn new_u8(tcx: TyCtxt<'tcx>) -> Self {
934        tcx.types.u8
935    }
936
937    fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Self {
938        Ty::new_infer(tcx, infer)
939    }
940
941    fn new_var(tcx: TyCtxt<'tcx>, vid: ty::TyVid) -> Self {
942        Ty::new_var(tcx, vid)
943    }
944
945    fn new_param(tcx: TyCtxt<'tcx>, param: ty::ParamTy) -> Self {
946        Ty::new_param(tcx, param.index, param.name)
947    }
948
949    fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType<'tcx>) -> Self {
950        Ty::new_placeholder(tcx, placeholder)
951    }
952
953    fn new_bound(
954        interner: TyCtxt<'tcx>,
955        debruijn: ty::DebruijnIndex,
956        var: ty::BoundTy<'tcx>,
957    ) -> Self {
958        Ty::new_bound(interner, debruijn, var)
959    }
960
961    fn new_anon_bound(tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self {
962        Ty::new_bound(tcx, debruijn, ty::BoundTy { var, kind: ty::BoundTyKind::Anon })
963    }
964
965    fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: ty::BoundVar) -> Self {
966        Ty::new_canonical_bound(tcx, var)
967    }
968
969    fn new_alias(
970        interner: TyCtxt<'tcx>,
971        is_rigid: ty::IsRigid,
972        alias_ty: ty::AliasTy<'tcx>,
973    ) -> Self {
974        Ty::new_alias(interner, is_rigid, alias_ty)
975    }
976
977    fn new_error(interner: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Self {
978        Ty::new_error(interner, guar)
979    }
980
981    fn new_adt(
982        interner: TyCtxt<'tcx>,
983        adt_def: ty::AdtDef<'tcx>,
984        args: ty::GenericArgsRef<'tcx>,
985    ) -> Self {
986        Ty::new_adt(interner, adt_def, args)
987    }
988
989    fn new_foreign(interner: TyCtxt<'tcx>, def_id: DefId) -> Self {
990        Ty::new_foreign(interner, def_id)
991    }
992
993    fn new_dynamic(
994        interner: TyCtxt<'tcx>,
995        preds: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
996        region: ty::Region<'tcx>,
997    ) -> Self {
998        Ty::new_dynamic(interner, preds, region)
999    }
1000
1001    fn new_coroutine(
1002        interner: TyCtxt<'tcx>,
1003        def_id: DefId,
1004        args: ty::GenericArgsRef<'tcx>,
1005    ) -> Self {
1006        Ty::new_coroutine(interner, def_id, args)
1007    }
1008
1009    fn new_coroutine_closure(
1010        interner: TyCtxt<'tcx>,
1011        def_id: DefId,
1012        args: ty::GenericArgsRef<'tcx>,
1013    ) -> Self {
1014        Ty::new_coroutine_closure(interner, def_id, args)
1015    }
1016
1017    fn new_closure(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
1018        Ty::new_closure(interner, def_id, args)
1019    }
1020
1021    fn new_coroutine_witness(
1022        interner: TyCtxt<'tcx>,
1023        def_id: DefId,
1024        args: ty::GenericArgsRef<'tcx>,
1025    ) -> Self {
1026        Ty::new_coroutine_witness(interner, def_id, args)
1027    }
1028
1029    fn new_coroutine_witness_for_coroutine(
1030        interner: TyCtxt<'tcx>,
1031        def_id: DefId,
1032        coroutine_args: ty::GenericArgsRef<'tcx>,
1033    ) -> Self {
1034        Ty::new_coroutine_witness_for_coroutine(interner, def_id, coroutine_args)
1035    }
1036
1037    fn new_ptr(interner: TyCtxt<'tcx>, ty: Self, mutbl: hir::Mutability) -> Self {
1038        Ty::new_ptr(interner, ty, mutbl)
1039    }
1040
1041    fn new_ref(
1042        interner: TyCtxt<'tcx>,
1043        region: ty::Region<'tcx>,
1044        ty: Self,
1045        mutbl: hir::Mutability,
1046    ) -> Self {
1047        Ty::new_ref(interner, region, ty, mutbl)
1048    }
1049
1050    fn new_array_with_const_len(interner: TyCtxt<'tcx>, ty: Self, len: ty::Const<'tcx>) -> Self {
1051        Ty::new_array_with_const_len(interner, ty, len)
1052    }
1053
1054    fn new_slice(interner: TyCtxt<'tcx>, ty: Self) -> Self {
1055        Ty::new_slice(interner, ty)
1056    }
1057
1058    fn new_tup(interner: TyCtxt<'tcx>, tys: &[Ty<'tcx>]) -> Self {
1059        Ty::new_tup(interner, tys)
1060    }
1061
1062    fn new_tup_from_iter<It, T>(interner: TyCtxt<'tcx>, iter: It) -> T::Output
1063    where
1064        It: Iterator<Item = T>,
1065        T: CollectAndApply<Self, Self>,
1066    {
1067        Ty::new_tup_from_iter(interner, iter)
1068    }
1069
1070    fn tuple_fields(self) -> &'tcx ty::List<Ty<'tcx>> {
1071        self.tuple_fields()
1072    }
1073
1074    fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1075        self.to_opt_closure_kind()
1076    }
1077
1078    fn from_closure_kind(interner: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Self {
1079        Ty::from_closure_kind(interner, kind)
1080    }
1081
1082    fn from_coroutine_closure_kind(
1083        interner: TyCtxt<'tcx>,
1084        kind: rustc_type_ir::ClosureKind,
1085    ) -> Self {
1086        Ty::from_coroutine_closure_kind(interner, kind)
1087    }
1088
1089    fn new_fn_def(
1090        interner: TyCtxt<'tcx>,
1091        def_id: DefId,
1092        args: ty::Binder<'tcx, ty::GenericArgsRef<'tcx>>,
1093    ) -> Self {
1094        Ty::new_fn_def(interner, def_id, args)
1095    }
1096
1097    fn new_fn_ptr(interner: TyCtxt<'tcx>, sig: ty::Binder<'tcx, ty::FnSig<'tcx>>) -> Self {
1098        Ty::new_fn_ptr(interner, sig)
1099    }
1100
1101    fn new_pat(interner: TyCtxt<'tcx>, ty: Self, pat: ty::Pattern<'tcx>) -> Self {
1102        Ty::new_pat(interner, ty, pat)
1103    }
1104
1105    fn new_unsafe_binder(interner: TyCtxt<'tcx>, ty: ty::Binder<'tcx, Ty<'tcx>>) -> Self {
1106        Ty::new_unsafe_binder(interner, ty)
1107    }
1108
1109    fn new_unit(interner: TyCtxt<'tcx>) -> Self {
1110        interner.types.unit
1111    }
1112
1113    fn new_usize(interner: TyCtxt<'tcx>) -> Self {
1114        interner.types.usize
1115    }
1116
1117    fn discriminant_ty(self, interner: TyCtxt<'tcx>) -> Ty<'tcx> {
1118        self.discriminant_ty(interner)
1119    }
1120
1121    fn has_unsafe_fields(self) -> bool {
1122        Ty::has_unsafe_fields(self)
1123    }
1124}
1125
1126/// Type utilities
1127impl<'tcx> Ty<'tcx> {
1128    // It would be nicer if this returned the value instead of a reference,
1129    // like how `Predicate::kind` and `Region::kind` do. (It would result in
1130    // many fewer subsequent dereferences.) But that gives a small but
1131    // noticeable performance hit. See #126069 for details.
1132    #[inline(always)]
1133    pub fn kind(self) -> &'tcx TyKind<'tcx> {
1134        self.0.0
1135    }
1136
1137    #[inline]
1138    pub fn is_unit(self) -> bool {
1139        match self.kind() {
1140            Tuple(tys) => tys.is_empty(),
1141            _ => false,
1142        }
1143    }
1144
1145    /// Check if type is an `usize`.
1146    #[inline]
1147    pub fn is_usize(self) -> bool {
1148        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Uint(UintTy::Usize) => true,
    _ => false,
}matches!(self.kind(), Uint(UintTy::Usize))
1149    }
1150
1151    /// Check if type is an `usize` or an integral type variable.
1152    #[inline]
1153    pub fn is_usize_like(self) -> bool {
1154        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Uint(UintTy::Usize) | Infer(IntVar(_)) => true,
    _ => false,
}matches!(self.kind(), Uint(UintTy::Usize) | Infer(IntVar(_)))
1155    }
1156
1157    #[inline]
1158    pub fn is_never(self) -> bool {
1159        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Never => true,
    _ => false,
}matches!(self.kind(), Never)
1160    }
1161
1162    #[inline]
1163    pub fn is_primitive(self) -> bool {
1164        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Bool | Char | Int(_) | Uint(_) | Float(_) => true,
    _ => false,
}matches!(self.kind(), Bool | Char | Int(_) | Uint(_) | Float(_))
1165    }
1166
1167    #[inline]
1168    pub fn is_adt(self) -> bool {
1169        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Adt(..) => true,
    _ => false,
}matches!(self.kind(), Adt(..))
1170    }
1171
1172    #[inline]
1173    pub fn is_self_param(self) -> bool {
1174        if let Param(param) = self.kind() {
1175            param.index == 0 && param.name == kw::SelfUpper
1176        } else {
1177            false
1178        }
1179    }
1180
1181    #[inline]
1182    pub fn is_ref(self) -> bool {
1183        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Ref(..) => true,
    _ => false,
}matches!(self.kind(), Ref(..))
1184    }
1185
1186    #[inline]
1187    pub fn is_ty_var(self) -> bool {
1188        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(TyVar(_)) => true,
    _ => false,
}matches!(self.kind(), Infer(TyVar(_)))
1189    }
1190
1191    #[inline]
1192    pub fn ty_vid(self) -> Option<ty::TyVid> {
1193        match self.kind() {
1194            &Infer(TyVar(vid)) => Some(vid),
1195            _ => None,
1196        }
1197    }
1198
1199    #[inline]
1200    pub fn float_vid(self) -> Option<ty::FloatVid> {
1201        match self.kind() {
1202            &Infer(FloatVar(vid)) => Some(vid),
1203            _ => None,
1204        }
1205    }
1206
1207    #[inline]
1208    pub fn is_ty_or_numeric_infer(self) -> bool {
1209        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(_) => true,
    _ => false,
}matches!(self.kind(), Infer(_))
1210    }
1211
1212    #[inline]
1213    pub fn is_phantom_data(self) -> bool {
1214        if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false }
1215    }
1216
1217    #[inline]
1218    pub fn is_unsafe_cell(self) -> bool {
1219        if let Adt(def, _) = self.kind() { def.is_unsafe_cell() } else { false }
1220    }
1221
1222    #[inline]
1223    pub fn is_bool(self) -> bool {
1224        *self.kind() == Bool
1225    }
1226
1227    /// Returns `true` if this type is a `str`.
1228    #[inline]
1229    pub fn is_str(self) -> bool {
1230        *self.kind() == Str
1231    }
1232
1233    /// Returns true if this type is `&str`. The reference's lifetime is ignored.
1234    #[inline]
1235    pub fn is_imm_ref_str(self) -> bool {
1236        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    ty::Ref(_, inner, hir::Mutability::Not) if inner.is_str() => true,
    _ => false,
}matches!(self.kind(), ty::Ref(_, inner, hir::Mutability::Not) if inner.is_str())
1237    }
1238
1239    #[inline]
1240    pub fn is_param(self, index: u32) -> bool {
1241        match self.kind() {
1242            ty::Param(data) => data.index == index,
1243            _ => false,
1244        }
1245    }
1246
1247    #[inline]
1248    pub fn is_slice(self) -> bool {
1249        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Slice(_) => true,
    _ => false,
}matches!(self.kind(), Slice(_))
1250    }
1251
1252    #[inline]
1253    pub fn is_array_slice(self) -> bool {
1254        match self.kind() {
1255            Slice(_) => true,
1256            ty::RawPtr(ty, _) | Ref(_, ty, _) => #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    Slice(_) => true,
    _ => false,
}matches!(ty.kind(), Slice(_)),
1257            _ => false,
1258        }
1259    }
1260
1261    #[inline]
1262    pub fn is_array(self) -> bool {
1263        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Array(..) => true,
    _ => false,
}matches!(self.kind(), Array(..))
1264    }
1265
1266    #[inline]
1267    pub fn is_simd(self) -> bool {
1268        match self.kind() {
1269            Adt(def, _) => def.repr().simd(),
1270            _ => false,
1271        }
1272    }
1273
1274    #[inline]
1275    pub fn is_scalable_vector(self) -> bool {
1276        match self.kind() {
1277            Adt(def, _) => def.repr().scalable(),
1278            _ => false,
1279        }
1280    }
1281
1282    pub fn sequence_element_type(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1283        match self.kind() {
1284            Array(ty, _) | Slice(ty) => *ty,
1285            Str => tcx.types.u8,
1286            _ => crate::util::bug::bug_fmt(format_args!("`sequence_element_type` called on non-sequence value: {0}",
        self))bug!("`sequence_element_type` called on non-sequence value: {}", self),
1287        }
1288    }
1289
1290    pub fn scalable_vector_parts(
1291        self,
1292        tcx: TyCtxt<'tcx>,
1293    ) -> Option<(u16, Ty<'tcx>, NumScalableVectors)> {
1294        let Adt(def, args) = self.kind() else {
1295            return None;
1296        };
1297        let (num_vectors, vec_def) = match def.repr().scalable? {
1298            ScalableElt::ElementCount(_) => (NumScalableVectors::for_non_tuple(), *def),
1299            ScalableElt::Container => (
1300                NumScalableVectors::from_field_count(def.non_enum_variant().fields.len())?,
1301                def.non_enum_variant().fields[FieldIdx::ZERO]
1302                    .ty(tcx, args)
1303                    .skip_norm_wip()
1304                    .ty_adt_def()?,
1305            ),
1306        };
1307        let Some(ScalableElt::ElementCount(element_count)) = vec_def.repr().scalable else {
1308            return None;
1309        };
1310        let variant = vec_def.non_enum_variant();
1311        {
    match (&variant.fields.len(), &1) {
        (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!(variant.fields.len(), 1);
1312        let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1313        Some((element_count, field_ty.skip_norm_wip(), num_vectors))
1314    }
1315
1316    pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {
1317        let Adt(def, args) = self.kind() else {
1318            crate::util::bug::bug_fmt(format_args!("`simd_size_and_type` called on invalid type"))bug!("`simd_size_and_type` called on invalid type")
1319        };
1320        if !def.repr().simd() {
    {
        ::core::panicking::panic_fmt(format_args!("`simd_size_and_type` called on non-SIMD type"));
    }
};assert!(def.repr().simd(), "`simd_size_and_type` called on non-SIMD type");
1321        let variant = def.non_enum_variant();
1322        {
    match (&variant.fields.len(), &1) {
        (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!(variant.fields.len(), 1);
1323        let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1324        let Array(f0_elem_ty, f0_len) = field_ty.skip_norm_wip().kind() else {
1325            crate::util::bug::bug_fmt(format_args!("Simd type has non-array field type {0:?}",
        field_ty))bug!("Simd type has non-array field type {field_ty:?}")
1326        };
1327        // FIXME(repr_simd): https://github.com/rust-lang/rust/pull/78863#discussion_r522784112
1328        // The way we evaluate the `N` in `[T; N]` here only works since we use
1329        // `simd_size_and_type` post-monomorphization. It will probably start to ICE
1330        // if we use it in generic code. See the `simd-array-trait` ui test.
1331        (
1332            f0_len
1333                .try_to_target_usize(tcx)
1334                .expect("expected SIMD field to have definite array size"),
1335            *f0_elem_ty,
1336        )
1337    }
1338
1339    #[inline]
1340    pub fn is_mutable_ptr(self) -> bool {
1341        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    RawPtr(_, hir::Mutability::Mut) | Ref(_, _, hir::Mutability::Mut) => true,
    _ => false,
}matches!(self.kind(), RawPtr(_, hir::Mutability::Mut) | Ref(_, _, hir::Mutability::Mut))
1342    }
1343
1344    /// Get the mutability of the reference or `None` when not a reference
1345    #[inline]
1346    pub fn ref_mutability(self) -> Option<hir::Mutability> {
1347        match self.kind() {
1348            Ref(_, _, mutability) => Some(*mutability),
1349            _ => None,
1350        }
1351    }
1352
1353    #[inline]
1354    pub fn is_raw_ptr(self) -> bool {
1355        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    RawPtr(_, _) => true,
    _ => false,
}matches!(self.kind(), RawPtr(_, _))
1356    }
1357
1358    /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer).
1359    /// `Box` is *not* considered a pointer here!
1360    #[inline]
1361    pub fn is_any_ptr(self) -> bool {
1362        self.is_ref() || self.is_raw_ptr() || self.is_fn_ptr()
1363    }
1364
1365    #[inline]
1366    pub fn is_box(self) -> bool {
1367        match self.kind() {
1368            Adt(def, _) => def.is_box(),
1369            _ => false,
1370        }
1371    }
1372
1373    /// Tests whether this is a Box definitely using the global allocator.
1374    ///
1375    /// If the allocator is still generic, the answer is `false`, but it may
1376    /// later turn out that it does use the global allocator.
1377    #[inline]
1378    pub fn is_box_global(self, tcx: TyCtxt<'tcx>) -> bool {
1379        match self.kind() {
1380            Adt(def, args) if def.is_box() => {
1381                let Some(alloc) = args.get(1) else {
1382                    // Single-argument Box is always global. (for "minicore" tests)
1383                    return true;
1384                };
1385                alloc.expect_ty().ty_adt_def().is_some_and(|alloc_adt| {
1386                    tcx.is_lang_item(alloc_adt.did(), LangItem::GlobalAlloc)
1387                })
1388            }
1389            _ => false,
1390        }
1391    }
1392
1393    pub fn boxed_ty(self) -> Option<Ty<'tcx>> {
1394        match self.kind() {
1395            Adt(def, args) if def.is_box() => Some(args.type_at(0)),
1396            _ => None,
1397        }
1398    }
1399
1400    pub fn pinned_ty(self) -> Option<Ty<'tcx>> {
1401        match self.kind() {
1402            Adt(def, args) if def.is_pin() => Some(args.type_at(0)),
1403            _ => None,
1404        }
1405    }
1406
1407    /// Returns the type, pinnedness, mutability, and the region of a reference (`&T` or `&mut T`)
1408    /// or a pinned-reference type (`Pin<&T>` or `Pin<&mut T>`).
1409    ///
1410    /// Regarding the [`pin_ergonomics`] feature, one of the goals is to make pinned references
1411    /// (`Pin<&T>` and `Pin<&mut T>`) behaves similar to normal references (`&T` and `&mut T`).
1412    /// This function is useful when references and pinned references are processed similarly.
1413    ///
1414    /// [`pin_ergonomics`]: https://github.com/rust-lang/rust/issues/130494
1415    pub fn maybe_pinned_ref(
1416        self,
1417    ) -> Option<(Ty<'tcx>, ty::Pinnedness, ty::Mutability, Region<'tcx>)> {
1418        match self.kind() {
1419            Adt(def, args)
1420                if def.is_pin()
1421                    && let &ty::Ref(region, ty, mutbl) = args.type_at(0).kind() =>
1422            {
1423                Some((ty, ty::Pinnedness::Pinned, mutbl, region))
1424            }
1425            &Ref(region, ty, mutbl) => Some((ty, ty::Pinnedness::Not, mutbl, region)),
1426            _ => None,
1427        }
1428    }
1429
1430    /// Panics if called on any type other than `Box<T>`.
1431    pub fn expect_boxed_ty(self) -> Ty<'tcx> {
1432        self.boxed_ty()
1433            .unwrap_or_else(|| crate::util::bug::bug_fmt(format_args!("`expect_boxed_ty` is called on non-box type {0:?}",
        self))bug!("`expect_boxed_ty` is called on non-box type {:?}", self))
1434    }
1435
1436    /// A scalar type is one that denotes an atomic datum, with no sub-components.
1437    /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1438    /// contents are abstract to rustc.)
1439    #[inline]
1440    pub fn is_scalar(self) -> bool {
1441        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Bool | Char | Int(_) | Float(_) | Uint(_) | FnDef(..) | FnPtr(..) |
        RawPtr(_, _) | Infer(IntVar(_) | FloatVar(_)) => true,
    _ => false,
}matches!(
1442            self.kind(),
1443            Bool | Char
1444                | Int(_)
1445                | Float(_)
1446                | Uint(_)
1447                | FnDef(..)
1448                | FnPtr(..)
1449                | RawPtr(_, _)
1450                | Infer(IntVar(_) | FloatVar(_))
1451        )
1452    }
1453
1454    /// Returns `true` if this type is a floating point type.
1455    #[inline]
1456    pub fn is_floating_point(self) -> bool {
1457        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Float(_) | Infer(FloatVar(_)) => true,
    _ => false,
}matches!(self.kind(), Float(_) | Infer(FloatVar(_)))
1458    }
1459
1460    #[inline]
1461    pub fn is_trait(self) -> bool {
1462        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Dynamic(_, _) => true,
    _ => false,
}matches!(self.kind(), Dynamic(_, _))
1463    }
1464
1465    #[inline]
1466    pub fn is_enum(self) -> bool {
1467        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Adt(adt_def, _) if adt_def.is_enum() => true,
    _ => false,
}matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum())
1468    }
1469
1470    #[inline]
1471    pub fn is_union(self) -> bool {
1472        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Adt(adt_def, _) if adt_def.is_union() => true,
    _ => false,
}matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union())
1473    }
1474
1475    #[inline]
1476    pub fn is_closure(self) -> bool {
1477        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Closure(..) => true,
    _ => false,
}matches!(self.kind(), Closure(..))
1478    }
1479
1480    #[inline]
1481    pub fn is_coroutine(self) -> bool {
1482        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Coroutine(..) => true,
    _ => false,
}matches!(self.kind(), Coroutine(..))
1483    }
1484
1485    #[inline]
1486    pub fn is_coroutine_closure(self) -> bool {
1487        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    CoroutineClosure(..) => true,
    _ => false,
}matches!(self.kind(), CoroutineClosure(..))
1488    }
1489
1490    #[inline]
1491    pub fn is_integral(self) -> bool {
1492        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(IntVar(_)) | Int(_) | Uint(_) => true,
    _ => false,
}matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_))
1493    }
1494
1495    #[inline]
1496    pub fn is_fresh_ty(self) -> bool {
1497        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(FreshTy(_)) => true,
    _ => false,
}matches!(self.kind(), Infer(FreshTy(_)))
1498    }
1499
1500    #[inline]
1501    pub fn is_fresh(self) -> bool {
1502        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)) => true,
    _ => false,
}matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)))
1503    }
1504
1505    #[inline]
1506    pub fn is_char(self) -> bool {
1507        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Char => true,
    _ => false,
}matches!(self.kind(), Char)
1508    }
1509
1510    #[inline]
1511    pub fn is_numeric(self) -> bool {
1512        self.is_integral() || self.is_floating_point()
1513    }
1514
1515    #[inline]
1516    pub fn is_signed(self) -> bool {
1517        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Int(_) => true,
    _ => false,
}matches!(self.kind(), Int(_))
1518    }
1519
1520    #[inline]
1521    pub fn is_ptr_sized_integral(self) -> bool {
1522        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize) => true,
    _ => false,
}matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize))
1523    }
1524
1525    #[inline]
1526    pub fn has_concrete_skeleton(self) -> bool {
1527        !#[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Param(_) | Infer(_) | Error(_) => true,
    _ => false,
}matches!(self.kind(), Param(_) | Infer(_) | Error(_))
1528    }
1529
1530    /// Checks whether a type recursively contains another type
1531    ///
1532    /// Example: `Option<()>` contains `()`
1533    pub fn contains(self, other: Ty<'tcx>) -> bool {
1534        struct ContainsTyVisitor<'tcx>(Ty<'tcx>);
1535
1536        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsTyVisitor<'tcx> {
1537            type Result = ControlFlow<()>;
1538
1539            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1540                if self.0 == t { ControlFlow::Break(()) } else { t.super_visit_with(self) }
1541            }
1542        }
1543
1544        let cf = self.visit_with(&mut ContainsTyVisitor(other));
1545        cf.is_break()
1546    }
1547
1548    /// Checks whether a type recursively contains any closure
1549    ///
1550    /// Example: `Option<{closure@file.rs:4:20}>` returns true
1551    pub fn contains_closure(self) -> bool {
1552        struct ContainsClosureVisitor;
1553
1554        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsClosureVisitor {
1555            type Result = ControlFlow<()>;
1556
1557            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1558                if let ty::Closure(..) = t.kind() {
1559                    ControlFlow::Break(())
1560                } else {
1561                    t.super_visit_with(self)
1562                }
1563            }
1564        }
1565
1566        let cf = self.visit_with(&mut ContainsClosureVisitor);
1567        cf.is_break()
1568    }
1569
1570    /// Returns the deepest `async_drop_in_place::{closure}` implementation.
1571    ///
1572    /// `async_drop_in_place<T>::{closure}`, when T is a coroutine, is a proxy-impl
1573    /// to call async drop poll from impl coroutine.
1574    pub fn find_async_drop_impl_coroutine<F: FnMut(Ty<'tcx>)>(
1575        self,
1576        tcx: TyCtxt<'tcx>,
1577        mut f: F,
1578    ) -> Ty<'tcx> {
1579        if !self.is_coroutine() {
    ::core::panicking::panic("assertion failed: self.is_coroutine()")
};assert!(self.is_coroutine());
1580        let mut cor_ty = self;
1581        let mut ty = cor_ty;
1582        loop {
1583            let ty::Coroutine(def_id, args) = ty.kind() else { return cor_ty };
1584            cor_ty = ty;
1585            f(ty);
1586            if !tcx.is_async_drop_in_place_coroutine(*def_id) {
1587                return cor_ty;
1588            }
1589            ty = args.first().unwrap().expect_ty();
1590        }
1591    }
1592
1593    /// Returns the type of `*ty`.
1594    ///
1595    /// The parameter `explicit` indicates if this is an *explicit* dereference.
1596    /// Some types -- notably raw ptrs -- can only be dereferenced explicitly.
1597    pub fn builtin_deref(self, explicit: bool) -> Option<Ty<'tcx>> {
1598        match *self.kind() {
1599            _ if let Some(boxed) = self.boxed_ty() => Some(boxed),
1600            Ref(_, ty, _) => Some(ty),
1601            RawPtr(ty, _) if explicit => Some(ty),
1602            _ => None,
1603        }
1604    }
1605
1606    /// Returns the type of `ty[i]`.
1607    pub fn builtin_index(self) -> Option<Ty<'tcx>> {
1608        match self.kind() {
1609            Array(ty, _) | Slice(ty) => Some(*ty),
1610            _ => None,
1611        }
1612    }
1613
1614    {}
#[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("fn_sig",
                                    "rustc_middle::ty::sty", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_middle/src/ty/sty.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1614u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn ::tracing::field::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: PolyFnSig<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        { self.kind().fn_sig(tcx) }
    }
}#[tracing::instrument(level = "trace", skip(tcx))]
1615    pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
1616        self.kind().fn_sig(tcx)
1617    }
1618
1619    {}
#[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("unnormalized_fn_sig",
                                    "rustc_middle::ty::sty", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_middle/src/ty/sty.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1619u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn ::tracing::field::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:
                    ty::Unnormalized<'tcx, PolyFnSig<'tcx>> = loop {};
            return __tracing_attr_fake_return;
        }
        { self.kind().unnormalized_fn_sig(tcx) }
    }
}#[tracing::instrument(level = "trace", skip(tcx))]
1620    pub fn unnormalized_fn_sig(self, tcx: TyCtxt<'tcx>) -> ty::Unnormalized<'tcx, PolyFnSig<'tcx>> {
1621        self.kind().unnormalized_fn_sig(tcx)
1622    }
1623
1624    #[inline]
1625    pub fn is_fn(self) -> bool {
1626        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    FnDef(..) | FnPtr(..) => true,
    _ => false,
}matches!(self.kind(), FnDef(..) | FnPtr(..))
1627    }
1628
1629    #[inline]
1630    pub fn is_fn_ptr(self) -> bool {
1631        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    FnPtr(..) => true,
    _ => false,
}matches!(self.kind(), FnPtr(..))
1632    }
1633
1634    #[inline]
1635    pub fn is_opaque(self) -> bool {
1636        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => true,
    _ => false,
}matches!(self.kind(), Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }))
1637    }
1638
1639    #[inline]
1640    pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
1641        match self.kind() {
1642            Adt(adt, _) => Some(*adt),
1643            _ => None,
1644        }
1645    }
1646
1647    /// Returns a list of tuple type arguments.
1648    ///
1649    /// Panics when called on anything but a tuple.
1650    #[inline]
1651    pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> {
1652        match self.kind() {
1653            Tuple(args) => args,
1654            _ => crate::util::bug::bug_fmt(format_args!("tuple_fields called on non-tuple: {0:?}",
        self))bug!("tuple_fields called on non-tuple: {self:?}"),
1655        }
1656    }
1657
1658    /// Returns a list of tuple type arguments, or `None` if `self` isn't a tuple.
1659    #[inline]
1660    pub fn opt_tuple_fields(self) -> Option<&'tcx List<Ty<'tcx>>> {
1661        match self.kind() {
1662            Tuple(args) => Some(args),
1663            _ => None,
1664        }
1665    }
1666
1667    /// If the type contains variants, returns the valid range of variant indices.
1668    //
1669    // FIXME: This requires the optimized MIR in the case of coroutines.
1670    #[inline]
1671    pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
1672        match self.kind() {
1673            TyKind::Adt(adt, _) => Some(adt.variant_range()),
1674            TyKind::Coroutine(def_id, args) => {
1675                Some(args.as_coroutine().variant_range(*def_id, tcx))
1676            }
1677            TyKind::UnsafeBinder(bound_ty) => {
1678                tcx.instantiate_bound_regions_with_erased((*bound_ty).into()).variant_range(tcx)
1679            }
1680            _ => None,
1681        }
1682    }
1683
1684    /// If the type contains variants, returns the variant for `variant_index`.
1685    /// Panics if `variant_index` is out of range.
1686    //
1687    // FIXME: This requires the optimized MIR in the case of coroutines.
1688    #[inline]
1689    pub fn discriminant_for_variant(
1690        self,
1691        tcx: TyCtxt<'tcx>,
1692        variant_index: VariantIdx,
1693    ) -> Option<Discr<'tcx>> {
1694        match self.kind() {
1695            TyKind::Adt(adt, _) if adt.is_enum() => {
1696                Some(adt.discriminant_for_variant(tcx, variant_index))
1697            }
1698            TyKind::Coroutine(def_id, args) => {
1699                Some(args.as_coroutine().discriminant_for_variant(*def_id, tcx, variant_index))
1700            }
1701            TyKind::UnsafeBinder(bound_ty) => tcx
1702                .instantiate_bound_regions_with_erased((*bound_ty).into())
1703                .discriminant_for_variant(tcx, variant_index),
1704            _ => None,
1705        }
1706    }
1707
1708    /// Returns the type of the discriminant of this type.
1709    pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1710        match self.kind() {
1711            ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
1712            ty::Coroutine(_, args) => args.as_coroutine().discr_ty(tcx),
1713
1714            ty::Param(_) | ty::Alias(..) | ty::Infer(ty::TyVar(_)) => {
1715                let assoc_items = tcx.associated_item_def_ids(
1716                    tcx.require_lang_item(LangItem::DiscriminantKind, DUMMY_SP),
1717                );
1718                Ty::new_projection_from_args(
1719                    tcx,
1720                    ty::IsRigid::No,
1721                    assoc_items[0],
1722                    tcx.mk_args(&[self.into()]),
1723                )
1724            }
1725
1726            ty::Pat(ty, _) => ty.discriminant_ty(tcx),
1727            ty::UnsafeBinder(bound_ty) => {
1728                tcx.instantiate_bound_regions_with_erased((*bound_ty).into()).discriminant_ty(tcx)
1729            }
1730
1731            ty::Bool
1732            | ty::Char
1733            | ty::Int(_)
1734            | ty::Uint(_)
1735            | ty::Float(_)
1736            | ty::Adt(..)
1737            | ty::Foreign(_)
1738            | ty::Str
1739            | ty::Array(..)
1740            | ty::Slice(_)
1741            | ty::RawPtr(_, _)
1742            | ty::Ref(..)
1743            | ty::FnDef(..)
1744            | ty::FnPtr(..)
1745            | ty::Dynamic(..)
1746            | ty::Closure(..)
1747            | ty::CoroutineClosure(..)
1748            | ty::CoroutineWitness(..)
1749            | ty::Never
1750            | ty::Tuple(_)
1751            | ty::Error(_)
1752            | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
1753
1754            ty::Bound(..)
1755            | ty::Placeholder(_)
1756            | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1757                crate::util::bug::bug_fmt(format_args!("`discriminant_ty` applied to unexpected type: {0:?}",
        self))bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
1758            }
1759        }
1760    }
1761
1762    /// Returns the type of metadata for (potentially wide) pointers to this type,
1763    /// or the struct tail if the metadata type cannot be determined.
1764    pub fn ptr_metadata_ty_or_tail(
1765        self,
1766        tcx: TyCtxt<'tcx>,
1767        normalize: impl FnMut(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
1768    ) -> Result<Ty<'tcx>, Ty<'tcx>> {
1769        let tail = tcx.struct_tail_raw(self, &ObligationCause::dummy(), normalize, || {});
1770        match tail.kind() {
1771            // Sized types
1772            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1773            | ty::Uint(_)
1774            | ty::Int(_)
1775            | ty::Bool
1776            | ty::Float(_)
1777            | ty::FnDef(..)
1778            | ty::FnPtr(..)
1779            | ty::RawPtr(..)
1780            | ty::Char
1781            | ty::Ref(..)
1782            | ty::Coroutine(..)
1783            | ty::CoroutineWitness(..)
1784            | ty::Array(..)
1785            | ty::Closure(..)
1786            | ty::CoroutineClosure(..)
1787            | ty::Never
1788            | ty::Error(_) => Ok(tcx.types.unit),
1789            // Extern types have metadata = ().
1790            ty::Foreign(..) => Ok(tcx.types.unit),
1791            // If returned by `struct_tail_raw` this is a unit struct
1792            // without any fields, or not a struct, and therefore is Sized.
1793            ty::Adt(..) => Ok(tcx.types.unit),
1794            // If returned by `struct_tail_raw` this is the empty tuple,
1795            // a.k.a. unit type, which is Sized
1796            ty::Tuple(..) => Ok(tcx.types.unit),
1797
1798            ty::Str | ty::Slice(_) => Ok(tcx.types.usize),
1799
1800            ty::Dynamic(_, _) => {
1801                let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, DUMMY_SP);
1802                Ok(tcx.type_of(dyn_metadata).instantiate(tcx, &[tail.into()]).skip_norm_wip())
1803            }
1804
1805            // We don't know the metadata of `self`, but it must be equal to the
1806            // metadata of `tail`.
1807            ty::Param(_) | ty::Alias(..) => Err(tail),
1808
1809            ty::UnsafeBinder(_) => {
    ::core::panicking::panic_fmt(format_args!("not implemented: {0}",
            format_args!("FIXME(unsafe_binder)")));
}unimplemented!("FIXME(unsafe_binder)"),
1810
1811            ty::Infer(ty::TyVar(_))
1812            | ty::Pat(..)
1813            | ty::Bound(..)
1814            | ty::Placeholder(..)
1815            | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => crate::util::bug::bug_fmt(format_args!("`ptr_metadata_ty_or_tail` applied to unexpected type: {0:?} (tail = {1:?})",
        self, tail))bug!(
1816                "`ptr_metadata_ty_or_tail` applied to unexpected type: {self:?} (tail = {tail:?})"
1817            ),
1818        }
1819    }
1820
1821    /// Returns the type of metadata for (potentially wide) pointers to this type.
1822    /// Causes an ICE if the metadata type cannot be determined.
1823    pub fn ptr_metadata_ty(
1824        self,
1825        tcx: TyCtxt<'tcx>,
1826        normalize: impl FnMut(Unnormalized<'tcx, Ty<'tcx>>) -> Ty<'tcx>,
1827    ) -> Ty<'tcx> {
1828        match self.ptr_metadata_ty_or_tail(tcx, normalize) {
1829            Ok(metadata) => metadata,
1830            Err(tail) => crate::util::bug::bug_fmt(format_args!("`ptr_metadata_ty` failed to get metadata for type: {0:?} (tail = {1:?})",
        self, tail))bug!(
1831                "`ptr_metadata_ty` failed to get metadata for type: {self:?} (tail = {tail:?})"
1832            ),
1833        }
1834    }
1835
1836    /// Given a pointer or reference type, returns the type of the *pointee*'s
1837    /// metadata. If it can't be determined exactly (perhaps due to still
1838    /// being generic) then a projection through `ptr::Pointee` will be returned.
1839    ///
1840    /// This is particularly useful for getting the type of the result of
1841    /// [`UnOp::PtrMetadata`](crate::mir::UnOp::PtrMetadata).
1842    ///
1843    /// Panics if `self` is not dereferenceable.
1844    #[track_caller]
1845    pub fn pointee_metadata_ty_or_projection(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1846        let Some(pointee_ty) = self.builtin_deref(true) else {
1847            crate::util::bug::bug_fmt(format_args!("Type {0:?} is not a pointer or reference type",
        self))bug!("Type {self:?} is not a pointer or reference type")
1848        };
1849        if pointee_ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized) {
1850            tcx.types.unit
1851        } else {
1852            match pointee_ty.ptr_metadata_ty_or_tail(tcx, |x| x.skip_norm_wip()) {
1853                Ok(metadata_ty) => metadata_ty,
1854                Err(tail_ty) => {
1855                    let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, DUMMY_SP);
1856                    Ty::new_projection(tcx, ty::IsRigid::No, metadata_def_id, [tail_ty])
1857                }
1858            }
1859        }
1860    }
1861
1862    /// When we create a closure, we record its kind (i.e., what trait
1863    /// it implements, constrained by how it uses its borrows) into its
1864    /// [`ty::ClosureArgs`] or [`ty::CoroutineClosureArgs`] using a type
1865    /// parameter. This is kind of a phantom type, except that the
1866    /// most convenient thing for us to are the integral types. This
1867    /// function converts such a special type into the closure
1868    /// kind. To go the other way, use [`Ty::from_closure_kind`].
1869    ///
1870    /// Note that during type checking, we use an inference variable
1871    /// to represent the closure kind, because it has not yet been
1872    /// inferred. Once upvar inference (in `rustc_hir_analysis/src/check/upvar.rs`)
1873    /// is complete, that type variable will be unified with one of
1874    /// the integral types.
1875    ///
1876    /// ```rust,ignore (snippet of compiler code)
1877    /// if let TyKind::Closure(def_id, args) = closure_ty.kind()
1878    ///     && let Some(closure_kind) = args.as_closure().kind_ty().to_opt_closure_kind()
1879    /// {
1880    ///     println!("{closure_kind:?}");
1881    /// } else if let TyKind::CoroutineClosure(def_id, args) = closure_ty.kind()
1882    ///     && let Some(closure_kind) = args.as_coroutine_closure().kind_ty().to_opt_closure_kind()
1883    /// {
1884    ///     println!("{closure_kind:?}");
1885    /// }
1886    /// ```
1887    ///
1888    /// After upvar analysis, you should instead use [`ty::ClosureArgs::kind()`]
1889    /// or [`ty::CoroutineClosureArgs::kind()`] to assert that the `ClosureKind`
1890    /// has been constrained instead of manually calling this method.
1891    ///
1892    /// ```rust,ignore (snippet of compiler code)
1893    /// if let TyKind::Closure(def_id, args) = closure_ty.kind()
1894    /// {
1895    ///     println!("{:?}", args.as_closure().kind());
1896    /// } else if let TyKind::CoroutineClosure(def_id, args) = closure_ty.kind()
1897    /// {
1898    ///     println!("{:?}", args.as_coroutine_closure().kind());
1899    /// }
1900    /// ```
1901    pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1902        match self.kind() {
1903            Int(int_ty) => match int_ty {
1904                ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
1905                ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1906                ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1907                _ => crate::util::bug::bug_fmt(format_args!("cannot convert type `{0:?}` to a closure kind",
        self))bug!("cannot convert type `{:?}` to a closure kind", self),
1908            },
1909
1910            // "Bound" types appear in canonical queries when the
1911            // closure type is not yet known, and `Placeholder` and `Param`
1912            // may be encountered in generic `AsyncFnKindHelper` goals.
1913            Bound(..) | Placeholder(_) | Param(_) | Infer(_) => None,
1914
1915            Error(_) => Some(ty::ClosureKind::Fn),
1916
1917            _ => crate::util::bug::bug_fmt(format_args!("cannot convert type `{0:?}` to a closure kind",
        self))bug!("cannot convert type `{:?}` to a closure kind", self),
1918        }
1919    }
1920
1921    /// Inverse of [`Ty::to_opt_closure_kind`]. See docs on that method
1922    /// for explanation of the relationship between `Ty` and [`ty::ClosureKind`].
1923    pub fn from_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1924        match kind {
1925            ty::ClosureKind::Fn => tcx.types.i8,
1926            ty::ClosureKind::FnMut => tcx.types.i16,
1927            ty::ClosureKind::FnOnce => tcx.types.i32,
1928        }
1929    }
1930
1931    /// Like [`Ty::to_opt_closure_kind`], but it caps the "maximum" closure kind
1932    /// to `FnMut`. This is because although we have three capability states,
1933    /// `AsyncFn`/`AsyncFnMut`/`AsyncFnOnce`, we only need to distinguish two coroutine
1934    /// bodies: by-ref and by-value.
1935    ///
1936    /// See the definition of `AsyncFn` and `AsyncFnMut` and the `CallRefFuture`
1937    /// associated type for why we don't distinguish [`ty::ClosureKind::Fn`] and
1938    /// [`ty::ClosureKind::FnMut`] for the purpose of the generated MIR bodies.
1939    ///
1940    /// This method should be used when constructing a `Coroutine` out of a
1941    /// `CoroutineClosure`, when the `Coroutine`'s `kind` field is being populated
1942    /// directly from the `CoroutineClosure`'s `kind`.
1943    pub fn from_coroutine_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1944        match kind {
1945            ty::ClosureKind::Fn | ty::ClosureKind::FnMut => tcx.types.i16,
1946            ty::ClosureKind::FnOnce => tcx.types.i32,
1947        }
1948    }
1949
1950    /// Fast path helper for testing if a type is `Sized` or `MetaSized`.
1951    ///
1952    /// Returning true means the type is known to implement the sizedness trait. Returning `false`
1953    /// means nothing -- could be sized, might not be.
1954    ///
1955    /// Note that we could never rely on the fact that a type such as `[_]` is trivially `!Sized`
1956    /// because we could be in a type environment with a bound such as `[_]: Copy`. A function with
1957    /// such a bound obviously never can be called, but that doesn't mean it shouldn't typecheck.
1958    /// This is why this method doesn't return `Option<bool>`.
1959    {}
#[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("has_trivial_sizedness",
                                    "rustc_middle::ty::sty", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_middle/src/ty/sty.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1959u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("sizedness")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("sizedness");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sizedness)
                                                            as &dyn ::tracing::field::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: bool = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match self.kind() {
                ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) | ty::Uint(_) |
                    ty::Int(_) | ty::Bool | ty::Float(_) | ty::FnDef(..) |
                    ty::FnPtr(..) | ty::UnsafeBinder(_) | ty::RawPtr(..) |
                    ty::Char | ty::Ref(..) | ty::Coroutine(..) |
                    ty::CoroutineWitness(..) | ty::Array(..) | ty::Pat(..) |
                    ty::Closure(..) | ty::CoroutineClosure(..) | ty::Never |
                    ty::Error(_) => true,
                ty::Str | ty::Slice(_) | ty::Dynamic(_, _) =>
                    match sizedness {
                        SizedTraitKind::Sized => false,
                        SizedTraitKind::MetaSized => true,
                    },
                ty::Foreign(..) =>
                    match sizedness {
                        SizedTraitKind::Sized | SizedTraitKind::MetaSized => false,
                    },
                ty::Tuple(tys) =>
                    tys.last().is_none_or(|ty|
                            ty.has_trivial_sizedness(tcx, sizedness)),
                ty::Adt(def, args) =>
                    def.sizedness_constraint(tcx,
                            sizedness).is_none_or(|ty|
                            {
                                ty.instantiate(tcx,
                                            args).skip_norm_wip().has_trivial_sizedness(tcx, sizedness)
                            }),
                ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) |
                    ty::Bound(..) => false,
                ty::Infer(ty::TyVar(_)) => false,
                ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) |
                    ty::FreshFloatTy(_)) => {
                    crate::util::bug::bug_fmt(format_args!("`has_trivial_sizedness` applied to unexpected type: {0:?}",
                            self))
                }
            }
        }
    }
}#[instrument(skip(tcx), level = "debug")]
1960    pub fn has_trivial_sizedness(self, tcx: TyCtxt<'tcx>, sizedness: SizedTraitKind) -> bool {
1961        match self.kind() {
1962            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1963            | ty::Uint(_)
1964            | ty::Int(_)
1965            | ty::Bool
1966            | ty::Float(_)
1967            | ty::FnDef(..)
1968            | ty::FnPtr(..)
1969            | ty::UnsafeBinder(_)
1970            | ty::RawPtr(..)
1971            | ty::Char
1972            | ty::Ref(..)
1973            | ty::Coroutine(..)
1974            | ty::CoroutineWitness(..)
1975            | ty::Array(..)
1976            | ty::Pat(..)
1977            | ty::Closure(..)
1978            | ty::CoroutineClosure(..)
1979            | ty::Never
1980            | ty::Error(_) => true,
1981
1982            ty::Str | ty::Slice(_) | ty::Dynamic(_, _) => match sizedness {
1983                SizedTraitKind::Sized => false,
1984                SizedTraitKind::MetaSized => true,
1985            },
1986
1987            ty::Foreign(..) => match sizedness {
1988                SizedTraitKind::Sized | SizedTraitKind::MetaSized => false,
1989            },
1990
1991            ty::Tuple(tys) => tys.last().is_none_or(|ty| ty.has_trivial_sizedness(tcx, sizedness)),
1992
1993            ty::Adt(def, args) => def.sizedness_constraint(tcx, sizedness).is_none_or(|ty| {
1994                ty.instantiate(tcx, args).skip_norm_wip().has_trivial_sizedness(tcx, sizedness)
1995            }),
1996
1997            ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) | ty::Bound(..) => false,
1998
1999            ty::Infer(ty::TyVar(_)) => false,
2000
2001            ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2002                bug!("`has_trivial_sizedness` applied to unexpected type: {:?}", self)
2003            }
2004        }
2005    }
2006
2007    /// Fast path helper for primitives which are always `Copy` and which
2008    /// have a side-effect-free `Clone` impl.
2009    ///
2010    /// Returning true means the type is known to be pure and `Copy+Clone`.
2011    /// Returning `false` means nothing -- could be `Copy`, might not be.
2012    ///
2013    /// This is mostly useful for optimizations, as these are the types
2014    /// on which we can replace cloning with dereferencing.
2015    pub fn is_trivially_pure_clone_copy(self) -> bool {
2016        match self.kind() {
2017            ty::Bool | ty::Char | ty::Never => true,
2018
2019            // These aren't even `Clone`
2020            ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
2021
2022            ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
2023            | ty::Int(..)
2024            | ty::Uint(..)
2025            | ty::Float(..) => true,
2026
2027            // ZST which can't be named are fine.
2028            ty::FnDef(..) => true,
2029
2030            ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
2031
2032            // A 100-tuple isn't "trivial", so doing this only for reasonable sizes.
2033            ty::Tuple(field_tys) => {
2034                field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
2035            }
2036
2037            ty::Pat(ty, _) => ty.is_trivially_pure_clone_copy(),
2038
2039            // Sometimes traits aren't implemented for every ABI or arity,
2040            // because we can't be generic over everything yet.
2041            ty::FnPtr(..) => false,
2042
2043            // Definitely absolutely not copy.
2044            ty::Ref(_, _, hir::Mutability::Mut) => false,
2045
2046            // The standard library has a blanket Copy impl for shared references and raw pointers,
2047            // for all unsized types.
2048            ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => true,
2049
2050            ty::Coroutine(..) | ty::CoroutineWitness(..) => false,
2051
2052            // Might be, but not "trivial" so just giving the safe answer.
2053            ty::Adt(..) | ty::Closure(..) | ty::CoroutineClosure(..) => false,
2054
2055            ty::UnsafeBinder(_) => false,
2056
2057            // Needs normalization or revealing to determine, so no is the safe answer.
2058            ty::Alias(..) => false,
2059
2060            ty::Param(..) | ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(..) => {
2061                false
2062            }
2063        }
2064    }
2065
2066    pub fn is_trivially_wf(self, tcx: TyCtxt<'tcx>) -> bool {
2067        match *self.kind() {
2068            ty::Bool
2069            | ty::Char
2070            | ty::Int(_)
2071            | ty::Uint(_)
2072            | ty::Float(_)
2073            | ty::Str
2074            | ty::Never
2075            | ty::Param(_)
2076            | ty::Placeholder(_)
2077            | ty::Bound(..) => true,
2078
2079            ty::Slice(ty) => {
2080                ty.is_trivially_wf(tcx) && ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
2081            }
2082            ty::RawPtr(ty, _) => ty.is_trivially_wf(tcx),
2083
2084            ty::FnPtr(sig_tys, _) => {
2085                sig_tys.skip_binder().inputs_and_output.iter().all(|ty| ty.is_trivially_wf(tcx))
2086            }
2087            ty::Ref(_, ty, _) => ty.is_global() && ty.is_trivially_wf(tcx),
2088
2089            ty::Infer(infer) => match infer {
2090                ty::TyVar(_) => false,
2091                ty::IntVar(_) | ty::FloatVar(_) => true,
2092                ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => true,
2093            },
2094
2095            ty::Adt(_, _)
2096            | ty::Tuple(_)
2097            | ty::Array(..)
2098            | ty::Foreign(_)
2099            | ty::Pat(_, _)
2100            | ty::FnDef(..)
2101            | ty::UnsafeBinder(..)
2102            | ty::Dynamic(..)
2103            | ty::Closure(..)
2104            | ty::CoroutineClosure(..)
2105            | ty::Coroutine(..)
2106            | ty::CoroutineWitness(..)
2107            | ty::Alias(..)
2108            | ty::Error(_) => false,
2109        }
2110    }
2111
2112    /// If `self` is a primitive, return its [`Symbol`].
2113    pub fn primitive_symbol(self) -> Option<Symbol> {
2114        match self.kind() {
2115            ty::Bool => Some(sym::bool),
2116            ty::Char => Some(sym::char),
2117            ty::Float(f) => match f {
2118                ty::FloatTy::F16 => Some(sym::f16),
2119                ty::FloatTy::F32 => Some(sym::f32),
2120                ty::FloatTy::F64 => Some(sym::f64),
2121                ty::FloatTy::F128 => Some(sym::f128),
2122            },
2123            ty::Int(f) => match f {
2124                ty::IntTy::Isize => Some(sym::isize),
2125                ty::IntTy::I8 => Some(sym::i8),
2126                ty::IntTy::I16 => Some(sym::i16),
2127                ty::IntTy::I32 => Some(sym::i32),
2128                ty::IntTy::I64 => Some(sym::i64),
2129                ty::IntTy::I128 => Some(sym::i128),
2130            },
2131            ty::Uint(f) => match f {
2132                ty::UintTy::Usize => Some(sym::usize),
2133                ty::UintTy::U8 => Some(sym::u8),
2134                ty::UintTy::U16 => Some(sym::u16),
2135                ty::UintTy::U32 => Some(sym::u32),
2136                ty::UintTy::U64 => Some(sym::u64),
2137                ty::UintTy::U128 => Some(sym::u128),
2138            },
2139            ty::Str => Some(sym::str),
2140            _ => None,
2141        }
2142    }
2143
2144    pub fn is_c_void(self, tcx: TyCtxt<'_>) -> bool {
2145        match self.kind() {
2146            ty::Adt(adt, _) => tcx.is_lang_item(adt.did(), LangItem::CVoid),
2147            _ => false,
2148        }
2149    }
2150
2151    pub fn is_async_drop_in_place_coroutine(self, tcx: TyCtxt<'_>) -> bool {
2152        match self.kind() {
2153            ty::Coroutine(def, ..) => tcx.is_async_drop_in_place_coroutine(*def),
2154            _ => false,
2155        }
2156    }
2157
2158    /// Returns `true` when the outermost type cannot be further normalized,
2159    /// resolved, or instantiated. This includes all primitive types, but also
2160    /// things like ADTs and trait objects, since even if their arguments or
2161    /// nested types may be further simplified, the outermost [`TyKind`] or
2162    /// type constructor remains the same.
2163    pub fn is_known_rigid(self) -> bool {
2164        self.kind().is_known_rigid()
2165    }
2166
2167    /// Iterator that walks `self` and any types reachable from
2168    /// `self`, in depth-first order. Note that just walks the types
2169    /// that appear in `self`, it does not descend into the fields of
2170    /// structs or variants. For example:
2171    ///
2172    /// ```text
2173    /// isize => { isize }
2174    /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2175    /// [isize] => { [isize], isize }
2176    /// ```
2177    pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
2178        TypeWalker::new(self.into())
2179    }
2180
2181    /// Returns `true` if this is a `MaybeDangling<T>`-like type, i.e., a type whose inner
2182    /// references are not required to be dereferenceable and are not reborrowed.
2183    #[inline]
2184    pub fn is_like_maybe_dangling(self) -> bool {
2185        match self.kind() {
2186            ty::Adt(def, _) => {
2187                // ManuallyDrop is "natively" like maybe-dangling so that we don't have
2188                // to nest field types even deeper.
2189                def.flags().contains(AdtFlags::IS_MAYBE_DANGLING)
2190                    || def.flags().contains(AdtFlags::IS_MANUALLY_DROP)
2191            }
2192            ty::Closure(..) | ty::Coroutine(..) | ty::CoroutineClosure(..) => true,
2193            _ => false,
2194        }
2195    }
2196}
2197
2198impl<'tcx> rustc_type_ir::inherent::Tys<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> {
2199    fn inputs(self) -> &'tcx [Ty<'tcx>] {
2200        self.split_last().unwrap().1
2201    }
2202
2203    fn output(self) -> Ty<'tcx> {
2204        *self.split_last().unwrap().0
2205    }
2206}
2207
2208impl<'tcx> rustc_type_ir::inherent::Symbol<TyCtxt<'tcx>> for Symbol {
2209    const KW_UNDERSCORE_LIFETIME: Self = kw::UnderscoreLifetime;
2210    const KW_STATIC_LIFETIME: Self = kw::StaticLifetime;
2211    const SYM_ANON: Self = sym::anon;
2212}
2213
2214// Some types are used a lot. Make sure they don't unintentionally get bigger.
2215#[cfg(target_pointer_width = "64")]
2216mod size_asserts {
2217    use rustc_data_structures::static_assert_size;
2218
2219    use super::*;
2220    // tidy-alphabetical-start
2221    const _: [(); 32] = [(); ::std::mem::size_of::<TyKind<'_>>()];static_assert_size!(TyKind<'_>, 32);
2222    const _: [(); 40] =
    [(); ::std::mem::size_of::<ty::WithCachedTypeInfo<TyKind<'_>>>()];static_assert_size!(ty::WithCachedTypeInfo<TyKind<'_>>, 40);
2223    // tidy-alphabetical-end
2224}