aboutsummaryrefslogtreecommitdiff
path: root/dbg.d
blob: 4af02a62b5b539064a6829dcf2e42d6a9e4f612e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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;
}