@psdo/compiler 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ import type { Counters } from "./types.js";
2
+ export interface InstrumentationEntry {
3
+ counters?: Partial<Counters>;
4
+ event?: Record<string, unknown>;
5
+ }
6
+ export declare const INSTRUMENTATION: Record<string, InstrumentationEntry>;
@@ -0,0 +1,6 @@
1
+ export const INSTRUMENTATION = {
2
+ swap: {
3
+ counters: { swaps: 1 },
4
+ event: { kind: "swap", a: "$arg0", b: "$arg1", aLocation: "$argLoc0", bLocation: "$argLoc1" }
5
+ }
6
+ };
@@ -0,0 +1,51 @@
1
+ import type { Counters, Expr, Frame, Program, Env, FunctionDef, Value, FunctionMap, ClassMap, SessionStats, ClassDef } from "./types.js";
2
+ export declare const PRELUDE_DEFS: (ClassDef | FunctionDef)[];
3
+ type Checkpoint = {
4
+ env: Env;
5
+ functions: FunctionMap;
6
+ classes: ClassMap;
7
+ counters: Counters;
8
+ };
9
+ export declare class Interpreter {
10
+ private readonly functions;
11
+ private readonly classes;
12
+ private readonly structureIds;
13
+ private nextStructureId;
14
+ private scope;
15
+ private counters;
16
+ private frames;
17
+ private executionCount;
18
+ private line;
19
+ constructor();
20
+ define(chunk: Program): void;
21
+ exec(chunk: Program): Frame[];
22
+ evalTop(expr: Expr): {
23
+ value: Value | undefined;
24
+ frames: Frame[];
25
+ };
26
+ restore(point: Checkpoint): void;
27
+ checkpoint(): Checkpoint;
28
+ private variableRef;
29
+ private elementRef;
30
+ private resolveTarget;
31
+ private evaluateLocated;
32
+ private evaluate;
33
+ private executeStmt;
34
+ private tick;
35
+ private execute;
36
+ private bindArguments;
37
+ private runBody;
38
+ private callFunction;
39
+ private fieldRef;
40
+ private newObject;
41
+ private callMethod;
42
+ private makeFrame;
43
+ private emit;
44
+ private stableIdFor;
45
+ private deriveStructures;
46
+ variableNames(): string[];
47
+ variables(): Record<string, Value>;
48
+ stats(): SessionStats;
49
+ }
50
+ export declare function interpret(program: Program): Frame[];
51
+ export {};
@@ -0,0 +1,610 @@
1
+ import { COUNTERS_DEFAULT } from "./types.js";
2
+ import { tokenise } from "./lexer.js";
3
+ import { parseProgram } from "./ast.js";
4
+ import { PRELUDE } from "./prelude.js";
5
+ import { INSTRUMENTATION } from "./instrumentation.js";
6
+ import { RuntimeError } from "./errors.js";
7
+ import { fail, makeError } from "./messages.js";
8
+ const STACK_DEPTH_LIMIT = 128;
9
+ const EXECUTION_LIMIT = 165535;
10
+ function loadPrelude() {
11
+ const program = parseProgram(tokenise(PRELUDE));
12
+ const defs = program.filter((stmt) => stmt.kind === "Class" || stmt.kind === "Function");
13
+ return defs;
14
+ }
15
+ export const PRELUDE_DEFS = loadPrelude();
16
+ const PRELUDE_NAMES = new Set(PRELUDE_DEFS.map(stmt => stmt.name));
17
+ function applyEventTemplate(template, argValues, argLocations) {
18
+ const result = {};
19
+ for (const [key, val] of Object.entries(template)) {
20
+ if (typeof val === "string") {
21
+ const argMatch = /^\$arg(\d+)$/.exec(val);
22
+ if (argMatch) {
23
+ const idx = Number(argMatch[1]);
24
+ const argVal = argValues[idx];
25
+ if (argVal === undefined) {
26
+ throw new Error(`Instrumentation template references $arg${idx} but only ${argValues.length} argument(s) were given`);
27
+ }
28
+ result[key] = argVal;
29
+ continue;
30
+ }
31
+ const locMatch = /^\$argLoc(\d+)$/.exec(val);
32
+ if (locMatch) {
33
+ const idx = Number(locMatch[1]);
34
+ if (idx >= argLocations.length) {
35
+ throw new Error(`Instrumentation template references $argLoc${idx} but only ${argLocations.length} argument(s) were given`);
36
+ }
37
+ if (argLocations[idx] !== undefined)
38
+ result[key] = argLocations[idx];
39
+ continue;
40
+ }
41
+ }
42
+ result[key] = val;
43
+ }
44
+ return result;
45
+ }
46
+ const binaryOp = {
47
+ "+": (a, b) => a + b,
48
+ "-": (a, b) => a - b,
49
+ "*": (a, b) => a * b,
50
+ "/": (a, b) => a / b,
51
+ "%": (a, b) => a % b,
52
+ "^": (a, b) => Math.pow(a, b),
53
+ "<": (a, b) => a < b ? 1 : 0,
54
+ ">": (a, b) => a > b ? 1 : 0,
55
+ "<=": (a, b) => a <= b ? 1 : 0,
56
+ ">=": (a, b) => a >= b ? 1 : 0,
57
+ "==": (a, b) => a === b ? 1 : 0,
58
+ "!=": (a, b) => a !== b ? 1 : 0,
59
+ "or": (a, b) => (a !== 0) || (b !== 0) ? 1 : 0,
60
+ "and": (a, b) => (a !== 0) && (b !== 0) ? 1 : 0,
61
+ };
62
+ const forDir = {
63
+ "TO": (n) => n + 1,
64
+ "DOWNTO": (n) => n - 1,
65
+ };
66
+ const COMPARISON_OPS = new Set(["<", ">", "<=", ">=", "==", "!="]);
67
+ class ReturnSignal {
68
+ value;
69
+ constructor(value) {
70
+ this.value = value;
71
+ }
72
+ }
73
+ function describe(val) {
74
+ if (typeof val === "number")
75
+ return "a number";
76
+ if (Array.isArray(val))
77
+ return "an array";
78
+ return `an object (${val.cls})`;
79
+ }
80
+ function toNum(val) {
81
+ if (typeof val === "number")
82
+ return val;
83
+ fail("expectedNumber", { got: describe(val) });
84
+ }
85
+ function toArr(val) {
86
+ if (Array.isArray(val))
87
+ return val;
88
+ fail("expectedArray", { got: describe(val) });
89
+ }
90
+ function isObject(val) {
91
+ return typeof val === "object" && !Array.isArray(val);
92
+ }
93
+ // functions where the body is written here in typescript because psdo cant
94
+ // express them, still needs to be declared in prelude.psdo
95
+ const NATIVE = {
96
+ len: ([a]) => toArr(a).length,
97
+ };
98
+ function rootName(target) {
99
+ return target.root.kind === "This" ? "this" : target.root.name;
100
+ }
101
+ function eventName(target) {
102
+ let name = rootName(target);
103
+ for (const a of target.path) {
104
+ if (a.kind === "Field")
105
+ name += `.${a.name}`;
106
+ }
107
+ return name;
108
+ }
109
+ function readVar(name, scope) {
110
+ const ref = scope.refs.get(name);
111
+ if (ref)
112
+ return ref.get();
113
+ const v = scope.env.get(name);
114
+ if (v === undefined)
115
+ fail("undefinedVariable", { name });
116
+ return v;
117
+ }
118
+ function writeVar(name, value, scope) {
119
+ const ref = scope.refs.get(name);
120
+ if (ref)
121
+ ref.set(value);
122
+ else
123
+ scope.env.set(name, value);
124
+ }
125
+ function countArrayCells(env) {
126
+ function count(v) {
127
+ if (!Array.isArray(v))
128
+ return 0;
129
+ let total = v.length;
130
+ for (const el of v)
131
+ total += count(el);
132
+ return total;
133
+ }
134
+ let total = 0;
135
+ for (const v of env.values())
136
+ total += count(v);
137
+ return total;
138
+ }
139
+ export class Interpreter {
140
+ // == exists for whole session == //
141
+ functions = new Map();
142
+ classes = new Map();
143
+ structureIds = new WeakMap;
144
+ nextStructureId = 0;
145
+ scope = { env: new Map(), refs: new Map(), depth: 0 };
146
+ counters = { ...COUNTERS_DEFAULT };
147
+ // == one input == //
148
+ frames = [];
149
+ executionCount = 0;
150
+ line = 1;
151
+ constructor() {
152
+ for (const builtin of PRELUDE_DEFS) {
153
+ if (builtin.kind === "Class")
154
+ this.classes.set(builtin.name, builtin);
155
+ if (builtin.kind === "Function")
156
+ this.functions.set(builtin.name, builtin);
157
+ }
158
+ }
159
+ define(chunk) {
160
+ for (const stmt of chunk) {
161
+ if (stmt.kind === "Class") {
162
+ if (PRELUDE_NAMES.has(stmt.name)) {
163
+ throw makeError("reservedName", { name: stmt.name }).withLine(stmt.line);
164
+ }
165
+ this.classes.set(stmt.name, stmt);
166
+ }
167
+ }
168
+ for (const stmt of chunk) {
169
+ if (stmt.kind === "Function") {
170
+ if (PRELUDE_NAMES.has(stmt.name)) {
171
+ throw makeError("reservedName", { name: stmt.name }).withLine(stmt.line);
172
+ }
173
+ this.functions.set(stmt.name, stmt);
174
+ }
175
+ }
176
+ }
177
+ exec(chunk) {
178
+ this.frames = [];
179
+ this.executionCount = 0;
180
+ for (const stmt of chunk) {
181
+ if (stmt.kind === "Function" || stmt.kind === "Class")
182
+ continue;
183
+ this.execute(stmt, this.scope);
184
+ }
185
+ const endLine = chunk.at(-1)?.line ?? 1;
186
+ this.emit(endLine, { kind: 'end' }, this.scope);
187
+ return this.frames;
188
+ }
189
+ evalTop(expr) {
190
+ this.frames = [];
191
+ this.executionCount = 0;
192
+ const scope = this.scope;
193
+ this.line = 1;
194
+ try {
195
+ const value = expr.kind === "Call" ? this.callFunction(expr, scope) : this.evaluate(expr, scope);
196
+ this.emit(this.line, { kind: 'end' }, scope);
197
+ return { value, frames: this.frames };
198
+ }
199
+ catch (e) {
200
+ if (e instanceof RuntimeError && e.line === undefined)
201
+ throw e.withLine(1);
202
+ throw e;
203
+ }
204
+ }
205
+ restore(point) {
206
+ this.scope.env = point.env;
207
+ this.functions.clear();
208
+ this.classes.clear();
209
+ for (const [name, def] of point.functions)
210
+ this.functions.set(name, def);
211
+ for (const [name, def] of point.classes)
212
+ this.classes.set(name, def);
213
+ this.counters = point.counters;
214
+ }
215
+ checkpoint() {
216
+ return {
217
+ env: structuredClone(this.scope.env),
218
+ functions: new Map(this.functions),
219
+ classes: new Map(this.classes),
220
+ counters: { ...this.counters }
221
+ };
222
+ }
223
+ // ====== Target Referencing ====== //
224
+ variableRef(name, scope) {
225
+ const ref = scope.refs.get(name);
226
+ if (ref)
227
+ return ref;
228
+ const value = scope.env.get(name);
229
+ const structureId = Array.isArray(value) ? this.stableIdFor(value) : name;
230
+ return {
231
+ get: () => readVar(name, scope),
232
+ set: (v) => writeVar(name, v, scope),
233
+ location: { structureId, indices: [] }
234
+ };
235
+ }
236
+ elementRef(parent, index, scope) {
237
+ const arr = toArr(parent.get());
238
+ const idx = toNum(this.evaluate(index, scope));
239
+ const location = parent.location && {
240
+ structureId: parent.location.structureId,
241
+ indices: [...parent.location.indices, idx]
242
+ };
243
+ return {
244
+ get: () => {
245
+ const v = arr[idx];
246
+ if (v === undefined)
247
+ fail("indexOutOfBounds", { idx });
248
+ return v;
249
+ },
250
+ set: (v) => {
251
+ if (!Number.isInteger(idx) || idx < 0)
252
+ fail("indexOutOfBounds", { idx });
253
+ arr[idx] = v;
254
+ },
255
+ ...(location ? { location } : {})
256
+ };
257
+ }
258
+ resolveTarget(target, scope) {
259
+ const { root, path } = target;
260
+ let place;
261
+ if (root.kind === "This") {
262
+ const self = scope.self;
263
+ if (!self)
264
+ fail("thisOutsideClass");
265
+ place = { get: () => self, set: () => fail("cannotAssignThis") };
266
+ }
267
+ else {
268
+ place = this.variableRef(root.name, scope);
269
+ }
270
+ for (const a of path) {
271
+ switch (a.kind) {
272
+ case "Field":
273
+ place = this.fieldRef(place, a.name, scope);
274
+ break;
275
+ case "Index":
276
+ place = this.elementRef(place, a.index, scope);
277
+ break;
278
+ }
279
+ }
280
+ return place;
281
+ }
282
+ evaluateLocated(expr, scope) {
283
+ if (expr.kind === "Path") {
284
+ const { get, location } = this.resolveTarget(expr.target, scope);
285
+ return { value: get(), ...(location ? { location } : {}) };
286
+ }
287
+ return { value: this.evaluate(expr, scope) };
288
+ }
289
+ // ====== Expressions ====== //
290
+ evaluate(expr, scope) {
291
+ switch (expr.kind) {
292
+ case "Number": return expr.value;
293
+ case "Array": {
294
+ const arr = [];
295
+ expr.elements.forEach(e => arr.push(this.evaluate(e, scope)));
296
+ return arr;
297
+ }
298
+ case "Path":
299
+ return this.resolveTarget(expr.target, scope).get();
300
+ case "New":
301
+ return this.newObject(expr.name, expr.args, scope);
302
+ case "Binary": {
303
+ const leftL = this.evaluateLocated(expr.left, scope);
304
+ const left = toNum(leftL.value);
305
+ if (expr.op === "and" && left === 0)
306
+ return 0;
307
+ if (expr.op === "or" && left !== 0)
308
+ return 1;
309
+ const rightL = this.evaluateLocated(expr.right, scope);
310
+ ;
311
+ const right = toNum(rightL.value);
312
+ const result = binaryOp[expr.op](left, right);
313
+ if (COMPARISON_OPS.has(expr.op)) {
314
+ const actualEvent = (leftL.location?.indices.length ?? 0) > 0 || (rightL.location?.indices.length ?? 0) > 0;
315
+ const event = {
316
+ kind: "compare", a: left, b: right, result: result != 0,
317
+ ...(leftL.location ? { aLocation: leftL.location } : {}),
318
+ ...(rightL.location ? { bLocation: rightL.location } : {}),
319
+ };
320
+ this.emit(this.line, event, scope, actualEvent ? { comparisons: 1 } : undefined);
321
+ }
322
+ return result;
323
+ }
324
+ case "Unary": {
325
+ const v = toNum(this.evaluate(expr.operand, scope));
326
+ if (expr.op === "-")
327
+ return -1 * v;
328
+ return v === 0 ? 1 : 0;
329
+ }
330
+ case "Call": {
331
+ const result = this.callFunction(expr, scope);
332
+ if (result === undefined) {
333
+ fail("noReturnValue", { name: rootName(expr.callee) });
334
+ }
335
+ return result;
336
+ }
337
+ }
338
+ }
339
+ // ====== Statements ====== //
340
+ executeStmt(stmt, scope) {
341
+ switch (stmt.kind) {
342
+ case "Assign": {
343
+ const target = stmt.target;
344
+ const value = this.evaluate(stmt.value, scope);
345
+ const place = this.resolveTarget(target, scope);
346
+ place.set(value);
347
+ const name = eventName(target);
348
+ const event = {
349
+ kind: "assign", name, value: structuredClone(value),
350
+ ...(target.path.length > 0 && place.location ? { location: place.location } : {})
351
+ };
352
+ this.emit(stmt.line, event, scope);
353
+ return;
354
+ }
355
+ case "If": {
356
+ const taken = toNum(this.evaluate(stmt.condition, scope)) !== 0;
357
+ const event = { kind: "branch", taken };
358
+ this.emit(stmt.line, event, scope);
359
+ if (taken)
360
+ stmt.thenBranch.forEach((s) => this.execute(s, scope));
361
+ else if (stmt.elseBranch)
362
+ stmt.elseBranch.forEach((s) => this.execute(s, scope));
363
+ return;
364
+ }
365
+ case "While": {
366
+ let condition = toNum(this.evaluate(stmt.condition, scope)) !== 0;
367
+ while (condition) {
368
+ this.tick();
369
+ stmt.block.forEach(s => this.execute(s, scope));
370
+ condition = toNum(this.evaluate(stmt.condition, scope)) !== 0;
371
+ }
372
+ return;
373
+ }
374
+ case "For": {
375
+ const from = toNum(this.evaluate(stmt.from, scope));
376
+ const to = toNum(this.evaluate(stmt.to, scope));
377
+ const step = forDir[stmt.dir];
378
+ const done = (i) => stmt.dir === "TO" ? i > to : i < to;
379
+ for (let i = from; !done(i); i = step(i)) {
380
+ this.tick();
381
+ writeVar(stmt.name, i, scope);
382
+ stmt.block.forEach(s => this.execute(s, scope));
383
+ }
384
+ scope.env.delete(stmt.name);
385
+ return;
386
+ }
387
+ case "Return": {
388
+ const value = stmt.value === undefined ? undefined : this.evaluate(stmt.value, scope);
389
+ throw new ReturnSignal(value);
390
+ }
391
+ case "Call": {
392
+ this.callFunction(stmt, scope);
393
+ }
394
+ }
395
+ }
396
+ tick() {
397
+ if (++this.executionCount >= EXECUTION_LIMIT)
398
+ fail("executionLimit", { limit: EXECUTION_LIMIT });
399
+ }
400
+ execute(stmt, scope) {
401
+ const outerLine = this.line;
402
+ this.line = stmt.line;
403
+ try {
404
+ this.tick();
405
+ this.executeStmt(stmt, scope);
406
+ }
407
+ catch (e) {
408
+ if (e instanceof RuntimeError && e.line === undefined)
409
+ throw e.withLine(stmt.line);
410
+ throw e;
411
+ }
412
+ finally {
413
+ this.line = outerLine;
414
+ }
415
+ }
416
+ bindArguments(params, args, scope) {
417
+ const env = new Map();
418
+ const refs = new Map();
419
+ const snapshot = [];
420
+ const locations = [];
421
+ for (let i = 0; i < args.length; i++) {
422
+ const param = params[i];
423
+ if (param.byRef) {
424
+ const arg = args[i];
425
+ if (arg.kind !== "Path")
426
+ fail("byRefNeedsVariable");
427
+ const ref = this.resolveTarget(arg.target, scope);
428
+ refs.set(param.name, ref);
429
+ snapshot.push(ref.get());
430
+ locations.push(ref.location);
431
+ }
432
+ else {
433
+ const located = this.evaluateLocated(args[i], scope);
434
+ env.set(param.name, located.value);
435
+ snapshot.push(located.value);
436
+ locations.push(located.location);
437
+ }
438
+ }
439
+ return { env, refs, snapshot, locations };
440
+ }
441
+ runBody(block, scope, name, enforceRtrn = true) {
442
+ try {
443
+ for (const stmt of block)
444
+ this.execute(stmt, scope);
445
+ if (enforceRtrn)
446
+ fail("missingReturn", { name });
447
+ return undefined;
448
+ }
449
+ catch (error) {
450
+ if (!(error instanceof ReturnSignal))
451
+ throw error;
452
+ const event = { kind: "return", name, value: structuredClone(error.value ?? 0) };
453
+ this.emit(this.line, event, scope);
454
+ return error.value;
455
+ }
456
+ }
457
+ callFunction(call, scope) {
458
+ if (scope.depth >= STACK_DEPTH_LIMIT)
459
+ fail("stackDepth", { limit: STACK_DEPTH_LIMIT });
460
+ const { callee, args, line } = call;
461
+ if (callee.path.length > 0)
462
+ return this.callMethod(call, scope);
463
+ const name = rootName(callee);
464
+ const funct = this.functions.get(name);
465
+ if (funct === undefined)
466
+ fail("undefinedFunction", { name });
467
+ const params = funct.params;
468
+ if (params.length !== args.length)
469
+ fail("wrongArgCount", { kind: "Function", name, expected: params.length, got: args.length });
470
+ const { env, refs, snapshot, locations } = this.bindArguments(params, args, scope);
471
+ const native = NATIVE[name];
472
+ if (native)
473
+ return native(snapshot);
474
+ const funcScope = { env, refs, depth: scope.depth + 1 };
475
+ const returnValue = this.runBody(funct.block, funcScope, name);
476
+ const instrumentation = INSTRUMENTATION[name];
477
+ if (instrumentation) {
478
+ const event = instrumentation.event ? applyEventTemplate(instrumentation.event, snapshot, locations) : undefined;
479
+ if (event)
480
+ this.emit(line, event, scope, instrumentation.counters);
481
+ }
482
+ return returnValue;
483
+ }
484
+ // ====== Classes ====== //
485
+ fieldRef(parent, name, scope) {
486
+ const obj = parent.get();
487
+ if (!isObject(obj))
488
+ fail("fieldOfNonObject", { field: name, got: describe(obj) });
489
+ const cls = this.classes.get(obj.cls);
490
+ const decl = cls.fields.find((f) => f.name === name);
491
+ if (!decl) {
492
+ if (cls.methods.some((m) => m.fn.name === name))
493
+ fail("fieldIsMethod", { cls: cls.name, name });
494
+ fail("noSuchField", { cls: cls.name, name });
495
+ }
496
+ if (decl.access === "private" && scope.self?.cls !== obj.cls)
497
+ fail("privateField", { cls: cls.name, name });
498
+ const value = obj.fields[name];
499
+ return {
500
+ get: () => {
501
+ const v = obj.fields[name];
502
+ if (v === undefined)
503
+ fail("unassignedField", { name });
504
+ return v;
505
+ },
506
+ set: (v) => { obj.fields[name] = v; },
507
+ ...(Array.isArray(value) ? { location: { structureId: this.stableIdFor(value), indices: [] } } : {})
508
+ };
509
+ }
510
+ newObject(name, args, scope) {
511
+ const cls = this.classes.get(name);
512
+ if (!cls)
513
+ fail("unknownClass", { name });
514
+ if (args.length !== (cls.ctor?.params.length ?? 0))
515
+ fail("wrongArgCount", { kind: "Constructor", name, expected: cls.ctor?.params.length ?? 0, got: args.length });
516
+ const obj = { kind: "object", cls: name, fields: {} };
517
+ if (!cls.ctor)
518
+ return obj;
519
+ if (scope.depth >= STACK_DEPTH_LIMIT)
520
+ fail("stackDepth", { limit: STACK_DEPTH_LIMIT });
521
+ const { env, refs } = this.bindArguments(cls.ctor.params, args, scope);
522
+ const ctorScope = { env, refs, depth: scope.depth + 1, self: obj };
523
+ this.runBody(cls.ctor.block, ctorScope, name, false);
524
+ return obj;
525
+ }
526
+ callMethod(call, scope) {
527
+ const callee = { ...call.callee, path: call.callee.path.slice() };
528
+ const target = callee.path.splice(-1, 1)[0];
529
+ if (target.kind === "Index")
530
+ fail("notCallable");
531
+ const name = target.name;
532
+ const obj = this.resolveTarget(callee, scope).get();
533
+ if (!isObject(obj))
534
+ fail("methodOnNonObject", { name, got: describe(obj) });
535
+ const cls = this.classes.get(obj.cls);
536
+ const method = cls.methods.find((m) => m.fn.name === name);
537
+ if (!method) {
538
+ if (cls.fields.some((f) => f.name === name))
539
+ fail("methodIsField", { cls: cls.name, name });
540
+ fail("noSuchMethod", { cls: cls.name, name });
541
+ }
542
+ if (method.access === "private" && scope.self?.cls !== obj.cls)
543
+ fail("privateMethod", { cls: cls.name, name });
544
+ const { params, block } = method.fn;
545
+ if (params.length !== call.args.length)
546
+ fail("wrongArgCount", { kind: "Method", name, expected: params.length, got: call.args.length });
547
+ const { env, refs } = this.bindArguments(params, call.args, scope);
548
+ const mthdScope = { env, refs, depth: scope.depth + 1, self: obj };
549
+ return this.runBody(block, mthdScope, name);
550
+ }
551
+ // ====== Helpers ====== //
552
+ makeFrame(line, event, scope, countersDelta) {
553
+ const counters = {
554
+ comparisons: this.counters.comparisons + (countersDelta?.comparisons ?? 0),
555
+ swaps: this.counters.swaps + (countersDelta?.swaps ?? 0),
556
+ visits: this.counters.visits + (countersDelta?.visits ?? 0),
557
+ };
558
+ const memory = {
559
+ stackDepth: scope.depth,
560
+ arrayCells: countArrayCells(scope.env),
561
+ };
562
+ return {
563
+ line, event,
564
+ structures: this.deriveStructures(scope.env),
565
+ env: Object.fromEntries(structuredClone(scope.env)),
566
+ counters,
567
+ memory,
568
+ timestampMs: performance.now(),
569
+ };
570
+ }
571
+ emit(line, event, scope, countersDelta) {
572
+ const frame = this.makeFrame(line, event, scope, countersDelta);
573
+ this.counters = { ...frame.counters };
574
+ this.frames.push(frame);
575
+ }
576
+ stableIdFor(arr) {
577
+ let id = this.structureIds.get(arr);
578
+ if (id === undefined) {
579
+ id = `struct${this.nextStructureId++}`;
580
+ this.structureIds.set(arr, id);
581
+ }
582
+ return id;
583
+ }
584
+ deriveStructures(env) {
585
+ const structures = [];
586
+ for (const [name, value] of env.entries()) {
587
+ if (Array.isArray(value))
588
+ structures.push({ kind: "array", id: this.stableIdFor(value), name, values: structuredClone(value) });
589
+ }
590
+ return structures;
591
+ }
592
+ // ====== Accessors ====== //
593
+ variableNames() {
594
+ return [...this.scope.env.keys()];
595
+ }
596
+ variables() {
597
+ return Object.fromEntries(structuredClone(this.scope.env));
598
+ }
599
+ stats() {
600
+ return {
601
+ ...this.counters,
602
+ arrayCells: countArrayCells(this.scope.env)
603
+ };
604
+ }
605
+ }
606
+ export function interpret(program) {
607
+ const interp = new Interpreter();
608
+ interp.define(program);
609
+ return interp.exec(program);
610
+ }