From ad6a98f6ad3cce9d69648360d00d5dcd67d8ca0f Mon Sep 17 00:00:00 2001 From: Tom Willemse Date: Fri, 12 Aug 2022 19:58:10 -0700 Subject: Chapter 26.7 --- clox/src/chunk.c | 16 ++++++++++------ clox/src/object.c | 4 ++++ clox/src/vm.c | 6 ++++-- 3 files changed, 18 insertions(+), 8 deletions(-) (limited to 'clox/src') diff --git a/clox/src/chunk.c b/clox/src/chunk.c index f368dec..297dcb7 100644 --- a/clox/src/chunk.c +++ b/clox/src/chunk.c @@ -1,9 +1,10 @@ #include #include "chunk.h" -#include "memory.h" +#include "memory.h" +#include "vm.h" -void initChunk(Chunk* chunk) { +void initChunk(Chunk *chunk) { chunk->count = 0; chunk->capacity = 0; chunk->code = NULL; @@ -11,18 +12,19 @@ void initChunk(Chunk* chunk) { initValueArray(&chunk->constants); } -void freeChunk(Chunk* chunk) { +void freeChunk(Chunk *chunk) { FREE_ARRAY(uint8_t, chunk->code, chunk->capacity); FREE_ARRAY(int, chunk->lines, chunk->capacity); freeValueArray(&chunk->constants); initChunk(chunk); } -void writeChunk(Chunk* chunk, uint8_t byte, int line) { +void writeChunk(Chunk *chunk, uint8_t byte, int line) { if (chunk->capacity < chunk->count + 1) { int oldCapacity = chunk->capacity; chunk->capacity = GROW_CAPACITY(oldCapacity); - chunk->code = GROW_ARRAY(uint8_t, chunk->code, oldCapacity, chunk->capacity); + chunk->code = + GROW_ARRAY(uint8_t, chunk->code, oldCapacity, chunk->capacity); chunk->lines = GROW_ARRAY(int, chunk->lines, oldCapacity, chunk->capacity); } @@ -31,7 +33,9 @@ void writeChunk(Chunk* chunk, uint8_t byte, int line) { chunk->count++; } -int addConstant(Chunk* chunk, Value value) { +int addConstant(Chunk *chunk, Value value) { + push(value); writeValueArray(&chunk->constants, value); + pop(); return chunk->constants.count - 1; } diff --git a/clox/src/object.c b/clox/src/object.c index 5f2bdde..376742f 100644 --- a/clox/src/object.c +++ b/clox/src/object.c @@ -58,7 +58,11 @@ static ObjString *allocateString(char *chars, int length, uint32_t hash) { string->length = length; string->chars = chars; string->hash = hash; + + push(OBJ_VAL(string)); tableSet(&vm.strings, string, NIL_VAL); + pop(); + return string; } diff --git a/clox/src/vm.c b/clox/src/vm.c index c9556b2..601b128 100644 --- a/clox/src/vm.c +++ b/clox/src/vm.c @@ -163,8 +163,8 @@ static bool isFalsey(Value value) { } static void concatenate() { - ObjString *b = AS_STRING(pop()); - ObjString *a = AS_STRING(pop()); + ObjString *b = AS_STRING(peek(0)); + ObjString *a = AS_STRING(peek(1)); int length = a->length + b->length; char *chars = ALLOCATE(char, length + 1); @@ -173,6 +173,8 @@ static void concatenate() { chars[length] = '\0'; ObjString *result = takeString(chars, length); + pop(); + pop(); push(OBJ_VAL(result)); } -- cgit v1.2.3-54-g00ecf