monkey-gc 0.15.0

QuickJS-style GC runtime for Monkey (bytecode VM with cycle collector)
Documentation
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
use std::collections::HashMap;

use byteorder::{BigEndian, ByteOrder};
use compiler::compiler::Bytecode;
use compiler::op_code::{cast_u8_to_opcode, Opcode};
use object::builtins::BuiltIns;
use object::Object;

use crate::frame::Frame;
use crate::value::{
    alloc_value, call_builtin, export_object, get_value, import_object, GcClosure, HashKey, Value,
};
use crate::{GcHeap, GcRef};

const STACK_SIZE: usize = 2048;
pub const GLOBAL_SIZE: usize = 65536;
const MAX_FRAMES: usize = 1024;

enum CalleeKind {
    Closure(GcClosure),
    Builtin(object::BuiltinFunc),
}

pub struct GcVM {
    heap: GcHeap,
    constants: Vec<GcRef>,
    stack: Vec<GcRef>,
    sp: usize,
    globals: Vec<GcRef>,
    frames: Vec<Frame>,
    frame_index: usize,
    null: GcRef,
    last_popped: GcRef,
}

impl GcVM {
    pub fn new(bytecode: Bytecode) -> Self {
        let mut heap = GcHeap::new();
        let null = alloc_value(&mut heap, Value::Null);
        let constants = bytecode
            .constants
            .iter()
            .map(|constant| import_object(&mut heap, constant))
            .collect();

        let main_fn = alloc_value(
            &mut heap,
            Value::CompiledFunction(object::CompiledFunction {
                instructions: bytecode.instructions.data,
                num_locals: 0,
                num_parameters: 0,
            }),
        );
        let main_instructions = compiled_instructions(&heap, main_fn);
        // Frames keep borrowed GcRefs. The initial main_fn allocation is the VM
        // root for these handles; placeholder frames do not take extra refs.
        let main_frame = Frame::new(
            GcClosure {
                func: main_fn,
                free: vec![],
            },
            main_instructions,
            0,
        );

        let empty_frame = Frame::new(
            GcClosure {
                func: main_fn,
                free: vec![],
            },
            vec![],
            0,
        );

        let mut frames = vec![empty_frame; MAX_FRAMES];
        frames[0] = main_frame;

        let stack = (0..STACK_SIZE).map(|_| heap.dup(null)).collect();
        let globals = (0..GLOBAL_SIZE).map(|_| heap.dup(null)).collect();
        let last_popped = heap.dup(null);

        GcVM {
            heap,
            constants,
            stack,
            sp: 0,
            globals,
            frames,
            frame_index: 1,
            null,
            last_popped,
        }
    }

    pub fn heap(&self) -> &GcHeap {
        &self.heap
    }

    pub fn heap_mut(&mut self) -> &mut GcHeap {
        &mut self.heap
    }

