1 // Helpers for handling cast expressions, used in both
4 use crate::ty::{self, Ty};
7 use rustc_macros::HashStable;
9 /// Types that are represented as ints.
10 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
20 pub fn is_signed(self) -> bool {
21 matches!(self, Self::I)
25 // Valid types for the result of a non-coercion cast
26 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
27 pub enum CastTy<'tcx> {
28 /// Various types that are represented as ints and handled mostly
29 /// in the same way, merged for easier matching.
31 /// Floating-point types.
33 /// Function pointers.
36 Ptr(ty::TypeAndMut<'tcx>),
37 /// Casting into a `dyn*` value.
41 /// Cast Kind. See [RFC 401](https://rust-lang.github.io/rfcs/0401-coercions.html)
42 /// (or rustc_hir_analysis/check/cast.rs).
43 #[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
59 impl<'tcx> CastTy<'tcx> {
60 /// Returns `Some` for integral/pointer casts.
61 /// Casts like unsizing casts will return `None`.
62 pub fn from_ty(t: Ty<'tcx>) -> Option<CastTy<'tcx>> {
64 ty::Bool => Some(CastTy::Int(IntTy::Bool)),
65 ty::Char => Some(CastTy::Int(IntTy::Char)),
66 ty::Int(_) => Some(CastTy::Int(IntTy::I)),
67 ty::Infer(ty::InferTy::IntVar(_)) => Some(CastTy::Int(IntTy::I)),
68 ty::Infer(ty::InferTy::FloatVar(_)) => Some(CastTy::Float),
69 ty::Uint(u) => Some(CastTy::Int(IntTy::U(u))),
70 ty::Float(_) => Some(CastTy::Float),
71 ty::Adt(d, _) if d.is_enum() && d.is_payloadfree() => Some(CastTy::Int(IntTy::CEnum)),
72 ty::RawPtr(mt) => Some(CastTy::Ptr(mt)),
73 ty::FnPtr(..) => Some(CastTy::FnPtr),
74 ty::Dynamic(_, _, ty::DynStar) => Some(CastTy::DynStar),
80 /// Returns `mir::CastKind` from the given parameters.
81 pub fn mir_cast_kind<'tcx>(from_ty: Ty<'tcx>, cast_ty: Ty<'tcx>) -> mir::CastKind {
82 let from = CastTy::from_ty(from_ty);
83 let cast = CastTy::from_ty(cast_ty);
84 let cast_kind = match (from, cast) {
85 (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => {
86 mir::CastKind::PointerExposeAddress
88 (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => mir::CastKind::PointerFromExposedAddress,
89 (_, Some(CastTy::DynStar)) => mir::CastKind::DynStar,
90 (Some(CastTy::Int(_)), Some(CastTy::Int(_))) => mir::CastKind::IntToInt,
91 (Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => mir::CastKind::FnPtrToPtr,
93 (Some(CastTy::Float), Some(CastTy::Int(_))) => mir::CastKind::FloatToInt,
94 (Some(CastTy::Int(_)), Some(CastTy::Float)) => mir::CastKind::IntToFloat,
95 (Some(CastTy::Float), Some(CastTy::Float)) => mir::CastKind::FloatToFloat,
96 (Some(CastTy::Ptr(_)), Some(CastTy::Ptr(_))) => mir::CastKind::PtrToPtr,
99 bug!("Attempting to cast non-castable types {:?} and {:?}", from_ty, cast_ty)