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, 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, 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    #[inline]
1257    pub fn is_scalable_vector(self) -> bool {
1258        match self.kind() {
1259            Adt(def, _) => def.repr().scalable(),
1260            _ => false,
1261        }
1262    }
1263
1264    pub fn sequence_element_type(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1265        match self.kind() {
1266            Array(ty, _) | Slice(ty) => *ty,
1267            Str => tcx.types.u8,
1268            _ => bug!("`sequence_element_type` called on non-sequence value: {}", self),
1269        }
1270    }
1271
1272    pub fn scalable_vector_element_count_and_type(self, tcx: TyCtxt<'tcx>) -> (u16, Ty<'tcx>) {
1273        let Adt(def, args) = self.kind() else {
1274            bug!("`scalable_vector_size_and_type` called on invalid type")
1275        };
1276        let Some(ScalableElt::ElementCount(element_count)) = def.repr().scalable else {
1277            bug!("`scalable_vector_size_and_type` called on non-scalable vector type");
1278        };
1279        let variant = def.non_enum_variant();
1280        assert_eq!(variant.fields.len(), 1);
1281        let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1282        (element_count, field_ty)
1283    }
1284
1285    pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {
1286        let Adt(def, args) = self.kind() else {
1287            bug!("`simd_size_and_type` called on invalid type")
1288        };
1289        assert!(def.repr().simd(), "`simd_size_and_type` called on non-SIMD type");
1290        let variant = def.non_enum_variant();
1291        assert_eq!(variant.fields.len(), 1);
1292        let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args);
1293        let Array(f0_elem_ty, f0_len) = field_ty.kind() else {
1294            bug!("Simd type has non-array field type {field_ty:?}")
1295        };
1296        // FIXME(repr_simd): https://github.com/rust-lang/rust/pull/78863#discussion_r522784112
1297        // The way we evaluate the `N` in `[T; N]` here only works since we use
1298        // `simd_size_and_type` post-monomorphization. It will probably start to ICE
1299        // if we use it in generic code. See the `simd-array-trait` ui test.
1300        (
1301            f0_len
1302                .try_to_target_usize(tcx)
1303                .expect("expected SIMD field to have definite array size"),
1304            *f0_elem_ty,
1305        )
1306    }
1307
1308    #[inline]
1309    pub fn is_mutable_ptr(self) -> bool {
1310        matches!(self.kind(), RawPtr(_, hir::Mutability::Mut) | Ref(_, _, hir::Mutability::Mut))
1311    }
1312
1313    /// Get the mutability of the reference or `None` when not a reference
1314    #[inline]
1315    pub fn ref_mutability(self) -> Option<hir::Mutability> {
1316        match self.kind() {
1317            Ref(_, _, mutability) => Some(*mutability),
1318            _ => None,
1319        }
1320    }
1321
1322    #[inline]
1323    pub fn is_raw_ptr(self) -> bool {
1324        matches!(self.kind(), RawPtr(_, _))
1325    }
1326
1327    /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer).
1328    /// `Box` is *not* considered a pointer here!
1329    #[inline]
1330    pub fn is_any_ptr(self) -> bool {
1331        self.is_ref() || self.is_raw_ptr() || self.is_fn_ptr()
1332    }
1333
1334    #[inline]
1335    pub fn is_box(self) -> bool {
1336        match self.kind() {
1337            Adt(def, _) => def.is_box(),
1338            _ => false,
1339        }
1340    }
1341
1342    /// Tests whether this is a Box definitely using the global allocator.
1343    ///
1344    /// If the allocator is still generic, the answer is `false`, but it may
1345    /// later turn out that it does use the global allocator.
1346    #[inline]
1347    pub fn is_box_global(self, tcx: TyCtxt<'tcx>) -> bool {
1348        match self.kind() {
1349            Adt(def, args) if def.is_box() => {
1350                let Some(alloc) = args.get(1) else {
1351                    // Single-argument Box is always global. (for "minicore" tests)
1352                    return true;
1353                };
1354                alloc.expect_ty().ty_adt_def().is_some_and(|alloc_adt| {
1355                    tcx.is_lang_item(alloc_adt.did(), LangItem::GlobalAlloc)
1356                })
1357            }
1358            _ => false,
1359        }
1360    }
1361
1362    pub fn boxed_ty(self) -> Option<Ty<'tcx>> {
1363        match self.kind() {
1364            Adt(def, args) if def.is_box() => Some(args.type_at(0)),
1365            _ => None,
1366        }
1367    }
1368
1369    pub fn pinned_ty(self) -> Option<Ty<'tcx>> {
1370        match self.kind() {
1371            Adt(def, args) if def.is_pin() => Some(args.type_at(0)),
1372            _ => None,
1373        }
1374    }
1375
1376    pub fn pinned_ref(self) -> Option<(Ty<'tcx>, ty::Mutability)> {
1377        if let Adt(def, args) = self.kind()
1378            && def.is_pin()
1379            && let &ty::Ref(_, ty, mutbl) = args.type_at(0).kind()
1380        {
1381            return Some((ty, mutbl));
1382        }
1383        None
1384    }
1385
1386    pub fn maybe_pinned_ref(self) -> Option<(Ty<'tcx>, ty::Pinnedness, ty::Mutability)> {
1387        match *self.kind() {
1388            Adt(def, args)
1389                if def.is_pin()
1390                    && let ty::Ref(_, ty, mutbl) = *args.type_at(0).kind() =>
1391            {
1392                Some((ty, ty::Pinnedness::Pinned, mutbl))
1393            }
1394            ty::Ref(_, ty, mutbl) => Some((ty, ty::Pinnedness::Not, mutbl)),
1395            _ => None,
1396        }
1397    }
1398
1399    /// Panics if called on any type other than `Box<T>`.
1400    pub fn expect_boxed_ty(self) -> Ty<'tcx> {
1401        self.boxed_ty()
1402            .unwrap_or_else(|| bug!("`expect_boxed_ty` is called on non-box type {:?}", self))
1403    }
1404
1405    /// A scalar type is one that denotes an atomic datum, with no sub-components.
1406    /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1407    /// contents are abstract to rustc.)
1408    #[inline]
1409    pub fn is_scalar(self) -> bool {
1410        matches!(
1411            self.kind(),
1412            Bool | Char
1413                | Int(_)
1414                | Float(_)
1415                | Uint(_)
1416                | FnDef(..)
1417                | FnPtr(..)
1418                | RawPtr(_, _)
1419                | Infer(IntVar(_) | FloatVar(_))
1420        )
1421    }
1422
1423    /// Returns `true` if this type is a floating point type.
1424    #[inline]
1425    pub fn is_floating_point(self) -> bool {
1426        matches!(self.kind(), Float(_) | Infer(FloatVar(_)))
1427    }
1428
1429    #[inline]
1430    pub fn is_trait(self) -> bool {
1431        matches!(self.kind(), Dynamic(_, _))
1432    }
1433
1434    #[inline]
1435    pub fn is_enum(self) -> bool {
1436        matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum())
1437    }
1438
1439    #[inline]
1440    pub fn is_union(self) -> bool {
1441        matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union())
1442    }
1443
1444    #[inline]
1445    pub fn is_closure(self) -> bool {
1446        matches!(self.kind(), Closure(..))
1447    }
1448
1449    #[inline]
1450    pub fn is_coroutine(self) -> bool {
1451        matches!(self.kind(), Coroutine(..))
1452    }
1453
1454    #[inline]
1455    pub fn is_coroutine_closure(self) -> bool {
1456        matches!(self.kind(), CoroutineClosure(..))
1457    }
1458
1459    #[inline]
1460    pub fn is_integral(self) -> bool {
1461        matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_))
1462    }
1463
1464    #[inline]
1465    pub fn is_fresh_ty(self) -> bool {
1466        matches!(self.kind(), Infer(FreshTy(_)))
1467    }
1468
1469    #[inline]
1470    pub fn is_fresh(self) -> bool {
1471        matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)))
1472    }
1473
1474    #[inline]
1475    pub fn is_char(self) -> bool {
1476        matches!(self.kind(), Char)
1477    }
1478
1479    #[inline]
1480    pub fn is_numeric(self) -> bool {
1481        self.is_integral() || self.is_floating_point()
1482    }
1483
1484    #[inline]
1485    pub fn is_signed(self) -> bool {
1486        matches!(self.kind(), Int(_))
1487    }
1488
1489    #[inline]
1490    pub fn is_ptr_sized_integral(self) -> bool {
1491        matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize))
1492    }
1493
1494    #[inline]
1495    pub fn has_concrete_skeleton(self) -> bool {
1496        !matches!(self.kind(), Param(_) | Infer(_) | Error(_))
1497    }
1498
1499    /// Checks whether a type recursively contains another type
1500    ///
1501    /// Example: `Option<()>` contains `()`
1502    pub fn contains(self, other: Ty<'tcx>) -> bool {
1503        struct ContainsTyVisitor<'tcx>(Ty<'tcx>);
1504
1505        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsTyVisitor<'tcx> {
1506            type Result = ControlFlow<()>;
1507
1508            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1509                if self.0 == t { ControlFlow::Break(()) } else { t.super_visit_with(self) }
1510            }
1511        }
1512
1513        let cf = self.visit_with(&mut ContainsTyVisitor(other));
1514        cf.is_break()
1515    }
1516
1517    /// Checks whether a type recursively contains any closure
1518    ///
1519    /// Example: `Option<{closure@file.rs:4:20}>` returns true
1520    pub fn contains_closure(self) -> bool {
1521        struct ContainsClosureVisitor;
1522
1523        impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsClosureVisitor {
1524            type Result = ControlFlow<()>;
1525
1526            fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1527                if let ty::Closure(..) = t.kind() {
1528                    ControlFlow::Break(())
1529                } else {
1530                    t.super_visit_with(self)
1531                }
1532            }
1533        }
1534
1535        let cf = self.visit_with(&mut ContainsClosureVisitor);
1536        cf.is_break()
1537    }
1538
1539    /// Returns the deepest `async_drop_in_place::{closure}` implementation.
1540    ///
1541    /// `async_drop_in_place<T>::{closure}`, when T is a coroutine, is a proxy-impl
1542    /// to call async drop poll from impl coroutine.
1543    pub fn find_async_drop_impl_coroutine<F: FnMut(Ty<'tcx>)>(
1544        self,
1545        tcx: TyCtxt<'tcx>,
1546        mut f: F,
1547    ) -> Ty<'tcx> {
1548        assert!(self.is_coroutine());
1549        let mut cor_ty = self;
1550        let mut ty = cor_ty;
1551        loop {
1552            let ty::Coroutine(def_id, args) = ty.kind() else { return cor_ty };
1553            cor_ty = ty;
1554            f(ty);
1555            if !tcx.is_async_drop_in_place_coroutine(*def_id) {
1556                return cor_ty;
1557            }
1558            ty = args.first().unwrap().expect_ty();
1559        }
1560    }
1561
1562    /// Returns the type of `*ty`.
1563    ///
1564    /// The parameter `explicit` indicates if this is an *explicit* dereference.
1565    /// Some types -- notably raw ptrs -- can only be dereferenced explicitly.
1566    pub fn builtin_deref(self, explicit: bool) -> Option<Ty<'tcx>> {
1567        match *self.kind() {
1568            _ if let Some(boxed) = self.boxed_ty() => Some(boxed),
1569            Ref(_, ty, _) => Some(ty),
1570            RawPtr(ty, _) if explicit => Some(ty),
1571            _ => None,
1572        }
1573    }
1574
1575    /// Returns the type of `ty[i]`.
1576    pub fn builtin_index(self) -> Option<Ty<'tcx>> {
1577        match self.kind() {
1578            Array(ty, _) | Slice(ty) => Some(*ty),
1579            _ => None,
1580        }
1581    }
1582
1583    #[tracing::instrument(level = "trace", skip(tcx))]
1584    pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
1585        self.kind().fn_sig(tcx)
1586    }
1587
1588    #[inline]
1589    pub fn is_fn(self) -> bool {
1590        matches!(self.kind(), FnDef(..) | FnPtr(..))
1591    }
1592
1593    #[inline]
1594    pub fn is_fn_ptr(self) -> bool {
1595        matches!(self.kind(), FnPtr(..))
1596    }
1597
1598    #[inline]
1599    pub fn is_impl_trait(self) -> bool {
1600        matches!(self.kind(), Alias(ty::Opaque, ..))
1601    }
1602
1603    #[inline]
1604    pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
1605        match self.kind() {
1606            Adt(adt, _) => Some(*adt),
1607            _ => None,
1608        }
1609    }
1610
1611    /// Iterates over tuple fields.
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            _ => bug!("tuple_fields called on non-tuple: {self:?}"),
1618        }
1619    }
1620
1621    /// If the type contains variants, returns the valid range of variant indices.
1622    //
1623    // FIXME: This requires the optimized MIR in the case of coroutines.
1624    #[inline]
1625    pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
1626        match self.kind() {
1627            TyKind::Adt(adt, _) => Some(adt.variant_range()),
1628            TyKind::Coroutine(def_id, args) => {
1629                Some(args.as_coroutine().variant_range(*def_id, tcx))
1630            }
1631            _ => None,
1632        }
1633    }
1634
1635    /// If the type contains variants, returns the variant for `variant_index`.
1636    /// Panics if `variant_index` is out of range.
1637    //
1638    // FIXME: This requires the optimized MIR in the case of coroutines.
1639    #[inline]
1640    pub fn discriminant_for_variant(
1641        self,
1642        tcx: TyCtxt<'tcx>,
1643        variant_index: VariantIdx,
1644    ) -> Option<Discr<'tcx>> {
1645        match self.kind() {
1646            TyKind::Adt(adt, _) if adt.is_enum() => {
1647                Some(adt.discriminant_for_variant(tcx, variant_index))
1648            }
1649            TyKind::Coroutine(def_id, args) => {
1650                Some(args.as_coroutine().discriminant_for_variant(*def_id, tcx, variant_index))
1651            }
1652            _ => None,
1653        }
1654    }
1655
1656    /// Returns the type of the discriminant of this type.
1657    pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1658        match self.kind() {
1659            ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
1660            ty::Coroutine(_, args) => args.as_coroutine().discr_ty(tcx),
1661
1662            ty::Param(_) | ty::Alias(..) | ty::Infer(ty::TyVar(_)) => {
1663                let assoc_items = tcx.associated_item_def_ids(
1664                    tcx.require_lang_item(hir::LangItem::DiscriminantKind, DUMMY_SP),
1665                );
1666                Ty::new_projection_from_args(tcx, assoc_items[0], tcx.mk_args(&[self.into()]))
1667            }
1668
1669            ty::Pat(ty, _) => ty.discriminant_ty(tcx),
1670
1671            ty::Bool
1672            | ty::Char
1673            | ty::Int(_)
1674            | ty::Uint(_)
1675            | ty::Float(_)
1676            | ty::Adt(..)
1677            | ty::Foreign(_)
1678            | ty::Str
1679            | ty::Array(..)
1680            | ty::Slice(_)
1681            | ty::RawPtr(_, _)
1682            | ty::Ref(..)
1683            | ty::FnDef(..)
1684            | ty::FnPtr(..)
1685            | ty::Dynamic(..)
1686            | ty::Closure(..)
1687            | ty::CoroutineClosure(..)
1688            | ty::CoroutineWitness(..)
1689            | ty::Never
1690            | ty::Tuple(_)
1691            | ty::UnsafeBinder(_)
1692            | ty::Error(_)
1693            | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
1694
1695            ty::Bound(..)
1696            | ty::Placeholder(_)
1697            | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1698                bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
1699            }
1700        }
1701    }
1702
1703    /// Returns the type of metadata for (potentially wide) pointers to this type,
1704    /// or the struct tail if the metadata type cannot be determined.
1705    pub fn ptr_metadata_ty_or_tail(
1706        self,
1707        tcx: TyCtxt<'tcx>,
1708        normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
1709    ) -> Result<Ty<'tcx>, Ty<'tcx>> {
1710        let tail = tcx.struct_tail_raw(self, &ObligationCause::dummy(), normalize, || {});
1711        match tail.kind() {
1712            // Sized types
1713            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1714            | ty::Uint(_)
1715            | ty::Int(_)
1716            | ty::Bool
1717            | ty::Float(_)
1718            | ty::FnDef(..)
1719            | ty::FnPtr(..)
1720            | ty::RawPtr(..)
1721            | ty::Char
1722            | ty::Ref(..)
1723            | ty::Coroutine(..)
1724            | ty::CoroutineWitness(..)
1725            | ty::Array(..)
1726            | ty::Closure(..)
1727            | ty::CoroutineClosure(..)
1728            | ty::Never
1729            | ty::Error(_)
1730            // Extern types have metadata = ().
1731            | ty::Foreign(..)
1732            // If returned by `struct_tail_raw` this is a unit struct
1733            // without any fields, or not a struct, and therefore is Sized.
1734            | ty::Adt(..)
1735            // If returned by `struct_tail_raw` this is the empty tuple,
1736            // a.k.a. unit type, which is Sized
1737            | ty::Tuple(..) => Ok(tcx.types.unit),
1738
1739            ty::Str | ty::Slice(_) => Ok(tcx.types.usize),
1740
1741            ty::Dynamic(_, _) => {
1742                let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, DUMMY_SP);
1743                Ok(tcx.type_of(dyn_metadata).instantiate(tcx, &[tail.into()]))
1744            }
1745
1746            // We don't know the metadata of `self`, but it must be equal to the
1747            // metadata of `tail`.
1748            ty::Param(_) | ty::Alias(..) => Err(tail),
1749
1750            | ty::UnsafeBinder(_) => todo!("FIXME(unsafe_binder)"),
1751
1752            ty::Infer(ty::TyVar(_))
1753            | ty::Pat(..)
1754            | ty::Bound(..)
1755            | ty::Placeholder(..)
1756            | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => bug!(
1757                "`ptr_metadata_ty_or_tail` applied to unexpected type: {self:?} (tail = {tail:?})"
1758            ),
1759        }
1760    }
1761
1762    /// Returns the type of metadata for (potentially wide) pointers to this type.
1763    /// Causes an ICE if the metadata type cannot be determined.
1764    pub fn ptr_metadata_ty(
1765        self,
1766        tcx: TyCtxt<'tcx>,
1767        normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
1768    ) -> Ty<'tcx> {
1769        match self.ptr_metadata_ty_or_tail(tcx, normalize) {
1770            Ok(metadata) => metadata,
1771            Err(tail) => bug!(
1772                "`ptr_metadata_ty` failed to get metadata for type: {self:?} (tail = {tail:?})"
1773            ),
1774        }
1775    }
1776
1777    /// Given a pointer or reference type, returns the type of the *pointee*'s
1778    /// metadata. If it can't be determined exactly (perhaps due to still
1779    /// being generic) then a projection through `ptr::Pointee` will be returned.
1780    ///
1781    /// This is particularly useful for getting the type of the result of
1782    /// [`UnOp::PtrMetadata`](crate::mir::UnOp::PtrMetadata).
1783    ///
1784    /// Panics if `self` is not dereferenceable.
1785    #[track_caller]
1786    pub fn pointee_metadata_ty_or_projection(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1787        let Some(pointee_ty) = self.builtin_deref(true) else {
1788            bug!("Type {self:?} is not a pointer or reference type")
1789        };
1790        if pointee_ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized) {
1791            tcx.types.unit
1792        } else {
1793            match pointee_ty.ptr_metadata_ty_or_tail(tcx, |x| x) {
1794                Ok(metadata_ty) => metadata_ty,
1795                Err(tail_ty) => {
1796                    let metadata_def_id = tcx.require_lang_item(LangItem::Metadata, DUMMY_SP);
1797                    Ty::new_projection(tcx, metadata_def_id, [tail_ty])
1798                }
1799            }
1800        }
1801    }
1802
1803    /// When we create a closure, we record its kind (i.e., what trait
1804    /// it implements, constrained by how it uses its borrows) into its
1805    /// [`ty::ClosureArgs`] or [`ty::CoroutineClosureArgs`] using a type
1806    /// parameter. This is kind of a phantom type, except that the
1807    /// most convenient thing for us to are the integral types. This
1808    /// function converts such a special type into the closure
1809    /// kind. To go the other way, use [`Ty::from_closure_kind`].
1810    ///
1811    /// Note that during type checking, we use an inference variable
1812    /// to represent the closure kind, because it has not yet been
1813    /// inferred. Once upvar inference (in `rustc_hir_analysis/src/check/upvar.rs`)
1814    /// is complete, that type variable will be unified with one of
1815    /// the integral types.
1816    ///
1817    /// ```rust,ignore (snippet of compiler code)
1818    /// if let TyKind::Closure(def_id, args) = closure_ty.kind()
1819    ///     && let Some(closure_kind) = args.as_closure().kind_ty().to_opt_closure_kind()
1820    /// {
1821    ///     println!("{closure_kind:?}");
1822    /// } else if let TyKind::CoroutineClosure(def_id, args) = closure_ty.kind()
1823    ///     && let Some(closure_kind) = args.as_coroutine_closure().kind_ty().to_opt_closure_kind()
1824    /// {
1825    ///     println!("{closure_kind:?}");
1826    /// }
1827    /// ```
1828    ///
1829    /// After upvar analysis, you should instead use [`ty::ClosureArgs::kind()`]
1830    /// or [`ty::CoroutineClosureArgs::kind()`] to assert that the `ClosureKind`
1831    /// has been constrained instead of manually calling this method.
1832    ///
1833    /// ```rust,ignore (snippet of compiler code)
1834    /// if let TyKind::Closure(def_id, args) = closure_ty.kind()
1835    /// {
1836    ///     println!("{:?}", args.as_closure().kind());
1837    /// } else if let TyKind::CoroutineClosure(def_id, args) = closure_ty.kind()
1838    /// {
1839    ///     println!("{:?}", args.as_coroutine_closure().kind());
1840    /// }
1841    /// ```
1842    pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
1843        match self.kind() {
1844            Int(int_ty) => match int_ty {
1845                ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
1846                ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
1847                ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
1848                _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1849            },
1850
1851            // "Bound" types appear in canonical queries when the
1852            // closure type is not yet known, and `Placeholder` and `Param`
1853            // may be encountered in generic `AsyncFnKindHelper` goals.
1854            Bound(..) | Placeholder(_) | Param(_) | Infer(_) => None,
1855
1856            Error(_) => Some(ty::ClosureKind::Fn),
1857
1858            _ => bug!("cannot convert type `{:?}` to a closure kind", self),
1859        }
1860    }
1861
1862    /// Inverse of [`Ty::to_opt_closure_kind`]. See docs on that method
1863    /// for explanation of the relationship between `Ty` and [`ty::ClosureKind`].
1864    pub fn from_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1865        match kind {
1866            ty::ClosureKind::Fn => tcx.types.i8,
1867            ty::ClosureKind::FnMut => tcx.types.i16,
1868            ty::ClosureKind::FnOnce => tcx.types.i32,
1869        }
1870    }
1871
1872    /// Like [`Ty::to_opt_closure_kind`], but it caps the "maximum" closure kind
1873    /// to `FnMut`. This is because although we have three capability states,
1874    /// `AsyncFn`/`AsyncFnMut`/`AsyncFnOnce`, we only need to distinguish two coroutine
1875    /// bodies: by-ref and by-value.
1876    ///
1877    /// See the definition of `AsyncFn` and `AsyncFnMut` and the `CallRefFuture`
1878    /// associated type for why we don't distinguish [`ty::ClosureKind::Fn`] and
1879    /// [`ty::ClosureKind::FnMut`] for the purpose of the generated MIR bodies.
1880    ///
1881    /// This method should be used when constructing a `Coroutine` out of a
1882    /// `CoroutineClosure`, when the `Coroutine`'s `kind` field is being populated
1883    /// directly from the `CoroutineClosure`'s `kind`.
1884    pub fn from_coroutine_closure_kind(tcx: TyCtxt<'tcx>, kind: ty::ClosureKind) -> Ty<'tcx> {
1885        match kind {
1886            ty::ClosureKind::Fn | ty::ClosureKind::FnMut => tcx.types.i16,
1887            ty::ClosureKind::FnOnce => tcx.types.i32,
1888        }
1889    }
1890
1891    /// Fast path helper for testing if a type is `Sized` or `MetaSized`.
1892    ///
1893    /// Returning true means the type is known to implement the sizedness trait. Returning `false`
1894    /// means nothing -- could be sized, might not be.
1895    ///
1896    /// Note that we could never rely on the fact that a type such as `[_]` is trivially `!Sized`
1897    /// because we could be in a type environment with a bound such as `[_]: Copy`. A function with
1898    /// such a bound obviously never can be called, but that doesn't mean it shouldn't typecheck.
1899    /// This is why this method doesn't return `Option<bool>`.
1900    #[instrument(skip(tcx), level = "debug")]
1901    pub fn has_trivial_sizedness(self, tcx: TyCtxt<'tcx>, sizedness: SizedTraitKind) -> bool {
1902        match self.kind() {
1903            ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1904            | ty::Uint(_)
1905            | ty::Int(_)
1906            | ty::Bool
1907            | ty::Float(_)
1908            | ty::FnDef(..)
1909            | ty::FnPtr(..)
1910            | ty::UnsafeBinder(_)
1911            | ty::RawPtr(..)
1912            | ty::Char
1913            | ty::Ref(..)
1914            | ty::Coroutine(..)
1915            | ty::CoroutineWitness(..)
1916            | ty::Array(..)
1917            | ty::Pat(..)
1918            | ty::Closure(..)
1919            | ty::CoroutineClosure(..)
1920            | ty::Never
1921            | ty::Error(_) => true,
1922
1923            ty::Str | ty::Slice(_) | ty::Dynamic(_, _) => match sizedness {
1924                SizedTraitKind::Sized => false,
1925                SizedTraitKind::MetaSized => true,
1926            },
1927
1928            ty::Foreign(..) => match sizedness {
1929                SizedTraitKind::Sized | SizedTraitKind::MetaSized => false,
1930            },
1931
1932            ty::Tuple(tys) => tys.last().is_none_or(|ty| ty.has_trivial_sizedness(tcx, sizedness)),
1933
1934            ty::Adt(def, args) => def
1935                .sizedness_constraint(tcx, sizedness)
1936                .is_none_or(|ty| ty.instantiate(tcx, args).has_trivial_sizedness(tcx, sizedness)),
1937
1938            ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) | ty::Bound(..) => false,
1939
1940            ty::Infer(ty::TyVar(_)) => false,
1941
1942            ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1943                bug!("`has_trivial_sizedness` applied to unexpected type: {:?}", self)
1944            }
1945        }
1946    }
1947
1948    /// Fast path helper for primitives which are always `Copy` and which
1949    /// have a side-effect-free `Clone` impl.
1950    ///
1951    /// Returning true means the type is known to be pure and `Copy+Clone`.
1952    /// Returning `false` means nothing -- could be `Copy`, might not be.
1953    ///
1954    /// This is mostly useful for optimizations, as these are the types
1955    /// on which we can replace cloning with dereferencing.
1956    pub fn is_trivially_pure_clone_copy(self) -> bool {
1957        match self.kind() {
1958            ty::Bool | ty::Char | ty::Never => true,
1959
1960            // These aren't even `Clone`
1961            ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
1962
1963            ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
1964            | ty::Int(..)
1965            | ty::Uint(..)
1966            | ty::Float(..) => true,
1967
1968            // ZST which can't be named are fine.
1969            ty::FnDef(..) => true,
1970
1971            ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
1972
1973            // A 100-tuple isn't "trivial", so doing this only for reasonable sizes.
1974            ty::Tuple(field_tys) => {
1975                field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
1976            }
1977
1978            ty::Pat(ty, _) => ty.is_trivially_pure_clone_copy(),
1979
1980            // Sometimes traits aren't implemented for every ABI or arity,
1981            // because we can't be generic over everything yet.
1982            ty::FnPtr(..) => false,
1983
1984            // Definitely absolutely not copy.
1985            ty::Ref(_, _, hir::Mutability::Mut) => false,
1986
1987            // The standard library has a blanket Copy impl for shared references and raw pointers,
1988            // for all unsized types.
1989            ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => true,
1990
1991            ty::Coroutine(..) | ty::CoroutineWitness(..) => false,
1992
1993            // Might be, but not "trivial" so just giving the safe answer.
1994            ty::Adt(..) | ty::Closure(..) | ty::CoroutineClosure(..) => false,
1995
1996            ty::UnsafeBinder(_) => false,
1997
1998            // Needs normalization or revealing to determine, so no is the safe answer.
1999            ty::Alias(..) => false,
2000
2001            ty::Param(..) | ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(..) => {
2002                false
2003            }
2004        }
2005    }
2006
2007    pub fn is_trivially_wf(self, tcx: TyCtxt<'tcx>) -> bool {
2008        match *self.kind() {
2009            ty::Bool
2010            | ty::Char
2011            | ty::Int(_)
2012            | ty::Uint(_)
2013            | ty::Float(_)
2014            | ty::Str
2015            | ty::Never
2016            | ty::Param(_)
2017            | ty::Placeholder(_)
2018            | ty::Bound(..) => true,
2019
2020            ty::Slice(ty) => {
2021                ty.is_trivially_wf(tcx) && ty.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
2022            }
2023            ty::RawPtr(ty, _) => ty.is_trivially_wf(tcx),
2024
2025            ty::FnPtr(sig_tys, _) => {
2026                sig_tys.skip_binder().inputs_and_output.iter().all(|ty| ty.is_trivially_wf(tcx))
2027            }
2028            ty::Ref(_, ty, _) => ty.is_global() && ty.is_trivially_wf(tcx),
2029
2030            ty::Infer(infer) => match infer {
2031                ty::TyVar(_) => false,
2032                ty::IntVar(_) | ty::FloatVar(_) => true,
2033                ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => true,
2034            },
2035
2036            ty::Adt(_, _)
2037            | ty::Tuple(_)
2038            | ty::Array(..)
2039            | ty::Foreign(_)
2040            | ty::Pat(_, _)
2041            | ty::FnDef(..)
2042            | ty::UnsafeBinder(..)
2043            | ty::Dynamic(..)
2044            | ty::Closure(..)
2045            | ty::CoroutineClosure(..)
2046            | ty::Coroutine(..)
2047            | ty::CoroutineWitness(..)
2048            | ty::Alias(..)
2049            | ty::Error(_) => false,
2050        }
2051    }
2052
2053    /// If `self` is a primitive, return its [`Symbol`].
2054    pub fn primitive_symbol(self) -> Option<Symbol> {
2055        match self.kind() {
2056            ty::Bool => Some(sym::bool),
2057            ty::Char => Some(sym::char),
2058            ty::Float(f) => match f {
2059                ty::FloatTy::F16 => Some(sym::f16),
2060                ty::FloatTy::F32 => Some(sym::f32),
2061                ty::FloatTy::F64 => Some(sym::f64),
2062                ty::FloatTy::F128 => Some(sym::f128),
2063            },
2064            ty::Int(f) => match f {
2065                ty::IntTy::Isize => Some(sym::isize),
2066                ty::IntTy::I8 => Some(sym::i8),
2067                ty::IntTy::I16 => Some(sym::i16),
2068                ty::IntTy::I32 => Some(sym::i32),
2069                ty::IntTy::I64 => Some(sym::i64),
2070                ty::IntTy::I128 => Some(sym::i128),
2071            },
2072            ty::Uint(f) => match f {
2073                ty::UintTy::Usize => Some(sym::usize),
2074                ty::UintTy::U8 => Some(sym::u8),
2075                ty::UintTy::U16 => Some(sym::u16),
2076                ty::UintTy::U32 => Some(sym::u32),
2077                ty::UintTy::U64 => Some(sym::u64),
2078                ty::UintTy::U128 => Some(sym::u128),
2079            },
2080            ty::Str => Some(sym::str),
2081            _ => None,
2082        }
2083    }
2084
2085    pub fn is_c_void(self, tcx: TyCtxt<'_>) -> bool {
2086        match self.kind() {
2087            ty::Adt(adt, _) => tcx.is_lang_item(adt.did(), LangItem::CVoid),
2088            _ => false,
2089        }
2090    }
2091
2092    pub fn is_async_drop_in_place_coroutine(self, tcx: TyCtxt<'_>) -> bool {
2093        match self.kind() {
2094            ty::Coroutine(def, ..) => tcx.is_async_drop_in_place_coroutine(*def),
2095            _ => false,
2096        }
2097    }
2098
2099    /// Returns `true` when the outermost type cannot be further normalized,
2100    /// resolved, or instantiated. This includes all primitive types, but also
2101    /// things like ADTs and trait objects, since even if their arguments or
2102    /// nested types may be further simplified, the outermost [`TyKind`] or
2103    /// type constructor remains the same.
2104    pub fn is_known_rigid(self) -> bool {
2105        self.kind().is_known_rigid()
2106    }
2107
2108    /// Iterator that walks `self` and any types reachable from
2109    /// `self`, in depth-first order. Note that just walks the types
2110    /// that appear in `self`, it does not descend into the fields of
2111    /// structs or variants. For example:
2112    ///
2113    /// ```text
2114    /// isize => { isize }
2115    /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
2116    /// [isize] => { [isize], isize }
2117    /// ```
2118    pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
2119        TypeWalker::new(self.into())
2120    }
2121}
2122
2123impl<'tcx> rustc_type_ir::inherent::Tys<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> {
2124    fn inputs(self) -> &'tcx [Ty<'tcx>] {
2125        self.split_last().unwrap().1
2126    }
2127
2128    fn output(self) -> Ty<'tcx> {
2129        *self.split_last().unwrap().0
2130    }
2131}
2132
2133// Some types are used a lot. Make sure they don't unintentionally get bigger.
2134#[cfg(target_pointer_width = "64")]
2135mod size_asserts {
2136    use rustc_data_structures::static_assert_size;
2137
2138    use super::*;
2139    // tidy-alphabetical-start
2140    static_assert_size!(TyKind<'_>, 24);
2141    static_assert_size!(ty::WithCachedTypeInfo<TyKind<'_>>, 48);
2142    // tidy-alphabetical-end
2143}