    pub fn run(&mut self) {
        while self.current_frame().ip < self.current_frame().instructions.len() as i32 - 1 {
            self.current_frame().ip += 1;
            let ip = self.current_frame().ip as usize;
            let ins = self.current_frame().instructions.clone();
            let op = *ins.get(ip).unwrap();
            let opcode = cast_u8_to_opcode(op);

            match opcode {
                Opcode::OpConst => {
                    let const_index = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
                    self.current_frame().ip += 2;
                    self.dup_and_push(self.constants[const_index]);
                }
                Opcode::OpAdd | Opcode::OpSub | Opcode::OpMul | Opcode::OpDiv => {
                    self.execute_binary_operation(opcode);
                }
                Opcode::OpPop => {
                    self.pop_discard();
                }
                Opcode::OpTrue => {
                    self.alloc_and_push(Value::Boolean(true));
                }
                Opcode::OpFalse => {
                    self.alloc_and_push(Value::Boolean(false));
                }
                Opcode::OpEqual | Opcode::OpNotEqual | Opcode::OpGreaterThan => {
                    self.execute_comparison(opcode);
                }
                Opcode::OpMinus => {
                    self.execute_minus_operation();
                }
                Opcode::OpBang => {
                    self.execute_bang_operation();
                }
                Opcode::OpJump => {
                    let pos = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
                    self.current_frame().ip = pos as i32 - 1;
                }
                Opcode::OpJumpNotTruthy => {
                    let pos = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
                    self.current_frame().ip += 2;
                    let condition = self.pop_owned();
                    if !is_truthy(&self.heap, condition) {
                        self.current_frame().ip = pos as i32 - 1;
                    }
                    self.heap.free(condition);
                }
                Opcode::OpNull => {
                    self.dup_and_push(self.null);
                }
                Opcode::OpGetGlobal => {
                    let global_index = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
                    self.current_frame().ip += 2;
                    self.dup_and_push(self.globals[global_index]);
                }
                Opcode::OpSetGlobal => {
                    let global_index = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
                    self.current_frame().ip += 2;
                    let value = self.pop_owned();
                    self.heap.free(self.globals[global_index]);
                    self.globals[global_index] = value;
                }
                Opcode::OpArray => {
                    let count = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
                    self.current_frame().ip += 2;
                    let start = self.sp - count;
                    let elements = self.build_array(start, self.sp);
                    let array = alloc_value(&mut self.heap, Value::Array(elements));
                    self.clear_stack_range(start, self.sp);
                    self.sp = start;
                    self.push_raw(array);
                }
                Opcode::OpHash => {
                    let count = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
                    self.current_frame().ip += 2;
                    let start = self.sp - count;
                    let elements = self.build_hash(start, self.sp);
                    let hash = alloc_value(&mut self.heap, Value::Hash(elements));
                    self.clear_stack_range(start, self.sp);
                    self.sp = start;
                    self.push_raw(hash);
                }
                Opcode::OpIndex => {
                    let index = self.pop_owned();
                    let left = self.pop_owned();
                    self.execute_index_operation(left, index);
                    self.heap.free(index);
                    self.heap.free(left);
                }
                Opcode::OpReturnValue => {
                    let return_value = self.pop_owned();
                    let frame = self.pop_frame();
                    let new_sp = frame.base_pointer - 1;
                    self.clear_stack_range(new_sp, self.sp);
                    self.sp = new_sp;
                    self.push_raw(return_value);
                }
                Opcode::OpReturn => {
                    let frame = self.pop_frame();
                    let new_sp = frame.base_pointer - 1;
                    self.clear_stack_range(new_sp, self.sp);
                    self.sp = new_sp;
                    self.dup_and_push(self.null);
                }
                Opcode::OpCall => {
                    let num_args = ins[ip + 1] as usize;
                    self.current_frame().ip += 1;
                    self.execute_call(num_args);
                }
                Opcode::OpSetLocal => {
                    let local_index = ins[ip + 1] as usize;
                    self.current_frame().ip += 1;
                    let base = self.current_frame().base_pointer;
                    let value = self.pop_owned();
                    self.heap.free(self.stack[base + local_index]);
                    self.stack[base + local_index] = value;
                }
                Opcode::OpGetLocal => {
                    let local_index = ins[ip + 1] as usize;
                    self.current_frame().ip += 1;
                    let base = self.current_frame().base_pointer;
                    self.dup_and_push(self.stack[base + local_index]);
                }
                Opcode::OpGetBuiltin => {
                    let built_index = ins[ip + 1] as usize;
                    self.current_frame().ip += 1;
                    let definition = BuiltIns.get(built_index).unwrap().1;
                    self.alloc_and_push(Value::Builtin(definition));
                }
                Opcode::OpClosure => {
                    let const_index = BigEndian::read_u16(&ins[ip + 1..ip + 3]) as usize;
                    let num_free = ins[ip + 3] as usize;
                    self.current_frame().ip += 3;
                    self.push_closure(const_index, num_free);
                }
                Opcode::OpGetFree => {
                    let free_index = ins[ip + 1] as usize;
                    self.current_frame().ip += 1;
                    let free_var = self.current_frame().cl.free[free_index];
                    self.dup_and_push(free_var);
                }
                Opcode::OpCurrentClosure => {
                    let current = self.current_frame().cl.clone();
                    self.alloc_and_push(Value::Closure(current));
                }
            }
        }
    }

    pub fn last_popped_stack_elm(&self) -> Option<GcRef> {
        Some(self.last_popped)
    }

    pub fn export_last_result(&self) -> Option<Object> {
        self.last_popped_stack_elm()
            .map(|reference| export_object(&self.heap, reference))
    }

    fn alloc_and_push(&mut self, value: Value) {
        let reference = alloc_value(&mut self.heap, value);
        self.push_raw(reference);
    }

