1 // Helpers for handling cast expressions, used in both 2 // typeck and codegen. 3 4 use crate::ty::{self, Ty}; 5 6 use rustc_macros::HashStable; 7 8 /// Types that are represented as ints. 9 #[derive(Copy, Clone, Debug, PartialEq, Eq)] 10 pub enum IntTy { 11 U(ty::UintTy), 12 I, 13 CEnum, 14 Bool, 15 Char, 16 } 17 18 // Valid types for the result of a non-coercion cast 19 #[derive(Copy, Clone, Debug, PartialEq, Eq)] 20 pub enum CastTy<'tcx> { 21 /// Various types that are represented as ints and handled mostly 22 /// in the same way, merged for easier matching. 23 Int(IntTy), 24 /// Floating-point types. 25 Float, 26 /// Function pointers. 27 FnPtr, 28 /// Raw pointers. 29 Ptr(ty::TypeAndMut<'tcx>), 30 } 31 32 /// Cast Kind. See [RFC 401](https://rust-lang.github.io/rfcs/0401-coercions.html) 33 /// (or librustc_typeck/check/cast.rs). 34 #[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)] 35 pub enum CastKind { 36 CoercionCast, 37 PtrPtrCast, 38 PtrAddrCast, 39 AddrPtrCast, 40 NumericCast, 41 EnumCast, 42 PrimIntCast, 43 U8CharCast, 44 ArrayPtrCast, 45 FnPtrPtrCast, 46 FnPtrAddrCast, 47 } 48 49 impl<'tcx> CastTy<'tcx> { 50 /// Returns `Some` for integral/pointer casts. 51 /// Casts like unsizing casts will return `None`. from_ty(t: Ty<'tcx>) -> Option<CastTy<'tcx>>52 pub fn from_ty(t: Ty<'tcx>) -> Option<CastTy<'tcx>> { 53 match *t.kind() { 54 ty::Bool => Some(CastTy::Int(IntTy::Bool)), 55 ty::Char => Some(CastTy::Int(IntTy::Char)), 56 ty::Int(_) => Some(CastTy::Int(IntTy::I)), 57 ty::Infer(ty::InferTy::IntVar(_)) => Some(CastTy::Int(IntTy::I)), 58 ty::Infer(ty::InferTy::FloatVar(_)) => Some(CastTy::Float), 59 ty::Uint(u) => Some(CastTy::Int(IntTy::U(u))), 60 ty::Float(_) => Some(CastTy::Float), 61 ty::Adt(d, _) if d.is_enum() && d.is_payloadfree() => Some(CastTy::Int(IntTy::CEnum)), 62 ty::RawPtr(mt) => Some(CastTy::Ptr(mt)), 63 ty::FnPtr(..) => Some(CastTy::FnPtr), 64 _ => None, 65 } 66 } 67 } 68