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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
|
package org.shedlang.compiler.backends.wasm;
import org.pcollections.PMap;
import org.pcollections.PStack;
import org.pcollections.PVector;
import org.shedlang.compiler.backends.targets.WasmTarget;
import org.shedlang.compiler.backends.wasm.structure.ast.instructions.*;
import org.shedlang.compiler.backends.wasm.structure.ast.linking.WasmMemoryAddress;
import org.shedlang.compiler.backends.wasm.structure.ast.modules.*;
import org.shedlang.compiler.backends.wasm.structure.ast.types.*;
import org.shedlang.compiler.patio.*;
import org.shedlang.compiler.patio.instructions.*;
import org.shedlang.compiler.patio.operands.*;
import org.shedlang.compiler.patio.types.*;
import org.shedlang.compiler.patio.values.*;
import org.shedlang.compiler.util.Lists;
import org.shedlang.compiler.util.P;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
public class PatioToWasm {
private static final String INDIRECT_FUNCTION_TABLE_NAME = "__indirect_function_table";
public static WasmModule generateCompilationUnit(
PatioCompilationUnit patioCompilationUnit,
WasmTarget target
) {
var module = WasmModule.EMPTY.addImport(
new WasmImport(
"env",
INDIRECT_FUNCTION_TABLE_NAME,
new WasmImportDescriptor.Table(
INDIRECT_FUNCTION_TABLE_NAME,
new WasmTableType(WasmReferenceType.FUNC_REF, WasmLimits.min32(0))
)
)
);
var wasmMemoryBuilder = WasmMemoryBuilder.empty(target.indexType());
for (var patioCompilationUnitElement : patioCompilationUnit.elements()) {
switch (patioCompilationUnitElement) {
case PatioDataElementImmutableDefinition patioDataElementImmutableDefinition -> {
wasmMemoryBuilder = wasmMemoryBuilder.add(
patioDataElementImmutableDefinition.name(),
patioDataValueToBytes(patioDataElementImmutableDefinition.value(), target),
WasmAlignment.ALIGN_32_BIT
).memory();
}
case PatioDataElementMutableDeclaration patioDataElementMutableDeclaration -> {
// TODO: how to test this?
module = module.addUndefinedDataElement(patioDataElementMutableDeclaration.name());
}
case PatioDataElementMutableDefinition patioDataElementMutableDefinition -> {
wasmMemoryBuilder = wasmMemoryBuilder.add(
patioDataElementMutableDefinition.name(),
patioDataValueToBytes(patioDataElementMutableDefinition.initialValue(), target),
WasmAlignment.ALIGN_32_BIT
).memory();
}
case PatioFunctionDeclaration patioFunctionDeclaration -> {
var name = patioFunctionDeclaration.name();
var wasmFuncType = new WasmFuncType(
patioFunctionDeclaration.params().stream()
.map(param -> patioTypeToWasmValueType(param.type(), target))
.toList(),
patioFunctionDeclaration.returnTypes().stream()
.map(returnType -> patioTypeToWasmValueType(returnType, target))
.toList()
);
module = module.addImport(new WasmImport(
"env",
name,
new WasmImportDescriptor.Func(name, wasmFuncType)
));
}
case PatioExceptionTypeDefinition patioExceptionTypeDefinition -> {
module = module.addTag(new WasmTag(
WasmTagType.EXCEPTION,
patioExceptionTypeDefinition.name(),
List.of(target.patioIntType())
));
}
case PatioFunctionDefinition patioFunctionDefinition -> {
var name = patioFunctionDefinition.name();
var wasmParams = new ArrayList<WasmLocal>();
var wasmLocals = new ArrayList<WasmLocal>();
for (var patioLocal : patioFunctionDefinition.locals()) {
var wasmLocal = patioLocalToWasmLocal(patioLocal, target);
switch (patioLocal.localType()) {
case PARAM -> {
wasmParams.add(wasmLocal);
}
case VAL, VAR -> {
wasmLocals.add(wasmLocal);
}
}
}
var wasmResultTypes = patioFunctionDefinition.returnTypes().stream()
.map(returnType -> patioTypeToWasmValueType(returnType, target))
.toList();
var context = generateInstructions(
patioFunctionDefinition.body(),
Context.forFunction(target, module, Lists.concat(wasmParams, wasmLocals))
);
module = context.module;
module = module.addFunction(new WasmFunction(
name,
wasmParams,
wasmLocals,
wasmResultTypes,
new WasmExpression(context.instructions)
));
}
}
}
module = wasmMemoryBuilder.toModule(module);
return module;
}
private static Context generateInstructions(
List<PatioInstruction> patioInstructions,
Context context
) {
for (var patioInstruction : patioInstructions) {
context = generateInstruction(patioInstruction, context);
}
return context;
}
private static Context generateInstruction(
PatioInstruction patioInstruction,
Context context
) {
var target = context.target;
return switch (patioInstruction) {
case PatioBlock patioBlock ->
generateInstructions(patioBlock.body(), context);
case PatioBoolToInt patioBoolToInt -> {
context = generateOperand(patioBoolToInt.value(), context);
if (target == WasmTarget.WASM64) {
context = context.addInstruction(new WasmI64ExtendI32Unsigned());
}
context = popIntoPatioLocal(patioBoolToInt.destination(), context);
yield context;
}
case PatioCall patioCall -> {
for (var patioArg : patioCall.args()) {
context = generateOperand(patioArg, context);
}
context = context.addInstruction(new WasmCall(new WasmFuncName(patioCall.functionName())));
for (var patioDestination : patioCall.destinations().reversed()) {
context = popIntoPatioLocal(patioDestination, context);
}
yield context;
}
case PatioCallPointer patioCallPointer -> {
for (var patioArg : patioCallPointer.args()) {
context = generateOperand(patioArg, context);
}
context = generateOperand(patioCallPointer.functionPointer(), context);
var wasmFuncType = new WasmFuncType(
patioOperandsToWasmValueTypes(patioCallPointer.args(), context),
patioOperandsToWasmValueTypes(patioCallPointer.destinations(), context)
);
context = context.addType(wasmFuncType);
context = context.addInstruction(new WasmCallIndirect(
new WasmTableName(INDIRECT_FUNCTION_TABLE_NAME),
wasmFuncType
));
for (var patioDestination : patioCallPointer.destinations().reversed()) {
context = popIntoPatioLocal(patioDestination, context);
}
yield context;
}
case PatioDataPtrToInt patioDataPtrToInt ->
generateOperandToPatioLocal(
patioDataPtrToInt.destination(),
patioDataPtrToInt.value(),
context
);
case PatioIf patioIf -> {
context = generateOperand(patioIf.condition(), context);
var wasmBlockTypeResult = generateBlockType(patioIf.destinations(), context);
var wasmBlockType = wasmBlockTypeResult.value();
context = wasmBlockTypeResult.context();
context = context.enterIfInstruction(wasmBlockType);
context = generateBlockBody(patioIf.trueBody(), context);
context = context.enterElse();
context = generateBlockBody(patioIf.falseBody(), context);
context = context.exitIfInstruction();
context = popIntoPatioLocals(patioIf.destinations(), context);
yield context;
}
case PatioIntAdd patioIntAdd ->
generateBinaryOperation(
patioIntAdd,
wasmIntAdd(target.patioIntType()),
context
);
case PatioIntEquals patioIntEquals ->
generateBinaryOperation(
patioIntEquals,
wasmIntEq(target.patioIntType()),
context
);
case PatioIntNotEqual patioIntNotEqual ->
generateBinaryOperation(
patioIntNotEqual,
wasmIntNe(target.patioIntType()),
context
);
case PatioIntSub patioIntSub ->
generateBinaryOperation(
patioIntSub,
wasmIntSub(target.patioIntType()),
context
);
case PatioIntToBool patioIntToBool -> {
context = generateOperand(patioIntToBool.value(), context);
if (target == WasmTarget.WASM64) {
context = context.addInstruction(new WasmI32WrapI64());
}
context = popIntoPatioLocal(patioIntToBool.destination(), context);
yield context;
}
case PatioIntToDataPtr patioIntToDataPtr ->
generateOperandToPatioLocal(
patioIntToDataPtr.destination(),
patioIntToDataPtr.value(),
context
);
case PatioLocalStore patioLocalStore ->
generateOperandToPatioLocal(
patioLocalStore.destination(),
patioLocalStore.value(),
context
);
case PatioLoop patioLoop -> {
context = context.enterBlockInstruction();
context = context.enterLoopInstruction();
context = generateInstructions(patioLoop.body(), context);
context = context.exitLoopInstruction();
context = context.exitBlockInstruction();
yield context;
}
case PatioLoopBreak patioLoopBreak -> {
context = context.addBrToBlockInstruction();
yield context;
}
case PatioLoopContinue patioLoopContinue -> {
context = context.addBrToLoopInstruction();
yield context;
}
case PatioMemoryLoad patioMemoryLoad -> {
context = generateOperand(patioMemoryLoad.pointer(), context);
context = context.addInstruction(wasmIntLoad(
context.wasmLocalType(patioMemoryLoad.destination()),
wasmMemoryArg(
patioMemoryLoad.layout(),
patioMemoryLoad.elementOffsets(),
target
)
));
context = popIntoPatioLocal(patioMemoryLoad.destination(), context);
yield context;
}
case PatioMemoryStore patioMemoryStore -> {
context = generateOperand(patioMemoryStore.pointer(), context);
context = generateOperand(patioMemoryStore.value(), context);
context = context.addInstruction(wasmIntStore(
patioOperandToWasmValueType(patioMemoryStore.value(), context),
wasmMemoryArg(
patioMemoryStore.layout(),
patioMemoryStore.elementOffsets(),
target
)
));
yield context;
}
case PatioReturn patioReturn -> {
for (var value : patioReturn.values()) {
context = generateOperand(value, context);
}
context = context.addInstruction(new WasmReturn());
yield context;
}
case PatioSwitch patioSwitch -> {
// TODO: use br_table?
var wasmBlockTypeResult = generateBlockType(patioSwitch.destinations(), context);
var wasmBlockType = wasmBlockTypeResult.value();
context = wasmBlockTypeResult.context();
for (var patioSwitchCase : patioSwitch.cases()) {
context = generateOperand(patioSwitch.value(), context);
context = context.addInstruction(wasmIntConst(
patioOperandToWasmValueType(patioSwitch.value(), context),
patioSwitchCase.value()
));
context = context.addInstruction(wasmIntEq(
patioOperandToWasmValueType(patioSwitch.value(), context)
));
context = context.enterIfInstruction(wasmBlockType);
context = generateBlockBody(patioSwitchCase.body(), context);
context = context.enterElse();
}
context = generateBlockBody(patioSwitch.defaultBody(), context);
for (var patioSwitchCase : patioSwitch.cases()) {
context = context.exitIfInstruction();
}
context = popIntoPatioLocals(patioSwitch.destinations(), context);
yield context;
}
case PatioThrow throw_ -> {
context = generateOperand(throw_.value(), context);
context = context.addInstruction(new WasmThrow(new WasmTagName(throw_.exceptionTypeName())));
yield context;
}
case PatioTry try_ -> {
var wasmBlockTypeResult = generateBlockType(try_.destinations(), context);
var wasmBlockType = wasmBlockTypeResult.value();
context = wasmBlockTypeResult.context();
context = context.enterTryInstruction(wasmBlockType);
context = generateBlockBody(try_.body(), context);
for (var catchClause : try_.catchClauses()) {
context = context.enterCatch(new WasmTagName(catchClause.exceptionTypeName()));
context = popIntoPatioLocal(catchClause.destination(), context);
context = generateBlockBody(catchClause.body(), context);
}
context = context.exitTryInstruction();
context = popIntoPatioLocals(try_.destinations(), context);
yield context;
}
case PatioUnreachable patioUnreachable ->
context.addInstruction(new WasmUnreachable());
case PatioVarLoad patioVarLoad -> {
yield generateOperandToPatioLocal(
patioVarLoad.destination(),
patioVarLoad.var(),
context
);
}
case PatioVarStore patioVarStore -> {
yield generateOperandToPatioLocal(
patioVarStore.var(),
patioVarStore.value(),
context
);
}
};
}
private static Context.Result<WasmBlockType> generateBlockType(
List<PatioLocalRef> destinations,
Context context
) {
if (destinations.isEmpty()) {
return context.toResult(WasmBlockType.EMPTY);
} else if (destinations.size() == 1) {
var valueType = patioOperandToWasmValueType(destinations.get(0), context);
return context.toResult(WasmBlockType.of(valueType));
} else {
var resultTypes = destinations.stream()
.map(patioTarget -> patioOperandToWasmValueType(patioTarget, context))
.toList();
var funcType = new WasmFuncType(List.of(), resultTypes);
return context.addType(funcType).toResult(WasmBlockType.of(funcType));
}
}
private static Context generateBlockBody(
PatioBlock block,
Context context
) {
context = generateInstructions(block.body(), context);
for (var patioResult : block.results()) {
context = generateOperand(patioResult, context);
}
return context;
}
private static Context generateBinaryOperation(
PatioInstructionBinaryOperation patioInstruction,
WasmInstruction wasmInstruction,
Context context
) {
context = generateOperand(patioInstruction.left(), context);
context = generateOperand(patioInstruction.right(), context);
context = context.addInstruction(wasmInstruction);
context = popIntoPatioLocal(patioInstruction.destination(), context);
return context;
}
private static Context generateOperandToPatioLocal(
PatioLocalRef destination,
PatioOperand value,
Context context
) {
context = generateOperand(value, context);
context = popIntoPatioLocal(destination, context);
return context;
}
private static Context popIntoPatioLocal(PatioLocalRef destination, Context context) {
var destinationWasmLocalIndex = context.wasmLocalIndex(destination);
return context.addInstruction(new WasmLocalSet(destinationWasmLocalIndex));
}
private static Context popIntoPatioLocals(
List<PatioLocalRef> destinations,
Context context
) {
for (var patioTarget : destinations.reversed()) {
context = popIntoPatioLocal(patioTarget, context);
}
return context;
}
private static Context generateOperand(
PatioOperand patioOperand,
Context context
) {
return switch (patioOperand) {
case PatioBoolConst patioBoolConst ->
context.addInstruction(new WasmI32Const(patioBoolConst.value() ? 1 : 0));
case PatioByteConst patioByteConst ->
context.addInstruction(new WasmI32Const(Byte.toUnsignedInt(patioByteConst.value())));
case PatioDataPtrConst patioDataPtrConst ->
context.addInstruction(generateDataPtrValue(
patioDataPtrConst.value(),
context.target
));
case PatioFunctionPtrConst patioFunctionPtrConst -> {
var wasmFuncName = new WasmFuncName(patioFunctionPtrConst.name());
context = context
.addInstruction(new WasmTableElementIndexConst(wasmFuncName));
if (context.target == WasmTarget.WASM64) {
context = context.addInstruction(new WasmI64ExtendI32Unsigned());
}
yield context;
}
case PatioIntConst patioIntConst ->
context.addInstruction(wasmIntConst(
context.target.patioIntType(),
generateIntValue(patioIntConst.value(), context.target)
));
case PatioInt32Const patioInt32Const ->
context.addInstruction(new WasmI32Const(
generateIntValue(patioInt32Const.value(), context.target)
));
case PatioLocalRef patioLocalRef -> {
var wasmLocalIndex = context.wasmLocalIndex(patioLocalRef);
yield context.addInstruction(new WasmLocalGet(wasmLocalIndex));
}
};
}
private static WasmInstruction generateDataPtrValue(PatioDataPtrValue value, WasmTarget target) {
return switch (value) {
case PatioDataPtrValueDataElement dataElement -> {
var wasmMemoryAddress = new WasmMemoryAddress(dataElement.name());
yield new WasmMemoryAddressConst(
target.indexType(),
wasmMemoryAddress
);
}
case PatioDataPtrValueNull patioDataPtrValueNull -> {
yield wasmIntConst(target.dataPtrType(), 0);
}
};
}
private static int generateIntValue(PatioIntValue value, WasmTarget target) {
return switch (value) {
case PatioIntValueByteOffsetOf byteOffsetOf ->
offsetOf(
byteOffsetOf.layout(),
byteOffsetOf.elementOffsets(),
target
);
case PatioIntValueByteSizeOf byteSizeOf ->
sizeOf(
byteSizeOf.layout(),
target
);
case PatioIntValueLiteral literal ->
literal.value();
};
}
private static int sizeOf(PatioDataLayout layout, WasmTarget target) {
return switch (layout) {
case PatioDataLayoutArray patioDataLayoutArray ->
sizeOf(patioDataLayoutArray.element(), target) * patioDataLayoutArray.size();
case PatioDataLayoutBool patioDataLayoutBool ->
1;
case PatioDataLayoutByte patioDataLayoutByte ->
1;
case PatioDataLayoutDataPtr patioDataLayoutDataPtr ->
target.dataPtrType().sizeBytes();
case PatioDataLayoutFunctionPtr patioDataLayoutFunctionPtr ->
target.functionPtrType().sizeBytes();
case PatioDataLayoutInt patioDataLayoutInt ->
target.patioIntType().sizeBytes();
case PatioDataLayoutInt32 patioDataLayoutInt32 ->
WasmValueType.I32.sizeBytes();
case PatioDataLayoutStruct patioDataLayoutStruct ->
patioDataLayoutStruct.elements().stream()
.map(element -> sizeOf(element, target))
.reduce(0, Integer::sum);
};
}
private static int offsetOf(
PatioDataLayout patioDataLayout,
List<Integer> patioOffsets,
WasmTarget target
) {
var wasmOffset = 0;
for (var patioOffset : patioOffsets) {
switch (patioDataLayout) {
case PatioDataLayoutArray patioDataLayoutArray -> {
var elementSize = sizeOf(patioDataLayoutArray.element(), target);
wasmOffset += elementSize * patioOffset;
patioDataLayout = patioDataLayoutArray.element();
}
case PatioDataLayoutBool patioDataLayoutBool -> {
throw new RuntimeException("offset not allowed for bools");
}
case PatioDataLayoutByte patioDataLayoutByte -> {
throw new RuntimeException("offset not allowed for bytes");
}
case PatioDataLayoutDataPtr patioDataLayoutDataPtr -> {
throw new RuntimeException("offset not allowed for data ptrs");
}
case PatioDataLayoutFunctionPtr patioDataLayoutFunctionPtr -> {
throw new RuntimeException("offset not allowed for function ptrs");
}
case PatioDataLayoutInt patioDataLayoutInt -> {
throw new RuntimeException("offset not allowed for ints");
}
case PatioDataLayoutInt32 patioDataLayoutInt32 -> {
throw new RuntimeException("offset not allowed for int32s");
}
case PatioDataLayoutStruct patioDataLayoutStruct -> {
for (var i = 0; i < patioOffset; i++) {
var element = patioDataLayoutStruct.elements().get(i);
wasmOffset += sizeOf(element, target);
}
patioDataLayout = patioDataLayoutStruct.elements().get(patioOffset);
}
}
}
return wasmOffset;
}
private static WasmMemoryArg wasmMemoryArg(
PatioDataLayout patioDataLayout,
List<Integer> patioOffsets,
WasmTarget target
) {
var wasmOffset = offsetOf(patioDataLayout, patioOffsets, target);
// TODO: alignment
return new WasmMemoryArg(wasmOffset, WasmAlignment.NONE);
}
private static byte[] patioDataValueToBytes(
PatioDataValue value,
WasmTarget target
) {
var bytes = ByteBuffer.allocate(sizeOf(value, target));
bytes.order(ByteOrder.LITTLE_ENDIAN);
patioDataValueToBytes(value, bytes, target);
return bytes.array();
}
private static void patioDataValueToBytes(
PatioDataValue value,
ByteBuffer bytes,
WasmTarget target
) {
switch (value) {
case PatioDataValueArray patioDataValueArray -> {
for (var element : patioDataValueArray.elements()) {
patioDataValueToBytes(element, bytes, target);
}
}
case PatioDataValueBool patioDataValueBool -> {
bytes.put(patioDataValueBool.value() ? (byte) 1 : (byte) 0);
}
case PatioDataValueByte patioDataValueByte -> {
bytes.put(patioDataValueByte.value());
}
case PatioDataValueDataPtr patioDataValueDataPtr -> {
switch (patioDataValueDataPtr.value()) {
case PatioDataPtrValueDataElement dataElement -> {
throw new UnsupportedOperationException("TODO");
}
case PatioDataPtrValueNull null_ -> {
bytes.putInt(0);
}
};
}
case PatioDataValueInt patioDataValueInt -> {
var intValue = generateIntValue(patioDataValueInt.value(), target);
switch (target) {
case WASM32 -> {
bytes.putInt(intValue);
}
case WASM64 -> {
bytes.putLong(intValue);
}
}
}
case PatioDataValueInt32 patioDataValueInt32 -> {
var intValue = generateIntValue(patioDataValueInt32.value(), target);
bytes.putInt(intValue);
}
case PatioDataValueStruct patioDataValueStruct -> {
for (var element : patioDataValueStruct.elements()) {
patioDataValueToBytes(element, bytes, target);
}
}
}
}
private static int sizeOf(PatioDataValue value, WasmTarget target) {
return sizeOf(value.layout(), target);
}
private static WasmLocal patioLocalToWasmLocal(
PatioLocal local,
WasmTarget target
) {
return new WasmLocal(local.name(), patioTypeToWasmValueType(local.type(), target));
}
private static List<WasmValueType> patioOperandsToWasmValueTypes(
List<? extends PatioOperand> operands,
Context context
) {
return operands.stream()
.map(operand -> patioOperandToWasmValueType(operand, context))
.toList();
}
private static WasmValueType patioOperandToWasmValueType(
PatioOperand operand,
Context context
) {
return switch (operand) {
case PatioOperandConst patioOperandConst ->
patioTypeToWasmValueType(patioOperandConst.type(), context.target);
case PatioLocalRef patioLocalRef ->
// TODO: push into PatioOperand?
context.wasmLocalType(patioLocalRef);
};
}
private static WasmValueType patioTypeToWasmValueType(
PatioType type,
WasmTarget target
) {
return switch (type) {
case PatioBoolType patioBoolType ->
WasmValueType.I32;
case PatioByteType patioByteType ->
WasmValueType.I32;
case PatioDataPtrType patioDataPtrType ->
target.dataPtrType();
case PatioFunctionPtrType patioFunctionPtrType ->
target.functionPtrType();
case PatioIntType patioIntType ->
target.patioIntType();
case PatioInt32Type patioInt32Type ->
WasmValueType.I32;
};
}
private static WasmInstruction wasmIntConst(WasmValueType wasmValueType, int value) {
return switch (wasmValueType) {
case WasmValueType.Number number -> {
yield switch (number.type()) {
case I32 -> new WasmI32Const(value);
case I64 -> new WasmI64Const(value);
case F32, F64 -> {
throw new IllegalArgumentException("Cannot create int const for " + number);
}
};
}
};
}
private static WasmInstruction wasmIntEq(WasmValueType wasmValueType) {
if (wasmValueType == WasmValueType.I32) {
return new WasmI32Eq();
} else if (wasmValueType == WasmValueType.I64) {
return new WasmI64Eq();
} else {
throw new IllegalArgumentException("Cannot create int eq for " + wasmValueType);
}
}
private static WasmInstruction wasmIntNe(WasmValueType wasmValueType) {
if (wasmValueType == WasmValueType.I32) {
return new WasmI32Ne();
} else if (wasmValueType == WasmValueType.I64) {
return new WasmI64Ne();
} else {
throw new IllegalArgumentException("Cannot create int ne for " + wasmValueType);
}
}
private static WasmInstruction wasmIntAdd(WasmValueType wasmValueType) {
if (wasmValueType == WasmValueType.I32) {
return new WasmI32Add();
} else if (wasmValueType == WasmValueType.I64) {
return new WasmI64Add();
} else {
throw new IllegalArgumentException("Cannot create int add for " + wasmValueType);
}
}
private static WasmInstruction wasmIntSub(WasmValueType wasmValueType) {
if (wasmValueType == WasmValueType.I32) {
return new WasmI32Sub();
} else if (wasmValueType == WasmValueType.I64) {
return new WasmI64Sub();
} else {
throw new IllegalArgumentException("Cannot create int sub for " + wasmValueType);
}
}
private static WasmInstruction wasmIntLoad(
WasmValueType wasmValueType,
WasmMemoryArg memoryArg
) {
if (wasmValueType == WasmValueType.I32) {
return new WasmI32Load(memoryArg);
} else if (wasmValueType == WasmValueType.I64) {
return new WasmI64Load(memoryArg);
} else {
throw new IllegalArgumentException("Cannot create int load for " + wasmValueType);
}
}
private static WasmInstruction wasmIntStore(
WasmValueType wasmValueType,
WasmMemoryArg memoryArg
) {
if (wasmValueType == WasmValueType.I32) {
return new WasmI32Store(memoryArg);
} else if (wasmValueType == WasmValueType.I64) {
return new WasmI64Store(memoryArg);
} else {
throw new IllegalArgumentException("Cannot create int store for " + wasmValueType);
}
}
private static class Context {
private record PatioLocalInfo(
WasmLocalIndex wasmLocalIndex,
WasmValueType wasmType
) {}
public static Context forFunction(
WasmTarget target,
WasmModule module,
List<WasmLocal> locals
) {
var patioLocalNameToInfo = P.<String, PatioLocalInfo>map();
for (var local : locals) {
var wasmLocalIndex = new WasmLocalIndex(patioLocalNameToInfo.size());
var localInfo = new PatioLocalInfo(wasmLocalIndex, local.type());
patioLocalNameToInfo = patioLocalNameToInfo.plus(
local.name(),
localInfo
);
}
return new Context(
target,
module,
P.vector(),
P.stack(),
patioLocalNameToInfo,
new NullStructuredInstructionBuilder(),
P.stack()
);
}
private final WasmTarget target;
private final WasmModule module;
private final PVector<WasmInstruction> instructions;
private final PStack<PVector<WasmInstruction>> instructionsStack;
private final PMap<String, PatioLocalInfo> patioLocalNameToInfo;
private final WasmStructuredInstructionBuilder structuredInstructionBuilder;
private final PStack<WasmStructuredInstructionBuilder> structuredInstructionBuilderStack;
private Context(
WasmTarget target,
WasmModule module,
PVector<WasmInstruction> instructions,
PStack<PVector<WasmInstruction>> instructionsStack,
PMap<String, PatioLocalInfo> patioLocalNameToInfo,
WasmStructuredInstructionBuilder structuredInstructionBuilder,
PStack<WasmStructuredInstructionBuilder> structuredInstructionBuilderStack
) {
this.target = target;
this.module = module;
this.instructions = instructions;
this.instructionsStack = instructionsStack;
this.patioLocalNameToInfo = patioLocalNameToInfo;
this.structuredInstructionBuilder = structuredInstructionBuilder;
this.structuredInstructionBuilderStack = structuredInstructionBuilderStack;
}
private Context addType(WasmFuncType type) {
return new Context(
this.target,
this.module.addType(type),
this.instructions,
this.instructionsStack,
this.patioLocalNameToInfo,
this.structuredInstructionBuilder,
this.structuredInstructionBuilderStack
);
}
private Context addInstruction(WasmInstruction instruction) {
return new Context(
this.target,
this.module,
this.instructions.plus(instruction),
this.instructionsStack,
this.patioLocalNameToInfo,
this.structuredInstructionBuilder,
this.structuredInstructionBuilderStack
);
}
private WasmLocalIndex wasmLocalIndex(PatioLocalRef patioLocalRef) {
return this.patioLocalNameToInfo.get(patioLocalRef.name()).wasmLocalIndex;
}
public WasmValueType wasmLocalType(PatioLocalRef patioLocalRef) {
return this.patioLocalNameToInfo.get(patioLocalRef.name()).wasmType;
}
public Context enterBlockInstruction() {
return new Context(
this.target,
this.module,
P.vector(),
this.instructionsStack.plus(this.instructions),
this.patioLocalNameToInfo,
new WasmBlockInstructionBuilder(),
this.structuredInstructionBuilderStack.plus(this.structuredInstructionBuilder)
);
}
public Context exitBlockInstruction() {
// TODO: verify matching enter/exit?
return exitStructuredInstruction();
}
public Context addBrToBlockInstruction() {
return addBr(WasmBlockInstructionBuilder.class);
}
public Context enterLoopInstruction() {
return new Context(
this.target,
this.module,
P.vector(),
this.instructionsStack.plus(this.instructions),
this.patioLocalNameToInfo,
new WasmLoopInstructionBuilder(),
this.structuredInstructionBuilderStack.plus(this.structuredInstructionBuilder)
);
}
public Context exitLoopInstruction() {
// TODO: verify matching enter/exit?
return exitStructuredInstruction();
}
public Context addBrToLoopInstruction() {
return addBr(WasmLoopInstructionBuilder.class);
}
public Context enterIfInstruction(WasmBlockType blockType) {
return new Context(
this.target,
this.module,
P.vector(),
this.instructionsStack.plus(this.instructions),
this.patioLocalNameToInfo,
new WasmIfInstructionBuilder(blockType),
this.structuredInstructionBuilderStack.plus(this.structuredInstructionBuilder)
);
}
public Context enterElse() {
return new Context(
this.target,
this.module,
P.vector(),
this.instructionsStack,
this.patioLocalNameToInfo,
this.structuredInstructionBuilder.enterElse(this.instructions),
this.structuredInstructionBuilderStack
);
}
public Context exitIfInstruction() {
// TODO: verify matching enter/exit?
return exitStructuredInstruction();
}
public Context enterTryInstruction(WasmBlockType blockType) {
return new Context(
this.target,
this.module,
P.vector(),
this.instructionsStack.plus(this.instructions),
this.patioLocalNameToInfo,
new WasmTryInstructionBuilder(blockType),
this.structuredInstructionBuilderStack.plus(this.structuredInstructionBuilder)
);
}
public Context enterCatch(WasmTagName tagName) {
return new Context(
this.target,
this.module,
P.vector(),
this.instructionsStack,
this.patioLocalNameToInfo,
this.structuredInstructionBuilder.enterCatch(tagName, this.instructions),
this.structuredInstructionBuilderStack
);
}
public Context exitTryInstruction() {
// TODO: verify matching enter/exit?
return exitStructuredInstruction();
}
public Context exitStructuredInstruction() {
var context = new Context(
this.target,
this.module,
this.instructionsStack.get(0),
this.instructionsStack.minus(0),
this.patioLocalNameToInfo,
this.structuredInstructionBuilderStack.get(0),
this.structuredInstructionBuilderStack.minus(0)
);
var instruction = this.structuredInstructionBuilder
.exit(this.instructions);
return context.addInstruction(instruction);
}
private Context addBr(Class<? extends WasmStructuredInstructionBuilder> clazz) {
var labelIndex = findLabelIndex(clazz);
return this.addInstruction(new WasmBr(labelIndex));
}
private int findLabelIndex(Class<? extends WasmStructuredInstructionBuilder> clazz) {
if (clazz.isInstance(this.structuredInstructionBuilder)) {
return 0;
}
for (var i = 0; i < this.structuredInstructionBuilderStack.size(); i++) {
if (clazz.isInstance(this.structuredInstructionBuilderStack.get(i))) {
return i + 1;
}
}
throw new IllegalStateException("cannot find label index");
}
record Result<T>(T value, Context context) {}
public <T> Result<T> toResult(T value) {
return new Result<>(value, this);
}
}
private interface WasmStructuredInstructionBuilder {
WasmInstruction exit(PVector<WasmInstruction> instructions);
default WasmStructuredInstructionBuilder enterElse(PVector<WasmInstruction> instructions) {
throw new UnsupportedOperationException();
}
default WasmStructuredInstructionBuilder enterCatch(
WasmTagName tagName,
PVector<WasmInstruction> instructions
) {
throw new UnsupportedOperationException();
}
}
private static class NullStructuredInstructionBuilder implements WasmStructuredInstructionBuilder {
@Override
public WasmInstruction exit(PVector<WasmInstruction> instructions) {
throw new UnsupportedOperationException();
}
}
private static class WasmBlockInstructionBuilder implements WasmStructuredInstructionBuilder {
@Override
public WasmInstruction exit(PVector<WasmInstruction> instructions) {
return new WasmBlock(WasmBlockType.EMPTY, instructions);
}
}
private static class WasmLoopInstructionBuilder implements WasmStructuredInstructionBuilder {
@Override
public WasmInstruction exit(PVector<WasmInstruction> instructions) {
return new WasmLoop(WasmBlockType.EMPTY, instructions);
}
}
private record WasmIfInstructionBuilder(
WasmBlockType blockType
) implements WasmStructuredInstructionBuilder {
@Override
public WasmInstruction exit(PVector<WasmInstruction> instructions) {
throw new IllegalStateException("if instruction without else not supported");
}
@Override
public WasmStructuredInstructionBuilder enterElse(PVector<WasmInstruction> instructions) {
return new WasmIfElseInstructionBuilder(blockType, instructions);
}
}
private record WasmIfElseInstructionBuilder(
WasmBlockType blockType,
PVector<WasmInstruction> ifTrue
) implements WasmStructuredInstructionBuilder {
@Override
public WasmInstruction exit(PVector<WasmInstruction> instructions) {
return new WasmIf(blockType, ifTrue, instructions);
}
}
private record WasmTryInstructionBuilder(
WasmBlockType blockType
) implements WasmStructuredInstructionBuilder {
@Override
public WasmInstruction exit(PVector<WasmInstruction> instructions) {
return new WasmTry(blockType, List.of(), instructions);
}
@Override
public WasmStructuredInstructionBuilder enterCatch(
WasmTagName tagName,
PVector<WasmInstruction> instructions
) {
return new WasmTryCatchInstructionBuilder(
blockType,
instructions,
tagName,
P.vector()
);
}
}
private record WasmTryCatchInstructionBuilder(
WasmBlockType blockType,
List<WasmInstruction> tryBodyInstructions,
WasmTagName tagName,
PVector<WasmCatchBlock> catchBlocks
) implements WasmStructuredInstructionBuilder {
@Override
public WasmInstruction exit(PVector<WasmInstruction> instructions) {
return new WasmTry(
this.blockType,
this.catchBlocks.plus(new WasmCatchBlock(this.tagName, instructions)),
this.tryBodyInstructions
);
}
@Override
public WasmStructuredInstructionBuilder enterCatch(
WasmTagName tagName,
PVector<WasmInstruction> instructions
) {
return new WasmTryCatchInstructionBuilder(
this.blockType,
this.tryBodyInstructions,
tagName,
this.catchBlocks.plus(new WasmCatchBlock(this.tagName, instructions))
);
}
}
}
|