aboutsummaryrefslogtreecommitdiffstats
path: root/clox/src/debug.c
diff options
context:
space:
mode:
authorGravatar Tom Willemse2021-07-08 02:24:24 -0700
committerGravatar Tom Willemse2021-07-08 02:25:13 -0700
commit2c007a8f94d65dc40f638b284db7e374a58b632f (patch)
tree260a1460cdb86c913e785171a85447afc03efddf /clox/src/debug.c
parenta779473cede81f4d3b4eed6f6b4e4184d43ffa87 (diff)
downloadcrafting-interpreters-2c007a8f94d65dc40f638b284db7e374a58b632f.tar.gz
crafting-interpreters-2c007a8f94d65dc40f638b284db7e374a58b632f.zip
Chapter 14.1-6
Diffstat (limited to 'clox/src/debug.c')
-rw-r--r--clox/src/debug.c46
1 files changed, 46 insertions, 0 deletions
diff --git a/clox/src/debug.c b/clox/src/debug.c
new file mode 100644
index 0000000..68fdbc5
--- /dev/null
+++ b/clox/src/debug.c
@@ -0,0 +1,46 @@
+#include <stdio.h>
+
+#include "debug.h"
+#include "value.h"
+
+void disassembleChunk(Chunk* chunk, const char* name) {
+ printf("== %s ==\n", name);
+
+ for (int offset = 0; offset < chunk->count;) {
+ offset = disassembleInstruction(chunk, offset);
+ }
+}
+
+static int constantInstruction(const char* name, Chunk* chunk, int offset) {
+ uint8_t constant = chunk->code[offset + 1];
+ printf("%-16s %4d '", name, constant);
+ printValue(chunk->constants.values[constant]);
+ printf("'\n");
+ return offset + 2;
+}
+
+static int simpleInstruction(const char* name, int offset) {
+ printf("%s\n", name);
+ return offset + 1;
+}
+
+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) {
+ case OP_CONSTANT:
+ return constantInstruction("OP_CONSTANT", chunk, offset);
+ case OP_RETURN:
+ return simpleInstruction("OP_RETURN", offset);
+ default:
+ printf("Unknown opcode %d\n", instruction);
+ return offset + 1;
+ }
+}