forked from tanishiking/scala-wasm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWasmBuilder.scala
1113 lines (964 loc) · 38.5 KB
/
WasmBuilder.scala
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
package wasm
package ir2wasm
import wasm4s._
import wasm4s.WasmContext._
import wasm4s.Names._
import wasm4s.Types._
import wasm4s.WasmInstr._
import TypeTransformer._
import org.scalajs.ir.{Trees => IRTrees}
import org.scalajs.ir.{Types => IRTypes}
import org.scalajs.ir.{Names => IRNames}
import org.scalajs.ir.{ClassKind, Position}
import org.scalajs.linker.interface.unstable.RuntimeClassNameMapperImpl
import org.scalajs.linker.standard.{CoreSpec, LinkedClass, LinkedTopLevelExport}
import collection.mutable
import java.awt.Window.Type
import _root_.wasm4s.Defaults
import EmbeddedConstants._
class WasmBuilder(coreSpec: CoreSpec) {
// val module = new WasmModule()
def genPrimitiveTypeDataGlobals()(implicit ctx: WasmContext): Unit = {
import WasmFieldName.typeData._
val primRefsWithTypeData = List(
IRTypes.VoidRef -> KindVoid,
IRTypes.BooleanRef -> KindBoolean,
IRTypes.CharRef -> KindChar,
IRTypes.ByteRef -> KindByte,
IRTypes.ShortRef -> KindShort,
IRTypes.IntRef -> KindInt,
IRTypes.LongRef -> KindLong,
IRTypes.FloatRef -> KindFloat,
IRTypes.DoubleRef -> KindDouble
)
for ((primRef, kind) <- primRefsWithTypeData) {
val typeDataFieldValues =
genTypeDataFieldValues(kind, specialInstanceTypes = 0, primRef, None, Nil)
val typeDataGlobal =
genTypeDataGlobal(primRef, WasmStructType.typeData, typeDataFieldValues, Nil)
ctx.addGlobal(typeDataGlobal)
}
}
def transformClassDef(clazz: LinkedClass)(implicit ctx: WasmContext) = {
val classInfo = ctx.getClassInfo(clazz.className)
if (!clazz.kind.isClass && classInfo.hasRuntimeTypeInfo) {
// Gen typeData -- for classes, we do it as part of the vtable generation
val typeRef = IRTypes.ClassRef(clazz.className)
val typeDataFieldValues = genTypeDataFieldValues(clazz, Nil)
val typeDataGlobal =
genTypeDataGlobal(typeRef, WasmStructType.typeData, typeDataFieldValues, Nil)
ctx.addGlobal(typeDataGlobal)
}
// Declare static fields
for {
field @ IRTrees.FieldDef(flags, name, _, ftpe) <- clazz.fields
if flags.namespace.isStatic
} {
val typ = transformType(ftpe)
val global = WasmGlobal(
WasmGlobalName.forStaticField(name.name),
typ,
WasmExpr(List(Defaults.defaultValue(typ))),
isMutable = true
)
ctx.addGlobal(global)
}
// Generate method implementations
for (method <- clazz.methods) {
if (method.body.isDefined)
genFunction(clazz, method)
}
clazz.kind match {
case ClassKind.ModuleClass => transformModuleClass(clazz)
case ClassKind.Class => transformClass(clazz)
case ClassKind.HijackedClass => transformHijackedClass(clazz)
case ClassKind.Interface => transformInterface(clazz)
case ClassKind.JSClass | ClassKind.JSModuleClass =>
transformJSClass(clazz)
case ClassKind.AbstractJSType | ClassKind.NativeJSClass | ClassKind.NativeJSModuleClass =>
() // nothing to do
}
}
def genArrayClasses()(implicit ctx: WasmContext): Unit = {
import WasmTypeName.WasmStructTypeName
// The vtable type is always the same as j.l.Object
val vtableTypeName = WasmStructTypeName.ObjectVTable
val vtableField = WasmStructField(
Names.WasmFieldName.vtable,
WasmRefType(vtableTypeName),
isMutable = false
)
val objectRef = IRTypes.ClassRef(IRNames.ObjectClass)
val typeRefsWithArrays: List[(IRTypes.NonArrayTypeRef, WasmStructTypeName, WasmArrayType)] =
List(
(IRTypes.BooleanRef, WasmStructTypeName.BooleanArray, WasmArrayType.i8Array),
(IRTypes.CharRef, WasmStructTypeName.CharArray, WasmArrayType.i16Array),
(IRTypes.ByteRef, WasmStructTypeName.ByteArray, WasmArrayType.i8Array),
(IRTypes.ShortRef, WasmStructTypeName.ShortArray, WasmArrayType.i16Array),
(IRTypes.IntRef, WasmStructTypeName.IntArray, WasmArrayType.i32Array),
(IRTypes.LongRef, WasmStructTypeName.LongArray, WasmArrayType.i64Array),
(IRTypes.FloatRef, WasmStructTypeName.FloatArray, WasmArrayType.f32Array),
(IRTypes.DoubleRef, WasmStructTypeName.DoubleArray, WasmArrayType.f64Array),
(objectRef, WasmStructTypeName.ObjectArray, WasmArrayType.anyArray)
)
for ((baseRef, structTypeName, underlyingArrayType) <- typeRefsWithArrays) {
val underlyingArrayField = WasmStructField(
WasmFieldName.arrayField,
WasmRefType(underlyingArrayType.name),
isMutable = false
)
val structType = WasmStructType(
structTypeName,
List(vtableField, WasmStructField.itables, underlyingArrayField),
Some(Names.WasmTypeName.WasmStructTypeName.forClass(IRNames.ObjectClass))
)
ctx.addGCType(structType)
HelperFunctions.genArrayCloneFunction(IRTypes.ArrayTypeRef(baseRef, 1))
}
genArrayClassItable()
}
def transformTopLevelExport(
topLevelExport: LinkedTopLevelExport
)(implicit ctx: WasmContext): Unit = {
topLevelExport.tree match {
case d: IRTrees.TopLevelJSClassExportDef => genDelayedTopLevelExport(d.exportName)
case d: IRTrees.TopLevelModuleExportDef => genDelayedTopLevelExport(d.exportName)
case d: IRTrees.TopLevelMethodExportDef => transformTopLevelMethodExportDef(d)
case d: IRTrees.TopLevelFieldExportDef => transformTopLevelFieldExportDef(d)
}
}
private def genTypeDataFieldValues(clazz: LinkedClass, vtableElems: List[WasmFunctionInfo])(
implicit ctx: WasmContext
): List[WasmInstr] = {
import WasmFieldName.typeData._
val className = clazz.className
val classInfo = ctx.getClassInfo(className)
val kind = className match {
case IRNames.ObjectClass => KindObject
case IRNames.BoxedUnitClass => KindBoxedUnit
case IRNames.BoxedBooleanClass => KindBoxedBoolean
case IRNames.BoxedCharacterClass => KindBoxedCharacter
case IRNames.BoxedByteClass => KindBoxedByte
case IRNames.BoxedShortClass => KindBoxedShort
case IRNames.BoxedIntegerClass => KindBoxedInteger
case IRNames.BoxedLongClass => KindBoxedLong
case IRNames.BoxedFloatClass => KindBoxedFloat
case IRNames.BoxedDoubleClass => KindBoxedDouble
case IRNames.BoxedStringClass => KindBoxedString
case _ =>
clazz.kind match {
case ClassKind.Class | ClassKind.ModuleClass | ClassKind.HijackedClass => KindClass
case ClassKind.Interface => KindInterface
case _ => KindJSType
}
}
val isJSClassInstanceFuncOpt = genIsJSClassInstanceFunction(clazz)
genTypeDataFieldValues(
kind,
classInfo.specialInstanceTypes,
IRTypes.ClassRef(clazz.className),
isJSClassInstanceFuncOpt,
vtableElems
)
}
private def genIsJSClassInstanceFunction(clazz: LinkedClass)(implicit
ctx: WasmContext
): Option[WasmFunctionName] = {
import org.scalajs.ir.OriginalName.NoOriginalName
implicit val noPos: Position = Position.NoPosition
def build(loadJSClass: (WasmFunctionContext) => Unit): WasmFunctionName = {
implicit val fctx = WasmFunctionContext(
WasmFunctionName.isJSClassInstance(clazz.className),
List("x" -> WasmRefType.anyref),
List(WasmInt32)
)
val List(xParam) = fctx.paramIndices
import fctx.instrs
if (clazz.kind == ClassKind.JSClass && !clazz.hasInstances) {
/* We need to constant-fold the instance test, to avoid trying to
* call $loadJSClass.className, since it will not exist at all.
*/
fctx.instrs += I32_CONST(0) // false
} else {
instrs += LOCAL_GET(xParam)
loadJSClass(fctx)
instrs += CALL(WasmFunctionName.jsBinaryOps(IRTrees.JSBinaryOp.instanceof))
instrs += CALL(WasmFunctionName.unbox(IRTypes.BooleanRef))
}
val func = fctx.buildAndAddToContext()
func.name
}
clazz.kind match {
case ClassKind.NativeJSClass =>
clazz.jsNativeLoadSpec.map { jsNativeLoadSpec =>
build { fctx =>
WasmExpressionBuilder.genLoadJSNativeLoadSpec(fctx, jsNativeLoadSpec)
}
}
case ClassKind.JSClass =>
if (clazz.jsClassCaptures.isEmpty) {
val funcName = build { fctx =>
fctx.instrs += CALL(WasmFunctionName.loadJSClass(clazz.className))
}
Some(funcName)
} else {
None
}
case _ =>
None
}
}
private def genTypeDataFieldValues(
kind: Int,
specialInstanceTypes: Int,
typeRef: IRTypes.NonArrayTypeRef,
isJSClassInstanceFuncOpt: Option[WasmFunctionName],
vtableElems: List[WasmFunctionInfo]
)(implicit
ctx: WasmContext
): List[WasmInstr] = {
val nameStr = typeRef match {
case typeRef: IRTypes.PrimRef =>
typeRef.displayName
case IRTypes.ClassRef(className) =>
RuntimeClassNameMapperImpl.map(
coreSpec.semantics.runtimeClassNameMapper,
className.nameString
)
}
val nameDataValueItems = nameStr.toList.map(c => I32_CONST(c.toInt))
val nameDataValueArrayNew =
ARRAY_NEW_FIXED(
WasmTypeName.WasmArrayTypeName.i16Array,
nameDataValueItems.size
)
val nameDataValue: List[WasmInstr] = nameDataValueItems :+ nameDataValueArrayNew
val strictAncestorsValue: List[WasmInstr] = {
typeRef match {
case IRTypes.ClassRef(className) =>
val ancestors = ctx.getClassInfo(className).ancestors
// By spec, the first element of `ancestors` is always the class itself
assert(
ancestors.headOption.contains(className),
s"The ancestors of ${className.nameString} do not start with itself: $ancestors"
)
val strictAncestors = ancestors.tail
val elems = for {
ancestor <- strictAncestors
if ctx.getClassInfo(ancestor).hasRuntimeTypeInfo
} yield {
GLOBAL_GET(WasmGlobalName.forVTable(ancestor))
}
elems :+ ARRAY_NEW_FIXED(
WasmTypeName.WasmArrayTypeName.typeDataArray,
elems.size
)
case _ =>
REF_NULL(WasmHeapType.None) :: Nil
}
}
val cloneFunction = {
val nullref = REF_NULL(WasmHeapType.NoFunc)
typeRef match {
case IRTypes.ClassRef(className) =>
val classInfo = ctx.getClassInfo(className)
// If the class is concrete and implements the `java.lang.Cloneable`,
// `HelperFunctions.genCloneFunction` should've generated the clone function
if (!classInfo.isAbstract && classInfo.ancestors.contains(IRNames.CloneableClass))
REF_FUNC(WasmFunctionName.clone(className))
else nullref
case _ => nullref
}
}
val isJSClassInstance = isJSClassInstanceFuncOpt match {
case None => REF_NULL(WasmHeapType.NoFunc)
case Some(funcName) => REF_FUNC(funcName)
}
val reflectiveProxies: List[WasmInstr] = {
val proxies = vtableElems.filter(_.isReflectiveProxy)
proxies.flatMap { method =>
val proxyId = ctx.getReflectiveProxyId(method.name.simpleName)
List(
I32_CONST(proxyId),
REF_FUNC(method.name),
STRUCT_NEW(Names.WasmTypeName.WasmStructTypeName.reflectiveProxy)
)
} :+ ARRAY_NEW_FIXED(Names.WasmTypeName.WasmArrayTypeName.reflectiveProxies, proxies.size)
}
nameDataValue :::
List(
// kind
I32_CONST(kind),
// specialInstanceTypes
I32_CONST(specialInstanceTypes)
) ::: (
// strictAncestors
strictAncestorsValue
) :::
List(
// componentType - always `null` since this method is not used for array types
REF_NULL(WasmHeapType(WasmTypeName.WasmStructTypeName.typeData)),
// name - initially `null`; filled in by the `typeDataName` helper
REF_NULL(WasmHeapType.Any),
// the classOf instance - initially `null`; filled in by the `createClassOf` helper
REF_NULL(WasmHeapType.ClassType),
// arrayOf, the typeData of an array of this type - initially `null`; filled in by the `arrayTypeData` helper
REF_NULL(WasmHeapType(WasmTypeName.WasmStructTypeName.ObjectVTable)),
// clonefFunction - will be invoked from `clone()` method invokaion on the class
cloneFunction,
// isJSClassInstance - invoked from the `isInstance()` helper for JS types
isJSClassInstance
) :::
// reflective proxies - used to reflective call on the class at runtime.
// Generated instructions create an array of reflective proxy structs, where each struct
// contains the ID of the reflective proxy and a reference to the actual method implementation.
reflectiveProxies
}
private def genTypeDataGlobal(
typeRef: IRTypes.NonArrayTypeRef,
typeDataType: WasmStructType,
typeDataFieldValues: List[WasmInstr],
vtableElems: List[REF_FUNC]
)(implicit ctx: WasmContext): WasmGlobal = {
val instrs: List[WasmInstr] =
typeDataFieldValues ::: vtableElems ::: STRUCT_NEW(typeDataType.name) :: Nil
WasmGlobal(
WasmGlobalName.forVTable(typeRef),
WasmRefType(typeDataType.name),
WasmExpr(instrs),
isMutable = false
)
}
/** @return
* Optionally returns the generated struct type for this class. If the given LinkedClass is an
* abstract class, returns None
*/
private def transformClassCommon(
clazz: LinkedClass
)(implicit ctx: WasmContext): WasmStructType = {
val className = clazz.name.name
val typeRef = IRTypes.ClassRef(className)
val classInfo = ctx.getClassInfo(className)
// generate vtable type, this should be done for both abstract and concrete classes
val vtable = ctx.calculateVtableType(className)
val vtableType = genVTableType(clazz, vtable.functions)
ctx.addGCType(vtableType)
val isAbstractClass = !clazz.hasDirectInstances
// we should't generate global vtable for abstract class because
// - Can't generate Global vtable because we can't fill the slot for abstract methods
// - We won't access vtable for abstract classes since we can't instantiate abstract classes, there's no point generating
//
// When we don't generate a vtable, we still generate the typeData
if (!isAbstractClass) {
// Generate an actual vtable
val functions = ctx.calculateGlobalVTable(className)
val typeDataFieldValues = genTypeDataFieldValues(clazz, functions)
val vtableElems = functions.map(method => WasmInstr.REF_FUNC(method.name))
val globalVTable = genTypeDataGlobal(typeRef, vtableType, typeDataFieldValues, vtableElems)
ctx.addGlobal(globalVTable)
genGlobalClassItable(clazz)
} else if (classInfo.hasRuntimeTypeInfo) {
// Only generate typeData
val typeDataFieldValues = genTypeDataFieldValues(clazz, Nil)
val globalTypeData =
genTypeDataGlobal(typeRef, WasmStructType.typeData, typeDataFieldValues, Nil)
ctx.addGlobal(globalTypeData)
}
// Declare the struct type for the class
val vtableField = WasmStructField(
Names.WasmFieldName.vtable,
WasmRefType(vtableType.name),
isMutable = false
)
val fields = classInfo.allFieldDefs.map(transformField)
val structType = WasmStructType(
Names.WasmTypeName.WasmStructTypeName.forClass(clazz.name.name),
vtableField +: WasmStructField.itables +: fields,
clazz.superClass.map(s => Names.WasmTypeName.WasmStructTypeName.forClass(s.name))
)
ctx.addGCType(structType)
// Define the `new` function, unless the class is abstract
if (!isAbstractClass) HelperFunctions.genNewDefault(clazz)
structType
}
private def genVTableType(clazz: LinkedClass, functions: List[WasmFunctionInfo])(implicit
ctx: WasmContext
): WasmStructType = {
val vtableFields =
functions.map { method =>
WasmStructField(
Names.WasmFieldName.forMethodTableEntry(method.name),
WasmRefType.nullable(method.toWasmFunctionType().name),
isMutable = false
)
}
val superType = clazz.superClass match {
case None => WasmTypeName.WasmStructTypeName.typeData
case Some(s) => WasmTypeName.WasmStructTypeName.forVTable(s.name)
}
WasmStructType(
Names.WasmTypeName.WasmStructTypeName.forVTable(clazz.name.name),
WasmStructType.typeData.fields ::: vtableFields,
Some(superType)
)
}
private def genLoadModuleFunc(clazz: LinkedClass)(implicit ctx: WasmContext): Unit = {
assert(clazz.kind == ClassKind.ModuleClass)
val ctor = clazz.methods
.find(_.methodName.isConstructor)
.getOrElse(throw new Error(s"Module class should have a constructor, ${clazz.name}"))
val typeName = WasmTypeName.WasmStructTypeName.forClass(clazz.name.name)
val globalInstanceName = WasmGlobalName.forModuleInstance(clazz.name.name)
val ctorName = WasmFunctionName(
ctor.flags.namespace,
clazz.name.name,
ctor.name.name
)
val body = List(
// global.get $module_name
// ref.if_null
// ref.null $module_type
// call $module_init ;; should set to global
// end
// global.get $module_name
GLOBAL_GET(globalInstanceName), // [rt]
REF_IS_NULL, // [rt] -> [i32] (bool)
IF(BlockType.ValueType()),
CALL(WasmFunctionName.newDefault(clazz.name.name)),
GLOBAL_SET(globalInstanceName),
GLOBAL_GET(globalInstanceName),
CALL(ctorName),
// ELSE,
END,
GLOBAL_GET(globalInstanceName) // [rt]
)
val sig =
WasmFunctionSignature(Nil, List(WasmRefType.nullable(typeName)))
val loadModuleTypeName = ctx.addFunctionType(sig)
val func = WasmFunction(
WasmFunctionName.loadModule(clazz.name.name),
WasmFunctionType(loadModuleTypeName, sig),
Nil,
WasmExpr(body)
)
ctx.addFunction(func)
}
/** Generate global instance of the class itable. Their init value will be an array of null refs
* of size = number of interfaces. They will be initialized in start function
*/
private def genGlobalClassItable(
clazz: LinkedClass
)(implicit ctx: WasmContext): Unit = {
val info = ctx.getClassInfo(clazz.className)
val implementsAnyInterface = info.ancestors.exists(a => ctx.getClassInfo(a).isInterface)
if (implementsAnyInterface) {
val globalName = WasmGlobalName.forITable(clazz.className)
ctx.addGlobalITable(clazz.className, genITableGlobal(globalName))
}
}
private def genArrayClassItable()(implicit ctx: WasmContext): Unit =
ctx.addGlobal(genITableGlobal(WasmGlobalName.arrayClassITable))
private def genITableGlobal(name: WasmGlobalName)(implicit ctx: WasmContext): WasmGlobal = {
val itablesInit = List(
I32_CONST(ctx.itablesLength),
ARRAY_NEW_DEFAULT(WasmArrayType.itables.name)
)
WasmGlobal(
name,
WasmRefType(WasmArrayType.itables.name),
init = WasmExpr(itablesInit),
isMutable = false
)
}
private def transformClass(clazz: LinkedClass)(implicit ctx: WasmContext): Unit = {
assert(clazz.kind == ClassKind.Class)
transformClassCommon(clazz)
}
private def transformHijackedClass(clazz: LinkedClass)(implicit ctx: WasmContext): Unit = {
// nothing to do
()
}
private def transformInterface(clazz: LinkedClass)(implicit ctx: WasmContext): Unit = {
assert(clazz.kind == ClassKind.Interface)
// gen itable type
val className = clazz.name.name
val classInfo = ctx.getClassInfo(clazz.className)
val itableType = WasmStructType(
Names.WasmTypeName.WasmStructTypeName.forITable(className),
classInfo.methods.map { m =>
WasmStructField(
Names.WasmFieldName(m.name.simpleName),
WasmRefType.nullable(m.toWasmFunctionType().name),
isMutable = false
)
},
None
)
ctx.addGCType(itableType)
// typeName
// genITable
// generateVTable()
}
private def transformModuleClass(clazz: LinkedClass)(implicit ctx: WasmContext) = {
assert(clazz.kind == ClassKind.ModuleClass)
val structType = transformClassCommon(clazz)
val heapType = WasmHeapType(structType.name)
if (clazz.hasInstances) {
// global instance
// (global name (ref null type))
val global = WasmGlobal(
Names.WasmGlobalName.forModuleInstance(clazz.name.name),
WasmRefType.nullable(heapType),
WasmExpr(List(REF_NULL(heapType))),
isMutable = true
)
ctx.addGlobal(global)
genLoadModuleFunc(clazz)
}
}
private def transformJSClass(clazz: LinkedClass)(implicit ctx: WasmContext): Unit = {
assert(clazz.kind.isJSClass)
// Define the globals holding the Symbols of private fields
for (fieldDef <- clazz.fields) {
fieldDef match {
case IRTrees.FieldDef(flags, name, _, _) if !flags.namespace.isStatic =>
ctx.addGlobal(
WasmGlobal(
WasmGlobalName.forJSPrivateField(name.name),
WasmRefType.anyref,
WasmExpr(List(REF_NULL(WasmHeapType.Any))),
isMutable = true
)
)
ctx.addJSPrivateFieldName(name.name)
case _ =>
()
}
}
if (clazz.hasInstances) {
genCreateJSClassFunction(clazz)
if (clazz.jsClassCaptures.isEmpty)
genLoadJSClassFunction(clazz)
if (clazz.kind == ClassKind.JSModuleClass)
genLoadJSModuleFunction(clazz)
}
}
private def genCreateJSClassFunction(clazz: LinkedClass)(implicit ctx: WasmContext): Unit = {
implicit val noPos: Position = Position.NoPosition
val jsClassCaptures = clazz.jsClassCaptures.getOrElse(Nil)
/* We need to decompose the body of the constructor into 3 closures.
* Given an IR constructor of the form
* constructor(...params) {
* preSuperStats;
* super(...superArgs);
* postSuperStats;
* }
* We will create closures for `preSuperStats`, `superArgs` and `postSuperStats`.
*
* There is one huge catch: `preSuperStats` can declare `VarDef`s at its top-level,
* and those vars are still visible inside `superArgs` and `postSuperStats`.
* The `preSuperStats` must therefore return a struct with the values of its
* declared vars, which will be given as an additional argument to `superArgs`
* and `postSuperStats`. We call that struct the `preSuperEnv`.
*
* In the future, we should optimize `preSuperEnv` to only store locals that
* are still used by `superArgs` and/or `postSuperArgs`.
*/
val ctor = clazz.jsConstructorDef.get
val allCtorParams = ctor.args ::: ctor.restParam.toList
val ctorBody = ctor.body
// Compute the pre-super environment
val preSuperDecls = ctorBody.beforeSuper.collect { case varDef: IRTrees.VarDef =>
varDef
}
// Build the `preSuperStats` function
val preSuperStatsFun = {
val preSuperEnvStructType = ctx.getClosureDataStructType(preSuperDecls.map(_.vtpe))
val preSuperEnvTyp = WasmRefType(preSuperEnvStructType.name)
implicit val fctx = WasmFunctionContext(
Some(clazz.className),
WasmFunctionName.preSuperStats(clazz.className),
Some(jsClassCaptures),
preSuperVarDefs = None,
hasNewTarget = true,
receiverTyp = None,
allCtorParams,
List(preSuperEnvTyp)
)
import fctx.instrs
WasmExpressionBuilder.generateBlockStats(ctorBody.beforeSuper) {
// Build and return the preSuperEnv struct
for (varDef <- preSuperDecls)
instrs += LOCAL_GET(fctx.lookupLocalAssertLocalStorage(varDef.name.name))
instrs += STRUCT_NEW(preSuperEnvStructType.name)
}
fctx.buildAndAddToContext()
}
// Build the `superArgs` function
val superArgsFun = {
implicit val fctx = WasmFunctionContext(
Some(clazz.className),
WasmFunctionName.superArgs(clazz.className),
Some(jsClassCaptures),
Some(preSuperDecls),
hasNewTarget = true,
receiverTyp = None,
allCtorParams,
List(WasmRefType.anyref) // a js.Array
)
WasmExpressionBuilder.generateIRBody(
IRTrees.JSArrayConstr(ctorBody.superCall.args),
IRTypes.AnyType
)
fctx.buildAndAddToContext()
}
// Build the `postSuperStats` function
val postSuperStatsFun = {
implicit val fctx = WasmFunctionContext(
Some(clazz.className),
WasmFunctionName.postSuperStats(clazz.className),
Some(jsClassCaptures),
Some(preSuperDecls),
hasNewTarget = true,
receiverTyp = Some(WasmRefType.anyref),
allCtorParams,
List(WasmRefType.anyref)
)
import fctx.instrs
// Create fields
for (fieldDef <- clazz.fields if !fieldDef.flags.namespace.isStatic) {
// Load instance
instrs += LOCAL_GET(fctx.receiverStorage.idx)
// Load name
fieldDef match {
case IRTrees.FieldDef(_, name, _, _) =>
instrs += GLOBAL_GET(WasmGlobalName.forJSPrivateField(name.name))
case IRTrees.JSFieldDef(_, nameTree, _) =>
WasmExpressionBuilder.generateIRBody(nameTree, IRTypes.AnyType)
}
// Generate boxed representation of the zero of the field
WasmExpressionBuilder.generateIRBody(IRTypes.zeroOf(fieldDef.ftpe), IRTypes.AnyType)
instrs += CALL(WasmFunctionName.installJSField)
}
WasmExpressionBuilder.generateIRBody(
IRTrees.Block(ctorBody.afterSuper),
IRTypes.AnyType
)
fctx.buildAndAddToContext()
}
// Build the actual `createJSClass` function
val createJSClassFun = {
implicit val fctx = WasmFunctionContext(
Some(clazz.className),
WasmFunctionName.createJSClassOf(clazz.className),
None,
None,
jsClassCaptures,
List(WasmRefType.any)
)
import fctx.instrs
// Bundle class captures in a capture data struct -- leave it on the stack for createJSClass
val dataStructType = ctx.getClosureDataStructType(jsClassCaptures.map(_.ptpe))
val dataStructLocal = fctx.addLocal(
"__classCaptures",
WasmRefType(dataStructType.name)
)
for (cc <- jsClassCaptures)
instrs += LOCAL_GET(fctx.lookupLocalAssertLocalStorage(cc.name.name))
instrs += STRUCT_NEW(dataStructType.name)
instrs += LOCAL_TEE(dataStructLocal)
/* Load super constructor; specified by
* https://lampwww.epfl.ch/~doeraene/sjsir-semantics/#sec-sjsir-classdef-runtime-semantics-evaluation
* - if `jsSuperClass` is defined, evaluate it;
* - otherwise evaluate `LoadJSConstructor` of the declared superClass.
*/
val jsSuperClassTree = clazz.jsSuperClass.getOrElse {
IRTrees.LoadJSConstructor(clazz.superClass.get.name)
}
WasmExpressionBuilder.generateIRBody(jsSuperClassTree, IRTypes.AnyType)
// Load the references to the 3 functions that make up the constructor
instrs += ctx.refFuncWithDeclaration(preSuperStatsFun.name)
instrs += ctx.refFuncWithDeclaration(superArgsFun.name)
instrs += ctx.refFuncWithDeclaration(postSuperStatsFun.name)
// Call the createJSClass helper to bundle everything
if (ctor.restParam.isDefined) {
instrs += I32_CONST(ctor.args.size) // number of fixed params
instrs += CALL(WasmFunctionName.createJSClassRest)
} else {
instrs += CALL(WasmFunctionName.createJSClass)
}
// Store the result, locally and possibly in the global cache
val jsClassLocal = fctx.addLocal("__jsClass", WasmRefType.any)
if (clazz.jsClassCaptures.isEmpty) {
// Static JS class with a global cache
instrs += LOCAL_TEE(jsClassLocal)
instrs += GLOBAL_SET(WasmGlobalName.forJSClassValue(clazz.className))
} else {
// Local or inner JS class, which is new every time
instrs += LOCAL_SET(jsClassLocal)
}
// Install methods and properties
for (methodOrProp <- clazz.exportedMembers) {
val isStatic = methodOrProp.flags.namespace.isStatic
instrs += LOCAL_GET(dataStructLocal)
instrs += LOCAL_GET(jsClassLocal)
val receiverTyp = if (isStatic) None else Some(WasmRefType.anyref)
methodOrProp match {
case IRTrees.JSMethodDef(flags, nameTree, params, restParam, body) =>
WasmExpressionBuilder.generateIRBody(nameTree, IRTypes.AnyType)
val closureFuncName = fctx.genInnerFuncName()
locally {
implicit val fctx: WasmFunctionContext = WasmFunctionContext(
Some(clazz.className),
closureFuncName,
Some(jsClassCaptures),
receiverTyp,
params ::: restParam.toList,
List(WasmRefType.anyref)
)
WasmExpressionBuilder.generateIRBody(body, IRTypes.AnyType)
fctx.buildAndAddToContext()
}
instrs += ctx.refFuncWithDeclaration(closureFuncName)
instrs += I32_CONST(if (restParam.isDefined) params.size else -1)
if (isStatic)
instrs += CALL(WasmFunctionName.installJSStaticMethod)
else
instrs += CALL(WasmFunctionName.installJSMethod)
case IRTrees.JSPropertyDef(flags, nameTree, optGetter, optSetter) =>
WasmExpressionBuilder.generateIRBody(nameTree, IRTypes.AnyType)
optGetter match {
case None =>
instrs += REF_NULL(WasmHeapType.Func)
case Some(getterBody) =>
val closureFuncName = fctx.genInnerFuncName()
locally {
implicit val fctx: WasmFunctionContext = WasmFunctionContext(
Some(clazz.className),
closureFuncName,
Some(jsClassCaptures),
receiverTyp,
Nil,
List(WasmRefType.anyref)
)
WasmExpressionBuilder.generateIRBody(getterBody, IRTypes.AnyType)
fctx.buildAndAddToContext()
}
instrs += ctx.refFuncWithDeclaration(closureFuncName)
}
optSetter match {
case None =>
instrs += REF_NULL(WasmHeapType.Func)
case Some((setterParamDef, setterBody)) =>
val closureFuncName = fctx.genInnerFuncName()
locally {
implicit val fctx: WasmFunctionContext = WasmFunctionContext(
Some(clazz.className),
closureFuncName,
Some(jsClassCaptures),
receiverTyp,
setterParamDef :: Nil,
Nil
)
WasmExpressionBuilder.generateIRBody(setterBody, IRTypes.NoType)
fctx.buildAndAddToContext()
}
instrs += ctx.refFuncWithDeclaration(closureFuncName)
}
if (isStatic)
instrs += CALL(WasmFunctionName.installJSStaticProperty)
else
instrs += CALL(WasmFunctionName.installJSProperty)
}
}
// Static fields
for (fieldDef <- clazz.fields if fieldDef.flags.namespace.isStatic) {
// Load class value
instrs += LOCAL_GET(jsClassLocal)
// Load name
fieldDef match {
case IRTrees.FieldDef(_, name, _, _) =>
throw new AssertionError(
s"Unexpected private static field ${name.name.nameString} "
+ s"in JS class ${clazz.className.nameString}"
)
case IRTrees.JSFieldDef(_, nameTree, _) =>
WasmExpressionBuilder.generateIRBody(nameTree, IRTypes.AnyType)
}
// Generate boxed representation of the zero of the field
WasmExpressionBuilder.generateIRBody(IRTypes.zeroOf(fieldDef.ftpe), IRTypes.AnyType)
instrs += CALL(WasmFunctionName.installJSField)
}
// Class initializer
for (classInit <- clazz.methods.find(_.methodName.isClassInitializer)) {
assert(
clazz.jsClassCaptures.isEmpty,
s"Illegal class initializer in non-static class ${clazz.className.nameString}"
)
val namespace = IRTrees.MemberNamespace.StaticConstructor
instrs += CALL(WasmFunctionName(namespace, clazz.className, IRNames.ClassInitializerName))
}
// Final result
instrs += LOCAL_GET(jsClassLocal)
fctx.buildAndAddToContext()
}
}
private def genLoadJSClassFunction(clazz: LinkedClass)(implicit ctx: WasmContext): Unit = {
val cachedJSClassGlobal = WasmGlobal(
WasmGlobalName.forJSClassValue(clazz.className),
WasmRefType.anyref,
WasmExpr(List(REF_NULL(WasmHeapType.Any))),
isMutable = true
)
ctx.addGlobal(cachedJSClassGlobal)
val fctx = WasmFunctionContext(
Some(clazz.className),
WasmFunctionName.loadJSClass(clazz.className),
None,
Nil,
List(WasmRefType.any)
)
import fctx.instrs
fctx.block(WasmRefType.any) { doneLabel =>
// Load cached JS class, return if non-null
instrs += GLOBAL_GET(cachedJSClassGlobal.name)
instrs += BR_ON_NON_NULL(doneLabel)
// Otherwise, call createJSClass -- it will also store the class in the cache
instrs += CALL(WasmFunctionName.createJSClassOf(clazz.className))
}
fctx.buildAndAddToContext()
}
private def genLoadJSModuleFunction(clazz: LinkedClass)(implicit ctx: WasmContext): Unit = {
val className = clazz.className
val cacheGlobalName = WasmGlobalName.forModuleInstance(className)
ctx.addGlobal(
WasmGlobal(
cacheGlobalName,
WasmRefType.anyref,
WasmExpr(List(REF_NULL(WasmHeapType.Any))),
isMutable = true
)
)
val fctx = WasmFunctionContext(
WasmFunctionName.loadModule(className),
Nil,
List(WasmRefType.anyref)
)
import fctx.instrs
fctx.block(WasmRefType.anyref) { doneLabel =>
// Load cached instance; return if non-null
instrs += GLOBAL_GET(cacheGlobalName)
instrs += BR_ON_NON_NULL(doneLabel)
// Get the JS class and instantiate it
instrs += CALL(WasmFunctionName.loadJSClass(className))
instrs += CALL(WasmFunctionName.jsNewArray)
instrs += CALL(WasmFunctionName.jsNew)
// Store and return the result
instrs += GLOBAL_SET(cacheGlobalName)
instrs += GLOBAL_GET(cacheGlobalName)
}
fctx.buildAndAddToContext()
}
private def transformTopLevelMethodExportDef(
exportDef: IRTrees.TopLevelMethodExportDef