From 73dfe7efa53b5ed58b9e1e94dceec14ec19d6308 Mon Sep 17 00:00:00 2001 From: Tom Willemse Date: Tue, 27 Jul 2021 22:21:40 -0700 Subject: Chapter 15.2 --- clox/src/vm.c | 30 +++++++++++++++++++++++++++--- clox/src/vm.h | 7 +++++++ 2 files changed, 34 insertions(+), 3 deletions(-) (limited to 'clox') diff --git a/clox/src/vm.c b/clox/src/vm.c index 14a206e..ffd207d 100644 --- a/clox/src/vm.c +++ b/clox/src/vm.c @@ -6,16 +6,39 @@ VM vm; -void initVM() {} +static void resetStack() { + vm.stackTop = vm.stack; +} + +void initVM() { + resetStack(); +} void freeVM() {} +void push(Value value) { + *vm.stackTop = value; + vm.stackTop++; +} + +Value pop() { + vm.stackTop--; + return *vm.stackTop; +} + static InterpretResult run() { #define READ_BYTE() (*vm.ip++) #define READ_CONSTANT() (vm.chunk->constants.values[READ_BYTE()]) for (;;) { #ifdef DEBUG_TRACE_EXECUTION + printf(" "); + for (Value *slot = vm.stack; slot < vm.stackTop; slot++) { + printf("[ "); + printValue(*slot); + printf(" ]"); + } + printf("\n"); disassembleInstruction(vm.chunk, (int)(vm.ip - vm.chunk->code)); #endif @@ -23,11 +46,12 @@ static InterpretResult run() { switch (instruction = READ_BYTE()) { case OP_CONSTANT: { Value constant = READ_CONSTANT(); - printValue(constant); - printf("\n"); + push(constant); break; } case OP_RETURN: { + printValue(pop()); + printf("\n"); return INTERPRET_OK; } } diff --git a/clox/src/vm.h b/clox/src/vm.h index d11ae70..2585bd2 100644 --- a/clox/src/vm.h +++ b/clox/src/vm.h @@ -2,10 +2,15 @@ #define clox_vm_h #include "chunk.h" +#include "value.h" + +#define STACK_MAX 256 typedef struct { Chunk *chunk; uint8_t *ip; + Value stack[STACK_MAX]; + Value* stackTop; } VM; typedef enum { @@ -17,5 +22,7 @@ typedef enum { void initVM(); void freeVM(); InterpretResult interpret(Chunk *chunk); +void push(Value value); +Value pop(); #endif -- cgit v1.2.3-54-g00ecf