aboutsummaryrefslogtreecommitdiff
path: root/dbg.d
diff options
context:
space:
mode:
authorBen Winston2023-05-20 13:36:28 -0400
committerBen Winston2023-05-20 13:36:28 -0400
commit6902cc5abe09da9f6f2d86f22d06684d97cfa9f3 (patch)
tree27946af44ede97cc4928c527c900018682686c9f /dbg.d
parent10c75f60c1f5fa27268ea9a850b63b777b087cbc (diff)
add debug
Diffstat (limited to 'dbg.d')
-rw-r--r--dbg.d64
1 files changed, 64 insertions, 0 deletions
diff --git a/dbg.d b/dbg.d
new file mode 100644
index 0000000..4af02a6
--- /dev/null
+++ b/dbg.d
@@ -0,0 +1,64 @@
+import std.stdio;
+import std.string;
+
+import chunk;
+import parser : Value, Atom, ValueType;
+//import parser;
+//import dbg;
+//import value;
+
+string printableValue(Value val) {
+ switch (val.type) {
+ case ValueType.STRING:
+ return val.as.str;
+ case ValueType.NUMBER:
+ return format("%g", val.as.number);
+ case ValueType.BOOLEAN:
+ if (val.as.boolean) {
+ return "true";
+ } else {
+ return "false";
+ }
+ default:
+ return "! unknown value type !";
+ }
+}
+
+string atomAsString(Atom a) {
+ return printableValue(a.value);
+}
+
+int constantInstruction(string message, Chunk chunk, int offset) {
+ ubyte idx = chunk.code[offset + 1];
+ //writeln("dunno how to write a constant");
+ writefln("%-16s %4d '%s'", message, idx, printableValue(chunk.constants[idx]));
+ //writefln("%-16s %4d '%s'", message, idx, atomAsString(chunk.constants[idx]));
+ return offset + 2;
+}
+
+int simpleInstruction(string message, int offset) {
+ writeln(message);
+ return offset + 1;
+}
+
+int disassemble(Chunk chunk, int offset) {
+ writef("%04d %4d ", offset, chunk.lines[offset]);
+
+ ubyte inst = chunk.code[offset];
+ switch (inst) {
+ case OpCode.OP_ADD:
+ return simpleInstruction("OP_ADD", offset);
+ case OpCode.OP_CONSTANT:
+ return constantInstruction("OP_CONSTANT", chunk, offset);
+ case OpCode.OP_NEGATE:
+ return simpleInstruction("OP_NEGATE", offset);
+ case OpCode.OP_POP:
+ return simpleInstruction("OP_POP", offset);
+ case OpCode.OP_RETURN:
+ return simpleInstruction("OP_RETURN", offset);
+ default:
+ writeln("unknown opcode?");
+ return offset + 1;
+ }
+ return 0;
+}