From 72c5830637c8e7dc6524bae32180861e0a64e60c Mon Sep 17 00:00:00 2001 From: zongor Date: Sat, 3 May 2025 21:28:34 -0400 Subject: [PATCH] add line numbers --- src/chunk.c | 7 ++++++- src/chunk.h | 3 ++- src/debug.c | 6 ++++++ src/main.c | 6 +++--- 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/chunk.c b/src/chunk.c index 77e73f8..1d86f26 100644 --- a/src/chunk.c +++ b/src/chunk.c @@ -6,23 +6,28 @@ void newChunk(Chunk* chunk) { chunk->count = 0; chunk->capacity = 0; chunk->code = NULL; + chunk->lines = NULL; newValueArray(&chunk->constants); } -void writeChunk(Chunk *chunk, uint8_t byte) { +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->lines = GROW_ARRAY(int, chunk->lines, + oldCapacity, chunk->capacity); } chunk->code[chunk->count] = byte; + chunk->lines[chunk->count] = line; chunk->count++; } void freeChunk(Chunk *chunk) { FREE_ARRAY(uint8_t, chunk->code, chunk->capacity); + FREE_ARRAY(int, chunk->lines, chunk->capacity); freeValueArray(&chunk->constants); newChunk(chunk); } diff --git a/src/chunk.h b/src/chunk.h index 9df161f..894ebe3 100644 --- a/src/chunk.h +++ b/src/chunk.h @@ -15,12 +15,13 @@ typedef struct Chunk { int count; int capacity; uint8_t *code; + int *lines; ValueArray constants; } Chunk; void newChunk(Chunk *chunk); void freeChunk(Chunk *chunk); -void writeChunk(Chunk *chunk, uint8_t byte); +void writeChunk(Chunk *chunk, uint8_t byte, int line); int addConstant(Chunk *chunk, Value value); #endif diff --git a/src/debug.c b/src/debug.c index 12f63c4..7b59fb0 100644 --- a/src/debug.c +++ b/src/debug.c @@ -27,6 +27,12 @@ static int simpleInstruction(const char* name, int offset) { int disassembleInstruction(Chunk* chunk, int offset) { printf("%04d ", offset); + if (offset > 0 && + chunk->lines[offset] == chunk->lines[offset - 1]) { + printf(" | "); + } else { + printf("%4d ", chunk->lines[offset]); + } uint8_t instruction = chunk->code[offset]; switch (instruction) { diff --git a/src/main.c b/src/main.c index 4edaa0a..7765e3e 100644 --- a/src/main.c +++ b/src/main.c @@ -7,10 +7,10 @@ int main(int argc, const char** argv) { newChunk(&chunk); int constant = addConstant(&chunk, 1.2); - writeChunk(&chunk, OP_CONSTANT); - writeChunk(&chunk, constant); + writeChunk(&chunk, OP_CONSTANT, 1); + writeChunk(&chunk, constant, 1); - writeChunk(&chunk, OP_RETURN); + writeChunk(&chunk, OP_RETURN, 1); disassembleChunk(&chunk, "test chunk"); freeChunk(&chunk);