]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_middle/src/ty/cast.rs
New upstream version 1.64.0+dfsg1
[rustc.git] / compiler / rustc_middle / src / ty / cast.rs
CommitLineData
62682a34 1// Helpers for handling cast expressions, used in both
94b46f34 2// typeck and codegen.
62682a34 3
9fa01778 4use crate::ty::{self, Ty};
62682a34 5
532ac7d7 6use rustc_macros::HashStable;
62682a34
SL
7
8/// Types that are represented as ints.
9#[derive(Copy, Clone, Debug, PartialEq, Eq)]
10pub enum IntTy {
5869c6ff 11 U(ty::UintTy),
62682a34
SL
12 I,
13 CEnum,
14 Bool,
dfeec247 15 Char,
62682a34
SL
16}
17
064997fb
FG
18impl IntTy {
19 pub fn is_signed(self) -> bool {
20 matches!(self, Self::I)
21 }
22}
23
62682a34
SL
24// Valid types for the result of a non-coercion cast
25#[derive(Copy, Clone, Debug, PartialEq, Eq)]
26pub 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),
5869c6ff 30 /// Floating-point types.
62682a34 31 Float,
5869c6ff 32 /// Function pointers.
62682a34 33 FnPtr,
5869c6ff 34 /// Raw pointers.
94b46f34 35 Ptr(ty::TypeAndMut<'tcx>),
62682a34
SL
36}
37
5869c6ff
XL
38/// Cast Kind. See [RFC 401](https://rust-lang.github.io/rfcs/0401-coercions.html)
39/// (or librustc_typeck/check/cast.rs).
3dfed10e 40#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
62682a34
SL
41pub enum CastKind {
42 CoercionCast,
43 PtrPtrCast,
44 PtrAddrCast,
45 AddrPtrCast,
46 NumericCast,
47 EnumCast,
48 PrimIntCast,
49 U8CharCast,
50 ArrayPtrCast,
51 FnPtrPtrCast,
dfeec247 52 FnPtrAddrCast,
62682a34
SL
53}
54
55impl<'tcx> CastTy<'tcx> {
0bf4aa26 56 /// Returns `Some` for integral/pointer casts.
5869c6ff 57 /// Casts like unsizing casts will return `None`.
e9174d1e 58 pub fn from_ty(t: Ty<'tcx>) -> Option<CastTy<'tcx>> {
1b1a35ee 59 match *t.kind() {
b7449926
XL
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),
dfeec247 67 ty::Adt(d, _) if d.is_enum() && d.is_payloadfree() => Some(CastTy::Int(IntTy::CEnum)),
b7449926 68 ty::RawPtr(mt) => Some(CastTy::Ptr(mt)),
b7449926 69 ty::FnPtr(..) => Some(CastTy::FnPtr),
62682a34
SL
70 _ => None,
71 }
72 }
73}