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