aboutsummaryrefslogtreecommitdiff
path: root/crates/sloth_vm/src/vm.rs
blob: ded7aa6c2ad24aa74c353c795a66eb912562e5da (plain)
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
use std::mem::MaybeUninit;

use sloth_bytecode::Opcode;

use crate::value::{Function, Object, ObjectType, Primitive};
use crate::{ObjectMap, Stack};

#[derive(Clone, Copy)]
pub struct CallFrame {
    pointer: usize,
    stack_offset: usize,
    function: *const Function, // TODO: Safety
}

impl CallFrame {
    #[inline]
    fn function(&self) -> &Function {
        unsafe { &*self.function }
    }
}

impl From<&Function> for CallFrame {
    fn from(value: &Function) -> Self {
        Self {
            pointer: 0,
            stack_offset: 0,
            function: value as *const _,
        }
    }
}

const CALL_STACK_SIZE: usize = 1024;

pub struct CallStack {
    top: usize,
    frames: [MaybeUninit<CallFrame>; CALL_STACK_SIZE],
}

impl Default for CallStack {
    fn default() -> Self {
        Self {
            top: 0,
            frames: [MaybeUninit::uninit(); CALL_STACK_SIZE],
        }
    }
}

impl CallStack {
    fn push(&mut self, frame: CallFrame) {
        self.frames[self.top].write(frame);
        self.top += 1;
    }

    fn pop(&mut self) {
        self.top -= 1;
    }

    fn peek(&self) -> &CallFrame {
        unsafe { self.frames[self.top - 1].assume_init_ref() }
    }

    fn peek_mut(&mut self) -> &mut CallFrame {
        unsafe { self.frames[self.top - 1].assume_init_mut() }
    }
}

pub struct VM {
    stack: Stack,
    call_stack: CallStack,
    objects: ObjectMap,
}

impl Default for VM {
    fn default() -> Self {
        Self::init(ObjectMap::default())
    }
}

impl VM {
    pub fn init(objects: ObjectMap) -> Self {
        Self {
            stack: Stack::default(),
            call_stack: CallStack::default(),
            objects,
        }
    }

    pub fn new(objects: ObjectMap, mut root: Function) -> Self {
        let mut this = Self::init(objects);

        // Allocating the root function
        root.chunk.code.push(Opcode::Hlt as u8);
        this.call_stack.push(CallFrame::from(&root));
        this.objects
            .allocate(Object::new(ObjectType::Function(root)));

        this
    }

    pub fn step(&mut self) -> bool {
        use Primitive::*;

        let opcode = self.read_u8();

        match Opcode::from_u8(opcode) {
            Opcode::Constant => {
                let idx = self.read_u16();
                let value = self.call_stack.peek().function().chunk.constants[idx as usize];

                self.stack.push(value);
            }
            Opcode::Dup => {
                let value = self.stack.pop();
                self.stack.push(value);
                self.stack.push(value);
            }
            Opcode::Del => {
                self.stack.pop();
            }

            Opcode::Add => {
                let value = match self.stack.pop2() {
                    (Integer(lhs), Integer(rhs)) => Integer(lhs + rhs),
                    (Float(lhs), Float(rhs)) => Float(lhs + rhs),
                    _ => panic!(),
                };

                self.stack.push(value);
            }
            Opcode::Sub => {
                let value = match self.stack.pop2() {
                    (Integer(lhs), Integer(rhs)) => Integer(lhs - rhs),
                    (Float(lhs), Float(rhs)) => Float(lhs - rhs),
                    _ => panic!(),
                };

                self.stack.push(value);
            }
            Opcode::Mul => {
                let value = match self.stack.pop2() {
                    (Integer(lhs), Integer(rhs)) => Integer(lhs * rhs),
                    (Float(lhs), Float(rhs)) => Float(lhs * rhs),
                    _ => panic!(),
                };

                self.stack.push(value);
            }
            Opcode::Div => {
                let value = match self.stack.pop2() {
                    (Integer(_), Integer(0)) => panic!("Divide by 0"),
                    (Integer(lhs), Integer(rhs)) => Integer(lhs / rhs),
                    (Float(lhs), Float(rhs)) => Float(lhs / rhs),
                    _ => panic!(),
                };

                self.stack.push(value);
            }
            Opcode::Mod => {
                let value = match self.stack.pop2() {
                    (Integer(lhs), Integer(rhs)) => Integer(lhs % rhs),
                    (Float(lhs), Float(rhs)) => Float(lhs % rhs),
                    _ => panic!(),
                };

                self.stack.push(value);
            }

            Opcode::Call => {
                let Primitive::Object(ptr) = self.stack.pop() else {
                    panic!("Last element on stack was not an object");
                };

                let Some(obj) = self.objects.get(ptr as usize) else {
                    panic!("Pointer referenced nothing");
                };

                let ObjectType::Function(function) = &obj.typ else {
                    panic!("Object was not a function");
                };

                // Push the function onto the call stack
                self.call_stack.push(CallFrame::from(function));
            }

            Opcode::Return => {
                // TODO: Return values

                self.call_stack.pop();
            }

            Opcode::Hlt => return false,
            Opcode::Exit => return false,

            _ => unimplemented!(),
        }

        true
    }

