]> git.proxmox.com Git - rustc.git/blob - src/librustc/middle/cast.rs
34088d5f13ee705c0e02dc94db9772f89b4dc15b
[rustc.git] / src / librustc / middle / 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 trans.
13
14 use middle::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(&'tcx ty::mt<'tcx>),
40 /// References
41 RPtr(&'tcx ty::mt<'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(tcx: &ty::ctxt<'tcx>, t: Ty<'tcx>)
62 -> Option<CastTy<'tcx>> {
63 match t.sty {
64 ty::TyBool => Some(CastTy::Int(IntTy::Bool)),
65 ty::TyChar => Some(CastTy::Int(IntTy::Char)),
66 ty::TyInt(_) => Some(CastTy::Int(IntTy::I)),
67 ty::TyUint(u) => Some(CastTy::Int(IntTy::U(u))),
68 ty::TyFloat(_) => Some(CastTy::Float),
69 ty::TyEnum(..) if ty::type_is_c_like_enum(
70 tcx, t) => Some(CastTy::Int(IntTy::CEnum)),
71 ty::TyRawPtr(ref mt) => Some(CastTy::Ptr(mt)),
72 ty::TyRef(_, ref mt) => Some(CastTy::RPtr(mt)),
73 ty::TyBareFn(..) => Some(CastTy::FnPtr),
74 _ => None,
75 }
76 }
77 }