/
Symbols.scala
3818 lines (3281 loc) · 159 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
/*
* 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.
*/
/* NSC -- new Scala compiler
* Copyright 2005-2013 LAMP/EPFL
* @author Martin Odersky
*/
package scala
package reflect
package internal
import scala.collection.immutable
import scala.collection.mutable.ListBuffer
import util.{ Statistics, shortClassOfInstance, StatisticsStatics }
import Flags._
import scala.annotation.tailrec
import scala.reflect.io.{ AbstractFile, NoAbstractFile }
import Variance._
trait Symbols extends api.Symbols { self: SymbolTable =>
import definitions._
import statistics._
protected var ids = 0
def getCurrentSymbolIdCount: Int = ids
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[this] var _recursionTable = immutable.Map.empty[Symbol, Int]
def recursionTable = _recursionTable
def recursionTable_=(value: immutable.Map[Symbol, Int]) = _recursionTable = value
private[this] var _lockedCount = 0
def lockedCount = this._lockedCount
def lockedCount_=(i: Int) = _lockedCount = i
@deprecated("Global existential IDs no longer used", "2.12.1")
private[this] var existentialIds = 0
@deprecated("Global existential IDs no longer used", "2.12.1")
protected def nextExistentialId() = { existentialIds += 1; existentialIds }
@deprecated("Use overload that accepts an id", "2.12.1")
protected def freshExistentialName(suffix: String): TypeName = freshExistentialName(suffix, nextExistentialId())
protected def freshExistentialName(suffix: String, id: Int): TypeName = newTypeName("_" + id + 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
/**
* This map stores the original owner the first time the owner of a symbol is re-assigned.
* The original owner of a symbol is needed in some places in the backend. Ideally, owners should
* be versioned like the type history.
*/
private[this] val originalOwnerMap = perRunCaches.newAnyRefMap[Symbol, Symbol]()
// 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.)
// could be private since 2.11.6, but left protected to avoid potential breakages (eg ensime)
protected def saveOriginalOwner(sym: Symbol): Unit = {
// some synthetic symbols have NoSymbol as owner initially
if (sym.owner != NoSymbol) {
if (originalOwnerMap contains sym) ()
else defineOriginalOwner(sym, sym.rawowner)
}
}
def defineOriginalOwner(sym: Symbol, owner: Symbol): Unit = {
originalOwnerMap(sym) = owner
}
def symbolOf[T: WeakTypeTag]: TypeSymbol = weakTypeOf[T].typeSymbolDirect.asType
abstract class SymbolContextApiImpl extends SymbolApi {
this: Symbol =>
def isFreeTerm: Boolean = false
def asFreeTerm: FreeTermSymbol = throw new ScalaReflectionException(s"$this is not a free term")
def isFreeType: Boolean = false
def asFreeType: FreeTypeSymbol = throw new ScalaReflectionException(s"$this is not a free type")
def isExistential: Boolean = this.isExistentiallyBound
def isParamWithDefault: Boolean = this.hasDefault
// `isByNameParam` is only true for a call-by-name parameter of a *method*,
// an argument of the primary constructor seen in the class body is excluded by `isValueParameter`
def isByNameParam: Boolean = this.isValueParameter && (this hasFlag BYNAMEPARAM)
def isImplementationArtifact: Boolean = this hasFlag (BRIDGE | VBRIDGE | ARTIFACT)
def isJava: Boolean = isJavaDefined
def isField: Boolean = isTerm && !isModule && (!isMethod || owner.isTrait && isAccessor)
def isMutableVal = if (owner.isTrait) !hasFlag(STABLE) else isMutable
def isVal: Boolean = isField && !isMutableVal
def isVar: Boolean = isField && !isLazy && isMutableVal
def isAbstract: Boolean = isAbstractClass || isDeferred || isAbstractType
def isPrivateThis = this hasAllFlags (PRIVATE | LOCAL)
def isProtectedThis = this hasAllFlags (PROTECTED | LOCAL)
def isJavaEnum: Boolean = hasJavaEnumFlag
def isJavaAnnotation: Boolean = hasJavaAnnotationFlag
def isStaticAnnotation: Boolean =
hasJavaAnnotationFlag || isNonBottomSubClass(StaticAnnotationClass)
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 = {
// See `getFlag` to learn more about the `isThreadsafe` call in the body of this method.
if (!isCompilerUniverse && !isThreadsafe(purpose = AllOps)) initialize
enclosingPackage.info.decls.foreach { sym =>
if(sourceFile == sym.sourceFile) {
sym.rawInfo.forceDirectSuperclasses
}
}
if(!isPastTyper)
updateAttachment(KnownDirectSubclassesCalled)
children
}
def selfType = {
// See `getFlag` to learn more about the `isThreadsafe` call in the body of this method.
if (!isCompilerUniverse && !isThreadsafe(purpose = AllOps)) initialize
typeOfThis
}
def baseClasses = info.baseClasses
def module = sourceModule
def thisPrefix: Type = thisType
def superPrefix(supertpe: Type): Type = SuperType(thisType, supertpe)
// These two methods used to call fullyInitializeSymbol on `this`.
//
// The only positive effect of that is, to the best of my knowledge, convenient printing
// (if you print a signature of the symbol that's not fully initialized,
// you might end up with weird <?>'s in value/type params)
//
// Another effect is obviously full initialization of that symbol,
// but that one shouldn't be necessary from the public API standpoint,
// because everything that matters auto-initializes at runtime,
// and auto-initialization at compile-time is anyway dubious
// (I've had spurious cyclic refs caused by calling typeSignature
// that initialized parent, which was in the middle of initialization).
//
// Given that and also given the pressure of being uniform with info and infoIn,
// I've removed calls to fullyInitializeSymbol from typeSignature and typeSignatureIn,
// injected fullyInitializeSymbol in showDecl, and injected fullyInitializeType in runtime Type.toString
// (the latter will make things a bit harder to debug in runtime universe, because
// toString might now very rarely cause cyclic references, but we also have showRaw that doesn't do initialization).
//
// Auto-initialization in runtime Type.toString is one of the examples of why a cake-based design
// isn't a very good idea for reflection API. Sometimes we want to same pretty name for both a compiler-facing
// and a user-facing API that should have different behaviors (other examples here include isPackage, isCaseClass, etc).
// Within a cake it's fundamentally impossible to achieve that.
def typeSignature: Type = info
def typeSignatureIn(site: Type): Type = site memberInfo this
def toType: Type = tpe
def toTypeIn(site: Type): Type = site.memberType(this)
def toTypeConstructor: Type = typeConstructor
def setAnnotations(annots: AnnotationInfo*): this.type = { setAnnotations(annots.toList); this }
def getter: Symbol = getterIn(owner)
def setter: Symbol = setterIn(owner)
def companion: Symbol = {
if (isModule && !hasPackageFlag) companionSymbol
else if (isModuleClass && !isPackageClass) sourceModule.companionSymbol
else if (isClass && !isModuleClass && !isPackageClass) companionSymbol
else NoSymbol
}
def infoIn(site: Type): Type = typeSignatureIn(site)
def overrides: List[Symbol] = allOverriddenSymbols
def paramLists: List[List[Symbol]] = paramss
}
private[reflect] final case class SymbolKind(accurate: String, sanitized: String, abbreviation: String) {
def skolemize: SymbolKind = copy(accurate = s"$accurate skolem", abbreviation = s"$abbreviation#SKO")
}
protected def newStubSymbol(owner: Symbol,
name: Name,
missingMessage: String): Symbol = {
name match {
case n: TypeName => new StubClassSymbol(owner, n, missingMessage)
case _ => new StubTermSymbol(owner, name.toTermName, missingMessage)
}
}
/** 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 {
// makes sure that all symbols that runtime reflection deals with are synchronized
private def isSynchronized = this.isInstanceOf[scala.reflect.runtime.SynchronizedSymbols#SynchronizedSymbol]
private def isAprioriThreadsafe = isThreadsafe(AllOps)
if (!(isCompilerUniverse || isSynchronized || isAprioriThreadsafe))
throw new AssertionError(s"unsafe symbol $initName (child of $initOwner) in runtime reflection universe") // Not an assert to avoid retention of `initOwner` as a field!
type AccessBoundaryType = Symbol
type AnnotationType = AnnotationInfo
// TODO - don't allow names to be renamed in this unstructured 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) {
def msg = s"In $owner, renaming $name -> $n"
if (isSpecialized) debuglog(msg) else log(msg)
}
}
def asNameType(n: Name): NameType
// Syncnote: need not be protected, as only assignment happens in owner_=, which is not exposed to api
// The null check is for NoSymbol, which can't pass a reference to itself to the constructor and also
// can't call owner_= due to an assertion it contains.
private[this] var _rawowner = if (initOwner eq null) this else initOwner
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): Unit = { _validTo = x}
def setName(name: Name): this.type = { this.name = asNameType(name) ; this }
// Update the surrounding scopes
protected[this] def changeNameInOwners(name: Name): Unit = {
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 = variance.symbolicString
override def flagMask =
if (settings.debug && !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 = shortClassOfInstance(this)
def symbolCreationString: String = (
"%s%25s | %-40s | %s".format(
if (settings.uniqid) "%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 UnitTpe
/** Instance constructor with info set. */
def newClassConstructor(pos: Position): MethodSymbol =
newConstructor(pos) setInfo MethodType(Nil, this.tpe)
def newLinkedModule(moduleClass: Symbol, newFlags: Long = 0L): ModuleSymbol = {
val m = newModuleSymbol(moduleClass.name.toTermName, moduleClass.pos, MODULE | newFlags)
connectModuleToClass(m, moduleClass.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.toTermName, pos, flags)
val c = newModuleClass(name.toTypeName, pos, flags & ModuleToClassFlags)
connectModuleToClass(m, c)
(m, c)
}
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.
* 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(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 =
newExistentialSkolem(basis.name.toTypeName, basis.info, basis.flags, basis.pos, origin)
/** Create a new existential type skolem with this symbol its owner, and the given other properties.
*/
def newExistentialSkolem(name: TypeName, info: Type, flags: Long, pos: Position, origin: AnyRef): TypeSkolem = {
val skolem = newTypeSkolemSymbol(name.toTypeName, origin, pos, (flags | EXISTENTIAL) & ~PARAM)
skolem setInfo (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
@deprecated("Use overload that accepts an id", "2.12.1")
final def freshExistential(suffix: String): TypeSymbol =
newExistential(freshExistentialName(suffix), pos)
final def freshExistential(suffix: String, id: Int): TypeSymbol =
newExistential(freshExistentialName(suffix, id), 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
/** Refinement types P { val x: String; type T <: Number }
* also have symbols, they are refinementClasses
*/
final def newRefinementClass(pos: Position): RefinementClassSymbol =
createRefinementClassSymbol(pos, 0L)
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 = {
// Invoke the overridden `newStubSymbol` in Global that gives us access to typer
Symbols.this.newStubSymbol(this, name, missingMessage)
}
/** Given a field, construct a term symbol that represents the source construct that gave rise the field */
def sugaredSymbolOrSelf = {
val getter = getterIn(owner)
if (getter == NoSymbol) {
this
} else {
val result = owner.newValue(getter.name.toTermName, newFlags = getter.flags & ~Flags.METHOD).setPrivateWithin(getter.privateWithin).setInfo(getter.info.resultType)
val setter = setterIn(owner)
if (setter != NoSymbol) result.setFlag(Flags.MUTABLE)
result
}
}
// ----- 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
@deprecated("trait implementation classes have been removed in Scala 2.12", "2.12.0")
def isImplClass = false
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 isExistentialSkolem = false
def isExistentiallyBound = false
def isGADTSkolem = false
def isTypeParameter = false
def isTypeParameterOrSkolem = false
def isTypeSkolem = 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 isDefaultGetter = 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
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
/** Can this symbol only be subclassed by bottom classes? This is assessed
* to be the case if it is final, and any type parameters are invariant.
*/
def hasOnlyBottomSubclasses = {
def loop(tparams: List[Symbol]): Boolean = tparams match {
case Nil => true
case x :: xs => x.variance.isInvariant && loop(xs)
}
isClass && isFinal && loop(typeParams)
}
final def isOverridableMember = !(isClass || isEffectivelyFinal || isTypeParameter) && safeOwner.isClass
/** Does this symbol denote a wrapper created by the repl? */
final def isInterpreterWrapper = (
(this hasFlag MODULE)
&& isTopLevel
&& nme.isReplWrapperName(name)
)
/** In our current architecture, symbols for top-level classes and modules
* are created as dummies. Package symbols just call newClass(name) or newModule(name) and
* consider their job done.
*
* In order for such a dummy to provide meaningful info (e.g. a list of its members),
* it needs to go through unpickling. Unpickling is a process of reading Scala metadata
* from ScalaSignature annotations and assigning it to symbols and types.
*
* A single unpickling session takes a top-level class or module, parses the ScalaSignature annotation
* and then reads metadata for the unpicklee, its companion (if any) and all their members recursively
* (i.e. the pickle not only contains info about directly nested classes/modules, but also about
* classes/modules nested into those and so on).
*
* Unpickling is triggered automatically whenever info (info in compiler parlance) is called.
* This happens because package symbols assign completer thunks to the dummies they create.
* Therefore metadata loading happens lazily and transparently.
*
* Almost transparently. Unfortunately metadata isn't limited to just signatures (i.e. lists of members).
* It also includes flags (which determine e.g. whether a class is sealed or not), annotations and privateWithin.
* This gives rise to unpleasant effects like in scala/bug#6277, when a flag test called on an uninitialize symbol
* produces incorrect results.
*
* One might think that the solution is simple: automatically call the completer
* whenever one needs flags, annotations and privateWithin - just like it's done for info.
* Unfortunately, this leads to weird crashes in scalac, and currently we can't attempt
* to fix the core of the compiler risk stability a few weeks before the final release.
* upd. Haha, "a few weeks before the final release". This surely sounds familiar :)
*
* However we do need to fix this for runtime reflection, since this idiosyncrasy is not something
* we'd like to expose to reflection users. Therefore a proposed solution is to check whether we're in a
* runtime reflection universe, and if yes and if we've not yet loaded the requested info, then to commence initialization.
*/
def getFlag(mask: Long): Long = {
mask & (if ((mask & PhaseIndependentFlags) == mask) rawflags else flags)
}
/** Does symbol have ANY flag in `mask` set? */
final def hasFlag(mask: Long): Boolean = getFlag(mask) != 0
/** Does symbol have ALL the flags in `mask` set? */
final def hasAllFlags(mask: Long): Boolean = getFlag(mask) == mask
def setFlag(mask: Long): this.type = { _rawflags |= mask ; this }
def resetFlag(mask: Long): this.type = { _rawflags &= ~mask ; this }
def resetFlags(): Unit = { rawflags = 0 }
/** 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 = {
val fs = _rawflags & phase.flagMask
(fs | ((fs & LateFlags) >>> LateShift)) & ~((fs & AntiFlags) >>> AntiShift)
}
def flags_=(fs: Long) = _rawflags = fs
def rawflags_=(x: Long): Unit = { _rawflags = x }
final def hasGetter = isTerm && nme.isLocalName(name)
/**
* Nested modules with a non-static owner receive the METHOD flag during UnCurry's info transform.
* (They are replaced by a ClassDef and DefDef for the module accessor during the fields phase.)
*
* Note: the METHOD flag is added lazily in the info transformer of the UnCurry phase.
* This means that forcing the `sym.info` may change the value of `sym.isMethod`. Forcing the
* info is in the responsibility of the caller. Doing it eagerly here was tried (0ccdb151f) but
* has proven to lead to bugs (scala/bug#8907).
*
* Here's an example where one can see all four of FF FT TF TT for (isStatic, isMethod) at
* various phases.
*
* trait A1 { case class Quux() }
* object A2 extends A1 { object Flax }
* // -- namer object Quux in trait A1
* // -M flatten object Quux in trait A1
* // S- flatten object Flax in object A2
* // -M posterasure object Quux in trait A1
* // -M jvm object Quux in trait A1
* // SM jvm object Quux in object A2
*
* So "isModuleNotMethod" exists not for its achievement in brevity, but to encapsulate the
* relevant condition.
*/
def isModuleNotMethod = isModule && !isMethod
// After RefChecks, the `isStatic` check is mostly redundant: all non-static modules should
// be methods (and vice versa). There's a corner case on the vice-versa with mixed-in module
// symbols:
// trait T { object A }
// object O extends T
// The module symbol A is cloned into T$impl (addInterfaces), and then cloned into O (mixin).
// Since the original A is not static, it's turned into a method. The clone in O however is
// static (owned by a module), but it's also a method.
def isStaticModule = isModuleNotMethod && isStatic
final def isInitializedToDefault = !isType && hasAllFlags(DEFAULTINIT | ACCESSOR)
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) &&
!phase.erasedTypes && info.firstParent.typeSymbol == AnyValClass && !isPrimitiveValueClass
final def isMethodWithExtension =
isMethod && owner.isDerivedValueClass && !isParamAccessor && !isConstructor && !hasFlag(SUPERACCESSOR) && !isMacro && !isSpecialized
final def isAnonymousFunction = isSynthetic && (name containsName tpnme.ANON_FUN_NAME)
final def isDelambdafyFunction = isSynthetic && (name containsName tpnme.DELAMBDAFY_LAMBDA_CLASS_NAME)
final def isDelambdafyTarget = isArtifact && isMethod && hasAttachment[DelambdafyTarget.type]
final def isDefinedInPackage = effectiveOwner.isPackageClass
final def needsFlatClasses = phase.flatClasses && (rawowner ne NoSymbol) && !rawowner.isPackageClass
// TODO introduce a flag for these?
final def isPatternTypeVariable: Boolean =
isAbstractType && !isExistential && !isTypeParameterOrSkolem && isLocalToBlock
/** 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): Unit = { }
// 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
/** The package object symbol corresponding to this package or package class symbol, or NoSymbol otherwise */
def packageObject: Symbol =
if (isPackageClass) tpe.packageObject
else if (hasPackageFlag) moduleClass.packageObject
else NoSymbol
/** 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 &&*/ {
// scala/bug#5941 runtime reflection can have distinct symbols representing `package scala` (from different mirrors)
// We check equality by FQN here to make sure we omit prefixes uniformly for all of them.
def matches(sym1: Symbol, sym2: Symbol) = (sym1 eq sym2) || (sym1.hasPackageFlag && sym2.hasPackageFlag && sym1.name == sym2.name && sym1.fullNameString == sym2.fullNameString)
val skipped = skipPackageObject
UnqualifiedOwners.exists((sym: Symbol) => matches(sym, skipped)) || 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 eq null)
|| (info.isComplete && !info.isHigherKinded)
)
}
def isStrictFP: Boolean = !isDeferred && (hasAnnotation(ScalaStrictFPAttr) || originalOwner.isStrictFP)
def isSerializable = info.baseClasses.exists(_ == SerializableClass)
def isDeprecated = hasAnnotation(DeprecatedAttr)
def deprecationMessage = getAnnotation(DeprecatedAttr) flatMap (_ stringArg 0)
def deprecationVersion = getAnnotation(DeprecatedAttr) flatMap (_ stringArg 1)
def deprecatedParamName = getAnnotation(DeprecatedNameAttr) flatMap (ann => ann.symbolArg(0).orElse(ann.stringArg(0).map(newTermName)).orElse(Some(nme.NO_NAME)))
def deprecatedParamVersion = getAnnotation(DeprecatedNameAttr) flatMap (_ stringArg 1)
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 implicitAmbiguousMsg = getAnnotation(ImplicitAmbiguousClass) 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) && (unexpandedName == nme.OUTER)
/** Is this symbol an accessor method for outer? */
final def isOuterField = isArtifact && (unexpandedName == nme.OUTER_LOCAL)
/** Is this symbol an outer parameter in a constructor */
final def isOuterParam = isParameter && owner.isConstructor && (name == nme.OUTER_ARG || name == nme.OUTER)
/** Does this symbol denote a stable value, ignoring volatility?
*
* Stability and volatility are checked separately to allow volatile paths in patterns that amount to equality checks. scala/bug#6815
*/
final def isStable = isTerm && !isMutable && !(hasFlag(BYNAMEPARAM)) && (!isMethod || hasStableFlag)
final def hasVolatileType = tpe.isVolatile && !hasAnnotation(uncheckedStableClass)
/** 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? */
// xeno-by: why this obscure use of the CASE flag? why not simply compare name with nme.apply and nme.unapply?
final def isCaseApplyOrUnapply =
isMethod && isCase && isSynthetic
/** Is this symbol a synthetic copy method in a case class? */
final def isCaseCopy =
isMethod && owner.isCase && isSynthetic && name == nme.copy
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
*
* TODO: should this only be invoked on class / module symbols? because there's also `isStaticMember`.
*
* Note: the result of `isStatic` changes over time.
* - Lambdalift local definitions to the class level, the `owner` field is modified.
* object T { def foo { object O } }
* After lambdalift, the OModule.isStatic is true.
*
* - After flatten, nested classes are moved to the package level. Invoking `owner` on a
* class returns a package class, for which `isStaticOwner` is true. For example,
* class C { object O }
* OModuleClass.isStatic is true after flatten. Using phase travel to get before flatten,
* method `owner` returns the class C.
*
* Why not make a stable version of `isStatic`? Maybe some parts of the compiler depend on the
* current implementation.