    fn dup_and_push(&mut self, reference: GcRef) {
        let duplicated = self.heap.dup(reference);
        self.push_raw(duplicated);
    }

    fn push_raw(&mut self, value: GcRef) {
        if self.sp >= STACK_SIZE {
            panic!("Stack overflow");
        }
        let old = self.stack[self.sp];
        self.stack[self.sp] = value;
        self.heap.free(old);
        self.sp += 1;
    }

    /// Move the top stack slot's owned reference to the caller.
    ///
    /// The caller must either free the returned ref or store it in another
    /// owning location. The vacated stack slot is reset to a null ref.
    fn pop_owned(&mut self) -> GcRef {
        self.sp -= 1;
        let value = self.stack[self.sp];
        self.stack[self.sp] = self.heap.dup(self.null);
        value
    }

    fn pop_discard(&mut self) {
        let value = self.pop_owned();
        self.heap.free(self.last_popped);
        self.last_popped = value;
    }

    fn clear_stack_range(&mut self, start: usize, end: usize) {
        for index in start..end {
            let old = self.stack[index];
            self.stack[index] = self.heap.dup(self.null);
            self.heap.free(old);
        }
    }

    fn execute_binary_operation(&mut self, opcode: Opcode) {
        let right = self.pop_owned();
        let left = self.pop_owned();
        match (get_value(&self.heap, left), get_value(&self.heap, right)) {
            (Value::Integer(l), Value::Integer(r)) => {
                let result = match opcode {
                    Opcode::OpAdd => l + r,
                    Opcode::OpSub => l - r,
                    Opcode::OpMul => l * r,
                    Opcode::OpDiv => l / r,
                    _ => panic!("Unknown opcode for int"),
                };
                self.alloc_and_push(Value::Integer(result));
            }
            (Value::String(l), Value::String(r)) => {
                let result = match opcode {
                    Opcode::OpAdd => l.to_string() + r,
                    _ => panic!("Unknown opcode for string"),
                };
                self.alloc_and_push(Value::String(result));
            }
            _ => panic!("unsupported binary operation for those types"),
        }
        self.heap.free(left);
        self.heap.free(right);
    }

    fn execute_comparison(&mut self, opcode: Opcode) {
        let right = self.pop_owned();
        let left = self.pop_owned();
        let result = match (get_value(&self.heap, left), get_value(&self.heap, right)) {
            (Value::Integer(l), Value::Integer(r)) => match opcode {
                Opcode::OpEqual => l == r,
                Opcode::OpNotEqual => l != r,
                Opcode::OpGreaterThan => l > r,
                _ => panic!("Unknown opcode for comparing int"),
            },
            (Value::Boolean(l), Value::Boolean(r)) => match opcode {
                Opcode::OpEqual => l == r,
                Opcode::OpNotEqual => l != r,
                _ => panic!("Unknown opcode for comparing boolean"),
            },
            _ => panic!("unsupported comparison for those types"),
        };
        self.alloc_and_push(Value::Boolean(result));
        self.heap.free(left);
        self.heap.free(right);
    }

    fn execute_minus_operation(&mut self) {
        let operand = self.pop_owned();
        let negated = match get_value(&self.heap, operand) {
            Value::Integer(l) => -l,
            _ => panic!("unsupported types for negation"),
        };
        self.alloc_and_push(Value::Integer(negated));
        self.heap.free(operand);
    }

    fn execute_bang_operation(&mut self) {
        let operand = self.pop_owned();
        let result = match get_value(&self.heap, operand) {
            Value::Boolean(l) => !l,
            _ => false,
        };
        self.alloc_and_push(Value::Boolean(result));
        self.heap.free(operand);
    }

    fn build_array(&mut self, start: usize, end: usize) -> Vec<GcRef> {
        let mut elements = Vec::with_capacity(end - start);
        for i in start..end {
            elements.push(self.stack[i]);
        }
        elements
    }

    fn build_hash(&mut self, start: usize, end: usize) -> HashMap<HashKey, GcRef> {
        let mut elements = HashMap::new();
        for i in (start..end).step_by(2) {
            let key_ref = self.stack[i];
            let key = HashKey::from_value(get_value(&self.heap, key_ref))
                .expect("hash key must be hashable");
            elements.insert(key, self.stack[i + 1]);
        }
        elements
    }

