forked from tanishiking/scala-wasm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWasmContext.scala
900 lines (792 loc) · 31.8 KB
/
WasmContext.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
package wasm.wasm4s
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.LinkedHashMap
import Names._
import Names.WasmTypeName._
import Types._
import org.scalajs.ir.{Names => IRNames}
import org.scalajs.ir.{Types => IRTypes}
import org.scalajs.ir.{Trees => IRTrees}
import org.scalajs.ir.{ClassKind, Position}
import wasm.ir2wasm.TypeTransformer
import wasm.ir2wasm.WasmExpressionBuilder
import org.scalajs.linker.interface.ModuleInitializer
import org.scalajs.linker.interface.unstable.ModuleInitializerImpl
import org.scalajs.linker.standard.LinkedTopLevelExport
import java.nio.charset.StandardCharsets
trait ReadOnlyWasmContext {
import WasmContext._
protected val gcTypes = new WasmSymbolTable[WasmTypeName, WasmGCTypeDefinition]()
protected val functions = new WasmSymbolTable[WasmFunctionName, WasmFunction]()
protected val globals = new WasmSymbolTable[WasmGlobalName, WasmGlobal]()
protected val itableIdx = mutable.Map[IRNames.ClassName, Int]()
protected val classInfo = mutable.Map[IRNames.ClassName, WasmClassInfo]()
private val vtablesCache = mutable.Map[IRNames.ClassName, WasmVTable]()
protected var nextItableIdx: Int
val cloneFunctionTypeName: WasmFunctionTypeName
val isJSClassInstanceFuncTypeName: WasmFunctionTypeName
def itablesLength = nextItableIdx
/** Get an index of the itable for the given interface. The itable instance must be placed at the
* index in the array of itables (whose size is `itablesLength`).
*/
def getItableIdx(iface: IRNames.ClassName): Int =
itableIdx.getOrElse(
iface,
throw new IllegalArgumentException(s"Interface $iface is not registed.")
)
def getClassInfoOption(name: IRNames.ClassName): Option[WasmClassInfo] =
classInfo.get(name)
def getClassInfo(name: IRNames.ClassName): WasmClassInfo =
classInfo.getOrElse(name, throw new Error(s"Class not found: $name"))
def inferTypeFromTypeRef(typeRef: IRTypes.TypeRef): IRTypes.Type = typeRef match {
case IRTypes.PrimRef(tpe) =>
tpe
case IRTypes.ClassRef(className) =>
if (className == IRNames.ObjectClass || getClassInfo(className).kind.isJSType)
IRTypes.AnyType
else
IRTypes.ClassType(className)
case typeRef: IRTypes.ArrayTypeRef =>
IRTypes.ArrayType(typeRef)
}
/** Collects all methods declared and inherited by the given class, super-class.
*
* @param className
* class to collect methods from
* @param includeAbstractMethods
* whether to include abstract methods
* @return
* list of methods in order that "collectVTableMethods(superClass) ++ methods from the class"
*/
private def collectVTableMethods(
className: IRNames.ClassName,
includeAbstractMethods: Boolean
): List[WasmFunctionInfo] = {
val info = classInfo.getOrElse(className, throw new Error(s"Class not found: $className"))
assert(
info.kind.isClass || info.kind == ClassKind.HijackedClass,
s"collectVTableMethods cannot be called for non-class ${className.nameString}"
)
val fromSuperClass =
info.superClass.map(collectVTableMethods(_, includeAbstractMethods)).getOrElse(Nil)
fromSuperClass ++
(if (includeAbstractMethods) info.methods
else info.methods.filterNot(_.isAbstract))
}
def calculateGlobalVTable(name: IRNames.ClassName): List[WasmFunctionInfo] = {
val vtableType = calculateVtableType(name)
// Do not include abstract methods when calculating vtable instance,
// all slots should be filled with the function reference to the concrete methods
val methodsReverse = collectVTableMethods(name, includeAbstractMethods = false).reverse
vtableType.functions.map { slot =>
methodsReverse
.find(_.name.simpleName == slot.name.simpleName)
.getOrElse(throw new Error(s"No implementation found for ${slot.name} in ${name}"))
}
}
def calculateVtableType(name: IRNames.ClassName): WasmVTable = {
vtablesCache.getOrElseUpdate(
name, {
val functions =
collectVTableMethods(name, includeAbstractMethods = true)
.foldLeft(Array.empty[WasmFunctionInfo]) { case (acc, m) =>
acc.indexWhere(_.name.simpleName == m.name.simpleName) match {
case i if i < 0 => acc :+ m
case i => if (m.isAbstract) acc else acc.updated(i, m)
}
}
.toList
WasmVTable(functions)
}
)
}
}
case class StringData(
constantStringIndex: Int,
offset: Int
)
trait TypeDefinableWasmContext extends ReadOnlyWasmContext { this: WasmContext =>
protected val functionSignatures = LinkedHashMap.empty[WasmFunctionSignature, Int]
protected val constantStringGlobals = LinkedHashMap.empty[String, StringData]
protected val classItableGlobals = LinkedHashMap.empty[IRNames.ClassName, WasmGlobalName]
protected val closureDataTypes = LinkedHashMap.empty[List[IRTypes.Type], WasmStructType]
protected val reflectiveProxies = LinkedHashMap.empty[String, Int]
protected var stringPool = new mutable.ArrayBuffer[Byte]()
protected var nextConstantStringIndex: Int = 0
private var nextConstatnStringOffset: Int = 0
private var nextArrayTypeIndex: Int = 1
private var nextClosureDataTypeIndex: Int = 1
private var nextReflectiveProxyIdx: Int = 0
def addFunction(fun: WasmFunction): Unit
protected def addGlobal(g: WasmGlobal): Unit
def getImportedModuleGlobal(moduleName: String): WasmGlobalName
protected def addFuncDeclaration(name: WasmFunctionName): Unit
/** Retrieves a unique identifier for a reflective proxy with the given name */
def getReflectiveProxyId(name: String): Int =
reflectiveProxies.getOrElseUpdate(
name, {
val idx = nextReflectiveProxyIdx
nextReflectiveProxyIdx += 1
idx
}
)
val cloneFunctionTypeName: WasmFunctionTypeName =
addFunctionType(
WasmFunctionSignature(
List(WasmRefType(WasmHeapType.ObjectType)),
List(WasmRefType(WasmHeapType.ObjectType))
)
)
val isJSClassInstanceFuncTypeName: WasmFunctionTypeName =
addFunctionType(WasmFunctionSignature(List(WasmRefType.anyref), List(WasmInt32)))
val exceptionTagName: WasmTagName
def addFunctionType(sig: WasmFunctionSignature): WasmFunctionTypeName = {
functionSignatures.get(sig) match {
case None =>
val idx = functionSignatures.size
functionSignatures.update(sig, idx)
val typeName = WasmFunctionTypeName(idx)
val ty = WasmFunctionType(typeName, sig)
module.addFunctionType(ty)
typeName
case Some(value) => WasmFunctionTypeName(value)
}
}
def addConstantStringGlobal(str: String): StringData = {
constantStringGlobals.get(str) match {
case Some(data) =>
data
case None =>
val bytes = encodeStringToWTF16LE(str)
val offset = nextConstatnStringOffset
val data = StringData(nextConstantStringIndex, offset)
constantStringGlobals(str) = data
stringPool ++= bytes
nextConstantStringIndex += 1
nextConstatnStringOffset += bytes.length
data
}
}
def getConstantStringInstr(str: String): List[WasmInstr] = {
val data = addConstantStringGlobal(str)
List(
WasmInstr.I32_CONST(data.offset),
// Assuming that the stringLiteral method will instantiate the
// constant string from the data section using "array.newData $i16Array ..."
// The length of the array should be equal to the length of the WTF-16 encoded string
WasmInstr.I32_CONST(str.length()),
WasmInstr.I32_CONST(data.constantStringIndex),
WasmInstr.CALL(WasmFunctionName.stringLiteral)
)
}
def getClosureDataStructType(captureParamTypes: List[IRTypes.Type]): WasmStructType = {
closureDataTypes.getOrElseUpdate(
captureParamTypes, {
val fields: List[WasmStructField] =
for ((tpe, i) <- captureParamTypes.zipWithIndex)
yield WasmStructField(
WasmFieldName.captureParam(i),
TypeTransformer.transformType(tpe)(this),
isMutable = false
)
val structTypeName = WasmStructTypeName.captureData(nextClosureDataTypeIndex)
nextClosureDataTypeIndex += 1
val structType = WasmStructType(structTypeName, fields, superType = None)
addGCType(structType)
structType
}
)
}
def refFuncWithDeclaration(name: WasmFunctionName): WasmInstr.REF_FUNC = {
addFuncDeclaration(name)
WasmInstr.REF_FUNC(name)
}
private def extractArrayElemType(typeRef: IRTypes.ArrayTypeRef): IRTypes.Type = {
if (typeRef.dimensions > 1) IRTypes.ArrayType(typeRef.copy(dimensions = typeRef.dimensions - 1))
else inferTypeFromTypeRef(typeRef.base)
}
/** http://simonsapin.github.io/wtf-8/#encoding-ill-formed-utf-16
*/
private def encodeStringToWTF16LE(input: String): Array[Byte] = {
val result = scala.collection.mutable.ArrayBuffer[Int]()
var i = 0
while (i < input.length) {
val codePoint = input.codePointAt(i)
if (codePoint < 0x10000) {
// BMP code point
result += codePoint
i += Character.charCount(codePoint)
} else {
// Supplementary code point
val highSurrogate = ((codePoint - 0x10000) >> 10) + 0xD800
val lowSurrogate = ((codePoint - 0x10000) & 0x3FF) + 0xDC00
result += highSurrogate
result += lowSurrogate
i += 2
}
}
result
.flatMap(codeUnit => Seq((codeUnit & 0xFF).toByte, ((codeUnit >> 8) & 0xFF).toByte))
.toArray
}
}
class WasmContext(val module: WasmModule) extends TypeDefinableWasmContext {
import WasmContext._
import WasmRefType.anyref
private val _importedModules: mutable.LinkedHashSet[String] =
new mutable.LinkedHashSet()
override protected var nextItableIdx: Int = 0
private val _jsPrivateFieldNames: mutable.ListBuffer[IRNames.FieldName] =
new mutable.ListBuffer()
private val _funcDeclarations: mutable.LinkedHashSet[WasmFunctionName] =
new mutable.LinkedHashSet()
def addExport(exprt: WasmExport): Unit = module.addExport(exprt)
def addFunction(fun: WasmFunction): Unit = {
module.addFunction(fun)
functions.define(fun)
}
def addGCType(ty: WasmStructType): Unit = {
module.addRecGroupType(ty)
gcTypes.define(ty)
}
def addGlobalITable(name: IRNames.ClassName, g: WasmGlobal): Unit = {
classItableGlobals.put(name, g.name)
module.addGlobal(g)
globals.define(g)
}
def addGlobal(g: WasmGlobal): Unit = {
module.addGlobal(g)
globals.define(g)
}
def getImportedModuleGlobal(moduleName: String): WasmGlobalName = {
val name = WasmGlobalName.forImportedModule(moduleName)
if (_importedModules.add(moduleName)) {
module.addImport(
WasmImport(
"__scalaJSImports",
moduleName,
WasmImportDesc.Global(name, anyref, isMutable = false)
)
)
}
name
}
def allImportedModules: List[String] = _importedModules.toList
def addFuncDeclaration(name: WasmFunctionName): Unit =
_funcDeclarations += name
def putClassInfo(name: IRNames.ClassName, info: WasmClassInfo): Unit = {
classInfo.put(name, info)
if (info.isInterface) {
itableIdx.put(name, nextItableIdx)
nextItableIdx += 1
}
}
def addJSPrivateFieldName(fieldName: IRNames.FieldName): Unit =
_jsPrivateFieldNames += fieldName
val exceptionTagName: WasmTagName = WasmTagName("exception")
locally {
val exceptionSig = WasmFunctionSignature(List(WasmRefType.externref), Nil)
val typ = WasmFunctionType(addFunctionType(exceptionSig), exceptionSig)
module.addImport(
WasmImport("__scalaJSHelpers", "JSTag", WasmImportDesc.Tag(exceptionTagName, typ))
)
}
private def addHelperImport(
name: WasmFunctionName,
params: List[WasmType],
results: List[WasmType]
): Unit = {
val sig = WasmFunctionSignature(params, results)
val typ = WasmFunctionType(addFunctionType(sig), sig)
module.addImport(WasmImport(name.namespace, name.simpleName, WasmImportDesc.Func(name, typ)))
}
private def addGlobalHelperImport(
name: WasmGlobalName,
typ: WasmType,
isMutable: Boolean
): Unit = {
module.addImport(
WasmImport(
"__scalaJSHelpers",
name.name,
WasmImportDesc.Global(name, typ, isMutable)
)
)
}
addGCType(WasmStructType.typeData(this))
addGCType(WasmStructType.reflectiveProxy)
addHelperImport(WasmFunctionName.is, List(anyref, anyref), List(WasmInt32))
addHelperImport(WasmFunctionName.undef, List(), List(WasmRefType.any))
addHelperImport(WasmFunctionName.isUndef, List(anyref), List(WasmInt32))
locally {
import IRTypes._
for (primRef <- List(BooleanRef, ByteRef, ShortRef, IntRef, FloatRef, DoubleRef)) {
val wasmType = primRef match {
case FloatRef => WasmFloat32
case DoubleRef => WasmFloat64
case _ => WasmInt32
}
addHelperImport(WasmFunctionName.box(primRef), List(wasmType), List(anyref))
addHelperImport(WasmFunctionName.unbox(primRef), List(anyref), List(wasmType))
addHelperImport(WasmFunctionName.unboxOrNull(primRef), List(anyref), List(anyref))
addHelperImport(WasmFunctionName.typeTest(primRef), List(anyref), List(WasmInt32))
}
}
addHelperImport(WasmFunctionName.fmod, List(WasmFloat64, WasmFloat64), List(WasmFloat64))
addHelperImport(
WasmFunctionName.closure,
List(WasmRefType.func, anyref),
List(WasmRefType.any)
)
addHelperImport(
WasmFunctionName.closureThis,
List(WasmRefType.func, anyref),
List(WasmRefType.any)
)
addHelperImport(
WasmFunctionName.closureRest,
List(WasmRefType.func, anyref, WasmInt32),
List(WasmRefType.any)
)
addHelperImport(
WasmFunctionName.closureThisRest,
List(WasmRefType.func, anyref, WasmInt32),
List(WasmRefType.any)
)
addHelperImport(
WasmFunctionName.closureRestNoData,
List(WasmRefType.func, WasmInt32),
List(WasmRefType.any)
)
addHelperImport(WasmFunctionName.emptyString, List(), List(WasmRefType.any))
addHelperImport(WasmFunctionName.stringLength, List(WasmRefType.any), List(WasmInt32))
addHelperImport(WasmFunctionName.stringCharAt, List(WasmRefType.any, WasmInt32), List(WasmInt32))
addHelperImport(WasmFunctionName.jsValueToString, List(WasmRefType.any), List(WasmRefType.any))
addHelperImport(WasmFunctionName.jsValueToStringForConcat, List(anyref), List(WasmRefType.any))
addHelperImport(WasmFunctionName.booleanToString, List(WasmInt32), List(WasmRefType.any))
addHelperImport(WasmFunctionName.charToString, List(WasmInt32), List(WasmRefType.any))
addHelperImport(WasmFunctionName.intToString, List(WasmInt32), List(WasmRefType.any))
addHelperImport(WasmFunctionName.longToString, List(WasmInt64), List(WasmRefType.any))
addHelperImport(WasmFunctionName.doubleToString, List(WasmFloat64), List(WasmRefType.any))
addHelperImport(
WasmFunctionName.stringConcat,
List(WasmRefType.any, WasmRefType.any),
List(WasmRefType.any)
)
addHelperImport(WasmFunctionName.isString, List(anyref), List(WasmInt32))
addHelperImport(WasmFunctionName.jsValueType, List(WasmRefType.any), List(WasmInt32))
addHelperImport(WasmFunctionName.bigintHashCode, List(WasmRefType.any), List(WasmInt32))
addHelperImport(
WasmFunctionName.symbolDescription,
List(WasmRefType.any),
List(WasmRefType.anyref)
)
addHelperImport(
WasmFunctionName.idHashCodeGet,
List(WasmRefType.extern, WasmRefType.any),
List(WasmInt32)
)
addHelperImport(
WasmFunctionName.idHashCodeSet,
List(WasmRefType.extern, WasmRefType.any, WasmInt32),
Nil
)
addHelperImport(WasmFunctionName.jsGlobalRefGet, List(WasmRefType.any), List(anyref))
addHelperImport(WasmFunctionName.jsGlobalRefSet, List(WasmRefType.any, anyref), Nil)
addHelperImport(WasmFunctionName.jsGlobalRefTypeof, List(WasmRefType.any), List(WasmRefType.any))
addHelperImport(WasmFunctionName.jsNewArray, Nil, List(anyref))
addHelperImport(WasmFunctionName.jsArrayPush, List(anyref, anyref), List(anyref))
addHelperImport(
WasmFunctionName.jsArraySpreadPush,
List(anyref, anyref),
List(anyref)
)
addHelperImport(WasmFunctionName.jsNewObject, Nil, List(anyref))
addHelperImport(
WasmFunctionName.jsObjectPush,
List(anyref, anyref, anyref),
List(anyref)
)
addHelperImport(WasmFunctionName.jsSelect, List(anyref, anyref), List(anyref))
addHelperImport(WasmFunctionName.jsSelectSet, List(anyref, anyref, anyref), Nil)
addHelperImport(WasmFunctionName.jsNew, List(anyref, anyref), List(anyref))
addHelperImport(WasmFunctionName.jsFunctionApply, List(anyref, anyref), List(anyref))
addHelperImport(
WasmFunctionName.jsMethodApply,
List(anyref, anyref, anyref),
List(anyref)
)
addHelperImport(WasmFunctionName.jsImportCall, List(anyref), List(anyref))
addHelperImport(WasmFunctionName.jsImportMeta, Nil, List(anyref))
addHelperImport(WasmFunctionName.jsDelete, List(anyref, anyref), Nil)
addHelperImport(WasmFunctionName.jsForInSimple, List(anyref, anyref), Nil)
addHelperImport(WasmFunctionName.jsIsTruthy, List(anyref), List(WasmInt32))
addHelperImport(WasmFunctionName.jsLinkingInfo, Nil, List(anyref))
for ((op, name) <- WasmFunctionName.jsUnaryOps)
addHelperImport(name, List(anyref), List(anyref))
for ((op, name) <- WasmFunctionName.jsBinaryOps) {
val resultType =
if (op == IRTrees.JSBinaryOp.=== || op == IRTrees.JSBinaryOp.!==) WasmInt32
else anyref
addHelperImport(name, List(anyref, anyref), List(resultType))
}
addHelperImport(WasmFunctionName.newSymbol, Nil, List(anyref))
addHelperImport(
WasmFunctionName.createJSClass,
List(anyref, anyref, WasmRefType.func, WasmRefType.func, WasmRefType.func),
List(WasmRefType.any)
)
addHelperImport(
WasmFunctionName.createJSClassRest,
List(anyref, anyref, WasmRefType.func, WasmRefType.func, WasmRefType.func, WasmInt32),
List(WasmRefType.any)
)
addHelperImport(
WasmFunctionName.installJSField,
List(anyref, anyref, anyref),
Nil
)
addHelperImport(
WasmFunctionName.installJSMethod,
List(anyref, anyref, anyref, WasmRefType.func, WasmInt32),
Nil
)
addHelperImport(
WasmFunctionName.installJSStaticMethod,
List(anyref, anyref, anyref, WasmRefType.func, WasmInt32),
Nil
)
addHelperImport(
WasmFunctionName.installJSProperty,
List(anyref, anyref, anyref, WasmRefType.funcref, WasmRefType.funcref),
Nil
)
addHelperImport(
WasmFunctionName.installJSStaticProperty,
List(anyref, anyref, anyref, WasmRefType.funcref, WasmRefType.funcref),
Nil
)
addHelperImport(
WasmFunctionName.jsSuperGet,
List(anyref, anyref, anyref),
List(anyref)
)
addHelperImport(
WasmFunctionName.jsSuperSet,
List(anyref, anyref, anyref, anyref),
Nil
)
addHelperImport(
WasmFunctionName.jsSuperCall,
List(anyref, anyref, anyref, anyref),
List(anyref)
)
addGlobalHelperImport(WasmGlobalName.idHashCodeMap, WasmRefType.extern, isMutable = false)
def complete(
moduleInitializers: List[ModuleInitializer.Initializer],
classesWithStaticInit: List[IRNames.ClassName],
topLevelExportDefs: List[LinkedTopLevelExport]
): Unit = {
/* Before generating the string globals in `genStartFunction()`, make sure
* to allocate the ones that will be required by the module initializers.
*/
for (init <- moduleInitializers) {
ModuleInitializerImpl.fromInitializer(init) match {
case ModuleInitializerImpl.MainMethodWithArgs(_, _, args) =>
args.foreach(addConstantStringGlobal(_))
case ModuleInitializerImpl.VoidMainMethod(_, _) =>
() // nothing to do
}
}
// string
module.addData(WasmData(WasmDataName.string, stringPool.toArray, WasmData.Mode.Passive))
addGlobal(
WasmGlobal(
WasmGlobalName.stringLiteralCache,
WasmRefType(WasmArrayTypeName.anyArray),
WasmExpr(
List(
WasmInstr.I32_CONST(nextConstantStringIndex),
WasmInstr.ARRAY_NEW_DEFAULT(WasmArrayTypeName.anyArray)
)
),
isMutable = false
)
)
genStartFunction(moduleInitializers, classesWithStaticInit, topLevelExportDefs)
genDeclarativeElements()
}
private def genStartFunction(
moduleInitializers: List[ModuleInitializer.Initializer],
classesWithStaticInit: List[IRNames.ClassName],
topLevelExportDefs: List[LinkedTopLevelExport]
): Unit = {
import WasmInstr._
import WasmTypeName._
val fctx = WasmFunctionContext(WasmFunctionName.start, Nil, Nil)(this)
import fctx.instrs
// Initialize itables
for ((name, globalName) <- classItableGlobals) {
val classInfo = getClassInfo(name)
val interfaces = classInfo.ancestors.map(getClassInfo(_)).filter(_.isInterface)
val vtable = calculateVtableType(name)
interfaces.foreach { iface =>
val idx = getItableIdx(iface.name)
instrs += WasmInstr.GLOBAL_GET(globalName)
instrs += WasmInstr.I32_CONST(idx)
iface.methods.foreach { method =>
val func = vtable.resolve(method.name)
instrs += WasmInstr.REF_FUNC(func.name)
}
instrs += WasmInstr.STRUCT_NEW(WasmTypeName.WasmStructTypeName.forITable(iface.name))
instrs += WasmInstr.ARRAY_SET(WasmTypeName.WasmArrayTypeName.itables)
}
}
locally {
// For array classes, resolve methods in the vtable of jl.Object
val globalName = WasmGlobalName.arrayClassITable
val objectVTable = calculateVtableType(IRNames.ObjectClass)
for {
interfaceName <- List(IRNames.SerializableClass, IRNames.CloneableClass)
// Use getClassInfoOption in case the reachability analysis got rid of those interfaces
interfaceInfo <- getClassInfoOption(interfaceName)
} {
instrs += GLOBAL_GET(globalName)
instrs += I32_CONST(getItableIdx(interfaceName))
for (method <- interfaceInfo.methods)
instrs += refFuncWithDeclaration(objectVTable.resolve(method.name).name)
instrs += STRUCT_NEW(WasmStructTypeName.forITable(interfaceName))
instrs += ARRAY_SET(WasmArrayTypeName.itables)
}
}
// Initialize the JS private field symbols
for (fieldName <- _jsPrivateFieldNames) {
instrs += WasmInstr.CALL(WasmFunctionName.newSymbol)
instrs += WasmInstr.GLOBAL_SET(WasmGlobalName.forJSPrivateField(fieldName))
}
// Emit the static initializers
for (className <- classesWithStaticInit) {
val funcName = WasmFunctionName(
IRTrees.MemberNamespace.StaticConstructor,
className,
IRNames.StaticInitializerName
)
instrs += WasmInstr.CALL(funcName)
}
// Initialize the top-level exports that require it
for (tle <- topLevelExportDefs) {
tle.tree match {
case IRTrees.TopLevelJSClassExportDef(_, exportName) =>
instrs += CALL(WasmFunctionName.loadJSClass(tle.owningClass))
instrs += GLOBAL_SET(WasmGlobalName.forTopLevelExport(tle.exportName))
case IRTrees.TopLevelModuleExportDef(_, exportName) =>
instrs += CALL(WasmFunctionName.loadModule(tle.owningClass))
instrs += GLOBAL_SET(WasmGlobalName.forTopLevelExport(tle.exportName))
case IRTrees.TopLevelMethodExportDef(_, methodDef) =>
// We only need initialization if there is a restParam
if (methodDef.restParam.isDefined) {
instrs += refFuncWithDeclaration(WasmFunctionName.forExport(tle.exportName))
instrs += I32_CONST(methodDef.args.size)
instrs += CALL(WasmFunctionName.closureRestNoData)
instrs += GLOBAL_SET(WasmGlobalName.forTopLevelExport(tle.exportName))
}
case IRTrees.TopLevelFieldExportDef(_, _, _) =>
// Nothing to do
()
}
}
// Emit the module initializers
moduleInitializers.foreach { init =>
def genCallStatic(className: IRNames.ClassName, methodName: IRNames.MethodName): Unit = {
val functionName =
WasmFunctionName(IRTrees.MemberNamespace.PublicStatic, className, methodName)
instrs += WasmInstr.CALL(functionName)
}
implicit val noPos: Position = Position.NoPosition
val stringArrayTypeRef = IRTypes.ArrayTypeRef(IRTypes.ClassRef(IRNames.BoxedStringClass), 1)
val callTree = ModuleInitializerImpl.fromInitializer(init) match {
case ModuleInitializerImpl.MainMethodWithArgs(className, encodedMainMethodName, args) =>
IRTrees.ApplyStatic(
IRTrees.ApplyFlags.empty,
className,
IRTrees.MethodIdent(encodedMainMethodName),
List(IRTrees.ArrayValue(stringArrayTypeRef, args.map(IRTrees.StringLiteral(_))))
)(IRTypes.NoType)
case ModuleInitializerImpl.VoidMainMethod(className, encodedMainMethodName) =>
IRTrees.ApplyStatic(
IRTrees.ApplyFlags.empty,
className,
IRTrees.MethodIdent(encodedMainMethodName),
Nil
)(IRTypes.NoType)
}
WasmExpressionBuilder.generateIRBody(callTree, IRTypes.NoType)(this, fctx)
}
// Finish the start function
if (instrs.nonEmpty) {
fctx.buildAndAddToContext()
module.setStartFunction(WasmFunctionName.start)
}
}
private def genDeclarativeElements(): Unit = {
// Aggregated Elements
if (_funcDeclarations.nonEmpty) {
/* Functions that are referred to with `ref.func` in the Code section
* must be declared ahead of time in one of the earlier sections
* (otherwise the module does not validate). It can be the Global section
* if they are meaningful there (which is why `ref.func` in the vtables
* work out of the box). In the absence of any other specific place, an
* Element section with the declarative mode is the recommended way to
* introduce these declarations.
*/
val exprs = _funcDeclarations.toList.map { name =>
WasmExpr(List(WasmInstr.REF_FUNC(name)))
}
module.addElement(WasmElement(WasmRefType.funcref, exprs, WasmElement.Mode.Declarative))
}
}
}
object WasmContext {
private val classFieldOffset = 2 // vtable, itables
final class WasmClassInfo(
val name: IRNames.ClassName,
val kind: ClassKind,
val jsClassCaptures: Option[List[IRTrees.ParamDef]],
private var _methods: List[WasmFunctionInfo],
val reflectiveProxies: List[WasmFunctionInfo],
val allFieldDefs: List[IRTrees.FieldDef],
val superClass: Option[IRNames.ClassName],
val interfaces: List[IRNames.ClassName],
val ancestors: List[IRNames.ClassName],
private var _hasInstances: Boolean,
val isAbstract: Boolean,
val hasRuntimeTypeInfo: Boolean,
val jsNativeLoadSpec: Option[IRTrees.JSNativeLoadSpec],
val jsNativeMembers: Map[IRNames.MethodName, IRTrees.JSNativeLoadSpec]
) {
private val fieldIdxByName: Map[IRNames.FieldName, Int] =
allFieldDefs.map(_.name.name).zipWithIndex.map(p => p._1 -> (p._2 + classFieldOffset)).toMap
// See caller in Preprocessor.preprocess
def setHasInstances(): Unit =
_hasInstances = true
def hasInstances: Boolean = _hasInstances
private var _specialInstanceTypes: Int = 0
def addSpecialInstanceType(jsValueType: Int): Unit =
_specialInstanceTypes |= (1 << jsValueType)
/** A bitset of the `jsValueType`s corresponding to hijacked classes that extend this class.
*
* This value is used for instance tests against this class. A JS value `x` is an instance of
* this type iff `jsValueType(x)` is a member of this bitset. Because of how a bitset works,
* this means testing the following formula:
*
* {{{
* ((1 << jsValueType(x)) & specialInstanceTypes) != 0
* }}}
*
* For example, if this class is `Comparable`, we want the bitset to contain the values for
* `boolean`, `string` and `number` (but not `undefined`), because `jl.Boolean`, `jl.String`
* and `jl.Double` implement `Comparable`.
*
* This field is initialized with 0, and augmented during preprocessing by calls to
* `addSpecialInstanceType`.
*
* This technique is used both for static `isInstanceOf` tests as well as reflective tests
* through `Class.isInstance`. For the latter, this value is stored in
* `typeData.specialInstanceTypes`. For the former, it is embedded as a constant in the
* generated code.
*
* See the `isInstance` and `genInstanceTest` helpers.
*
* Special cases: this value remains 0 for all the numeric hijacked classes except `jl.Double`,
* since `jsValueType(x) == JSValueTypeNumber` is not enough to deduce that
* `x.isInstanceOf[Int]`, for example.
*/
def specialInstanceTypes: Int = _specialInstanceTypes
/** Is this class an ancestor of any hijacked class?
*
* This includes but is not limited to the hijacked classes themselves, as well as `jl.Object`.
*/
def isAncestorOfHijackedClass: Boolean =
specialInstanceTypes != 0 || kind == ClassKind.HijackedClass
def isInterface = kind == ClassKind.Interface
def methods: List[WasmFunctionInfo] = _methods
def maybeAddAbstractMethod(methodName: IRNames.MethodName, ctx: WasmContext): Unit = {
if (!methods.exists(_.name.simpleName == methodName.nameString)) {
val wasmName = WasmFunctionName(IRTrees.MemberNamespace.Public, name, methodName)
val argTypes = methodName.paramTypeRefs.map(ctx.inferTypeFromTypeRef(_))
val resultType = ctx.inferTypeFromTypeRef(methodName.resultTypeRef)
_methods = _methods :+ WasmFunctionInfo(
wasmName,
argTypes,
resultType,
isAbstract = true,
isReflectiveProxy = methodName.isReflectiveProxy
)
}
}
@tailrec
private def resolvePublicMethodOpt(
methodName: IRNames.MethodName
)(implicit ctx: ReadOnlyWasmContext): Option[IRNames.ClassName] = {
if (methods.exists(_.name.simpleName == methodName.nameString)) {
Some(name)
} else {
superClass match {
case None =>
None
case Some(superClass) =>
ctx.getClassInfo(superClass).resolvePublicMethodOpt(methodName)
}
}
}
def resolvePublicMethod(namespace: IRTrees.MemberNamespace, methodName: IRNames.MethodName)(
implicit ctx: ReadOnlyWasmContext
): IRNames.ClassName = {
if (isInterface || namespace != IRTrees.MemberNamespace.Public) {
name
} else {
resolvePublicMethodOpt(methodName).getOrElse {
throw new AssertionError(
s"Cannot find method ${methodName.nameString} in class ${name.nameString}"
)
}
}
}
def getFieldIdx(name: IRNames.FieldName): WasmFieldIdx = {
WasmFieldIdx(
fieldIdxByName.getOrElse(
name, {
throw new AssertionError(
s"Unknown field ${name.nameString} in class ${this.name.nameString}"
)
}
)
)
}
}
case class WasmFunctionInfo(
name: WasmFunctionName,
argTypes: List[IRTypes.Type],
resultType: IRTypes.Type,
// flags: IRTrees.MemberFlags,
isAbstract: Boolean,
isReflectiveProxy: Boolean
) {
def toWasmFunctionType()(implicit ctx: TypeDefinableWasmContext): WasmFunctionType =
TypeTransformer.transformFunctionType(this)
}
case class WasmFieldInfo(name: WasmFieldName, tpe: Types.WasmType)
case class WasmVTable(val functions: List[WasmFunctionInfo]) {
def resolve(name: WasmFunctionName): WasmFunctionInfo =
functions
.find(_.name.simpleName == name.simpleName)
.getOrElse(throw new Error(s"Function not found: $name"))
def resolveWithIdx(name: WasmFunctionName): (Int, WasmFunctionInfo) = {
val idx = functions.indexWhere(_.name.simpleName == name.simpleName)
if (idx < 0)
throw new Error(s"Function not found: $name among ${functions.map(_.name.simpleName)}")
else (idx, functions(idx))
}
}
}