aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--chunk.d2
-rw-r--r--dbg.d64
-rw-r--r--main.d1
-rw-r--r--parser.d19
4 files changed, 68 insertions, 18 deletions
diff --git a/chunk.d b/chunk.d
index 5233a87..56b960d 100644
--- a/chunk.d
+++ b/chunk.d
@@ -33,9 +33,11 @@ class Function : Obj {
enum OpCode {
OP_ADD,
+ OP_NEGATE,
OP_RETURN,
OP_CONSTANT,
OP_POP,
+ OP_NIL,
}
class Chunk {
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;
+}
diff --git a/main.d b/main.d
index 18927d8..bd1d2b0 100644
--- a/main.d
+++ b/main.d
@@ -2,6 +2,7 @@ import std.stdio;
import std.string;
import parser;
+import dbg;
/*
import compiler;
import obj;
diff --git a/parser.d b/parser.d
index d471f4d..71b835b 100644
--- a/parser.d
+++ b/parser.d
@@ -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;