forked from scala/scala
/
SpecializeTypes.scala
2085 lines (1864 loc) · 92.9 KB
/
SpecializeTypes.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 (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala
package tools.nsc
package transform
import scala.annotation.nowarn
import scala.collection.mutable
import scala.tools.nsc.symtab.Flags
import scala.tools.nsc.Reporting.WarningCategory
import scala.util.chaining._
/** Specialize code on types.
*
* Make sure you've read the thesis:
*
* Iulian Dragos: Compiling Scala for Performance (chapter 4)
*
* There are some things worth noting, (possibly) not mentioned there:
* 0) Make sure you understand the meaning of various `SpecializedInfo` descriptors
* defined below.
*
* 1) Specializing traits by introducing bridges in specialized methods
* of the specialized trait may introduce problems during mixin composition.
* Concretely, it may cause cyclic calls and result in a stack overflow.
* See ticket #4351.
* This was solved by introducing an `Abstract` specialized info descriptor.
* Instead of generating a bridge in the trait, an abstract method is generated.
*
* 2) Specialized private members sometimes have to be switched to protected.
* In some cases, even this is not enough. Example:
*
* {{{
* class A[@specialized T](protected val d: T) {
* def foo(that: A[T]) = that.d
* }
* }}}
*
* Specialization will generate a specialized class and a specialized method:
*
* {{{
* class A\$mcI\$sp(protected val d: Int) extends A[Int] {
* def foo(that: A[Int]) = foo\$mcI\$sp(that)
* def foo(that: A[Int]) = that.d
* }
* }}}
*
* Above, `A\$mcI\$sp` cannot access `d`, so the method cannot be typechecked.
*/
abstract class SpecializeTypes extends InfoTransform with TypingTransformers {
import global._
import definitions._
import Flags._
private val inlineFunctionExpansion = settings.Ydelambdafy.value == "inline"
/** the name of the phase: */
val phaseName: String = "specialize"
/** The following flags may be set by this phase: */
override def phaseNewFlags: Long = notPRIVATE
/** This phase changes base classes. */
override def changesBaseClasses = true
override def keepsTypeParams = true
type TypeEnv = Map[Symbol, Type]
def emptyEnv: TypeEnv = Map[Symbol, Type]()
private implicit val typeOrdering: Ordering[Type] = Ordering[String] on ("" + _.typeSymbol.name)
/** TODO - this is a lot of maps.
*/
/** For a given class and concrete type arguments, give its specialized class */
val specializedClass = perRunCaches.newAnyRefMap[Symbol, mutable.AnyRefMap[TypeEnv, Symbol]]()
/** Map a method symbol to a list of its specialized overloads in the same class. */
private val overloads = perRunCaches.newMap[Symbol, List[Overload]]() withDefaultValue Nil
/** Map a symbol to additional information on specialization. */
private val info = perRunCaches.newMap[Symbol, SpecializedInfo]()
/** Map class symbols to the type environments where they were created. */
private val typeEnv = perRunCaches.newMap[Symbol, TypeEnv]() withDefaultValue emptyEnv
// Key: a specialized class or method
// Value: a map from tparams in the original class to tparams in the specialized class.
private val anyrefSpecCache = perRunCaches.newMap[Symbol, mutable.Map[Symbol, Symbol]]()
// holds mappings from members to the type variables in the class
// that they were already specialized for, so that they don't get
// specialized twice (this is for AnyRef specializations)
private val wasSpecializedForTypeVars = perRunCaches.newMap[Symbol, Set[Symbol]]() withDefaultValue Set()
/** Concrete methods that use a specialized type, or override such methods. */
private val concreteSpecMethods = perRunCaches.newWeakSet[Symbol]()
private def specializedOn(sym: Symbol): List[Symbol] = {
val GroupOfSpecializable = currentRun.runDefinitions.GroupOfSpecializable
def expandGroup(tp: Type): List[Symbol] =
tp.baseType(GroupOfSpecializable) match {
case TypeRef(_, GroupOfSpecializable, arg :: Nil) => arg.typeArgs.map(_.typeSymbol)
case _ => tp.typeSymbol :: Nil
}
sym.getAnnotation(SpecializedClass) match {
case Some(AnnotationInfo(_, Nil, _)) => specializableTypes.map(_.typeSymbol)
case Some(AnnotationInfo(_, args, _)) => args.map(_.tpe).flatMap(expandGroup)
case _ => Nil
}
}
@annotation.tailrec private def findSymbol[T](candidates: List[T], f: T => Symbol): Symbol = {
if (candidates.isEmpty) NoSymbol
else f(candidates.head) match {
case NoSymbol => findSymbol(candidates.tail, f)
case sym => sym
}
}
private def hasNewParents(tree: Tree) = {
val parents = tree.symbol.info.parents
val prev = enteringPrevPhase(tree.symbol.info.parents)
(parents != prev) && {
debuglog(s"$tree parents changed from: $prev to: $parents")
true
}
}
// If we replace `isBoundedGeneric` with (tp <:< AnyRefTpe),
// then pos/spec-List.scala fails - why? Does this kind of check fail
// for similar reasons? Does `sym.isAbstractType` make a difference?
private def isSpecializedAnyRefSubtype(tp: Type, sym: Symbol) = {
specializedOn(sym).exists(s => !isPrimitiveValueClass(s)) &&
!isPrimitiveValueClass(tp.typeSymbol) &&
isBoundedGeneric(tp)
//(tp <:< AnyRefTpe)
}
object TypeEnv {
/** Return a new type environment binding specialized type parameters of sym to
* the given args. Expects the lists to have the same length.
*/
def fromSpecialization(sym: Symbol, args: List[Type]): TypeEnv = {
ifDebug(assert(sym.info.typeParams.sizeCompare(args) == 0, "" + sym + " args: " + args))
emptyEnv ++ collectMap2(sym.info.typeParams, args)((k, v) => k.isSpecialized)
}
/** Does typeenv `t1` include `t2`? All type variables in `t1`
* are defined in `t2` and:
* - are bound to the same type, or
* - are an AnyRef specialization and `t2` is bound to a subtype of AnyRef
*/
def includes(t1: TypeEnv, t2: TypeEnv) = t1 forall {
case (sym, tpe) =>
t2 get sym exists { t2tp =>
(tpe == t2tp) || !(isPrimitiveValueType(tpe) || isPrimitiveValueType(t2tp)) // u.t.b. (t2tp <:< AnyRefTpe)
}
}
/** Reduce the given environment to contain mappings only for type variables in tps. */
def restrict(env: TypeEnv, tps: Set[Symbol]): TypeEnv =
env.view.filterKeys(tps).toMap
/** Is the given environment a valid specialization for sym?
* It is valid if each binding is from a @specialized type parameter in sym (or its owner)
* to a type for which `sym` is specialized.
*/
def isValid(env: TypeEnv, sym: Symbol): Boolean = {
env forall { case (tvar, tpe) =>
tvar.isSpecialized && (concreteTypes(tvar) contains tpe) && {
(sym.typeParams contains tvar) ||
(sym.owner != rootMirror.RootClass && (sym.owner.typeParams contains tvar))
}
}
}
}
case class Overload(sym: Symbol, env: TypeEnv) {
override def toString = "specialized overload " + sym + " in " + env
def matchesSym(sym1: Symbol) = sym.info =:= sym1.info
def matchesEnv(env1: TypeEnv) = TypeEnv.includes(env, env1)
}
private def newOverload(method: Symbol, specializedMethod: Symbol, env: TypeEnv) = {
assert(!specializedMethod.isOverloaded, specializedMethod.defString)
val om = Overload(specializedMethod, env)
overloads(method) ::= om
om
}
/** Just to mark uncheckable */
override def newPhase(prev: scala.tools.nsc.Phase): StdPhase = new SpecializationPhase(prev)
class SpecializationPhase(prev: scala.tools.nsc.Phase) extends InfoPhase(prev) {
override def checkable = false
override def run(): Unit = {
super.run()
exitingSpecialize {
FunctionClass.seq.take(MaxFunctionAritySpecialized + 1).foreach(_.info)
TupleClass.seq.take(MaxTupleAritySpecialized).foreach(_.info)
}
// Remove the final modifier and @inline annotation from anything in the
// original class (since it's being overridden in at least one subclass).
//
// We do this here so that the specialized subclasses will correctly copy
// final and @inline.
//
// TODO Try to move this logic back to the info transform.
info.foreach {
case (sym, SpecialOverload(target, _)) =>
sym.resetFlag(FINAL)
target.resetFlag(FINAL)
sym.removeAnnotation(ScalaInlineClass)
target.removeAnnotation(ScalaInlineClass)
case _ =>
}
}
}
protected def newTransformer(unit: CompilationUnit): AstTransformer =
new SpecializationTransformer(unit)
sealed abstract class SpecializedInfo {
def target: Symbol
/** Are type bounds of @specialized type parameters of 'target' now in 'env'? */
def typeBoundsIn(env: TypeEnv) = false
/** A degenerated method has @specialized type parameters that appear only in
* type bounds of other @specialized type parameters (and not in its result type).
*/
def degenerate = false
}
/** Symbol is a special overloaded method of 'original', in the environment env. */
case class SpecialOverload(original: Symbol, env: TypeEnv) extends SpecializedInfo {
def target = original
}
/** Symbol is a method that should be forwarded to 't' */
case class Forward(t: Symbol) extends SpecializedInfo {
def target = t
}
/** Symbol is a specialized abstract method, either specialized or original. The original `t` is abstract. */
case class Abstract(t: Symbol) extends SpecializedInfo {
def target = t
}
/** Symbol is a special overload of the super accessor. Treated like an abstract method with no specialized overload. */
case class SpecialSuperAccessor(t: Symbol) extends SpecializedInfo {
def target = t
}
/** Symbol is a specialized accessor for the `target` field. */
case class SpecializedAccessor(target: Symbol) extends SpecializedInfo { }
/** Symbol is a specialized method whose body should be the target's method body. */
case class Implementation(target: Symbol) extends SpecializedInfo
/** Symbol is a specialized override paired with `target`. */
case class SpecialOverride(target: Symbol) extends SpecializedInfo
/** A specialized inner class that specializes original inner class `target` on a type parameter of the enclosing class, in the typeenv `env`. */
case class SpecializedInnerClass(target: Symbol, env: TypeEnv) extends SpecializedInfo
/** Symbol is a normalized member obtained by specializing 'target'. */
case class NormalizedMember(target: Symbol) extends SpecializedInfo {
/** Type bounds of a @specialized type var are now in the environment. */
override def typeBoundsIn(env: TypeEnv): Boolean = {
target.info.typeParams exists { tvar =>
tvar.isSpecialized && (specializedTypeVars(tvar.info.bounds) exists env.isDefinedAt)
}
}
override lazy val degenerate = {
val stvTypeParams = specializedTypeVars(target.info.typeParams map (_.info))
val stvResult = specializedTypeVars(target.info.resultType)
debuglog("degenerate: " + target + " stv tparams: " + stvTypeParams + " stv info: " + stvResult)
(stvTypeParams diff stvResult).nonEmpty
}
}
/** Has `clazz` any type parameters that need be specialized? */
def hasSpecializedParams(clazz: Symbol) =
clazz.info.typeParams exists (_.isSpecialized)
/** Return specialized type parameters. */
def specializedParams(sym: Symbol): List[Symbol] =
sym.info.typeParams filter (_.isSpecialized)
/** Given an original class symbol and a list of types its type parameters are instantiated at
* returns a list of type parameters that should remain in the TypeRef when instantiating a
* specialized type.
*/
def survivingArgs(sym: Symbol, args: List[Type]): List[Type] =
for ((tvar, tpe) <- sym.info.typeParams.zip(args) if !tvar.isSpecialized || !isPrimitiveValueType(tpe))
yield tpe
/** Is `member` potentially affected by specialization? This is a gross overapproximation,
* but it should be okay for use outside of specialization.
*/
def possiblySpecialized(sym: Symbol) = specializedTypeVars(sym).nonEmpty
/** Refines possiblySpecialized taking into account the instantiation of the specialized type variables at `site` */
def isSpecializedIn(sym: Symbol, site: Type) =
specializedTypeVars(sym) exists { tvar =>
val concretes = concreteTypes(tvar)
(concretes contains AnyRefTpe) || (concretes contains site.memberType(tvar))
}
val specializedType = new TypeMap {
override def apply(tp: Type): Type = tp match {
case TypeRef(pre, sym, args) if args.nonEmpty =>
val pre1 = this(pre)
// when searching for a specialized class, take care to map all
// type parameters that are subtypes of AnyRef to AnyRef
val args1 = map2(args, sym.info.typeParams)((tp, orig) =>
if (isSpecializedAnyRefSubtype(tp, orig)) AnyRefTpe
else tp
)
specializedClass.getOrElse(sym, Map.empty[TypeEnv, Symbol]).get(TypeEnv.fromSpecialization(sym, args1)) match {
case Some(sym1) => typeRef(pre1, sym1, survivingArgs(sym, args))
case None => typeRef(pre1, sym, args)
}
case _ => tp
}
}
def specializedFunctionName(sym: Symbol, args: List[Type]) = exitingSpecialize {
require(isFunctionSymbol(sym), sym)
val env: TypeEnv = TypeEnv.fromSpecialization(sym, args)
specializedClass.getOrElse(sym, Map.empty[TypeEnv, Symbol]).get(env) match {
case Some(x) =>
x.name
case None =>
sym.name
}
}
/** Return the specialized name of 'sym' in the given environment. It
* guarantees the same result regardless of the map order by sorting
* type variables alphabetically.
*
* !!! Is this safe in the face of the following?
* scala> trait T { def foo[A] = 0}; object O extends T { override def foo[B] = 0 }
*/
private def specializedName(sym: Symbol, env: TypeEnv): TermName = {
val tvars = (
if (sym.isClass) env.keySet
else specializedTypeVars(sym).intersect(env.keySet)
)
specializedName(sym.name, tvars, env)
}
private def specializedName(name: Name, tvars: Set[Symbol], env: TypeEnv): TermName = {
val (methparams, others) = tvars.toList sortBy ("" + _.name) partition (_.owner.isMethod)
// debuglog("specName(" + sym + ") env: " + env + " tvars: " + tvars)
specializedName(name, methparams map env, others map env)
}
/** Specialize name for the two list of types. The first one denotes
* specialization on method type parameters, the second on outer environment.
*/
private def specializedName(name: Name, types1: List[Type], types2: List[Type]): TermName = (
if (name == nme.CONSTRUCTOR || (types1.isEmpty && types2.isEmpty))
name.toTermName
else if (nme.isSetterName(name))
specializedName(name.getterName, types1, types2).setterName
else if (nme.isLocalName(name))
specializedName(name.getterName, types1, types2).localName
else {
val (base, cs, ms) = nme.splitSpecializedName(name)
newTermName(base.toString + "$"
+ "m" + ms + types1.map(t => abbrvTag(t.typeSymbol)).mkString("", "", "")
+ "c" + cs + types2.map(t => abbrvTag(t.typeSymbol)).mkString("", "", "$sp"))
}
)
private lazy val specializableTypes = ScalaValueClasses.map(_.tpe).sorted
/** If the symbol is the companion of a value class, the value class.
* Otherwise, AnyRef.
*/
def specializesClass(sym: Symbol): Symbol = {
val c = sym.companionClass
if (isPrimitiveValueClass(c)) c else AnyRefClass
}
/** Return the types `sym` should be specialized at. This may be some of the primitive types
* or AnyRef. AnyRef means that a new type parameter T will be generated later, known to be a
* subtype of AnyRef (T <: AnyRef).
* These are in a meaningful order for stability purposes.
*/
def concreteTypes(sym: Symbol): List[Type] = {
val types = if (!sym.isSpecialized)
Nil // no @specialized Annotation
else
specializedOn(sym).map(s => specializesClass(s).tpe).sorted
if (isBoundedGeneric(sym.tpe) && (types contains AnyRefTpe))
runReporting.warning(sym.pos, s"$sym is always a subtype of $AnyRefTpe.", WarningCategory.Other, sym)
types
}
/** Return a list of all type environments for all specializations
* of @specialized types in `tps`.
*/
private def specializations(tps: List[Symbol]): List[TypeEnv] = {
// the keys in each TypeEnv
val keys: List[Symbol] = tps filter (_.isSpecialized)
// creating each permutation of concrete types
def loop(ctypes: List[List[Type]]): List[List[Type]] = ctypes match {
case Nil => Nil
case set :: Nil => set map (_ :: Nil)
case set :: sets => for (x <- set ; xs <- loop(sets)) yield x :: xs
}
// zip the keys with each permutation to create a TypeEnv.
// If we don't exclude the "all AnyRef" specialization, we will
// incur duplicate members and crash during mixin.
loop(keys map concreteTypes) filterNot (_ forall (_ <:< AnyRefTpe)) map (xss => Map(keys zip xss: _*))
}
/** Does the given 'sym' need to be specialized in the environment 'env'?
* Specialization is needed for
* - members with specialized type parameters found in the given environment
* - constructors of specialized classes
* - normalized members whose type bounds appear in the environment
* But suppressed for:
* - any member with the @unspecialized annotation, or which has an
* enclosing member with the annotation.
*/
private def needsSpecialization(env: TypeEnv, sym: Symbol): Boolean = (
!hasUnspecializableAnnotation(sym) && (
specializedTypeVars(sym).intersect(env.keySet).diff(wasSpecializedForTypeVars(sym)).nonEmpty
|| sym.isClassConstructor && sym.enclClass.typeParams.exists(_.isSpecialized)
|| isNormalizedMember(sym) && info(sym).typeBoundsIn(env)
)
)
private def hasUnspecializableAnnotation(sym: Symbol): Boolean =
sym.ownersIterator.exists(_.hasAnnotation(UnspecializedClass))
def isNormalizedMember(m: Symbol) = m.isSpecialized && info.get(m).exists {
case NormalizedMember(_) => true
case _ => false
}
def specializedTypeVars(tpes: List[Type]): Set[Symbol] = {
val result = mutable.ListBuffer.empty[Symbol]
tpes.foreach(specializedTypeVarsBuffer(_, result))
result.toSet
}
def specializedTypeVars(sym: Symbol): Set[Symbol] = {
val result = mutable.ListBuffer.empty[Symbol]
specializedTypeVarsBuffer(sym, result)
result.toSet
}
/** Return the set of @specialized type variables mentioned by the given type.
* It only counts type variables that appear:
* - naked
* - as arguments to type constructors in @specialized positions
* (arrays are considered as Array[@specialized T])
*/
def specializedTypeVars(tpe: Type): Set[Symbol] = {
val result = new mutable.ListBuffer[Symbol]()
specializedTypeVarsBuffer(tpe, result)
result.toSet
}
def specializedTypeVarsBuffer(sym: Symbol, result: mutable.Buffer[Symbol]): Unit =
if (!neverHasTypeParameters(sym))
enteringTyper(specializedTypeVarsBuffer(sym.info, result))
/** Return the set of @specialized type variables mentioned by the given type.
* It only counts type variables that appear:
* - naked
* - as arguments to type constructors in @specialized positions
* (arrays are considered as Array[@specialized T])
*/
def specializedTypeVarsBuffer(tpe: Type, result: mutable.Buffer[Symbol]): Unit = tpe match {
case TypeRef(pre, sym, args) =>
if (sym.isAliasType)
specializedTypeVarsBuffer(tpe.dealiasWiden, result)
else if (sym.isTypeParameter && sym.isSpecialized || (sym.isTypeSkolem && sym.deSkolemize.isSpecialized))
result += sym
else if (sym == ArrayClass)
args.foreach(tp => specializedTypeVarsBuffer(tp, result))
else if (!args.isEmpty)
enteringTyper {
foreach2(sym.typeParams, args) { (tp, arg) =>
if (tp.isSpecialized)
specializedTypeVarsBuffer(arg, result)
}
}
case PolyType(tparams, resTpe) => specializedTypeVarsBuffer(resTpe, result); tparams.foreach(sym => specializedTypeVarsBuffer(sym.info, result))
// since this method may be run at phase typer (before uncurry, where NMTs are eliminated)
case NullaryMethodType(resTpe) => specializedTypeVarsBuffer(resTpe, result)
case MethodType(argSyms, resTpe) => specializedTypeVarsBuffer(resTpe, result); argSyms.foreach(sym => specializedTypeVarsBuffer(sym.tpe, result))
case ExistentialType(_, res) => specializedTypeVarsBuffer(res, result)
case AnnotatedType(_, tp) => specializedTypeVarsBuffer(tp, result)
case TypeBounds(lo, hi) => specializedTypeVarsBuffer(lo, result); specializedTypeVarsBuffer(hi, result)
case RefinedType(parents, _) => parents.foreach(p => specializedTypeVarsBuffer(p, result))
case _ => ()
}
/** Returns the type parameter in the specialized class `sClass` that corresponds to type parameter
* `tparam` in the original class. It will create it if needed or use the one from the cache.
*/
private def typeParamSubAnyRef(tparam: Symbol, sClass: Symbol): Type = {
val sClassMap = anyrefSpecCache.getOrElseUpdate(sClass, mutable.Map[Symbol, Symbol]())
sClassMap.getOrElseUpdate(tparam,
tparam.cloneSymbol(sClass, tparam.flags, tparam.name append tpnme.SPECIALIZED_SUFFIX)
modifyInfo (info => TypeBounds(info.lowerBound, AnyRefTpe))
).tpe
}
/** Cleans the anyrefSpecCache of all type parameter symbols of a class.
*/
private def cleanAnyRefSpecCache(clazz: Symbol, decls: List[Symbol]): Unit = {
// remove class type parameters and those of normalized members.
clazz :: decls foreach (anyrefSpecCache remove _)
}
/** Type parameters that survive when specializing in the specified environment. */
def survivingParams(params: List[Symbol], env: TypeEnv) =
params filter {
p =>
!p.isSpecialized ||
!env.contains(p) ||
!isPrimitiveValueType(env(p))
}
/** Produces the symbols from type parameters `syms` of the original owner,
* in the given type environment `env`. The new owner is `nowner`.
*
* Non-specialized type parameters are cloned into new ones.
* Type parameters specialized on AnyRef have preexisting symbols.
*
* For instance, a @specialized(AnyRef) T, will become T\$sp <: AnyRef.
*/
def produceTypeParameters(syms: List[Symbol], nowner: Symbol, env: TypeEnv) = {
val cloned = for (s <- syms) yield if (!env.contains(s)) s.cloneSymbol(nowner) else env(s).typeSymbol
// log("producing type params: " + cloned.map(t => (t, t.tpe.upperBound)))
foreach2(syms, cloned) { (orig, cln) =>
cln.removeAnnotation(SpecializedClass)
if (env.contains(orig))
cln modifyInfo (info => TypeBounds(info.lowerBound, AnyRefTpe))
}
cloned.foreach(_.substInfo(syms, cloned))
cloned
}
/** Maps AnyRef bindings from a raw environment (holding AnyRefs) into type parameters from
* the specialized symbol (class (specialization) or member (normalization)), leaves everything else as-is.
*/
private def mapAnyRefsInSpecSym(env: TypeEnv, origsym: Symbol, specsym: Symbol): TypeEnv = env transform {
case (sym, AnyRefTpe) if sym.owner == origsym => typeParamSubAnyRef(sym, specsym)
case (k, v) => v
}
/** Maps AnyRef bindings from a raw environment (holding AnyRefs) into type parameters from
* the original class, leaves everything else as-is.
*/
private def mapAnyRefsInOrigCls(env: TypeEnv, origcls: Symbol): TypeEnv = env transform {
case (sym, AnyRefTpe) if sym.owner == origcls => sym.tpe
case (k, v) => v
}
/** Specialize 'clazz', in the environment `outerEnv`. The outer
* environment contains bindings for specialized types of enclosing
* classes.
*
* A class C is specialized w.r.t to its own specialized type params
* `stps`, by specializing its members, and creating a new class for
* each combination of `stps`.
*/
def specializeClass(clazz: Symbol, outerEnv: TypeEnv): List[Symbol] = {
def specializedClass(env0: TypeEnv, normMembers: List[Symbol]): Symbol = {
/* It gets hard to follow all the clazz and cls, and specializedClass
* was both already used for a map and mucho long. So "sClass" is the
* specialized subclass of "clazz" throughout this file.
*/
// scala/bug#5545: Eliminate classes with the same name loaded from the bytecode already present - all we need to do is
// to force .info on them, as their lazy type will be evaluated and the symbols will be eliminated. Unfortunately
// evaluating the info after creating the specialized class will mess the specialized class signature, so we'd
// better evaluate it before creating the new class symbol
val clazzName = specializedName(clazz, env0).toTypeName
val bytecodeClazz = clazz.owner.info.decl(clazzName)
// debuglog("Specializing " + clazz + ", but found " + bytecodeClazz + " already there")
bytecodeClazz.info
val sClass = {
val sc = clazz.owner.newClass(clazzName, clazz.pos, (clazz.flags | SPECIALIZED) & ~CASE)
sc.setAnnotations(clazz.annotations)
sc
}
def cloneInSpecializedClass(member: Symbol, flagFn: Long => Long, newName: Name = null) =
member.cloneSymbol(sClass, flagFn(member.flags | SPECIALIZED), newName)
clazz.sourceFile match {
case null =>
case file =>
sClass.associatedFile = file
currentRun.symSource(sClass) = file // needed later on by mixin
}
val env = mapAnyRefsInSpecSym(env0, clazz, sClass)
typeEnv(sClass) = env
this.specializedClass.getOrElseUpdate(clazz, new mutable.AnyRefMap()).update(env0, sClass)
val decls1 = newScope // declarations of the newly specialized class 'sClass'
var oldClassTParams: List[Symbol] = Nil // original unspecialized type parameters
var newClassTParams: List[Symbol] = Nil // unspecialized type parameters of 'specializedClass' (cloned)
// has to be a val in order to be computed early. It is later called
// within 'enteringPhase(next)', which would lead to an infinite cycle otherwise
val specializedInfoType: Type = {
oldClassTParams = survivingParams(clazz.info.typeParams, env)
newClassTParams = produceTypeParameters(oldClassTParams, sClass, env) map subst(env)
// log("new tparams " + newClassTParams.zip(newClassTParams map {s => (s.tpe, s.tpe.upperBound)}) + ", in env: " + env)
def applyContext(tpe: Type) =
subst(env, tpe).instantiateTypeParams(oldClassTParams, newClassTParams.map(_.tpeHK))
/* Return a list of specialized parents to be re-mixed in a specialized subclass.
* Assuming env = [T -> Int] and
* class Integral[@specialized T] extends Numeric[T]
* and Numeric[U] is specialized on U, this produces List(Numeric$mcI).
*
* so that class Integral$mci extends Integral[Int] with Numeric$mcI.
*/
def specializedParents(parents: List[Type]): List[Type] = {
var res: List[Type] = Nil
// log(specializedClass + ": seeking specialized parents of class with parents: " + parents.map(_.typeSymbol))
for (p <- parents) {
val stp = exitingSpecialize(specializedType(p))
if (stp != p)
if (p.typeSymbol.isTrait) res ::= stp
else if (currentRun.compiles(clazz))
// TODO change to error
runReporting.warning(clazz.pos,
s"${p.typeSymbol} must be a trait. Specialized version of $clazz will inherit generic $p",
WarningCategory.Other,
clazz)
}
res
}
var parents = List(applyContext(enteringTyper(clazz.tpe_*)))
// log("!!! Parents: " + parents + ", sym: " + parents.map(_.typeSymbol))
if (parents.head.typeSymbol.isTrait)
parents = parents.head.parents.head :: parents
val extraSpecializedMixins = specializedParents(clazz.info.parents map applyContext)
if (extraSpecializedMixins.nonEmpty)
debuglog("extra specialized mixins for %s: %s".format(clazz.name.decode, extraSpecializedMixins.mkString(", ")))
// If the class being specialized has a self-type, the self type may
// require specialization. First exclude classes whose self types have
// the same type constructor as the class itself, since they will
// already be covered. Then apply the current context to the self-type
// as with the parents and assign it to typeOfThis.
if (clazz.typeOfThis.typeConstructor ne clazz.typeConstructor) {
sClass.typeOfThis = applyContext(clazz.typeOfThis)
debuglog("Rewriting self-type for specialized class:\n" +
" " + clazz.defStringSeenAs(clazz.typeOfThis) + "\n" +
" => " + sClass.defStringSeenAs(sClass.typeOfThis)
)
}
GenPolyType(newClassTParams, ClassInfoType(parents ::: extraSpecializedMixins, decls1, sClass))
}
exitingSpecialize(sClass setInfo specializedInfoType)
val fullEnv = outerEnv ++ env
/* Enter 'sym' in the scope of the current specialized class. Its type is
* mapped through the active environment, binding type variables to concrete
* types. The existing typeEnv for `sym` is composed with the current active
* environment
*/
def enterMember(sym: Symbol): Symbol = {
typeEnv(sym) = fullEnv ++ typeEnv(sym) // append the full environment
sym.modifyInfo(_.substThis(clazz, sClass).instantiateTypeParams(oldClassTParams, newClassTParams.map(_.tpeHK)))
// we remove any default parameters. At this point, they have been all
// resolved by the type checker. Later on, erasure re-typechecks everything and
// chokes if it finds default parameters for specialized members, even though
// they are never needed.
foreachParamss(sym)(_ resetFlag DEFAULTPARAM)
decls1 enter subst(fullEnv)(sym)
}
/* Create and enter in scope an overridden symbol m1 for `m` that forwards
* to `om`. `om` is a fresh, special overload of m1 that is an implementation
* of `m`. For example, for a
*
* class Foo[@specialized A] {
* def m(x: A) = <body> // m
* }
* , for class Foo$I extends Foo[Int], this method enters two new symbols in
* the scope of Foo$I:
*
* def m(x: Int) = m$I(x) // m1
* def m$I(x: Int) = <body>/adapted to env {A -> Int} // om
*/
def forwardToOverload(m: Symbol): Symbol = {
val specMember = enterMember(cloneInSpecializedClass(m, f => (f | OVERRIDE) & ~(DEFERRED | CASEACCESSOR)))
val om = specializedOverload(sClass, m, env).setFlag(OVERRIDE)
val original = info.get(m) match {
case Some(NormalizedMember(tg)) => tg
case _ => m
}
info(specMember) = Forward(om)
info(om) = if (original.isDeferred) Forward(original) else Implementation(original)
typeEnv(om) = env ++ typeEnv(m) // add the environment for any method tparams
newOverload(specMember, om, typeEnv(om))
enterMember(om)
}
for (m <- normMembers if needsSpecialization(fullEnv, m) && satisfiable(fullEnv)) {
if (!m.isDeferred)
addConcreteSpecMethod(m)
// specialized members have to be overridable.
if (m.isPrivate)
m.resetFlag(PRIVATE).setFlag(PROTECTED)
if (m.isConstructor) {
val specCtor = enterMember(cloneInSpecializedClass(m, x => x))
info(specCtor) = Forward(m)
}
else if (isNormalizedMember(m)) { // methods added by normalization
val NormalizedMember(original) = info(m): @unchecked
if (nonConflicting(env ++ typeEnv(m))) {
if (info(m).degenerate) {
debuglog("degenerate normalized member " + m.defString)
val specMember = enterMember(cloneInSpecializedClass(m, _ & ~DEFERRED))
info(specMember) = Implementation(original)
typeEnv(specMember) = env ++ typeEnv(m)
} else {
val om = forwardToOverload(m)
debuglog("normalizedMember " + m + " om: " + om + " " + pp(typeEnv(om)))
}
}
else
debuglog("conflicting env for " + m + " env: " + env)
}
else if (m.isDeferred && m.isSpecialized) { // abstract methods
val specMember = enterMember(cloneInSpecializedClass(m, _ | DEFERRED))
// debuglog("deferred " + specMember.fullName + " remains abstract")
info(specMember) = Abstract(specMember)
// was: new Forward(specMember) {
// override def target = m.owner.info.member(specializedName(m, env))
// }
} else if (m.hasFlag(SUPERACCESSOR)) { // basically same as abstract case
// we don't emit a specialized overload for the super accessor because we can't jump back and forth
// between specialized and non-specialized methods during an invokespecial for the super call,
// so, we must jump immediately into the non-specialized world to find our super
val specMember = enterMember(cloneInSpecializedClass(m, f => f))
// rebindSuper in mixins knows how to rejigger this
// (basically it skips this specialized class in the base class seq, and then also never rebinds to a specialized method)
specMember.asInstanceOf[TermSymbol].referenced = m.alias
info(specMember) = SpecialSuperAccessor(specMember)
} else if (m.isMethod && !m.hasFlag(DEFERRED) && (!m.hasFlag(ACCESSOR) || m.hasFlag(LAZY))) { // other concrete methods
forwardToOverload(m)
} else if (m.isValue && !m.isMethod) { // concrete value definition
def mkAccessor(field: Symbol, name: Name) = {
val newFlags = (SPECIALIZED | m.getterIn(clazz).flags) & ~(LOCAL | CASEACCESSOR | PARAMACCESSOR)
// we rely on the super class to initialize param accessors
val sym = sClass.newMethod(name.toTermName, field.pos, newFlags)
info(sym) = SpecializedAccessor(field)
sym
}
def overrideIn(clazz: Symbol, sym: Symbol) = {
val newFlags = (sym.flags | OVERRIDE | SPECIALIZED) & ~(DEFERRED | CASEACCESSOR | PARAMACCESSOR)
val sym1 = sym.cloneSymbol(clazz, newFlags)
sym1.modifyInfo(_.asSeenFrom(clazz.tpe, sym1.owner))
}
val specVal = specializedOverload(sClass, m, env)
addConcreteSpecMethod(m)
specVal.asInstanceOf[TermSymbol].setAlias(m)
enterMember(specVal)
// create accessors
if (m.isLazy) {
// no getters needed (we'll specialize the compute method and accessor separately), can stay private
// m.setFlag(PRIVATE) -- TODO: figure out how to leave the non-specialized lazy var private
// (the implementation needs it to be visible while duplicating and retypechecking,
// but it really could be private in bytecode)
specVal.setFlag(PRIVATE)
}
else if (nme.isLocalName(m.name)) {
val specGetter = mkAccessor(specVal, specVal.getterName) setInfo MethodType(Nil, specVal.info)
val origGetter = overrideIn(sClass, m.getterIn(clazz))
info(origGetter) = Forward(specGetter)
enterMember(specGetter)
enterMember(origGetter)
debuglog("specialize accessor in %s: %s -> %s".format(sClass.name.decode, origGetter.name.decode, specGetter.name.decode))
clazz.caseFieldAccessors.find(_.name.startsWith(m.name)) foreach { cfa =>
val cfaGetter = overrideIn(sClass, cfa)
info(cfaGetter) = SpecializedAccessor(specVal)
enterMember(cfaGetter)
debuglog("override case field accessor %s -> %s".format(m.name.decode, cfaGetter.name.decode))
}
if (specVal.isVariable && m.setterIn(clazz) != NoSymbol) {
val specSetter = mkAccessor(specVal, specGetter.setterName)
.resetFlag(STABLE)
specSetter.setInfo(MethodType(specSetter.newSyntheticValueParams(List(specVal.info)),
UnitTpe))
val origSetter = overrideIn(sClass, m.setterIn(clazz))
info(origSetter) = Forward(specSetter)
enterMember(specSetter)
enterMember(origSetter)
}
}
else { // if there are no accessors, specialized methods will need to access this field in specialized subclasses
m.resetFlag(PRIVATE)
specVal.resetFlag(PRIVATE)
debuglog("no accessors for %s/%s, specialized methods must access field in subclass".format(
m.name.decode, specVal.name.decode))
}
}
else if (m.isClass) {
val specClass: Symbol = cloneInSpecializedClass(m, x => x)
typeEnv(specClass) = fullEnv
specClass setName specializedName(specClass, fullEnv).toTypeName
enterMember(specClass)
debuglog("entered specialized class " + specClass.fullName)
info(specClass) = SpecializedInnerClass(m, fullEnv)
}
}
sClass
}
val decls1 = clazz.info.decls.toList flatMap { m: Symbol =>
if (m.isAnonymousClass) List(m) else {
normalizeMember(m.owner, m, outerEnv) flatMap { normalizedMember =>
val ms = specializeMember(m.owner, normalizedMember, outerEnv, clazz.info.typeParams)
// interface traits have concrete members now
if (ms.nonEmpty && clazz.isTrait && clazz.isInterface)
clazz.resetFlag(INTERFACE)
if (normalizedMember.isMethod) {
val newTpe = subst(outerEnv, normalizedMember.info)
// only do it when necessary, otherwise the method type might be at a later phase already
if (newTpe != normalizedMember.info) {
normalizedMember updateInfo newTpe
}
}
normalizedMember :: ms
}
}
}
val subclasses = specializations(clazz.info.typeParams) filter satisfiable
subclasses foreach {
env =>
val spc = specializedClass(env, decls1)
val existing = clazz.owner.info.decl(spc.name)
// a symbol for the specialized class already exists if there's a classfile for it.
// keeping both crashes the compiler on test/files/pos/spec-Function1.scala
if (existing != NoSymbol)
clazz.owner.info.decls.unlink(existing)
exitingSpecialize(clazz.owner.info.decls enter spc) //!!! assumes fully specialized classes
}
if (subclasses.nonEmpty) clazz.resetFlag(FINAL)
cleanAnyRefSpecCache(clazz, decls1)
decls1
}
/** Expand member `sym` to a set of normalized members. Normalized members
* are monomorphic or polymorphic only in non-specialized types.
*
* Given method m[@specialized T, U](x: T, y: U) it returns
* m[T, U](x: T, y: U),
* m\$I[ U](x: Int, y: U),
* m\$D[ U](x: Double, y: U)
* // etc.
*/
private def normalizeMember(owner: Symbol, sym: Symbol, outerEnv: TypeEnv): List[Symbol] = {
sym :: (
if (!sym.isMethod || enteringTyper(sym.typeParams.isEmpty)) Nil
else if (sym.hasDefault) {
/* Specializing default getters is useless, also see scala/bug#7329 . */
sym.resetFlag(SPECIALIZED)
Nil
} else {
// debuglog("normalizeMember: " + sym.fullNameAsName('.').decode)
var specializingOn = specializedParams(sym)
val unusedStvars = specializingOn filterNot specializedTypeVars(sym.info)
// I think the last condition should be !sym.isArtifact, but that made the
// compiler start warning about Tuple1.scala and Tuple2.scala claiming
// their type parameters are used in non-specializable positions. Why is
// unusedStvars.nonEmpty for these classes???
if (unusedStvars.nonEmpty && currentRun.compiles(sym) && !sym.isSynthetic) {
runReporting.warning(sym.pos,
"%s %s unused or used in non-specializable positions.".format(
unusedStvars.mkString("", ", ", ""),
if (unusedStvars.lengthIs == 1) "is" else "are"),
WarningCategory.Other,
sym)
unusedStvars foreach (_ removeAnnotation SpecializedClass)
specializingOn = specializingOn filterNot (unusedStvars contains _)
}
for (env0 <- specializations(specializingOn) if needsSpecialization(env0, sym)) yield {
// !!! Can't this logic be structured so that the new symbol's name is
// known when the symbol is cloned? It is much cleaner not to be mutating
// names after the fact. And it adds about a billion lines of
// "Renaming value _1 in class Tuple2 to _1$mcZ$sp" to obscure the small
// number of other (important) actual symbol renamings.
val tps = survivingParams(sym.info.typeParams, env0)
val specMember = sym.cloneSymbol(owner, (sym.flags | SPECIALIZED) & ~DEFERRED) // <-- this needs newName = ...
val env = mapAnyRefsInSpecSym(env0, sym, specMember)
val (keys, vals) = env.toList.unzip
specMember setName specializedName(sym, env) // <-- but the name is calculated based on the cloned symbol
// debuglog("%s normalizes to %s%s".format(sym, specMember,
// if (tps.isEmpty) "" else " with params " + tps.mkString(", ")))
typeEnv(specMember) = outerEnv ++ env
val tps1 = produceTypeParameters(tps, specMember, env)
tps1 foreach (_ modifyInfo (_.instantiateTypeParams(keys, vals)))
// the cloneInfo is necessary so that method parameter symbols are cloned at the new owner
val methodType = sym.info.resultType.instantiateTypeParams(keys ++ tps, vals ++ tps1.map(_.tpeHK)).cloneInfo(specMember)
specMember setInfo GenPolyType(tps1, methodType)
debuglog("%s expands to %s in %s".format(sym, specMember.name.decode, pp(env)))
info(specMember) = NormalizedMember(sym)
newOverload(sym, specMember, env)
specMember
}
}
)
}
// concise printing of type env
private def pp(env: TypeEnv): String = {
env.toList.sortBy(_._1.name).map {
case (k, v) =>
val vsym = v.typeSymbol
if (k == vsym) "" + k.name
else "" + k.name + ":" + vsym.name
}.mkString("env(", ", ", ")")
}
/** Specialize member `m` w.r.t. to the outer environment and the type
* parameters of the innermost enclosing class.
*
* Turns 'private' into 'protected' for members that need specialization.
*
* Return a list of symbols that are specializations of 'sym', owned by 'owner'.
*/
private def specializeMember(owner: Symbol, sym: Symbol, outerEnv: TypeEnv, tps: List[Symbol]): List[Symbol] = {
def specializeOn(tparams: List[Symbol]): List[Symbol] = specializations(tparams) map { spec0 =>
val spec = mapAnyRefsInOrigCls(spec0, owner)
if (sym.isPrivate) {
sym.resetFlag(PRIVATE).setFlag(PROTECTED)
debuglog("Set %s to private[%s]".format(sym, sym.enclosingPackage))
}
val specMember = subst(outerEnv)(specializedOverload(owner, sym, spec))
typeEnv(specMember) = typeEnv(sym) ++ outerEnv ++ spec
wasSpecializedForTypeVars(specMember) ++= spec collect { case (s, tp) if s.tpe == tp => s }
val wasSpec = wasSpecializedForTypeVars(specMember)
if (wasSpec.nonEmpty)
debuglog("specialized overload for %s in %s".format(specMember, pp(typeEnv(specMember))))
newOverload(sym, specMember, spec)
info(specMember) = SpecialOverload(sym, typeEnv(specMember))