Chapter 15.2

This commit is contained in:
Tom Willemse 2021-07-27 22:21:40 -07:00
parent 79c1056553
commit 73dfe7efa5
Signed by: ryuslash
GPG key ID: 7D5C407B435025C1
2 changed files with 34 additions and 3 deletions

View file

@ -6,16 +6,39 @@
VM vm; VM vm;
void initVM() {} static void resetStack() {
vm.stackTop = vm.stack;
}
void initVM() {
resetStack();
}
void freeVM() {} void freeVM() {}
void push(Value value) {
*vm.stackTop = value;
vm.stackTop++;
}
Value pop() {
vm.stackTop--;
return *vm.stackTop;
}
static InterpretResult run() { static InterpretResult run() {
#define READ_BYTE() (*vm.ip++) #define READ_BYTE() (*vm.ip++)
#define READ_CONSTANT() (vm.chunk->constants.values[READ_BYTE()]) #define READ_CONSTANT() (vm.chunk->constants.values[READ_BYTE()])
for (;;) { for (;;) {
#ifdef DEBUG_TRACE_EXECUTION #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)); disassembleInstruction(vm.chunk, (int)(vm.ip - vm.chunk->code));
#endif #endif
@ -23,11 +46,12 @@ static InterpretResult run() {
switch (instruction = READ_BYTE()) { switch (instruction = READ_BYTE()) {
case OP_CONSTANT: { case OP_CONSTANT: {
Value constant = READ_CONSTANT(); Value constant = READ_CONSTANT();
printValue(constant); push(constant);
printf("\n");
break; break;
} }
case OP_RETURN: { case OP_RETURN: {
printValue(pop());
printf("\n");
return INTERPRET_OK; return INTERPRET_OK;
} }
} }

View file

@ -2,10 +2,15 @@
#define clox_vm_h #define clox_vm_h
#include "chunk.h" #include "chunk.h"
#include "value.h"
#define STACK_MAX 256
typedef struct { typedef struct {
Chunk *chunk; Chunk *chunk;
uint8_t *ip; uint8_t *ip;
Value stack[STACK_MAX];
Value* stackTop;
} VM; } VM;
typedef enum { typedef enum {
@ -17,5 +22,7 @@ typedef enum {
void initVM(); void initVM();
void freeVM(); void freeVM();
InterpretResult interpret(Chunk *chunk); InterpretResult interpret(Chunk *chunk);
void push(Value value);
Value pop();
#endif #endif