1 // Helpers for handling cast expressions, used in both
4 use crate::ty::{self, Ty};
6 use rustc_macros::HashStable;
8 /// Types that are represented as ints.
9 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
19 pub fn is_signed(self) -> bool {
20 matches!(self, Self::I)
24 // Valid types for the result of a non-coercion cast
25 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
26 pub enum CastTy<'tcx> {
27 /// Various types that are represented as ints and handled mostly
28 /// in the same way, merged for easier matching.
30 /// Floating-point types.
32 /// Function pointers.
35 Ptr(ty::TypeAndMut<'tcx>),
36 /// Casting into a `dyn*` value.
40 /// Cast Kind. See [RFC 401](https://rust-lang.github.io/rfcs/0401-coercions.html)
41 /// (or rustc_hir_analysis/check/cast.rs).
42 #[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
58 impl<'tcx> CastTy<'tcx> {
59 /// Returns `Some` for integral/pointer casts.
60 /// Casts like unsizing casts will return `None`.
61 pub fn from_ty(t: Ty<'tcx>) -> Option<CastTy<'tcx>> {
63 ty::Bool => Some(CastTy::Int(IntTy::Bool)),
64 ty::Char => Some(CastTy::Int(IntTy::Char)),
65 ty::Int(_) => Some(CastTy::Int(IntTy::I)),
66 ty::Infer(ty::InferTy::IntVar(_)) => Some(CastTy::Int(IntTy::I)),
67 ty::Infer(ty::InferTy::FloatVar(_)) => Some(CastTy::Float),
68 ty::Uint(u) => Some(CastTy::Int(IntTy::U(u))),
69 ty::Float(_) => Some(CastTy::Float),
70 ty::Adt(d, _) if d.is_enum() && d.is_payloadfree() => Some(CastTy::Int(IntTy::CEnum)),
71 ty::RawPtr(mt) => Some(CastTy::Ptr(mt)),
72 ty::FnPtr(..) => Some(CastTy::FnPtr),
73 ty::Dynamic(_, _, ty::DynStar) => Some(CastTy::DynStar),