diff options
| author | Ben Winston | 2023-05-21 20:26:59 -0400 |
|---|---|---|
| committer | Ben Winston | 2023-05-21 20:26:59 -0400 |
| commit | 8e1f84b1369909745859777d07a5e8e74b5df334 (patch) | |
| tree | 460f42755407e9ddf1b3e6dfabea6a09b3d1585d | |
| parent | a26bfccdc52ab50a83b8f8d170c9e1a3be0164a5 (diff) | |
move disassembly into compiler, preparing for functions
| -rw-r--r-- | chunk.d | 12 | ||||
| -rw-r--r-- | compiler.d | 19 | ||||
| -rw-r--r-- | dbg.d | 16 | ||||
| -rw-r--r-- | main.d | 11 |
4 files changed, 32 insertions, 26 deletions
@@ -6,6 +6,7 @@ import parser; enum ObjType { FUNCTION, + SCRIPT, } abstract class Obj { @@ -14,19 +15,22 @@ abstract class Obj { class Function : Obj { Chunk chunk; + int arity; string name; + ObjType type; - this() { - this.type = ObjType.FUNCTION; + this(ObjType type) { + this.type = type; this.chunk = new Chunk(); + this.arity = 0; this.name = ""; } override string toString() { - if (name == "") { + if (type == ObjType.SCRIPT) { return "<neb>"; } else { - return name; + return format("<fn %s>", name); } } } @@ -7,11 +7,6 @@ import parser; import chunk; import dbg; -enum FunctionType { - FUNCTION, - SCRIPT, -} - struct Local { Symbol sym; int depth; @@ -20,7 +15,6 @@ struct Local { class Compiler { Function func; - FunctionType type; Parser* parser; Local[] locals; int localCount; @@ -369,15 +363,16 @@ class Compiler { Function finish() { this.func.chunk.writeOp(OpCode.OP_RETURN, current.line); + disassembleChunk(func.chunk, to!string(func)); return func; } - this(FunctionType type, Parser* parser) { + this(ObjType type, Parser* parser) { this.parser = parser; - this.func = new Function(); - this.type = type; - localCount = 0; - //locals ~= Local(new Symbol("", -1), 0); - //localCount++; + this.func = new Function(type); + //localCount = 0; + + locals ~= Local(new Symbol("", -1), 0); + localCount++; } } @@ -80,6 +80,10 @@ string printableValue(Value val) { } } +string printableFunction(Function func) { + return format("%s", func); +} + string atomAsString(Atom a) { return printableValue(a.value); } @@ -110,6 +114,18 @@ int simpleInstruction(string message, int offset) { return offset + 1; } +void disassembleChunk(Chunk chunk, string name) { + writefln("== %s ==", name); + int cnt = 0; + while(true) { + if (cnt >= chunk.code.length) { + break; + } + cnt = disassemble(chunk, cnt); + } + +} + int disassemble(Chunk chunk, int offset) { writef("%04d %4d ", offset, chunk.lines[offset]); @@ -28,18 +28,9 @@ void repl() { Parser parser = new Parser(input); - Compiler compiler = new Compiler(FunctionType.SCRIPT, &parser); + Compiler compiler = new Compiler(ObjType.SCRIPT, &parser); Function func = compiler.compile(); - int cnt = 0; - writeln("== disassembly =="); - while(true) { - if (cnt >= func.chunk.code.length) { - break; - } - cnt = disassemble(func.chunk, cnt); - } - VM vm = new VM(func); vm.run(); |
