mylang_vm/
entity.rs

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//! 仮想マシンで扱う「実体」の定義

use std::fmt::{Debug, Display, Formatter, Result as FmtResult};

/// 符号付き32ビット整数値
pub struct I32Entity(i32);

impl I32Entity {
    pub fn new(value: i32) -> Self {
        Self(value)
    }

    pub fn add(&self, rhs: &Self) -> Self {
        Self(self.0 + rhs.0)
    }
}

impl Debug for I32Entity {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(f, "{}", self.0)
    }
}

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

/// 文字列データ
pub struct StrEntity(String);

impl StrEntity {
    pub fn new(value: String) -> Self {
        Self(value)
    }
}

impl Debug for StrEntity {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(f, "{}", self.0)
    }
}

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

/// 実行時型情報
#[derive(Debug)]
pub enum RuntimeTypeInfo {
    Addr,
    I32,
    Str,
}

impl Display for RuntimeTypeInfo {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(
            f,
            "{}",
            match self {
                RuntimeTypeInfo::Addr => "addr",
                RuntimeTypeInfo::I32 => "i32",
                RuntimeTypeInfo::Str => "str",
            }
        )
    }
}

/// バイトコード実行時に扱う値
#[derive(Debug)]
pub enum Entity {
    Addr(usize),
    I32(I32Entity),
    Str(StrEntity),
}

impl Entity {
    pub fn get_type(&self) -> RuntimeTypeInfo {
        match self {
            Entity::Addr(_) => RuntimeTypeInfo::Addr,
            Entity::I32(_) => RuntimeTypeInfo::I32,
            Entity::Str(_) => RuntimeTypeInfo::Str,
        }
    }
}