1
0

変数を実�

This commit is contained in:
otya128
2015-06-05 19:57:35 +09:00
parent 9b36cd2961
commit 04f35b3801
3 changed files with 49 additions and 7 deletions

View File

@@ -9,17 +9,20 @@ class VM
{
Code[] code;
int stacki;
int pc;
Value[] stack;
this(Code[] code)
Value[] global;
this(Code[] code, int len)
{
this.code = code;
this.stack = new Value[1024 * 1024];
this.global = new Value[len];
}
void run()
{
for(int i = 0; i < this.code.length; i++)
for(pc = 0; pc < this.code.length; pc++)
{
code[i].execute(this);
code[pc].execute(this);
}
}
void push(ref Value value)
@@ -34,6 +37,7 @@ class VM
enum CodeType
{
Push,
PushG,
Operate,
Return,
Goto,
@@ -65,7 +69,7 @@ class PrintCode : Code
write(arg.integerValue);
break;
case ValueType.String:
write(arg.stringValue.to!string);
write(arg.stringValue);
break;
default:
//type missmatch
@@ -90,6 +94,20 @@ class Push : Code
vm.push(imm);
}
}
class PushG : Code
{
int var;
this(int var)
{
this.type = CodeType.PushG;
this.var = var;
}
override void execute(VM vm)
{
vm.push(vm.global[var]);
}
}
class Operate : Code
{
TokenType operator;
@@ -111,7 +129,16 @@ class Operate : Code
}
class Goto : Code
{
int address;
this(int addr)
{
this.type = CodeType.Goto;
address = addr;
}
override void execute(VM vm)
{
vm.pc = address - 1;
}
}
class Gosub : Code
{

View File

@@ -14,10 +14,16 @@ class Compiler
}
Code[] code;
int[wstring] global;
int globalIndex = 0;
void genCodeImm(Value value)
{
code ~= new Push(value);
}
void genCodePushGlobal(int ind)
{
code ~= new PushG(ind);
}
void genCodeOP(TokenType op)
{
code ~= new Operate(op);
@@ -39,6 +45,15 @@ class Compiler
}
break;
case NodeType.Variable:
auto var = cast(Variable)exp;
int global = this.global.get(var.name, 0);
if(global == 0)
{
//local変数をあたる
//それでもだめならOPTION STRICTならエラー
this.global[var.name] = ++globalIndex = global;
}
genCodePushGlobal(global);
break;
case NodeType.CallFunction:
{
@@ -89,6 +104,6 @@ class Compiler
stderr.writeln("Compile:NotImpl ", i.type);
}
}
return new VM(code);
return new VM(code, globalIndex + 1);
}
}

View File

@@ -8,7 +8,7 @@ int main(string[] argv)
writeln(parser.calc());
}
auto parser = new Parser("PRINT 1+1,2+3;10-5");
auto parser = new Parser("PRINT 1+1,2+3;10-5,A");
auto vm = parser.compile();
vm.run();
readln();