    pub fn run(&mut self) {
        while self.step() {}
    }

    #[inline(always)]
    fn read_u8(&mut self) -> u8 {
        let frame = self.call_stack.peek_mut();
        let function = frame.function();
        let byte = function.chunk.code[frame.pointer];
        frame.pointer += 1;
        byte
    }

    #[inline(always)]
    fn read_u16(&mut self) -> u16 {
        let frame = self.call_stack.peek_mut();
        let chunk = &frame.function().chunk;

        let bytes = (chunk.code[frame.pointer], chunk.code[frame.pointer + 1]);

        frame.pointer += 2;

        ((bytes.0 as u16) << 8) + (bytes.1 as u16)
    }
}

#[cfg(test)]
mod tests {
    use crate::value::{Function, Object, ObjectType, Primitive};
    use crate::{Chunk, ObjectMap, VM};

    #[test]
    fn arithmetic_ops() {
        // Addition
        let mut vm = VM::new(
            ObjectMap::default(),
            Function::root(Chunk {
                constants: vec![Primitive::Integer(7)],
                code: vec![
                    0x00, 0, 0,    // Load constant from 0
                    0x10, // Duplicate
                    0x20, // Add
                    0xE0,
                ],
            }),
        );

        vm.run();
        assert_eq!(vm.stack.peek(), Primitive::Integer(14));

        let mut vm = VM::new(
            ObjectMap::default(),
            Function::root(Chunk {
                constants: vec![Primitive::Integer(2), Primitive::Integer(11)],
                code: vec![
                    0x00, 0, 0, // Load constant from 0
                    0x00, 0, 1,    // Load constant from 1
                    0x20, // Add
                    0xE0,
                ],
            }),
        );

        vm.run();
        assert_eq!(vm.stack.peek(), Primitive::Integer(13));
    }

    #[test]
    fn allocation() {
        let mut vm = VM::new(
            ObjectMap::from(vec![
                Object::new(ObjectType::String("Hello World!".to_owned())),
                Object::new(ObjectType::String("Hello Slothlang!".to_owned())),
                Object::new(ObjectType::Function(Function {
                    name: Some("foo".to_string()),
                    chunk: Chunk {
                        constants: vec![Primitive::Integer(7)],
                        code: vec![0x00, 0, 0, 0x10, 0x20, 0x51],
                    },
                    arity: 0,
                })),
            ]),
            Function::root(Chunk {
                constants: vec![
                    Primitive::Object(0),
                    Primitive::Object(1),
                    Primitive::Object(2),
                ],
                code: vec![
                    0x00, 0, 0, // Load constant from 0
                    0x00, 0, 1, // Load constant from 1
                    0x00, 0, 2, // Load constant from 2
                    0x50, 0xE0,
                ],
            }),
        );

        vm.run();

        assert_eq!(vm.stack.peek(), Primitive::Integer(14));
    }
}