-
Notifications
You must be signed in to change notification settings - Fork 384
/
PrepJSInterop.scala
1542 lines (1356 loc) · 57.2 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
/*
* Scala.js (https://www.scala-js.org/)
*
* Copyright EPFL.
*
* Licensed under Apache License 2.0
* (https://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package org.scalajs.nscplugin
import scala.tools.nsc
import nsc._
import scala.collection.immutable.ListMap
import scala.collection.mutable
import org.scalajs.ir.Trees.{JSGlobalRef, JSNativeLoadSpec}
/** Prepares classes extending js.Any for JavaScript interop
*
* This phase does:
* - Sanity checks for js.Any hierarchy
* - Annotate subclasses of js.Any to be treated specially
* - Rewrite calls to scala.Enumeration.Value (include name string)
* - 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.
*
* @author Tobias Schlatter
*/
abstract class PrepJSInterop[G <: Global with Singleton](val global: G)
extends plugins.PluginComponent with PrepJSExports[G]
with transform.Transform with CompatComponent {
import PrepJSInterop._
/** Not for use in the constructor body: only initialized afterwards. */
val jsAddons: JSGlobalAddons {
val global: PrepJSInterop.this.global.type
}
/** Not for use in the constructor body: only initialized afterwards. */
val scalaJSOpts: ScalaJSOptions
import global._
import jsAddons._
import definitions._
import rootMirror._
import jsDefinitions._
import jsInterop.JSName
val phaseName: String = "jsinterop"
override def description: String = "prepare ASTs for JavaScript interop"
override def newPhase(p: nsc.Phase): StdPhase = new JSInteropPhase(p)
class JSInteropPhase(prev: nsc.Phase) extends Phase(prev) {
override def name: String = phaseName
override def description: String = PrepJSInterop.this.description
override def run(): Unit = {
jsPrimitives.initPrepJSPrimitives()
jsInterop.clearGlobalState()
super.run()
}
}
override protected def newTransformer(unit: CompilationUnit): Transformer =
new JSInteropTransformer(unit)
private object jsnme {
val hasNext = newTermName("hasNext")
val next = newTermName("next")
val nextName = newTermName("nextName")
val Value = newTermName("Value")
val Val = newTermName("Val")
val ArrowAssoc = newTermName("ArrowAssoc")
}
class JSInteropTransformer(unit: CompilationUnit) extends Transformer {
/** 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
/** Nicer syntax for `allEnclosingOwners isnt kind`. */
private object noEnclosingOwner {
@inline def is(kind: OwnerKind): Boolean =
allEnclosingOwners isnt kind
}
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
}
}
/** Tests whether this is a ScalaDoc run.
*
* There are some things we must not do in ScalaDoc runs because, because
* ScalaDoc runs don't do everything we need, for example constant-folding
* 'final val's.
*
* At the same time, it's no big deal to skip these things, because we
* won't reach the backend.
*
* We don't completely disable this phase under ScalaDoc mostly because
* we want to keep the addition of `JSType` annotations, so that they
* appear in the doc.
*
* Preparing exports, however, is a pure waste of time, which we cannot
* do properly anyway because of the aforementioned limitation.
*/
private def forScaladoc = global.isInstanceOf[doc.ScaladocGlobal]
/** Whether to check that we have proper literals in some crucial places. */
private def shouldCheckLiterals = !forScaladoc
/** Whether to check and prepare exports. */
private def shouldPrepareExports = !forScaladoc
/** DefDefs in class templates that export methods to JavaScript */
private val exporters = mutable.Map.empty[Symbol, mutable.ListBuffer[Tree]]
override def transform(tree: Tree): Tree = {
tree match {
case tree: MemberDef => transformMemberDef(tree)
case tree: Template => transformTemplateTree(tree)
case _ => transformStatOrExpr(tree)
}
}
private def transformMemberDef(tree: MemberDef): Tree = {
val sym = moduleToModuleClass(tree.symbol)
checkInternalAnnotations(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.hasAnnotation(JSNativeAnnotation)
if (isJSNative)
checkJSNativeDefinition(tree.pos, sym)
else
checkJSNativeSpecificAnnotsOnNonJSNative(tree)
checkJSNameAnnots(sym)
val transformedTree: Tree = tree match {
case tree: ImplDef =>
if (shouldPrepareExports)
registerClassOrModuleExports(sym)
if (isJSAny(sym))
transformJSImplDef(tree)
else
transformScalaImplDef(tree)
case tree: ValOrDefDef =>
/* Prepare exports for methods, local defs and local variables.
* Avoid *fields* (non-local non-method) because they all have a
* corresponding getter, which is the one that handles exports.
* (Note that local-to-block can never have exports, but the error
* messages for that are handled by genExportMember).
*/
if (shouldPrepareExports && (sym.isMethod || sym.isLocalToBlock)) {
exporters.getOrElseUpdate(sym.owner, mutable.ListBuffer.empty) ++=
genExportMember(sym)
}
if (sym.isLocalToBlock) {
super.transform(tree)
} else if (isJSNative) {
transformJSNativeValOrDefDef(tree)
} else if (enclosingOwner is OwnerKind.JSType) {
val fixedTree = tree match {
case tree: DefDef => fixPublicBeforeTyper(tree)
case _ => tree
}
transformValOrDefDefInJSType(fixedTree)
} else {
transformScalaValOrDefDef(tree)
}
case _:TypeDef | _:PackageDef =>
super.transform(tree)
}
/* Give tree.symbol, not sym, so that for modules it is the module
* symbol, not the module class symbol.
*
* #1899 This must be done *after* transforming the member def tree,
* because fixPublicBeforeTyper must have run.
*/
markExposedIfRequired(tree.symbol)
transformedTree
}
private def transformScalaImplDef(tree: ImplDef): Tree = {
val sym = moduleToModuleClass(tree.symbol)
val isModuleDef = tree.isInstanceOf[ModuleDef]
// 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.isSynthetic) {
reporter.error(tree.pos,
"Native JS traits, classes and objects cannot contain inner " +
"Scala traits, classes or objects (i.e., not extending js.Any)")
}
}
if (sym == UnionClass)
sym.addAnnotation(JSTypeAnnot)
val kind = if (sym.isSubClass(ScalaEnumClass)) {
if (isModuleDef) OwnerKind.EnumMod
else if (sym == ScalaEnumClass) OwnerKind.EnumImpl
else OwnerKind.EnumClass
} else {
if (isModuleDef) OwnerKind.NonEnumScalaMod
else OwnerKind.NonEnumScalaClass
}
enterOwner(kind) {
super.transform(tree)
}
}
private def transformScalaValOrDefDef(tree: ValOrDefDef): Tree = {
tree match {
// Catch ValDefs in enumerations with simple calls to Value
case ValDef(mods, name, tpt, ScalaEnumValue.NoName(optPar))
if anyEnclosingOwner is OwnerKind.Enum =>
val nrhs = ScalaEnumValName(tree.symbol.owner, tree.symbol, optPar)
treeCopy.ValDef(tree, mods, name, transform(tpt), nrhs)
// Exporter generation
case _ =>
super.transform(tree)
}
}
private def transformTemplateTree(tree: Template): Template = {
val Template(parents, self, body) = tree
/* Do not transform `self`. We do not need to perform any checks on
* it (#3998).
*/
val transformedParents = parents.map(transform(_))
val nonTransformedSelf = self
val transformedBody = body.map(transform(_))
val clsSym = tree.symbol.owner
// Check that @JSExportStatic fields come first
if (clsSym.isModuleClass) { // quick check to avoid useless work
var foundStatOrNonStaticVal: Boolean = false
for (tree <- transformedBody) {
tree match {
case vd: ValDef if vd.symbol.hasAnnotation(JSExportStaticAnnotation) =>
if (foundStatOrNonStaticVal) {
reporter.error(vd.pos,
"@JSExportStatic vals and vars must be defined before " +
"any other val/var, and before any constructor " +
"statement.")
}
case vd: ValDef if !vd.symbol.isLazy =>
foundStatOrNonStaticVal = true
case _: MemberDef =>
case _ =>
foundStatOrNonStaticVal = true
}
}
}
// Add exports to the template, if there are any
val transformedBodyWithExports = exporters.get(clsSym).fold {
transformedBody
} { exports =>
transformedBody ::: exports.toList
}
treeCopy.Template(tree, transformedParents, nonTransformedSelf,
transformedBodyWithExports)
}
private def transformStatOrExpr(tree: Tree): Tree = {
tree match {
/* Anonymous function, need to check that it is not used as a SAM for a
* JS type, unless it is js.FunctionN or js.ThisFunctionN.
* See #2921.
*/
case tree: Function =>
val tpeSym = tree.tpe.typeSymbol
if (isJSAny(tpeSym) && !AllJSFunctionClasses.contains(tpeSym)) {
reporter.error(tree.pos,
"Using an anonymous function as a SAM for the JavaScript " +
"type " + tpeSym.fullNameString + " is not allowed. " +
"Use an anonymous class instead.")
}
super.transform(tree)
// Catch Select on Enumeration.Value we couldn't transform but need to
// we ignore the implementation of scala.Enumeration itself
case ScalaEnumValue.NoName(_) if noEnclosingOwner is OwnerKind.EnumImpl =>
reporter.warning(tree.pos,
"""Couldn't transform call to Enumeration.Value.
|The resulting program is unlikely to function properly as this
|operation requires reflection.""".stripMargin)
super.transform(tree)
case ScalaEnumValue.NullName() if noEnclosingOwner is OwnerKind.EnumImpl =>
reporter.warning(tree.pos,
"""Passing null as name to Enumeration.Value
|requires reflection at runtime. The resulting
|program is unlikely to function properly.""".stripMargin)
super.transform(tree)
case ScalaEnumVal.NoName(_) if noEnclosingOwner is OwnerKind.EnumImpl =>
reporter.warning(tree.pos,
"""Calls to the non-string constructors of Enumeration.Val
|require reflection at runtime. The resulting
|program is unlikely to function properly.""".stripMargin)
super.transform(tree)
case ScalaEnumVal.NullName() if noEnclosingOwner is OwnerKind.EnumImpl =>
reporter.warning(tree.pos,
"""Passing null as name to a constructor of Enumeration.Val
|requires reflection at runtime. The resulting
|program is unlikely to function properly.""".stripMargin)
super.transform(tree)
// Validate js.constructorOf[T]
case TypeApply(ctorOfTree, List(tpeArg))
if ctorOfTree.symbol == 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 == JSConstructorTag_materialize =>
validateJSConstructorOf(tree, tpeArg)
typer.typed {
atPos(tree.pos) {
val ctorOf = gen.mkTypeApply(
gen.mkAttributedRef(JSPackage_constructorOf), List(tpeArg))
gen.mkMethodCall(Runtime_newConstructorTag,
List(tpeArg.tpe), List(ctorOf))
}
}
/* Catch calls to Predef.classOf[T]. These should NEVER reach this phase
* but unfortunately do. In normal cases, the typer phase replaces these
* calls by a literal constant of the given type. However, when we compile
* the scala library itself and Predef.scala is in the sources, this does
* not happen.
*
* The trees reach this phase under the form:
*
* scala.this.Predef.classOf[T]
*
* or, as of Scala 2.12.0, as:
*
* scala.Predef.classOf[T]
*
* or so it seems, at least.
*
* If we encounter such a tree, depending on the plugin options, we fail
* here or silently fix those calls.
*/
case TypeApply(classOfTree @ Select(predef, nme.classOf), List(tpeArg))
if predef.symbol == PredefModule =>
if (scalaJSOpts.fixClassOf) {
// Replace call by literal constant containing type
if (typer.checkClassType(tpeArg)) {
typer.typed { Literal(Constant(tpeArg.tpe.dealias.widen)) }
} else {
reporter.error(tpeArg.pos, s"Type ${tpeArg} is not a class type")
EmptyTree
}
} else {
reporter.error(classOfTree.pos,
"""This classOf resulted in an unresolved classOf in the jscode
|phase. This is most likely a bug in the Scala compiler. ScalaJS
|is probably able to work around this bug. Enable the workaround
|by passing the fixClassOf option to the plugin.""".stripMargin)
EmptyTree
}
// Compile-time errors and warnings for js.Dynamic.literal
case Apply(Apply(fun, nameArgs), args)
if fun.symbol == JSDynamicLiteral_applyDynamic ||
fun.symbol == JSDynamicLiteral_applyDynamicNamed =>
// Check that the first argument list is a constant string "apply"
nameArgs match {
case List(Literal(Constant(s: String))) =>
if (s != "apply") {
reporter.error(tree.pos,
s"js.Dynamic.literal does not have a method named $s")
}
case _ =>
reporter.error(tree.pos,
s"js.Dynamic.literal.${tree.symbol.name} may not be " +
"called directly")
}
// Warn for known duplicate property names
val knownPropNames = mutable.Set.empty[String]
for (arg <- args) {
def processPropName(propNameTree: Tree): Unit = {
propNameTree match {
case Literal(Constant(propName: String)) =>
if (!knownPropNames.add(propName)) {
reporter.warning(propNameTree.pos,
s"""Duplicate property "$propName" shadows a """ +
"previously defined one")
}
case _ =>
// ignore
}
}
arg match {
case Apply(fun, List(propNameTree, _))
if fun.symbol == Tuple2_apply =>
processPropName(propNameTree)
case Apply(fun @ TypeApply(Select(receiver, nme.MINGT), _), _)
if currentRun.runDefinitions.isArrowAssoc(fun.symbol) =>
receiver match {
case Apply(TypeApply(Select(predef, jsnme.ArrowAssoc), _),
List(propNameTree))
if predef.symbol == PredefModule =>
processPropName(propNameTree)
case _ =>
// ignore
}
case _ =>
// ignore
}
}
super.transform(tree)
case _ => super.transform(tree)
}
}
private def validateJSConstructorOf(tree: Tree, tpeArg: Tree): Unit = {
val classValue = try {
typer.typedClassOf(tree, tpeArg)
} catch {
case typeError: TypeError =>
reporter.error(typeError.pos, typeError.msg)
EmptyTree
}
if (classValue != EmptyTree) {
val Literal(classConstant) = classValue
val tpe = classConstant.typeValue.dealiasWiden
val typeSym = tpe.typeSymbol
if (typeSym.isTrait || typeSym.isModuleClass) {
reporter.error(tpeArg.pos,
s"non-trait class type required but $tpe found")
}
}
}
/** Performs checks and rewrites specific to classes / objects extending
* js.Any.
*/
private def transformJSImplDef(implDef: ImplDef): Tree = {
val sym = moduleToModuleClass(implDef.symbol)
sym.addAnnotation(JSTypeAnnot)
val isJSLambda =
sym.isAnonymousClass && AllJSFunctionClasses.exists(sym.isSubClass(_))
if (isJSLambda)
transformJSLambdaImplDef(implDef)
else
transformNonLambdaJSImplDef(implDef)
}
/** Performs checks and rewrites specific to JS lambdas, i.e., anonymous
* classes extending one of the JS function types.
*
* JS lambdas are special because they are completely hijacked by the
* back-end, so although at this phase they look like normal anonymous
* classes, they do not behave like ones.
*/
private def transformJSLambdaImplDef(implDef: ImplDef): Tree = {
/* For the purposes of checking inner members, a JS lambda acts as a JS
* native class owner.
*
* TODO This is probably not right, but historically it has always been
* that way. It should be revisited.
*/
enterOwner(OwnerKind.JSNativeClass) {
super.transform(implDef)
}
}
/** Performs checks and rewrites for all JS classes, traits and objects
* except JS lambdas.
*/
private def transformNonLambdaJSImplDef(implDef: ImplDef): Tree = {
val sym = moduleToModuleClass(implDef.symbol)
val isJSNative = sym.hasAnnotation(JSNativeAnnotation)
// Forbid @EnableReflectiveInstantiation on JS types
sym.getAnnotation(EnableReflectiveInstantiationAnnotation).foreach {
annot =>
reporter.error(annot.pos,
"@EnableReflectiveInstantiation cannot be used on types " +
"extending js.Any.")
}
// Forbid package objects that extends js.Any
if (sym.isPackageObjectClass)
reporter.error(implDef.pos, "Package objects may not extend js.Any.")
// Check that we do not have a case modifier
if (implDef.mods.hasFlag(Flag.CASE)) {
reporter.error(implDef.pos, "Classes and objects extending " +
"js.Any may not have a case modifier")
}
// Check the parents
for (parent <- sym.info.parents) {
parent.typeSymbol match {
case AnyRefClass | ObjectClass =>
// AnyRef is valid, except for non-native JS traits
if (!isJSNative && !sym.isTrait) {
reporter.error(implDef.pos,
"Non-native JS classes and objects cannot directly extend " +
"AnyRef. They must extend a JS class (native or not).")
}
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.isTrait &&
parentSym.hasAnnotation(JSNativeAnnotation)) {
reporter.error(implDef.pos,
"Non-native JS types cannot directly extend native JS " +
"traits.")
}
case DynamicClass =>
/* We have to allow scala.Dynamic to be able to define js.Dynamic
* and similar constructs.
* This causes the unsoundness filed as #1385.
*/
case parentSym =>
/* This is a Scala class or trait other than AnyRef and Dynamic,
* which is never valid.
*/
reporter.error(implDef.pos,
s"${sym.nameString} extends ${parentSym.fullName} " +
"which does not extend js.Any.")
}
}
// Checks for non-native JS stuff
if (!isJSNative) {
// It cannot be in a native JS class or trait
if (enclosingOwner is OwnerKind.JSNativeClass) {
reporter.error(implDef.pos,
"Native JS classes and traits cannot contain non-native JS " +
"classes, traits or objects")
}
// Unless it is a trait, it cannot be in a native JS object
if (!sym.isTrait && (enclosingOwner is OwnerKind.JSNativeMod)) {
reporter.error(implDef.pos,
"Native JS objects cannot contain inner non-native JS " +
"classes or objects")
}
// Local JS classes cannot be abstract (implementation restriction)
if (!sym.isTrait && sym.isAbstractClass && sym.isLocalToBlock) {
reporter.error(implDef.pos,
"Implementation restriction: local JS classes cannot be abstract")
}
}
// Check for consistency of JS semantics across overriding
for (overridingPair <- new overridingPairs.Cursor(sym).iterator) {
val low = overridingPair.low
val high = overridingPair.high
def errorPos = {
if (sym == low.owner) low.pos
else if (sym == high.owner) high.pos
else sym.pos
}
def memberDefString(membSym: Symbol): String =
membSym.defStringSeenAs(sym.thisType.memberType(membSym))
// Check for overrides with different JS names - issue #1983
if (jsInterop.jsNameOf(low) != jsInterop.jsNameOf(high)) {
val msg = {
def memberDefStringWithJSName(membSym: Symbol) = {
memberDefString(membSym) +
membSym.locationString + " with JSName '" +
jsInterop.jsNameOf(membSym).displayName + '\''
}
"A member of a JS class is overriding another member with a different JS name.\n\n" +
memberDefStringWithJSName(low) + "\n" +
" is conflicting with\n" +
memberDefStringWithJSName(high) + "\n"
}
reporter.error(errorPos, msg)
}
/* 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.isTrait && !sym.isDeferred && !sym.isConstructor &&
!sym.owner.hasAnnotation(JSNativeAnnotation)
}
if (isJSOptional(low) && !(high.isDeferred || isJSOptional(high))) {
reporter.error(errorPos,
s"Cannot override concrete ${memberDefString(high)} from " +
s"${high.owner.fullName} in a non-native JS trait.")
}
}
}
val kind = {
if (!isJSNative) {
if (sym.isModuleClass) OwnerKind.JSMod
else OwnerKind.JSClass
} else {
if (sym.isModuleClass) OwnerKind.JSNativeMod
else OwnerKind.JSNativeClass
}
}
enterOwner(kind) {
super.transform(implDef)
}
}
private def checkJSNativeDefinition(pos: Position, sym: Symbol): Unit = {
// Check if we may have a JS native here
if (sym.isLocalToBlock) {
reporter.error(pos,
"@js.native is not allowed on local definitions")
} else if (!sym.isClass && (anyEnclosingOwner is (OwnerKind.ScalaClass | OwnerKind.JSType))) {
reporter.error(pos,
"@js.native vals and defs can only appear in static Scala objects")
} else if (sym.isClass && !isJSAny(sym)) {
reporter.error(pos,
"Classes, traits and objects not extending js.Any may not have " +
"an @js.native annotation")
} else if (anyEnclosingOwner is OwnerKind.ScalaClass) {
reporter.error(pos,
"Scala traits and classes may not have native JS members")
} else if (enclosingOwner is OwnerKind.JSNonNative) {
reporter.error(pos,
"non-native JS classes, traits and objects may not have " +
"native JS members")
} else if (!sym.isTrait) {
/* Compute the loading spec now, before `flatten` destroys the name.
* We store it in a global map.
*/
val optLoadSpec = checkAndComputeJSNativeLoadSpecOf(pos, sym)
for (loadSpec <- optLoadSpec)
jsInterop.storeJSNativeLoadSpec(sym, loadSpec)
} else {
assert(sym.isTrait, sym) // just tested in the previous `if`
for (annot <- sym.annotations) {
val annotSym = annot.symbol
if (JSNativeLoadingSpecAnnots.contains(annotSym)) {
reporter.error(annot.pos,
s"Traits may not have an @${annotSym.nameString} annotation.")
}
}
}
}
private def checkAndComputeJSNativeLoadSpecOf(pos: Position,
sym: Symbol): Option[JSNativeLoadSpec] = {
import JSNativeLoadSpec._
def makeGlobalRefNativeLoadSpec(globalRef: String,
path: List[String]): Global = {
val validatedGlobalRef = if (!JSGlobalRef.isValidJSGlobalRefName(globalRef)) {
reporter.error(pos,
"The name of a JS global variable must be a valid JS " +
s"identifier (got '$globalRef')")
"erroneous"
} else {
globalRef
}
Global(validatedGlobalRef, path)
}
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 (JSNativeLoadingSpecAnnots.contains(annotSym)) {
reporter.error(annot.pos,
"Nested JS classes and objects cannot " +
s"have an @${annotSym.nameString} annotation.")
}
}
if (sym.owner.isStaticOwner) {
for (annot <- sym.annotations) {
if (annot.symbol == JSNameAnnotation &&
annot.args.head.tpe.typeSymbol != StringClass) {
reporter.error(annot.pos,
"Implementation restriction: @JSName with a js.Symbol is " +
"not supported on nested native classes and objects")
}
}
val jsName = jsInterop.jsNameOf(sym) match {
case JSName.Literal(jsName) => jsName
case JSName.Computed(_) => "<erroneous>" // compile error above
}
val ownerLoadSpec = jsInterop.jsNativeLoadSpecOfOption(sym.owner)
val loadSpec = ownerLoadSpec match {
case None =>
// The owner is a JSGlobalScope
makeGlobalRefNativeLoadSpec(jsName, Nil)
case Some(Global(globalRef, path)) =>
Global(globalRef, path :+ jsName)
case Some(Import(module, path)) =>
Import(module, path :+ jsName)
case Some(ImportWithGlobalFallback(
Import(module, modulePath), Global(globalRef, globalPath))) =>
ImportWithGlobalFallback(
Import(module, modulePath :+ jsName),
Global(globalRef, globalPath :+ jsName))
}
Some(loadSpec)
} else {
None
}
} else {
def parsePath(pathName: String): List[String] =
pathName.split('.').toList
def parseGlobalPath(pathName: String): Global = {
val globalRef :: path = parsePath(pathName)
makeGlobalRefNativeLoadSpec(globalRef, path)
}
checkAndGetJSNativeLoadingSpecAnnotOf(pos, sym) match {
case Some(annot) if annot.symbol == JSGlobalScopeAnnotation =>
if (!sym.isModuleClass) {
reporter.error(annot.pos,
"@JSGlobalScope can only be used on native JS objects (with @js.native).")
}
None
case Some(annot) if annot.symbol == JSGlobalAnnotation =>
if (shouldCheckLiterals)
checkJSGlobalLiteral(annot)
val pathName = annot.stringArg(0).getOrElse {
val needsExplicitJSName = {
(enclosingOwner is OwnerKind.ScalaMod) &&
!sym.owner.isPackageObjectClass
}
if (needsExplicitJSName) {
reporter.error(annot.pos,
"Native JS members inside non-native objects " +
"must have an explicit name in @JSGlobal")
}
jsInterop.defaultJSNameOf(sym)
}
Some(parseGlobalPath(pathName))
case Some(annot) if annot.symbol == JSImportAnnotation =>
if (shouldCheckLiterals)
checkJSImportLiteral(annot)
val module = annot.stringArg(0).getOrElse {
"" // an error is reported by checkJSImportLiteral in this case
}
val path = annot.stringArg(1).fold[List[String]](Nil)(parsePath)
val importSpec = Import(module, path)
val loadSpec = annot.stringArg(2).fold[JSNativeLoadSpec] {
importSpec
} { globalPathName =>
ImportWithGlobalFallback(importSpec,
parseGlobalPath(globalPathName))
}
Some(loadSpec)
case None =>
/* We already emitted an error. Invent something not to cause
* cascading errors.
*/
Some(JSNativeLoadSpec.Global("erroneous", Nil))
}
}
}
/** Verify a ValOrDefDef that is annotated with `@js.native`. */
private def transformJSNativeValOrDefDef(tree: ValOrDefDef): ValOrDefDef = {
val sym = tree.symbol
if (sym.isLazy || jsInterop.isJSSetter(sym)) {
reporter.error(tree.pos,
"@js.native is not allowed on vars, lazy vals and setter defs")
} else if (jsInterop.isJSBracketAccess(sym)) {
reporter.error(tree.pos,
"@JSBracketAccess is not allowed on @js.native vals and defs")
} else if (jsInterop.isJSBracketCall(sym)) {
reporter.error(tree.pos,
"@JSBracketCall is not allowed on @js.native vals and defs")
}
if (!sym.isAccessor)
checkRHSCallsJSNative(tree, "@js.native members")
if (sym.isMethod) { // i.e., it is not a field
for (overridden <- sym.allOverriddenSymbols.headOption) {
val verb = if (overridden.isDeferred) "implement" else "override"
reporter.error(tree.pos,
s"An @js.native member cannot $verb the inherited member " +
overridden.fullName)
}
}
tree
}
/** Verify a ValOrDefDef inside a js.Any */
private def transformValOrDefDefInJSType(tree: ValOrDefDef): Tree = {
val sym = tree.symbol
assert(!sym.isLocalToBlock, s"$tree at ${tree.pos}")
sym.name match {
case nme.apply if !sym.hasAnnotation(JSNameAnnotation) =>
if (jsInterop.isJSGetter(sym)) {
reporter.error(sym.pos, s"A member named apply represents function " +
"application in JavaScript. A parameterless member should be " +
"exported as a property. You must add @JSName(\"apply\")")
} else if (enclosingOwner is OwnerKind.JSNonNative) {
reporter.error(sym.pos,
"A non-native JS class cannot declare a method " +
"named `apply` without `@JSName`")
}
case nme.equals_ if sym.tpe.matches(Any_equals.tpe) =>
reporter.warning(sym.pos, "Overriding equals in a JS class does " +
"not change how it is compared. To silence this warning, change " +
"the name of the method and optionally add @JSName(\"equals\").")
case nme.hashCode_ if sym.tpe.matches(Any_hashCode.tpe) =>
reporter.warning(sym.pos, "Overriding hashCode in a JS class does " +
"not change its hash code. To silence this warning, change " +
"the name of the method and optionally add @JSName(\"hashCode\").")
case _ =>
}
if (jsInterop.isJSSetter(sym))
checkSetterSignature(sym, tree.pos, exported = false)
if (jsInterop.isJSBracketAccess(sym)) {
if (enclosingOwner is OwnerKind.JSNonNative) {
reporter.error(tree.pos,
"@JSBracketAccess is not allowed in non-native JS classes")
} else {
val paramCount = sym.paramss.map(_.size).sum
if (paramCount != 1 && paramCount != 2) {
reporter.error(tree.pos,
"@JSBracketAccess methods must have one or two parameters")
} else if (paramCount == 2 &&
sym.tpe.finalResultType.typeSymbol != UnitClass) {
reporter.error(tree.pos,
"@JSBracketAccess methods with two parameters must return Unit")
}
for (param <- sym.paramss.flatten) {
if (isScalaRepeatedParamType(param.tpe)) {
reporter.error(param.pos,
"@JSBracketAccess methods may not have repeated parameters")
} else if (param.isParamWithDefault) {
reporter.error(param.pos,
"@JSBracketAccess methods may not have default parameters")
}
}
}
}
if (jsInterop.isJSBracketCall(sym)) {
if (enclosingOwner is OwnerKind.JSNonNative) {
reporter.error(tree.pos,
"@JSBracketCall is not allowed in non-native JS classes")
} else {
// JS bracket calls must have at least one non-repeated parameter
sym.tpe.paramss match {
case (param :: _) :: _ if !isScalaRepeatedParamType(param.tpe) =>
// ok
case _ =>
reporter.error(tree.pos, "@JSBracketCall methods must have at " +
"least one non-repeated parameter")
}
}
}
if (sym.hasAnnotation(NativeAttr)) {
// Native methods are not allowed
reporter.error(tree.pos, "Methods in a js.Any may not be @native")
}
/* In native JS types, there should not be any private member, except
* private[this] constructors.
*/
if ((enclosingOwner is OwnerKind.JSNative) && isPrivateMaybeWithin(sym)) {
// Necessary for `private[this] val/var
def isFieldPrivateThis: Boolean = {
sym.isPrivateThis &&
!sym.isParamAccessor &&
!sym.owner.info.decls.exists(s => s.isGetter && s.accessed == sym)
}
if (sym.isClassConstructor) {
if (!sym.isPrivateThis) {
reporter.error(sym.pos,
"Native JS classes may not have private constructors. " +
"Use `private[this]` to declare an internal constructor.")
}
} else if (sym.isMethod || isFieldPrivateThis) {
reporter.error(tree.pos,
"Native JS classes may not have private members. " +
"Use a public member in a private facade instead.")
}
}
if (enclosingOwner is OwnerKind.JSNonNative) {
// Private methods cannot be overloaded
if (sym.isMethod && isPrivateMaybeWithin(sym)) {
val alts = sym.owner.info.member(sym.name).filter(_.isMethod)
if (alts.isOverloaded) {
reporter.error(tree.pos,
"Private methods in non-native JS classes cannot be " +
"overloaded. Use different names instead.")
}
}
// private[Scope] methods must be final
if (sym.isMethod && (sym.hasAccessBoundary && !sym.isProtected) &&
!sym.isFinal && !sym.isClassConstructor) {
reporter.error(tree.pos,
"Qualified private members in non-native JS classes " +
"must be final")
}
// Traits must be pure interfaces, except for js.undefined members
if (sym.owner.isTrait && sym.isTerm && !sym.isConstructor) {
if (sym.isMethod && isPrivateMaybeWithin(sym)) {
reporter.error(tree.pos,
"A non-native JS trait cannot contain private members")
} else if (sym.isLazy) {