-
Notifications
You must be signed in to change notification settings - Fork 0
/
vm.ts
238 lines (204 loc) · 6.92 KB
/
vm.ts
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import { RuntimeError } from "./errors/errors";
import { Token } from "./lexing/token";
import { Binary, Data, Literal, Operation, Zero, Copy, Unary, ConditionalCopy, Condition, OperationAction } from "./operation";
import { GeneralRegisterIndex, Register, SpecialRegister } from "./register";
export class VM {
private _stackA: number[] = [];
private _stackB: number[] = [];
private _activeStack: "A" | "B" = "A";
private _r0: number = 0;
private _r1: number = 0;
private _r2: number = 0;
private _r3: number = 0;
private _r4: number = 0;
private _r5: number = 0;
private _r6: number = 0;
private _r7: number = 0;
private _r8: number = 0;
private _r9: number = 0;
private _rc: number = 1;
private _rv: number = 1;
private _operations: Operation[];
private get stack(): number[] {
if (this._activeStack === "A") {
return this._stackA;
}
return this._stackB;
}
private set stack(value: number[]) {
if (this._activeStack === "A") {
this._stackA = value;
}
this._stackB = value;
}
private get _rs(): number {
return this.stack.length;
}
constructor(operations: Operation[]) {
// Insert no-ops so that jumps to lines work as expected
const lastLine = operations[operations.length - 1].rootCommandToken.line;
this._operations = [];
for (let i = 0; i < lastLine + 1; i++) {
const existingLine: undefined | Operation = operations.filter((o) => o.rootCommandToken.line === i)[0];
if (!existingLine) {
this._operations.push({ action: "Noop", rootCommandToken: null as any as Token, type: "Noop" });
} else {
this._operations.push(existingLine);
}
}
}
private halt(): boolean {
return this._rc <= 0 || this._rc >= this._operations.length;
}
private swapStack(): void {
if (this._activeStack === "A") {
this._activeStack = "B";
} else {
this._activeStack = "A";
}
}
private getRegisterValue(index: Register): number {
return this[`_r${index}`];
}
private setRegisterValue(index: Register, value: number) {
if (index === `s`) {
throw new RuntimeError(`Cannot set stack size register (rs)`);
}
this[`_r${index}`] = value;
}
private storeResult(value: number) {
this.setRegisterValue("v", value);
}
private resolve(data: Data): number {
if ((data as Literal).type === "Literal") {
return (data as Literal).value;
}
return this.getRegisterValue(data as Register);
}
public run() {
while (!this.halt()) {
this.step();
}
}
private set(set: Unary): void {
this.setRegisterValue("v", this.resolve(set.v1));
}
private push(): void {
this.stack.push(this._rv);
}
private pop(): void {
if (this.stack.length === 0) {
throw new RuntimeError(`Tried to pop from empty stack. ${JSON.stringify(this)}`);
};
this.storeResult(this.stack.pop() as number);
}
private copy(copy: Copy): void {
this.setRegisterValue(copy.v2, this.resolve(copy.v1));
}
private conditionalCopy(conditionalCopy: ConditionalCopy): void {
const condA = this.resolve(conditionalCopy.v3);
const condB = this.resolve(conditionalCopy.v4);
const actionMap: Record<Condition, (a: number, b: number) => boolean> = {
"EQ": (a, b) => a == b,
"GT": (a, b) => a > b,
"LT": (a, b) => a < b
}
if (actionMap[conditionalCopy.condition](condA, condB)) {
this.copy({ ...conditionalCopy, type: "BinaryArg" });
}
}
private binaryOp(v1: Data, v2: Data, action: (a: number, b: number) => number): void {
this.storeResult(action(this.resolve(v1), this.resolve(v2)));
}
private add(add: Binary): void {
this.binaryOp(add.v1, add.v2, (a, b) => a + b);
}
private sub(sub: Binary): void {
this.binaryOp(sub.v1, sub.v2, (a, b) => a - b);
}
private mul(mul: Binary): void {
this.binaryOp(mul.v1, mul.v2, (a, b) => a * b);
}
private div(div: Binary): void {
this.binaryOp(div.v1, div.v2, (a, b) => a / b);
}
private mod(mod: Binary): void {
this.binaryOp(mod.v1, mod.v2, (a, b) => a % b);
}
private write(write: Unary): void {
console.log(this.resolve(write.v1));
}
private writeStack(): void {
const output = this.stack.reverse().join(" ");
this.stack = [];
console.log(output);
}
private writeStackChars(): void {
const output = this.stack.reverse().map(n => String.fromCharCode(n)).join("");
this.stack = [];
console.log(output);
}
private writeChar(writeChar: Unary): void {
console.log(String.fromCharCode(this.resolve(writeChar.v1)));
}
private assertCoverAllActions(action: never): never {
throw new Error("Didn't expect to get here");
}
private step() {
const operation: Operation = this._operations[this._rc];
// Increment prog counter before the operation as this shows the next operation location
// Also means if user sets the value, we don't overwrite it
this._rc++;
switch (operation.action) {
case "Noop":
break;
case "Set":
this.set(operation as Unary);
break;
case "Push":
this.push();
break;
case "Pop":
this.pop();
break;
case "Copy":
this.copy(operation as Copy);
break;
case "ConditionalCopy":
this.conditionalCopy(operation as ConditionalCopy);
break;
case "Add":
this.add(operation as Binary);
break;
case "Sub":
this.sub(operation as Binary);
break;
case "Mul":
this.mul(operation as Binary);
break;
case "Div":
this.div(operation as Binary);
break;
case "Mod":
this.mod(operation as Binary);
break;
case "Write":
this.write(operation as Unary);
break;
case "WriteStack":
this.writeStack();
break;
case "WriteChar":
this.writeChar(operation as Unary);
break;
case "WriteStackChars":
this.writeStackChars();
break;
case "Swap":
this.swapStack();
break;
default:
this.assertCoverAllActions(operation.action);
}
}
}