-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjlearner.js
3193 lines (2910 loc) · 90.3 KB
/
jlearner.js
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
function assert(b) { if (!b) throw new Error("Assertion failure"); }
function isDigit(c) { return '0' <= c && c <= '9'; }
function isAlpha(c) { return 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '_'; }
function has(object, propertyName) { return Object.prototype.hasOwnProperty.call(object, propertyName); }
keywordsList = [
'abstract', 'assert',
'boolean', 'break', 'byte',
'case', 'catch', 'char', 'class', 'const', 'continue',
'default', 'do', 'double',
'else', 'enum', 'extends',
'false', 'final', 'finally', 'float', 'for',
'goto',
'if', 'implements', 'import', 'instanceof', 'int', 'interface',
'long',
'native', 'new', 'null',
'package', 'private', 'protected', 'public',
'return', 'short', 'static', 'strictfp', 'super', 'switch', 'synchronized',
'this', 'throw', 'throws', 'transient', 'true', 'try',
'void', 'volatile', 'while'
];
keywords = {};
for (let keyword of keywordsList)
keywords[keyword] = true;
operatorsList = [
'(', ')', '{', '}', '[', ']', ';', ',', '.', '...', '@', '::',
'=', '>', '<', '!', '-', '?', ':', '->',
'==', '>=', '<=', '!=', '&&', '||', '++', '--',
'+', '-', '*', '/', '&', '|', '^', '%', '<<', '>>', '>>>',
'+=', '-=', '*=', '/=', '&=', '|=', '^=', '%=', '<<=', '>>=', '>>>='
]
operators = {};
operatorPrefixes = {};
for (let operator of operatorsList) {
operators[operator] = true;
for (let i = 1; i < operator.length; i++)
operatorPrefixes[operator.substring(0, i)] = true;
}
class Scanner {
constructor(doc, text) {
this.doc = doc;
this.text = text;
this.pos = -1;
this.startOfLine = 0;
this.isOnNewLine = true;
this.eat();
}
eat() {
this.pos++;
this.c = (this.pos == this.text.length ? "<EOF>" : this.text.charAt(this.pos));
}
getIndentation() {
return this.text.slice(this.startOfLine, this.tokenStart);
}
nextToken() {
eatWhite:
for (;;) {
switch (this.c) {
case ' ':
case '\t':
this.eat();
break;
case '\n':
case '\r':
this.eat();
this.startOfLine = this.pos;
this.isOnNewLine = true;
break;
case '/':
let commentStart = this.pos;
if (this.pos + 1 < this.text.length) {
switch (this.text.charAt(this.pos + 1)) {
case '/':
this.eat();
this.eat();
while (this.c != '<EOF>' && this.c != '\n' && this.c != '\r')
this.eat();
continue eatWhite;
case '*':
this.eat();
this.eat();
for (;;) {
if (this.c == '<EOF>')
throw new LocError({doc: this.doc, start: commentStart, end: this.pos}, "Missing terminator for multiline comment");
else if (this.c == '*' && this.pos + 1 < this.text.length && this.text.charAt(this.pos + 1) == '/') {
this.eat();
this.eat();
continue eatWhite;
} else
this.eat();
}
default:
break eatWhite;
}
} else
break eatWhite;
default:
break eatWhite;
}
}
this.tokenStart = this.pos;
this.tokenIsOnNewLine = this.isOnNewLine;
this.isOnNewLine = false;
if (isDigit(this.c)) {
this.eat();
while (isDigit(this.c))
this.eat();
this.value = this.text.substring(this.tokenStart, this.pos);
return "NUMBER";
}
if (isAlpha(this.c)) {
let c0 = this.c;
this.eat();
while (isAlpha(this.c) || isDigit(this.c))
this.eat();
this.value = this.text.substring(this.tokenStart, this.pos);
if (has(keywords, this.value))
return this.value;
return 'A' <= c0 && c0 <= 'Z' ? "TYPE_IDENT" : "IDENT";
}
if (this.c == '<EOF>')
return 'EOF';
let newPos = this.pos + 1;
let longestOperatorFound = null;
for (;;) {
let operatorCandidate = this.text.substring(this.tokenStart, newPos);
if (has(operators, operatorCandidate))
longestOperatorFound = operatorCandidate;
if (has(operatorPrefixes, operatorCandidate) && newPos < this.text.length)
newPos++;
else
break;
}
if (longestOperatorFound === null)
throw new LocError({doc: this.doc, start: this.tokenStart, end: this.tokenStart + 1}, "Bad character");
this.pos += longestOperatorFound.length - 1;
this.eat();
return longestOperatorFound;
}
}
class LocalBinding {
constructor(declaration, value) {
this.declaration = declaration;
this.value = value;
}
setValue(value) {
return this.value = value;
}
getNameHTML() {
return this.declaration.type.resolve().toHTML() + " " + this.declaration.name;
}
}
class OperandBinding {
constructor(expression, value) {
this.expression = expression;
this.value = value;
}
getNameHTML() {
return "(operand)";
}
}
class Scope {
constructor(outerScope) {
this.outerScope = outerScope;
this.bindings = {};
}
tryLookup(x) {
if (has(this.bindings, x))
return this.bindings[x];
if (this.outerScope != null)
return this.outerScope.tryLookup(x);
return null;
}
lookup(loc, x) {
let result = this.tryLookup(x);
if (result == null)
throw new ExecutionError(loc, "No such variable in scope: " + x);
return result;
}
*allBindings() {
if (this.outerScope != null)
yield* this.outerScope.allBindings();
for (let x in this.bindings)
yield this.bindings[x];
}
}
class StackFrame {
constructor(title, env) {
this.title = title;
this.env = env;
this.operands = [];
}
*allBindings() {
yield* this.env.allBindings();
for (let operand of this.operands)
yield operand;
}
}
class ASTNode {
constructor(loc, instrLoc) {
this.loc = loc;
this.instrLoc = instrLoc;
}
async breakpoint() {
await checkBreakpoint(this);
}
executionError(msg) {
throw new ExecutionError(this.instrLoc, msg);
}
}
class Expression extends ASTNode {
constructor(loc, instrLoc) {
super(loc, instrLoc);
}
check_(env) {
this.type = this.check(env);
return this.type;
}
checkAgainst(env, targetType, targetTypeExplanation) {
let t = this.check_(env);
if (targetType instanceof ReferenceType && t == nullType)
return;
if (!targetType.equals(t))
this.executionError("Expression has type " + t + ", but an expression of type " + targetType + (targetTypeExplanation ? " (" + targetTypeExplanation + ")" : "") + " was expected");
}
async evaluateBinding(env) {
this.executionError("This expression cannot appear on the left-hand side of an assignment");
}
push(value) {
push(new OperandBinding(this, value));
}
}
class IntLiteral extends Expression {
constructor(loc, value, silent) {
super(loc, loc);
this.value = value;
this.silent = silent;
}
check(env) {
return intType;
}
async evaluate(env) {
if (this.silent !== true)
await this.breakpoint();
this.push(+this.value);
}
}
class BooleanLiteral extends Expression {
constructor(loc, value, silent) {
super(loc, loc);
this.value = value;
this.silent = silent;
}
check(env) {
return booleanType;
}
async evaluate(env) {
if (this.silent !== true)
await this.breakpoint();
this.push(this.value);
}
}
class NullLiteral extends Expression {
constructor(loc) {
super(loc, loc);
}
check(env) {
return nullType;
}
async evaluate(env) {
await this.breakpoint();
this.push(null);
}
}
class UnaryOperatorExpression extends Expression {
constructor(loc, instrLoc, operator, operand) {
super(loc, instrLoc);
this.operator = operator;
this.operand = operand;
}
check(env) {
switch (this.operator) {
case '!':
this.operand.checkAgainst(env, booleanType);
return booleanType;
default:
this.executionError("Operator not supported");
}
}
eval(v) {
switch (this.operator) {
case '!': return !v;
default: this.executionError("Operator '" + this.operator + "' not supported.");
}
}
async evaluate(env) {
await this.operand.evaluate(env);
await this.breakpoint();
let [v] = pop(1);
this.push(this.eval(v));
}
}
class BinaryOperatorExpression extends Expression {
constructor(loc, instrLoc, leftOperand, operator, rightOperand) {
super(loc, instrLoc);
this.leftOperand = leftOperand;
this.operator = operator;
this.rightOperand = rightOperand;
}
check(env) {
switch (this.operator) {
case '+':
case '-':
case '*':
case '/':
case '%':
case '>>':
case '>>>':
case '<<':
case '&':
case '|':
case '^':
this.leftOperand.checkAgainst(env, intType);
this.rightOperand.checkAgainst(env, intType);
return intType;
case '<':
case '<=':
case '>':
case '>=':
this.leftOperand.checkAgainst(env, intType);
this.rightOperand.checkAgainst(env, intType);
return booleanType;
case '&&':
case '||':
this.leftOperand.checkAgainst(env, booleanType);
this.rightOperand.checkAgainst(env, booleanType);
return booleanType;
case '==':
case '!=':
let lt = this.leftOperand.check_(env);
let rt = this.rightOperand.check_(env);
if (!(lt instanceof ReferenceType && rt instanceof ReferenceType))
if (lt != rt)
this.executionError("Cannot compare a " + lt + " and a " + rt);
if (this.leftOperand instanceof NewExpression)
this.executionError("An expression of the form 'new ... == ...' will always evaluate to 'false' because it compares the objects' identity, not their contents. To compare the objects' contents, compare their fields one by one.");
if (this.leftOperand instanceof AbstractNewArrayExpression)
this.executionError("An expression of the form 'new ... == ...' will always evaluate to 'false' because it compares the arrays' identity, not their contents. To compare the arrays' contents, compare their elements one by one.");
if (this.rightOperand instanceof NewExpression)
this.executionError("An expression of the form '... == new ...' will always evaluate to 'false' because it compares the objects' identity, not their contents. To compare the objects' contents, compare their fields one by one.");
if (this.rightOperand instanceof AbstractNewArrayExpression)
this.executionError("An expression of the form '... == new ...' will always evaluate to 'false' because it compares the arrays' identity, not their contents. To compare the arrays' contents, compare their elements one by one.");
return booleanType;
default:
this.executionError("Operator not supported");
}
}
eval(v1, v2) {
switch (this.operator) {
case '+': return (v1 + v2)|0;
case '-': return (v1 - v2)|0;
case '*': return (v1 * v2)|0;
case '/': return (v1 / v2)|0;
case '%': return (v1 % v2)|0;
case '&': return v1 & v2;
case '|': return v1 | v2;
case '^': return v1 ^ v2;
case '>>': return v1 >> v2;
case '>>>': return v1 >>> v2;
case '<<': return v1 << v2;
case '==': return v1 == v2;
case '!=': return v1 != v2;
case '<': return v1 < v2;
case '<=': return v1 <= v2;
case '>': return v1 > v2;
case '>=': return v1 >= v2;
default: this.executionError("Operator '" + this.operator + "' not supported.");
}
}
async evaluate(env) {
await this.leftOperand.evaluate(env);
if (this.operator == '&&' || this.operator == '||') {
await this.breakpoint();
let [b] = pop(1);
if (b == (this.operator == '&&'))
await this.rightOperand.evaluate(env);
else
this.push(b);
} else {
await this.rightOperand.evaluate(env);
await this.breakpoint();
let [v1, v2] = pop(2);
this.push(this.eval(v1, v2));
}
}
}
class VariableExpression extends Expression {
constructor(loc, name) {
super(loc, loc);
this.name = name;
}
check(env) {
return env.lookup(this.loc, this.name).declaration.type.type;
}
async evaluateBinding(env) {
return () => env.lookup(this.loc, this.name);
}
async evaluate(env) {
await this.breakpoint();
this.push(env.lookup(this.loc, this.name).value);
}
}
class AssignmentExpression extends Expression {
constructor(loc, instrLoc, lhs, op, rhs) {
super(loc, instrLoc);
this.lhs = lhs;
this.op = op;
this.rhs = rhs;
}
check(env) {
if (this.op == '=') {
let t = this.lhs.check_(env);
let explanation;
if (this.lhs instanceof VariableExpression)
explanation = `the declared type of variable '${this.lhs.name}'`;
else if (this.lhs instanceof SelectExpression)
explanation = `the declared type of field '${this.lhs.selector}'`;
else if (this.lhs instanceof SubscriptExpression)
explanation = "the array's element type";
this.rhs.checkAgainst(env, t, explanation);
return t;
} else {
this.lhs.checkAgainst(env, intType);
this.rhs.checkAgainst(env, intType);
return intType;
}
}
evaluateOperator(lhs, rhs) {
switch (this.op) {
case '=': return rhs;
case '+=': return (lhs + rhs)|0;
case '-=': return (lhs - rhs)|0;
case '*=': return (lhs * rhs)|0;
case '/=': return (lhs / rhs)|0;
case '%=': return (lhs % rhs)|0;
case '&=': return lhs & rhs;
case '|=': return lhs | rhs;
case '^=': return lhs ^ rhs;
case '>>=': return lhs >> rhs;
case '>>>=': return lhs >>> rhs;
case '<<=': return lhs << rhs;
default:
this.executionError("Operator not supported");
}
}
async evaluate(env) {
let bindingThunk = await this.lhs.evaluateBinding(env);
if (this.op != '=')
this.push(bindingThunk(peek).value);
await this.rhs.evaluate(env);
await this.breakpoint();
let [rhs] = pop(1);
let [lhsValue] = this.op == '=' ? [undefined] : pop(1);
let lhs = bindingThunk(pop);
let result = this.evaluateOperator(lhsValue, rhs);
this.push(lhs.setValue(result));
}
}
class IncrementExpression extends Expression {
constructor(loc, instrLoc, operand, isDecrement, isPostfix) {
super(loc, instrLoc);
this.operand = operand;
this.isDecrement = isDecrement;
this.isPostfix = isPostfix;
}
check(env) {
this.operand.checkAgainst(env, intType);
return intType;
}
async evaluate(env) {
let bindingThunk = await this.operand.evaluateBinding(env);
await this.breakpoint();
let lhs = bindingThunk(pop);
let oldValue = lhs.value;
if (this.isDecrement)
lhs.value = (lhs.value - 1)|0;
else
lhs.value = (lhs.value + 1)|0;
this.push(this.isPostfix ? oldValue : lhs.value);
}
}
let objectsCount = 0;
let objectsShown = [];
function collectGarbage() {
for (let o of objectsShown)
o.marked = false;
for (let stackFrame of callStack)
for (let binding of stackFrame.allBindings())
if (binding.value instanceof JavaObject)
binding.value.mark();
let newObjectsShown = [];
for (let o of objectsShown) {
if (o.marked)
newObjectsShown.push(o);
else
o.hide();
}
objectsShown = newObjectsShown;
}
function computeNextObjectY() {
let svg = document.getElementById('arrows-svg');
let svgRect = svg.getClientRects()[0];
let nextObjectY = 0;
for (let o of objectsShown) {
let rect = o.domNode.getClientRects()[0];
nextObjectY = Math.max(nextObjectY, rect.bottom - svgRect.top + 15);
}
return nextObjectY;
}
function createHeapObjectDOMNode(object) {
let heap = document.getElementById('heap');
let node = document.createElement('table');
heap.appendChild(node);
node.className = 'object-table';
node.style.left = "0px";
node.style.top = computeNextObjectY() + "px";
node.onmousedown = event0 => {
event0.preventDefault();
let left0 = node.offsetLeft;
let top0 = node.offsetTop;
let moveListener = event => {
event.preventDefault();
node.style.left = (left0 + event.x - event0.x) + "px";
node.style.top = (top0 + event.y - event0.y) + "px";
updateArrows();
};
let upListener = event => {
document.removeEventListener('mousemove', moveListener);
document.removeEventListener('mouseup', upListener);
};
document.addEventListener('mousemove', moveListener);
document.addEventListener('mouseup', upListener);
};
objectsShown.push(object);
node.className = 'object-table';
let titleRow = document.createElement('tr');
node.appendChild(titleRow);
let titleCell = document.createElement('td');
titleRow.appendChild(titleCell);
titleCell.colSpan = 2;
titleCell.className = 'object-title-td';
titleCell.innerText = object.toString();
updateHeapObjectDOMNode(node, object.fields);
return node;
}
function updateHeapObjectDOMNode(node, fields) {
while (node.lastChild != node.firstChild)
node.removeChild(node.lastChild);
for (let field in fields) {
let fieldRow = document.createElement('tr');
node.appendChild(fieldRow);
let nameCell = document.createElement('td');
fieldRow.appendChild(nameCell);
nameCell.className = 'field-name';
nameCell.innerText = field;
let valueCell = document.createElement('td');
fieldRow.appendChild(valueCell);
valueCell.className = 'field-value';
valueCell.innerText = fields[field].value;
fields[field].valueCell = valueCell;
}
}
function updateFieldArrows() {
for (let o of objectsShown)
o.updateFieldArrows();
}
async function updateAbstractFields() {
for (let o of objectsShown)
await o.updateAbstractFields();
}
async function setObjectsViewMode(abstract) {
for (let o of objectsShown)
o.setViewMode(abstract);
if (abstract)
await updateAbstractFields();
}
class FieldBinding {
constructor(value) {
this.value = value;
this.arrow = null;
}
setValue(value) {
if (this.arrow != null) {
this.arrow.parentNode.removeChild(this.arrow);
this.arrow = null;
}
this.value = value;
if (value instanceof JavaObject && !isInAbstractViewMode()) {
this.arrow = createArrow(this.valueCell, value.domNode);
this.valueCell.innerText = "()";
this.valueCell.style.color = "white";
} else {
this.valueCell.innerText = value == null ? "null" : value;
this.valueCell.style.color = "black";
}
return value;
}
updateArrow() {
this.setValue(this.value);
}
}
class JavaObject {
constructor(type, fields) {
this.id = ++objectsCount;
this.type = type;
this.fields = fields;
this.domNode = createHeapObjectDOMNode(this);
}
toString() {
return this.type.toString() + " (id=" + this.id + ")";
}
mark() {
if (!this.marked) {
this.marked = true;
for (let field in this.fields) {
let value = this.fields[field].value;
if (value instanceof JavaObject)
value.mark();
}
}
}
hide() {
this.domNode.parentNode.removeChild(this.domNode);
for (let field in this.fields) // Remove arrows
this.fields[field].setValue(null);
}
updateFieldArrows() {
for (let field in this.fields)
this.fields[field].updateArrow();
}
setViewMode(abstract) {
}
updateAbstractFields() {}
}
function initialClassFieldBindings(class_) {
let fields = {};
for (let field in class_.fields)
fields[field] = new FieldBinding(class_.fields[field].type.resolve().defaultValue());
return fields;
}
class JavaClassObject extends JavaObject {
constructor(class_) {
super(class_.type, initialClassFieldBindings(class_));
this.class_ = class_;
this.abstractViewMode = false;
this.abstractFields = {};
for (const [methodName, method] of Object.entries(this.class_.methods)) {
if (method.parameterDeclarations.length == 0 && method.name.startsWith('get'))
this.abstractFields[method.name + '()'] = new FieldBinding(null);
}
if (isInAbstractViewMode())
this.setViewMode(true);
}
setViewMode(abstract) {
this.abstractViewMode = abstract;
updateHeapObjectDOMNode(this.domNode, abstract ? this.abstractFields : this.fields);
}
async updateAbstractFields() {
for (const [methodName, method] of Object.entries(this.class_.methods)) {
if (method.parameterDeclarations.length == 0 && method.name.startsWith('get')) {
await method.call(undefined, [], this);
const result = pop(1);
this.abstractFields[method.name + '()'].setValue(result);
}
}
}
}
function initialArrayFieldBindings(initialContents) {
let fields = {};
for (let i = 0; i < initialContents.length; i++)
fields[i] = new FieldBinding(initialContents[i]);
return fields;
}
class JavaArrayObject extends JavaObject {
constructor(elementType, initialContents) {
super(new ArrayType(elementType), initialArrayFieldBindings(initialContents));
this.length = initialContents.length;
}
}
class NewExpression extends Expression {
constructor(loc, instrLoc, className, args) {
super(loc, instrLoc);
this.className = className;
this.arguments = args;
}
check(env) {
if (!has(classes, this.className))
this.executionError("No such class: " + this.className);
let class_ = classes[this.className];
let parameterDeclarations = [];
if (class_.ctor) {
parameterDeclarations = class_.ctor.parameterDeclarations;
}
if (parameterDeclarations.length != this.arguments.length)
this.executionError("Incorrect number of constructor arguments");
for (let i = 0; i < this.arguments.length; i++)
this.arguments[i].checkAgainst(env, parameterDeclarations[i].type.type, `the declared type of parameter '${parameterDeclarations[i].name}'`);
return class_.type;
}
async evaluate(env) {
if (!has(classes, this.className))
this.executionError("No such class: " + this.className);
let class_ = classes[this.className];
let parameterDeclarations = [];
if (class_.ctor) {
parameterDeclarations = class_.ctor.parameterDeclarations;
}
if (parameterDeclarations.length != this.arguments.length)
this.executionError("Incorrect number of constructor arguments");
for (let e of this.arguments)
await e.evaluate(env);
await this.breakpoint();
let args = pop(this.arguments.length);
let newObject = new JavaClassObject(class_);
if (class_.ctor) {
await class_.ctor.call(this, args, newObject);
pop(1);
}
this.push(newObject);
}
}
class AbstractNewArrayExpression extends Expression {
constructor(loc, instrLoc) {
super(loc, instrLoc);
}
}
class NewArrayExpression extends AbstractNewArrayExpression {
constructor(loc, instrLoc, elementType, lengthExpr) {
super(loc, instrLoc);
this.elementType = elementType;
this.lengthExpr = lengthExpr;
}
check(env) {
this.elementType.resolve();
this.lengthExpr.checkAgainst(env, intType);
return new ArrayType(this.elementType.type);
}
async evaluate(env) {
await this.lengthExpr.evaluate(env);
await this.breakpoint();
let [length] = pop(1);
if (length < 0)
this.executionError("Negative array length");
this.elementType.resolve();
this.push(new JavaArrayObject(this.elementType.type, Array(length).fill(this.elementType.type.defaultValue())));
}
}
class NewArrayWithInitializerExpression extends AbstractNewArrayExpression {
constructor(loc, instrLoc, elementType, elementExpressions) {
super(loc, instrLoc);
this.elementType = elementType;
this.elementExpressions = elementExpressions;
}
check(env) {
this.elementType.resolve();
for (let e of this.elementExpressions)
e.checkAgainst(env, this.elementType.type);
return new ArrayType(this.elementType.type);
}
async evaluate(env) {
for (let e of this.elementExpressions)
await e.evaluate(env);
await this.breakpoint();
let elements = pop(this.elementExpressions.length);
this.elementType.resolve();
this.push(new JavaArrayObject(this.elementType.type, elements));
}
}
class ReadOnlyBinding {
constructor(value) {
this.value = value;
}
}
class SelectExpression extends Expression {
constructor(loc, instrLoc, target, selectorLoc, selector) {
super(loc, instrLoc);
this.target = target;
this.selectorLoc = selectorLoc;
this.selector = selector;
}
check(env) {
let targetType = this.target.check_(env);
if (targetType instanceof ArrayType) {
if (this.selector != "length")
this.executionError("Arrays do not have a field named '" + this.selector + "'");
return intType;
}
if (!(targetType instanceof ClassType))
this.executionError("Target expression must be of class type");
if (!has(targetType.class_.fields, this.selector))
this.executionError("Class " + targetType.class_.name + " does not have a field named '" + this.selector + "'");
return targetType.class_.fields[this.selector].type.type;
}
async evaluateBinding(env, allowReadOnly) {
await this.target.evaluate(env);
return pop => {
let [target] = pop(1);
if (target instanceof JavaArrayObject) {
if (this.selector != "length")
this.executionError(target + " does not have a field named '" + this.selector + "'");
if (allowReadOnly !== true)
this.executionError("Cannot modify an array's length");
return new ReadOnlyBinding(target.length);
}
if (!(target instanceof JavaObject))
this.executionError(target + " is not an object");
if (!has(target.fields, this.selector))
this.executionError("Target does not have a field named " + this.selector);
return target.fields[this.selector];
}
}
async evaluate(env) {
let bindingThunk = await this.evaluateBinding(env, true);
await this.breakpoint();
this.push(bindingThunk(pop).value);
}
}
class SubscriptExpression extends Expression {
constructor(loc, instrLoc, target, index) {
super(loc, instrLoc);
this.target = target;
this.index = index;
}
check(env) {
let targetType = this.target.check_(env);
if (!(targetType instanceof ArrayType))
this.executionError("Target of subscript expression must be of array type");
this.index.checkAgainst(env, intType);
return targetType.elementType;
}
async evaluateBinding(env) {
await this.target.evaluate(env);
await this.index.evaluate(env);
return pop => {
let [target, index] = pop(2);
if (!(target instanceof JavaArrayObject))
this.executionError(target + " is not an array");
if (index < 0)
this.executionError("Negative array index " + index);
if (target.length <= index)
this.executionError("Array index " + index + " not less than array length " + target.length);
return target.fields[index];
}
}
async evaluate(env) {
let bindingThunk = await this.evaluateBinding(env);
await this.breakpoint();
this.push(bindingThunk(pop).value);
}
}
class CallExpression extends Expression {
constructor(loc, instrLoc, callee, args) {
super(loc, instrLoc);
this.callee = callee;
this.arguments = args;
}
check(env) {
let method;
if (this.callee instanceof VariableExpression) {
if (!has(toplevelMethods, this.callee.name))
this.executionError("No such top-level method: " + this.callee.name);
method = toplevelMethods[this.callee.name];
} else if (this.callee instanceof SelectExpression) {
let targetType = this.callee.target.check(env);
if (targetType instanceof ClassType) {
if (!has(targetType.class_.methods, this.callee.selector))
this.executionError(`No method called ${this.callee.selector} in class ${this.callee.target.class_.name}`);
method = targetType.class_.methods[this.callee.selector];
} else if (targetType instanceof ArrayType) {
if (this.callee.selector != 'clone')
this.executionError(`Array objects do not have a method called ${this.callee.selector}`);
return targetType;
} else
this.executionError(`Cannot call a method on an expression of type ${targetType}`);
} else
this.executionError("The callee expression must be a method name");
if (method.parameterDeclarations.length != this.arguments.length)
this.executionError("Incorrect number of arguments");
for (let i = 0; i < this.arguments.length; i++)
this.arguments[i].checkAgainst(env, method.parameterDeclarations[i].type.type, `the declared type of parameter '${method.parameterDeclarations[i].name}'`);
return method.returnType.type;