From 9286c148f601072dded92233a328a8867ff7ab0c Mon Sep 17 00:00:00 2001 From: Bad Diode Date: Fri, 22 Oct 2021 12:24:10 +0200 Subject: Add a stack for our VM --- src/bytecode/vm.h | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) (limited to 'src/bytecode/vm.h') 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 @@ #include "ops.h" #include "debug.h" +#define VM_STACK_CAP 1024 + typedef struct VM { + // Program code. Chunk *chunk; + // Program counter. u8 *pc; + // Stack. + Object *stack; } VM; VM vm_init(void); @@ -21,12 +27,14 @@ vm_init(void) { VM vm = { .chunk = chunk_init(), }; + array_init(vm.stack, VM_STACK_CAP); return vm; } void vm_free(VM vm) { chunk_free(vm.chunk); + array_free(vm.stack); } void @@ -43,17 +51,26 @@ vm_interpret(VM vm) { u8 *last = vm.chunk->code + array_size(vm.chunk->code); while (vm.pc < last) { #ifdef DEBUG_TRACE_EXECUTION - disassemble_instruction(vm.chunk, (vm.pc - vm.chunk->code)); + printf("stack: [ "); + for (size_t i = 0; i < array_size(vm.stack); i++) { + display(vm.stack[i]); + if (i < array_size(vm.stack) - 1) { + printf(" | "); + } + } + printf(" ]\nop: "); + disassemble_instruction(vm.chunk, (vm.pc - vm.chunk->code)); #endif u8 instruction = *vm.pc++; switch (instruction) { case OP_CONSTANT: { u8 constant = *vm.pc++; Object obj = vm.chunk->constants[constant]; - display(obj); - printf("\n"); + array_push(vm.stack, obj); } break; case OP_RETURN: { + display(array_pop(vm.stack)); + printf("\n"); return; } break; default: { -- cgit v1.2.1