-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathcompiler.ts
2921 lines (2771 loc) · 103 KB
/
compiler.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
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
import {
Stmt,
Expr,
UniOp,
BinOp,
Type,
Program,
Literal,
FunDef,
ClosureDef,
VarInit,
Class,
Destructure,
AssignTarget,
Location,
Assignable,
} from "./ast";
import {
NUM,
BOOL,
NONE,
CLASS,
STRING,
unhandledTag,
unreachable,
WithTag,
bigintToWords,
} from "./utils";
import * as BaseException from "./error";
import { RunTime } from "./errorManager";
import {
MemoryManager,
TAG_BIGINT,
TAG_CLASS,
TAG_CLOSURE,
TAG_DICT,
TAG_DICT_ENTRY,
TAG_LIST,
TAG_OPAQUE,
TAG_REF,
TAG_STRING,
TAG_TUPLE,
} from "./alloc";
import { augmentFnGc } from "./compiler-gc";
import { defaultMaxListeners } from "stream";
// https://learnxinyminutes.com/docs/wasm/
// Numbers are offsets into global memory
export type GlobalEnv = {
globals: Map<string, number>;
classes: Map<string, Map<string, [number, Literal]>>;
locals: Map<string, number>; // Map from local/param to stack slot index
funs: Map<string, [number, Array<string>]>; // <function name, [tbl idx, Array of nonlocals]>
};
export const emptyEnv: GlobalEnv = {
globals: new Map(),
classes: new Map(),
locals: new Map(),
funs: new Map(),
};
const FENCE_TEMPS = 2;
const RELEASE_TEMPS = 1;
const HOLD_TEMPS = 0;
export const nTagBits = 1;
const INT_LITERAL_MAX = BigInt(2 ** (31 - nTagBits) - 1);
const INT_LITERAL_MIN = BigInt(-(2 ** (31 - nTagBits)));
export enum ListContentTag {
Num = 0,
Bool,
None,
Str,
Class,
List,
Dict,
Callable,
}
enum ListCopyMode {
Copy = 0,
Slice,
Double,
Concat,
}
export const encodeLiteral: Array<string> = [
`(i32.const ${nTagBits})`,
"(i32.shl)",
"(i32.const 1)", // literals are tagged with a 1 in the LSB
"(i32.add)",
];
export const decodeLiteral: Array<string> = [`(i32.const ${nTagBits})`, "(i32.shr_s)"];
export function augmentEnv(
env: GlobalEnv,
prog: Program<[Type, Location]>,
mm: MemoryManager
): GlobalEnv {
const newGlobals = new Map(env.globals);
const newClasses = new Map(env.classes);
const newFuns = new Map(env.funs);
// set the referenced value to be num since we use i32 in wasm
const RefMap = new Map<string, [number, Literal]>();
RefMap.set("$deref", [0, { tag: "num", value: BigInt(0) }]);
newClasses.set("$ref", RefMap);
let idx = newFuns.size;
prog.closures.forEach((clo) => {
newFuns.set(clo.name, [idx, clo.nonlocals]);
idx += 1;
if (clo.isGlobal) {
const globalAddr = mm.staticAlloc(4n);
newGlobals.set(clo.name, Number(globalAddr));
}
});
prog.inits.forEach((v) => {
// Allocate static memory for the global variable
// NOTE(alex:mm) assumes that allocations return a 32-bit address
const globalAddr = mm.staticAlloc(4n);
console.log(`global var '${v.name}' addr: ${globalAddr.toString()}`);
newGlobals.set(v.name, Number(globalAddr));
mm.addGlobal(globalAddr);
});
// for rg
const rgAddr = mm.staticAlloc(4n);
newGlobals.set("rg", Number(rgAddr));
mm.addGlobal(rgAddr);
prog.classes.forEach((cls) => {
const classFields = new Map();
cls.fields.forEach((field, i) => classFields.set(field.name, [i, field.value]));
newClasses.set(cls.name, classFields);
});
return {
globals: newGlobals,
classes: newClasses,
locals: env.locals,
funs: newFuns,
};
}
type CompileResult = {
functions: string;
mainSource: string;
newEnv: GlobalEnv;
};
export function makeLocals(locals: Set<string>): Array<string> {
const localDefines: Array<string> = [];
locals.forEach((v) => {
localDefines.push(`(local $${v} i32)`);
});
return localDefines;
}
//Any built-in WASM functions go here
export function libraryFuns(): string {
var libfunc = dictUtilFuns().join("\n") + "\n" + stringUtilFuns().join("\n");
libfunc += "\n" + listBuiltInFuns().join("\n");
return libfunc;
}
export function makeId<A>(a: A, x: string): Destructure<A> {
return {
isDestructured: false,
targets: [
{
target: { a: a, tag: "id", name: x },
starred: false,
ignore: false,
},
],
};
}
export function makeLookup<A>(a: A, obj: Expr<A>, field: string): Destructure<A> {
return {
isDestructured: false,
targets: [
{
ignore: false,
starred: false,
target: {
a: a,
tag: "lookup",
field: field,
obj: obj,
},
},
],
valueType: a,
};
}
export function compile(
ast: Program<[Type, Location]>,
env: GlobalEnv,
mm: MemoryManager
): CompileResult {
const withDefines = augmentEnv(env, ast, mm);
let stackIndexOffset = 0; // NOTE(alex:mm): assumes start function has no params
const definedVars: Set<string> = new Set(); //getLocals(ast);
definedVars.add("$last");
definedVars.add("$allocPointer"); // Used to cache the result of `gcalloc`
definedVars.add("$addr"); // address of the allocated memory
definedVars.add("$list_base");
definedVars.add("$list_index");
definedVars.add("$list_index2");
definedVars.add("$list_temp");
definedVars.add("$list_size");
definedVars.add("$list_bound");
definedVars.add("$list_cmp");
definedVars.add("$list_cmp2");
definedVars.add("$destruct");
definedVars.add("$destructListOffset");
definedVars.add("$string_val"); //needed for string operations
definedVars.add("$string_class"); //needed for strings in class
definedVars.add("$string_index"); //needed for string index check out of bounds
definedVars.add("$string_address"); //needed for string indexing
definedVars.add("$slice_start"); //needed for string slicing
definedVars.add("$slice_end"); //needed for string slicing
definedVars.add("$slice_stride"); //needed for string slicing
definedVars.add("$counter"); //needed for string slicing
definedVars.add("$length"); //needed for string slicing
definedVars.forEach((v) => {
env.locals.set(v, stackIndexOffset);
stackIndexOffset += 1;
});
const localDefines = makeLocals(definedVars);
const funs: Array<string> = [];
ast.funs.forEach((f) => {
funs.push(codeGenFunDef(f, withDefines).join("\n"));
});
ast.closures.forEach((clo) => {
funs.push(codeGenClosureDef(clo, withDefines).join("\n"));
});
const globalFuns: Array<string> = [];
ast.closures.forEach((clo) => {
if (clo.isGlobal) {
globalFuns.push(clo.name);
}
});
const initFuns = initGlobalFuns(globalFuns, withDefines);
const classes: Array<string> = ast.classes.map((cls) => codeGenClass(cls, withDefines)).flat();
const allFuns = funs.concat(classes).join("\n\n");
// const stmts = ast.filter((stmt) => stmt.tag !== "fun");
const inits = ast.inits.map((init) => codeGenInit(init, withDefines)).flat();
const commandGroups = ast.stmts.map((stmt) => codeGenStmt(stmt, withDefines));
const commands = localDefines.concat(initFuns.concat(inits.concat(...commandGroups)));
const augmentedCommands = augmentFnGc(commands, withDefines.locals, {
main: true,
debug: {
name: "entry",
},
});
withDefines.locals.clear();
return {
functions: allFuns,
mainSource: augmentedCommands.join("\n"),
newEnv: withDefines,
};
}
function initGlobalFuns(funs: Array<string>, env: GlobalEnv): Array<string> {
const inits: Array<string> = [];
funs.forEach((fun) => {
let fun_info = env.funs.get(fun);
let idx = fun_info[0];
let length = fun_info[1].length;
let loc = envLookup(env, fun);
inits.push(...myMemAlloc(`$$addr`, length + 1, true));
inits.push(`(i32.store (local.get $$addr) (i32.const ${idx})) ;; function idx`);
inits.push(`(i32.store (i32.const ${loc}) (local.get $$addr)) ;; global function reference`);
});
// global functions have no nonlocals, assert length == 0
return inits;
}
function envLookup(env: GlobalEnv, name: string): number {
//if(!env.globals.has(name)) { console.log("Could not find " + name + " in ", env); throw new Error("Could not find name " + name); }
if (!env.globals.has(name)) {
console.log("Could not find " + name + " in ", env);
throw new BaseException.InternalException(
"Report this as a bug to the compiler developer, this shouldn't happen "
);
}
// NOTE(alex:mm): ADDRESS of the global variable is store in the environment
return env.globals.get(name);
}
function codeGenStmt(stmt: Stmt<[Type, Location]>, env: GlobalEnv): Array<string> {
switch (stmt.tag) {
case "return":
var valStmts = codeGenTempGuard(codeGenExpr(stmt.value, env), FENCE_TEMPS);
valStmts.push("(return)");
return valStmts;
case "assignment":
const valueCode = codeGenExpr(stmt.value, env);
const getValue = "(local.get $$destruct)";
// TODO(alex): make more granular?
return codeGenTempGuard(
[
...valueCode,
"(local.set $$destruct)",
...codeGenDestructure(stmt.destruct, getValue, env),
],
FENCE_TEMPS
);
case "expr":
var exprStmts = codeGenExpr(stmt.expr, env);
return codeGenTempGuard(exprStmts.concat([`(local.set $$last)`]), FENCE_TEMPS);
case "if":
// TODO(alex:mm): Are these temporary guards correct/minimal?
var condExpr = codeGenTempGuard(
codeGenExpr(stmt.cond, env).concat(decodeLiteral),
FENCE_TEMPS
);
var thnStmts = stmt.thn.map((innerStmt) => codeGenStmt(innerStmt, env)).flat();
var elsStmts = stmt.els.map((innerStmt) => codeGenStmt(innerStmt, env)).flat();
return condExpr
.concat(["(if (then"])
.concat(thnStmts)
.concat([")", "(else"])
.concat(elsStmts)
.concat(["))"]);
case "while":
var wcondExpr = codeGenTempGuard(
codeGenExpr(stmt.cond, env).concat(decodeLiteral),
FENCE_TEMPS
);
var bodyStmts = stmt.body.map((innerStmt) => codeGenStmt(innerStmt, env)).flat();
return ["(block (loop (br_if 1"]
.concat(wcondExpr)
.concat(["(i32.eqz))"])
.concat(bodyStmts)
.concat(["(br 0) ))"]);
case "for":
var bodyStmts = stmt.body.map((innerStmt) => codeGenStmt(innerStmt, env)).flat();
var iter = codeGenExpr(stmt.iterable, env);
var rgExpr: Expr<[Type, Location]> = {
a: [CLASS("Range"), stmt.a[1]],
tag: "id",
name: "rg",
};
var Expr_cur: Expr<[Type, Location]> = {
a: [NUM, stmt.a[1]],
tag: "lookup",
obj: rgExpr,
field: "cur",
};
var Code_cur = codeGenExpr(Expr_cur, env);
var Expr_stop: Expr<[Type, Location]> = {
a: [NUM, stmt.a[1]],
tag: "lookup",
obj: rgExpr,
field: "stop",
};
var Code_stop = codeGenExpr(Expr_stop, env);
var Expr_step: Expr<[Type, Location]> = {
a: [NUM, stmt.a[1]],
tag: "lookup",
obj: rgExpr,
field: "step",
};
var Code_step_expr = codeGenExpr(Expr_step, env);
// name = cur
var ass: Stmt<[Type, Location]> = {
a: [NONE, stmt.a[1]],
tag: "assignment",
destruct: makeId([NUM, stmt.a[1]], stmt.name),
value: Expr_cur,
};
var Code_ass = codeGenStmt(ass, env);
// add step to cur
var ncur: Expr<[Type, Location]> = {
a: [NUM, stmt.a[1]],
tag: "binop",
op: BinOp.Plus,
left: Expr_cur,
right: Expr_step,
};
var step: Stmt<[Type, Location]> = {
a: rgExpr.a,
tag: "assignment",
destruct: makeLookup(rgExpr.a, rgExpr, "cur"),
value: ncur,
};
var Code_step = codeGenStmt(step, env);
// stop condition cur<step
var Expr_cond: Expr<[Type, Location]> = {
a: [BOOL, stmt.a[1]],
tag: "binop",
op: BinOp.Gte,
left: Expr_cur,
right: Expr_stop,
};
var Code_cond = codeGenExpr(Expr_cond, env);
// if have index
if (stmt.index) {
var iass: Stmt<[Type, Location]> = {
a: [NONE, stmt.a[1]],
tag: "assignment",
destruct: makeId([NUM, stmt.a[1]], stmt.index),
value: { a: [NUM, stmt.a[1]], tag: "literal", value: { tag: "num", value: BigInt(0) } },
};
var Code_iass = codeGenStmt(iass, env);
var nid: Expr<[Type, Location]> = {
a: [NUM, stmt.a[1]],
tag: "binop",
op: BinOp.Plus,
left: { a: [NUM, stmt.a[1]], tag: "id", name: stmt.index },
right: { a: [NUM, stmt.a[1]], tag: "literal", value: { tag: "num", value: BigInt(1) } },
};
var niass: Stmt<[Type, Location]> = {
a: [NONE, stmt.a[1]],
tag: "assignment",
destruct: makeId([NUM, stmt.a[1]], stmt.index),
value: nid,
};
var Code_idstep = codeGenStmt(niass, env);
// iterable should be a Range object
return codeGenTempGuard(
[
`(i32.const ${envLookup(env, "rg")})`,
...iter,
`(i32.store)`,
...Code_iass,
"(block",
"(loop",
...Code_step,
...Code_idstep,
...["(bf_if 1", ...Code_cond, ...decodeLiteral, "))"],
...Code_ass,
...bodyStmts,
"(br 0)",
"))",
],
FENCE_TEMPS
);
}
// iterable should be a Range object
// test
// ${Code_cond.join("\n")}(call $print_bool)(local.set $$last)
// ${Code_cur.join("\n")}(call $print_num)(local.set $$last)
// ${Code_stop.join("\n")}(call $print_num)(local.set $$last)
// ${Code_step_expr.join("\n")}(call $print_num)(local.set $$last)
return codeGenTempGuard(
[
`(i32.const ${envLookup(env, "rg")})`,
...iter,
`(i32.store)`,
`(block`,
` (loop`,
...Code_step,
...[`(br_if 1 `, ...Code_cond, ...decodeLiteral, ")"],
...Code_ass,
...bodyStmts,
`(br 0)`,
`))`,
],
FENCE_TEMPS
);
case "pass":
return [];
case "break":
// break to depth
return [`(br ${stmt.depth})`];
case "continue":
console.log(stmt);
return [`(br ${stmt.depth})`];
default:
unhandledTag(stmt);
}
}
/**
* Generate assign statements as described by the destructuring term
* @param destruct Destructuring description of assign targets
* @param value WASM code literal value for fetching the referenced value. E.g. "(local.get $$myValue)"
* @param env GlobalEnv
*/
function codeGenDestructure(
destruct: Destructure<[Type, Location]>,
value: string,
env: GlobalEnv
): string[] {
let assignStmts: string[] = [];
if (destruct.isDestructured) {
const objTyp = destruct.valueType[0];
switch (objTyp.tag) {
// TODO: Remove class-based destructuring in the long term, leave for now until it can be safely removed
case "class": {
const className = objTyp.name;
const classFields = env.classes.get(className).values();
// Collect every assignStmt
assignStmts = destruct.targets.flatMap((target) => {
const assignable = target.target;
if (target.starred) {
throw new Error("Do not currently support starred assignment targets for objects");
} else {
const [offset, _] = classFields.next().value;
// The WASM code value that we extracted from the object at this current offset
const addressOffset = offset * 4;
const fieldValue = [value, `(i32.load offset=${addressOffset})`];
return codeGenAssignable(assignable, fieldValue, env);
}
});
break;
}
case "tuple": {
let offset = 0;
assignStmts = destruct.targets.flatMap((target) => {
const assignable = target.target;
if (target.starred) {
throw new Error("Do not currently support starred assignment targets for tuples");
} else {
const fieldValue = [value, `(i32.load offset=${offset})`];
offset += 4;
return codeGenAssignable(assignable, fieldValue, env);
}
});
break;
}
case "list": {
// Determines if we have a single target with starred == true
// used to run a different runtime length check
const isStarred = destruct.targets.some((target) => target.starred);
let targetListLength: number;
let compareLengthOperator: string;
if (isStarred) {
// Targets list length - 1 is the lower bound for number of required elements in our array
// The array can be larger/equal to this (because of star operator) but not smaller
targetListLength = destruct.targets.length - 1;
compareLengthOperator = `(i32.ge_u)`;
} else {
// No star operator simply means the target lists and the runtime list must be same length
targetListLength = destruct.targets.length;
compareLengthOperator = `(i32.eq)`;
}
// TODO: Add nice runtime error instead of "RuntimeError: unreachable"
const lengthCheck = [
value,
`(i32.load offset=4)`, // list length, stored at byte offset 4
`(i32.const ${targetListLength})`, // number of destruct targets
compareLengthOperator,
`(if (then (nop)) (else (unreachable)))`,
//`(if (then (nop)) (else (call $SomeExitingErrorFunction)))`
];
// Skip past the three header values of lists and to the actual values
let initalizeOffset = [`(i32.const 12)`, `(local.set $$destructListOffset)`];
let offset = [`(local.get $$destructListOffset)`];
const targetStmts = destruct.targets.flatMap((target) => {
const assignable = target.target;
if (target.starred) {
//throw new Error("Star operator not implemented yet.");
// The starting index of the star operator
// subtracting the 12 for the header values, dividing by 4 to convert from byte offset to index in list
const startStarIndex = [`(i32.div_s (i32.sub ${offset} (i32.const 12)) (i32.const 4))`];
let nonStarredElements = destruct.targets.length - 1;
// The WASM number of elements we need in our starred element list
const numStarElements = [
value,
`(i32.load offset=4)`, // list length, stored at byte offset 4
`(i32.const ${nonStarredElements})`,
`(i32.sub)`, // results in the number of elements needed in the starred list
];
// The ending index of the star operator (exclusive)
const endStarIndex = [
`(i32.add ${startStarIndex.join("\n")} ${numStarElements.join("\n")})`,
];
const sourceList = [value];
const incrementOffset = [
...offset,
`(i32.mul ${numStarElements.join("\n")} (i32.const 4))`,
`(i32.add)`,
`(local.set $$destructListOffset)`,
];
let copyListSlice: string[] = [
...startStarIndex,
...endStarIndex,
...sourceList,
...codeGenListCopy(ListCopyMode.Slice),
];
return codeGenAssignable(assignable, copyListSlice, env).concat(incrementOffset);
} else {
const fieldValue = [`(i32.load (i32.add ${value} ${offset}))`];
const incrementOffset = [
...offset,
`(i32.const 4)`,
`(i32.add)`,
`(local.set $$destructListOffset)`,
];
return codeGenAssignable(assignable, fieldValue, env).concat(incrementOffset);
}
});
assignStmts = [...lengthCheck, ...initalizeOffset, ...targetStmts];
break;
}
}
} else {
const target = destruct.targets[0];
assignStmts = codeGenAssignable(target.target, [value], env);
}
return assignStmts;
}
function codeGenAssignable(
target: Assignable<[Type, Location]>,
value: string[],
env: GlobalEnv
): string[] {
// NOTE(alex:mm): temp guards are generated at the statement level
switch (target.tag) {
case "id": // Variables
if (env.locals.has(target.name)) {
const localIndex = env.locals.get(target.name);
const result = [...value, `(local.set $${target.name})`];
return result;
} else {
const locationToStore = [`(i32.const ${envLookup(env, target.name)}) ;; ${target.name}`];
return [...locationToStore, ...value, "(i32.store)"];
}
case "lookup": // Field lookup
var objStmts = codeGenExpr(target.obj, env);
const objTyp = target.obj.a[0];
if (objTyp.tag !== "class") {
// I don't think this error can happen
throw new BaseException.InternalException(
"Report this as a bug to the compiler developer, this shouldn't happen " + objTyp.tag
);
}
var checkNone = codeGenRuntimeCheck(target.obj.a[1], objStmts, RunTime.CHECK_NONE_CLASS);
objStmts = objStmts.concat(checkNone);
const className = objTyp.name;
const [offset, _] = env.classes.get(className).get(target.field);
if (target.field == "$deref") {
return [...objStmts, ...value, `(i32.store)`];
} else {
return [...objStmts, `(i32.add (i32.const ${offset * 4}))`, ...value, `(i32.store)`];
}
case "bracket-lookup":
switch (target.obj.a[0].tag) {
case "dict":
var objStmts = codeGenExpr(target.obj, env);
var checkNone = codeGenRuntimeCheck(target.obj.a[1], objStmts, RunTime.CHECK_NONE_LOOKUP);
objStmts = objStmts.concat(checkNone);
return objStmts.concat(codeGenDictKeyVal(target.key, value, 10, env));
case "list":
const listObjStmts = codeGenExpr(target.obj, env);
const listKeyStmts = codeGenExpr(target.key, env);
//Add base + (3*4) + (key*4)
//TODO key is bigNum handling
const listLocationToStore = [
...listObjStmts,
`(i32.add (i32.const 12)) ;; move past type, size, bound`,
...listKeyStmts,
...decodeLiteral,
`(i32.mul (i32.const 4)) `,
`(i32.add)`,
];
return [...listLocationToStore, ...value, "(i32.store)"];
default:
throw new BaseException.InternalException(
"Bracket-assign for types other than dict not implemented"
);
}
default:
// Force type error if assignable is added without implementation
// At the very least, there should be a stub
const err: never = target;
throw new BaseException.InternalException(`Unknown target ${JSON.stringify(err)} (compiler)`);
}
}
function codeGenInit(init: VarInit<[Type, Location]>, env: GlobalEnv): Array<string> {
const value = codeGenLiteral(init.value);
if (env.locals.has(init.name)) {
return [...value, `(local.set $${init.name})`];
} else {
const locationToStore = [
`(i32.const ${envLookup(env, init.name)}) ;; global variable ${init.name}`,
];
return locationToStore.concat(value).concat([`(i32.store)`]);
}
}
// NOTE(alex:mm): Assuming this is only called for closure allocation
// which uses a class-based layout
function myMemAlloc(name: string, sizeInValueCount: number, closure?: boolean): Array<string> {
const allocs: Array<string> = [];
const sizeInBytes = sizeInValueCount * 4;
let tag = closure ? TAG_CLOSURE : TAG_REF;
allocs.push(
`(i32.const ${Number(closure ? TAG_CLOSURE : TAG_REF)}) ;; heap-tag: ${
closure ? "closure" : "ref"
}`
);
allocs.push(`(i32.const ${sizeInBytes})`);
allocs.push(`(call $$gcalloc)`);
allocs.push(`(local.set ${name}) ;; allocate memory for ${name}`);
return allocs;
}
function initNested(nested: Array<string>, env: GlobalEnv): Array<string> {
// this is where the closures are constructed, except for global closures
// the accesses of callable variables does not create a closure
const inits: Array<string> = [];
nested.forEach((fun) => {
inits.push(...myMemAlloc(`$${fun}_$ref`, 1));
});
nested.forEach((fun) => {
let [idx, nonlocals] = env.funs.get(fun);
// NOTE(alex:mm): Pass `true` to allocate with TAG_CLOSURE
inits.push(...myMemAlloc(`$$addr`, nonlocals.length + 1, true));
inits.push(`(i32.store (local.get $$addr) (i32.const ${idx})) ;; function idx`);
nonlocals.forEach((v, i) => {
// the dependent variable 'v' exists in the parent scope
inits.push(
`(i32.store (i32.add (local.get $$addr) (i32.const ${(i + 1) * 4})) (local.get $${v}_$ref))`
);
});
inits.push(`(i32.store (local.get $${fun}_$ref) (local.get $$addr))`);
});
return inits;
}
const fPTR = "$$fPTR"; // the first extra argument
function initNonlocals(nonlocals: Array<string>): Array<string> {
// extract the references for nonlocals from the '$fPTR'
const inits: Array<string> = [];
nonlocals.forEach((v, i) => {
inits.push(`(i32.load (i32.add (local.get ${fPTR}) (i32.const ${(i + 1) * 4})))`);
inits.push(`(local.set $${v}_$ref)`);
});
return inits;
}
function initRef(refs: Set<string>): Array<string> {
// for parameters and local variables, extra references are created and initialized
const inits: Array<string> = [];
refs.forEach((name) => {
inits.push(...myMemAlloc(`$${name}_$ref`, 1));
inits.push(`(i32.store (local.get $${name}_$ref) (local.get $${name}))`);
});
return inits;
}
function codeGenClosureDef(def: ClosureDef<[Type, Location]>, env: GlobalEnv): Array<string> {
let currentLocalIndex = 0;
const definedVars: Set<string> = new Set();
definedVars.add("$allocPointer"); // Used to cache the result of `gcalloc`
definedVars.add("$last");
definedVars.add("$addr");
definedVars.add("$list_base");
definedVars.add("$list_index");
definedVars.add("$list_index2");
definedVars.add("$list_temp");
definedVars.add("$list_size");
definedVars.add("$list_bound");
definedVars.add("$list_cmp");
definedVars.add("$list_cmp2");
definedVars.add("$destruct");
definedVars.add("$destructListOffset");
definedVars.add("$string_val"); //needed for string operations
definedVars.add("$string_class"); //needed for strings in class
definedVars.add("$string_index"); //needed for string index check out of bounds
definedVars.add("$string_address"); //needed for string indexing
definedVars.add("$slice_start"); //needed for string slicing
definedVars.add("$slice_end"); //needed for string slicing
definedVars.add("$slice_stride"); //needed for string slicing
definedVars.add("$counter"); //needed for string slicing
definedVars.add("$length"); //needed for string slicing
def.nonlocals.forEach((v) => definedVars.add(`${v}_$ref`)); // nonlocals are reference, ending with '_$ref'
def.nested.forEach((f) => definedVars.add(`${f}_$ref`)); // nested functions are references of function ptrs, ending with _$ref
// ToDo, optimize after EA
def.inits.forEach((v) => definedVars.add(`${v.name}`));
def.inits.forEach((v) => definedVars.add(`${v.name}_$ref`));
def.parameters.forEach((p) => definedVars.add(`${p.name}_$ref`));
// references that required memory allocation
const extraRefs: Set<string> = new Set();
def.inits.forEach((v) => extraRefs.add(`${v.name}`));
def.parameters.forEach((p) => {
extraRefs.add(`${p.name}`);
env.locals.set(p.name, currentLocalIndex);
currentLocalIndex += 1;
});
definedVars.forEach((v) => {
env.locals.set(v, currentLocalIndex);
currentLocalIndex += 1;
});
const locals = makeLocals(definedVars);
const inits = def.inits.map((init) => codeGenInit(init, env)).flat();
const refs = initRef(extraRefs);
const nonlocals = initNonlocals(def.nonlocals);
const nested = initNested(def.nested, env);
let params = def.parameters.map((p) => `(param $${p.name} i32)`).join(" ");
let stmts = def.body.map((stmt) => codeGenStmt(stmt, env)).flat();
let body = locals
.concat(inits)
.concat(refs)
.concat(nonlocals)
.concat(nested)
.concat(stmts)
.concat(["(i32.const 0)", "(return)"]);
const localMap = env.locals;
const augmentedBody = augmentFnGc(body, localMap, {
main: false,
debug: {
name: def.name,
},
});
const augmentedBodyStr = augmentedBody.join("\n");
env.locals.clear();
return [
`(func $${def.name} (param ${fPTR} i32) ${params} (result i32)
${augmentedBodyStr}
)`,
];
}
function codeGenFunDef(def: FunDef<[Type, Location]>, env: GlobalEnv): Array<string> {
var definedVars: Set<string> = new Set();
def.inits.forEach((v) => definedVars.add(v.name));
definedVars.add("$last");
// Used to cache the result of `gcalloc` and dump
// it to the stack for initialization
// NOTE(alex:mm): need to `local.get` object pointer BEFORE generating code
// for inner expressions
definedVars.add("$allocPointer"); // Used to cache the result of `gcalloc`
definedVars.add("$list_base");
definedVars.add("$list_index");
definedVars.add("$list_index2");
definedVars.add("$list_temp");
definedVars.add("$list_size");
definedVars.add("$list_bound");
definedVars.add("$list_cmp");
definedVars.add("$list_cmp2");
definedVars.add("$destruct");
definedVars.add("$destructListOffset");
definedVars.add("$string_val"); //needed for string operations
definedVars.add("$string_class"); //needed for strings in class
definedVars.add("$string_index"); //needed for string index check out of bounds
definedVars.add("$string_address"); //needed for string indexing
definedVars.add("$slice_start"); //needed for string slicing
definedVars.add("$slice_end"); //needed for string slicing
definedVars.add("$slice_stride"); //needed for string slicing
definedVars.add("$counter"); //needed for string slicing
definedVars.add("$length"); //needed for string slicing
// NOTE(alex:mm): parameters indices go first
let currLocalIndex = 0;
var params = def.parameters
.map((p) => {
env.locals.set(p.name, currLocalIndex);
currLocalIndex += 1;
return `(param $${p.name} i32)`;
})
.join(" ");
definedVars.forEach((v) => {
env.locals.set(v, currLocalIndex);
currLocalIndex += 1;
});
const locals = makeLocals(definedVars);
const inits = def.inits.map((init) => codeGenInit(init, env)).flat();
var stmts = def.body.map((innerStmt) => codeGenStmt(innerStmt, env)).flat();
const body = locals.concat(inits).concat(stmts).concat(["(i32.const 0)", "(return)"]);
const localMap = env.locals;
const augmentedBody = augmentFnGc(body, localMap, {
main: false,
debug: {
name: def.name,
},
});
const augmentedBodyStr = augmentedBody.join("\n");
env.locals.clear();
return [
`(func $${def.name} ${params} (result i32)
${augmentedBodyStr}
)`,
];
}
function codeGenClass(cls: Class<[Type, Location]>, env: GlobalEnv): Array<string> {
const methods = [...cls.methods];
methods.forEach((method) => (method.name = `${cls.name}$${method.name}`));
const result = methods.map((method) => codeGenFunDef(method, env));
return result.flat();
}
function codeGenListCopy(mode: ListCopyMode): Array<string> {
var stmts: Array<string> = [];
var loopstmts: Array<string> = [];
var condstmts: Array<string> = [];
var concatstmts: Array<string> = [];
var doublestmts: Array<string> = [];
var tempstmts: Array<string> = [];
var listType = 10; //temporary list type number
var header = [4, 8]; //size, bound relative position
var cmp = [""];
stmts.push(
...[
`(local.tee $$list_cmp)`, //store first address to local var
`(i32.add (i32.const 8))`,
`(i32.load)`,
`(local.set $$list_temp)`, //capacity
`(i32.const 0)`,
`(local.set $$list_index2)`, //second index
]
);
if (mode === ListCopyMode.Slice) {
stmts.push(
...[
`(local.set $$list_bound)`, // max index(not include)
`(local.set $$list_index)`, // current index
`(local.get $$list_bound)`,
`(local.get $$list_index)`,
`(i32.sub)`,
`(local.set $$list_size)`,
] //size of list
);
} else {
stmts.push(
...[
`(local.get $$list_cmp)`,
`(i32.add (i32.const 4))`,
`(i32.load)`,
`(local.tee $$list_size)`, //capacity
`(local.set $$list_bound)`,
`(i32.const 0)`,
`(local.set $$list_index)`,
]
);
}
if (mode === ListCopyMode.Concat) {
cmp = ["", "2"];
stmts.push(
...[
`(local.tee $$list_cmp2)`,
`(i32.add (i32.const 8))`,
`(i32.load)`,
`(local.get $$list_temp)`,
`(i32.add)`,
`(local.set $$list_temp)`, //capacity