llvm_scratch/core/llvm_type/
llvm_type.rs

1use std::fmt;
2use std::fmt::Formatter;
3
4#[derive(Eq, PartialEq, PartialOrd, Ord, Hash, Clone)]
5pub struct LLVMType {
6    /// integer, void, aggrigate and etc.
7    pub kind: LLVMTypeKind,
8}
9
10#[allow(dead_code)]
11impl LLVMType {
12    fn new(k: LLVMTypeKind) -> Self {
13        Self { kind: k }
14    }
15
16    pub fn new_int(bit_width: u32) -> Self {
17        Self::new(LLVMTypeKind::INTEGER { bit_width })
18    }
19    pub fn new_uint(bit_width: u32) -> Self {
20        Self::new(LLVMTypeKind::UNSIGNEDINTEGER { bit_width })
21    }
22    pub fn new_void() -> Self {
23        Self::new(LLVMTypeKind::VOID)
24    }
25    pub fn new_pointer(inner: LLVMType) -> Self {
26        Self::new(LLVMTypeKind::POINTER {
27            inner: Box::new(inner),
28        })
29    }
30    pub fn new_array(elem: LLVMType, len: usize) -> Self {
31        Self::new(LLVMTypeKind::ARRAY {
32            element_type: Box::new(elem),
33            length: len,
34        })
35    }
36
37    pub fn is_aggrigate(&self) -> bool {
38        match &self.kind {
39            LLVMTypeKind::ARRAY { element_type: _ty, length: _len } => true,
40            _ => false,
41        }
42    }
43}
44
45impl fmt::Display for LLVMType {
46    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
47        write!(f, "{}", self.kind)
48    }
49}
50
51#[derive(Eq, PartialEq, PartialOrd, Ord, Hash, Clone)]
52pub enum LLVMTypeKind {
53    VOID,
54    INTEGER { bit_width: u32 },
55    UNSIGNEDINTEGER { bit_width: u32 },
56    POINTER { inner: Box<LLVMType> },
57    ARRAY { element_type: Box<LLVMType>, length: usize },
58}
59
60impl fmt::Display for LLVMTypeKind {
61    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
62        match self {
63            Self::VOID => write!(f, "void"),
64            Self::INTEGER { bit_width: bits } => write!(f, "i{}", bits),
65            Self::UNSIGNEDINTEGER { bit_width: bits } => write!(f, "u{}", bits),
66            Self::POINTER { inner: inner_ty } => write!(f, "{}*", inner_ty),
67            Self::ARRAY { element_type: ty, length: len } => write!(f, "[{} x {}]", ty, len),
68        }
69    }
70}