1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use std::fmt;
use std::fmt::Formatter;

#[derive(Eq, PartialEq, PartialOrd, Ord, Hash, Clone)]
pub struct LLVMType {
    /// integer, void, aggrigate and etc.
    pub kind: LLVMTypeKind,
}

#[allow(dead_code)]
impl LLVMType {
    fn new(k: LLVMTypeKind) -> Self {
        Self { kind: k }
    }

    pub fn new_int(bit_width: u32) -> Self {
        Self::new(LLVMTypeKind::INTEGER { bit_width })
    }
    pub fn new_uint(bit_width: u32) -> Self {
        Self::new(LLVMTypeKind::UNSIGNEDINTEGER { bit_width })
    }
    pub fn new_void() -> Self {
        Self::new(LLVMTypeKind::VOID)
    }
    pub fn new_pointer(inner: LLVMType) -> Self {
        Self::new(LLVMTypeKind::POINTER {
            inner: Box::new(inner),
        })
    }
    pub fn new_array(elem: LLVMType, len: usize) -> Self {
        Self::new(LLVMTypeKind::ARRAY {
            element_type: Box::new(elem),
            length: len,
        })
    }

    pub fn is_aggrigate(&self) -> bool {
        match &self.kind {
            LLVMTypeKind::ARRAY { element_type: _ty, length: _len } => true,
            _ => false,
        }
    }
}

impl fmt::Display for LLVMType {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.kind)
    }
}

#[derive(Eq, PartialEq, PartialOrd, Ord, Hash, Clone)]
pub enum LLVMTypeKind {
    VOID,
    INTEGER { bit_width: u32 },
    UNSIGNEDINTEGER { bit_width: u32 },
    POINTER { inner: Box<LLVMType> },
    ARRAY { element_type: Box<LLVMType>, length: usize },
}

impl fmt::Display for LLVMTypeKind {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::VOID => write!(f, "void"),
            Self::INTEGER { bit_width: bits } => write!(f, "i{}", bits),
            Self::UNSIGNEDINTEGER { bit_width: bits } => write!(f, "u{}", bits),
            Self::POINTER { inner: inner_ty } => write!(f, "{}*", inner_ty),
            Self::ARRAY { element_type: ty, length: len } => write!(f, "[{} x {}]", ty, len),
        }
    }
}