forked from Nivanchenko/OneScriptJS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOneScriptVirtualMachine.ts
More file actions
241 lines (211 loc) · 8.08 KB
/
Copy pathOneScriptVirtualMachine.ts
File metadata and controls
241 lines (211 loc) · 8.08 KB
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
239
240
241
import { Op } from './OneScriptOperations.js';
import { Instruction } from './OneScriptCompiler.js';
export class OSMachine {
private stack: any[];
private variables: Map<string, any>;
private labels: Map<any, number>;
private ip: number;
private breakTargets: string[]; // Стек целей для break
private continueTargets: string[]; // Стек целей для continue
constructor() {
this.stack = [];
this.variables = new Map<string, any>(); // имя → значение
this.labels = new Map<any, number>(); // имя метки → индекс в программе
this.ip = 0; // instruction pointer (для управления переходами)
this.breakTargets = []; // Стек целей для break
this.continueTargets = []; // Стек целей для continue
}
resolveLabels(instructions: Instruction[]) {
this.labels.clear();
for (let i = 0; i < instructions.length; i++) {
const instr = instructions[i];
if (instr && instr.code === Op.LABEL) {
this.labels.set(instr.arg, i);
}
}
}
run(instructions: Instruction[]) {
this.resolveLabels(instructions);
this.ip = 0;
this.breakTargets = [];
this.continueTargets = [];
while (this.ip < instructions.length) {
const instr = instructions[this.ip];
if (!instr) {
throw new Error(`Instruction at index ${this.ip} is undefined`);
}
this.ip++;
switch (instr.code) {
case Op.PUSH:
this.stack.push(instr.arg);
break;
case Op.LOAD:
const value = this.variables.get(instr.arg);
if (value === undefined) throw new ReferenceError(`Переменная не определена: ${instr.arg}`);
this.stack.push(value);
break;
case Op.STORE:
const val = this.stack.pop();
this.variables.set(instr.arg, val);
break;
case Op.ADD:
const addb = this.stack.pop();
const adda = this.stack.pop();
if (adda === undefined || addb === undefined) {
throw new Error('Stack underflow in ADD operation');
}
this.stack.push(adda + addb);
break;
case Op.SUB:
const subb = this.stack.pop();
const suba = this.stack.pop();
if (suba === undefined || subb === undefined) {
throw new Error('Stack underflow in SUB operation');
}
this.stack.push(suba - subb);
break;
case Op.MUL:
const multb = this.stack.pop();
const multa = this.stack.pop();
if (multa === undefined || multb === undefined) {
throw new Error('Stack underflow in MUL operation');
}
this.stack.push(multa * multb);
break;
case Op.DIV:
const divb = this.stack.pop();
const diva = this.stack.pop();
if (diva === undefined || divb === undefined) {
throw new Error('Stack underflow in DIV operation');
}
this.stack.push(diva / divb);
break;
case Op.DECLARE:
this.variables.set(instr.arg, null); // инициализируем
break;
case Op.EQ:
const eqb = this.stack.pop();
const eqa = this.stack.pop();
if (eqa === undefined || eqb === undefined) {
throw new Error('Stack underflow in EQ operation');
}
this.stack.push(eqa === eqb);
break;
case Op.NE:
const neb = this.stack.pop();
const nea = this.stack.pop();
if (nea === undefined || neb === undefined) {
throw new Error('Stack underflow in NE operation');
}
this.stack.push(nea !== neb);
break;
case Op.LT:
const ltb = this.stack.pop();
const lta = this.stack.pop();
if (lta === undefined || ltb === undefined) {
throw new Error('Stack underflow in LT operation');
}
this.stack.push(lta < ltb);
break;
case Op.LE:
const leb = this.stack.pop();
const lea = this.stack.pop();
if (lea === undefined || leb === undefined) {
throw new Error('Stack underflow in LE operation');
}
this.stack.push(lea <= leb);
break;
case Op.GT:
const gtb = this.stack.pop();
const gta = this.stack.pop();
if (gta === undefined || gtb === undefined) {
throw new Error('Stack underflow in GT operation');
}
this.stack.push(gta > gtb);
break;
case Op.GE:
const geb = this.stack.pop();
const gea = this.stack.pop();
if (gea === undefined || geb === undefined) {
throw new Error('Stack underflow in GE operation');
}
this.stack.push(gea >= geb);
break;
case Op.AND:
const rightAnd = this.stack.pop();
const leftAnd = this.stack.pop();
if (leftAnd === undefined || rightAnd === undefined) {
throw new Error('Stack underflow in AND operation');
}
this.stack.push(leftAnd && rightAnd);
break;
case Op.OR:
const rightOr = this.stack.pop();
const leftOr = this.stack.pop();
if (leftOr === undefined || rightOr === undefined) {
throw new Error('Stack underflow in OR operation');
}
this.stack.push(leftOr || rightOr);
break;
case Op.JUMP_IF_FALSE:
const jmpvalue = this.stack.pop();
if (!jmpvalue) {
const target = this.labels.get(instr.arg);
if (target === undefined) throw new Error(`Метка не найдена: ${instr.arg}`);
this.ip = target + 1; // +1, потому что в конце цикла ip++
}
break;
case Op.JUMP:
const target2 = this.labels.get(instr.arg);
if (target2 === undefined) throw new Error(`Метка не найдена: ${instr.arg}`);
this.ip = target2 + 1;
break;
case Op.LABEL:
// ничего не делаем — метки уже разрешены
break;
case Op.NOT:
const NOTvalue = this.stack.pop();
if (NOTvalue === undefined) {
throw new Error('Stack underflow in NOT operation');
}
this.stack.push(!NOTvalue);
break;
case Op.NEG:
const NEGnum = this.stack.pop();
if (NEGnum === undefined) {
throw new Error('Stack underflow in NEG operation');
}
if (typeof NEGnum !== 'number') {
throw new Error(`Cannot apply unary minus to non-number: ${typeof NEGnum}`);
}
this.stack.push(-NEGnum);
break;
case Op.BREAK:
// Переход к следующей за циклом метке
if (this.breakTargets.length > 0) {
const target = this.labels.get(this.breakTargets[this.breakTargets.length - 1]);
if (target === undefined) throw new Error(`Метка для break не найдена: ${this.breakTargets[this.breakTargets.length - 1]}`);
this.ip = target + 1;
}
break;
case Op.CONTINUE:
// Переход к следующей итерации цикла
if (this.continueTargets.length > 0) {
const target = this.labels.get(this.continueTargets[this.continueTargets.length - 1]);
if (target === undefined) throw new Error(`Метка для continue не найдена: ${this.continueTargets[this.continueTargets.length - 1]}`);
this.ip = target + 1;
}
break;
default:
throw new Error(`Неизвестная инструкция: ${instr.code}`);
}
}
}
dumpVariables(): Record<string, any> {
const result: Record<string, any> = {};
for (const [key, value] of this.variables) {
result[key] = value;
}
return result;
}
}