diff options
| author | Ben Winston | 2023-05-20 13:36:28 -0400 |
|---|---|---|
| committer | Ben Winston | 2023-05-20 13:36:28 -0400 |
| commit | 6902cc5abe09da9f6f2d86f22d06684d97cfa9f3 (patch) | |
| tree | 27946af44ede97cc4928c527c900018682686c9f | |
| parent | 10c75f60c1f5fa27268ea9a850b63b777b087cbc (diff) | |
add debug
| -rw-r--r-- | chunk.d | 2 | ||||
| -rw-r--r-- | dbg.d | 64 | ||||
| -rw-r--r-- | main.d | 1 | ||||
| -rw-r--r-- | parser.d | 19 |
4 files changed, 68 insertions, 18 deletions
@@ -33,9 +33,11 @@ class Function : Obj { enum OpCode { OP_ADD, + OP_NEGATE, OP_RETURN, OP_CONSTANT, OP_POP, + OP_NIL, } class Chunk { @@ -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; +} @@ -2,6 +2,7 @@ import std.stdio; import std.string; import parser; +import dbg; /* import compiler; import obj; @@ -4,6 +4,7 @@ import std.algorithm : canFind; import std.conv : to; import chunk; +import dbg; enum FormType { ATOM, @@ -174,24 +175,6 @@ Value makeObjValue(Obj obj) { return val; } -string atomAsString(Atom a) { - Value val = a.value; - 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 !"; - } -} - class Parser { string source; |
