/
Symbols.scala
3331 lines (2845 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-2013 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 scala.annotation.tailrec
import scala.reflect.io.AbstractFile
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 = scala.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, value: => Any, flags: Long = 0L, origin: String): FreeTermSymbol =
new FreeTermSymbol(name, value, origin) initFlags flags
/** Create a new free type. Its owner is NoSymbol.
*/
def newFreeTypeSymbol(name: TypeName, flags: Long = 0L, origin: String): FreeTypeSymbol =
new FreeTypeSymbol(name, origin) initFlags flags
/** Determines whether the given information request should trigger the given symbol's completer.
* See comments to `Symbol.needsInitialize` for details.
*/
protected def shouldTriggerCompleter(symbol: Symbol, completer: Type, isFlagRelated: Boolean, mask: Long) =
completer match {
case null => false
case _: FlagAgnosticCompleter => !isFlagRelated
case _ => abort(s"unsupported completer: $completer of class ${if (completer != null) completer.getClass else null} for symbol ${symbol.fullName}")
}
/** 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 isExistential: Boolean = this.isExistentiallyBound
def isParamWithDefault: Boolean = this.hasDefault
def isByNameParam: Boolean = this.isValueParameter && (this hasFlag BYNAMEPARAM)
def isImplementationArtifact: Boolean = (this hasFlag BRIDGE) || (this hasFlag VBRIDGE) || (this hasFlag ARTIFACT)
def isJava: Boolean = isJavaDefined
def isVal: Boolean = isTerm && !isModule && !isMethod && !isMutable
def isVar: Boolean = isTerm && !isModule && !isMethod && !isLazy && isMutable
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 knownDirectSubclasses = children
def baseClasses = info.baseClasses
def module = sourceModule
def thisPrefix: Type = thisType
def selfType: Type = typeOfThis
def typeSignature: Type = { fullyInitializeSymbol(this); info }
def typeSignatureIn(site: Type): Type = { fullyInitializeSymbol(this); site memberInfo this }
def toType: Type = tpe
def toTypeIn(site: Type): Type = site.memberType(this)
def toTypeConstructor: Type = typeConstructor
def setTypeSignature(tpe: Type): this.type = { setInfo(tpe); this }
def setAnnotations(annots: AnnotationInfo*): this.type = { setAnnotations(annots.toList); this }
def getter: Symbol = getter(owner)
def setter: Symbol = setter(owner)
}
/** 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 = {
if (shouldLogAtThisPhase) {
val msg = s"Renaming $fullLocationString to $n"
if (isSpecialized) debuglog(msg) else log(msg)
}
}
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, newFlags0: Long = 0L): ModuleSymbol = {
val newFlags = newFlags0 | MODULE
val m = newModuleSymbol(name, pos, newFlags)
val clazz = newModuleClass(name.toTypeName, pos, newFlags & 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, flags0: FlagSet): (ModuleSymbol, ClassSymbol) = {
val flags = flags0 | MODULE
val m = newModuleSymbol(name, pos, flags)
val c = newModuleClass(name.toTypeName, pos, flags & 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)
private def freshNamer: () => TermName = {
var cnt = 0
() => { cnt += 1; nme.syntheticParamName(cnt) }
}
/** Synthetic value parameters when parameter symbols are not available
*/
final def newSyntheticValueParamss(argtypess: List[List[Type]]): List[List[TermSymbol]] =
argtypess map (xs => newSyntheticValueParams(xs, freshNamer))
/** 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] =
newSyntheticValueParams(argtypes, freshNamer)
final def newSyntheticValueParams(argtypes: List[Type], freshName: () => TermName): List[TermSymbol] =
argtypes map (tp => newSyntheticValueParam(tp, freshName()))
/** 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, name: TermName = nme.syntheticParamName(1)): TermSymbol =
newValueParameter(name, owner.pos.focus, SYNTHETIC) setInfo argtype
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)
}
// don't test directly -- use isGADTSkolem
// used to single out a gadt skolem symbol in deskolemizeGADT
// gadtskolems are created in adaptConstrPattern and removed at the end of typedCase
final protected[Symbols] def GADT_SKOLEM_FLAGS = CASEACCESSOR | SYNTHETIC
// flags set up to maintain TypeSkolem's invariant: origin.isInstanceOf[Symbol] == !hasFlag(EXISTENTIAL)
// GADT_SKOLEM_FLAGS (== CASEACCESSOR | SYNTHETIC) used to single this symbol out in deskolemizeGADT
// TODO: it would be better to allocate a new bit in the flag long for GADTSkolem rather than OR'ing together CASEACCESSOR | SYNTHETIC
def newGADTSkolem(name: TypeName, origin: Symbol, info: Type): TypeSkolem =
newTypeSkolemSymbol(name, origin, origin.pos, origin.flags & ~(EXISTENTIAL | PARAM) | GADT_SKOLEM_FLAGS) setInfo info
final def freshExistential(suffix: String): TypeSymbol =
newExistential(freshExistentialName(suffix), pos)
/** 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)
}
/** Creates a placeholder symbol for when a name is encountered during
* unpickling for which there is no corresponding classfile. This defers
* failure to the point when that name is used for something, which is
* often to the point of never.
*/
def newStubSymbol(name: Name, missingMessage: String): Symbol = name match {
case n: TypeName => new StubClassSymbol(this, n, missingMessage)
case _ => new StubTermSymbol(this, name.toTermName, missingMessage)
}
@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
/** 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
def isInvariant = !isCovariant && !isContravariant
/** 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)
)
final def getFlag(mask: Long): Long = {
if (!isCompilerUniverse && needsInitialize(isFlagRelated = true, mask = mask)) initialize
flags & mask
}
/** Does symbol have ANY flag in `mask` set? */
final def hasFlag(mask: Long): Boolean = {
if (!isCompilerUniverse && needsInitialize(isFlagRelated = true, mask = mask)) initialize
(flags & mask) != 0
}
/** Does symbol have ALL the flags in `mask` set? */
final def hasAllFlags(mask: Long): Boolean = {
if (!isCompilerUniverse && needsInitialize(isFlagRelated = true, mask = mask)) initialize
(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) && !isTermMacro
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 isDeprecated = hasAnnotation(DeprecatedAttr)
def deprecationMessage = getAnnotation(DeprecatedAttr) flatMap (_ stringArg 0)
def deprecationVersion = getAnnotation(DeprecatedAttr) flatMap (_ stringArg 1)
def deprecatedParamName = getAnnotation(DeprecatedNameAttr) flatMap (_ symbolArg 0)
def hasDeprecatedInheritanceAnnotation
= hasAnnotation(DeprecatedInheritanceAttr)
def deprecatedInheritanceMessage
= getAnnotation(DeprecatedInheritanceAttr) flatMap (_ stringArg 0)
def deprecatedInheritanceVersion
= getAnnotation(DeprecatedInheritanceAttr) flatMap (_ stringArg 1)
def hasDeprecatedOverridingAnnotation
= hasAnnotation(DeprecatedOverridingAttr)
def deprecatedOverridingMessage
= getAnnotation(DeprecatedOverridingAttr) flatMap (_ stringArg 0)
def deprecatedOverridingVersion
= getAnnotation(DeprecatedOverridingAttr) flatMap (_ stringArg 1)
// !!! 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) }
def isCompileTimeOnly = hasAnnotation(CompileTimeOnlyAttr)
def compileTimeOnlyMessage = getAnnotation(CompileTimeOnlyAttr) flatMap (_ stringArg 0)
/** Is this symbol an accessor method for outer? */
final def isOuterAccessor = {
hasFlag(STABLE | ARTIFACT) &&
originalName == nme.OUTER
}
/** Is this symbol an accessor method for outer? */
final def isOuterField = {
hasFlag(ARTIFACT) &&
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?
* A: If it's a member of a toplevel object, or of an object contained in a toplevel object, or any number of levels deep.
* http://groups.google.com/group/scala-internals/browse_thread/thread/d385bcd60b08faf6
*/
def isStatic = (this hasFlag STATIC) || owner.isStaticOwner
/** Is this symbol a static constructor? */
final def isStaticConstructor: Boolean =
isStaticMember && isClassConstructor
/** Is this symbol a static member of its class? (i.e. needs to be implemented as a Java static?) */
final def isStaticMember: Boolean =
hasFlag(STATIC) || owner.isImplClass
/** Does this symbol denote a class that defines static symbols? */
final def isStaticOwner: Boolean =
isPackageClass || isModuleClass && isStatic
def isTopLevelModule = hasFlag(MODULE) && owner.isPackageClass
/** Is this symbol effectively final? I.e, it cannot be overridden */
final def isEffectivelyFinal: Boolean = (
(this hasFlag FINAL | PACKAGE)
|| isModuleOrModuleClass && (owner.isPackageClass || !settings.overrideObjects.value)
|| isTerm && (
isPrivate
|| isLocal
|| owner.isClass && owner.isEffectivelyFinal
)
)
/** Is this symbol locally defined? I.e. not accessed from outside `this` instance */
final def isLocal: Boolean = owner.isTerm
/** Is this symbol a constant? */
final def isConstant: Boolean = isStable && isConstantType(tpe.resultType)
/** Is this class nested in another class or module (not a package)? */
def isNestedClass = false
/** Is this class locally defined?
* A class is local, if
* - it is anonymous, or
* - its owner is a value
* - it is defined within a local class
*/
def isLocalClass = false
def isStableClass = false
/* code for fixing nested objects
override final def isModuleClass: Boolean =
super.isModuleClass && !isExpandedModuleClass
*/
/** Is this class or type defined as a structural refinement type?
*/
final def isStructuralRefinement: Boolean =
(isClass || isType || isModule) && info.normalize/*.underlying*/.isStructuralRefinement
/** Is this a term symbol only defined in a refinement (so that it needs
* to be accessed by reflection)?
*/
def isOnlyRefinementMember: Boolean =
isTerm && // type members are not affected
owner.isRefinementClass && // owner must be a refinement class
(owner.info decl name) == this && // symbol must be explicitly declared in the refinement (not synthesized from glb)
allOverriddenSymbols.isEmpty && // symbol must not override a symbol in a base class
!isConstant // symbol must not be a constant. Question: Can we exclude @inline methods as well?
final def isStructuralRefinementMember = owner.isStructuralRefinement && isPossibleInRefinement && isPublic
final def isPossibleInRefinement = !isConstructor && !isOverridingSymbol
/** Is this symbol a member of class `clazz`? */
def isMemberOf(clazz: Symbol) =
clazz.info.member(name).alternatives contains this
/** A a member of class `base` is incomplete if
* (1) it is declared deferred or
* (2) it is abstract override and its super symbol in `base` is
* nonexistent or incomplete.
*
* @param base ...
* @return ...
*/
final def isIncompleteIn(base: Symbol): Boolean =
this.isDeferred ||
(this hasFlag ABSOVERRIDE) && {
val supersym = superSymbol(base)
supersym == NoSymbol || supersym.isIncompleteIn(base)
}
// Does not always work if the rawInfo is a SourcefileLoader, see comment
// in "def coreClassesFirst" in Global.
def exists = !owner.isPackageClass || { rawInfo.load(this); rawInfo != NoType }
final def isInitialized: Boolean =
validTo != NoPeriod
/** Can this symbol be loaded by a reflective mirror?
*
* Scalac relies on `ScalaSignature' annotation to retain symbols across compilation runs.
* Such annotations (also called "pickles") are applied on top-level classes and include information
* about all symbols reachable from the annotee. However, local symbols (e.g. classes or definitions local to a block)
* are typically unreachable and information about them gets lost.
*
* This method is useful for macro writers who wish to save certain ASTs to be used at runtime.
* With `isLocatable' it's possible to check whether a tree can be retained as is, or it needs special treatment.
*/
final def isLocatable: Boolean = {
if (this == NoSymbol) return false
if (isRoot || isRootPackage) return true
if (!owner.isLocatable) return false
if (owner.isTerm) return false
if (isLocalDummy) return false
if (isAliasType) return true
if (isType && isNonClassType) return false
if (isRefinementClass) return false
return true
}
/** The variance of this symbol as an integer */
final def variance: Int =
if (isCovariant) 1
else if (isContravariant) -1
else 0
/** The sequence number of this parameter symbol among all type
* and value parameters of symbol's owner. -1 if symbol does not
* appear among the parameters of its owner.
*/
def paramPos: Int = {
def searchIn(tpe: Type, base: Int): Int = {
def searchList(params: List[Symbol], fallback: Type): Int = {
val idx = params indexOf this
if (idx >= 0) idx + base
else searchIn(fallback, base + params.length)
}
tpe match {
case PolyType(tparams, res) => searchList(tparams, res)
case MethodType(params, res) => searchList(params, res)
case _ => -1
}
}
searchIn(owner.info, 0)
}
// ------ owner attribute --------------------------------------------------------------
def owner: Symbol = {
if (Statistics.hotEnabled) Statistics.incCounter(ownerCount)
rawowner
}
// TODO - don't allow the owner to be changed without checking invariants, at least
// when under some flag. Define per-phase invariants for owner/owned relationships,
// e.g. after flatten all classes are owned by package classes, there are lots and
// lots of these to be declared (or more realistically, discovered.)
def owner_=(owner: Symbol) {
// don't keep the original owner in presentation compiler runs
// (the map will grow indefinitely, and the only use case is the
// backend).
if (!forInteractive) {
if (originalOwner contains this) ()
else originalOwner(this) = rawowner
}
assert(isCompilerUniverse, "owner_= is not thread-safe; cannot be run in reflexive code")
if (traceSymbolActivity)
traceSymbols.recordNewSymbolOwner(this, owner)
_rawowner = owner
}
def ownerChain: List[Symbol] = this :: owner.ownerChain
def originalOwnerChain: List[Symbol] = this :: originalOwner.getOrElse(this, rawowner).originalOwnerChain
// Non-classes skip self and return rest of owner chain; overridden in ClassSymbol.
def enclClassChain: List[Symbol] = owner.enclClassChain
def ownersIterator: Iterator[Symbol] = new Iterator[Symbol] {
private var current = Symbol.this
def hasNext = current ne NoSymbol
def next = { val r = current; current = current.owner; r }
}
/** Same as `ownerChain contains sym` but more efficient, and
* with a twist for refinement classes (see RefinementClassSymbol.)
*/
def hasTransOwner(sym: Symbol): Boolean = {
var o = this
while ((o ne sym) && (o ne NoSymbol)) o = o.owner
(o eq sym)
}
// ------ name attribute --------------------------------------------------------------
/** If this symbol has an expanded name, its original name, otherwise its name itself.
* @see expandName
*/
def originalName: Name = nme.originalName(nme.dropLocalSuffix(name))
/** The name of the symbol before decoding, e.g. `\$eq\$eq` instead of `==`.
*/
def encodedName: String = name.toString
/** The decoded name of the symbol, e.g. `==` instead of `\$eq\$eq`.
*/