forked from scala/scala3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSCodeGen.scala
4925 lines (4277 loc) · 178 KB
/
JSCodeGen.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 dotty.tools.backend.sjs
import scala.language.unsafeNulls
import scala.annotation.switch
import scala.collection.mutable
import dotty.tools.FatalError
import dotty.tools.dotc.CompilationUnit
import dotty.tools.dotc.ast.tpd
import dotty.tools.dotc.core.*
import Contexts.*
import Decorators.*
import Flags.*
import Names.*
import NameKinds.DefaultGetterName
import Types.*
import Symbols.*
import Phases.*
import StdNames.*
import TypeErasure.ErasedValueType
import dotty.tools.dotc.transform.{Erasure, ValueClasses}
import dotty.tools.dotc.util.SourcePosition
import dotty.tools.dotc.report
import dotty.tools.sjs.ir
import dotty.tools.sjs.ir.{ClassKind, Position, Names => jsNames, Trees => js, Types => jstpe}
import dotty.tools.sjs.ir.Names.{ClassName, MethodName, SimpleMethodName}
import dotty.tools.sjs.ir.OriginalName
import dotty.tools.sjs.ir.OriginalName.NoOriginalName
import dotty.tools.sjs.ir.Trees.OptimizerHints
import dotty.tools.dotc.transform.sjs.JSSymUtils.*
import JSEncoding.*
import ScopedVar.withScopedVars
import scala.reflect.NameTransformer
/** Main codegen for Scala.js IR.
*
* [[GenSJSIR]] creates one instance of `JSCodeGen` per compilation unit.
* The `run()` method processes the whole compilation unit and generates
* `.sjsir` files for it.
*
* There are 4 main levels of translation:
*
* - `genCompilationUnit()` iterates through all the type definitions in the
* compilation unit. Each generated `js.ClassDef` is serialized to an
* `.sjsir` file.
* - `genScalaClass()` and other similar methods generate the skeleton of
* classes.
* - `genMethod()` and similar methods generate the declarations of methods.
* - `genStatOrExpr()` and everything else generate the bodies of methods.
*/
class JSCodeGen()(using genCtx: Context) {
import JSCodeGen.*
import tpd.*
val sjsPlatform = dotty.tools.dotc.config.SJSPlatform.sjsPlatform
val jsdefn = JSDefinitions.jsdefn
private val primitives = new JSPrimitives(genCtx)
val positionConversions = new JSPositions()(using genCtx)
import positionConversions.*
private val jsExportsGen = new JSExportsGen(this)
// Some state --------------------------------------------------------------
private val lazilyGeneratedAnonClasses = new MutableSymbolMap[TypeDef]
private val generatedClasses = mutable.ListBuffer.empty[js.ClassDef]
private val generatedStaticForwarderClasses = mutable.ListBuffer.empty[(Symbol, js.ClassDef)]
val currentClassSym = new ScopedVar[Symbol]
private val currentMethodSym = new ScopedVar[Symbol]
private val localNames = new ScopedVar[LocalNameGenerator]
private val thisLocalVarIdent = new ScopedVar[Option[js.LocalIdent]]
private val isModuleInitialized = new ScopedVar[ScopedVar.VarBox[Boolean]]
private val undefinedDefaultParams = new ScopedVar[mutable.Set[Symbol]]
/* Contextual JS class value for some operations of nested JS classes that need one. */
private val contextualJSClassValue = new ScopedVar[Option[js.Tree]](None)
/** Resets all of the scoped state in the context of `body`. */
private def resetAllScopedVars[T](body: => T): T = {
withScopedVars(
currentClassSym := null,
currentMethodSym := null,
localNames := null,
thisLocalVarIdent := null,
isModuleInitialized := null,
undefinedDefaultParams := null
) {
body
}
}
private def withPerMethodBodyState[A](methodSym: Symbol)(body: => A): A = {
withScopedVars(
currentMethodSym := methodSym,
thisLocalVarIdent := None,
isModuleInitialized := new ScopedVar.VarBox(false),
undefinedDefaultParams := mutable.Set.empty,
) {
body
}
}
private def acquireContextualJSClassValue[A](f: Option[js.Tree] => A): A = {
val jsClassValue = contextualJSClassValue.get
withScopedVars(
contextualJSClassValue := None
) {
f(jsClassValue)
}
}
def withNewLocalNameScope[A](body: => A): A = {
withScopedVars(localNames := new LocalNameGenerator) {
body
}
}
/** Implicitly materializes the current local name generator. */
implicit def implicitLocalNames: LocalNameGenerator = localNames.get
def currentThisType: jstpe.Type = {
encodeClassType(currentClassSym) match {
case tpe @ jstpe.ClassType(cls) =>
jstpe.BoxedClassToPrimType.getOrElse(cls, tpe)
case tpe =>
tpe
}
}
/** Returns a new fresh local identifier. */
private def freshLocalIdent()(implicit pos: Position): js.LocalIdent =
localNames.get.freshLocalIdent()
/** Returns a new fresh local identifier. */
def freshLocalIdent(base: String)(implicit pos: Position): js.LocalIdent =
localNames.get.freshLocalIdent(base)
/** Returns a new fresh local identifier. */
private def freshLocalIdent(base: TermName)(implicit pos: Position): js.LocalIdent =
localNames.get.freshLocalIdent(base)
private def consumeLazilyGeneratedAnonClass(sym: Symbol): TypeDef = {
val typeDef = lazilyGeneratedAnonClasses.remove(sym)
if (typeDef == null) {
throw new FatalError(
i"Could not find tree for lazily generated anonymous class ${sym.fullName} at ${sym.sourcePos}")
} else {
typeDef
}
}
// Compilation unit --------------------------------------------------------
def run(): Unit = {
try {
genCompilationUnit(ctx.compilationUnit)
} finally {
generatedClasses.clear()
generatedStaticForwarderClasses.clear()
}
}
/** Generates the Scala.js IR for a compilation unit
* This method iterates over all the class and interface definitions
* found in the compilation unit and emits their IR (.sjsir).
*
* Some classes are never actually emitted:
* - Classes representing primitive types
* - The scala.Array class
*
* TODO Some classes representing anonymous functions are not actually emitted.
* Instead, a temporary representation of their `apply` method is built
* and recorded, so that it can be inlined as a JavaScript anonymous
* function in the method that instantiates it.
*
* Other ClassDefs are emitted according to their nature:
* * Non-native JS class -> `genNonNativeJSClass()`
* * Other JS type (<: js.Any) -> `genRawJSClassData()`
* * Interface -> `genInterface()`
* * Normal class -> `genClass()`
*/
private def genCompilationUnit(cunit: CompilationUnit): Unit = {
def collectTypeDefs(tree: Tree): List[TypeDef] = {
tree match {
case EmptyTree => Nil
case PackageDef(_, stats) => stats.flatMap(collectTypeDefs)
case cd: TypeDef => cd :: Nil
case _: ValDef => Nil // module instance
}
}
val allTypeDefs = collectTypeDefs(cunit.tpdTree)
/* #13221 Set JavaStatic on all the Module fields of static module classes.
* This is necessary for `desugarIdent` not to crash in some obscure
* scenarios.
*
* !!! Part of this logic is duplicated in BCodeSkelBuilder.genPlainClass
*
* However, here we only do this for Module fields, not all fields.
*/
for (typeDef <- allTypeDefs) {
if (typeDef.symbol.is(ModuleClass)) {
typeDef.symbol.info.decls.foreach { f =>
if (f.isField && f.is(Module))
f.setFlag(JavaStatic)
}
}
}
val (anonJSClassTypeDefs, otherTypeDefs) =
allTypeDefs.partition(td => td.symbol.isAnonymousClass && td.symbol.isJSType)
// Record the TypeDefs of anonymous JS classes to be lazily generated
for (td <- anonJSClassTypeDefs)
lazilyGeneratedAnonClasses(td.symbol) = td
/* Finally, we emit true code for the remaining class defs. */
for (td <- otherTypeDefs) {
val sym = td.symbol
implicit val pos: Position = sym.span
/* Do not actually emit code for primitive types nor scala.Array. */
val isPrimitive =
sym.isPrimitiveValueClass || sym == defn.ArrayClass
if (!isPrimitive) {
withScopedVars(
currentClassSym := sym
) {
val tree = if (sym.isJSType) {
if (!sym.is(Trait) && sym.isNonNativeJSClass)
genNonNativeJSClass(td)
else
genRawJSClassData(td)
} else if (sym.is(Trait)) {
genInterface(td)
} else {
genScalaClass(td)
}
generatedClasses += tree
}
}
}
for (tree <- generatedClasses)
genIRFile(cunit, tree)
if (generatedStaticForwarderClasses.nonEmpty) {
/* #4148 Add generated static forwarder classes, except those that
* would collide with regular classes on case insensitive file systems.
*/
/* I could not find any reference anywhere about what locale is used
* by case insensitive file systems to compare case-insensitively.
* In doubt, force the English locale, which is probably going to do
* the right thing in virtually all cases (especially if users stick
* to ASCII class names), and it has the merit of being deterministic,
* as opposed to using the OS' default locale.
* The JVM backend performs a similar test to emit a warning for
* conflicting top-level classes. However, it uses `toLowerCase()`
* without argument, which is not deterministic.
*/
def caseInsensitiveNameOf(classDef: js.ClassDef): String =
classDef.name.name.nameString.toLowerCase(java.util.Locale.ENGLISH)
val generatedCaseInsensitiveNames =
generatedClasses.map(caseInsensitiveNameOf).toSet
for ((site, classDef) <- generatedStaticForwarderClasses) {
if (!generatedCaseInsensitiveNames.contains(caseInsensitiveNameOf(classDef))) {
genIRFile(cunit, classDef)
} else {
report.warning(
s"Not generating the static forwarders of ${classDef.name.name.nameString} " +
"because its name differs only in case from the name of another class or trait in this compilation unit.",
site.srcPos)
}
}
}
}
private def genIRFile(cunit: CompilationUnit, tree: ir.Trees.ClassDef): Unit = {
val outfile = getFileFor(cunit, tree.name.name, ".sjsir")
val output = outfile.bufferedOutput
try {
ir.Serializers.serialize(output, tree)
} finally {
output.close()
}
}
private def getFileFor(cunit: CompilationUnit, className: ClassName,
suffix: String): dotty.tools.io.AbstractFile = {
val outputDirectory = ctx.settings.outputDir.value
val pathParts = className.nameString.split('.')
val dir = pathParts.init.foldLeft(outputDirectory)(_.subdirectoryNamed(_))
val filename = pathParts.last
dir.fileNamed(filename + suffix)
}
// Generate a class --------------------------------------------------------
/** Gen the IR ClassDef for a Scala class definition (maybe a module class).
*/
private def genScalaClass(td: TypeDef): js.ClassDef = {
val sym = td.symbol.asClass
implicit val pos: SourcePosition = sym.sourcePos
assert(!sym.is(Trait),
"genScalaClass() must be called only for normal classes: "+sym)
assert(sym.superClass != NoSymbol, sym)
if (hasDefaultCtorArgsAndJSModule(sym)) {
report.error(
"Implementation restriction: " +
"constructors of Scala classes cannot have default parameters if their companion module is JS native.",
td)
}
val classIdent = encodeClassNameIdent(sym)
val originalName = originalNameOfClass(sym)
val isHijacked = false //isHijackedBoxedClass(sym)
// Optimizer hints
val isDynamicImportThunk = sym.isSubClass(jsdefn.DynamicImportThunkClass)
def isStdLibClassWithAdHocInlineAnnot(sym: Symbol): Boolean = {
val fullName = sym.fullName.toString
(fullName.startsWith("scala.Tuple") && !fullName.endsWith("$")) ||
(fullName.startsWith("scala.collection.mutable.ArrayOps$of"))
}
val shouldMarkInline = (
isDynamicImportThunk ||
sym.hasAnnotation(jsdefn.InlineAnnot) ||
(sym.isAnonymousFunction && !sym.isSubClass(defn.PartialFunctionClass)) ||
isStdLibClassWithAdHocInlineAnnot(sym))
val optimizerHints = {
OptimizerHints.empty
.withInline(shouldMarkInline)
.withNoinline(sym.hasAnnotation(jsdefn.NoinlineAnnot))
}
// Generate members (constructor + methods)
val generatedNonFieldMembers = new mutable.ListBuffer[js.MemberDef]
val tpl = td.rhs.asInstanceOf[Template]
for (tree <- tpl.constr :: tpl.body) {
tree match {
case EmptyTree => ()
case vd: ValDef =>
// fields are added via genClassFields(), but we need to generate the JS native members
val sym = vd.symbol
if (!sym.is(Module) && sym.hasAnnotation(jsdefn.JSNativeAnnot))
generatedNonFieldMembers += genJSNativeMemberDef(vd)
case dd: DefDef =>
val sym = dd.symbol
if sym.hasAnnotation(jsdefn.JSNativeAnnot) then
if !sym.is(Accessor) then
generatedNonFieldMembers += genJSNativeMemberDef(dd)
else
generatedNonFieldMembers ++= genMethod(dd)
case _ =>
throw new FatalError("Illegal tree in body of genScalaClass(): " + tree)
}
}
// Generate fields and add to methods + ctors
val generatedMembers = genClassFields(td) ++ generatedNonFieldMembers.toList
// Generate member exports
val memberExports = jsExportsGen.genMemberExports(sym)
// Generate top-level export definitions
val topLevelExportDefs = jsExportsGen.genTopLevelExports(sym)
// Static initializer
val optStaticInitializer = {
// Initialization of reflection data, if required
val reflectInit = {
val enableReflectiveInstantiation = {
sym.baseClasses.exists { ancestor =>
ancestor.hasAnnotation(jsdefn.EnableReflectiveInstantiationAnnot)
}
}
if (enableReflectiveInstantiation)
genRegisterReflectiveInstantiation(sym).toList
else
Nil
}
// Initialization of the module because of field exports
val needsStaticModuleInit =
topLevelExportDefs.exists(_.isInstanceOf[js.TopLevelFieldExportDef])
val staticModuleInit =
if (!needsStaticModuleInit) Nil
else List(genLoadModule(sym))
val staticInitializerStats = reflectInit ::: staticModuleInit
if (staticInitializerStats.nonEmpty)
List(genStaticConstructorWithStats(ir.Names.StaticInitializerName, js.Block(staticInitializerStats)))
else
Nil
}
val optDynamicImportForwarder =
if (isDynamicImportThunk) List(genDynamicImportForwarder(sym))
else Nil
val allMemberDefsExceptStaticForwarders =
generatedMembers ::: memberExports ::: optStaticInitializer ::: optDynamicImportForwarder
// Add static forwarders
val allMemberDefs = if (!isCandidateForForwarders(sym)) {
allMemberDefsExceptStaticForwarders
} else {
if (isStaticModule(sym)) {
/* If the module class has no linked class, we must create one to
* hold the static forwarders. Otherwise, this is going to be handled
* when generating the companion class.
*/
if (!sym.linkedClass.exists) {
val forwarders = genStaticForwardersFromModuleClass(Nil, sym)
if (forwarders.nonEmpty) {
val forwardersClassDef = js.ClassDef(
js.ClassIdent(ClassName(classIdent.name.nameString.stripSuffix("$"))),
originalName,
ClassKind.Class,
None,
Some(js.ClassIdent(ir.Names.ObjectClass)),
Nil,
None,
None,
forwarders,
Nil
)(js.OptimizerHints.empty)
generatedStaticForwarderClasses += sym -> forwardersClassDef
}
}
allMemberDefsExceptStaticForwarders
} else {
val forwarders = genStaticForwardersForClassOrInterface(
allMemberDefsExceptStaticForwarders, sym)
allMemberDefsExceptStaticForwarders ::: forwarders
}
}
// Hashed definitions of the class
val hashedDefs = ir.Hashers.hashMemberDefs(allMemberDefs)
// The complete class definition
val kind =
if (isStaticModule(sym)) ClassKind.ModuleClass
else if (isHijacked) ClassKind.HijackedClass
else ClassKind.Class
val classDefinition = js.ClassDef(
classIdent,
originalName,
kind,
None,
Some(encodeClassNameIdent(sym.superClass)),
genClassInterfaces(sym, forJSClass = false),
None,
None,
hashedDefs,
topLevelExportDefs)(
optimizerHints)
classDefinition
}
/** Gen the IR ClassDef for a Scala.js-defined JS class. */
private def genNonNativeJSClass(td: TypeDef): js.ClassDef = {
val sym = td.symbol.asClass
implicit val pos: SourcePosition = sym.sourcePos
assert(sym.isNonNativeJSClass,
i"genNonNativeJSClass() must be called only for non-native JS classes: $sym")
assert(sym.superClass != NoSymbol, sym)
if (hasDefaultCtorArgsAndJSModule(sym)) {
report.error(
"Implementation restriction: " +
"constructors of non-native JS classes cannot have default parameters if their companion module is JS native.",
td)
}
val classIdent = encodeClassNameIdent(sym)
val originalName = originalNameOfClass(sym)
// Generate members (constructor + methods)
val constructorTrees = new mutable.ListBuffer[DefDef]
val generatedMethods = new mutable.ListBuffer[js.MethodDef]
val dispatchMethodNames = new mutable.ListBuffer[JSName]
val tpl = td.rhs.asInstanceOf[Template]
for (tree <- tpl.constr :: tpl.body) {
tree match {
case EmptyTree => ()
case _: ValDef =>
() // fields are added via genClassFields()
case dd: DefDef =>
val sym = dd.symbol
val exposed = sym.isJSExposed
if (sym.isClassConstructor) {
constructorTrees += dd
} else if (exposed && sym.is(Accessor, butNot = Lazy)) {
// Exposed accessors must not be emitted, since the field they access is enough.
} else if (sym.hasAnnotation(jsdefn.JSOptionalAnnot)) {
// Optional methods must not be emitted
} else {
generatedMethods ++= genMethod(dd)
// Collect the names of the dispatchers we have to create
if (exposed && !sym.is(Deferred)) {
/* We add symbols that we have to expose here. This way we also
* get inherited stuff that is implemented in this class.
*/
dispatchMethodNames += sym.jsName
}
}
case _ =>
throw new FatalError("Illegal tree in gen of genNonNativeJSClass(): " + tree)
}
}
// Static members (exported from the companion object)
val staticMembers = {
val module = sym.companionModule
if (!module.exists) {
Nil
} else {
val companionModuleClass = module.moduleClass
val exports = withScopedVars(currentClassSym := companionModuleClass) {
jsExportsGen.genStaticExports(companionModuleClass)
}
if (exports.exists(_.isInstanceOf[js.JSFieldDef])) {
val classInitializer =
genStaticConstructorWithStats(ir.Names.ClassInitializerName, genLoadModule(companionModuleClass))
exports :+ classInitializer
} else {
exports
}
}
}
val topLevelExports = jsExportsGen.genTopLevelExports(sym)
val (generatedConstructor, jsClassCaptures) = withNewLocalNameScope {
val isNested = sym.isNestedJSClass
if (isNested)
localNames.reserveLocalName(JSSuperClassParamName)
val (captures, ctor) = genJSClassCapturesAndConstructor(constructorTrees.toList)
val jsClassCaptures = if (isNested) {
val superParam = js.ParamDef(js.LocalIdent(JSSuperClassParamName),
NoOriginalName, jstpe.AnyType, mutable = false)
Some(superParam :: captures)
} else {
assert(captures.isEmpty, s"found non nested JS class with captures $captures at $pos")
None
}
(ctor, jsClassCaptures)
}
// Generate fields (and add to methods + ctors)
val generatedMembers = {
genClassFields(td) :::
generatedConstructor ::
jsExportsGen.genJSClassDispatchers(sym, dispatchMethodNames.result().distinct) :::
generatedMethods.toList :::
staticMembers
}
// Hashed definitions of the class
val hashedMemberDefs = ir.Hashers.hashMemberDefs(generatedMembers)
// The complete class definition
val kind =
if (isStaticModule(sym)) ClassKind.JSModuleClass
else ClassKind.JSClass
val classDefinition = js.ClassDef(
classIdent,
originalNameOfClass(sym),
kind,
jsClassCaptures,
Some(encodeClassNameIdent(sym.superClass)),
genClassInterfaces(sym, forJSClass = true),
jsSuperClass = jsClassCaptures.map(_.head.ref),
None,
hashedMemberDefs,
topLevelExports)(
OptimizerHints.empty)
classDefinition
}
/** Gen the IR ClassDef for a raw JS class or trait.
*/
private def genRawJSClassData(td: TypeDef): js.ClassDef = {
val sym = td.symbol.asClass
implicit val pos: Position = sym.span
val classIdent = encodeClassNameIdent(sym)
val kind = {
if (sym.is(Trait)) ClassKind.AbstractJSType
else if (sym.is(ModuleClass)) ClassKind.NativeJSModuleClass
else ClassKind.NativeJSClass
}
val superClass =
if (sym.is(Trait)) None
else Some(encodeClassNameIdent(sym.superClass))
val jsNativeLoadSpec = computeJSNativeLoadSpecOfClass(sym)
js.ClassDef(
classIdent,
originalNameOfClass(sym),
kind,
None,
superClass,
genClassInterfaces(sym, forJSClass = true),
None,
jsNativeLoadSpec,
Nil,
Nil)(
OptimizerHints.empty)
}
/** Gen the IR ClassDef for an interface definition.
*/
private def genInterface(td: TypeDef): js.ClassDef = {
val sym = td.symbol.asClass
implicit val pos: SourcePosition = sym.sourcePos
val classIdent = encodeClassNameIdent(sym)
val generatedMethods = new mutable.ListBuffer[js.MethodDef]
val tpl = td.rhs.asInstanceOf[Template]
for (tree <- tpl.constr :: tpl.body) {
tree match {
case EmptyTree => ()
case dd: DefDef => generatedMethods ++= genMethod(dd)
case _ =>
throw new FatalError(
i"""Illegal tree in gen of genInterface(): $tree
|class = $td
|in ${ctx.compilationUnit}""")
}
}
val superInterfaces = genClassInterfaces(sym, forJSClass = false)
val genMethodsList = generatedMethods.toList
val allMemberDefs =
if (!isCandidateForForwarders(sym)) genMethodsList
else genMethodsList ::: genStaticForwardersForClassOrInterface(genMethodsList, sym)
// Hashed definitions of the interface
val hashedDefs = ir.Hashers.hashMemberDefs(allMemberDefs)
js.ClassDef(
classIdent,
originalNameOfClass(sym),
ClassKind.Interface,
None,
None,
superInterfaces,
None,
None,
hashedDefs,
Nil)(
OptimizerHints.empty)
}
private def genClassInterfaces(sym: ClassSymbol, forJSClass: Boolean)(
implicit pos: Position): List[js.ClassIdent] = {
for {
intf <- sym.directlyInheritedTraits
if !(forJSClass && intf == defn.DynamicClass)
} yield {
encodeClassNameIdent(intf)
}
}
// Static forwarders -------------------------------------------------------
/* This mimics the logic in BCodeHelpers.addForwarders and the code that
* calls it, except that we never have collisions with existing methods in
* the companion class. This is because in the IR, only methods with the
* same `MethodName` (including signature) and that are also
* `PublicStatic` would collide. There should never be an actual collision
* because the only `PublicStatic` methods that are otherwise generated are
* the bodies of SAMs, which have mangled names. If that assumption is
* broken, an error message is emitted asking the user to report a bug.
*
* It is important that we always emit forwarders, because some Java APIs
* actually have a public static method and a public instance method with
* the same name. For example the class `Integer` has a
* `def hashCode(): Int` and a `static def hashCode(Int): Int`. The JVM
* back-end considers them as colliding because they have the same name,
* but we must not.
*
* By default, we only emit forwarders for top-level objects, like the JVM
* back-end. However, if requested via a compiler option, we enable them
* for all static objects. This is important so we can implement static
* methods of nested static classes of JDK APIs (see scala-js/#3950).
*/
/** Is the given Scala class, interface or module class a candidate for
* static forwarders?
*
* - the flag `-XnoForwarders` is not set to true, and
* - the symbol is static, and
* - either of both of the following is true:
* - the flag `-scalajsGenStaticForwardersForNonTopLevelObjects` is set to true, or
* - the symbol was originally at the package level
*
* Other than the Scala.js-specific flag, and the fact that we also consider
* interfaces, this performs the same tests as the JVM back-end.
*/
def isCandidateForForwarders(sym: Symbol): Boolean = {
!ctx.settings.XnoForwarders.value && sym.isStatic && {
ctx.settings.scalajsGenStaticForwardersForNonTopLevelObjects.value || {
atPhase(flattenPhase) {
toDenot(sym).owner.is(PackageClass)
}
}
}
}
/** Gen the static forwarders to the members of a class or interface for
* methods of its companion object.
*
* This is only done if there exists a companion object and it is not a JS
* type.
*
* Precondition: `isCandidateForForwarders(sym)` is true
*/
def genStaticForwardersForClassOrInterface(
existingMembers: List[js.MemberDef], sym: Symbol)(
implicit pos: SourcePosition): List[js.MemberDef] = {
val module = sym.companionModule
if (!module.exists) {
Nil
} else {
val moduleClass = module.moduleClass
if (!moduleClass.isJSType)
genStaticForwardersFromModuleClass(existingMembers, moduleClass)
else
Nil
}
}
/** Gen the static forwarders for the methods of a module class.
*
* Precondition: `isCandidateForForwarders(moduleClass)` is true
*/
def genStaticForwardersFromModuleClass(existingMembers: List[js.MemberDef],
moduleClass: Symbol)(
implicit pos: SourcePosition): List[js.MemberDef] = {
assert(moduleClass.is(ModuleClass), moduleClass)
val existingPublicStaticMethodNames = existingMembers.collect {
case js.MethodDef(flags, name, _, _, _, _)
if flags.namespace == js.MemberNamespace.PublicStatic =>
name.name
}.toSet
val staticNames = moduleClass.companionClass.info.allMembers
.collect { case d if d.name.isTermName && d.symbol.isScalaStatic => d.name }.toSet
val members = {
moduleClass.info.membersBasedOnFlags(required = Flags.Method,
excluded = Flags.ExcludedForwarder).map(_.symbol)
}
def isExcluded(m: Symbol): Boolean = {
def hasAccessBoundary = m.accessBoundary(defn.RootClass) ne defn.RootClass
def isOfJLObject: Boolean = m.owner eq defn.ObjectClass
def isDefaultParamOfJSNativeDef: Boolean = {
m.name.is(DefaultGetterName) && {
val info = new DefaultParamInfo(m)
!info.isForConstructor && info.attachedMethod.hasAnnotation(jsdefn.JSNativeAnnot)
}
}
m.is(Deferred)
|| m.isConstructor
|| hasAccessBoundary
|| isOfJLObject
|| m.hasAnnotation(jsdefn.JSNativeAnnot) || isDefaultParamOfJSNativeDef // #4557
|| staticNames(m.name)
}
val forwarders = for {
m <- members
if !isExcluded(m)
} yield {
withNewLocalNameScope {
val flags = js.MemberFlags.empty.withNamespace(js.MemberNamespace.PublicStatic)
val methodIdent = encodeMethodSym(m)
val originalName = originalNameOfMethod(m)
val jsParams = for {
(paramName, paramInfo) <- m.info.paramNamess.flatten.zip(m.info.paramInfoss.flatten)
} yield {
js.ParamDef(freshLocalIdent(paramName), NoOriginalName,
toIRType(paramInfo), mutable = false)
}
val resultType = toIRType(m.info.resultType)
if (existingPublicStaticMethodNames.contains(methodIdent.name)) {
report.error(
"Unexpected situation: found existing public static method " +
s"${methodIdent.name.nameString} in the companion class of " +
s"${moduleClass.fullName}; cannot generate a static forwarder " +
"the method of the same name in the object." +
"Please report this as a bug in the Scala.js support in dotty.",
pos)
}
js.MethodDef(flags, methodIdent, originalName, jsParams, resultType, Some {
genApplyMethod(genLoadModule(moduleClass), m, jsParams.map(_.ref))
})(OptimizerHints.empty, None)
}
}
forwarders.toList
}
// Generate the fields of a class ------------------------------------------
/** Gen definitions for the fields of a class. */
private def genClassFields(td: TypeDef): List[js.MemberDef] = {
val classSym = td.symbol.asClass
assert(currentClassSym.get == classSym,
"genClassFields called with a ClassDef other than the current one")
val isJSClass = classSym.isNonNativeJSClass
// Term members that are neither methods nor modules are fields
classSym.info.decls.filter { f =>
!f.isOneOf(MethodOrModule) && f.isTerm
&& !f.hasAnnotation(jsdefn.JSNativeAnnot)
&& !f.hasAnnotation(jsdefn.JSOptionalAnnot)
&& !f.hasAnnotation(jsdefn.JSExportStaticAnnot)
}.flatMap({ f =>
implicit val pos = f.span
val isTopLevelExport = f.hasAnnotation(jsdefn.JSExportTopLevelAnnot)
val isJavaStatic = f.is(JavaStatic)
assert(!(isTopLevelExport && isJavaStatic),
em"found ${f.fullName} which is both a top-level export and a Java static")
val isStaticField = isTopLevelExport || isJavaStatic
val namespace = if isStaticField then js.MemberNamespace.PublicStatic else js.MemberNamespace.Public
val mutable = isStaticField || f.is(Mutable)
val flags = js.MemberFlags.empty.withMutable(mutable).withNamespace(namespace)
val irTpe0 =
if (isJSClass) genExposedFieldIRType(f)
else if (isTopLevelExport) jstpe.AnyType
else toIRType(f.info)
// scala-js/#4370 Fields cannot have type NothingType
val irTpe =
if (irTpe0 == jstpe.NothingType) encodeClassType(defn.NothingClass)
else irTpe0
if (isJSClass && f.isJSExposed)
js.JSFieldDef(flags, genExpr(f.jsName)(f.sourcePos), irTpe) :: Nil
else
val fieldIdent = encodeFieldSym(f)
val originalName = originalNameOfField(f)
val fieldDef = js.FieldDef(flags, fieldIdent, originalName, irTpe)
val optionalStaticFieldGetter =
if isJavaStatic then
// Here we are generating a public static getter for the static field,
// this is its API for other units. This is necessary for singleton
// enum values, which are backed by static fields.
val className = encodeClassName(classSym)
val body = js.Block(
js.LoadModule(className),
js.SelectStatic(className, fieldIdent)(irTpe))
js.MethodDef(js.MemberFlags.empty.withNamespace(js.MemberNamespace.PublicStatic),
encodeStaticMemberSym(f), originalName, Nil, irTpe,
Some(body))(
OptimizerHints.empty, None) :: Nil
else
Nil
fieldDef :: optionalStaticFieldGetter
}).toList
}
def genExposedFieldIRType(f: Symbol): jstpe.Type = {
val tpeEnteringPosterasure = atPhase(elimErasedValueTypePhase)(f.info)
tpeEnteringPosterasure match {
case tpe: ErasedValueType =>
/* Here, we must store the field as the boxed representation of
* the value class. The default value of that field, as
* initialized at the time the instance is created, will
* therefore be null. This will not match the behavior we would
* get in a Scala class. To match the behavior, we would need to
* initialized to an instance of the boxed representation, with
* an underlying value set to the zero of its type. However we
* cannot implement that, so we live with the discrepancy.
*
* In dotc this is usually not an issue, because it unboxes `null` to
* the zero of the underlying type, unlike scalac which throws an NPE.
*/
jstpe.ClassType(encodeClassName(tpe.tycon.typeSymbol))
case _ =>
// Other types are not boxed, so we can initialized them to their true zero.
toIRType(f.info)
}
}
// Static initializers -----------------------------------------------------
private def genStaticConstructorWithStats(name: MethodName, stats: js.Tree)(
implicit pos: Position): js.MethodDef = {
js.MethodDef(
js.MemberFlags.empty.withNamespace(js.MemberNamespace.StaticConstructor),
js.MethodIdent(name),
NoOriginalName,
Nil,
jstpe.NoType,
Some(stats))(
OptimizerHints.empty, None)
}
private def genRegisterReflectiveInstantiation(sym: Symbol)(
implicit pos: SourcePosition): Option[js.Tree] = {
if (isStaticModule(sym))
genRegisterReflectiveInstantiationForModuleClass(sym)
else if (sym.is(ModuleClass))
None // scala-js#3228
else if (sym.is(Lifted) && !sym.originalOwner.isClass)
None // scala-js#3227
else
genRegisterReflectiveInstantiationForNormalClass(sym)
}
private def genRegisterReflectiveInstantiationForModuleClass(sym: Symbol)(
implicit pos: SourcePosition): Option[js.Tree] = {
val fqcnArg = js.StringLiteral(sym.fullName.toString)
val runtimeClassArg = js.ClassOf(toTypeRef(sym.info))
val loadModuleFunArg =
js.Closure(arrow = true, Nil, Nil, None, genLoadModule(sym), Nil)
val stat = genApplyMethod(
genLoadModule(jsdefn.ReflectModule),
jsdefn.Reflect_registerLoadableModuleClass,
List(fqcnArg, runtimeClassArg, loadModuleFunArg))
Some(stat)
}
private def genRegisterReflectiveInstantiationForNormalClass(sym: Symbol)(
implicit pos: SourcePosition): Option[js.Tree] = {
val ctors =
if (sym.is(Abstract)) Nil
else sym.info.member(nme.CONSTRUCTOR).alternatives.map(_.symbol).filter(m => !m.isOneOf(Private | Protected))
if (ctors.isEmpty) {
None
} else {
val constructorsInfos = for {
ctor <- ctors
} yield {