rustc_middle/ty/
cast.rs
1use rustc_macros::{HashStable, TyDecodable, TyEncodable};
5
6use crate::mir;
7use crate::ty::{self, Ty};
8
9#[derive(Copy, Clone, Debug, PartialEq, Eq)]
11pub enum IntTy {
12 U(ty::UintTy),
13 I,
14 CEnum,
15 Bool,
16 Char,
17}
18
19impl IntTy {
20 pub fn is_signed(self) -> bool {
21 matches!(self, Self::I)
22 }
23}
24
25#[derive(Copy, Clone, Debug, PartialEq, Eq)]
27pub enum CastTy<'tcx> {
28 Int(IntTy),
31 Float,
33 FnPtr,
35 Ptr(ty::TypeAndMut<'tcx>),
37}
38
39#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
42pub enum CastKind {
43 PtrPtrCast,
44 PtrAddrCast,
45 AddrPtrCast,
46 NumericCast,
47 EnumCast,
48 PrimIntCast,
49 U8CharCast,
50 ArrayPtrCast,
51 FnPtrPtrCast,
52 FnPtrAddrCast,
53}
54
55impl<'tcx> CastTy<'tcx> {
56 pub fn from_ty(t: Ty<'tcx>) -> Option<CastTy<'tcx>> {
59 match *t.kind() {
60 ty::Bool => Some(CastTy::Int(IntTy::Bool)),
61 ty::Char => Some(CastTy::Int(IntTy::Char)),
62 ty::Int(_) => Some(CastTy::Int(IntTy::I)),
63 ty::Infer(ty::InferTy::IntVar(_)) => Some(CastTy::Int(IntTy::I)),
64 ty::Infer(ty::InferTy::FloatVar(_)) => Some(CastTy::Float),
65 ty::Uint(u) => Some(CastTy::Int(IntTy::U(u))),
66 ty::Float(_) => Some(CastTy::Float),
67 ty::Adt(d, _) if d.is_enum() && d.is_payloadfree() => Some(CastTy::Int(IntTy::CEnum)),
68 ty::RawPtr(ty, mutbl) => Some(CastTy::Ptr(ty::TypeAndMut { ty, mutbl })),
69 ty::FnPtr(..) => Some(CastTy::FnPtr),
70 _ => None,
71 }
72 }
73}
74
75pub fn mir_cast_kind<'tcx>(from_ty: Ty<'tcx>, cast_ty: Ty<'tcx>) -> mir::CastKind {
77 let from = CastTy::from_ty(from_ty);
78 let cast = CastTy::from_ty(cast_ty);
79 let cast_kind = match (from, cast) {
80 (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => {
81 mir::CastKind::PointerExposeProvenance
82 }
83 (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => mir::CastKind::PointerWithExposedProvenance,
84 (Some(CastTy::Int(_)), Some(CastTy::Int(_))) => mir::CastKind::IntToInt,
85 (Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => mir::CastKind::FnPtrToPtr,
86
87 (Some(CastTy::Float), Some(CastTy::Int(_))) => mir::CastKind::FloatToInt,
88 (Some(CastTy::Int(_)), Some(CastTy::Float)) => mir::CastKind::IntToFloat,
89 (Some(CastTy::Float), Some(CastTy::Float)) => mir::CastKind::FloatToFloat,
90 (Some(CastTy::Ptr(_)), Some(CastTy::Ptr(_))) => mir::CastKind::PtrToPtr,
91
92 (_, _) => {
93 bug!("Attempting to cast non-castable types {:?} and {:?}", from_ty, cast_ty)
94 }
95 };
96 cast_kind
97}