Chapter 15.1

This commit is contained in:
Tom Willemse 2021-07-22 01:09:11 -07:00
parent 7fe0c7f639
commit 50473e5ab5
Signed by: ryuslash
GPG key ID: 7D5C407B435025C1
5 changed files with 76 additions and 2 deletions

View file

@ -8,4 +8,6 @@ add_executable(Lox
debug.c
value.h
value.c
vm.h
vm.c
main.c)

View file

@ -5,4 +5,6 @@
#include <stddef.h>
#include <stdint.h>
#define DEBUG_TRACE_EXECUTION
#endif

View file

@ -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;
}

44
clox/src/vm.c Normal file
View file

@ -0,0 +1,44 @@
#include <stdio.h>
#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();
}

21
clox/src/vm.h Normal file
View file

@ -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