/
Symbols.scala
3424 lines (2919 loc) · 134 KB
/
Symbols.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
/* NSC -- new Scala compiler
* Copyright 2005-2011 LAMP/EPFL
* @author Martin Odersky
*/
package scala.reflect
package internal
import scala.collection.{ mutable, immutable }
import scala.collection.mutable.ListBuffer
import util.Statistics
import Flags._
import base.Attachments
trait Symbols extends api.Symbols { self: SymbolTable =>
import definitions._
import SymbolsStats._
protected var ids = 0
val emptySymbolArray = new Array[Symbol](0)
protected def nextId() = { ids += 1; ids }
/** Used for deciding in the IDE whether we can interrupt the compiler */
//protected var activeLocks = 0
/** Used for debugging only */
//protected var lockedSyms = collection.immutable.Set[Symbol]()
/** Used to keep track of the recursion depth on locked symbols */
private var recursionTable = immutable.Map.empty[Symbol, Int]
private var nextexid = 0
protected def freshExistentialName(suffix: String) = {
nextexid += 1
newTypeName("_" + nextexid + suffix)
}
// Set the fields which point companions at one another. Returns the module.
def connectModuleToClass(m: ModuleSymbol, moduleClass: ClassSymbol): ModuleSymbol = {
moduleClass.sourceModule = m
m setModuleClass moduleClass
m
}
/** Create a new free term. Its owner is NoSymbol.
*/
def newFreeTermSymbol(name: TermName, info: Type, value: => Any, flags: Long = 0L, origin: String): FreeTermSymbol =
new FreeTermSymbol(name, value, origin) initFlags flags setInfo info
/** Create a new free type. Its owner is NoSymbol.
*/
def newFreeTypeSymbol(name: TypeName, info: Type, value: => Any, flags: Long = 0L, origin: String): FreeTypeSymbol =
new FreeTypeSymbol(name, value, origin) initFlags flags setInfo info
/** The original owner of a class. Used by the backend to generate
* EnclosingMethod attributes.
*/
val originalOwner = perRunCaches.newMap[Symbol, Symbol]()
abstract class SymbolContextApiImpl extends SymbolContextApi {
this: Symbol =>
def kind: String = kindString
def isExistential: Boolean = this.isExistentiallyBound
def newNestedSymbol(name: Name, pos: Position, newFlags: Long, isClass: Boolean): Symbol = name match {
case n: TermName => newTermSymbol(n, pos, newFlags)
case n: TypeName => if (isClass) newClassSymbol(n, pos, newFlags) else newNonClassSymbol(n, pos, newFlags)
}
def thisPrefix: Type = thisType
def selfType: Type = typeOfThis
def typeSignature: Type = info
def typeSignatureIn(site: Type): Type = site memberInfo this
def asType: Type = tpe
def asTypeIn(site: Type): Type = site.memberType(this)
def asTypeConstructor: Type = typeConstructor
def setFlags(flags: FlagSet): this.type = setInternalFlags(flags)
def setInternalFlags(flag: Long): this.type = { setFlag(flag); this }
def setTypeSignature(tpe: Type): this.type = { setInfo(tpe); this }
def getAnnotations: List[AnnotationInfo] = { initialize; annotations }
def setAnnotations(annots: AnnotationInfo*): this.type = { setAnnotations(annots.toList); this }
def resolveOverloaded(
pre: Type,
targs: Seq[Type],
posVargTypes: Seq[Type],
nameVargTypes: Seq[(TermName, Type)],
expected: Type
): Symbol = {
// Begin Correlation Helpers
def isCompatible(tp: Type, pt: Type): Boolean = {
def isCompatibleByName(tp: Type, pt: Type): Boolean = pt match {
case TypeRef(_, ByNameParamClass, List(res)) if !definitions.isByNameParamType(tp) =>
isCompatible(tp, res)
case _ =>
false
}
(tp weak_<:< pt) || isCompatibleByName(tp, pt)
}
def signatureAsSpecific(method1: MethodSymbol, method2: MethodSymbol): Boolean = {
(substituteTypeParams(method1), substituteTypeParams(method2)) match {
case (NullaryMethodType(r1), NullaryMethodType(r2)) =>
r1 weak_<:< r2
case (NullaryMethodType(_), MethodType(_, _)) =>
true
case (MethodType(_, _), NullaryMethodType(_)) =>
false
case (MethodType(p1, _), MethodType(p2, _)) =>
val len = p1.length max p2.length
val sub = extend(p1 map (_.typeSignature), len)
val sup = extend(p2 map (_.typeSignature), len)
(sub corresponds sup)(isCompatible)
}
}
def scopeMoreSpecific(method1: MethodSymbol, method2: MethodSymbol): Boolean = {
val o1 = method1.owner.asClassSymbol
val o2 = method2.owner.asClassSymbol
val c1 = if (o1.hasFlag(Flag.MODULE)) o1.companionSymbol else o1
val c2 = if (o2.hasFlag(Flag.MODULE)) o2.companionSymbol else o2
c1.typeSignature <:< c2.typeSignature
}
def moreSpecific(method1: MethodSymbol, method2: MethodSymbol): Boolean = {
def points(m1: MethodSymbol, m2: MethodSymbol) = {
val p1 = if (signatureAsSpecific(m1, m2)) 1 else 0
val p2 = if (scopeMoreSpecific(m1, m2)) 1 else 0
p1 + p2
}
points(method1, method2) > points(method2, method1)
}
def combineInto (
variadic: Boolean
)(
positional: Seq[Type],
named: Seq[(TermName, Type)]
)(
target: Seq[TermName],
defaults: Map[Int, Type]
): Option[Seq[Type]] = {
val offset = positional.length
val unfilled = target.zipWithIndex drop offset
val canAcceptAllNameVargs = named forall { case (argName, _) =>
unfilled exists (_._1 == argName)
}
val paramNamesUnique = {
named.length == named.map(_._1).distinct.length
}
if (canAcceptAllNameVargs && paramNamesUnique) {
val rest = unfilled map { case (paramName, paramIndex) =>
val passedIn = named.collect {
case (argName, argType) if argName == paramName => argType
}.headOption
if (passedIn isDefined) passedIn
else defaults.get(paramIndex).map(_.asInstanceOf[Type])
}
val rest1 = {
if (variadic && !rest.isEmpty && !rest.last.isDefined) rest.init
else rest
}
if (rest1 forall (_.isDefined)) {
val joined = positional ++ rest1.map(_.get)
val repeatedCollapsed = {
if (variadic) {
val (normal, repeated) = joined.splitAt(target.length - 1)
if (repeated.forall(_ =:= repeated.head)) Some(normal ++ repeated.headOption)
else None
}
else Some(joined)
}
if (repeatedCollapsed.exists(_.length == target.length))
repeatedCollapsed
else if (variadic && repeatedCollapsed.exists(_.length == target.length - 1))
repeatedCollapsed
else None
} else None
} else None
}
// Begin Reflection Helpers
// Replaces a repeated parameter type at the end of the parameter list
// with a number of non-repeated parameter types in order to pad the
// list to be nargs in length
def extend(types: Seq[Type], nargs: Int): Seq[Type] = {
if (isVarArgTypes(types)) {
val repeatedType = types.last.normalize.typeArgs.head
types.init ++ Seq.fill(nargs - (types.length - 1))(repeatedType)
} else types
}
// Replaces by-name parameters with their result type and
// TypeRefs with the thing they reference
def unwrap(paramType: Type): Type = paramType match {
case TypeRef(_, IntClass, _) => typeOf[Int]
case TypeRef(_, LongClass, _) => typeOf[Long]
case TypeRef(_, ShortClass, _) => typeOf[Short]
case TypeRef(_, ByteClass, _) => typeOf[Byte]
case TypeRef(_, CharClass, _) => typeOf[Char]
case TypeRef(_, FloatClass, _) => typeOf[Float]
case TypeRef(_, DoubleClass, _) => typeOf[Double]
case TypeRef(_, BooleanClass, _) => typeOf[Boolean]
case TypeRef(_, UnitClass, _) => typeOf[Unit]
case TypeRef(_, NullClass, _) => typeOf[Null]
case TypeRef(_, AnyClass, _) => typeOf[Any]
case TypeRef(_, NothingClass, _) => typeOf[Nothing]
case TypeRef(_, AnyRefClass, _) => typeOf[AnyRef]
case TypeRef(_, ByNameParamClass, List(resultType)) => unwrap(resultType)
case t: Type => t
}
// Gives the names of the parameters to a method
def paramNames(signature: Type): Seq[TermName] = signature match {
case PolyType(_, resultType) => paramNames(resultType)
case MethodType(params, _) => params.map(_.name.asInstanceOf[TermName])
case NullaryMethodType(_) => Seq.empty
}
def valParams(signature: Type): Seq[TermSymbol] = signature match {
case PolyType(_, resultType) => valParams(resultType)
case MethodType(params, _) => params.map(_.asTermSymbol)
case NullaryMethodType(_) => Seq.empty
}
// Returns a map from parameter index to default argument type
def defaultTypes(method: MethodSymbol): Map[Int, Type] = {
val typeSig = substituteTypeParams(method)
val owner = method.owner
valParams(typeSig).zipWithIndex.filter(_._1.hasFlag(Flag.DEFAULTPARAM)).map { case(_, index) =>
val name = nme.defaultGetterName(method.name.decodedName, index + 1)
val default = owner.asType member name
index -> default.typeSignature.asInstanceOf[NullaryMethodType].resultType
}.toMap
}
// True if any of method's parameters have default values. False otherwise.
def usesDefault(method: MethodSymbol): Boolean = valParams(method.typeSignature) drop(posVargTypes).length exists { param =>
(param hasFlag Flag.DEFAULTPARAM) && nameVargTypes.forall { case (argName, _) =>
param.name != argName
}
}
// The number of type parameters that the method takes
def numTypeParams(x: MethodSymbol): Int = {
x.typeSignature.typeParams.length
}
def substituteTypeParams(m: MethodSymbol): Type = {
(pre memberType m) match {
case m: MethodType => m
case n: NullaryMethodType => n
case PolyType(tparams, rest) => rest.substituteTypes(tparams, targs.toList)
}
}
// Begin Selection Helpers
def select(
alternatives: Seq[MethodSymbol],
filters: Seq[Seq[MethodSymbol] => Seq[MethodSymbol]]
): Seq[MethodSymbol] =
filters.foldLeft(alternatives)((a, f) => {
if (a.size > 1) f(a) else a
})
// Drop arguments that take the wrong number of type
// arguments.
val posTargLength: Seq[MethodSymbol] => Seq[MethodSymbol] = _.filter { alt =>
numTypeParams(alt) == targs.length
}
// Drop methods that are not applicable to the arguments
val applicable: Seq[MethodSymbol] => Seq[MethodSymbol] = _.filter { alt =>
// Note: combine returns None if a is not applicable and
// None.exists(_ => true) == false
val paramTypes =
valParams(substituteTypeParams(alt)).map(p => unwrap(p.typeSignature))
val variadic = isVarArgTypes(paramTypes)
val maybeArgTypes =
combineInto(variadic)(posVargTypes, nameVargTypes)(paramNames(alt.typeSignature), defaultTypes(alt))
maybeArgTypes exists { argTypes =>
if (isVarArgTypes(argTypes) && !isVarArgTypes(paramTypes)) false
else {
val a = argTypes
val p = extend(paramTypes, argTypes.length)
(a corresponds p)(_ weak_<:< _)
}
}
}
// Always prefer methods that don't need to use default
// arguments over those that do.
// e.g. when resolving foo(1), prefer def foo(x: Int) over
// def foo(x: Int, y: Int = 4)
val noDefaults: Seq[MethodSymbol] => Seq[MethodSymbol] =
_ filterNot usesDefault
// Try to select the most specific method. If that's not possible,
// return all of the candidates (this will likely cause an error
// higher up in the call stack)
val mostSpecific: Seq[MethodSymbol] => Seq[MethodSymbol] = { alts =>
val sorted = alts.sortWith(moreSpecific)
val mostSpecific = sorted.head
val agreeTest: MethodSymbol => Boolean =
moreSpecific(mostSpecific, _)
val disagreeTest: MethodSymbol => Boolean =
moreSpecific(_, mostSpecific)
if (!sorted.tail.forall(agreeTest)) {
mostSpecific +: sorted.tail.filterNot(agreeTest)
} else if (sorted.tail.exists(disagreeTest)) {
mostSpecific +: sorted.tail.filter(disagreeTest)
} else {
Seq(mostSpecific)
}
}
def finalResult(t: Type): Type = t match {
case PolyType(_, rest) => finalResult(rest)
case MethodType(_, result) => finalResult(result)
case NullaryMethodType(result) => finalResult(result)
case t: Type => t
}
// If a result type is given, drop alternatives that don't meet it
val resultType: Seq[MethodSymbol] => Seq[MethodSymbol] =
if (expected == NoType) identity
else _.filter { alt =>
finalResult(substituteTypeParams(alt)) <:< expected
}
def defaultFilteringOps =
Seq(posTargLength, resultType, applicable, noDefaults, mostSpecific)
// Begin Method Proper
val alts = alternatives.map(_.asMethodSymbol)
val selection = select(alts, defaultFilteringOps)
val knownApplicable = applicable(selection)
if (knownApplicable.size == 1) knownApplicable.head
else NoSymbol
}
}
/** The class for all symbols */
abstract class Symbol protected[Symbols] (initOwner: Symbol, initPos: Position, initName: Name)
extends SymbolContextApiImpl
with HasFlags
with Annotatable[Symbol]
with Attachable {
type AccessBoundaryType = Symbol
type AnnotationType = AnnotationInfo
// TODO - don't allow names to be renamed in this unstructured a fashion.
// Rename as little as possible. Enforce invariants on all renames.
type TypeOfClonedSymbol >: Null <: Symbol { type NameType = Symbol.this.NameType }
// Abstract here so TypeSymbol and TermSymbol can have a private[this] field
// with the proper specific type.
def rawname: NameType
def name: NameType
def name_=(n: Name): Unit
def asNameType(n: Name): NameType
private[this] var _rawowner = initOwner // Syncnote: need not be protected, as only assignment happens in owner_=, which is not exposed to api
private[this] var _rawflags: Long = _
def rawowner = _rawowner
def rawflags = _rawflags
rawatt = initPos
val id = nextId() // identity displayed when -uniqid
//assert(id != 3390, initName)
private[this] var _validTo: Period = NoPeriod
if (traceSymbolActivity)
traceSymbols.recordNewSymbol(this)
def validTo = _validTo
def validTo_=(x: Period) { _validTo = x}
def setName(name: Name): this.type = { this.name = asNameType(name) ; this }
// Update the surrounding scopes
protected[this] def changeNameInOwners(name: Name) {
if (owner.isClass) {
var ifs = owner.infos
while (ifs != null) {
ifs.info.decls.rehash(this, name)
ifs = ifs.prev
}
}
}
def rawFlagString(mask: Long): String = calculateFlagString(rawflags & mask)
def rawFlagString: String = rawFlagString(flagMask)
def debugFlagString: String = flagString(AllFlags)
/** String representation of symbol's variance */
def varianceString: String =
if (variance == 1) "+"
else if (variance == -1) "-"
else ""
override def flagMask =
if (settings.debug.value && !isAbstractType) AllFlags
else if (owner.isRefinementClass) ExplicitFlags & ~OVERRIDE
else ExplicitFlags
// make the error message more googlable
def flagsExplanationString =
if (isGADTSkolem) " (this is a GADT skolem)"
else ""
def shortSymbolClass = getClass.getName.split('.').last.stripPrefix("Symbols$")
def symbolCreationString: String = (
"%s%25s | %-40s | %s".format(
if (settings.uniqid.value) "%06d | ".format(id) else "",
shortSymbolClass,
name.decode + " in " + owner,
rawFlagString
)
)
// ------ creators -------------------------------------------------------------------
final def newValue(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): TermSymbol =
newTermSymbol(name, pos, newFlags)
final def newVariable(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): TermSymbol =
newTermSymbol(name, pos, MUTABLE | newFlags)
final def newValueParameter(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): TermSymbol =
newTermSymbol(name, pos, PARAM | newFlags)
/** Create local dummy for template (owner of local blocks) */
final def newLocalDummy(pos: Position): TermSymbol =
newTermSymbol(nme.localDummyName(this), pos) setInfo NoType
final def newMethod(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): MethodSymbol =
createMethodSymbol(name, pos, METHOD | newFlags)
final def newMethodSymbol(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): MethodSymbol =
createMethodSymbol(name, pos, METHOD | newFlags)
final def newLabel(name: TermName, pos: Position = NoPosition): MethodSymbol =
newMethod(name, pos, LABEL)
/** Propagates ConstrFlags (JAVA, specifically) from owner to constructor. */
final def newConstructor(pos: Position, newFlags: Long = 0L): MethodSymbol =
newMethod(nme.CONSTRUCTOR, pos, getFlag(ConstrFlags) | newFlags)
/** Static constructor with info set. */
def newStaticConstructor(pos: Position): MethodSymbol =
newConstructor(pos, STATIC) setInfo UnitClass.tpe
/** Instance constructor with info set. */
def newClassConstructor(pos: Position): MethodSymbol =
newConstructor(pos) setInfo MethodType(Nil, this.tpe)
def newLinkedModule(clazz: Symbol, newFlags: Long = 0L): ModuleSymbol = {
val m = newModuleSymbol(clazz.name.toTermName, clazz.pos, MODULE | newFlags)
connectModuleToClass(m, clazz.asInstanceOf[ClassSymbol])
}
final def newModule(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleSymbol = {
val m = newModuleSymbol(name, pos, newFlags | MODULE)
val clazz = newModuleClass(name.toTypeName, pos, m getFlag ModuleToClassFlags)
connectModuleToClass(m, clazz)
}
final def newPackage(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleSymbol = {
assert(name == nme.ROOT || isPackageClass, this)
newModule(name, pos, PackageFlags | newFlags)
}
final def newThisSym(name: TermName = nme.this_, pos: Position = NoPosition): TermSymbol =
newTermSymbol(name, pos, SYNTHETIC)
final def newImport(pos: Position): TermSymbol =
newTermSymbol(nme.IMPORT, pos)
final def newModuleSymbol(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleSymbol =
newTermSymbol(name, pos, newFlags).asInstanceOf[ModuleSymbol]
final def newModuleAndClassSymbol(name: Name, pos: Position, flags: FlagSet): (ModuleSymbol, ClassSymbol) = {
val m = newModuleSymbol(name, pos, flags | MODULE)
val c = newModuleClass(name.toTypeName, pos, m getFlag ModuleToClassFlags)
connectModuleToClass(m, c)
(m, c)
}
final def newPackageSymbol(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleSymbol =
newTermSymbol(name, pos, newFlags).asInstanceOf[ModuleSymbol]
final def newModuleClassSymbol(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleClassSymbol =
newClassSymbol(name, pos, newFlags).asInstanceOf[ModuleClassSymbol]
final def newTypeSkolemSymbol(name: TypeName, origin: AnyRef, pos: Position = NoPosition, newFlags: Long = 0L): TypeSkolem =
createTypeSkolemSymbol(name, origin, pos, newFlags)
/** @param pre type relative to which alternatives are seen.
* for instance:
* class C[T] {
* def m(x: T): T
* def m'(): T
* }
* val v: C[Int]
*
* Then v.m has symbol TermSymbol(flags = {OVERLOADED},
* tpe = OverloadedType(C[Int], List(m, m')))
* You recover the type of m doing a
*
* m.tpe.asSeenFrom(pre, C) (generally, owner of m, which is C here).
*
* or:
*
* pre.memberType(m)
*/
final def newOverloaded(pre: Type, alternatives: List[Symbol]): TermSymbol = (
newTermSymbol(alternatives.head.name.toTermName, alternatives.head.pos, OVERLOADED)
setInfo OverloadedType(pre, alternatives)
)
final def newErrorValue(name: TermName): TermSymbol =
newTermSymbol(name, pos, SYNTHETIC | IS_ERROR) setInfo ErrorType
/** Symbol of a type definition type T = ...
*/
final def newAliasType(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): AliasTypeSymbol =
createAliasTypeSymbol(name, pos, newFlags)
/** Symbol of an abstract type type T >: ... <: ...
*/
final def newAbstractType(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): AbstractTypeSymbol =
createAbstractTypeSymbol(name, pos, DEFERRED | newFlags)
/** Symbol of a type parameter
*/
final def newTypeParameter(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): TypeSymbol =
newAbstractType(name, pos, PARAM | newFlags)
// is defined in SymbolCreations
// final def newTypeSymbol(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): TypeSymbol =
// (if ((newFlags & DEFERRED) != 0) new AbstractTypeSymbol(this, pos, name)
// else new AbstractTypeSymbol(this, pos, name)) setFlag newFlags
/** Symbol of an existential type T forSome { ... }
*/
final def newExistential(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): TypeSymbol =
newAbstractType(name, pos, EXISTENTIAL | newFlags)
/** Synthetic value parameters when parameter symbols are not available
*/
final def newSyntheticValueParamss(argtypess: List[List[Type]]): List[List[TermSymbol]] = {
var cnt = 0
def freshName() = { cnt += 1; nme.syntheticParamName(cnt) }
mmap(argtypess)(tp => newValueParameter(freshName(), owner.pos.focus, SYNTHETIC) setInfo tp)
}
def newSyntheticTypeParam(): TypeSymbol = newSyntheticTypeParam("T0", 0L)
def newSyntheticTypeParam(name: String, newFlags: Long): TypeSymbol = newTypeParameter(newTypeName(name), NoPosition, newFlags) setInfo TypeBounds.empty
def newSyntheticTypeParams(num: Int): List[TypeSymbol] = (0 until num).toList map (n => newSyntheticTypeParam("T" + n, 0L))
/** Create a new existential type skolem with this symbol its owner,
* based on the given symbol and origin.
*/
def newExistentialSkolem(basis: Symbol, origin: AnyRef): TypeSkolem = {
val skolem = newTypeSkolemSymbol(basis.name.toTypeName, origin, basis.pos, (basis.flags | EXISTENTIAL) & ~PARAM)
skolem setInfo (basis.info cloneInfo skolem)
}
// flags set up to maintain TypeSkolem's invariant: origin.isInstanceOf[Symbol] == !hasFlag(EXISTENTIAL)
// CASEACCESSOR | SYNTHETIC used to single this symbol out in deskolemizeGADT
def newGADTSkolem(name: TypeName, origin: Symbol, info: Type): TypeSkolem =
newTypeSkolemSymbol(name, origin, origin.pos, origin.flags & ~(EXISTENTIAL | PARAM) | CASEACCESSOR | SYNTHETIC) setInfo info
final def freshExistential(suffix: String): TypeSymbol =
newExistential(freshExistentialName(suffix), pos)
/** Synthetic value parameters when parameter symbols are not available.
* Calling this method multiple times will re-use the same parameter names.
*/
final def newSyntheticValueParams(argtypes: List[Type]): List[TermSymbol] =
newSyntheticValueParamss(List(argtypes)).head
/** Synthetic value parameter when parameter symbol is not available.
* Calling this method multiple times will re-use the same parameter name.
*/
final def newSyntheticValueParam(argtype: Type): Symbol =
newSyntheticValueParams(List(argtype)).head
/** Type skolems are type parameters ''seen from the inside''
* Assuming a polymorphic method m[T], its type is a PolyType which has a TypeParameter
* with name `T` in its typeParams list. While type checking the parameters, result type and
* body of the method, there's a local copy of `T` which is a TypeSkolem.
*/
final def newTypeSkolem: TypeSkolem =
owner.newTypeSkolemSymbol(name.toTypeName, this, pos, flags)
final def newClass(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): ClassSymbol =
newClassSymbol(name, pos, newFlags)
/** A new class with its info set to a ClassInfoType with given scope and parents. */
def newClassWithInfo(name: TypeName, parents: List[Type], scope: Scope, pos: Position = NoPosition, newFlags: Long = 0L): ClassSymbol = {
val clazz = newClass(name, pos, newFlags)
clazz setInfo ClassInfoType(parents, scope, clazz)
}
final def newErrorClass(name: TypeName): ClassSymbol =
newClassWithInfo(name, Nil, new ErrorScope(this), pos, SYNTHETIC | IS_ERROR)
final def newModuleClass(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): ModuleClassSymbol =
newModuleClassSymbol(name, pos, newFlags | MODULE)
final def newAnonymousFunctionClass(pos: Position = NoPosition, newFlags: Long = 0L): ClassSymbol =
newClassSymbol(tpnme.ANON_FUN_NAME, pos, FINAL | SYNTHETIC | newFlags)
final def newAnonymousFunctionValue(pos: Position, newFlags: Long = 0L): TermSymbol =
newTermSymbol(nme.ANON_FUN_NAME, pos, SYNTHETIC | newFlags) setInfo NoType
def newImplClass(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): ClassSymbol = {
newClassSymbol(name, pos, newFlags | IMPLCLASS)
}
/** Refinement types P { val x: String; type T <: Number }
* also have symbols, they are refinementClasses
*/
final def newRefinementClass(pos: Position): RefinementClassSymbol =
createRefinementClassSymbol(pos, 0L)
/** Create a new getter for current symbol (which must be a field)
*/
final def newGetter: MethodSymbol = (
owner.newMethod(nme.getterName(name.toTermName), NoPosition, getterFlags(flags))
setPrivateWithin privateWithin
setInfo MethodType(Nil, tpe)
)
final def newErrorSymbol(name: Name): Symbol = name match {
case x: TypeName => newErrorClass(x)
case x: TermName => newErrorValue(x)
}
@deprecated("Use the other signature", "2.10.0")
def newClass(pos: Position, name: TypeName): Symbol = newClass(name, pos)
@deprecated("Use the other signature", "2.10.0")
def newModuleClass(pos: Position, name: TypeName): Symbol = newModuleClass(name, pos)
@deprecated("Use the other signature", "2.10.0")
def newLabel(pos: Position, name: TermName): MethodSymbol = newLabel(name, pos)
@deprecated("Use the other signature", "2.10.0")
def newValue(pos: Position, name: TermName): TermSymbol = newTermSymbol(name, pos)
@deprecated("Use the other signature", "2.10.0")
def newAliasType(pos: Position, name: TypeName): Symbol = newAliasType(name, pos)
@deprecated("Use the other signature", "2.10.0")
def newAbstractType(pos: Position, name: TypeName): Symbol = newAbstractType(name, pos)
@deprecated("Use the other signature", "2.10.0")
def newExistential(pos: Position, name: TypeName): Symbol = newExistential(name, pos)
@deprecated("Use the other signature", "2.10.0")
def newMethod(pos: Position, name: TermName): MethodSymbol = newMethod(name, pos)
// ----- locking and unlocking ------------------------------------------------------
// True if the symbol is unlocked.
// True if the symbol is locked but still below the allowed recursion depth.
// False otherwise
private[scala] def lockOK: Boolean = {
((_rawflags & LOCKED) == 0L) ||
((settings.Yrecursion.value != 0) &&
(recursionTable get this match {
case Some(n) => (n <= settings.Yrecursion.value)
case None => true }))
}
// Lock a symbol, using the handler if the recursion depth becomes too great.
private[scala] def lock(handler: => Unit): Boolean = {
if ((_rawflags & LOCKED) != 0L) {
if (settings.Yrecursion.value != 0) {
recursionTable get this match {
case Some(n) =>
if (n > settings.Yrecursion.value) {
handler
false
} else {
recursionTable += (this -> (n + 1))
true
}
case None =>
recursionTable += (this -> 1)
true
}
} else { handler; false }
} else {
_rawflags |= LOCKED
true
// activeLocks += 1
// lockedSyms += this
}
}
// Unlock a symbol
private[scala] def unlock() = {
if ((_rawflags & LOCKED) != 0L) {
// activeLocks -= 1
// lockedSyms -= this
_rawflags &= ~LOCKED
if (settings.Yrecursion.value != 0)
recursionTable -= this
}
}
// ----- tests ----------------------------------------------------------------------
def isAliasType = false
def isAbstractType = false
def isSkolem = false
/** A Type, but not a Class. */
def isNonClassType = false
/** The bottom classes are Nothing and Null, found in Definitions. */
def isBottomClass = false
def isSpecialized = this hasFlag SPECIALIZED
/** These are all tests for varieties of ClassSymbol, which has these subclasses:
* - ModuleClassSymbol
* - RefinementClassSymbol
* - PackageClassSymbol (extends ModuleClassSymbol)
*/
def isAbstractClass = false
def isAnonOrRefinementClass = false
def isAnonymousClass = false
def isCaseClass = false
def isConcreteClass = false
def isImplClass = false // the implementation class of a trait
def isJavaInterface = false
def isNumericValueClass = false
def isPrimitiveValueClass = false
def isRefinementClass = false
override def isTrait = false
/** Qualities of Types, always false for TermSymbols.
*/
def isContravariant = false
def isCovariant = false
def isExistentialQuantified = false
def isExistentialSkolem = false
def isExistentiallyBound = false
def isGADTSkolem = false
def isTypeParameter = false
def isTypeParameterOrSkolem = false
def isTypeSkolem = false
def isTypeMacro = false
/** Qualities of Terms, always false for TypeSymbols.
*/
def isAccessor = false
def isBridge = false
def isCapturedVariable = false
def isClassConstructor = false
def isConstructor = false
def isEarlyInitialized = false
def isGetter = false
def isLocalDummy = false
def isMixinConstructor = false
def isOverloaded = false
def isSetter = false
def isSetterParameter = false
def isValue = false
def isValueParameter = false
def isVariable = false
override def hasDefault = false
def isTermMacro = false
/** Qualities of MethodSymbols, always false for TypeSymbols
* and other TermSymbols.
*/
def isCaseAccessorMethod = false
def isLiftedMethod = false
def isSourceMethod = false
def isVarargsMethod = false
override def isLabel = false
/** Package/package object tests */
def isPackageClass = false
def isPackageObject = false
def isPackageObjectClass = false
def isPackageObjectOrClass = isPackageObject || isPackageObjectClass
def isModuleOrModuleClass = isModule || isModuleClass
/** Overridden in custom objects in Definitions */
def isRoot = false
def isRootPackage = false
def isRootSymbol = false // RootPackage and RootClass. TODO: also NoSymbol.
def isEmptyPackage = false
def isEmptyPackageClass = false
/** Is this symbol an effective root for fullname string?
*/
def isEffectiveRoot = false
final def isLazyAccessor = isLazy && lazyAccessor != NoSymbol
final def isOverridableMember = !(isClass || isEffectivelyFinal) && (this ne NoSymbol) && owner.isClass
/** Does this symbol denote a wrapper created by the repl? */
final def isInterpreterWrapper = (
(this hasFlag MODULE)
&& owner.isPackageClass
&& nme.isReplWrapperName(name)
)
@inline final def getFlag(mask: Long): Long = flags & mask
/** Does symbol have ANY flag in `mask` set? */
@inline final def hasFlag(mask: Long): Boolean = (flags & mask) != 0
/** Does symbol have ALL the flags in `mask` set? */
@inline final def hasAllFlags(mask: Long): Boolean = (flags & mask) == mask
def setFlag(mask: Long): this.type = { _rawflags |= mask ; this }
def resetFlag(mask: Long): this.type = { _rawflags &= ~mask ; this }
def resetFlags() { rawflags &= TopLevelCreationFlags }
/** Default implementation calls the generic string function, which
* will print overloaded flags as <flag1/flag2/flag3>. Subclasses
* of Symbol refine.
*/
override def resolveOverloadedFlag(flag: Long): String = Flags.flagToString(flag)
/** Set the symbol's flags to the given value, asserting
* that the previous value was 0.
*/
def initFlags(mask: Long): this.type = {
assert(rawflags == 0L, symbolCreationString)
_rawflags = mask
this
}
final def flags: Long = {
if (Statistics.hotEnabled) Statistics.incCounter(flagsCount)
val fs = _rawflags & phase.flagMask
(fs | ((fs & LateFlags) >>> LateShift)) & ~(fs >>> AntiShift)
}
def flags_=(fs: Long) = _rawflags = fs
def rawflags_=(x: Long) { _rawflags = x }
final def hasGetter = isTerm && nme.isLocalName(name)
final def isInitializedToDefault = !isType && hasAllFlags(DEFAULTINIT | ACCESSOR)
final def isStaticModule = isModule && isStatic && !isMethod
final def isThisSym = isTerm && owner.thisSym == this
final def isError = hasFlag(IS_ERROR)
final def isErroneous = isError || isInitialized && tpe.isErroneous
def isHigherOrderTypeParameter = owner.isTypeParameterOrSkolem
// class C extends D( { class E { ... } ... } ). Here, E is a class local to a constructor
def isClassLocalToConstructor = false
final def isDerivedValueClass =
isClass && !hasFlag(PACKAGE | TRAIT) &&
info.firstParent.typeSymbol == AnyValClass && !isPrimitiveValueClass
final def isMethodWithExtension =
isMethod && owner.isDerivedValueClass && !isParamAccessor && !isConstructor && !hasFlag(SUPERACCESSOR)
final def isAnonymousFunction = isSynthetic && (name containsName tpnme.ANON_FUN_NAME)
final def isDefinedInPackage = effectiveOwner.isPackageClass
final def needsFlatClasses = phase.flatClasses && rawowner != NoSymbol && !rawowner.isPackageClass
/** change name by appending $$<fully-qualified-name-of-class `base`>
* Do the same for any accessed symbols or setters/getters.
* Implementation in TermSymbol.
*/
def expandName(base: Symbol) { }
// In java.lang, Predef, or scala package/package object
def isInDefaultNamespace = UnqualifiedOwners(effectiveOwner)
/** The owner, skipping package objects.
*/
def effectiveOwner = owner.skipPackageObject
/** If this is a package object or its implementing class, its owner: otherwise this.
*/
def skipPackageObject: Symbol = this
/** If this is a constructor, its owner: otherwise this.
*/
final def skipConstructor: Symbol = if (isConstructor) owner else this
/** Conditions where we omit the prefix when printing a symbol, to avoid
* unpleasantries like Predef.String, $iw.$iw.Foo and <empty>.Bippy.
*/
final def isOmittablePrefix = /*!settings.debug.value &&*/ (
UnqualifiedOwners(skipPackageObject)
|| isEmptyPrefix
)
def isEmptyPrefix = (
isEffectiveRoot // has no prefix for real, <empty> or <root>
|| isAnonOrRefinementClass // has uninteresting <anon> or <refinement> prefix
|| nme.isReplWrapperName(name) // has ugly $iw. prefix (doesn't call isInterpreterWrapper due to nesting)
)
def isFBounded = info match {
case TypeBounds(_, _) => info.baseTypeSeq exists (_ contains this)
case _ => false
}
/** Is symbol a monomorphic type?
* assumption: if a type starts out as monomorphic, it will not acquire
* type parameters in later phases.
*/
final def isMonomorphicType =
isType && {
val info = originalInfo
info.isComplete && !info.isHigherKinded
}
def isStrictFP = hasAnnotation(ScalaStrictFPAttr) || (enclClass hasAnnotation ScalaStrictFPAttr)
def isSerializable = (
info.baseClasses.exists(p => p == SerializableClass || p == JavaSerializableClass)
|| hasAnnotation(SerializableAttr) // last part can be removed, @serializable annotation is deprecated
)
def hasBridgeAnnotation = hasAnnotation(BridgeClass)
def hasStaticAnnotation = hasAnnotation(StaticClass)
def isDeprecated = hasAnnotation(DeprecatedAttr)
def deprecationMessage = getAnnotation(DeprecatedAttr) flatMap (_ stringArg 0)
def deprecationVersion = getAnnotation(DeprecatedAttr) flatMap (_ stringArg 1)
def deprecatedParamName = getAnnotation(DeprecatedNameAttr) flatMap (_ symbolArg 0)
// !!! when annotation arguments are not literal strings, but any sort of
// assembly of strings, there is a fair chance they will turn up here not as
// Literal(const) but some arbitrary AST. However nothing in the compiler
// prevents someone from writing a @migration annotation with a calculated
// string. So this needs attention. For now the fact that migration is
// private[scala] ought to provide enough protection.
def hasMigrationAnnotation = hasAnnotation(MigrationAnnotationClass)
def migrationMessage = getAnnotation(MigrationAnnotationClass) flatMap { _.stringArg(0) }
def migrationVersion = getAnnotation(MigrationAnnotationClass) flatMap { _.stringArg(1) }
def elisionLevel = getAnnotation(ElidableMethodClass) flatMap { _.intArg(0) }
def implicitNotFoundMsg = getAnnotation(ImplicitNotFoundClass) flatMap { _.stringArg(0) }
/** Is this symbol an accessor method for outer? */
final def isOuterAccessor = {
hasFlag(STABLE | HIDDEN) &&
originalName == nme.OUTER
}
/** Is this symbol an accessor method for outer? */
final def isOuterField = {
hasFlag(HIDDEN) &&
originalName == nme.OUTER_LOCAL
}
/** Does this symbol denote a stable value? */
def isStable = false
/** Does this symbol denote the primary constructor of its enclosing class? */
final def isPrimaryConstructor =
isConstructor && owner.primaryConstructor == this
/** Does this symbol denote an auxiliary constructor of its enclosing class? */
final def isAuxiliaryConstructor =
isConstructor && !isPrimaryConstructor
/** Is this symbol a synthetic apply or unapply method in a companion object of a case class? */
final def isCaseApplyOrUnapply =
isMethod && isCase && isSynthetic
/** Is this symbol a trait which needs an implementation class? */
final def needsImplClass = (
isTrait
&& (!isInterface || hasFlag(lateINTERFACE))
&& !isImplClass
)
/** Is this a symbol which exists only in the implementation class, not in its trait? */
final def isImplOnly = isPrivate || (
(owner.isTrait || owner.isImplClass) && (
hasAllFlags(LIFTED | MODULE | METHOD)
|| isConstructor
|| hasFlag(notPRIVATE | LIFTED) && !hasFlag(ACCESSOR | SUPERACCESSOR | MODULE)
)
)
final def isModuleVar = hasFlag(MODULEVAR)
/** Is this symbol static (i.e. with no outer instance)?
* Q: When exactly is a sym marked as STATIC?