aboutsummaryrefslogtreecommitdiffstats
path: root/src/bytecode/vm.h
diff options
context:
space:
mode:
authorBad Diode <bd@badd10de.dev>2021-10-22 12:24:10 +0200
committerBad Diode <bd@badd10de.dev>2021-10-22 12:24:10 +0200
commit9286c148f601072dded92233a328a8867ff7ab0c (patch)
treeb3326e3c6b247b0e732cae41038ea30d341d272d /src/bytecode/vm.h
parentd9474f1d7c0c6674179fd0f27cd1c084c8227ed5 (diff)
downloadbdl-9286c148f601072dded92233a328a8867ff7ab0c.tar.gz
bdl-9286c148f601072dded92233a328a8867ff7ab0c.zip
Add a stack for our VM
Diffstat (limited to 'src/bytecode/vm.h')
-rw-r--r--src/bytecode/vm.h23
1 files changed, 20 insertions, 3 deletions
diff --git a/src/bytecode/vm.h b/src/bytecode/vm.h
index d53fcf9..d9b37a3 100644
--- a/src/bytecode/vm.h
+++ b/src/bytecode/vm.h
@@ -7,9 +7,15 @@
7#include "ops.h" 7#include "ops.h"
8#include "debug.h" 8#include "debug.h"
9 9
10#define VM_STACK_CAP 1024
11
10typedef struct VM { 12typedef struct VM {
13 // Program code.
11 Chunk *chunk; 14 Chunk *chunk;
15 // Program counter.
12 u8 *pc; 16 u8 *pc;
17 // Stack.
18 Object *stack;
13} VM; 19} VM;
14 20
15VM vm_init(void); 21VM vm_init(void);
@@ -21,12 +27,14 @@ vm_init(void) {
21 VM vm = { 27 VM vm = {
22 .chunk = chunk_init(), 28 .chunk = chunk_init(),
23 }; 29 };
30 array_init(vm.stack, VM_STACK_CAP);
24 return vm; 31 return vm;
25} 32}
26 33
27void 34void
28vm_free(VM vm) { 35vm_free(VM vm) {
29 chunk_free(vm.chunk); 36 chunk_free(vm.chunk);
37 array_free(vm.stack);
30} 38}
31 39
32void 40void
@@ -43,17 +51,26 @@ vm_interpret(VM vm) {
43 u8 *last = vm.chunk->code + array_size(vm.chunk->code); 51 u8 *last = vm.chunk->code + array_size(vm.chunk->code);
44 while (vm.pc < last) { 52 while (vm.pc < last) {
45#ifdef DEBUG_TRACE_EXECUTION 53#ifdef DEBUG_TRACE_EXECUTION
46 disassemble_instruction(vm.chunk, (vm.pc - vm.chunk->code)); 54 printf("stack: [ ");
55 for (size_t i = 0; i < array_size(vm.stack); i++) {
56 display(vm.stack[i]);
57 if (i < array_size(vm.stack) - 1) {
58 printf(" | ");
59 }
60 }
61 printf(" ]\nop: ");
62 disassemble_instruction(vm.chunk, (vm.pc - vm.chunk->code));
47#endif 63#endif
48 u8 instruction = *vm.pc++; 64 u8 instruction = *vm.pc++;
49 switch (instruction) { 65 switch (instruction) {
50 case OP_CONSTANT: { 66 case OP_CONSTANT: {
51 u8 constant = *vm.pc++; 67 u8 constant = *vm.pc++;
52 Object obj = vm.chunk->constants[constant]; 68 Object obj = vm.chunk->constants[constant];
53 display(obj); 69 array_push(vm.stack, obj);
54 printf("\n");
55 } break; 70 } break;
56 case OP_RETURN: { 71 case OP_RETURN: {
72 display(array_pop(vm.stack));
73 printf("\n");
57 return; 74 return;
58 } break; 75 } break;
59 default: { 76 default: {