]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/cast.rs
introduce Guard enum
[rust.git] / src / librustc / ty / cast.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Helpers for handling cast expressions, used in both
12 // typeck and codegen.
13
14 use ty::{self, Ty};
15
16 use syntax::ast;
17
18 /// Types that are represented as ints.
19 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
20 pub enum IntTy {
21     U(ast::UintTy),
22     I,
23     CEnum,
24     Bool,
25     Char
26 }
27
28 // Valid types for the result of a non-coercion cast
29 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
30 pub enum CastTy<'tcx> {
31     /// Various types that are represented as ints and handled mostly
32     /// in the same way, merged for easier matching.
33     Int(IntTy),
34     /// Floating-Point types
35     Float,
36     /// Function Pointers
37     FnPtr,
38     /// Raw pointers
39     Ptr(ty::TypeAndMut<'tcx>),
40     /// References
41     RPtr(ty::TypeAndMut<'tcx>),
42 }
43
44 /// Cast Kind. See RFC 401 (or librustc_typeck/check/cast.rs)
45 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
46 pub enum CastKind {
47     CoercionCast,
48     PtrPtrCast,
49     PtrAddrCast,
50     AddrPtrCast,
51     NumericCast,
52     EnumCast,
53     PrimIntCast,
54     U8CharCast,
55     ArrayPtrCast,
56     FnPtrPtrCast,
57     FnPtrAddrCast
58 }
59
60 impl<'tcx> CastTy<'tcx> {
61     pub fn from_ty(t: Ty<'tcx>) -> Option<CastTy<'tcx>> {
62         match t.sty {
63             ty::TyBool => Some(CastTy::Int(IntTy::Bool)),
64             ty::TyChar => Some(CastTy::Int(IntTy::Char)),
65             ty::TyInt(_) => Some(CastTy::Int(IntTy::I)),
66             ty::TyInfer(ty::InferTy::IntVar(_)) => Some(CastTy::Int(IntTy::I)),
67             ty::TyInfer(ty::InferTy::FloatVar(_)) => Some(CastTy::Float),
68             ty::TyUint(u) => Some(CastTy::Int(IntTy::U(u))),
69             ty::TyFloat(_) => Some(CastTy::Float),
70             ty::TyAdt(d,_) if d.is_enum() && d.is_payloadfree() =>
71                 Some(CastTy::Int(IntTy::CEnum)),
72             ty::TyRawPtr(mt) => Some(CastTy::Ptr(mt)),
73             ty::TyRef(_, ty, mutbl) => Some(CastTy::RPtr(ty::TypeAndMut { ty, mutbl })),
74             ty::TyFnPtr(..) => Some(CastTy::FnPtr),
75             _ => None,
76         }
77     }
78 }