Repository navigation
Expand file tree
/
Copy pathinterpreter.ts
More file actions
2715 lines (2520 loc) · 100 KB
/
Copy pathinterpreter.ts
File metadata and controls
2715 lines (2520 loc) · 100 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
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* AST interpreter that executes programs directly without compilation.
* Implements environment-based variable scoping and object-oriented programming features.
*/
import type {
Program,
Statement,
Expression,
FunctionDeclaration,
ClassDeclaration,
MethodDeclaration,
Constructor,
} from './ast';
import { lvalueName } from './ast';
/**
* Property names that must never be reachable through a program's `obj[key]`
* or `obj.key` access. Reading `"x"["constructor"]["constructor"]` hands back
* the host `Function` constructor, and writing `arr["__proto__"]` /
* `obj.prototype` reaches a built-in prototype — either one lets interpreted
* code (which may arrive from an untrusted share/embed link) break out of the
* AST walker and run arbitrary JavaScript on the page's origin. Student
* programs have no legitimate reason to touch these keys, so we reject them
* rather than try to make them safe.
*/
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
/** Throws if `key` is one of the keys that can escape the interpreter. */
function assertSafeKey(key: unknown): void {
if (FORBIDDEN_KEYS.has(String(key))) {
throw new Error(`Access to property '${String(key)}' is not allowed`);
}
}
export class Environment {
public values: Record<string, any> = {};
public types: Record<string, string> = {}; // Track declared types
public declarationOrigins: Record<string, number> = {}; // Track declaration token positions
public parent?: Environment;
/**
* Creates a new instance.
*/
constructor(parent?: Environment) {
this.parent = parent;
}
define(name: string, value: any, type?: string, declarationOrigin?: number) {
this.values[name] = value;
if (type) {
this.types[name] = type;
if (declarationOrigin !== undefined) {
this.declarationOrigins[name] = declarationOrigin;
}
}
}
assign(name: string, value: any) {
if (name in this.values) {
this.values[name] = value;
return;
}
if (this.parent) {
this.parent.assign(name, value);
return;
}
throw new Error(`Undefined variable '${name}'`);
}
get(name: string): any {
if (name in this.values) return this.values[name];
if (this.parent) return this.parent.get(name);
throw new Error(`Undefined variable '${name}'`);
}
getType(name: string): string | undefined {
if (name in this.types) return this.types[name];
if (this.parent) return this.parent.getType(name);
return undefined;
}
getAllVariables(): Record<string, any> {
const vars: Record<string, any> = { ...this.values };
if (this.parent) {
return { ...this.parent.getAllVariables(), ...vars };
}
return vars;
}
}
class ReturnException extends Error {
value: any;
/**
* Creates a new instance.
*/
constructor(value: any) {
super('Return');
this.value = value;
}
}
// Loop control-flow signals, thrown by `break`/`continue` and caught by the
// nearest enclosing loop (or, for break, an enclosing switch).
class BreakException extends Error {
constructor() {
super('Break');
}
}
class ContinueException extends Error {
constructor() {
super('Continue');
}
}
/**
* Marks a declared-but-unassigned variable/field (`int x;`, an unassigned
* Praxis placeholder hole). Reading one is a runtime error — Praxly has no
* static definite-assignment check, so this is enforced dynamically at first
* use instead. Distinct from `Undefined variable`/`Undefined field` (which
* mean "this name doesn't exist at all").
*/
class UninitializedValue {
toString(): string {
return '<uninitialized>';
}
}
const UNINITIALIZED = new UninitializedValue();
// Thrown when code reads a variable/field holding UNINITIALIZED. Kept distinct
// from a plain lookup-failure Error so callers that tolerate "not found" (e.g.
// the bare-identifier-might-be-a-field fallback) don't silently swallow a real
// "you used this before assigning it" error.
class UninitializedAccessError extends Error {}
export class InputPrompt extends Error {
prompt: string;
/**
* Creates a new instance.
*/
constructor(prompt: string = '') {
super('InputPrompt');
this.prompt = prompt;
}
}
/** One entry of the debugger's call stack: a function/method invocation and the
* variables local to it. The bottom entry is always the global scope. */
export interface StackFrame {
name: string;
variables: Record<string, any>;
}
/** What the step-through generator yields to the debugger after each step. */
export interface DebugStepEvent {
nodeId: string;
nodeType: string;
loc: { start: number; end: number } | null;
/** Flat "visible right now" view: globals shadowed by the current frame's locals. */
variables: Record<string, any>;
/** Global scope first, innermost call last. */
callStack: StackFrame[];
prompt?: string;
}
/** A user-written callable the debugger can step into. */
interface ResolvedCallable {
name: string;
decl: FunctionDeclaration | MethodDeclaration;
thisInstance?: JavaInstance;
}
// Call names the identifier-call ladder in `evaluate` dispatches as built-ins
// BEFORE looking up user functions. The debugger's resolveUserCallable must skip
// them so debug-mode dispatch matches run mode. Keep in sync with that ladder.
const BUILTIN_CALL_NAMES = new Set([
'Scanner',
'Random',
'super',
'input',
'INPUT',
'len',
'LENGTH',
'range',
'APPEND',
'INSERT',
'REMOVE',
'int',
'INT',
'float',
'FLOAT',
'str',
'String',
'STRING',
'bool',
'BOOL',
'boolean',
'parseInt',
'parseFloat',
'Number',
'Boolean',
'random',
'RANDOM',
'randomInt',
'RANDOMINT',
'randomSeed',
'RANDOMSEED',
'setSeed',
'ArrayList',
'List',
'Array',
]);
// Numeric built-ins that `evaluate` resolves after user functions but before
// sibling methods — a sibling method with one of these names is never reached.
const NUMERIC_BUILTIN_NAMES = new Set(['min', 'max', 'abs', 'sqrt', 'log']);
// OOP Classes
class JavaClass {
name: string;
methods: Map<string, MethodDeclaration> = new Map();
ctorDecl: Constructor | undefined;
fields: Map<string, any> = new Map();
superClass?: JavaClass;
/**
* Creates a new instance.
*/
constructor(name: string, superClass?: JavaClass) {
this.name = name;
this.superClass = superClass;
}
addMethod(method: MethodDeclaration) {
this.methods.set(method.name, method);
}
setConstructor(ctor: Constructor) {
this.ctorDecl = ctor;
}
getMethod(name: string): MethodDeclaration | undefined {
if (this.methods.has(name)) return this.methods.get(name);
if (this.superClass) return this.superClass.getMethod(name);
return undefined;
}
}
class JavaInstance {
klass: JavaClass;
fields: Map<string, any> = new Map();
/**
* Creates a new instance.
*/
constructor(klass: JavaClass) {
this.klass = klass;
}
getField(name: string): any {
if (this.fields.has(name)) return this.checkInitializedField(name, this.fields.get(name));
// Check class fields, walking up the superclass chain for inherited fields
let klass: JavaClass | undefined = this.klass;
while (klass) {
if (klass.fields.has(name)) return this.checkInitializedField(name, klass.fields.get(name));
klass = klass.superClass;
}
throw new Error(`Undefined field '${name}'`);
}
private checkInitializedField(name: string, value: any): any {
if (value === UNINITIALIZED) {
throw new UninitializedAccessError(`Uninitialized field '${name}'`);
}
return value;
}
setField(name: string, value: any) {
this.fields.set(name, value);
}
callMethod(methodName: string, args: any[], interpreter: Interpreter, env: Environment): any {
const method = this.klass.getMethod(methodName);
if (!method) {
// Default Object methods when the class doesn't override them (AP CSA).
if (methodName === 'toString' && args.length === 0) return `${this.klass.name} instance`;
if (methodName === 'equals' && args.length === 1) return this === args[0];
throw new Error(`Undefined method '${methodName}'`);
}
const methodEnv = new Environment(env);
methodEnv.define('this', this);
methodEnv.define('self', this); // Python compatibility
// Bind parameters (no default values; argument count must match exactly)
interpreter.bindParams(method.params, args, methodEnv);
try {
interpreter.executeBlock(method.body.body, methodEnv);
} catch (e) {
if (e instanceof ReturnException) return e.value;
throw e;
}
return null;
}
}
// Java Scanner over System.in. Reads whitespace-delimited tokens (next/nextInt/…)
// with a small buffer, and whole lines (nextLine) — both drawn from the shared
// input queue. The interpreter dispatches its methods (see the Scanner branch in
// evaluate) where it can reuse readInputLine().
class JavaScanner {
tokenBuffer: string[] = [];
}
// Java Random: each instance owns its PRNG state (seedable via setSeed); nextInt/
// nextDouble/nextBoolean route through it. Modeled on JavaScanner — the interpreter
// dispatches its methods (see the Random branch in evaluate). An unseeded instance
// uses Math.random; a setSeed(s) instance uses the same Mulberry32 as the procedural
// randomSeed(s), so a seeded Java Random matches a seeded randomInt with the same seed.
class JavaRandom {
rng: (() => number) | null = null;
next(): number {
return this.rng ? this.rng() : Math.random();
}
}
export class Interpreter {
private globalEnv = new Environment();
private output: string[] = [];
private outputLineBuffer: string = '';
private classes: Map<string, JavaClass> = new Map();
private currentEnv: Environment = this.globalEnv;
private sourceCode: string = ''; // Store source code for line number extraction
private inputQueue: string[] = []; // Queue of pending inputs
private isDebugging: boolean = false; // Flag to track if we're in debug mode
private inputHandler?: (prompt: string) => string; // Callback for collecting input in normal mode
private seededRandom: (() => number) | null = null;
// --- Debug-mode state (only used on the stepThroughWithState path) ---
/** Active user-function invocations, innermost last. */
private debugCallStack: Array<{ name: string; env: Environment }> = [];
/** Stack of per-expression caches of stepped-through call results, keyed by
* CallExpression node id (see resolveUserCalls). `evaluate` consults the top
* cache so a call whose body was already stepped through isn't run twice. */
private debugCallResults: Array<Map<string, any>> = [];
setInputQueue(inputs: string[]) {
this.inputQueue = [...inputs];
}
addInput(input: string) {
// console.log('addInput called with:', input, 'Queue length before:', this.inputQueue.length);
this.inputQueue.push(input);
// console.log('Queue length after:', this.inputQueue.length);
}
hasInput(): boolean {
return this.inputQueue.length > 0;
}
getNextInput(): string | null {
// console.log('getNextInput called, queue length:', this.inputQueue.length);
const result = this.inputQueue.length > 0 ? this.inputQueue.shift()! : null;
// console.log('getNextInput returning:', result);
return result;
}
// Reads and echoes one line of input, or (when the queue is empty) prompts via
// the input handler / throws InputPrompt for the UI. Shared by input() and Scanner.
private readInputLine(prompt: string): string {
const nextInput = this.getNextInput();
if (nextInput !== null) {
this.flushOutputBuffer();
this.output.push(`> ${nextInput}`);
return nextInput;
}
if (this.inputHandler && !this.isDebugging) return this.inputHandler(prompt);
throw new InputPrompt(prompt);
}
setDebugging(isDebugging: boolean) {
this.isDebugging = isDebugging;
}
setInputHandler(handler: (prompt: string) => string) {
this.inputHandler = handler;
}
// Mulberry32 PRNG provides deterministic pseudo-random values for randomSeed().
private createSeededRandom(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t ^= t + Math.imul(t ^ (t >>> 7), 61 | t);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
private normalizeSeed(seedValue: any): number {
const seed = Number(seedValue);
if (!Number.isFinite(seed)) return 0;
return Math.trunc(seed) >>> 0;
}
private getRandomValue(): number {
return this.seededRandom ? this.seededRandom() : Math.random();
}
private isIntegerType(typeName?: string): boolean {
if (!typeName) return false;
const baseType = typeName.replace(/\[\]/g, '');
return ['int', 'byte', 'short', 'long'].includes(baseType);
}
private isFloatType(typeName?: string): boolean {
if (!typeName) return false;
const baseType = typeName.replace(/\[\]/g, '');
return baseType === 'float' || baseType === 'double';
}
private inferExpressionType(expr: Expression, env: Environment): string | undefined {
switch (expr.type) {
case 'Identifier':
return env.getType((expr as any).name);
case 'Literal': {
const literal = expr as any;
if (typeof literal.value === 'number') {
return String(literal.raw ?? '').includes('.') ? 'double' : 'int';
}
if (typeof literal.value === 'boolean') return 'boolean';
if (typeof literal.value === 'string')
return literal.value.length === 1 ? 'char' : 'String';
return undefined;
}
case 'MemberExpression':
if ((expr as any).property?.name === 'length') return 'int';
return undefined;
case 'IndexExpression': {
const objExpr = (expr as any).object;
const objType = this.inferExpressionType(objExpr, env);
if (objType?.endsWith('[]')) return objType.slice(0, -2);
return undefined;
}
case 'CallExpression': {
const call = expr as any;
if (call.callee?.type === 'Identifier') {
const callee = String(call.callee.name || '').toLowerCase();
if (callee === 'int') return 'int';
if (callee === 'float') return 'float';
if (callee === 'bool' || callee === 'boolean') return 'boolean';
if (callee === 'str' || callee === 'string') return 'String';
// `random()` / `RANDOM()` yield a float; CSP `RANDOM(a, b)` (2 args)
// yields an inclusive integer.
if (callee === 'random') return call.arguments?.length === 2 ? 'int' : 'double';
if (callee === 'randomint') return 'int';
}
if (call.callee?.type === 'MemberExpression') {
const method = call.callee.property?.name;
if (method === 'length') return 'int';
if (method === 'substring' || method === 'toLowerCase' || method === 'toUpperCase')
return 'String';
if (method === 'charAt') return 'char';
}
return undefined;
}
case 'UnaryExpression': {
const op = (expr as any).operator;
if (op === 'not' || op === '!') return 'boolean';
return this.inferExpressionType((expr as any).argument, env);
}
case 'BinaryExpression': {
const binary = expr as any;
const operator = binary.operator;
if (['==', '!=', '>', '<', '>=', '<=', 'and', 'or', 'in', 'not in'].includes(operator)) {
return 'boolean';
}
const leftType = this.inferExpressionType(binary.left, env);
const rightType = this.inferExpressionType(binary.right, env);
if (operator === '/') {
if (this.isIntegerType(leftType) && this.isIntegerType(rightType)) return 'int';
if (this.isFloatType(leftType) || this.isFloatType(rightType)) return 'double';
return undefined;
}
if (this.isFloatType(leftType) || this.isFloatType(rightType)) return 'double';
if (this.isIntegerType(leftType) && this.isIntegerType(rightType)) return 'int';
if (operator === '+' && (leftType === 'String' || rightType === 'String')) return 'String';
return undefined;
}
default:
return undefined;
}
}
private appendOutputText(text: string, appendLineFeed: boolean) {
// A `\n` inside the text is a line break: everything before it completes the
// current output line. This keeps the output array one-entry-per-line even
// when a printed value (or a terminator baked into it) contains a newline —
// essential for faithful cross-language print/DISPLAY round-tripping.
const combined = this.outputLineBuffer + text;
const parts = combined.split('\n');
for (let i = 0; i < parts.length - 1; i++) this.output.push(parts[i]);
this.outputLineBuffer = parts[parts.length - 1];
if (appendLineFeed) {
this.output.push(this.outputLineBuffer);
this.outputLineBuffer = '';
}
}
private flushOutputBuffer() {
if (this.outputLineBuffer.length > 0) {
this.output.push(this.outputLineBuffer);
this.outputLineBuffer = '';
}
}
/**
* Interprets and executes the provided program.
*/
interpret(program: Program, sourceCode: string = ''): string[] {
this.sourceCode = sourceCode;
this.output = [];
this.outputLineBuffer = '';
this.globalEnv = new Environment();
this.classes = new Map();
this.isDebugging = false; // Not in debug mode for normal execution
this.seededRandom = null;
this.debugCallStack = [];
this.debugCallResults = [];
try {
// First pass: register all classes and procedures
for (const stmt of program.body) {
if (stmt.type === 'ClassDeclaration') {
this.registerClass(stmt);
} else if (stmt.type === 'FunctionDeclaration') {
this.globalEnv.define(stmt.name, stmt);
}
}
// Second pass: execute all non-class and non-function statements
const statements = program.body.filter(
(stmt) => stmt.type !== 'ClassDeclaration' && stmt.type !== 'FunctionDeclaration'
);
this.executeBlock(statements, this.globalEnv);
// Third pass: if there's a Main class, execute its main() method
if (this.classes.has('Main')) {
const mainClass = this.classes.get('Main')!;
const mainMethod = mainClass.getMethod('main');
if (mainMethod) {
const mainInstance = new JavaInstance(mainClass);
// Java's `main(String[] args)` receives an empty argument array.
const mainArgs = mainMethod.params.length > 0 ? [[]] : [];
mainInstance.callMethod('main', mainArgs, this, this.globalEnv);
}
}
} catch (e: any) {
// InputPrompt in normal run mode should propagate to UI for console handling
if (e instanceof InputPrompt) {
this.flushOutputBuffer();
throw e;
}
const message = e.message || String(e);
this.flushOutputBuffer();
// If the error message already starts with "runtime error occurred", don't add prefix
if (message.startsWith('runtime error occurred')) {
this.output.push(message);
} else {
this.output.push(`Runtime Error: ${message}`);
}
}
this.flushOutputBuffer();
return this.output;
}
*stepThroughWithState(
program: Program,
sourceCode: string = ''
): Generator<DebugStepEvent, string[], void> {
this.sourceCode = sourceCode;
this.output = [];
this.outputLineBuffer = '';
this.globalEnv = new Environment();
this.currentEnv = this.globalEnv;
this.isDebugging = true; // We're in debug mode for step-through execution
this.seededRandom = null;
this.debugCallStack = [];
this.debugCallResults = [];
try {
// First pass: register all classes and procedures
for (const stmt of program.body) {
if (stmt.type === 'ClassDeclaration') {
this.registerClass(stmt);
} else if (stmt.type === 'FunctionDeclaration') {
this.globalEnv.define(stmt.name, stmt);
}
}
// Second pass: execute all non-class and non-function statements
const statements = program.body.filter(
(stmt) => stmt.type !== 'ClassDeclaration' && stmt.type !== 'FunctionDeclaration'
);
yield* this.executeBlockGeneratorWithState(statements, this.globalEnv);
// Third pass: if there's a Main class, execute its main() method. Mirror
// the normal-run path (callMethod): bind `this` so bare calls to sibling
// static methods resolve, and give main its own stack frame.
if (this.classes.has('Main')) {
const mainClass = this.classes.get('Main')!;
const mainMethod = mainClass.getMethod('main');
if (mainMethod) {
const mainInstance = new JavaInstance(mainClass);
const mainEnv = new Environment(this.globalEnv);
mainEnv.define('this', mainInstance);
mainEnv.define('self', mainInstance);
// Java's `main(String[] args)` receives an empty argument array.
if (mainMethod.params.length > 0) {
this.bindParams(mainMethod.params, [[]], mainEnv);
}
this.debugCallStack.push({ name: 'main', env: mainEnv });
try {
yield* this.executeBlockGeneratorWithState(mainMethod.body.body, mainEnv);
} catch (e) {
if (!(e instanceof ReturnException)) throw e; // `return` from main just ends it
} finally {
this.debugCallStack.pop();
}
}
}
} catch (e: any) {
// InputPrompt should propagate to debugger, not be caught here
if (e instanceof InputPrompt) {
this.flushOutputBuffer();
throw e;
}
const message = e.message || String(e);
this.flushOutputBuffer();
// If the error message already starts with "runtime error occurred", don't add prefix
if (message.startsWith('runtime error occurred')) {
this.output.push(message);
} else {
this.output.push(`Runtime Error: ${message}`);
}
}
this.flushOutputBuffer();
return this.output;
}
/** Snapshot of the call stack for the debugger: global scope first, then one
* frame per active user-function call, innermost last. */
getStackFrames(): StackFrame[] {
const frames: StackFrame[] = [
{ name: 'global', variables: this.snapshotFrameVariables(this.globalEnv) },
];
for (const frame of this.debugCallStack) {
frames.push({ name: frame.name, variables: this.snapshotFrameVariables(frame.env) });
}
return frames;
}
/** An environment's own variables, minus runtime bookkeeping (function/class
* declarations, the bound `this`/`self`) that would clutter a variable table. */
private snapshotFrameVariables(env: Environment): Record<string, any> {
const variables: Record<string, any> = {};
for (const [name, value] of Object.entries(env.values)) {
if (name === 'this' || name === 'self') continue;
if (value && typeof value === 'object' && value.type === 'FunctionDeclaration') continue;
if (value instanceof JavaClass) continue;
variables[name] = value;
}
return variables;
}
/** Builds the event yielded to the debugger for one step at `stmt`. */
private debugEvent(stmt: Statement, overrides: Partial<DebugStepEvent> = {}): DebugStepEvent {
const callStack = this.getStackFrames();
const globals = callStack[0].variables;
const locals = callStack[callStack.length - 1].variables;
return {
nodeId: stmt.id,
nodeType: stmt.type,
loc: stmt.loc || null,
variables: callStack.length > 1 ? { ...globals, ...locals } : globals,
callStack,
...overrides,
};
}
private *executeBlockGeneratorWithState(
statements: Statement[],
env: Environment
): Generator<DebugStepEvent, void, void> {
const MAX_ITERATIONS = 10000; // Safety limit to prevent truly infinite loops
for (const stmt of statements) {
this.currentEnv = env;
switch (stmt.type) {
case 'If': {
// Announce the `if` line, then evaluate the condition (stepping into
// any user function calls it contains) and walk the taken branch.
yield this.debugEvent(stmt);
const condition = yield* this.evaluateForDebug(stmt.condition, env, stmt, false);
if (condition) {
yield* this.executeBlockGeneratorWithState(stmt.thenBranch.body, env);
} else if (stmt.elseBranch) {
yield* this.executeBlockGeneratorWithState(stmt.elseBranch.body, env);
}
break;
}
case 'While': {
// The infinite-loop heuristic compares condition variables across the
// first iteration; a condition that calls functions can change without
// any variable changing (and re-evaluating it here would repeat the
// call's side effects), so it only applies to call-free conditions.
const heuristicApplies = !this.expressionContainsCall(stmt.condition);
let isFirstIteration = true;
let iterationCount = 0;
while (true) {
iterationCount++;
if (iterationCount > MAX_ITERATIONS) throw this.infiniteLoopError(stmt.loc);
// Announce the `while` line for each condition check.
yield this.debugEvent(stmt);
const condition = yield* this.evaluateForDebug(stmt.condition, env, stmt, false);
if (!condition) break;
let conditionVars: Set<string> | null = null;
let oldValues: Record<string, any> | null = null;
if (isFirstIteration && heuristicApplies) {
conditionVars = this.extractVariablesFromExpression(stmt.condition);
oldValues = {};
for (const varName of conditionVars) {
try {
oldValues[varName] = env.get(varName);
} catch {
// Variable doesn't exist yet
}
}
}
const signal = yield* this.runIterationGenerator(stmt.body.body, env);
if (signal === 'break') break;
if (isFirstIteration) {
isFirstIteration = false;
// Run the heuristic only when the body ran to completion (a
// continue iteration is inconclusive).
if (signal === 'normal' && conditionVars && oldValues && conditionVars.size > 0) {
const conditionStillTrue = this.evaluate(stmt.condition, env);
const varsChanged = this.hasVariablesChanged(conditionVars, oldValues, env);
if (
conditionStillTrue &&
!varsChanged &&
!this.blockModifiesVariables(stmt.body.body, conditionVars, env)
) {
throw this.infiniteLoopError(stmt.loc);
}
}
}
}
break;
}
case 'For': {
// C-style for loop; any clause may be absent (`for (;;)`).
if (stmt.init) this.execute(stmt.init, env);
let iterationCount = 0;
while (true) {
iterationCount++;
if (iterationCount > MAX_ITERATIONS) throw this.infiniteLoopError(stmt.loc);
yield this.debugEvent(stmt);
if (stmt.condition) {
const condition = yield* this.evaluateForDebug(stmt.condition, env, stmt, false);
if (!condition) break;
}
const signal = yield* this.runIterationGenerator(stmt.body.body, env);
if (signal === 'break') break;
// `continue` still runs the update clause (C semantics).
if (stmt.update) this.execute(stmt.update, env);
}
break;
}
case 'ForEach': {
const iterable = yield* this.evaluateForDebug(stmt.iterable, env, stmt);
if (!Array.isArray(iterable) && typeof iterable !== 'string') {
throw new Error('For-each loop requires array or string');
}
for (const item of iterable) {
env.define(stmt.variable, item);
yield this.debugEvent(stmt);
if ((yield* this.runIterationGenerator(stmt.body.body, env)) === 'break') break;
}
break;
}
case 'DoWhile': {
let iterationCount = 0;
while (true) {
iterationCount++;
if (iterationCount > MAX_ITERATIONS) throw this.infiniteLoopError(stmt.loc);
yield this.debugEvent(stmt);
if ((yield* this.runIterationGenerator(stmt.body.body, env)) === 'break') break;
const condition = yield* this.evaluateForDebug(stmt.condition, env, stmt, false);
if (!condition) break;
}
break;
}
case 'RepeatUntil': {
// Post-condition loop: body runs first, stops when condition becomes TRUE.
let iterationCount = 0;
while (true) {
iterationCount++;
if (iterationCount > MAX_ITERATIONS) throw this.infiniteLoopError(stmt.loc);
yield this.debugEvent(stmt);
if ((yield* this.runIterationGenerator(stmt.body.body, env)) === 'break') break;
const condition = yield* this.evaluateForDebug(stmt.condition, env, stmt, false);
if (condition) break;
}
break;
}
case 'Return': {
const value = yield* this.evaluateForDebug(stmt.value, env, stmt);
// Show the `return` line while the function's locals are still alive;
// the next step lands back at the call site with this frame gone.
yield this.debugEvent(stmt);
throw new ReturnException(value);
}
case 'Break':
yield this.debugEvent(stmt);
throw new BreakException();
case 'Continue':
yield this.debugEvent(stmt);
throw new ContinueException();
case 'BlankLine':
break; // no runtime effect — not worth a debugger step
default: {
// Step into any user function calls in the statement's expressions
// first; their results are cached so executing the statement below
// doesn't run them a second time.
const cache = new Map<string, any>();
this.debugCallResults.push(cache);
try {
for (const expr of this.statementExpressions(stmt)) {
yield* this.resolveUserCalls(expr, env, stmt, cache, true);
}
// Execute, pausing (and later retrying) when console input is needed.
while (true) {
try {
this.execute(stmt, env);
break;
} catch (e) {
if (!(e instanceof InputPrompt)) throw e;
yield this.debugEvent(stmt, { nodeType: 'InputPrompt', prompt: e.prompt });
}
}
} finally {
this.debugCallResults.pop();
}
yield this.debugEvent(stmt);
}
}
}
}
/** Runs one loop-body iteration in debug mode, translating break/continue
* signals into a return code (the generator twin of runIteration). */
private *runIterationGenerator(
body: Statement[],
env: Environment
): Generator<DebugStepEvent, 'normal' | 'continue' | 'break', void> {
try {
yield* this.executeBlockGeneratorWithState(body, env);
return 'normal';
} catch (e) {
if (e instanceof ContinueException) return 'continue';
if (e instanceof BreakException) return 'break';
throw e;
}
}
/** The expressions a statement evaluates directly — the places a user function
* call the debugger should step into can appear. */
private statementExpressions(stmt: Statement): Expression[] {
switch (stmt.type) {
case 'Print':
return stmt.expressions;
case 'Assignment':
// Value first, then the target (matching execute's evaluation order —
// the target only holds expressions for member/index assignments).
return [stmt.value, stmt.target as Expression];
case 'ExpressionStatement':
return [stmt.expression];
case 'Switch':
return [(stmt as any).discriminant];
default:
return [];
}
}
/**
* Evaluates an expression during debugging: first steps through any user
* function calls inside it (caching their results so the final evaluation
* doesn't re-run them), then evaluates the whole expression, pausing and
* retrying when it needs console input. `announceCallSites` yields an extra
* step at `stmt` before entering each call — control-flow statements that
* already announced their own line pass false.
*/
private *evaluateForDebug(
expr: Expression | undefined,
env: Environment,
stmt: Statement,
announceCallSites = true
): Generator<DebugStepEvent, any, void> {
if (!expr) return null;
const cache = new Map<string, any>();
this.debugCallResults.push(cache);
try {
yield* this.resolveUserCalls(expr, env, stmt, cache, announceCallSites);
return yield* this.evaluateWithInputRetry(expr, env, stmt);
} finally {
this.debugCallResults.pop();
}
}
/** Evaluates during debugging, yielding an input-prompt step and retrying
* whenever the expression asks for console input that isn't queued yet. */
private *evaluateWithInputRetry(
expr: Expression,
env: Environment,
stmt: Statement
): Generator<DebugStepEvent, any, void> {
while (true) {
try {
return this.evaluate(expr, env);
} catch (e) {
if (!(e instanceof InputPrompt)) throw e;
yield this.debugEvent(stmt, { nodeType: 'InputPrompt', prompt: e.prompt });
}
}
}
/**
* Walks an expression in evaluation order and steps through every user-written
* function/method call in it, caching each call's result by node id so the
* later "real" evaluation (which consults the cache via debugCallResults)
* reuses the results instead of running the calls again.
*/
private *resolveUserCalls(
expr: any,
env: Environment,
stmt: Statement,
cache: Map<string, any>,
announceCallSites: boolean
): Generator<DebugStepEvent, void, void> {
if (!expr || typeof expr !== 'object') return;
switch (expr.type) {
case 'CallExpression': {
// Arguments evaluate first, so calls inside them are stepped first.
for (const arg of expr.arguments ?? []) {
yield* this.resolveUserCalls(arg, env, stmt, cache, announceCallSites);
}
const target = this.resolveUserCallable(expr, env);
if (!target) return; // built-in or unresolvable — evaluate runs it normally
if (announceCallSites) yield this.debugEvent(stmt);
const args: any[] = [];
for (const arg of expr.arguments ?? []) {
args.push(yield* this.evaluateWithInputRetry(arg, env, stmt));
}
cache.set(expr.id, yield* this.stepIntoCall(target, args, env));
return;
}
case 'ConditionalExpression': {
// Mirror evaluate's laziness: only the taken branch runs.
yield* this.resolveUserCalls(expr.test, env, stmt, cache, announceCallSites);
const test = yield* this.evaluateWithInputRetry(expr.test, env, stmt);
const branch = test ? expr.consequent : expr.alternate;
yield* this.resolveUserCalls(branch, env, stmt, cache, announceCallSites);
return;
}
case 'Assignment': // expression-position assignment (e.g. a for-update `x = f(y)`)
case 'CompoundAssignment':
yield* this.resolveUserCalls(expr.value ?? expr.right, env, stmt, cache, announceCallSites);
return;
case 'BinaryExpression': // `and`/`or` are eager in evaluate, so both sides always run
yield* this.resolveUserCalls(expr.left, env, stmt, cache, announceCallSites);
yield* this.resolveUserCalls(expr.right, env, stmt, cache, announceCallSites);