crafting-interpreters/clox/src/debug.c

80 lines
2.3 KiB
C
Raw Normal View History

2021-07-08 02:24:24 -07:00
#include <stdio.h>
#include "debug.h"
#include "value.h"
2021-07-29 23:38:20 -07:00
void disassembleChunk(Chunk *chunk, const char *name) {
2021-07-08 02:24:24 -07:00
printf("== %s ==\n", name);
for (int offset = 0; offset < chunk->count;) {
offset = disassembleInstruction(chunk, offset);
}
}
2021-07-29 23:38:20 -07:00
static int constantInstruction(const char *name, Chunk *chunk, int offset) {
2021-07-08 02:24:24 -07:00
uint8_t constant = chunk->code[offset + 1];
printf("%-16s %4d '", name, constant);
printValue(chunk->constants.values[constant]);
printf("'\n");
return offset + 2;
}
2021-07-29 23:38:20 -07:00
static int simpleInstruction(const char *name, int offset) {
2021-07-08 02:24:24 -07:00
printf("%s\n", name);
return offset + 1;
}
2021-07-29 23:38:20 -07:00
int disassembleInstruction(Chunk *chunk, int offset) {
2021-07-08 02:24:24 -07:00
printf("%04d ", offset);
2021-07-29 23:38:20 -07:00
if (offset > 0 && chunk->lines[offset] == chunk->lines[offset - 1]) {
2021-07-08 02:24:24 -07:00
printf(" | ");
} else {
printf("%4d ", chunk->lines[offset]);
}
uint8_t instruction = chunk->code[offset];
switch (instruction) {
case OP_CONSTANT:
return constantInstruction("OP_CONSTANT", chunk, offset);
2021-09-06 02:03:31 -07:00
case OP_NIL:
return simpleInstruction("OP_NIL", offset);
case OP_TRUE:
return simpleInstruction("OP_TRUE", offset);
case OP_FALSE:
return simpleInstruction("OP_FALSE", offset);
2021-09-20 21:47:41 -07:00
case OP_POP:
return simpleInstruction("OP_POP", offset);
2021-10-11 00:13:15 -07:00
case OP_GET_GLOBAL:
return constantInstruction("OP_GET_GLOBAL", chunk, offset);
2021-09-20 21:47:41 -07:00
case OP_DEFINE_GLOBAL:
return constantInstruction("OP_DEFINE_GLOBAL", chunk, offset);
2021-10-21 19:51:01 -07:00
case OP_SET_GLOBAL:
return constantInstruction("OP_SET_GLOBAL", chunk, offset);
2021-09-06 02:03:31 -07:00
case OP_EQUAL:
return simpleInstruction("OP_EQUAL", offset);
case OP_GREATER:
return simpleInstruction("OP_GREATER", offset);
case OP_LESS:
return simpleInstruction("OP_LESS", offset);
2021-07-29 23:56:42 -07:00
case OP_ADD:
return simpleInstruction("OP_ADD", offset);
case OP_SUBTRACT:
return simpleInstruction("OP_SUBTRACT", offset);
case OP_MULTIPLY:
return simpleInstruction("OP_MULTIPLY", offset);
case OP_DIVIDE:
return simpleInstruction("OP_DIVIDE", offset);
2021-09-06 02:03:31 -07:00
case OP_NOT:
return simpleInstruction("OP_NOT", offset);
2021-07-29 23:38:20 -07:00
case OP_NEGATE:
return simpleInstruction("OP_NEGATE", offset);
2021-09-20 21:47:41 -07:00
case OP_PRINT:
return simpleInstruction("OP_PRINT", offset);
2021-07-08 02:24:24 -07:00
case OP_RETURN:
return simpleInstruction("OP_RETURN", offset);
default:
printf("Unknown opcode %d\n", instruction);
return offset + 1;
}
}