-
Notifications
You must be signed in to change notification settings - Fork 1k
/
PrepJSInterop.scala
1371 lines (1184 loc) · 55.7 KB
/
PrepJSInterop.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.dotc
package transform
package sjs
import scala.collection.mutable
import ast.tpd
import core.*
import typer.Checking
import util.SrcPos
import Annotations.*
import Constants.*
import Contexts.*
import Decorators.*
import DenotTransformers.*
import Flags.*
import NameKinds.{DefaultGetterName, ModuleClassName}
import NameOps.*
import StdNames.*
import Symbols.*
import Types.*
import JSSymUtils.*
import org.scalajs.ir.Trees.JSGlobalRef
import dotty.tools.backend.sjs.JSDefinitions.jsdefn
/** A macro transform that runs after typer and before pickler to perform
* additional Scala.js-specific checks and transformations necessary for
* interoperability with JavaScript.
*
* It performs the following functions:
*
* - Sanity checks for the js.Any hierarchy
* - Annotate subclasses of js.Any to be treated specially
* - Create JSExport methods: Dummy methods that are propagated
* through the whole compiler chain to mark exports. This allows
* exports to have the same semantics than methods.
*
* This is the equivalent of `PrepJSInterop` in Scala 2, minus the handling
* of `scala.Enumeration`.
*
* The reason for making this a macro transform is that some functions (in particular
* all the checks that behave differently depending on properties of classes in
* the enclosing class chain) are naturally top-down and don't lend themselves to the
* bottom-up approach of a mini phase.
*
* In addition, the addition of export forwarders must be done before pickling to
* be signature-compatible with scalac, and there are only macro transforms before
* pickling.
*/
class PrepJSInterop extends MacroTransform with IdentityDenotTransformer { thisPhase =>
import PrepJSInterop.*
import tpd.*
override def phaseName: String = PrepJSInterop.name
override def description: String = PrepJSInterop.description
override def isEnabled(using Context): Boolean =
ctx.settings.scalajs.value
override def changesMembers: Boolean = true // the phase adds export forwarders
protected def newTransformer(using Context): Transformer =
new ScalaJSPrepJSInteropTransformer
class ScalaJSPrepJSInteropTransformer extends Transformer with Checking {
import PrepJSExports.*
/** Kind of the directly enclosing (most nested) owner. */
private var enclosingOwner: OwnerKind = OwnerKind.None
/** Cumulative kinds of all enclosing owners. */
private var allEnclosingOwners: OwnerKind = OwnerKind.None
/** Nicer syntax for `allEnclosingOwners is kind`. */
private def anyEnclosingOwner: OwnerKind = allEnclosingOwners
private def enterOwner[A](kind: OwnerKind)(body: => A): A = {
require(kind.isBaseKind, kind)
val oldEnclosingOwner = enclosingOwner
val oldAllEnclosingOwners = allEnclosingOwners
enclosingOwner = kind
allEnclosingOwners |= kind
try {
body
} finally {
enclosingOwner = oldEnclosingOwner
allEnclosingOwners = oldAllEnclosingOwners
}
}
private var dynamicImportEnclosingClasses: Set[Symbol] = Set.empty
private def enterDynamicImportEnclosingClass[A](cls: Symbol)(body: => A): A = {
val saved = dynamicImportEnclosingClasses
dynamicImportEnclosingClasses = saved + cls
try
body
finally
dynamicImportEnclosingClasses = saved
}
private def hasImplicitThisPrefixToDynamicImportEnclosingClass(tpe: Type)(using Context): Boolean =
tpe match
case tpe: ThisType => dynamicImportEnclosingClasses.contains(tpe.cls)
case TermRef(prefix, _) => hasImplicitThisPrefixToDynamicImportEnclosingClass(prefix)
case _ => false
end hasImplicitThisPrefixToDynamicImportEnclosingClass
/** DefDefs in class templates that export methods to JavaScript */
private val exporters = mutable.Map.empty[Symbol, mutable.ListBuffer[Tree]]
override def transform(tree: Tree)(using Context): Tree = {
tree match {
case tree: ValDef if tree.symbol.is(Module) =>
/* Never apply this transformation on the term definition of modules.
* Instead, all relevant checks are performed on the module class definition.
* We still need to mark exposed if required, since that needs to be done
* on the module symbol, not its module class.
*/
markExposedIfRequired(tree.symbol)
super.transform(tree)
case tree: MemberDef => transformMemberDef(tree)
case tree: Template => transformTemplate(tree)
case _ => transformStatOrExpr(tree)
}
}
private def transformMemberDef(tree: MemberDef)(using Context): Tree = {
val sym = tree.symbol
checkInternalAnnotations(sym)
stripJSAnnotsOnExported(sym)
/* Checks related to @js.native:
* - if @js.native, verify that it is allowed in this context, and if
* yes, compute and store the JS native load spec
* - if not @js.native, verify that we do not use any other annotation
* reserved for @js.native members (namely, JS native load spec annots)
*/
val isJSNative = sym.getAnnotation(jsdefn.JSNativeAnnot) match {
case Some(annot) =>
checkJSNativeDefinition(tree, annot.tree, sym)
true
case None =>
checkJSNativeSpecificAnnotsOnNonJSNative(tree)
false
}
checkJSNameAnnots(sym)
constFoldJSExportTopLevelAndStaticAnnotations(sym)
markExposedIfRequired(tree.symbol)
tree match {
case tree: TypeDef if tree.isClassDef =>
val exports = genExport(sym)
if (exports.nonEmpty)
exporters.getOrElseUpdate(sym.owner, mutable.ListBuffer.empty) ++= exports
if (isJSAny(sym))
transformJSClassDef(tree)
else
transformScalaClassDef(tree)
case _: TypeDef =>
super.transform(tree)
case tree: ValOrDefDef =>
// Prepare exports
val exports = genExport(sym)
if (exports.nonEmpty) {
val target = if (sym.isConstructor) sym.owner.owner else sym.owner
exporters.getOrElseUpdate(target, mutable.ListBuffer.empty) ++= exports
}
if (sym.isLocalToBlock)
super.transform(tree)
else if (isJSNative)
transformJSNativeValOrDefDef(tree)
else if (enclosingOwner is OwnerKind.JSType)
transformValOrDefDefInJSType(tree)
else
transformScalaValOrDefDef(tree)
}
}
private def transformScalaClassDef(tree: TypeDef)(using Context): Tree = {
val sym = tree.symbol
// In native JS things, only js.Any stuff is allowed
if (enclosingOwner is OwnerKind.JSNative) {
/* We have to allow synthetic companion objects here, as they get
* generated when a nested native JS class has default arguments in
* its constructor (see #1891).
*/
if (!sym.is(Synthetic)) {
report.error(
"Native JS traits, classes and objects cannot contain inner Scala traits, classes or objects (i.e., not extending js.Any)",
tree)
}
}
if (sym == jsdefn.PseudoUnionClass)
sym.addAnnotation(jsdefn.JSTypeAnnot)
val kind = if (sym.isSubClass(jsdefn.scalaEnumeration.EnumerationClass)) {
if (sym.is(Module)) OwnerKind.EnumMod
else if (sym == jsdefn.scalaEnumeration.EnumerationClass) OwnerKind.EnumImpl
else OwnerKind.EnumClass
} else {
if (sym.is(Module)) OwnerKind.NonEnumScalaMod
else OwnerKind.NonEnumScalaClass
}
enterOwner(kind) {
super.transform(tree)
}
}
private def transformTemplate(tree: Template)(using Context): Template = {
// First, recursively transform the template
val transformedTree = super.transform(tree).asInstanceOf[Template]
val clsSym = ctx.owner
// Check that @JSExportStatic fields come first
if (clsSym.is(ModuleClass)) { // quick check to avoid useless work
var foundStatOrNonStaticVal: Boolean = false
for (tree <- transformedTree.body) {
tree match {
case vd: ValDef if vd.symbol.hasAnnotation(jsdefn.JSExportStaticAnnot) =>
if (foundStatOrNonStaticVal) {
report.error(
"@JSExportStatic vals and vars must be defined before any other val/var, and before any constructor statement.",
vd)
}
case vd: ValDef if !vd.symbol.is(Lazy) =>
foundStatOrNonStaticVal = true
case _: MemberDef =>
case _ =>
foundStatOrNonStaticVal = true
}
}
}
// Add exports to the template, if there are any
exporters.get(clsSym).fold {
transformedTree
} { exports =>
assert(exports.nonEmpty, s"found empty exporters for $clsSym" )
checkNoDoubleDeclaration(clsSym)
cpy.Template(transformedTree)(
transformedTree.constr,
transformedTree.parents,
Nil,
transformedTree.self,
transformedTree.body ::: exports.toList
)
}
}
private def transformStatOrExpr(tree: Tree)(using Context): Tree = {
tree match {
case Closure(env, call, functionalInterface) =>
val tpeSym = functionalInterface.tpe.typeSymbol
if (tpeSym.isJSType) {
def reportError(reasonAndExplanation: String): Unit = {
report.error(
em"Using an anonymous function as a SAM for the JavaScript type ${
tpeSym.fullName
} is not allowed because $reasonAndExplanation",
tree)
}
if (!tpeSym.is(Trait) || tpeSym.asClass.superClass != jsdefn.JSFunctionClass) {
reportError(
"it is not a trait extending js.Function. " +
"Use an anonymous class instead.")
} else if (tpeSym.hasAnnotation(jsdefn.JSNativeAnnot)) {
reportError(
"it is a native JS type. " +
"It is not possible to directly implement it.")
} else if (!tree.tpe.possibleSamMethods.exists(_.symbol.hasJSCallCallingConvention)) {
reportError(
"its single abstract method is not named `apply`. " +
"Use an anonymous class instead.")
}
}
super.transform(tree)
// Validate js.constructorOf[T]
case TypeApply(ctorOfTree, List(tpeArg))
if ctorOfTree.symbol == jsdefn.JSPackage_constructorOf =>
validateJSConstructorOf(tree, tpeArg)
super.transform(tree)
/* Rewrite js.ConstructorTag.materialize[T] into
* runtime.newConstructorTag[T](js.constructorOf[T])
*/
case TypeApply(ctorOfTree, List(tpeArg))
if ctorOfTree.symbol == jsdefn.JSConstructorTag_materialize =>
validateJSConstructorOf(tree, tpeArg)
val ctorOf = ref(jsdefn.JSPackage_constructorOf).appliedToTypeTree(tpeArg)
ref(jsdefn.Runtime_newConstructorTag).appliedToType(tpeArg.tpe).appliedTo(ctorOf)
/* Rewrite js.dynamicImport[T](body) into
*
* runtime.dynamicImport[T](
* new DynamicImportThunk { def apply(): Any = body }
* )
*/
case Apply(TypeApply(fun, List(tpeArg)), List(body))
if fun.symbol == jsdefn.JSPackage_dynamicImport =>
val span = tree.span
val currentOwner = ctx.owner
assert(currentOwner.isTerm, s"unexpected owner: $currentOwner at ${tree.sourcePos}")
val enclosingClass = currentOwner.enclosingClass
// new DynamicImportThunk { def apply(): Any = body }
val dynamicImportThunkAnonClass = AnonClass(currentOwner, List(jsdefn.DynamicImportThunkType), span) { cls =>
val applySym = newSymbol(cls, nme.apply, Method, MethodType(Nil, Nil, defn.AnyType), coord = span).entered
val transformedBody = enterDynamicImportEnclosingClass(enclosingClass) {
transform(body)
}
val newBody = transformedBody.changeOwnerAfter(currentOwner, applySym, thisPhase)
val applyDefDef = DefDef(applySym, newBody)
List(applyDefDef)
}
// runtime.DynamicImport[A](new ...)
ref(jsdefn.Runtime_dynamicImport)
.appliedToTypeTree(tpeArg)
.appliedTo(dynamicImportThunkAnonClass)
// #17344 Make `ThisType`-based references to enclosing classes of `js.dynamicImport` explicit
case tree: Ident if hasImplicitThisPrefixToDynamicImportEnclosingClass(tree.tpe) =>
def rec(tpe: Type): Tree = (tpe: @unchecked) match // exhaustive because of the `if ... =>`
case tpe: ThisType => This(tpe.cls)
case tpe @ TermRef(prefix, _) => rec(prefix).select(tpe.symbol)
rec(tree.tpe).withSpan(tree.span)
// Compile-time errors and warnings for js.Dynamic.literal
case Apply(Apply(fun, nameArgs), args)
if fun.symbol == jsdefn.JSDynamicLiteral_applyDynamic ||
fun.symbol == jsdefn.JSDynamicLiteral_applyDynamicNamed =>
// Check that the first argument list is a constant string "apply"
nameArgs match {
case List(Literal(Constant(s: String))) =>
if (s != "apply")
report.error(em"js.Dynamic.literal does not have a method named $s", tree)
case _ =>
report.error(em"js.Dynamic.literal.${tree.symbol.name} may not be called directly", tree)
}
// TODO Warn for known duplicate property names
super.transform(tree)
// Warnings for scala.Enumeration.Value that could not be transformed
case _:Ident | _:Select | _:Apply if jsdefn.scalaEnumeration.isValueMethodNoName(tree.symbol) =>
report.warning(
"Could not transform call to scala.Enumeration.Value.\n" +
"The resulting program is unlikely to function properly as this operation requires reflection.",
tree)
super.transform(tree)
// Warnings for scala.Enumeration.Value with a `null` name
case Apply(_, args) if jsdefn.scalaEnumeration.isValueMethodName(tree.symbol) && isNullLiteral(args.last) =>
report.warning(
"Passing null as name to scala.Enumeration.Value requires reflection at run-time.\n" +
"The resulting program is unlikely to function properly.",
tree)
super.transform(tree)
// Warnings for scala.Enumeration.Val without name
case _: Apply if jsdefn.scalaEnumeration.isValCtorNoName(tree.symbol) =>
report.warning(
"Calls to the non-string constructors of scala.Enumeration.Val require reflection at run-time.\n" +
"The resulting program is unlikely to function properly.",
tree)
super.transform(tree)
// Warnings for scala.Enumeration.Val with a `null` name
case Apply(_, args) if jsdefn.scalaEnumeration.isValCtorName(tree.symbol) && isNullLiteral(args.last) =>
report.warning(
"Passing null as name to a constructor of scala.Enumeration.Val requires reflection at run-time.\n" +
"The resulting program is unlikely to function properly.",
tree)
super.transform(tree)
case _: Export =>
if enclosingOwner is OwnerKind.JSNative then
report.error("Native JS traits, classes and objects cannot contain exported definitions.", tree)
else if enclosingOwner is OwnerKind.JSTrait then
report.error("Non-native JS traits cannot contain exported definitions.", tree)
super.transform(tree)
case _ =>
super.transform(tree)
}
}
private def isNullLiteral(tree: Tree): Boolean = tree match
case Literal(Constant(null)) => true
case _ => false
private def validateJSConstructorOf(tree: Tree, tpeArg: Tree)(using Context): Unit = {
val tpe = checkClassType(tpeArg.tpe, tpeArg.srcPos, traitReq = false, stablePrefixReq = false)
tpe.underlyingClassRef(refinementOK = false) match {
case typeRef: TypeRef if typeRef.symbol.isOneOf(Trait | ModuleClass) =>
report.error(em"non-trait class type required but $tpe found", tpeArg)
case _ =>
// an error was already reported above
}
}
/** Performs checks and rewrites specific to classes / objects extending `js.Any`. */
private def transformJSClassDef(classDef: TypeDef)(using Context): Tree = {
val sym = classDef.symbol.asClass
val isJSNative = sym.hasAnnotation(jsdefn.JSNativeAnnot)
sym.addAnnotation(jsdefn.JSTypeAnnot)
// Forbid @EnableReflectiveInstantiation on JS types
sym.getAnnotation(jsdefn.EnableReflectiveInstantiationAnnot).foreach { annot =>
report.error(
"@EnableReflectiveInstantiation cannot be used on types extending js.Any.",
annot.tree)
}
// Forbid package objects that extends js.Any
if (sym.isPackageObject)
report.error("Package objects may not extend js.Any.", classDef)
// Check that we do not have a case modifier
if (sym.is(Case)) {
report.error(
"Classes and objects extending js.Any may not have a case modifier",
classDef)
}
// Check the parents
for (parentSym <- sym.parentSyms) {
parentSym match {
case parentSym if parentSym == defn.ObjectClass =>
// AnyRef is valid, except for non-native JS classes and objects
if (!isJSNative && !sym.is(Trait)) {
report.error(
"Non-native JS classes and objects cannot directly extend AnyRef. They must extend a JS class (native or not).",
classDef)
}
case parentSym if isJSAny(parentSym) =>
// A non-native JS type cannot extend a native JS trait
// Otherwise, extending a JS type is valid
if (!isJSNative && parentSym.is(Trait) && parentSym.hasAnnotation(jsdefn.JSNativeAnnot)) {
report.error(
"Non-native JS types cannot directly extend native JS traits.",
classDef)
}
case parentSym if parentSym == defn.DynamicClass =>
/* We have to allow scala.Dynamic to be able to define js.Dynamic
* and similar constructs.
* This causes the unsoundness filed as scala-js/scala-js#1385.
*/
case parentSym =>
/* This is a Scala class or trait other than AnyRef and Dynamic,
* which is never valid.
*/
report.error(
em"${sym.name} extends ${parentSym.fullName} which does not extend js.Any.",
classDef)
}
}
// Checks for non-native JS stuff
if (!isJSNative) {
// It cannot be in a native JS class or trait
if (enclosingOwner is OwnerKind.JSNativeClass) {
report.error(
"Native JS classes and traits cannot contain non-native JS classes, traits or objects",
classDef)
}
// Unless it is a trait, it cannot be in a native JS object
if (!sym.is(Trait) && (enclosingOwner is OwnerKind.JSNativeMod)) {
report.error(
"Native JS objects cannot contain inner non-native JS classes or objects",
classDef)
}
// Local JS classes cannot be abstract (implementation restriction)
if (sym.is(Abstract, butNot = Trait) && sym.isLocalToBlock) {
report.error(
"Implementation restriction: local JS classes cannot be abstract",
classDef)
}
}
// Check for consistency of JS semantics across overriding
val overridingPairsCursor = new OverridingPairs.Cursor(sym)
while (overridingPairsCursor.hasNext) {
val overriding = overridingPairsCursor.overriding
val overridden = overridingPairsCursor.overridden
overridingPairsCursor.next() // prepare for next turn
val clsSym = sym
if (overriding.isTerm) {
def errorPos = {
if (clsSym == overriding.owner) overriding.srcPos
else if (clsSym == overridden.owner) overridden.srcPos
else clsSym.srcPos
}
// Some utils inspired by RefChecks
def infoString0(sym: Symbol, showLocation: Boolean): String = {
val sym1 = sym.underlyingSymbol
def info = clsSym.thisType.memberInfo(sym1)
val infoStr =
if (sym1.is(Module)) ""
else i" of type $info"
val ccStr = s" called from JS as '${sym.jsCallingConvention.displayName}'"
i"${if (showLocation) sym1.showLocated else sym1}$infoStr$ccStr"
}
def infoString(sym: Symbol): String = infoString0(sym, sym.owner != clsSym)
def infoStringWithLocation(sym: Symbol): String = infoString0(sym, true)
def emitOverrideError(msg: String): Unit = {
report.error(
em"""error overriding ${infoStringWithLocation(overridden)};
| ${infoString(overriding)} $msg""",
errorPos)
}
// Check for overrides with different JS names - issue scala-js/scala-js#1983
if (overriding.jsCallingConvention != overridden.jsCallingConvention)
emitOverrideError("has a different JS calling convention")
/* Cannot override a non-@JSOptional with an @JSOptional. Unfortunately
* at this point the symbols do not have @JSOptional yet, so we need
* to detect whether it would be applied.
*/
if (!isJSNative) {
def isJSOptional(sym: Symbol): Boolean = {
sym.owner.is(Trait) && !sym.is(Deferred) && !sym.isConstructor &&
!sym.owner.hasAnnotation(jsdefn.JSNativeAnnot)
}
if (isJSOptional(overriding) && !(overridden.is(Deferred) || isJSOptional(overridden)))
emitOverrideError("cannot override a concrete member in a non-native JS trait")
}
}
}
val kind = {
if (!isJSNative) {
if (sym.is(ModuleClass)) OwnerKind.JSMod
else if (sym.is(Trait)) OwnerKind.JSTrait
else OwnerKind.JSNonTraitClass
} else {
if (sym.is(ModuleClass)) OwnerKind.JSNativeMod
else OwnerKind.JSNativeClass
}
}
enterOwner(kind) {
super.transform(classDef)
}
}
private def checkJSNativeDefinition(treePos: SrcPos, annotPos: SrcPos, sym: Symbol)(using Context): Unit = {
// Check if we may have a JS native here
if (sym.isLocalToBlock) {
report.error("@js.native is not allowed on local definitions", annotPos)
} else if (!sym.isClass && (anyEnclosingOwner is (OwnerKind.ScalaClass | OwnerKind.JSType))) {
report.error("@js.native vals and defs can only appear in static Scala objects", annotPos)
} else if (sym.isClass && !isJSAny(sym)) {
report.error("Classes, traits and objects not extending js.Any may not have an @js.native annotation", annotPos)
} else if (anyEnclosingOwner is OwnerKind.ScalaClass) {
report.error("Scala traits and classes may not have native JS members", annotPos)
} else if (enclosingOwner is OwnerKind.JSNonNative) {
report.error("non-native JS classes, traits and objects may not have native JS members", annotPos)
} else {
// The symbol can be annotated with @js.native. Now check its JS native loading spec.
if (sym.is(Trait)) {
for (annot <- sym.annotations) {
val annotSym = annot.symbol
if (isJSNativeLoadingSpecAnnot(annotSym))
report.error(em"Traits may not have an @${annotSym.name} annotation.", annot.tree)
}
} else {
checkJSNativeLoadSpecOf(treePos, sym)
}
}
}
private def checkJSNativeLoadSpecOf(pos: SrcPos, sym: Symbol)(using Context): Unit = {
def checkGlobalRefName(globalRef: String): Unit = {
if (!JSGlobalRef.isValidJSGlobalRefName(globalRef))
report.error(em"The name of a JS global variable must be a valid JS identifier (got '$globalRef')", pos)
}
if (enclosingOwner is OwnerKind.JSNative) {
/* We cannot get here for @js.native vals and defs. That would mean we
* have an @js.native val/def inside a JavaScript type, which is not
* allowed and already caught in checkJSNativeDefinition().
*/
assert(sym.isClass,
s"undetected @js.native val or def ${sym.fullName} inside JS type at $pos")
for (annot <- sym.annotations) {
val annotSym = annot.symbol
if (isJSNativeLoadingSpecAnnot(annotSym))
report.error(em"Nested JS classes and objects cannot have an @${annotSym.name} annotation.", annot.tree)
}
if (sym.owner.isStaticOwner) {
for (annot <- sym.annotations) {
if (annot.symbol == jsdefn.JSNameAnnot && !(annot.arguments.head.tpe.derivesFrom(defn.StringClass))) {
report.error(
"Implementation restriction: " +
"@JSName with a js.Symbol is not supported on nested native classes and objects",
annot.tree)
}
}
if (sym.owner.hasAnnotation(jsdefn.JSGlobalScopeAnnot)) {
val jsName = sym.jsName match {
case JSName.Literal(jsName) =>
checkGlobalRefName(jsName)
case JSName.Computed(_) =>
() // compile error above or in `checkJSNameArgument`
}
}
}
} else {
def checkGlobalRefPath(pathName: String): Unit = {
val dotIndex = pathName.indexOf('.')
val globalRef =
if (dotIndex < 0) pathName
else pathName.substring(0, dotIndex).nn
checkGlobalRefName(globalRef)
}
checkAndGetJSNativeLoadingSpecAnnotOf(pos, sym) match {
case Some(annot) if annot.symbol == jsdefn.JSGlobalScopeAnnot =>
if (!sym.is(Module)) {
report.error(
"@JSGlobalScope can only be used on native JS objects (with @js.native).",
annot.tree)
}
case Some(annot) if annot.symbol == jsdefn.JSGlobalAnnot =>
checkJSGlobalLiteral(annot)
val pathName = annot.argumentConstantString(0).getOrElse {
val symTermName = sym.name.exclude(NameKinds.ModuleClassName).toTermName
if (symTermName == nme.apply) {
report.error(
"Native JS definitions named 'apply' must have an explicit name in @JSGlobal",
annot.tree)
} else if (symTermName.isSetterName) {
report.error(
"Native JS definitions with a name ending in '_=' must have an explicit name in @JSGlobal",
annot.tree)
}
sym.defaultJSName
}
checkGlobalRefPath(pathName)
case Some(annot) if annot.symbol == jsdefn.JSImportAnnot =>
checkJSImportLiteral(annot)
if (annot.arguments.sizeIs < 2) {
val symTermName = sym.name.exclude(NameKinds.ModuleClassName).toTermName
if (symTermName == nme.apply) {
report.error(
"Native JS definitions named 'apply' must have an explicit name in @JSImport",
annot.tree)
} else if (symTermName.isSetterName) {
report.error(
"Native JS definitions with a name ending in '_=' must have an explicit name in @JSImport",
annot.tree)
}
}
annot.argumentConstantString(2).foreach { globalPathName =>
checkGlobalRefPath(globalPathName)
}
case _ =>
// We already emitted an error in checkAndGetJSNativeLoadingSpecAnnotOf
()
}
}
}
/** Transforms a non-`@js.native` ValDef or DefDef in a Scala class. */
private def transformScalaValOrDefDef(tree: ValOrDefDef)(using Context): Tree = {
tree match {
// Catch ValDefs in enumerations with simple calls to Value
case vd: ValDef
if (enclosingOwner is OwnerKind.Enum) && jsdefn.scalaEnumeration.isValueMethodNoName(vd.rhs.symbol) =>
val enumDefn = jsdefn.scalaEnumeration
// Extract the Int argument if it is present
val optIntArg = vd.rhs match {
case _:Select | _:Ident => None
case Apply(_, intArg :: Nil) => Some(intArg)
}
val defaultName = vd.name.getterName.encode.toString
/* Construct the following tree
*
* if (nextName != null && nextName.hasNext)
* nextName.next()
* else
* <defaultName>
*/
val thisClass = vd.symbol.owner.asClass
val nextNameTree = This(thisClass).select(enumDefn.Enumeration_nextName)
val nullCompTree = nextNameTree.select(nme.NE).appliedTo(Literal(Constant(null)))
val hasNextTree = nextNameTree.select(enumDefn.hasNext)
val condTree = nullCompTree.select(nme.ZAND).appliedTo(hasNextTree)
val nameTree = If(condTree, nextNameTree.select(enumDefn.next).appliedToNone, Literal(Constant(defaultName)))
val newRhs = optIntArg match {
case None =>
This(thisClass).select(enumDefn.Enumeration_Value_StringArg).appliedTo(nameTree)
case Some(intArg) =>
This(thisClass).select(enumDefn.Enumeration_Value_IntStringArg).appliedTo(intArg, nameTree)
}
cpy.ValDef(vd)(rhs = newRhs)
case _ =>
super.transform(tree)
}
}
/** Verify a ValOrDefDef that is annotated with `@js.native`. */
private def transformJSNativeValOrDefDef(tree: ValOrDefDef)(using Context): ValOrDefDef = {
val sym = tree.symbol
def annotPos(annotSym: Symbol): SrcPos =
sym.getAnnotation(annotSym).get.tree
if (sym.is(Lazy) || sym.isJSSetter)
report.error("@js.native is not allowed on vars, lazy vals and setter defs", annotPos(jsdefn.JSNativeAnnot))
else if (sym.isJSBracketAccess)
report.error("@JSBracketAccess is not allowed on @js.native vals and defs", annotPos(jsdefn.JSBracketAccessAnnot))
else if (sym.isJSBracketCall)
report.error("@JSBracketCall is not allowed on @js.native vals and defs", annotPos(jsdefn.JSBracketCallAnnot))
checkRHSCallsJSNative(tree, "@js.native members")
// Check that we do not override or implement anything from a superclass
val overriddenSymbols = sym.allOverriddenSymbols
if (overriddenSymbols.hasNext) {
val overridden = overriddenSymbols.next()
val verb = if (overridden.is(Deferred)) "implement" else "override"
report.error(em"An @js.native member cannot $verb the inherited member ${overridden.fullName}", tree)
}
tree
}
/** Verify a ValOrDefDef inside a js.Any */
private def transformValOrDefDefInJSType(tree: ValOrDefDef)(using Context): Tree = {
val sym = tree.symbol
assert(!sym.isLocalToBlock, i"$tree at ${tree.span}")
sym.name match {
case nme.apply if !sym.hasAnnotation(jsdefn.JSNameAnnot) && (!sym.is(Method) || sym.isJSGetter) =>
report.error(
"A member named apply represents function application in JavaScript. " +
"A parameterless member should be exported as a property. " +
"You must add @JSName(\"apply\")",
sym)
case nme.equals_ if sym.info.matches(defn.Any_equals.info) =>
report.error(
"error overriding method equals(that: Any): Boolean in a JS class;\n" +
" method equals(that: Any): Boolean is considered final in trait js.Any;\n" +
" if you want to define a method named \"equals\" in JavaScript, use a different name and add @JSName(\"equals\").",
sym)
case nme.hashCode_ if sym.info.matches(defn.Any_hashCode.info) =>
report.error(
"error overriding method hashCode(): Int in a JS class;\n" +
" method hashCode(): Int is considered final in trait js.Any;\n" +
" if you want to define a method named \"hashCode\" in JavaScript, use a different name and add @JSName(\"hashCode\").",
sym)
case _ =>
}
if (sym.isJSSetter)
checkSetterSignature(sym, tree, exported = false)
if (enclosingOwner is OwnerKind.JSNonNative) {
JSCallingConvention.of(sym) match {
case JSCallingConvention.Property(_) => // checked above
case JSCallingConvention.Method(_) => // no checks needed
case JSCallingConvention.Call if !sym.is(Deferred) =>
report.error("A non-native JS class cannot declare a concrete method named `apply` without `@JSName`", tree)
case JSCallingConvention.Call => // if sym.isDeferred
/* Allow an abstract `def apply` only if the owner is a plausible
* JS function SAM trait.
*/
val owner = sym.owner
val isPlausibleJSFunctionType = {
owner.is(Trait) &&
owner.asClass.superClass == jsdefn.JSFunctionClass &&
owner.typeRef.possibleSamMethods.map(_.symbol) == Seq(sym) &&
!sym.info.isInstanceOf[PolyType]
}
if (!isPlausibleJSFunctionType) {
report.error(
"A non-native JS type can only declare an abstract method named `apply` without `@JSName` " +
"if it is the SAM of a trait that extends js.Function",
tree)
}
case JSCallingConvention.BracketAccess =>
report.error("@JSBracketAccess is not allowed in non-native JS classes", tree)
case JSCallingConvention.BracketCall =>
report.error("@JSBracketCall is not allowed in non-native JS classes", tree)
case JSCallingConvention.UnaryOp(_) =>
report.error("A non-native JS class cannot declare a method named like a unary operation without `@JSName`", tree)
case JSCallingConvention.BinaryOp(_) =>
report.error("A non-native JS class cannot declare a method named like a binary operation without `@JSName`", tree)
}
} else {
def checkNoDefaultOrRepeated(subject: String) = {
if (sym.info.paramInfoss.flatten.exists(_.isRepeatedParam))
report.error(s"$subject may not have repeated parameters", tree)
if (sym.hasDefaultParams)
report.error(s"$subject may not have default parameters", tree)
}
JSCallingConvention.of(sym) match {
case JSCallingConvention.Property(_) => // checked above
case JSCallingConvention.Method(_) => // no checks needed
case JSCallingConvention.Call => // no checks needed
case JSCallingConvention.UnaryOp(_) => // no checks needed
case JSCallingConvention.BinaryOp(_) =>
checkNoDefaultOrRepeated("methods representing binary operations")
case JSCallingConvention.BracketAccess =>
val paramCount = sym.info.paramNamess.map(_.size).sum
if (paramCount != 1 && paramCount != 2)
report.error("@JSBracketAccess methods must have one or two parameters", tree)
else if (paramCount == 2 && !sym.info.finalResultType.isRef(defn.UnitClass))
report.error("@JSBracketAccess methods with two parameters must return Unit", tree)
checkNoDefaultOrRepeated("@JSBracketAccess methods")
case JSCallingConvention.BracketCall =>
// JS bracket calls must have at least one non-repeated parameter
sym.info.stripPoly match {
case mt: MethodType if mt.paramInfos.nonEmpty && !mt.paramInfos.head.isRepeatedParam =>
// ok
case _ =>
report.error("@JSBracketCall methods must have at least one non-repeated parameter", tree)
}
}
}
if (sym.hasAnnotation(defn.NativeAnnot)) {
// Native methods are not allowed
report.error("Methods in a js.Any may not be @native", tree)
}
/* In native JS types, there should not be any private member, except
* private[this] constructors.
*/
if ((enclosingOwner is OwnerKind.JSNative) && isPrivateMaybeWithin(sym)) {
if (sym.isClassConstructor) {
if (!sym.isAllOf(PrivateLocal)) {
report.error(
"Native JS classes may not have private constructors. " +
"Use `private[this]` to declare an internal constructor.",
sym)
}
} else if (!sym.is(ParamAccessor)) {
report.error(
"Native JS classes may not have private members. " +
"Use a public member in a private facade instead.",
tree)
}
}
if (enclosingOwner is OwnerKind.JSNonNative) {
// Private methods cannot be overloaded
if (sym.is(Method) && isPrivateMaybeWithin(sym)) {
val alts = sym.owner.info.memberBasedOnFlags(sym.name, required = Method)
if (alts.isOverloaded) {
report.error(
"Private methods in non-native JS classes cannot be overloaded. Use different names instead.",
tree)
}
}
// private[Scope] methods must be final
if (!sym.isOneOf(Final | Protected) && sym.privateWithin.exists && !sym.isClassConstructor)
report.error("Qualified private members in non-native JS classes must be final", tree)
// Traits must be pure interfaces, except for js.undefined members
if (sym.owner.is(Trait) && sym.isTerm && !sym.isConstructor) {
if (sym.is(Method) && isPrivateMaybeWithin(sym)) {
report.error("A non-native JS trait cannot contain private members", tree)
} else if (sym.is(Lazy)) {
report.error("A non-native JS trait cannot contain lazy vals", tree)
} else if (sym.is(ParamAccessor)) {
// #12621
report.error("A non-native JS trait cannot have constructor parameters", tree)
} else if (!sym.is(Deferred)) {
/* Tell the back-end not to emit this thing. In fact, this only
* matters for mixed-in members created from this member.
*/
sym.addAnnotation(jsdefn.JSOptionalAnnot)
if (!sym.isSetter) {
// Check that methods do not have parens
if (sym.is(Method, butNot = Accessor) && sym.info.stripPoly.isInstanceOf[MethodType])
report.error("In non-native JS traits, defs with parentheses must be abstract.", tree.rhs)
// Check that the rhs is `js.undefined`
tree.rhs match {
case sel: Select if sel.symbol == jsdefn.JSPackage_undefined =>
// ok
case Apply(Apply(TypeApply(fromTypeConstructorFun, _), (sel: Select) :: Nil), _)
if sel.symbol == jsdefn.JSPackage_undefined
&& fromTypeConstructorFun.symbol == jsdefn.PseudoUnion_fromTypeConstructor =>
// ok: js.|.fromTypeConstructor(js.undefined)(...)
case _ =>
report.error(
"Members of non-native JS traits must either be abstract, or their right-hand-side must be `js.undefined`.",
tree)
}
}
}
}
} else { // enclosingOwner isnt OwnerKind.JSNonNative
// Check that the rhs is valid
if (sym.isPrimaryConstructor || sym.isOneOf(Param | ParamAccessor | Deferred | Synthetic)
|| sym.name.is(DefaultGetterName) || sym.isSetter) {
/* Ignore, i.e., allow:
* - primary constructor
* - all kinds of parameters
* - setters
* - default parameter getters (i.e., the default value of parameters)
* - abstract members
* - synthetic members (to avoid double errors with case classes, e.g. generated copy method)
*/
} else if (sym.isConstructor) {
// Force secondary ctor to have only a call to the primary ctor inside
tree.rhs match {
case Block(List(Apply(trg, _)), Literal(Constant(())))
if trg.symbol.isPrimaryConstructor && trg.symbol.owner == sym.owner =>
// everything is fine here
case _ =>
report.error(
"A secondary constructor of a native JS class may only call the primary constructor",
tree.rhs)
}
} else {
// Check that the tree's rhs is exactly `= js.native`
checkRHSCallsJSNative(tree, "Concrete members of JS native types")
}
}
super.transform(tree)
}
/** Removes annotations from exported definitions (e.g. `export foo.bar`):
* - `js.native`
* - `js.annotation.*`
*/
private def stripJSAnnotsOnExported(sym: Symbol)(using Context): Unit =
if !sym.is(Exported) then
return // only remove annotations from exported definitions
val JSNativeAnnot = jsdefn.JSNativeAnnot