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::LangItem;
14use rustc_hir::def_id::DefId;
15use rustc_macros::{HashStable, 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::{self as ir, BoundVar, CollectAndApply, TypeVisitableExt, elaborate};
21use tracing::instrument;
22use ty::util::IntTypeExt;
23
24use super::GenericParamDefKind;
25use crate::infer::canonical::Canonical;
26use crate::traits::ObligationCause;
27use crate::ty::InferTy::*;
28use crate::ty::{
29    self, AdtDef, Const, Discr, GenericArg, GenericArgs, GenericArgsRef, List, ParamEnv, Region,
30    Ty, TyCtxt, TypeFlags, TypeSuperVisitable, TypeVisitable, TypeVisitor, UintTy, ValTree,
31};
32
33// Re-export and re-parameterize some `I = TyCtxt<'tcx>` types here
34#[rustc_diagnostic_item = "TyKind"]
35pub type TyKind<'tcx> = ir::TyKind<TyCtxt<'tcx>>;
36pub type TypeAndMut<'tcx> = ir::TypeAndMut<TyCtxt<'tcx>>;
37pub type AliasTy<'tcx> = ir::AliasTy<TyCtxt<'tcx>>;
38pub type AliasTyKind<'tcx> = ir::AliasTyKind<TyCtxt<'tcx>>;
39pub type FnSig<'tcx> = ir::FnSig<TyCtxt<'tcx>>;
40pub type Binder<'tcx, T> = ir::Binder<TyCtxt<'tcx>, T>;
41pub type EarlyBinder<'tcx, T> = ir::EarlyBinder<TyCtxt<'tcx>, T>;
42pub type TypingMode<'tcx> = ir::TypingMode<TyCtxt<'tcx>>;
43pub type TypingModeEqWrapper<'tcx> = ir::TypingModeEqWrapper<TyCtxt<'tcx>>;
44pub type Placeholder<'tcx, T> = ir::Placeholder<TyCtxt<'tcx>, T>;
45pub type PlaceholderRegion<'tcx> = ir::PlaceholderRegion<TyCtxt<'tcx>>;
46pub type PlaceholderType<'tcx> = ir::PlaceholderType<TyCtxt<'tcx>>;
47pub type PlaceholderConst<'tcx> = ir::PlaceholderConst<TyCtxt<'tcx>>;
48pub type BoundTy<'tcx> = ir::BoundTy<TyCtxt<'tcx>>;
49pub type BoundConst<'tcx> = ir::BoundConst<TyCtxt<'tcx>>;
50pub type BoundRegion<'tcx> = ir::BoundRegion<TyCtxt<'tcx>>;
51pub type BoundVariableKind<'tcx> = ir::BoundVariableKind<TyCtxt<'tcx>>;
52pub type BoundRegionKind<'tcx> = ir::BoundRegionKind<TyCtxt<'tcx>>;
53pub type BoundTyKind<'tcx> = ir::BoundTyKind<TyCtxt<'tcx>>;
54
55pub trait Article {
56    fn article(&self) -> &'static str;
57}
58
59impl<'tcx> Article for TyKind<'tcx> {
60    /// Get the article ("a" or "an") to use with this type.
61    fn article(&self) -> &'static str {
62        match self {
63            Int(_) | Float(_) | Array(_, _) => "an",
64            Adt(def, _) if def.is_enum() => "an",
65            // This should never happen, but ICEing and causing the user's code
66            // to not compile felt too harsh.
67            Error(_) => "a",
68            _ => "a",
69        }
70    }
71}
72
73impl<'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(layout.field_tys[*field].ty).instantiate(tcx,
                                        self.args)
                                }
                            })
                })
    }
    #[doc =
    " This is the types of the fields of a coroutine which are not stored in a"]
    #[doc = " variant."]
    #[inline]
    fn prefix_tys(self) -> &'tcx List<Ty<'tcx>> { self.upvar_tys() }
}#[extension(pub trait CoroutineArgsExt<'tcx>)]
74impl<'tcx> ty::CoroutineArgs<TyCtxt<'tcx>> {
75    /// Coroutine has not been resumed yet.
76    const UNRESUMED: usize = 0;
77    /// Coroutine has returned or is completed.
78    const RETURNED: usize = 1;
79    /// Coroutine has been poisoned.
80    const POISONED: usize = 2;
81    /// Number of variants to reserve in coroutine state. Corresponds to
82    /// `UNRESUMED` (beginning of a coroutine) and `RETURNED`/`POISONED`
83    /// (end of a coroutine) states.
84    const RESERVED_VARIANTS: usize = 3;
85
86    const UNRESUMED_NAME: &'static str = "Unresumed";
87    const RETURNED_NAME: &'static str = "Returned";
88    const POISONED_NAME: &'static str = "Panicked";
89
90    /// The valid variant indices of this coroutine.
91    #[inline]
92    fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
93        // FIXME requires optimized MIR
94        FIRST_VARIANT..tcx.coroutine_layout(def_id, self.args).unwrap().variant_fields.next_index()
95    }
96
97    /// The discriminant for the given variant. Panics if the `variant_index` is
98    /// out of range.
99    #[inline]
100    fn discriminant_for_variant(
101        &self,
102        def_id: DefId,
103        tcx: TyCtxt<'tcx>,
104        variant_index: VariantIdx,
105    ) -> Discr<'tcx> {
106        // Coroutines don't support explicit discriminant values, so they are
107        // the same as the variant index.
108        assert!(self.variant_range(def_id, tcx).contains(&variant_index));
109        Discr { val: variant_index.as_usize() as u128, ty: self.discr_ty(tcx) }
110    }
111
112    /// The set of all discriminants for the coroutine, enumerated with their
113    /// variant indices.
114    #[inline]
115    fn discriminants(
116        self,
117        def_id: DefId,
118        tcx: TyCtxt<'tcx>,
119    ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> {
120        self.variant_range(def_id, tcx).map(move |index| {
121            (index, Discr { val: index.as_usize() as u128, ty: self.discr_ty(tcx) })
122        })
123    }
124
125    /// Calls `f` with a reference to the name of the enumerator for the given
126    /// variant `v`.
127    fn variant_name(v: VariantIdx) -> Cow<'static, str> {
128        match v.as_usize() {
129            Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
130            Self::RETURNED => Cow::from(Self::RETURNED_NAME),
131            Self::POISONED => Cow::from(Self::POISONED_NAME),
132            _ => Cow::from(format!("Suspend{}", v.as_usize() - Self::RESERVED_VARIANTS)),
133        }
134    }
135
136    /// The type of the state discriminant used in the coroutine type.
137    #[inline]
138    fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
139        tcx.types.u32
140    }
141
142    /// This returns the types of the MIR locals which had to be stored across suspension points.
143    /// It is calculated in rustc_mir_transform::coroutine::StateTransform.
144    /// All the types here must be in the tuple in CoroutineInterior.
145    ///
146    /// The locals are grouped by their variant number. Note that some locals may
147    /// be repeated in multiple variants.
148    #[inline]
149    fn state_tys(
150        self,
151        def_id: DefId,
152        tcx: TyCtxt<'tcx>,
153    ) -> impl Iterator<Item: Iterator<Item = Ty<'tcx>>> {
154        let layout = tcx.coroutine_layout(def_id, self.args).unwrap();
155        layout.variant_fields.iter().map(move |variant| {
156            variant.iter().map(move |field| {
157                if tcx.is_async_drop_in_place_coroutine(def_id) {
158                    layout.field_tys[*field].ty
159                } else {
160                    ty::EarlyBinder::bind(layout.field_tys[*field].ty).instantiate(tcx, self.args)
161                }
162            })
163        })
164    }
165
166    /// This is the types of the fields of a coroutine which are not stored in a
167    /// variant.
168    #[inline]
169    fn prefix_tys(self) -> &'tcx List<Ty<'tcx>> {
170        self.upvar_tys()
171    }
172}
173
174#[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]
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, '__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
            for UpvarArgs<'tcx> {
            #[inline]
            fn hash_stable(&self,
                __hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                ::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
                match *self {
                    UpvarArgs::Closure(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    UpvarArgs::Coroutine(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    UpvarArgs::CoroutineClosure(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable, 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)]
175pub enum UpvarArgs<'tcx> {
176    Closure(GenericArgsRef<'tcx>),
177    Coroutine(GenericArgsRef<'tcx>),
178    CoroutineClosure(GenericArgsRef<'tcx>),
179}
180
181impl<'tcx> UpvarArgs<'tcx> {
182    /// Returns an iterator over the list of types of captured paths by the closure/coroutine.
183    /// In case there was a type error in figuring out the types of the captured path, an
184    /// empty iterator is returned.
185    #[inline]
186    pub fn upvar_tys(self) -> &'tcx List<Ty<'tcx>> {
187        let tupled_tys = match self {
188            UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(),
189            UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(),
190            UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().tupled_upvars_ty(),
191        };
192
193        match tupled_tys.kind() {
194            TyKind::Error(_) => ty::List::empty(),
195            TyKind::Tuple(..) => self.tupled_upvars_ty().tuple_fields(),
196            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"),
197            ty => crate::util::bug::bug_fmt(format_args!("Unexpected representation of upvar types tuple {0:?}",
        ty))bug!("Unexpected representation of upvar types tuple {:?}", ty),
198        }
199    }
200
201    #[inline]
202    pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
203        match self {
204            UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(),
205            UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(),
206            UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().tupled_upvars_ty(),
207        }
208    }
209}
210
211/// An inline const is modeled like
212/// ```ignore (illustrative)
213/// const InlineConst<'l0...'li, T0...Tj, R>: R;
214/// ```
215/// where:
216///
217/// - 'l0...'li and T0...Tj are the generic parameters
218///   inherited from the item that defined the inline const,
219/// - R represents the type of the constant.
220///
221/// When the inline const is instantiated, `R` is instantiated as the actual inferred
222/// type of the constant. The reason that `R` is represented as an extra type parameter
223/// is the same reason that [`ty::ClosureArgs`] have `CS` and `U` as type parameters:
224/// inline const can reference lifetimes that are internal to the creating function.
225#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for InlineConstArgs<'tcx> { }Copy, #[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)]
226pub struct InlineConstArgs<'tcx> {
227    /// Generic parameters from the enclosing item,
228    /// concatenated with the inferred type of the constant.
229    pub args: GenericArgsRef<'tcx>,
230}
231
232/// Struct returned by `split()`.
233pub struct InlineConstArgsParts<'tcx, T> {
234    pub parent_args: &'tcx [GenericArg<'tcx>],
235    pub ty: T,
236}
237
238impl<'tcx> InlineConstArgs<'tcx> {
239    /// Construct `InlineConstArgs` from `InlineConstArgsParts`.
240    pub fn new(
241        tcx: TyCtxt<'tcx>,
242        parts: InlineConstArgsParts<'tcx, Ty<'tcx>>,
243    ) -> InlineConstArgs<'tcx> {
244        InlineConstArgs {
245            args: tcx.mk_args_from_iter(
246                parts.parent_args.iter().copied().chain(std::iter::once(parts.ty.into())),
247            ),
248        }
249    }
250
251    /// Divides the inline const args into their respective components.
252    /// The ordering assumed here must match that used by `InlineConstArgs::new` above.
253    fn split(self) -> InlineConstArgsParts<'tcx, GenericArg<'tcx>> {
254        match self.args[..] {
255            [ref parent_args @ .., ty] => InlineConstArgsParts { parent_args, ty },
256            _ => crate::util::bug::bug_fmt(format_args!("inline const args missing synthetics"))bug!("inline const args missing synthetics"),
257        }
258    }
259
260    /// Returns the generic parameters of the inline const's parent.
261    pub fn parent_args(self) -> &'tcx [GenericArg<'tcx>] {
262        self.split().parent_args
263    }
264
265    /// Returns the type of this inline const.
266    pub fn ty(self) -> Ty<'tcx> {
267        self.split().ty.expect_ty()
268    }
269}
270
271pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>;
272pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>;
273
274#[derive(#[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::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> {
        match ::core::cmp::PartialOrd::partial_cmp(&self.index, &other.index)
            {
            ::core::option::Option::Some(::core::cmp::Ordering::Equal) =>
                ::core::cmp::PartialOrd::partial_cmp(&self.name, &other.name),
            cmp => cmp,
        }
    }
}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) {
                match *self {
                    ParamTy { index: ref __binding_0, name: ref __binding_1 } =>
                        {
                        ::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)]
275#[derive(const _: () =
    {
        impl<'__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
            for ParamTy {
            #[inline]
            fn hash_stable(&self,
                __hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                match *self {
                    ParamTy { index: ref __binding_0, name: ref __binding_1 } =>
                        {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                        { __binding_1.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable)]
276pub struct ParamTy {
277    pub index: u32,
278    pub name: Symbol,
279}
280
281impl rustc_type_ir::inherent::ParamLike for ParamTy {
282    fn index(self) -> u32 {
283        self.index
284    }
285}
286
287impl<'tcx> ParamTy {
288    pub fn new(index: u32, name: Symbol) -> ParamTy {
289        ParamTy { index, name }
290    }
291
292    pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
293        ParamTy::new(def.index, def.name)
294    }
295
296    #[inline]
297    pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
298        Ty::new_param(tcx, self.index, self.name)
299    }
300
301    pub fn span_from_generics(self, tcx: TyCtxt<'tcx>, item_with_generics: DefId) -> Span {
302        let generics = tcx.generics_of(item_with_generics);
303        let type_param = generics.type_param(self, tcx);
304        tcx.def_span(type_param.def_id)
305    }
306}
307
308#[derive(#[automatically_derived]
impl ::core::marker::Copy for ParamConst { }Copy, #[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) {
                match *self {
                    ParamConst { index: ref __binding_0, name: ref __binding_1 }
                        => {
                        ::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::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> {
        match ::core::cmp::PartialOrd::partial_cmp(&self.index, &other.index)
            {
            ::core::option::Option::Some(::core::cmp::Ordering::Equal) =>
                ::core::cmp::PartialOrd::partial_cmp(&self.name, &other.name),
            cmp => cmp,
        }
    }
}PartialOrd)]
309#[derive(const _: () =
    {
        impl<'__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
            for ParamConst {
            #[inline]
            fn hash_stable(&self,
                __hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                match *self {
                    ParamConst { index: ref __binding_0, name: ref __binding_1 }
                        => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                        { __binding_1.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable)]
310pub struct ParamConst {
311    pub index: u32,
312    pub name: Symbol,
313}
314
315impl rustc_type_ir::inherent::ParamLike for ParamConst {
316    fn index(self) -> u32 {
317        self.index
318    }
319}
320
321impl ParamConst {
322    pub fn new(index: u32, name: Symbol) -> ParamConst {
323        ParamConst { index, name }
324    }
325
326    pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
327        ParamConst::new(def.index, def.name)
328    }
329
330    #[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("compiler/rustc_middle/src/ty/sty.rs"),
                                    ::tracing_core::__macro_support::Option::Some(330u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
                                    ::tracing_core::field::FieldSet::new(&["self", "env"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&env)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Ty<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut candidates =
                env.caller_bounds().iter().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")]
331    pub fn find_const_ty_from_env<'tcx>(self, env: ParamEnv<'tcx>) -> Ty<'tcx> {
332        let mut candidates = env.caller_bounds().iter().filter_map(|clause| {
333            // `ConstArgHasType` are never desugared to be higher ranked.
334            match clause.kind().skip_binder() {
335                ty::ClauseKind::ConstArgHasType(param_ct, ty) => {
336                    assert!(!(param_ct, ty).has_escaping_bound_vars());
337
338                    match param_ct.kind() {
339                        ty::ConstKind::Param(param_ct) if param_ct.index == self.index => Some(ty),
340                        _ => None,
341                    }
342                }
343                _ => None,
344            }
345        });
346
347        // N.B. it may be tempting to fix ICEs by making this function return
348        // `Option<Ty<'tcx>>` instead of `Ty<'tcx>`; however, this is generally
349        // considered to be a bandaid solution, since it hides more important
350        // underlying issues with how we construct generics and predicates of
351        // items. It's advised to fix the underlying issue rather than trying
352        // to modify this function.
353        let ty = candidates.next().unwrap_or_else(|| {
354            bug!("cannot find `{self:?}` in param-env: {env:#?}");
355        });
356        assert!(
357            candidates.next().is_none(),
358            "did not expect duplicate `ConstParamHasTy` for `{self:?}` in param-env: {env:#?}"
359        );
360        ty
361    }
362}
363
364/// Constructors for `Ty`
365impl<'tcx> Ty<'tcx> {
366    /// Avoid using this in favour of more specific `new_*` methods, where possible.
367    /// The more specific methods will often optimize their creation.
368    #[allow(rustc::usage_of_ty_tykind)]
369    #[inline]
370    fn new(tcx: TyCtxt<'tcx>, st: TyKind<'tcx>) -> Ty<'tcx> {
371        tcx.mk_ty_from_kind(st)
372    }
373
374    #[inline]
375    pub fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Ty<'tcx> {
376        Ty::new(tcx, TyKind::Infer(infer))
377    }
378
379    #[inline]
380    pub fn new_var(tcx: TyCtxt<'tcx>, v: ty::TyVid) -> Ty<'tcx> {
381        // Use a pre-interned one when possible.
382        tcx.types
383            .ty_vars
384            .get(v.as_usize())
385            .copied()
386            .unwrap_or_else(|| Ty::new(tcx, Infer(TyVar(v))))
387    }
388
389    #[inline]
390    pub fn new_int_var(tcx: TyCtxt<'tcx>, v: ty::IntVid) -> Ty<'tcx> {
391        Ty::new_infer(tcx, IntVar(v))
392    }
393
394    #[inline]
395    pub fn new_float_var(tcx: TyCtxt<'tcx>, v: ty::FloatVid) -> Ty<'tcx> {
396        Ty::new_infer(tcx, FloatVar(v))
397    }
398
399    #[inline]
400    pub fn new_fresh(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
401        // Use a pre-interned one when possible.
402        tcx.types
403            .fresh_tys
404            .get(n as usize)
405            .copied()
406            .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshTy(n)))
407    }
408
409    #[inline]
410    pub fn new_fresh_int(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
411        // Use a pre-interned one when possible.
412        tcx.types
413            .fresh_int_tys
414            .get(n as usize)
415            .copied()
416            .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshIntTy(n)))
417    }
418
419    #[inline]
420    pub fn new_fresh_float(tcx: TyCtxt<'tcx>, n: u32) -> Ty<'tcx> {
421        // Use a pre-interned one when possible.
422        tcx.types
423            .fresh_float_tys
424            .get(n as usize)
425            .copied()
426            .unwrap_or_else(|| Ty::new_infer(tcx, ty::FreshFloatTy(n)))
427    }
428
429    #[inline]
430    pub fn new_param(tcx: TyCtxt<'tcx>, index: u32, name: Symbol) -> Ty<'tcx> {
431        Ty::new(tcx, Param(ParamTy { index, name }))
432    }
433
434    #[inline]
435    pub fn new_bound(
436        tcx: TyCtxt<'tcx>,
437        index: ty::DebruijnIndex,
438        bound_ty: ty::BoundTy<'tcx>,
439    ) -> Ty<'tcx> {
440        // Use a pre-interned one when possible.
441        if let ty::BoundTy { var, kind: ty::BoundTyKind::Anon } = bound_ty
442            && let Some(inner) = tcx.types.anon_bound_tys.get(index.as_usize())
443            && let Some(ty) = inner.get(var.as_usize()).copied()
444        {
445            ty
446        } else {
447            Ty::new(tcx, Bound(ty::BoundVarIndexKind::Bound(index), bound_ty))
448        }
449    }
450
451    #[inline]
452    pub fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: BoundVar) -> Ty<'tcx> {
453        // Use a pre-interned one when possible.
454        if let Some(ty) = tcx.types.anon_canonical_bound_tys.get(var.as_usize()).copied() {
455            ty
456        } else {
457            Ty::new(
458                tcx,
459                Bound(
460                    ty::BoundVarIndexKind::Canonical,
461                    ty::BoundTy { var, kind: ty::BoundTyKind::Anon },
462                ),
463            )
464        }
465    }
466
467    #[inline]
468    pub fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType<'tcx>) -> Ty<'tcx> {
469        Ty::new(tcx, Placeholder(placeholder))
470    }
471
472    #[inline]
473    pub fn new_alias(tcx: TyCtxt<'tcx>, alias_ty: ty::AliasTy<'tcx>) -> Ty<'tcx> {
474        if true {
    match (alias_ty.kind, tcx.def_kind(alias_ty.kind.def_id())) {
        (ty::Opaque { .. }, DefKind::OpaqueTy) |
            (ty::Projection { .. } | ty::Inherent { .. }, DefKind::AssocTy) |
            (ty::Free { .. }, DefKind::TyAlias) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "(ty::Opaque { .. }, DefKind::OpaqueTy) |\n(ty::Projection { .. } | ty::Inherent { .. }, DefKind::AssocTy) |\n(ty::Free { .. }, DefKind::TyAlias)",
                ::core::option::Option::None);
        }
    };
};debug_assert_matches!(
475            (alias_ty.kind, tcx.def_kind(alias_ty.kind.def_id())),
476            (ty::Opaque { .. }, DefKind::OpaqueTy)
477                | (ty::Projection { .. } | ty::Inherent { .. }, DefKind::AssocTy)
478                | (ty::Free { .. }, DefKind::TyAlias)
479        );
480        Ty::new(tcx, Alias(alias_ty))
481    }
482
483    #[inline]
484    pub fn new_pat(tcx: TyCtxt<'tcx>, base: Ty<'tcx>, pat: ty::Pattern<'tcx>) -> Ty<'tcx> {
485        Ty::new(tcx, Pat(base, pat))
486    }
487
488    #[inline]
489    pub fn new_field_representing_type(
490        tcx: TyCtxt<'tcx>,
491        base: Ty<'tcx>,
492        variant: VariantIdx,
493        field: FieldIdx,
494    ) -> Ty<'tcx> {
495        let Some(did) = tcx.lang_items().field_representing_type() else {
496            crate::util::bug::bug_fmt(format_args!("could not locate the `FieldRepresentingType` lang item"))bug!("could not locate the `FieldRepresentingType` lang item")
497        };
498        let def = tcx.adt_def(did);
499        let args = tcx.mk_args(&[
500            base.into(),
501            Const::new_value(
502                tcx,
503                ValTree::from_scalar_int(tcx, variant.as_u32().into()),
504                tcx.types.u32,
505            )
506            .into(),
507            Const::new_value(
508                tcx,
509                ValTree::from_scalar_int(tcx, field.as_u32().into()),
510                tcx.types.u32,
511            )
512            .into(),
513        ]);
514        Ty::new_adt(tcx, def, args)
515    }
516
517    #[inline]
518    #[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("compiler/rustc_middle/src/ty/sty.rs"),
                                    ::tracing_core::__macro_support::Option::Some(518u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
                                    ::tracing_core::field::FieldSet::new(&["def_id", "args"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Ty<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            Ty::new_alias(tcx,
                AliasTy::new_from_args(tcx, ty::Opaque { def_id }, args))
        }
    }
}#[instrument(level = "debug", skip(tcx))]
519    pub fn new_opaque(tcx: TyCtxt<'tcx>, def_id: DefId, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
520        Ty::new_alias(tcx, 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::InlineConst
655                | DefKind::OpaqueTy
656                | DefKind::Field
657                | DefKind::LifetimeParam
658                | DefKind::GlobalAsm
659                | DefKind::Impl { .. }
660                | DefKind::Closure
661                | DefKind::SyntheticCoroutineBody => {
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    #[inline]
707    pub fn new_fn_def(
708        tcx: TyCtxt<'tcx>,
709        def_id: DefId,
710        args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
711    ) -> Ty<'tcx> {
712        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!(
713            tcx.def_kind(def_id),
714            DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)
715        );
716        let args = tcx.check_and_mk_args(def_id, args);
717        Ty::new(tcx, FnDef(def_id, args))
718    }
719
720    #[inline]
721    pub fn new_fn_ptr(tcx: TyCtxt<'tcx>, fty: PolyFnSig<'tcx>) -> Ty<'tcx> {
722        let (sig_tys, hdr) = fty.split();
723        Ty::new(tcx, FnPtr(sig_tys, hdr))
724    }
725
726    #[inline]
727    pub fn new_unsafe_binder(tcx: TyCtxt<'tcx>, b: Binder<'tcx, Ty<'tcx>>) -> Ty<'tcx> {
728        Ty::new(tcx, UnsafeBinder(b.into()))
729    }
730
731    #[inline]
732    pub fn new_dynamic(
733        tcx: TyCtxt<'tcx>,
734        obj: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
735        reg: ty::Region<'tcx>,
736    ) -> Ty<'tcx> {
737        if truecfg!(debug_assertions) {
738            let projection_count = obj
739                .projection_bounds()
740                .filter(|item| !tcx.generics_require_sized_self(item.item_def_id()))
741                .count();
742            let expected_count: usize = obj
743                .principal_def_id()
744                .into_iter()
745                .flat_map(|principal_def_id| {
746                    // IMPORTANT: This has to agree with HIR ty lowering of dyn trait!
747                    elaborate::supertraits(
748                        tcx,
749                        ty::Binder::dummy(ty::TraitRef::identity(tcx, principal_def_id)),
750                    )
751                    .map(|principal| {
752                        tcx.associated_items(principal.def_id())
753                            .in_definition_order()
754                            .filter(|item| item.is_type() || item.is_type_const())
755                            .filter(|item| !item.is_impl_trait_in_trait())
756                            .filter(|item| !tcx.generics_require_sized_self(item.def_id))
757                            .count()
758                    })
759                })
760                .sum();
761            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!(
762                projection_count, expected_count,
763                "expected {obj:?} to have {expected_count} projections, \
764                but it has {projection_count}"
765            );
766        }
767        Ty::new(tcx, Dynamic(obj, reg))
768    }
769
770    #[inline]
771    pub fn new_projection_from_args(
772        tcx: TyCtxt<'tcx>,
773        item_def_id: DefId,
774        args: ty::GenericArgsRef<'tcx>,
775    ) -> Ty<'tcx> {
776        Ty::new_alias(
777            tcx,
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        item_def_id: DefId,
786        args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>,
787    ) -> Ty<'tcx> {
788        Ty::new_alias(tcx, AliasTy::new(tcx, ty::Projection { def_id: item_def_id }, args))
789    }
790
791    #[inline]
792    pub fn new_closure(
793        tcx: TyCtxt<'tcx>,
794        def_id: DefId,
795        closure_args: GenericArgsRef<'tcx>,
796    ) -> Ty<'tcx> {
797        tcx.debug_assert_args_compatible(def_id, closure_args);
798        Ty::new(tcx, Closure(def_id, closure_args))
799    }
800
801    #[inline]
802    pub fn new_coroutine_closure(
803        tcx: TyCtxt<'tcx>,
804        def_id: DefId,
805        closure_args: GenericArgsRef<'tcx>,
806    ) -> Ty<'tcx> {
807        tcx.debug_assert_args_compatible(def_id, closure_args);
808        Ty::new(tcx, CoroutineClosure(def_id, closure_args))
809    }
810
811    #[inline]
812    pub fn new_coroutine(
813        tcx: TyCtxt<'tcx>,
814        def_id: DefId,
815        coroutine_args: GenericArgsRef<'tcx>,
816    ) -> Ty<'tcx> {
817        tcx.debug_assert_args_compatible(def_id, coroutine_args);
818        Ty::new(tcx, Coroutine(def_id, coroutine_args))
819    }
820
821    #[inline]
822    pub fn new_coroutine_witness(
823        tcx: TyCtxt<'tcx>,
824        def_id: DefId,
825        args: GenericArgsRef<'tcx>,
826    ) -> Ty<'tcx> {
827        if truecfg!(debug_assertions) {
828            tcx.debug_assert_args_compatible(tcx.typeck_root_def_id(def_id), args);
829        }
830        Ty::new(tcx, CoroutineWitness(def_id, args))
831    }
832
833    pub fn new_coroutine_witness_for_coroutine(
834        tcx: TyCtxt<'tcx>,
835        def_id: DefId,
836        coroutine_args: GenericArgsRef<'tcx>,
837    ) -> Ty<'tcx> {
838        tcx.debug_assert_args_compatible(def_id, coroutine_args);
839        // HACK: Coroutine witness types are lifetime erased, so they
840        // never reference any lifetime args from the coroutine. We erase
841        // the regions here since we may get into situations where a
842        // coroutine is recursively contained within itself, leading to
843        // witness types that differ by region args. This means that
844        // cycle detection in fulfillment will not kick in, which leads
845        // to unnecessary overflows in async code. See the issue:
846        // <https://github.com/rust-lang/rust/issues/145151>.
847        let args =
848            ty::GenericArgs::for_item(tcx, tcx.typeck_root_def_id(def_id), |def, _| {
849                match def.kind {
850                    ty::GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
851                    ty::GenericParamDefKind::Type { .. }
852                    | ty::GenericParamDefKind::Const { .. } => coroutine_args[def.index as usize],
853                }
854            });
855        Ty::new_coroutine_witness(tcx, def_id, args)
856    }
857
858    // misc
859
860    #[inline]
861    pub fn new_static_str(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
862        Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, tcx.types.str_)
863    }
864
865    // lang and diagnostic tys
866
867    fn new_generic_adt(tcx: TyCtxt<'tcx>, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> {
868        let adt_def = tcx.adt_def(wrapper_def_id);
869        let args = GenericArgs::for_item(tcx, wrapper_def_id, |param, args| match param.kind {
870            GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => crate::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
871            GenericParamDefKind::Type { has_default, .. } => {
872                if param.index == 0 {
873                    ty_param.into()
874                } else {
875                    if !has_default { ::core::panicking::panic("assertion failed: has_default") };assert!(has_default);
876                    tcx.type_of(param.def_id).instantiate(tcx, args).into()
877                }
878            }
879        });
880        Ty::new_adt(tcx, adt_def, args)
881    }
882
883    #[inline]
884    pub fn new_lang_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, item: LangItem) -> Option<Ty<'tcx>> {
885        let def_id = tcx.lang_items().get(item)?;
886        Some(Ty::new_generic_adt(tcx, def_id, ty))
887    }
888
889    #[inline]
890    pub fn new_diagnostic_item(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, name: Symbol) -> Option<Ty<'tcx>> {
891        let def_id = tcx.get_diagnostic_item(name)?;
892        Some(Ty::new_generic_adt(tcx, def_id, ty))
893    }
894
895    #[inline]
896    pub fn new_box(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
897        let def_id = tcx.require_lang_item(LangItem::OwnedBox, DUMMY_SP);
898        Ty::new_generic_adt(tcx, def_id, ty)
899    }
900
901    #[inline]
902    pub fn new_option(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
903        let def_id = tcx.require_lang_item(LangItem::Option, DUMMY_SP);
904        Ty::new_generic_adt(tcx, def_id, ty)
905    }
906
907    #[inline]
908    pub fn new_maybe_uninit(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
909        let def_id = tcx.require_lang_item(LangItem::MaybeUninit, DUMMY_SP);
910        Ty::new_generic_adt(tcx, def_id, ty)
911    }
912
913    /// Creates a `&mut Context<'_>` [`Ty`] with erased lifetimes.
914    pub fn new_task_context(tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
915        let context_did = tcx.require_lang_item(LangItem::Context, DUMMY_SP);
916        let context_adt_ref = tcx.adt_def(context_did);
917        let context_args = tcx.mk_args(&[tcx.lifetimes.re_erased.into()]);
918        let context_ty = Ty::new_adt(tcx, context_adt_ref, context_args);
919        Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, context_ty)
920    }
921}
922
923impl<'tcx> rustc_type_ir::inherent::Ty<TyCtxt<'tcx>> for Ty<'tcx> {
924    fn new_bool(tcx: TyCtxt<'tcx>) -> Self {
925        tcx.types.bool
926    }
927
928    fn new_u8(tcx: TyCtxt<'tcx>) -> Self {
929        tcx.types.u8
930    }
931
932    fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferTy) -> Self {
933        Ty::new_infer(tcx, infer)
934    }
935
936    fn new_var(tcx: TyCtxt<'tcx>, vid: ty::TyVid) -> Self {
937        Ty::new_var(tcx, vid)
938    }
939
940    fn new_param(tcx: TyCtxt<'tcx>, param: ty::ParamTy) -> Self {
941        Ty::new_param(tcx, param.index, param.name)
942    }
943
944    fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType<'tcx>) -> Self {
945        Ty::new_placeholder(tcx, placeholder)
946    }
947
948    fn new_bound(
949        interner: TyCtxt<'tcx>,
950        debruijn: ty::DebruijnIndex,
951        var: ty::BoundTy<'tcx>,
952    ) -> Self {
953        Ty::new_bound(interner, debruijn, var)
954    }
955
956    fn new_anon_bound(tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self {
957        Ty::new_bound(tcx, debruijn, ty::BoundTy { var, kind: ty::BoundTyKind::Anon })
958    }
959
960    fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: ty::BoundVar) -> Self {
961        Ty::new_canonical_bound(tcx, var)
962    }
963
964    fn new_alias(interner: TyCtxt<'tcx>, alias_ty: ty::AliasTy<'tcx>) -> Self {
965        Ty::new_alias(interner, alias_ty)
966    }
967
968    fn new_error(interner: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> Self {
969        Ty::new_error(interner, guar)
970    }
971
972    fn new_adt(
973        interner: TyCtxt<'tcx>,
974        adt_def: ty::AdtDef<'tcx>,
975        args: ty::GenericArgsRef<'tcx>,
976    ) -> Self {
977        Ty::new_adt(interner, adt_def, args)
978    }
979
980    fn new_foreign(interner: TyCtxt<'tcx>, def_id: DefId) -> Self {
981        Ty::new_foreign(interner, def_id)
982    }
983
984    fn new_dynamic(
985        interner: TyCtxt<'tcx>,
986        preds: &'tcx List<ty::PolyExistentialPredicate<'tcx>>,
987        region: ty::Region<'tcx>,
988    ) -> Self {
989        Ty::new_dynamic(interner, preds, region)
990    }
991
992    fn new_coroutine(
993        interner: TyCtxt<'tcx>,
994        def_id: DefId,
995        args: ty::GenericArgsRef<'tcx>,
996    ) -> Self {
997        Ty::new_coroutine(interner, def_id, args)
998    }
999
1000    fn new_coroutine_closure(
1001        interner: TyCtxt<'tcx>,
1002        def_id: DefId,
1003        args: ty::GenericArgsRef<'tcx>,
1004    ) -> Self {
1005        Ty::new_coroutine_closure(interner, def_id, args)
1006    }
1007
1008    fn new_closure(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
1009        Ty::new_closure(interner, def_id, args)
1010    }
1011
1012    fn new_coroutine_witness(
1013        interner: TyCtxt<'tcx>,
1014        def_id: DefId,
1015        args: ty::GenericArgsRef<'tcx>,
1016    ) -> Self {
1017        Ty::new_coroutine_witness(interner, def_id, args)
1018    }
1019
1020    fn new_coroutine_witness_for_coroutine(
1021        interner: TyCtxt<'tcx>,
1022        def_id: DefId,
1023        coroutine_args: ty::GenericArgsRef<'tcx>,
1024    ) -> Self {
1025        Ty::new_coroutine_witness_for_coroutine(interner, def_id, coroutine_args)
1026    }
1027
1028    fn new_ptr(interner: TyCtxt<'tcx>, ty: Self, mutbl: hir::Mutability) -> Self {
1029        Ty::new_ptr(interner, ty, mutbl)
1030    }
1031
1032    fn new_ref(
1033        interner: TyCtxt<'tcx>,
1034        region: ty::Region<'tcx>,
1035        ty: Self,
1036        mutbl: hir::Mutability,
1037    ) -> Self {
1038        Ty::new_ref(interner, region, ty, mutbl)
1039    }
1040
1041    fn new_array_with_const_len(interner: TyCtxt<'tcx>, ty: Self, len: ty::Const<'tcx>) -> Self {
1042        Ty::new_array_with_const_len(interner, ty, len)
1043    }
1044
1045    fn new_slice(interner: TyCtxt<'tcx>, ty: Self) -> Self {
1046        Ty::new_slice(interner, ty)
1047    }
1048
1049    fn new_tup(interner: TyCtxt<'tcx>, tys: &[Ty<'tcx>]) -> Self {
1050        Ty::new_tup(interner, tys)
1051    }
1052
1053    fn new_tup_from_iter<It, T>(interner: TyCtxt<'tcx>, iter: It) -> T::Output
1054    where
1055        It: Iterator<Item = T>,
1056        T: CollectAndApply<Self, Self>,
1057    {
1058        Ty::new_tup_from_iter(interner, iter)
1059    }
1060
1061    fn tuple_fields(self) -> &'tcx ty::List<Ty<'tcx>> {
1062        self.tuple_fields()
1063    }
1064
1065    fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1066        self.to_opt_closure_kind()
1067    }
1068
1069    fn from_closure_kind(interner: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Self {
1070        Ty::from_closure_kind(interner, kind)
1071    }
1072
1073    fn from_coroutine_closure_kind(
1074        interner: TyCtxt<'tcx>,
1075        kind: rustc_type_ir::ClosureKind,
1076    ) -> Self {
1077        Ty::from_coroutine_closure_kind(interner, kind)
1078    }
1079
1080    fn new_fn_def(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self {
1081        Ty::new_fn_def(interner, def_id, args)
1082    }
1083
1084    fn new_fn_ptr(interner: TyCtxt<'tcx>, sig: ty::Binder<'tcx, ty::FnSig<'tcx>>) -> Self {
1085        Ty::new_fn_ptr(interner, sig)
1086    }
1087
1088    fn new_pat(interner: TyCtxt<'tcx>, ty: Self, pat: ty::Pattern<'tcx>) -> Self {
1089        Ty::new_pat(interner, ty, pat)
1090    }
1091
1092    fn new_unsafe_binder(interner: TyCtxt<'tcx>, ty: ty::Binder<'tcx, Ty<'tcx>>) -> Self {
1093        Ty::new_unsafe_binder(interner, ty)
1094    }
1095
1096    fn new_unit(interner: TyCtxt<'tcx>) -> Self {
1097        interner.types.unit
1098    }
1099
1100    fn new_usize(interner: TyCtxt<'tcx>) -> Self {
1101        interner.types.usize
1102    }
1103
1104    fn discriminant_ty(self, interner: TyCtxt<'tcx>) -> Ty<'tcx> {
1105        self.discriminant_ty(interner)
1106    }
1107
1108    fn has_unsafe_fields(self) -> bool {
1109        Ty::has_unsafe_fields(self)
1110    }
1111}
1112
1113/// Type utilities
1114impl<'tcx> Ty<'tcx> {
1115    // It would be nicer if this returned the value instead of a reference,
1116    // like how `Predicate::kind` and `Region::kind` do. (It would result in
1117    // many fewer subsequent dereferences.) But that gives a small but
1118    // noticeable performance hit. See #126069 for details.
1119    #[inline(always)]
1120    pub fn kind(self) -> &'tcx TyKind<'tcx> {
1121        self.0.0
1122    }
1123
1124    // FIXME(compiler-errors): Think about removing this.
1125    #[inline(always)]
1126    pub fn flags(self) -> TypeFlags {
1127        self.0.0.flags
1128    }
1129
1130    #[inline]
1131    pub fn is_unit(self) -> bool {
1132        match self.kind() {
1133            Tuple(tys) => tys.is_empty(),
1134            _ => false,
1135        }
1136    }
1137
1138    /// Check if type is an `usize`.
1139    #[inline]
1140    pub fn is_usize(self) -> bool {
1141        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Uint(UintTy::Usize) => true,
    _ => false,
}matches!(self.kind(), Uint(UintTy::Usize))
1142    }
1143
1144    /// Check if type is an `usize` or an integral type variable.
1145    #[inline]
1146    pub fn is_usize_like(self) -> bool {
1147        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Uint(UintTy::Usize) | Infer(IntVar(_)) => true,
    _ => false,
}matches!(self.kind(), Uint(UintTy::Usize) | Infer(IntVar(_)))
1148    }
1149
1150    #[inline]
1151    pub fn is_never(self) -> bool {
1152        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Never => true,
    _ => false,
}matches!(self.kind(), Never)
1153    }
1154
1155    #[inline]
1156    pub fn is_primitive(self) -> bool {
1157        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Bool | Char | Int(_) | Uint(_) | Float(_) => true,
    _ => false,
}matches!(self.kind(), Bool | Char | Int(_) | Uint(_) | Float(_))
1158    }
1159
1160    #[inline]
1161    pub fn is_adt(self) -> bool {
1162        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Adt(..) => true,
    _ => false,
}matches!(self.kind(), Adt(..))
1163    }
1164
1165    #[inline]
1166    pub fn is_ref(self) -> bool {
1167        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Ref(..) => true,
    _ => false,
}matches!(self.kind(), Ref(..))
1168    }
1169
1170    #[inline]
1171    pub fn is_ty_var(self) -> bool {
1172        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(TyVar(_)) => true,
    _ => false,
}matches!(self.kind(), Infer(TyVar(_)))
1173    }
1174
1175    #[inline]
1176    pub fn ty_vid(self) -> Option<ty::TyVid> {
1177        match self.kind() {
1178            &Infer(TyVar(vid)) => Some(vid),
1179            _ => None,
1180        }
1181    }
1182
1183    #[inline]
1184    pub fn is_ty_or_numeric_infer(self) -> bool {
1185        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(_) => true,
    _ => false,
}matches!(self.kind(), Infer(_))
1186    }
1187
1188    #[inline]
1189    pub fn is_phantom_data(self) -> bool {
1190        if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false }
1191    }
1192
1193    #[inline]
1194    pub fn is_bool(self) -> bool {
1195        *self.kind() == Bool
1196    }
1197
1198    /// Returns `true` if this type is a `str`.
1199    #[inline]
1200    pub fn is_str(self) -> bool {
1201        *self.kind() == Str
1202    }
1203
1204    /// Returns true if this type is `&str`. The reference's lifetime is ignored.
1205    #[inline]
1206    pub fn is_imm_ref_str(self) -> bool {
1207        #[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())
1208    }
1209
1210    #[inline]
1211    pub fn is_param(self, index: u32) -> bool {
1212        match self.kind() {
1213            ty::Param(data) => data.index == index,
1214            _ => false,
1215        }
1216    }
1217
1218    #[inline]
1219    pub fn is_slice(self) -> bool {
1220        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Slice(_) => true,
    _ => false,
}matches!(self.kind(), Slice(_))
1221    }
1222
1223    #[inline]
1224    pub fn is_array_slice(self) -> bool {
1225        match self.kind() {
1226            Slice(_) => true,
1227            ty::RawPtr(ty, _) | Ref(_, ty, _) => #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    Slice(_) => true,
    _ => false,
}matches!(ty.kind(), Slice(_)),
1228            _ => false,
1229        }
1230    }
1231
1232    #[inline]
1233    pub fn is_array(self) -> bool {
1234        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Array(..) => true,
    _ => false,
}matches!(self.kind(), Array(..))
1235    }
1236
1237    #[inline]
1238    pub fn is_simd(self) -> bool {
1239        match self.kind() {
1240            Adt(def, _) => def.repr().simd(),
1241            _ => false,
1242        }
1243    }
1244
1245    #[inline]
1246    pub fn is_scalable_vector(self) -> bool {
1247        match self.kind() {
1248            Adt(def, _) => def.repr().scalable(),
1249            _ => false,
1250        }
1251    }
1252
1253    pub fn sequence_element_type(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1254        match self.kind() {
1255            Array(ty, _) | Slice(ty) => *ty,
1256            Str => tcx.types.u8,
1257            _ => 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),
1258        }
1259    }
1260
1261    pub fn scalable_vector_parts(
1262        self,
1263        tcx: TyCtxt<'tcx>,
1264    ) -> Option<(u16, Ty<'tcx>, NumScalableVectors)> {
1265        let Adt(def, args) = self.kind() else {
1266            return None;
1267        };
1268        let (num_vectors, vec_def) = match def.repr().scalable? {
1269            ScalableElt::ElementCount(_) => (NumScalableVectors::for_non_tuple(), *def),
1270            ScalableElt::Container => (
1271                NumScalableVectors::from_field_count(def.non_enum_variant().fields.len())?,
1272                def.non_enum_variant().fields[FieldIdx::ZERO].ty(tcx, args).ty_adt_def()?,
1273            ),
1274        };
1275        let Some(ScalableElt::ElementCount(element_count)) = vec_def.repr().scalable else {
1276            return None;
1277        };
1278        let variant = vec_def.non_enum_variant();
1279        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);
1280        let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1281        Some((element_count, field_ty, num_vectors))
1282    }
1283
1284    pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {
1285        let Adt(def, args) = self.kind() else {
1286            crate::util::bug::bug_fmt(format_args!("`simd_size_and_type` called on invalid type"))bug!("`simd_size_and_type` called on invalid type")
1287        };
1288        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");
1289        let variant = def.non_enum_variant();
1290        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);
1291        let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1292        let Array(f0_elem_ty, f0_len) = field_ty.kind() else {
1293            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:?}")
1294        };
1295        // FIXME(repr_simd): https://github.com/rust-lang/rust/pull/78863#discussion_r522784112
1296        // The way we evaluate the `N` in `[T; N]` here only works since we use
1297        // `simd_size_and_type` post-monomorphization. It will probably start to ICE
1298        // if we use it in generic code. See the `simd-array-trait` ui test.
1299        (
1300            f0_len
1301                .try_to_target_usize(tcx)
1302                .expect("expected SIMD field to have definite array size"),
1303            *f0_elem_ty,
1304        )
1305    }
1306
1307    #[inline]
1308    pub fn is_mutable_ptr(self) -> bool {
1309        #[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))
1310    }
1311
1312    /// Get the mutability of the reference or `None` when not a reference
1313    #[inline]
1314    pub fn ref_mutability(self) -> Option<hir::Mutability> {
1315        match self.kind() {
1316            Ref(_, _, mutability) => Some(*mutability),
1317            _ => None,
1318        }
1319    }
1320
1321    #[inline]
1322    pub fn is_raw_ptr(self) -> bool {
1323        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    RawPtr(_, _) => true,
    _ => false,
}matches!(self.kind(), RawPtr(_, _))
1324    }
1325
1326    /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer).
1327    /// `Box` is *not* considered a pointer here!
1328    #[inline]
1329    pub fn is_any_ptr(self) -> bool {
1330        self.is_ref() || self.is_raw_ptr() || self.is_fn_ptr()
1331    }
1332
1333    #[inline]
1334    pub fn is_box(self) -> bool {
1335        match self.kind() {
1336            Adt(def, _) => def.is_box(),
1337            _ => false,
1338        }
1339    }
1340
1341    /// Tests whether this is a Box definitely using the global allocator.
1342    ///
1343    /// If the allocator is still generic, the answer is `false`, but it may
1344    /// later turn out that it does use the global allocator.
1345    #[inline]
1346    pub fn is_box_global(self, tcx: TyCtxt<'tcx>) -> bool {
1347        match self.kind() {
1348            Adt(def, args) if def.is_box() => {
1349                let Some(alloc) = args.get(1) else {
1350                    // Single-argument Box is always global. (for "minicore" tests)
1351                    return true;
1352                };
1353                alloc.expect_ty().ty_adt_def().is_some_and(|alloc_adt| {
1354                    tcx.is_lang_item(alloc_adt.did(), LangItem::GlobalAlloc)
1355                })
1356            }
1357            _ => false,
1358        }
1359    }
1360
1361    pub fn boxed_ty(self) -> Option<Ty<'tcx>> {
1362        match self.kind() {
1363            Adt(def, args) if def.is_box() => Some(args.type_at(0)),
1364            _ => None,
1365        }
1366    }
1367
1368    pub fn pinned_ty(self) -> Option<Ty<'tcx>> {
1369        match self.kind() {
1370            Adt(def, args) if def.is_pin() => Some(args.type_at(0)),
1371            _ => None,
1372        }
1373    }
1374
1375    /// Returns the type, pinnedness, mutability, and the region of a reference (`&T` or `&mut T`)
1376    /// or a pinned-reference type (`Pin<&T>` or `Pin<&mut T>`).
1377    ///
1378    /// Regarding the [`pin_ergonomics`] feature, one of the goals is to make pinned references
1379    /// (`Pin<&T>` and `Pin<&mut T>`) behaves similar to normal references (`&T` and `&mut T`).
1380    /// This function is useful when references and pinned references are processed similarly.
1381    ///
1382    /// [`pin_ergonomics`]: https://github.com/rust-lang/rust/issues/130494
1383    pub fn maybe_pinned_ref(
1384        self,
1385    ) -> Option<(Ty<'tcx>, ty::Pinnedness, ty::Mutability, Region<'tcx>)> {
1386        match self.kind() {
1387            Adt(def, args)
1388                if def.is_pin()
1389                    && let &ty::Ref(region, ty, mutbl) = args.type_at(0).kind() =>
1390            {
1391                Some((ty, ty::Pinnedness::Pinned, mutbl, region))
1392            }
1393            &Ref(region, ty, mutbl) => Some((ty, ty::Pinnedness::Not, mutbl, region)),
1394            _ => None,
1395        }
1396    }
1397
1398    /// Panics if called on any type other than `Box<T>`.
1399    pub fn expect_boxed_ty(self) -> Ty<'tcx> {
1400        self.boxed_ty()
1401            .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))
1402    }
1403
1404    /// A scalar type is one that denotes an atomic datum, with no sub-components.
1405    /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1406    /// contents are abstract to rustc.)
1407    #[inline]
1408    pub fn is_scalar(self) -> bool {
1409        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Bool | Char | Int(_) | Float(_) | Uint(_) | FnDef(..) | FnPtr(..) |
        RawPtr(_, _) | Infer(IntVar(_) | FloatVar(_)) => true,
    _ => false,
}matches!(
1410            self.kind(),
1411            Bool | Char
1412                | Int(_)
1413                | Float(_)
1414                | Uint(_)
1415                | FnDef(..)
1416                | FnPtr(..)
1417                | RawPtr(_, _)
1418                | Infer(IntVar(_) | FloatVar(_))
1419        )
1420    }
1421
1422    /// Returns `true` if this type is a floating point type.
1423    #[inline]
1424    pub fn is_floating_point(self) -> bool {
1425        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Float(_) | Infer(FloatVar(_)) => true,
    _ => false,
}matches!(self.kind(), Float(_) | Infer(FloatVar(_)))
1426    }
1427
1428    #[inline]
1429    pub fn is_trait(self) -> bool {
1430        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Dynamic(_, _) => true,
    _ => false,
}matches!(self.kind(), Dynamic(_, _))
1431    }
1432
1433    #[inline]
1434    pub fn is_enum(self) -> bool {
1435        #[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())
1436    }
1437
1438    #[inline]
1439    pub fn is_union(self) -> bool {
1440        #[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())
1441    }
1442
1443    #[inline]
1444    pub fn is_closure(self) -> bool {
1445        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Closure(..) => true,
    _ => false,
}matches!(self.kind(), Closure(..))
1446    }
1447
1448    #[inline]
1449    pub fn is_coroutine(self) -> bool {
1450        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Coroutine(..) => true,
    _ => false,
}matches!(self.kind(), Coroutine(..))
1451    }
1452
1453    #[inline]
1454    pub fn is_coroutine_closure(self) -> bool {
1455        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    CoroutineClosure(..) => true,
    _ => false,
}matches!(self.kind(), CoroutineClosure(..))
1456    }
1457
1458    #[inline]
1459    pub fn is_integral(self) -> bool {
1460        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(IntVar(_)) | Int(_) | Uint(_) => true,
    _ => false,
}matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_))
1461    }
1462
1463    #[inline]
1464    pub fn is_fresh_ty(self) -> bool {
1465        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(FreshTy(_)) => true,
    _ => false,
}matches!(self.kind(), Infer(FreshTy(_)))
1466    }
1467
1468    #[inline]
1469    pub fn is_fresh(self) -> bool {
1470        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)) => true,
    _ => false,
}matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)))
1471    }
1472
1473    #[inline]
1474    pub fn is_char(self) -> bool {
1475        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Char => true,
    _ => false,
}matches!(self.kind(), Char)
1476    }
1477
1478    #[inline]
1479    pub fn is_numeric(self) -> bool {
1480        self.is_integral() || self.is_floating_point()
1481    }
1482
1483    #[inline]
1484    pub fn is_signed(self) -> bool {
1485        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Int(_) => true,
    _ => false,
}matches!(self.kind(), Int(_))
1486    }
1487
1488    #[inline]
1489    pub fn is_ptr_sized_integral(self) -> bool {
1490        #[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))
1491    }
1492
1493    #[inline]
1494    pub fn has_concrete_skeleton(self) -> bool {
1495        !#[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    Param(_) | Infer(_) | Error(_) => true,
    _ => false,
}matches!(self.kind(), Param(_) | Infer(_) | Error(_))
1496    }
1497
1498    /// Checks whether a type recursively contains another type
1499    ///
1500    /// Example: `Option<()>` contains `()`
1501    pub fn contains(self, other: Ty<'tcx>) -> bool {
1502        struct ContainsTyVisitor<'tcx>(Ty<'tcx>);
1503
1504        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsTyVisitor<'tcx> {
1505            type Result = ControlFlow<()>;
1506
1507            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1508                if self.0 == t { ControlFlow::Break(()) } else { t.super_visit_with(self) }
1509            }
1510        }
1511
1512        let cf = self.visit_with(&mut ContainsTyVisitor(other));
1513        cf.is_break()
1514    }
1515
1516    /// Checks whether a type recursively contains any closure
1517    ///
1518    /// Example: `Option<{closure@file.rs:4:20}>` returns true
1519    pub fn contains_closure(self) -> bool {
1520        struct ContainsClosureVisitor;
1521
1522        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsClosureVisitor {
1523            type Result = ControlFlow<()>;
1524
1525            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1526                if let ty::Closure(..) = t.kind() {
1527                    ControlFlow::Break(())
1528                } else {
1529                    t.super_visit_with(self)
1530                }
1531            }
1532        }
1533
1534        let cf = self.visit_with(&mut ContainsClosureVisitor);
1535        cf.is_break()
1536    }
1537
1538    /// Returns the deepest `async_drop_in_place::{closure}` implementation.
1539    ///
1540    /// `async_drop_in_place<T>::{closure}`, when T is a coroutine, is a proxy-impl
1541    /// to call async drop poll from impl coroutine.
1542    pub fn find_async_drop_impl_coroutine<F: FnMut(Ty<'tcx>)>(
1543        self,
1544        tcx: TyCtxt<'tcx>,
1545        mut f: F,
1546    ) -> Ty<'tcx> {
1547        if !self.is_coroutine() {
    ::core::panicking::panic("assertion failed: self.is_coroutine()")
};assert!(self.is_coroutine());
1548        let mut cor_ty = self;
1549        let mut ty = cor_ty;
1550        loop {
1551            let ty::Coroutine(def_id, args) = ty.kind() else { return cor_ty };
1552            cor_ty = ty;
1553            f(ty);
1554            if !tcx.is_async_drop_in_place_coroutine(*def_id) {
1555                return cor_ty;
1556            }
1557            ty = args.first().unwrap().expect_ty();
1558        }
1559    }
1560
1561    /// Returns the type of `*ty`.
1562    ///
1563    /// The parameter `explicit` indicates if this is an *explicit* dereference.
1564    /// Some types -- notably raw ptrs -- can only be dereferenced explicitly.
1565    pub fn builtin_deref(self, explicit: bool) -> Option<Ty<'tcx>> {
1566        match *self.kind() {
1567            _ if let Some(boxed) = self.boxed_ty() => Some(boxed),
1568            Ref(_, ty, _) => Some(ty),
1569            RawPtr(ty, _) if explicit => Some(ty),
1570            _ => None,
1571        }
1572    }
1573
1574    /// Returns the type of `ty[i]`.
1575    pub fn builtin_index(self) -> Option<Ty<'tcx>> {
1576        match self.kind() {
1577            Array(ty, _) | Slice(ty) => Some(*ty),
1578            _ => None,
1579        }
1580    }
1581
1582    #[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("compiler/rustc_middle/src/ty/sty.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1582u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
                                    ::tracing_core::field::FieldSet::new(&["self"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: PolyFnSig<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        { self.kind().fn_sig(tcx) }
    }
}#[tracing::instrument(level = "trace", skip(tcx))]
1583    pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
1584        self.kind().fn_sig(tcx)
1585    }
1586
1587    #[inline]
1588    pub fn is_fn(self) -> bool {
1589        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    FnDef(..) | FnPtr(..) => true,
    _ => false,
}matches!(self.kind(), FnDef(..) | FnPtr(..))
1590    }
1591
1592    #[inline]
1593    pub fn is_fn_ptr(self) -> bool {
1594        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    FnPtr(..) => true,
    _ => false,
}matches!(self.kind(), FnPtr(..))
1595    }
1596
1597    #[inline]
1598    pub fn is_opaque(self) -> bool {
1599        #[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 { .. }, .. }))
1600    }
1601
1602    #[inline]
1603    pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
1604        match self.kind() {
1605            Adt(adt, _) => Some(*adt),
1606            _ => None,
1607        }
1608    }
1609
1610    /// Returns a list of tuple type arguments.
1611    ///
1612    /// Panics when called on anything but a tuple.
1613    #[inline]
1614    pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> {
1615        match self.kind() {
1616            Tuple(args) => args,
1617            _ => crate::util::bug::bug_fmt(format_args!("tuple_fields called on non-tuple: {0:?}",
        self))bug!("tuple_fields called on non-tuple: {self:?}"),
1618        }
1619    }
1620
1621    /// Returns a list of tuple type arguments, or `None` if `self` isn't a tuple.
1622    #[inline]
1623    pub fn opt_tuple_fields(self) -> Option<&'tcx List<Ty<'tcx>>> {
1624        match self.kind() {
1625            Tuple(args) => Some(args),
1626            _ => None,
1627        }
1628    }
1629
1630    /// If the type contains variants, returns the valid range of variant indices.
1631    //
1632    // FIXME: This requires the optimized MIR in the case of coroutines.
1633    #[inline]
1634    pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
1635        match self.kind() {
1636            TyKind::Adt(adt, _) => Some(adt.variant_range()),
1637            TyKind::Coroutine(def_id, args) => {
1638                Some(args.as_coroutine().variant_range(*def_id, tcx))
1639            }
1640            TyKind::UnsafeBinder(bound_ty) => {
1641                tcx.instantiate_bound_regions_with_erased((*bound_ty).into()).variant_range(tcx)
1642            }
1643            _ => None,
1644        }
1645    }
1646
1647    /// If the type contains variants, returns the variant for `variant_index`.
1648    /// Panics if `variant_index` is out of range.
1649    //
1650    // FIXME: This requires the optimized MIR in the case of coroutines.
1651    #[inline]
1652    pub fn discriminant_for_variant(
1653        self,
1654        tcx: TyCtxt<'tcx>,
1655        variant_index: VariantIdx,
1656    ) -> Option<Discr<'tcx>> {
1657        match self.kind() {
1658            TyKind::Adt(adt, _) if adt.is_enum() => {
1659                Some(adt.discriminant_for_variant(tcx, variant_index))
1660            }
1661            TyKind::Coroutine(def_id, args) => {
1662                Some(args.as_coroutine().discriminant_for_variant(*def_id, tcx, variant_index))
1663            }
1664            TyKind::UnsafeBinder(bound_ty) => tcx
1665                .instantiate_bound_regions_with_erased((*bound_ty).into())
1666                .discriminant_for_variant(tcx, variant_index),
1667            _ => None,
1668        }
1669    }
1670
1671    /// Returns the type of the discriminant of this type.
1672    pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1673        match self.kind() {
1674            ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
1675            ty::Coroutine(_, args) => args.as_coroutine().discr_ty(tcx),
1676
1677            ty::Param(_) | ty::Alias(..) | ty::Infer(ty::TyVar(_)) => {
1678                let assoc_items = tcx.associated_item_def_ids(
1679                    tcx.require_lang_item(hir::LangItem::DiscriminantKind, DUMMY_SP),
1680                );
1681                Ty::new_projection_from_args(tcx, assoc_items[0], tcx.mk_args(&[self.into()]))
1682            }
1683
1684            ty::Pat(ty, _) => ty.discriminant_ty(tcx),
1685            ty::UnsafeBinder(bound_ty) => {
1686                tcx.instantiate_bound_regions_with_erased((*bound_ty).into()).discriminant_ty(tcx)
1687            }
1688
1689            ty::Bool
1690            | ty::Char
1691            | ty::Int(_)
1692            | ty::Uint(_)
1693            | ty::Float(_)
1694            | ty::Adt(..)
1695            | ty::Foreign(_)
1696            | ty::Str
1697            | ty::Array(..)
1698            | ty::Slice(_)
1699            | ty::RawPtr(_, _)
1700            | ty::Ref(..)
1701            | ty::FnDef(..)
1702            | ty::FnPtr(..)
1703            | ty::Dynamic(..)
1704            | ty::Closure(..)
1705            | ty::CoroutineClosure(..)
1706            | ty::CoroutineWitness(..)
1707            | ty::Never
1708            | ty::Tuple(_)
1709            | ty::Error(_)
1710            | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
1711
1712            ty::Bound(..)
1713            | ty::Placeholder(_)
1714            | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1715                crate::util::bug::bug_fmt(format_args!("`discriminant_ty` applied to unexpected type: {0:?}",
        self))bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
1716            }
1717        }
1718    }
1719
1720    /// Returns the type of metadata for (potentially wide) pointers to this type,
1721    /// or the struct tail if the metadata type cannot be determined.
1722    pub fn ptr_metadata_ty_or_tail(
1723        self,
1724        tcx: TyCtxt<'tcx>,
1725        normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
1726    ) -> Result<Ty<'tcx>, Ty<'tcx>> {
1727        let tail = tcx.struct_tail_raw(self, &ObligationCause::dummy(), normalize, || {});
1728        match tail.kind() {
1729            // Sized types
1730            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1731            | ty::Uint(_)
1732            | ty::Int(_)
1733            | ty::Bool
1734            | ty::Float(_)
1735            | ty::FnDef(..)
1736            | ty::FnPtr(..)
1737            | ty::RawPtr(..)
1738            | ty::Char
1739            | ty::Ref(..)
1740            | ty::Coroutine(..)
1741            | ty::CoroutineWitness(..)
1742            | ty::Array(..)
1743            | ty::Closure(..)
1744            | ty::CoroutineClosure(..)
1745            | ty::Never
1746            | ty::Error(_)
1747            // Extern types have metadata = ().
1748            | ty::Foreign(..)
1749            // If returned by `struct_tail_raw` this is a unit struct
1750            // without any fields, or not a struct, and therefore is Sized.
1751            | ty::Adt(..)
1752            // If returned by `struct_tail_raw` this is the empty tuple,
1753            // a.k.a. unit type, which is Sized
1754            | ty::Tuple(..) => Ok(tcx.types.unit),
1755
1756            ty::Str | ty::Slice(_) => Ok(tcx.types.usize),
1757
1758            ty::Dynamic(_, _) => {
1759                let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, DUMMY_SP);
1760                Ok(tcx.type_of(dyn_metadata).instantiate(tcx, &[tail.into()]))
1761            }
1762
1763            // We don't know the metadata of `self`, but it must be equal to the
1764            // metadata of `tail`.
1765            ty::Param(_) | ty::Alias(..) => Err(tail),
1766
1767            | ty::UnsafeBinder(_) => {
    ::core::panicking::panic_fmt(format_args!("not yet implemented: {0}",
            format_args!("FIXME(unsafe_binder)")));
}todo!("FIXME(unsafe_binder)"),
1768
1769            ty::Infer(ty::TyVar(_))
1770            | ty::Pat(..)
1771            | ty::Bound(..)
1772            | ty::Placeholder(..)
1773            | 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!(
1774                "`ptr_metadata_ty_or_tail` applied to unexpected type: {self:?} (tail = {tail:?})"
1775            ),
1776        }
1777    }
1778
1779    /// Returns the type of metadata for (potentially wide) pointers to this type.
1780    /// Causes an ICE if the metadata type cannot be determined.
1781    pub fn ptr_metadata_ty(
1782        self,
1783        tcx: TyCtxt<'tcx>,
1784        normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
1785    ) -> Ty<'tcx> {
1786        match self.ptr_metadata_ty_or_tail(tcx, normalize) {
1787            Ok(metadata) => metadata,
1788            Err(tail) => crate::util::bug::bug_fmt(format_args!("`ptr_metadata_ty` failed to get metadata for type: {0:?} (tail = {1:?})",
        self, tail))bug!(
1789                "`ptr_metadata_ty` failed to get metadata for type: {self:?} (tail = {tail:?})"
1790            ),
1791        }
1792    }
1793
1794    /// Given a pointer or reference type, returns the type of the *pointee*'s
1795    /// metadata. If it can't be determined exactly (perhaps due to still
1796    /// being generic) then a projection through `ptr::Pointee` will be returned.
1797    ///
1798    /// This is particularly useful for getting the type of the result of
1799    /// [`UnOp::PtrMetadata`](crate::mir::UnOp::PtrMetadata).
1800    ///
1801    /// Panics if `self` is not dereferenceable.
1802    #[track_caller]
1803    pub fn pointee_metadata_ty_or_projection(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1804        let Some(pointee_ty) = self.builtin_deref(true) else {
1805            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")
1806        };
1807        if pointee_ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized) {
1808            tcx.types.unit
1809        } else {
1810            match pointee_ty.ptr_metadata_ty_or_tail(tcx, |x| x) {
1811                Ok(metadata_ty) => metadata_ty,
1812                Err(tail_ty) => {
1813                    let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, DUMMY_SP);
1814                    Ty::new_projection(tcx, metadata_def_id, [tail_ty])
1815                }
1816            }
1817        }
1818    }
1819
1820    /// When we create a closure, we record its kind (i.e., what trait
1821    /// it implements, constrained by how it uses its borrows) into its
1822    /// [`ty::ClosureArgs`] or [`ty::CoroutineClosureArgs`] using a type
1823    /// parameter. This is kind of a phantom type, except that the
1824    /// most convenient thing for us to are the integral types. This
1825    /// function converts such a special type into the closure
1826    /// kind. To go the other way, use [`Ty::from_closure_kind`].
1827    ///
1828    /// Note that during type checking, we use an inference variable
1829    /// to represent the closure kind, because it has not yet been
1830    /// inferred. Once upvar inference (in `rustc_hir_analysis/src/check/upvar.rs`)
1831    /// is complete, that type variable will be unified with one of
1832    /// the integral types.
1833    ///
1834    /// ```rust,ignore (snippet of compiler code)
1835    /// if let TyKind::Closure(def_id, args) = closure_ty.kind()
1836    ///     && let Some(closure_kind) = args.as_closure().kind_ty().to_opt_closure_kind()
1837    /// {
1838    ///     println!("{closure_kind:?}");
1839    /// } else if let TyKind::CoroutineClosure(def_id, args) = closure_ty.kind()
1840    ///     && let Some(closure_kind) = args.as_coroutine_closure().kind_ty().to_opt_closure_kind()
1841    /// {
1842    ///     println!("{closure_kind:?}");
1843    /// }
1844    /// ```
1845    ///
1846    /// After upvar analysis, you should instead use [`ty::ClosureArgs::kind()`]
1847    /// or [`ty::CoroutineClosureArgs::kind()`] to assert that the `ClosureKind`
1848    /// has been constrained instead of manually calling this method.
1849    ///
1850    /// ```rust,ignore (snippet of compiler code)
1851    /// if let TyKind::Closure(def_id, args) = closure_ty.kind()
1852    /// {
1853    ///     println!("{:?}", args.as_closure().kind());
1854    /// } else if let TyKind::CoroutineClosure(def_id, args) = closure_ty.kind()
1855    /// {
1856    ///     println!("{:?}", args.as_coroutine_closure().kind());
1857    /// }
1858    /// ```
1859    pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1860        match self.kind() {
1861            Int(int_ty) => match int_ty {
1862                ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
1863                ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1864                ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1865                _ => 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),
1866            },
1867
1868            // "Bound" types appear in canonical queries when the
1869            // closure type is not yet known, and `Placeholder` and `Param`
1870            // may be encountered in generic `AsyncFnKindHelper` goals.
1871            Bound(..) | Placeholder(_) | Param(_) | Infer(_) => None,
1872
1873            Error(_) => Some(ty::ClosureKind::Fn),
1874
1875            _ => 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),
1876        }
1877    }
1878
1879    /// Inverse of [`Ty::to_opt_closure_kind`]. See docs on that method
1880    /// for explanation of the relationship between `Ty` and [`ty::ClosureKind`].
1881    pub fn from_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1882        match kind {
1883            ty::ClosureKind::Fn => tcx.types.i8,
1884            ty::ClosureKind::FnMut => tcx.types.i16,
1885            ty::ClosureKind::FnOnce => tcx.types.i32,
1886        }
1887    }
1888
1889    /// Like [`Ty::to_opt_closure_kind`], but it caps the "maximum" closure kind
1890    /// to `FnMut`. This is because although we have three capability states,
1891    /// `AsyncFn`/`AsyncFnMut`/`AsyncFnOnce`, we only need to distinguish two coroutine
1892    /// bodies: by-ref and by-value.
1893    ///
1894    /// See the definition of `AsyncFn` and `AsyncFnMut` and the `CallRefFuture`
1895    /// associated type for why we don't distinguish [`ty::ClosureKind::Fn`] and
1896    /// [`ty::ClosureKind::FnMut`] for the purpose of the generated MIR bodies.
1897    ///
1898    /// This method should be used when constructing a `Coroutine` out of a
1899    /// `CoroutineClosure`, when the `Coroutine`'s `kind` field is being populated
1900    /// directly from the `CoroutineClosure`'s `kind`.
1901    pub fn from_coroutine_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1902        match kind {
1903            ty::ClosureKind::Fn | ty::ClosureKind::FnMut => tcx.types.i16,
1904            ty::ClosureKind::FnOnce => tcx.types.i32,
1905        }
1906    }
1907
1908    /// Fast path helper for testing if a type is `Sized` or `MetaSized`.
1909    ///
1910    /// Returning true means the type is known to implement the sizedness trait. Returning `false`
1911    /// means nothing -- could be sized, might not be.
1912    ///
1913    /// Note that we could never rely on the fact that a type such as `[_]` is trivially `!Sized`
1914    /// because we could be in a type environment with a bound such as `[_]: Copy`. A function with
1915    /// such a bound obviously never can be called, but that doesn't mean it shouldn't typecheck.
1916    /// This is why this method doesn't return `Option<bool>`.
1917    #[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("compiler/rustc_middle/src/ty/sty.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1917u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::ty::sty"),
                                    ::tracing_core::field::FieldSet::new(&["self", "sizedness"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sizedness)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: 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).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")]