    fn execute_index_operation(&mut self, left: GcRef, index: GcRef) {
        let left_value = get_value(&self.heap, left).clone();
        let index_value = get_value(&self.heap, index).clone();
        match (&left_value, &index_value) {
            (Value::Array(array), Value::Integer(i)) => {
                self.execute_array_index(array, *i);
            }
            (Value::Hash(hash), _) => {
                self.execute_hash_index(hash, &index_value);
            }
            _ => panic!("unsupported index operation for those types"),
        }
    }

    fn execute_array_index(&mut self, array: &[GcRef], index: i64) {
        if index < array.len() as i64 && index >= 0 {
            self.dup_and_push(array[index as usize]);
        } else {
            self.dup_and_push(self.null);
        }
    }

    fn execute_hash_index(&mut self, hash: &HashMap<HashKey, GcRef>, index: &Value) {
        let key = HashKey::from_value(index).expect("unsupported hash index key");
        match hash.get(&key) {
            Some(value) => self.dup_and_push(*value),
            None => self.dup_and_push(self.null),
        }
    }

    fn current_frame(&mut self) -> &mut Frame {
        &mut self.frames[self.frame_index - 1]
    }

    fn push_frame(&mut self, frame: Frame) {
        self.frames[self.frame_index] = frame;
        self.frame_index += 1;
    }

    fn pop_frame(&mut self) -> Frame {
        self.frame_index -= 1;
        self.frames[self.frame_index].clone()
    }

    fn execute_call(&mut self, num_args: usize) {
        let callee = self.stack[self.sp - 1 - num_args];
        match callee_kind(&self.heap, callee) {
            CalleeKind::Closure(closure) => self.call_closure(closure, num_args),
            CalleeKind::Builtin(builtin) => self.call_builtin(builtin, num_args),
        }
    }

    fn call_closure(&mut self, closure: GcClosure, num_args: usize) {
        let compiled = match get_value(&self.heap, closure.func) {
            Value::CompiledFunction(f) => f.clone(),
            _ => panic!("closure without compiled function"),
        };
        if compiled.num_parameters != num_args {
            panic!("wrong number of arguments: want={}, got={}", compiled.num_parameters, num_args);
        }

        let frame = Frame::new(closure, compiled.instructions, self.sp - num_args);
        self.sp = frame.base_pointer + compiled.num_locals;
        self.push_frame(frame);
    }

    fn call_builtin(&mut self, builtin: object::BuiltinFunc, num_args: usize) {
        let base = self.sp - num_args - 1;
        let args = self.stack[self.sp - num_args..self.sp].to_vec();
        let result = call_builtin(&mut self.heap, builtin, args);
        self.clear_stack_range(base, self.sp);
        self.sp = base;
        self.push_raw(result);
    }

    fn push_closure(&mut self, const_index: usize, num_free: usize) {
        match get_value(&self.heap, self.constants[const_index]).clone() {
            Value::CompiledFunction(_) => {
                let start = self.sp - num_free;
                let mut free = Vec::with_capacity(num_free);
                for i in 0..num_free {
                    free.push(self.stack[start + i]);
                }
                let func = self.constants[const_index];
                let closure = alloc_value(
                    &mut self.heap,
                    Value::Closure(GcClosure {
                        func,
                        free,
                    }),
                );
                self.clear_stack_range(start, self.sp);
                self.sp = start;
                self.push_raw(closure);
            }
            other => panic!("not a function {:?}", other),
        }
    }
}

fn is_truthy(heap: &GcHeap, condition: GcRef) -> bool {
    match get_value(heap, condition) {
        Value::Boolean(b) => *b,
        Value::Null => false,
        _ => true,
    }
}

fn callee_kind(heap: &GcHeap, reference: GcRef) -> CalleeKind {
    match get_value(heap, reference) {
        Value::Closure(closure) => CalleeKind::Closure(closure.clone()),
        Value::Builtin(builtin) => CalleeKind::Builtin(*builtin),
        _ => panic!("calling non-closure"),
    }
}

fn compiled_instructions(heap: &GcHeap, func: GcRef) -> Vec<u8> {
    match get_value(heap, func) {
        Value::CompiledFunction(f) => f.instructions.clone(),
        _ => panic!("expected compiled function"),
    }
}