A Virtual Machine 15
This commit is contained in:
parent
7fa01b4fb9
commit
aba643a88e
7 changed files with 139 additions and 28 deletions
59
src/clox/vm.d
Normal file
59
src/clox/vm.d
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
module clox.vm;
|
||||
|
||||
import std.stdio;
|
||||
|
||||
import clox.chunk;
|
||||
import clox.value;
|
||||
import clox.dbg;
|
||||
import clox.util;
|
||||
|
||||
enum stackMax = 256;
|
||||
|
||||
struct VM{
|
||||
const(ubyte)* ip;
|
||||
Stack!(Value, stackMax) stack;
|
||||
Chunk* chunk;
|
||||
enum InterpretResult{ Ok, CompileError, RunetimeError }
|
||||
this(int _) @nogc nothrow {
|
||||
stack = typeof(stack)(0);
|
||||
}
|
||||
InterpretResult interpret(Chunk* chunk) @nogc nothrow {
|
||||
this.chunk = chunk;
|
||||
ip = &chunk.code[0];
|
||||
return run();
|
||||
}
|
||||
private InterpretResult run() @nogc nothrow {
|
||||
auto readByte() => *ip++;
|
||||
auto readIns() => cast(OpCode)readByte();
|
||||
auto readConstant() => chunk.constants[readByte()];
|
||||
while(true){
|
||||
debug(traceExec){
|
||||
writeln(" ", stack.live);
|
||||
debug disassembleInstruction(chunk, ip - &chunk.code[0]);
|
||||
}
|
||||
OpCode instruction = readIns();
|
||||
with(OpCode) opSwitch: final switch(instruction){
|
||||
case Constant:
|
||||
Value constant = readConstant();
|
||||
stack.push(constant);
|
||||
break;
|
||||
static foreach(k, op; [ Add: "+", Subtract: "-", Multiply: "*", Divide: "/" ]){
|
||||
case k:
|
||||
Value b = stack.pop();
|
||||
Value a = stack.pop();
|
||||
stack.push(mixin("a", op, "b"));
|
||||
break opSwitch;
|
||||
}
|
||||
case Negate:
|
||||
stack.push(-stack.pop());
|
||||
break;
|
||||
case Return:
|
||||
debug printValue(stack.pop());
|
||||
debug writeln();
|
||||
return InterpretResult.Ok;
|
||||
}
|
||||
}
|
||||
assert(0);
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue