-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathruntime.ts
281 lines (256 loc) Β· 8.16 KB
/
runtime.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import * as assert from 'assert';
//#if _MATBAS_BUILD == 'debug'
import { Span } from '@opentelemetry/api';
//#else
//#unset _DEBUG_TRACE_RUNTIME
//#endif
//#if _MATBAS_BUILD == 'debug'
import { startSpan } from './debug';
//#endif
//#if _DEBUG_TRACE_RUNTIME
import { startTraceExec, traceExec } from './debug';
//#endif
import { BaseException, NameError, NotImplementedError } from './exceptions';
import { Exit } from './exit';
import { RuntimeFault } from './faults';
import { Host } from './host';
import { Stack } from './stack';
import { Traceback } from './traceback';
import { Value, nil, Nil } from './value';
import { falsey } from './value/truthiness';
import { Byte } from './bytecode/byte';
import { Chunk } from './bytecode/chunk';
import { OpCode } from './bytecode/opcodes';
import { Short, bytesToShort } from './bytecode/short';
import * as op from './operations';
export type Globals = Record<string, Value>;
export class Runtime {
public stack: Stack<Value>;
public pc: number = -1;
public chunk: Chunk = new Chunk();
public globals: Globals = {};
constructor(private host: Host) {
this.stack = new Stack();
}
public reset(): void {
this.stack = new Stack();
this.chunk = new Chunk();
this.pc = 0;
}
public interpret(chunk: Chunk): Value | null {
this.chunk = chunk;
this.pc = 0;
return this.run();
}
// TODO: Using templates can help decrease boilerplate while increasing the
// amount of inlining. But if I'm going down that road, I might want to
// consider porting this to C++ anyway.
private readByte(): Byte {
const byte = this.chunk.code[this.pc];
this.pc++;
return byte;
}
private readCode(): OpCode {
return this.readByte();
}
private readConstant(): Value {
return this.chunk.constants[this.readByte()];
}
private readShort(): Short {
return bytesToShort([this.readByte(), this.readByte()]);
}
private readString(): string {
const value = this.readConstant();
assert.equal(typeof value, 'string', 'Value is string');
return value as string;
}
private createTraceback(): Traceback | null {
return new Traceback(
null,
this.chunk.filename,
this.chunk.lines[this.pc - 1],
);
}
private run(): Value | null {
//#if _MATBAS_BUILD == 'debug'
return startSpan('Runtime#run', (_: Span): Value | null => {
//#endif
let a: Value | null = null;
let b: Value | null = null;
//#if _DEBUG_TRACE_RUNTIME
startTraceExec();
//#endif
try {
while (true) {
//#if _DEBUG_TRACE_RUNTIME
traceExec(this);
//#endif
const instruction = this.readCode();
switch (instruction) {
case OpCode.Constant:
this.stack.push(this.readConstant());
break;
case OpCode.Nil:
this.stack.push(nil);
break;
case OpCode.True:
this.stack.push(true);
break;
case OpCode.False:
this.stack.push(false);
break;
case OpCode.Pop:
this.stack.pop();
break;
case OpCode.GetGlobal:
a = this.readString();
b = this.globals[a];
if (typeof b === 'undefined') {
throw new NameError(`Variable ${a} is undefined`);
}
this.stack.push(b);
break;
case OpCode.DefineGlobal:
a = this.readString();
// NOTE: Pops afterwards for garbage collection reasons
b = this.stack.peek();
if (typeof this.globals[a] !== 'undefined') {
throw new NameError(`Cannot define variable ${a} twice`);
}
this.globals[a] = b as Value;
this.stack.pop();
break;
case OpCode.SetGlobal:
a = this.readString();
// NOTE: Pops afterwards for garbage collection reasons
b = this.stack.peek();
if (typeof this.globals[a] === 'undefined') {
throw new NameError(`Cannot assign to undefined variable ${a}`);
}
this.globals[a] = b as Value;
// TODO: This is missing from my clox implementation. That's a
// bug, right?
this.stack.pop();
break;
case OpCode.Eq:
b = this.stack.pop();
a = this.stack.pop();
this.stack.push(op.eq(a, b));
break;
case OpCode.Gt:
b = this.stack.pop();
a = this.stack.pop();
this.stack.push(op.gt(a, b));
break;
case OpCode.Ge:
b = this.stack.pop();
a = this.stack.pop();
this.stack.push(op.ge(a, b));
break;
case OpCode.Lt:
b = this.stack.pop();
a = this.stack.pop();
this.stack.push(op.lt(a, b));
break;
case OpCode.Le:
b = this.stack.pop();
a = this.stack.pop();
this.stack.push(op.le(a, b));
break;
case OpCode.Ne:
b = this.stack.pop();
a = this.stack.pop();
this.stack.push(op.ne(a, b));
break;
case OpCode.Not:
a = this.stack.pop();
this.stack.push(op.not(a));
break;
case OpCode.Add:
b = this.stack.pop();
a = this.stack.pop();
this.stack.push(op.add(a, b));
break;
case OpCode.Sub:
b = this.stack.pop();
a = this.stack.pop();
this.stack.push(op.sub(a, b));
break;
case OpCode.Mul:
b = this.stack.pop();
a = this.stack.pop();
this.stack.push(op.mul(a, b));
break;
case OpCode.Div:
b = this.stack.pop();
a = this.stack.pop();
this.stack.push(op.div(a, b));
break;
case OpCode.Neg:
a = this.stack.pop();
this.stack.push(op.neg(a));
break;
case OpCode.Print:
this.host.writeLine(this.stack.pop());
break;
case OpCode.Exit:
a = this.stack.pop();
if (typeof a === 'number') {
b = Math.floor(a);
} else if (a instanceof Nil) {
b = 0;
} else if (a) {
b = 1;
} else {
b = 0;
}
this.host.exit(b);
return null;
case OpCode.Jump:
// Note, readShort increments the pc. If we didn't assign before,
// we would need to add extra to skip over those bytes!
a = this.readShort();
this.pc += a;
break;
case OpCode.JumpIfFalse:
a = this.readShort();
b = this.stack.peek();
if (falsey(b!)) {
this.pc += a;
}
break;
case OpCode.Loop:
this.notImplemented('Loop');
break;
case OpCode.Return:
a = this.stack.pop();
// TODO: Clean up the current frame, and only return if we're
// done with the main program.
return a;
default:
assert.ok(
this.pc < this.chunk.code.length,
'Program counter out of bounds',
);
this.notImplemented(`Unknown opcode: ${instruction}`);
}
}
} catch (err) {
let exc = err;
if (err instanceof Exit) {
throw err;
}
if (!(err instanceof BaseException)) {
exc = RuntimeFault.fromError(err);
}
exc.traceback = this.createTraceback();
throw exc;
}
//#if _MATBAS_BUILD == 'debug'
});
//#endif
}
private notImplemented(message: string): Value {
throw new NotImplementedError(message);
}
}