]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/cast.rs
Rollup merge of #101677 - winxpqq955:issue-101211, r=fee1-dead
[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 }
37
38 /// Cast Kind. See [RFC 401](https://rust-lang.github.io/rfcs/0401-coercions.html)
39 /// (or librustc_typeck/check/cast.rs).
40 #[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
41 pub enum CastKind {
42     CoercionCast,
43     PtrPtrCast,
44     PtrAddrCast,
45     AddrPtrCast,
46     NumericCast,
47     EnumCast,
48     PrimIntCast,
49     U8CharCast,
50     ArrayPtrCast,
51     FnPtrPtrCast,
52     FnPtrAddrCast,
53 }
54
55 impl<'tcx> CastTy<'tcx> {
56     /// Returns `Some` for integral/pointer casts.
57     /// Casts like unsizing casts will return `None`.
58     pub fn from_ty(t: Ty<'tcx>) -> Option<CastTy<'tcx>> {
59         match *t.kind() {
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),
67             ty::Adt(d, _) if d.is_enum() && d.is_payloadfree() => Some(CastTy::Int(IntTy::CEnum)),
68             ty::RawPtr(mt) => Some(CastTy::Ptr(mt)),
69             ty::FnPtr(..) => Some(CastTy::FnPtr),
70             _ => None,
71         }
72     }
73 }