]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/cast.rs
Rollup merge of #59026 - GuillaumeGomez:search-tabs-header, r=QuietMisdreavus
[rust.git] / src / librustc / 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 syntax::ast;
7 use rustc_macros::HashStable;
8
9 /// Types that are represented as ints.
10 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
11 pub enum IntTy {
12     U(ast::UintTy),
13     I,
14     CEnum,
15     Bool,
16     Char
17 }
18
19 // Valid types for the result of a non-coercion cast
20 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
21 pub enum CastTy<'tcx> {
22     /// Various types that are represented as ints and handled mostly
23     /// in the same way, merged for easier matching.
24     Int(IntTy),
25     /// Floating-Point types
26     Float,
27     /// Function Pointers
28     FnPtr,
29     /// Raw pointers
30     Ptr(ty::TypeAndMut<'tcx>),
31     /// References
32     RPtr(ty::TypeAndMut<'tcx>),
33 }
34
35 /// Cast Kind. See RFC 401 (or librustc_typeck/check/cast.rs)
36 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
37 pub enum CastKind {
38     CoercionCast,
39     PtrPtrCast,
40     PtrAddrCast,
41     AddrPtrCast,
42     NumericCast,
43     EnumCast,
44     PrimIntCast,
45     U8CharCast,
46     ArrayPtrCast,
47     FnPtrPtrCast,
48     FnPtrAddrCast
49 }
50
51 impl<'tcx> CastTy<'tcx> {
52     /// Returns `Some` for integral/pointer casts.
53     /// casts like unsizing casts will return `None`
54     pub fn from_ty(t: Ty<'tcx>) -> Option<CastTy<'tcx>> {
55         match t.sty {
56             ty::Bool => Some(CastTy::Int(IntTy::Bool)),
57             ty::Char => Some(CastTy::Int(IntTy::Char)),
58             ty::Int(_) => Some(CastTy::Int(IntTy::I)),
59             ty::Infer(ty::InferTy::IntVar(_)) => Some(CastTy::Int(IntTy::I)),
60             ty::Infer(ty::InferTy::FloatVar(_)) => Some(CastTy::Float),
61             ty::Uint(u) => Some(CastTy::Int(IntTy::U(u))),
62             ty::Float(_) => Some(CastTy::Float),
63             ty::Adt(d,_) if d.is_enum() && d.is_payloadfree() =>
64                 Some(CastTy::Int(IntTy::CEnum)),
65             ty::RawPtr(mt) => Some(CastTy::Ptr(mt)),
66             ty::Ref(_, ty, mutbl) => Some(CastTy::RPtr(ty::TypeAndMut { ty, mutbl })),
67             ty::FnPtr(..) => Some(CastTy::FnPtr),
68             _ => None,
69         }
70     }
71 }