]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/cast.rs
Auto merge of #100845 - timvermeulen:iter_compare, r=scottmcm
[rust.git] / compiler / rustc_middle / src / ty / cast.rs
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 impl IntTy {
19     pub fn is_signed(self) -> bool {
20         matches!(self, Self::I)
21     }
22 }
23
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.
29     Int(IntTy),
30     /// Floating-point types.
31     Float,
32     /// Function pointers.
33     FnPtr,
34     /// Raw pointers.
35     Ptr(ty::TypeAndMut<'tcx>),
36     /// Casting into a `dyn*` value.
37     DynStar,
38 }
39
40 /// Cast Kind. See [RFC 401](https://rust-lang.github.io/rfcs/0401-coercions.html)
41 /// (or librustc_typeck/check/cast.rs).
42 #[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
43 pub enum CastKind {
44     CoercionCast,
45     PtrPtrCast,
46     PtrAddrCast,
47     AddrPtrCast,
48     NumericCast,
49     EnumCast,
50     PrimIntCast,
51     U8CharCast,
52     ArrayPtrCast,
53     FnPtrPtrCast,
54     FnPtrAddrCast,
55     DynStarCast,
56 }
57
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>> {
62         match *t.kind() {
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),
74             _ => None,
75         }
76     }
77 }