From 50473e5ab573d85b1a555874332f6aecdd36f659 Mon Sep 17 00:00:00 2001 From: Tom Willemse Date: Thu, 22 Jul 2021 01:09:11 -0700 Subject: Chapter 15.1 --- clox/src/CMakeLists.txt | 2 ++ clox/src/common.h | 2 ++ clox/src/main.c | 9 +++++++-- clox/src/vm.c | 44 ++++++++++++++++++++++++++++++++++++++++++++ clox/src/vm.h | 21 +++++++++++++++++++++ 5 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 clox/src/vm.c create mode 100644 clox/src/vm.h (limited to 'clox') diff --git a/clox/src/CMakeLists.txt b/clox/src/CMakeLists.txt index 6d7e73b..435a82e 100644 --- a/clox/src/CMakeLists.txt +++ b/clox/src/CMakeLists.txt @@ -8,4 +8,6 @@ add_executable(Lox debug.c value.h value.c + vm.h + vm.c main.c) diff --git a/clox/src/common.h b/clox/src/common.h index c827b76..ddab699 100644 --- a/clox/src/common.h +++ b/clox/src/common.h @@ -5,4 +5,6 @@ #include #include +#define DEBUG_TRACE_EXECUTION + #endif diff --git a/clox/src/main.c b/clox/src/main.c index 9aeb8fd..0f810ba 100644 --- a/clox/src/main.c +++ b/clox/src/main.c @@ -1,8 +1,11 @@ -#include "common.h" #include "chunk.h" +#include "common.h" #include "debug.h" +#include "vm.h" + +int main(int argc, const char *argv[]) { + initVM(); -int main(int argc, const char* argv[]) { Chunk chunk; initChunk(&chunk); @@ -13,6 +16,8 @@ int main(int argc, const char* argv[]) { writeChunk(&chunk, OP_RETURN, 123); disassembleChunk(&chunk, "test chunk"); + interpret(&chunk); + freeVM(); freeChunk(&chunk); return 0; } diff --git a/clox/src/vm.c b/clox/src/vm.c new file mode 100644 index 0000000..14a206e --- /dev/null +++ b/clox/src/vm.c @@ -0,0 +1,44 @@ +#include + +#include "common.h" +#include "debug.h" +#include "vm.h" + +VM vm; + +void initVM() {} + +void freeVM() {} + +static InterpretResult run() { +#define READ_BYTE() (*vm.ip++) +#define READ_CONSTANT() (vm.chunk->constants.values[READ_BYTE()]) + + for (;;) { +#ifdef DEBUG_TRACE_EXECUTION + disassembleInstruction(vm.chunk, (int)(vm.ip - vm.chunk->code)); +#endif + + uint8_t instruction; + switch (instruction = READ_BYTE()) { + case OP_CONSTANT: { + Value constant = READ_CONSTANT(); + printValue(constant); + printf("\n"); + break; + } + case OP_RETURN: { + return INTERPRET_OK; + } + } + } + +#undef READ_BYTE +#undef READ_CONSTANT +} + +InterpretResult interpret(Chunk *chunk) { + vm.chunk = chunk; + vm.ip = vm.chunk->code; + return run(); +} diff --git a/clox/src/vm.h b/clox/src/vm.h new file mode 100644 index 0000000..d11ae70 --- /dev/null +++ b/clox/src/vm.h @@ -0,0 +1,21 @@ +#ifndef clox_vm_h +#define clox_vm_h + +#include "chunk.h" + +typedef struct { + Chunk *chunk; + uint8_t *ip; +} VM; + +typedef enum { + INTERPRET_OK, + INTERPRET_COMPILE_ERROR, + INTERPRET_RUNTIME_ERROR +} InterpretResult; + +void initVM(); +void freeVM(); +InterpretResult interpret(Chunk *chunk); + +#endif -- cgit v1.2.3-54-g00ecf