1918    pub fn has_trivial_sizedness(self, tcx: TyCtxt<'tcx>, sizedness: SizedTraitKind) -> bool {
1919        match self.kind() {
1920            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1921            | ty::Uint(_)
1922            | ty::Int(_)
1923            | ty::Bool
1924            | ty::Float(_)
1925            | ty::FnDef(..)
1926            | ty::FnPtr(..)
1927            | ty::UnsafeBinder(_)
1928            | ty::RawPtr(..)
1929            | ty::Char
1930            | ty::Ref(..)
1931            | ty::Coroutine(..)
1932            | ty::CoroutineWitness(..)
1933            | ty::Array(..)
1934            | ty::Pat(..)
1935            | ty::Closure(..)
1936            | ty::CoroutineClosure(..)
1937            | ty::Never
1938            | ty::Error(_) => true,
1939
1940            ty::Str | ty::Slice(_) | ty::Dynamic(_, _) => match sizedness {
1941                SizedTraitKind::Sized => false,
1942                SizedTraitKind::MetaSized => true,
1943            },
1944
1945            ty::Foreign(..) => match sizedness {
1946                SizedTraitKind::Sized | SizedTraitKind::MetaSized => false,
1947            },
1948
1949            ty::Tuple(tys) => tys.last().is_none_or(|ty| ty.has_trivial_sizedness(tcx, sizedness)),
1950
1951            ty::Adt(def, args) => def
1952                .sizedness_constraint(tcx, sizedness)
1953                .is_none_or(|ty| ty.instantiate(tcx, args).has_trivial_sizedness(tcx, sizedness)),
1954
1955            ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) | ty::Bound(..) => false,
1956
1957            ty::Infer(ty::TyVar(_)) => false,
1958
1959            ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1960                bug!("`has_trivial_sizedness` applied to unexpected type: {:?}", self)
1961            }
1962        }
1963    }
1964
1965    /// Fast path helper for primitives which are always `Copy` and which
1966    /// have a side-effect-free `Clone` impl.
1967    ///
1968    /// Returning true means the type is known to be pure and `Copy+Clone`.
1969    /// Returning `false` means nothing -- could be `Copy`, might not be.
1970    ///
1971    /// This is mostly useful for optimizations, as these are the types
1972    /// on which we can replace cloning with dereferencing.
1973    pub fn is_trivially_pure_clone_copy(self) -> bool {
1974        match self.kind() {
1975            ty::Bool | ty::Char | ty::Never => true,
1976
1977            // These aren't even `Clone`
1978            ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
1979
1980            ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
1981            | ty::Int(..)
1982            | ty::Uint(..)
1983            | ty::Float(..) => true,
1984
1985            // ZST which can't be named are fine.
1986            ty::FnDef(..) => true,
1987
1988            ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
1989
1990            // A 100-tuple isn't "trivial", so doing this only for reasonable sizes.
1991            ty::Tuple(field_tys) => {
1992                field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
1993            }
1994
1995            ty::Pat(ty, _) => ty.is_trivially_pure_clone_copy(),
1996
1997            // Sometimes traits aren't implemented for every ABI or arity,
1998            // because we can't be generic over everything yet.
1999            ty::FnPtr(..) => false,
2000
2001            // Definitely absolutely not copy.
2002            ty::Ref(_, _, hir::Mutability::Mut) => false,
2003
2004            // The standard library has a blanket Copy impl for shared references and raw pointers,
2005            // for all unsized types.
2006            ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => true,
2007
2008            ty::Coroutine(..) | ty::CoroutineWitness(..) => false,
2009
2010            // Might be, but not "trivial" so just giving the safe answer.
2011            ty::Adt(..) | ty::Closure(..) | ty::CoroutineClosure(..) => false,
2012
2013            ty::UnsafeBinder(_) => false,
2014
2015            // Needs normalization or revealing to determine, so no is the safe answer.
2016            ty::Alias(..) => false,
2017
2018            ty::Param(..) | ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(..) => {
2019                false
2020            }
2021        }
2022    }
2023
2024    pub fn is_trivially_wf(self, tcx: TyCtxt<'tcx>) -> bool {
2025        match *self.kind() {
2026            ty::Bool
2027            | ty::Char
2028            | ty::Int(_)
2029            | ty::Uint(_)
2030            | ty::Float(_)
2031            | ty::Str
2032            | ty::Never
2033            | ty::Param(_)
2034            | ty::Placeholder(_)
2035            | ty::Bound(..) => true,
2036
2037            ty::Slice(ty) => {
2038                ty.is_trivially_wf(tcx) && ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
2039            }
2040            ty::RawPtr(ty, _) => ty.is_trivially_wf(tcx),
2041
2042            ty::FnPtr(sig_tys, _) => {
2043                sig_tys.skip_binder().inputs_and_output.iter().all(|ty| ty.is_trivially_wf(tcx))
2044            }
2045            ty::Ref(_, ty, _) => ty.is_global() && ty.is_trivially_wf(tcx),
2046
2047            ty::Infer(infer) => match infer {
2048                ty::TyVar(_) => false,
2049                ty::IntVar(_) | ty::FloatVar(_) => true,
2050                ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => true,
2051            },
2052
2053            ty::Adt(_, _)
2054            | ty::Tuple(_)
2055            | ty::Array(..)
2056            | ty::Foreign(_)
2057            | ty::Pat(_, _)
2058            | ty::FnDef(..)
2059            | ty::UnsafeBinder(..)
2060            | ty::Dynamic(..)
2061            | ty::Closure(..)
2062            | ty::CoroutineClosure(..)
2063            | ty::Coroutine(..)
2064            | ty::CoroutineWitness(..)
2065            | ty::Alias(..)
2066            | ty::Error(_) => false,
2067        }
2068    }
2069
2070    /// If `self` is a primitive, return its [`Symbol`].
2071    pub fn primitive_symbol(self) -> Option<Symbol> {
2072        match self.kind() {
2073            ty::Bool => Some(sym::bool),
2074            ty::Char => Some(sym::char),
2075            ty::Float(f) => match f {
2076                ty::FloatTy::F16 => Some(sym::f16),
2077                ty::FloatTy::F32 => Some(sym::f32),
2078                ty::FloatTy::F64 => Some(sym::f64),
2079                ty::FloatTy::F128 => Some(sym::f128),
2080            },
2081            ty::Int(f) => match f {
2082                ty::IntTy::Isize => Some(sym::isize),
2083                ty::IntTy::I8 => Some(sym::i8),
2084                ty::IntTy::I16 => Some(sym::i16),
2085                ty::IntTy::I32 => Some(sym::i32),
2086                ty::IntTy::I64 => Some(sym::i64),
2087                ty::IntTy::I128 => Some(sym::i128),
2088            },
2089            ty::Uint(f) => match f {
2090                ty::UintTy::Usize => Some(sym::usize),
2091                ty::UintTy::U8 => Some(sym::u8),
2092                ty::UintTy::U16 => Some(sym::u16),
2093                ty::UintTy::U32 => Some(sym::u32),
2094                ty::UintTy::U64 => Some(sym::u64),
2095                ty::UintTy::U128 => Some(sym::u128),
2096            },
2097            ty::Str => Some(sym::str),
2098            _ => None,
2099        }
2100    }
2101
2102    pub fn is_c_void(self, tcx: TyCtxt<'_>) -> bool {
2103        match self.kind() {
2104            ty::Adt(adt, _) => tcx.is_lang_item(adt.did(), LangItem::CVoid),
2105            _ => false,
2106        }
2107    }
2108
2109    pub fn is_async_drop_in_place_coroutine(self, tcx: TyCtxt<'_>) -> bool {
2110        match self.kind() {
2111            ty::Coroutine(def, ..) => tcx.is_async_drop_in_place_coroutine(*def),
2112            _ => false,
2113        }
2114    }
2115
2116    /// Returns `true` when the outermost type cannot be further normalized,
2117    /// resolved, or instantiated. This includes all primitive types, but also
2118    /// things like ADTs and trait objects, since even if their arguments or
2119    /// nested types may be further simplified, the outermost [`TyKind`] or
2120    /// type constructor remains the same.
2121    pub fn is_known_rigid(self) -> bool {
2122        self.kind().is_known_rigid()
2123    }
2124
2125    /// Iterator that walks `self` and any types reachable from
2126    /// `self`, in depth-first order. Note that just walks the types
2127    /// that appear in `self`, it does not descend into the fields of
2128    /// structs or variants. For example:
2129    ///
2130    /// ```text
2131    /// isize => { isize }
2132    /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2133    /// [isize] => { [isize], isize }
2134    /// ```
2135    pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
2136        TypeWalker::new(self.into())
2137    }
2138}
2139
2140impl<'tcx> rustc_type_ir::inherent::Tys<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> {
2141    fn inputs(self) -> &'tcx [Ty<'tcx>] {
2142        self.split_last().unwrap().1
2143    }
2144
2145    fn output(self) -> Ty<'tcx> {
2146        *self.split_last().unwrap().0
2147    }
2148}
2149
2150impl<'tcx> rustc_type_ir::inherent::Symbol<TyCtxt<'tcx>> for Symbol {
2151    fn is_kw_underscore_lifetime(self) -> bool {
2152        self == kw::UnderscoreLifetime
2153    }
2154}
2155
2156// Some types are used a lot. Make sure they don't unintentionally get bigger.
2157#[cfg(target_pointer_width = "64")]
2158mod size_asserts {
2159    use rustc_data_structures::static_assert_size;
2160
2161    use super::*;
2162    // tidy-alphabetical-start
2163    const _: [(); 32] = [(); ::std::mem::size_of::<TyKind<'_>>()];static_assert_size!(TyKind<'_>, 32);
2164    const _: [(); 56] =
    [(); ::std::mem::size_of::<ty::WithCachedTypeInfo<TyKind<'_>>>()];static_assert_size!(ty::WithCachedTypeInfo<TyKind<'_>>, 56);
2165    // tidy-alphabetical-end
2166}