aboutsummaryrefslogtreecommitdiffstats
path: root/clox/src/vm.c
diff options
context:
space:
mode:
authorGravatar Tom Willemse2021-09-20 21:47:41 -0700
committerGravatar Tom Willemse2021-09-20 21:47:41 -0700
commitfcbea5f617edb6e3dfa68eb31efa402b4916c032 (patch)
tree26fb96c9bc9d603b21d80159027b288c79f7ff24 /clox/src/vm.c
parentaa41f26a26fcff212ecc55750a4806d83a6cf5dc (diff)
downloadcrafting-interpreters-fcbea5f617edb6e3dfa68eb31efa402b4916c032.tar.gz
crafting-interpreters-fcbea5f617edb6e3dfa68eb31efa402b4916c032.zip
Chapter 21.1 - 21.3
Diffstat (limited to 'clox/src/vm.c')
-rw-r--r--clox/src/vm.c22
1 files changed, 22 insertions, 0 deletions
diff --git a/clox/src/vm.c b/clox/src/vm.c
index e35a1e0..709f3d1 100644
--- a/clox/src/vm.c
+++ b/clox/src/vm.c
@@ -29,10 +29,13 @@ static void runtimeError(const char *format, ...) {
void initVM() {
resetStack();
vm.objects = NULL;
+
+ initTable(&vm.globals);
initTable(&vm.strings);
}
void freeVM() {
+ freeTable(&vm.globals);
freeTable(&vm.strings);
freeObjects();
}
@@ -70,6 +73,7 @@ static void concatenate() {
static InterpretResult run() {
#define READ_BYTE() (*vm.ip++)
#define READ_CONSTANT() (vm.chunk->constants.values[READ_BYTE()])
+#define READ_STRING() AS_STRING(READ_CONSTANT())
#define BINARY_OP(valueType, op) \
do { \
if (!IS_NUMBER(peek(0)) || !IS_NUMBER(peek(1))) { \
@@ -108,6 +112,15 @@ static InterpretResult run() {
case OP_FALSE:
push(BOOL_VAL(false));
break;
+ case OP_POP:
+ pop();
+ break;
+ case OP_DEFINE_GLOBAL: {
+ ObjString *name = READ_STRING();
+ tableSet(&vm.globals, name, peek(0));
+ pop();
+ break;
+ }
case OP_EQUAL: {
Value b = pop();
Value a = pop();
@@ -152,7 +165,15 @@ static InterpretResult run() {
}
push(NUMBER_VAL(-AS_NUMBER(pop())));
break;
+ case OP_PRINT: {
+ printValue(pop());
+ printf("\n");
+ break;
+ }
case OP_RETURN: {
+ /* The book said to remove this, but when I do I get an infinite loop and
+ then a segfault because it keeps trying to add the constant 1 to the
+ stack. */
printValue(pop());
printf("\n");
return INTERPRET_OK;
@@ -162,6 +183,7 @@ static InterpretResult run() {
#undef READ_BYTE
#undef READ_CONSTANT
+#undef READ_STRING
#undef BINARY_OP
}