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