Strings 19
This commit is contained in:
parent
10c44eab2e
commit
eec0a94aac
15 changed files with 358 additions and 55 deletions
|
|
@ -7,6 +7,7 @@ import clox.value;
|
|||
import clox.dbg;
|
||||
import clox.util;
|
||||
import clox.compiler;
|
||||
import clox.object;
|
||||
import clox.container.stack;
|
||||
import clox.container.varint;
|
||||
import clox.container.int24;
|
||||
|
|
@ -17,10 +18,14 @@ struct VM{
|
|||
const(ubyte)* ip;
|
||||
Stack!(Value, stackMax) stack;
|
||||
Chunk* chunk;
|
||||
Obj* objects;
|
||||
enum InterpretResult{ Ok, CompileError, RuntimeError }
|
||||
this(int _) @nogc nothrow {
|
||||
stack = typeof(stack)(0);
|
||||
}
|
||||
~this(){
|
||||
freeObjects();
|
||||
}
|
||||
InterpretResult interpret(string source){
|
||||
Chunk c = Chunk();
|
||||
Compiler compiler;
|
||||
|
|
@ -56,7 +61,7 @@ struct VM{
|
|||
}
|
||||
while(true){
|
||||
debug(traceExec){
|
||||
writeln(" ", stack.live);
|
||||
stderr.writeln(" ", stack.live);
|
||||
disassembleInstruction(chunk, ip - &chunk.code[0]);
|
||||
}
|
||||
OpCode instruction = readIns();
|
||||
|
|
@ -76,6 +81,15 @@ struct VM{
|
|||
break;
|
||||
static foreach(k, op; [ Add: "+", Subtract: "-", Multiply: "*", Divide: "/" ]){
|
||||
case k:
|
||||
static if(k == Add){
|
||||
if(peek(0).isStr && peek(1).isStr){
|
||||
const(Obj.String)* b = stack.pop().getStr;
|
||||
const(Obj.String)* a = stack.pop().getStr;
|
||||
Obj.String* newStr = Obj.String.concat(a, b, &this);
|
||||
stack.push(Value.str(newStr));
|
||||
break opSwitch;
|
||||
}
|
||||
}
|
||||
if(!peek(0).isNum || !peek(1).isNum){
|
||||
runtimeError("Operands must be numbers.");
|
||||
return InterpretResult.RuntimeError;
|
||||
|
|
@ -104,11 +118,18 @@ struct VM{
|
|||
break;
|
||||
case Return:
|
||||
debug printValue(stack.pop());
|
||||
debug writeln();
|
||||
debug stderr.writeln();
|
||||
return InterpretResult.Ok;
|
||||
}
|
||||
}
|
||||
assert(0);
|
||||
}
|
||||
void freeObjects(){
|
||||
for(Obj* obj = objects; obj !is null;){
|
||||
Obj* next = obj.next;
|
||||
obj.freeObject();
|
||||
obj = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue