~starkingdoms/starkingdoms

ref: 0216bf5e52ce141f5a1f5eaaf3e699eb07fed0b1 starkingdoms/kabel/src/vm.rs -rw-r--r-- 13.5 KiB
0216bf5e — ghostly_zsh fix issue with not ppopping to clear stack with an expression statement 1 year, 4 months ago
                                                                                
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
use crate::{mismatched_types, runtime_error::KabelRuntimeError, vm_boolean_binary, wrong_type};

pub struct VM {
    ip: usize,
    pub chunk: Vec<u8>,
    pub stack: Vec<Value>,
    pub pool: Vec<Value>,
    pub lines: Vec<(usize, usize)>, // line #, repeats number of instructions
    text: Vec<String>
}

impl VM {
    pub fn new(bytecode: Vec<u8>, lines: Vec<(usize, usize)>, pool: Vec<Value>, text: String) -> Self {
        Self {
            ip: 0,
            chunk: bytecode,
            stack: Vec::new(),
            pool,
            lines,
            text: text.lines().map(|s| s.to_string()).collect(),
        }
    }
    pub fn run(&mut self, output: &mut String) -> Result<(), KabelRuntimeError> {
        use Value::*;
        while self.ip < self.chunk.len() {
            match self.read() {
                0x00 => { // CONSTANT
                    let byte = self.read() as usize;
                    self.stack.push(self.pool[byte].clone());
                }
                0x01 => { // ADD
                    match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                        (Num(v1), Num(v2)) => self.stack.push(Num(v1 + v2)),
                        (Str(v1), Str(v2)) => {
                            self.stack.push(Str(v1 + &v2));
                        },
                        (Bool(_v1), Bool(_v2)) => {
                            return Err(wrong_type!(self, "Cannot add booleans"))
                        }
                        (v1, v2) => {
                            return Err(mismatched_types!(self, "Mismatched types: {} and {}", v1.type_str(), v2.type_str()))
                        }
                    }
                }
                0x02 => { // SUB
                    match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                        (Num(v1), Num(v2)) => self.stack.push(Num(v1 - v2)),
                        (Str(_v1), Str(_v2)) => {
                            return Err(wrong_type!(self, "Cannot subtract strings"))
                        },
                        (Bool(_v1), Bool(_v2)) => {
                            return Err(wrong_type!(self, "Cannot subtract booleans"))
                        }
                        (v1, v2) => {
                            return Err(mismatched_types!(self, "Mismatched types: {} and {}", v1.type_str(), v2.type_str()))
                        }
                    }
                }
                0x03 => { // MUL
                    match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                        (Num(v1), Num(v2)) => self.stack.push(Num(v1 * v2)),
                        (Str(v1), Num(v2)) => {
                            if v2.fract() == 0.0 {
                                self.stack.push(Str(v1.repeat(v2 as usize)));
                            } else {
                                return Err(wrong_type!(self, "Number must be an integer"))
                            }
                        }
                        (Str(_v1), Str(_v2)) => {
                            return Err(wrong_type!(self, "Cannot multiply strings"))
                        },
                        (Bool(_v1), Bool(_v2)) => {
                            return Err(wrong_type!(self, "Cannot multiply booleans"))
                        }
                        (v1, v2) => {
                            return Err(mismatched_types!(self, "Mismatched types: {} and {}", v1.type_str(), v2.type_str()))
                        }
                    }
                }
                0x04 => { // DIV
                    match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                        (Num(v1), Num(v2)) => self.stack.push(Num(v1 / v2)),
                        (Str(_v1), Str(_v2)) => {
                            return Err(wrong_type!(self, "Cannot divide strings"))
                        },
                        (Bool(_v1), Bool(_v2)) => {
                            return Err(wrong_type!(self, "Cannot divide booleans"))
                        }
                        (v1, v2) => {
                            return Err(mismatched_types!(self, "Mismatched types: {} and {}", v1.type_str(), v2.type_str()))
                        }
                    }
                }
                0x05 => { // MOD
                    match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                        (Num(v1), Num(v2)) => self.stack.push(Num(v1 % v2)),
                        (Str(_v1), Str(_v2)) => {
                            return Err(wrong_type!(self, "Cannot perform modulus on strings"))
                        },
                        (Bool(_v1), Bool(_v2)) => {
                            return Err(wrong_type!(self, "Cannot perform modulus on booleans"))
                        }
                        (v1, v2) => {
                            return Err(mismatched_types!(self, "Mismatched types: {} and {}", v1.type_str(), v2.type_str()))
                        }
                    }
                }
                0x06 => { // BITAND
                    match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                        (Num(v1), Num(v2)) => {
                            if v1.fract() != 0.0 {
                                return Err(wrong_type!(self, "Cannot perform bitwise AND on {}", v1))
                            }
                            if v2.fract() != 0.0 {
                                return Err(wrong_type!(self, "Cannot perform bitwise AND on {}", v2))
                            }
                            self.stack.push(Num((v1 as u32 & v2 as u32) as f32))
                        }
                        (Str(_v1), Str(_v2)) => {
                            return Err(wrong_type!(self, "Cannot perform bitwise AND on strings"))
                        },
                        (Bool(_v1), Bool(_v2)) => {
                            return Err(wrong_type!(self, "Cannot perform bitwise AND on booleans"))
                        }
                        (v1, v2) => {
                            return Err(mismatched_types!(self, "Mismatched types: {} and {}", v1.type_str(), v2.type_str()))
                        }
                    }
                }
                0x07 => { // BITXOR
                    match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                        (Num(v1), Num(v2)) => {
                            if v1.fract() != 0.0 {
                                return Err(wrong_type!(self, "Cannot perform bitwise XOR on {}", v1))
                            }
                            if v2.fract() != 0.0 {
                                return Err(wrong_type!(self, "Cannot perform bitwise XOR on {}", v2))
                            }
                            self.stack.push(Num((v1 as u32 ^ v2 as u32) as f32))
                        }
                        (Str(_v1), Str(_v2)) => {
                            return Err(wrong_type!(self, "Cannot perform bitwise XOR on strings"))
                        },
                        (Bool(_v1), Bool(_v2)) => {
                            return Err(wrong_type!(self, "Cannot perform bitwise XOR on booleans"))
                        }
                        (v1, v2) => {
                            return Err(mismatched_types!(self, "Mismatched types: {} and {}", v1.type_str(), v2.type_str()))
                        }
                    }
                }
                0x08 => { // BITOR
                    match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                        (Num(v1), Num(v2)) => {
                            if v1.fract() != 0.0 {
                                return Err(wrong_type!(self, "Cannot perform bitwise OR on {}", v1))
                            }
                            if v2.fract() != 0.0 {
                                return Err(wrong_type!(self, "Cannot perform bitwise OR on {}", v2))
                            }
                            self.stack.push(Num((v1 as u32 | v2 as u32) as f32))
                        }
                        (Str(_v1), Str(_v2)) => {
                            return Err(wrong_type!(self, "Cannot perform bitwise OR on strings"))
                        },
                        (Bool(_v1), Bool(_v2)) => {
                            return Err(wrong_type!(self, "Cannot perform bitwise OR on booleans"))
                        }
                        (v1, v2) => {
                            return Err(mismatched_types!(self, "Mismatched types: {} and {}", v1.type_str(), v2.type_str()))
                        }
                    }
                }
                // EQ
                0x09 => vm_boolean_binary!(self, ==),
                // NE
                0x0A => vm_boolean_binary!(self, !=),
                // GR
                0x0B => vm_boolean_binary!(self, >),
                // GE
                0x0C => vm_boolean_binary!(self, >=),
                // LS
                0x0D => vm_boolean_binary!(self, <),
                // LE
                0x0E => vm_boolean_binary!(self, <=),
                // OR
                0x0F => match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                    (Num(_v1), Num(_v2)) => {
                        return Err(wrong_type!(self, "Cannot perform logical OR on numbers"))
                    }
                    (Str(_v1), Str(_v2)) => {
                        return Err(wrong_type!(self, "Cannot perform logical OR on strings"))
                    },
                    (Bool(v1), Bool(v2)) => self.stack.push(Bool(v1 || v2)),
                    (v1, v2) => {
                        return Err(mismatched_types!(self, "Mismatched types: {} and {}", v1.type_str(), v2.type_str()))
                    }
                }
                // AND
                0x10 => match (self.stack.pop().unwrap(), self.stack.pop().unwrap()) {
                    (Num(_v1), Num(_v2)) => {
                        return Err(wrong_type!(self, "Cannot perform logical AND on numbers"))
                    }
                    (Str(_v1), Str(_v2)) => {
                        return Err(wrong_type!(self, "Cannot perform logical AND on strings"))
                    },
                    (Bool(v1), Bool(v2)) => self.stack.push(Bool(v1 && v2)),
                    (v1, v2) => {
                        return Err(mismatched_types!(self, "Mismatched types: {} and {}", v1.type_str(), v2.type_str()))
                    }
                }
                // NOT
                0x11 => match self.stack.pop().unwrap() {
                    Num(_v1) => {
                        return Err(wrong_type!(self, "Cannot perform logical NOT on numbers"))
                    }
                    Str(_v1) => {
                        return Err(wrong_type!(self, "Cannot perform logical NOT on strings"))
                    }
                    Bool(v1) => self.stack.push(Bool(!v1)),
                }
                // NEG
                0x12 => match self.stack.pop().unwrap() {
                    Num(v1) => self.stack.push(Num(-v1)),
                    Str(_v1) => {
                        return Err(wrong_type!(self, "Cannot negate strings"))
                    }
                    Bool(_v1) => {
                        return Err(wrong_type!(self, "Cannot negate bools"))
                    }
                }
                // JMP
                0x13 => {
                    let loc = self.read_u16();
                    self.ip += loc as usize;
                }
                // IF_NE
                0x14 => {
                    let condition = self.stack.pop().unwrap();
                    if let Value::Bool(condition) = condition {
                        if !condition {
                            let loc = self.read_u16();
                            self.ip += loc as usize;
                        } else {
                            self.read_u16();
                        }
                    } else {
                        return Err(wrong_type!(self, "if must have condition of type boolean"))
                    }
                }

                0xFD => { // POP
                    self.stack.pop().unwrap();
                }
                0xFE => { // PRINT
                    let value = self.stack.pop().unwrap();
                    match value {
                        Num(v) => *output += &v.to_string(),
                        Str(v) => *output += &v,
                        Bool(v) => *output += &v.to_string(),
                    }
                    *output += "\n";
                }
                _ => {}
            }
        }
        Ok(())
    }
    pub fn read(&mut self) -> u8 {
        let byte = self.chunk[self.ip];
        self.ip += 1;
        byte
    }
    pub fn read_u16(&mut self) -> u16 {
        let byte_one = (self.chunk[self.ip] as u16) << 0x08;
        self.ip += 1;
        let byte_two = self.chunk[self.ip] as u16;
        self.ip += 1;
        byte_one | byte_two
    }
    pub fn find_line(&mut self) -> usize { // returns line # at ip
        let mut line_ip = 0;
        for (line, rep) in self.lines.clone() {
            if line_ip + rep > self.ip {
                return line;
            }
            line_ip += rep;
        }
        panic!("Something went wrong in finding line for error")
    }
}

#[derive(Debug, Clone)]
pub enum Value {
    Num(f32), Str(String), Bool(bool),
}

impl Value {
    pub fn type_str(&self) -> String {
        match self {
            Value::Num(_) => "number".to_string(),
            Value::Str(_) => "string".to_string(),
            Value::Bool(_) => "bool".to_string(),
        }
    }
}