-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVM.cs
159 lines (115 loc) · 2.51 KB
/
VM.cs
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Simp {
public class VM {
//==================================================
public Table table;
readonly Value[] args = new Value[100];
readonly Value[] stack = new Value[100];
readonly OP[][] branches;
int argsIdx;
int stackIdx;
int argsCount;
int drop = 0;
//==================================================
public VM(Bytecode bytecode, params Dictionary<string, object>[] libs)
{
this.table = new Table (bytecode);
foreach (KeyValuePair<string, int> seek in bytecode.names)
{
table.Set (seek.Value, Value.UNDEFINED);
foreach (Dictionary<string, object> lib in libs)
{
if (lib.ContainsKey(seek.Key))
{
table.Set (seek.Value, Value.Create(lib[seek.Key]));
break;
}
}
}
branches = new OP[bytecode.branches.Count][];
int i = 0;
foreach (List<OP> branchAsList in bytecode.branches)
{
branches[i] = branchAsList.ToArray();
i++;
}
}
//==================================================
public void BeginScope()
{
table = new Table.Dynamic (table);
}
public void EndScope()
{
table = ((Table.Dynamic)table).super;
}
public Value Pop()
{
int curr = argsIdx;
argsIdx++;
argsCount--;
return args[curr];
}
public int ArgsCount()
{
return argsCount;
}
public void Drop(int i)
{
drop = i;
}
//==================================================
public Value Execute(int branch = 0)
{
Value result = Value.UNDEFINED;
OP[] ops = branches [branch];
int idx = -1;
while (true)
{
idx++;
if (idx >= ops.Length || drop > 0)
{
if (drop > 0)
{
drop--;
}
break;
}
OP op = ops[idx];
switch(op.type)
{
case OP.Type.IDENT:
result = table.Get(op.value.Int);
stack[stackIdx] = result;
stackIdx++;
break;
case OP.Type.VALUE:
result = op.value;
stack[stackIdx] = result;
stackIdx++;
break;
case OP.Type.CALL:
case OP.Type.RCALL:
argsCount = op.value.Int;
for(int i = argsCount - 1; i >= 0; i--)
{
args[i] = stack[stackIdx-1];
stackIdx--;
}
argsIdx = 1;
result = args[0].Cast<System.Func<VM, Value>>().Invoke (this);
if (op.type == OP.Type.RCALL)
{
stack[stackIdx] = result;
stackIdx++;
}
break;
}
}
return result;
}
}
}