mylang_vm/
lib.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
//! バイトコードインタプリタ

mod entity;

use mylang_bytecode::Inst;
use thiserror::Error;

use entity::{Entity, I32Entity, RuntimeTypeInfo, StrEntity};

/// バイトコードインタプリタで発生するエラー
#[derive(Debug, Error)]
pub enum VMError {
    /// スタックが空であり、値をスタックから取り出せなかった
    #[error("Stack underflow ({0})")]
    StackUnderflow(String),

    /// 取り出した値が、期待した型の値ではなかった
    #[error("Type mismatch (expected: {expected}, actual: {actual})")]
    TypeMismatch {
        expected: RuntimeTypeInfo,
        actual: RuntimeTypeInfo,
    },
}

/// バイトコードの実行結果
type VMResult<T> = Result<T, VMError>;

/// I32Const 命令を実行する
fn i32_const(stack: &mut Vec<Entity>, immediate: i32) {
    stack.push(Entity::I32(I32Entity::new(immediate)));
}

/// I32Add 命令を実行する
fn i32_add(stack: &mut Vec<Entity>) -> VMResult<()> {
    let lhs = stack.pop().ok_or_else(|| {
        VMError::StackUnderflow("Failed to get left-hand side of the addition".to_owned())
    })?;
    let rhs = stack.pop().ok_or_else(|| {
        VMError::StackUnderflow("Failed to get right-hand side of the addition".to_owned())
    })?;

    let lhs = match lhs {
        Entity::I32(i32_entity) => i32_entity,
        _ => {
            return Err(VMError::TypeMismatch {
                expected: RuntimeTypeInfo::I32,
                actual: lhs.get_type(),
            })
        }
    };

    let rhs = match rhs {
        Entity::I32(i32_entity) => i32_entity,
        _ => {
            return Err(VMError::TypeMismatch {
                expected: RuntimeTypeInfo::I32,
                actual: rhs.get_type(),
            })
        }
    };

    stack.push(Entity::I32(lhs.add(&rhs)));
    Ok(())
}

/// StrConst 命令を実行する
fn str_const(stack: &mut Vec<Entity>, immediate: &str) {
    stack.push(Entity::Str(StrEntity::new(immediate.to_owned())));
}

/// PrintI32 命令を実行する
fn print_i32(stack: &mut Vec<Entity>) -> VMResult<()> {
    let ent = stack
        .pop()
        .ok_or_else(|| VMError::StackUnderflow("Failed to get the entity to output".to_owned()))?;

    let ent = match ent {
        Entity::I32(i32_entity) => i32_entity,
        _ => {
            return Err(VMError::TypeMismatch {
                expected: RuntimeTypeInfo::I32,
                actual: ent.get_type(),
            })
        }
    };

    println!("{}", ent);
    Ok(())
}

/// PrintStr 命令を実行する
fn print_str(stack: &mut Vec<Entity>) -> VMResult<()> {
    let ent = stack
        .pop()
        .ok_or_else(|| VMError::StackUnderflow("Failed to get entity".to_owned()))?;

    let ent = match ent {
        Entity::Str(str_entity) => str_entity,
        _ => {
            return Err(VMError::TypeMismatch {
                expected: RuntimeTypeInfo::Str,
                actual: ent.get_type(),
            })
        }
    };

    println!("{}", ent);
    Ok(())
}

fn call(stack: &mut Vec<Entity>, pc: &mut usize, addr: usize) -> VMResult<()> {
    stack.push(Entity::Addr(*pc + 1));
    *pc = addr;
    Ok(())
}

fn ret(stack: &mut Vec<Entity>, pc: &mut usize) -> VMResult<()> {
    let addr = stack
        .pop()
        .ok_or_else(|| VMError::StackUnderflow("Failed to get return address".to_owned()))?;
    let addr = match addr {
        Entity::Addr(addr) => addr,
        _ => {
            return Err(VMError::TypeMismatch {
                expected: RuntimeTypeInfo::Addr,
                actual: addr.get_type(),
            })
        }
    };

    *pc = addr;
    Ok(())
}

/// バイトコードを解釈実行する
pub fn execute(insts: &[Inst]) -> VMResult<()> {
    let mut stack = Vec::<Entity>::new();
    let mut pc = 0;
    let len = insts.len();

    while pc < len {
        match &insts[pc] {
            Inst::I32Const(i) => i32_const(&mut stack, *i),

            Inst::I32Add => i32_add(&mut stack)?,

            Inst::StrConst(s) => str_const(&mut stack, s),

            Inst::PrintI32 => print_i32(&mut stack)?,

            Inst::PrintStr => print_str(&mut stack)?,

            Inst::Call(addr) => call(&mut stack, &mut pc, *addr)?,

            Inst::Return => ret(&mut stack, &mut pc)?,
        }

        pc += 1;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use crate::{
        entity::{Entity, I32Entity, StrEntity},
        i32_add,
    };

    #[test]
    fn test_i32_add() {
        let mut stack = vec![
            Entity::I32(I32Entity::new(3)),
            Entity::I32(I32Entity::new(4)),
        ];
        insta::assert_debug_snapshot!((i32_add(&mut stack), stack));
    }

    #[test]
    fn test_i32_add_underflow() {
        let mut stack = vec![Entity::I32(I32Entity::new(3))];
        insta::assert_debug_snapshot!((i32_add(&mut stack), stack));
    }

    #[test]
    fn test_i32_add_type_mismatch() {
        let mut stack = vec![
            Entity::Str(StrEntity::new("foo".to_owned())),
            Entity::I32(I32Entity::new(4)),
        ];
        insta::assert_debug_snapshot!((i32_add(&mut stack), stack));
    }
}