forked from scala/scala3
-
Notifications
You must be signed in to change notification settings - Fork 17
/
SymDenotations.scala
2325 lines (1998 loc) · 92.7 KB
/
SymDenotations.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
package dotty.tools
package dotc
package core
import Periods._, Contexts._, Symbols._, Denotations._, Names._, NameOps._, Annotations._
import Types._, Flags._, Decorators._, DenotTransformers._, StdNames._, Scopes._
import NameOps._, NameKinds._, Phases._
import TypeApplications.TypeParamInfo
import Scopes.Scope
import dotty.tools.io.AbstractFile
import Decorators.SymbolIteratorDecorator
import ast._
import annotation.tailrec
import util.SimpleIdentityMap
import util.Stats
import java.util.WeakHashMap
import config.Config
import reporting.diagnostic.Message
import reporting.diagnostic.messages.BadSymbolicReference
import reporting.trace
import scala.annotation.internal.sharable
trait SymDenotations { this: Context =>
import SymDenotations._
/** Factory method for SymDenotion creation. All creations
* should be done via this method.
*/
def SymDenotation(
symbol: Symbol,
owner: Symbol,
name: Name,
initFlags: FlagSet,
initInfo: Type,
initPrivateWithin: Symbol = NoSymbol)(implicit ctx: Context): SymDenotation = {
val result =
if (symbol.isClass)
if (initFlags is Package) new PackageClassDenotation(symbol, owner, name, initFlags, initInfo, initPrivateWithin)
else new ClassDenotation(symbol, owner, name, initFlags, initInfo, initPrivateWithin)
else new SymDenotation(symbol, owner, name, initFlags, initInfo, initPrivateWithin)
result.validFor = stablePeriod
result
}
def stillValid(denot: SymDenotation): Boolean =
if (denot.is(ValidForever) || denot.isRefinementClass || denot.isImport) true
else {
val initial = denot.initial
val firstPhaseId = initial.validFor.firstPhaseId.max(ctx.typerPhase.id)
if ((initial ne denot) || ctx.phaseId != firstPhaseId)
ctx.withPhase(firstPhaseId).stillValidInOwner(initial)
else
stillValidInOwner(denot)
}
private[SymDenotations] def stillValidInOwner(denot: SymDenotation): Boolean = try {
val owner = denot.owner.denot
stillValid(owner) && (
!owner.isClass
|| owner.isRefinementClass
|| owner.is(Scala2x)
|| (owner.unforcedDecls.lookupAll(denot.name) contains denot.symbol)
|| denot.isSelfSym
|| denot.isLocalDummy)
} catch {
case ex: StaleSymbol => false
}
/** Explain why symbol is invalid; used for debugging only */
def traceInvalid(denot: Denotation): Boolean = {
def show(d: Denotation) = s"$d#${d.symbol.id}"
def explain(msg: String) = {
println(s"${show(denot)} is invalid at ${this.period} because $msg")
false
}
denot match {
case denot: SymDenotation =>
def explainSym(msg: String) = explain(s"$msg\ndefined = ${denot.definedPeriodsString}")
if (denot.is(ValidForever) || denot.isRefinementClass) true
else {
implicit val ctx = this
val initial = denot.initial
if ((initial ne denot) || ctx.phaseId != initial.validFor.firstPhaseId) {
ctx.withPhase(initial.validFor.firstPhaseId).traceInvalid(initial)
} else try {
val owner = denot.owner.denot
if (!traceInvalid(owner)) explainSym("owner is invalid")
else if (!owner.isClass || owner.isRefinementClass || denot.isSelfSym) true
else if (owner.unforcedDecls.lookupAll(denot.name) contains denot.symbol) true
else explainSym(s"decls of ${show(owner)} are ${owner.unforcedDecls.lookupAll(denot.name).toList}, do not contain ${denot.symbol}")
} catch {
case ex: StaleSymbol => explainSym(s"$ex was thrown")
}
}
case _ =>
explain("denotation is not a SymDenotation")
}
}
/** Configurable: Accept stale symbol with warning if in IDE */
def staleOK: Boolean = Config.ignoreStaleInIDE && mode.is(Mode.Interactive)
/** Possibly accept stale symbol with warning if in IDE */
def acceptStale(denot: SingleDenotation): Boolean =
staleOK && {
ctx.echo(denot.staleSymbolMsg)
true
}
}
object SymDenotations {
/** A sym-denotation represents the contents of a definition
* during a period.
*/
class SymDenotation private[SymDenotations] (
symbol: Symbol,
final val maybeOwner: Symbol,
final val name: Name,
initFlags: FlagSet,
initInfo: Type,
initPrivateWithin: Symbol = NoSymbol) extends SingleDenotation(symbol, initInfo) {
//assert(symbol.id != 4940, name)
override def hasUniqueSym: Boolean = exists
/** Debug only
override def validFor_=(p: Period) = {
super.validFor_=(p)
}
*/
if (Config.checkNoSkolemsInInfo) assertNoSkolems(initInfo)
// ------ Getting and setting fields -----------------------------
private[this] var myFlags: FlagSet = adaptFlags(initFlags)
private[this] var myPrivateWithin: Symbol = initPrivateWithin
private[this] var myAnnotations: List[Annotation] = Nil
/** The owner of the symbol; overridden in NoDenotation */
def owner: Symbol = maybeOwner
/** The flag set */
final def flags(implicit ctx: Context): FlagSet = { ensureCompleted(); myFlags }
/** The flag set without forcing symbol completion.
* Should be used only for printing.
*/
private[dotc] final def flagsUNSAFE: FlagSet = myFlags
/** Adapt flag set to this denotation's term or type nature */
private def adaptFlags(flags: FlagSet) = if (isType) flags.toTypeFlags else flags.toTermFlags
/** Update the flag set */
final def flags_=(flags: FlagSet): Unit =
myFlags = adaptFlags(flags)
/** Set given flags(s) of this denotation */
final def setFlag(flags: FlagSet): Unit = { myFlags |= flags }
/** Unset given flags(s) of this denotation */
final def resetFlag(flags: FlagSet): Unit = { myFlags &~= flags }
/** Set applicable flags in {NoInits, PureInterface}
* @param parentFlags The flags that match the class or trait's parents
* @param bodyFlags The flags that match the class or trait's body
*/
final def setNoInitsFlags(parentFlags: FlagSet, bodyFlags: FlagSet): Unit =
setFlag(
if (myFlags.is(Trait)) NoInitsInterface & bodyFlags // no parents are initialized from a trait
else NoInits & bodyFlags & parentFlags)
private def isCurrent(fs: FlagSet) =
fs <= (
if (myInfo.isInstanceOf[SymbolLoader]) FromStartFlags
else AfterLoadFlags)
final def relevantFlagsFor(fs: FlagSet)(implicit ctx: Context) =
if (isCurrent(fs)) myFlags else flags
/** Has this denotation one of the flags in `fs` set? */
final def is(fs: FlagSet)(implicit ctx: Context): Boolean =
(if (isCurrent(fs)) myFlags else flags) is fs
/** Has this denotation one of the flags in `fs` set, whereas none of the flags
* in `butNot` are set?
*/
final def is(fs: FlagSet, butNot: FlagSet)(implicit ctx: Context): Boolean =
(if (isCurrent(fs) && isCurrent(butNot)) myFlags else flags) is (fs, butNot)
/** Has this denotation all of the flags in `fs` set? */
final def is(fs: FlagConjunction)(implicit ctx: Context): Boolean =
(if (isCurrent(fs)) myFlags else flags) is fs
/** Has this denotation all of the flags in `fs` set, whereas none of the flags
* in `butNot` are set?
*/
final def is(fs: FlagConjunction, butNot: FlagSet)(implicit ctx: Context): Boolean =
(if (isCurrent(fs) && isCurrent(butNot)) myFlags else flags) is (fs, butNot)
/** The type info, or, if symbol is not yet completed, the completer */
final def infoOrCompleter: Type = myInfo
/** Optionally, the info if it is completed */
final def unforcedInfo: Option[Type] = myInfo match {
case myInfo: LazyType => None
case _ => Some(myInfo)
}
final def completeFrom(completer: LazyType)(implicit ctx: Context): Unit =
if (Config.showCompletions) {
println(i"${" " * indent}completing ${if (isType) "type" else "val"} $name")
indent += 1
if (myFlags is Touched) throw CyclicReference(this)
myFlags |= Touched
// completions.println(s"completing ${this.debugString}")
try completer.complete(this)(ctx.withPhase(validFor.firstPhaseId))
catch {
case ex: CyclicReference =>
println(s"error while completing ${this.debugString}")
throw ex
}
finally {
indent -= 1
println(i"${" " * indent}completed $name in $owner")
}
}
else {
if (myFlags is Touched) throw CyclicReference(this)
myFlags |= Touched
completer.complete(this)(ctx.withPhase(validFor.firstPhaseId))
}
protected[dotc] def info_=(tp: Type): Unit = {
/* // DEBUG
def illegal: String = s"illegal type for $this: $tp"
if (this is Module) // make sure module invariants that allow moduleClass and sourceModule to work are kept.
tp match {
case tp: ClassInfo => assert(tp.selfInfo.isInstanceOf[TermRefBySym], illegal)
case tp: NamedType => assert(tp.isInstanceOf[TypeRefBySym], illegal)
case tp: ExprType => assert(tp.resultType.isInstanceOf[TypeRefBySym], illegal)
case _ =>
}
*/
if (Config.checkNoSkolemsInInfo) assertNoSkolems(tp)
myInfo = tp
}
/** The name, except
* - if this is a module class, strip the module class suffix
* - if this is a companion object with a clash-avoiding name, strip the
* "avoid clash" suffix
*/
def effectiveName(implicit ctx: Context): Name =
if (this is ModuleClass) name.stripModuleClassSuffix
else name.exclude(AvoidClashName)
/** The privateWithin boundary, NoSymbol if no boundary is given.
*/
final def privateWithin(implicit ctx: Context): Symbol = { ensureCompleted(); myPrivateWithin }
/** Set privateWithin. */
protected[dotc] final def privateWithin_=(sym: Symbol): Unit =
myPrivateWithin = sym
/** The annotations of this denotation */
final def annotations(implicit ctx: Context): List[Annotation] = {
ensureCompleted(); myAnnotations
}
/** Update the annotations of this denotation */
final def annotations_=(annots: List[Annotation]): Unit =
myAnnotations = annots
/** Does this denotation have an annotation matching the given class symbol? */
final def hasAnnotation(cls: Symbol)(implicit ctx: Context): Boolean =
dropOtherAnnotations(annotations, cls).nonEmpty
/** Apply transform `f` to all annotations of this denotation */
final def transformAnnotations(f: Annotation => Annotation)(implicit ctx: Context): Unit =
annotations = annotations.mapConserve(f)
/** Keep only those annotations that satisfy `p` */
final def filterAnnotations(p: Annotation => Boolean)(implicit ctx: Context): Unit =
annotations = annotations.filterConserve(p)
/** Optionally, the annotation matching the given class symbol */
final def getAnnotation(cls: Symbol)(implicit ctx: Context): Option[Annotation] =
dropOtherAnnotations(annotations, cls) match {
case annot :: _ => Some(annot)
case nil => None
}
/** The same as getAnnotation, but without ensuring
* that the symbol carrying the annotation is completed
*/
final def unforcedAnnotation(cls: Symbol)(implicit ctx: Context): Option[Annotation] =
dropOtherAnnotations(myAnnotations, cls) match {
case annot :: _ => Some(annot)
case nil => None
}
/** Add given annotation to the annotations of this denotation */
final def addAnnotation(annot: Annotation): Unit =
annotations = annot :: myAnnotations
/** Remove annotation with given class from this denotation */
final def removeAnnotation(cls: Symbol)(implicit ctx: Context): Unit =
annotations = myAnnotations.filterNot(_ matches cls)
/** Remove any annotations with same class as `annot`, and add `annot` */
final def updateAnnotation(annot: Annotation)(implicit ctx: Context): Unit = {
removeAnnotation(annot.symbol)
addAnnotation(annot)
}
/** Add all given annotations to this symbol */
final def addAnnotations(annots: TraversableOnce[Annotation])(implicit ctx: Context): Unit =
annots.foreach(addAnnotation)
@tailrec
private def dropOtherAnnotations(anns: List[Annotation], cls: Symbol)(implicit ctx: Context): List[Annotation] = anns match {
case ann :: rest => if (ann matches cls) anns else dropOtherAnnotations(rest, cls)
case Nil => Nil
}
/** The denotation is completed: info is not a lazy type and attributes have defined values */
final def isCompleted: Boolean = !myInfo.isInstanceOf[LazyType]
/** The denotation is in train of being completed */
final def isCompleting: Boolean = (myFlags is Touched) && !isCompleted
/** The completer of this denotation. @pre: Denotation is not yet completed */
final def completer: LazyType = myInfo.asInstanceOf[LazyType]
/** Make sure this denotation is completed */
final def ensureCompleted()(implicit ctx: Context): Unit = info
/** The symbols defined in this class or object.
* Careful! This does not force the type, so is compilation order dependent.
* This method should be used only in the following circumstances:
*
* 1. When accessing type parameters or type parameter accessors (both are entered before
* completion).
* 2. When obtaining the current scope in order to enter, rename or delete something there.
* 3. When playing it safe in order not to raise CylicReferences, e.g. for printing things
* or taking more efficient shortcuts (e.g. the stillValid test).
*/
final def unforcedDecls(implicit ctx: Context): Scope = myInfo match {
case cinfo: LazyType =>
val knownDecls = cinfo.decls
if (knownDecls ne EmptyScope) knownDecls
else { completeFrom(cinfo); unforcedDecls } // complete-once
case _ => info.decls
}
/** If this is a package class, the symbols entered in it
* before it is completed. (this is needed to eagerly enter synthetic
* aliases such as AnyRef into a package class without forcing it.
* Right now, the only usage is for the AnyRef alias in Definitions.
*/
final private[core] def currentPackageDecls(implicit ctx: Context): MutableScope = myInfo match {
case pinfo: SymbolLoaders.PackageLoader => pinfo.currentDecls
case _ => unforcedDecls.openForMutations
}
/** If this is a synthetic opaque type alias, mark it as Deferred with empty bounds
*/
final def normalizeOpaque()(implicit ctx: Context) = {
def abstractRHS(tp: Type): Type = tp match {
case tp: HKTypeLambda => tp.derivedLambdaType(resType = abstractRHS(tp.resType))
case _ => defn.AnyType
}
if (isOpaqueHelper) {
info match {
case TypeAlias(alias) =>
info = TypeBounds(defn.NothingType, abstractRHS(alias))
setFlag(Deferred)
case _ =>
}
}
}
// ------ Names ----------------------------------------------
/** The expanded name of this denotation. */
final def expandedName(implicit ctx: Context): Name =
if (name.is(ExpandedName) || isConstructor) name
else name.expandedName(initial.owner)
// need to use initial owner to disambiguate, as multiple private symbols with the same name
// might have been moved from different origins into the same class
/** The name with which the denoting symbol was created */
final def originalName(implicit ctx: Context): Name = initial.effectiveName
/** The encoded full path name of this denotation, where outer names and inner names
* are separated by `separator` strings as indicated by the given name kind.
* Drops package objects. Represents each term in the owner chain by a simple `_$`.
*/
def fullNameSeparated(kind: QualifiedNameKind)(implicit ctx: Context): Name =
maybeOwner.fullNameSeparated(kind, kind, name)
/** The encoded full path name of this denotation (separated by `prefixKind`),
* followed by the separator implied by `kind` and the given `name`.
* Drops package objects. Represents each term in the owner chain by a simple `_$`.
*/
def fullNameSeparated(prefixKind: QualifiedNameKind, kind: QualifiedNameKind, name: Name)(implicit ctx: Context): Name =
if (symbol == NoSymbol || isEffectiveRoot || kind == FlatName && is(PackageClass))
name
else {
var filler = ""
var encl = symbol
while (!encl.isClass && !encl.isPackageObject) {
encl = encl.owner
filler += "_$"
}
var prefix = encl.fullNameSeparated(prefixKind)
if (kind.separator == "$")
// duplicate scalac's behavior: don't write a double '$$' for module class members.
prefix = prefix.exclude(ModuleClassName)
def qualify(n: SimpleName) =
kind(prefix.toTermName, if (filler.isEmpty) n else termName(filler + n))
val fn = name replace {
case name: SimpleName => qualify(name)
case name @ AnyQualifiedName(_, _) => qualify(name.mangled.toSimpleName)
}
if (name.isTypeName) fn.toTypeName else fn.toTermName
}
/** The encoded flat name of this denotation, where joined names are separated by `separator` characters. */
def flatName(implicit ctx: Context): Name = fullNameSeparated(FlatName)
/** `fullName` where `.' is the separator character */
def fullName(implicit ctx: Context): Name = fullNameSeparated(QualifiedName)
// ----- Tests -------------------------------------------------
/** Is this denotation a type? */
override def isType: Boolean = name.isTypeName
/** Is this denotation a class? */
final def isClass: Boolean = isInstanceOf[ClassDenotation]
/** Is this denotation a non-trait class? */
final def isRealClass(implicit ctx: Context): Boolean = isClass && !is(Trait)
/** Cast to class denotation */
final def asClass: ClassDenotation = asInstanceOf[ClassDenotation]
/** is this symbol the result of an erroneous definition? */
def isError: Boolean = false
/** Make denotation not exist */
final def markAbsent(): Unit =
myInfo = NoType
/** Is symbol known to not exist, or potentially not completed yet? */
final def unforcedIsAbsent(implicit ctx: Context): Boolean =
myInfo == NoType ||
(this is (ModuleVal, butNot = Package)) && moduleClass.unforcedIsAbsent
/** Is symbol known to not exist? */
final def isAbsent(implicit ctx: Context): Boolean = {
ensureCompleted()
(myInfo `eq` NoType) ||
(this is (ModuleVal, butNot = Package)) && moduleClass.isAbsent
}
/** Is this symbol the root class or its companion object? */
final def isRoot: Boolean =
(maybeOwner eq NoSymbol) && (name.toTermName == nme.ROOT || name == nme.ROOTPKG)
/** Is this symbol the empty package class or its companion object? */
final def isEmptyPackage(implicit ctx: Context): Boolean =
name.toTermName == nme.EMPTY_PACKAGE && owner.isRoot
/** Is this symbol the empty package class or its companion object? */
final def isEffectiveRoot(implicit ctx: Context): Boolean = isRoot || isEmptyPackage
/** Is this symbol an anonymous class? */
final def isAnonymousClass(implicit ctx: Context): Boolean =
isClass && (initial.name startsWith str.ANON_CLASS)
final def isAnonymousFunction(implicit ctx: Context): Boolean =
this.symbol.is(Method) && (initial.name startsWith str.ANON_FUN)
final def isAnonymousModuleVal(implicit ctx: Context): Boolean =
this.symbol.is(ModuleVal) && (initial.name startsWith str.ANON_CLASS)
/** Is this a synthetic method that represents conversions between representations of a value class
* These methods are generated in ExtensionMethods
* and used in ElimErasedValueType.
*/
final def isValueClassConvertMethod(implicit ctx: Context): Boolean =
name.toTermName == nme.U2EVT ||
name.toTermName == nme.EVT2U
/** Is symbol a primitive value class? */
def isPrimitiveValueClass(implicit ctx: Context): Boolean =
maybeOwner == defn.ScalaPackageClass && defn.ScalaValueClasses().contains(symbol)
/** Is symbol a primitive numeric value class? */
def isNumericValueClass(implicit ctx: Context): Boolean =
maybeOwner == defn.ScalaPackageClass && defn.ScalaNumericValueClasses().contains(symbol)
/** Is symbol a class for which no runtime representation exists? */
def isNotRuntimeClass(implicit ctx: Context): Boolean = defn.NotRuntimeClasses contains symbol
/** Is this symbol a class representing a refinement? These classes
* are used only temporarily in Typer and Unpickler as an intermediate
* step for creating Refinement types.
*/
final def isRefinementClass(implicit ctx: Context): Boolean =
name == tpnme.REFINE_CLASS
/** Is this symbol a package object or its module class? */
def isPackageObject(implicit ctx: Context): Boolean = {
val nameMatches =
if (isType) name == tpnme.PACKAGE.moduleClassName
else name == nme.PACKAGE
nameMatches && (owner is Package) && (this is Module)
}
/** Is this symbol an abstract type? */
final def isAbstractType(implicit ctx: Context): Boolean = this is DeferredType
/** Is this symbol an alias type? */
final def isAliasType(implicit ctx: Context): Boolean = isAbstractOrAliasType && !(this is Deferred)
/** Is this symbol an abstract or alias type? */
final def isAbstractOrAliasType: Boolean = isType & !isClass
/** Is this symbol an abstract type or type parameter? */
final def isAbstractOrParamType(implicit ctx: Context): Boolean = this is DeferredOrTypeParam
/** Is this symbol a user-defined opaque alias type? */
def isOpaqueAlias(implicit ctx: Context): Boolean = is(Opaque, butNot = Synthetic)
/** Is this symbol the companion of an opaque alias type? */
def isOpaqueCompanion(implicit ctx: Context): Boolean = is(OpaqueModule)
/** Is this symbol a synthetic opaque type inside an opaque companion object? */
def isOpaqueHelper(implicit ctx: Context): Boolean = is(SyntheticOpaque, butNot = Module)
/** Can this symbol have a companion module?
* This is the case if it is a class or an opaque type alias.
*/
final def canHaveCompanion(implicit ctx: Context) = isClass || isOpaqueAlias
/** Is this the denotation of a self symbol of some class?
* This is the case if one of two conditions holds:
* 1. It is the symbol referred to in the selfInfo part of the ClassInfo
* which is the type of this symbol's owner.
* 2. This symbol is owned by a class, it's selfInfo field refers to a type
* (indicating the self definition does not introduce a name), and the
* symbol's name is "_".
* TODO: Find a more robust way to characterize self symbols, maybe by
* spending a Flag on them?
*/
final def isSelfSym(implicit ctx: Context): Boolean = owner.infoOrCompleter match {
case ClassInfo(_, _, _, _, selfInfo) =>
selfInfo == symbol ||
selfInfo.isInstanceOf[Type] && name == nme.WILDCARD
case _ => false
}
/** Is this definition contained in `boundary`?
* Same as `ownersIterator contains boundary` but more efficient.
*/
final def isContainedIn(boundary: Symbol)(implicit ctx: Context): Boolean = {
def recur(sym: Symbol): Boolean =
if (sym eq boundary) true
else if (sym eq NoSymbol) false
else if ((sym is PackageClass) && !(boundary is PackageClass)) false
else recur(sym.owner)
recur(symbol)
}
final def isProperlyContainedIn(boundary: Symbol)(implicit ctx: Context): Boolean =
symbol != boundary && isContainedIn(boundary)
/** Is this denotation static (i.e. with no outer instance)? */
final def isStatic(implicit ctx: Context): Boolean =
(if (maybeOwner eq NoSymbol) isRoot else maybeOwner.originDenotation.isStaticOwner) ||
myFlags.is(JavaStatic)
/** Is this a package class or module class that defines static symbols? */
final def isStaticOwner(implicit ctx: Context): Boolean =
myFlags.is(ModuleClass) && (myFlags.is(PackageClass) || isStatic)
/** Is this denotation defined in the same scope and compilation unit as that symbol? */
final def isCoDefinedWith(other: Symbol)(implicit ctx: Context): Boolean =
(this.effectiveOwner == other.effectiveOwner) &&
( !(this.effectiveOwner is PackageClass)
|| this.unforcedIsAbsent || other.unforcedIsAbsent
|| { // check if they are defined in the same file(or a jar)
val thisFile = this.symbol.associatedFile
val thatFile = other.associatedFile
( thisFile == null
|| thatFile == null
|| thisFile.path == thatFile.path // Cheap possibly wrong check, then expensive normalization
|| thisFile.canonicalPath == thatFile.canonicalPath
)
}
)
/** Is this a denotation of a stable term (or an arbitrary type)? */
final def isStable(implicit ctx: Context): Boolean =
isType || is(StableOrErased) || !is(UnstableValue) && !info.isInstanceOf[ExprType]
/** Is this a denotation of a class that does not have - either direct or inherited -
* initaliazion code?
*/
def isNoInitsClass(implicit ctx: Context): Boolean =
isClass &&
(asClass.baseClasses.forall(_.is(NoInits)) || defn.isAssuredNoInits(symbol))
/** Is this a "real" method? A real method is a method which is:
* - not an accessor
* - not an anonymous function
*/
final def isRealMethod(implicit ctx: Context): Boolean =
this.is(Method, butNot = Accessor) && !isAnonymousFunction
/** Is this a getter? */
final def isGetter(implicit ctx: Context): Boolean =
(this is Accessor) && !originalName.isSetterName && !originalName.isScala2LocalSuffix
/** Is this a setter? */
final def isSetter(implicit ctx: Context): Boolean =
(this is Accessor) &&
originalName.isSetterName &&
(!isCompleted || info.firstParamTypes.nonEmpty) // to avoid being fooled by var x_= : Unit = ...
/** is this a symbol representing an import? */
final def isImport: Boolean = name == nme.IMPORT
/** is this the constructor of a class? */
final def isClassConstructor: Boolean = name == nme.CONSTRUCTOR
/** Is this the constructor of a trait? */
final def isImplClassConstructor: Boolean = name == nme.TRAIT_CONSTRUCTOR
/** Is this the constructor of a trait or a class */
final def isConstructor: Boolean = name.isConstructorName
/** Is this a local template dummmy? */
final def isLocalDummy: Boolean = name.isLocalDummyName
/** Does this symbol denote the primary constructor of its enclosing class? */
final def isPrimaryConstructor(implicit ctx: Context): Boolean =
isConstructor && owner.primaryConstructor == symbol
/** Does this symbol denote the static constructor of its enclosing class? */
final def isStaticConstructor(implicit ctx: Context): Boolean =
name.isStaticConstructorName
/** Is this a subclass of the given class `base`? */
def isSubClass(base: Symbol)(implicit ctx: Context): Boolean = false
/** Is this a subclass of `base`,
* and is the denoting symbol also different from `Null` or `Nothing`?
* @note erroneous classes are assumed to derive from all other classes
* and all classes derive from them.
*/
def derivesFrom(base: Symbol)(implicit ctx: Context): Boolean = false
/** Is this symbol a class that extends `AnyVal`? */
final def isValueClass(implicit ctx: Context): Boolean = {
val di = initial
di.isClass &&
di.derivesFrom(defn.AnyValClass)(ctx.withPhase(di.validFor.firstPhaseId))
// We call derivesFrom at the initial phase both because AnyVal does not exist
// after Erasure and to avoid cyclic references caused by forcing denotations
}
/** Is this symbol a class references to which that are supertypes of null? */
final def isNullableClass(implicit ctx: Context): Boolean =
isClass && !isValueClass && !is(ModuleClass) && symbol != defn.NothingClass
/** Is this definition accessible as a member of tree with type `pre`?
* @param pre The type of the tree from which the selection is made
* @param superAccess Access is via super
* Everything is accessible if `pre` is `NoPrefix`.
* A symbol with type `NoType` is not accessible for any other prefix.
*/
final def isAccessibleFrom(pre: Type, superAccess: Boolean = false, whyNot: StringBuffer = null)(implicit ctx: Context): Boolean = {
/** Are we inside definition of `boundary`? */
def accessWithin(boundary: Symbol) = ctx.owner.isContainedIn(boundary)
/** Are we within definition of linked class of `boundary`? */
def accessWithinLinked(boundary: Symbol) = {
val linked = boundary.linkedClass
(linked ne NoSymbol) && accessWithin(linked)
}
/** Is `pre` the same as C.thisThis, where C is exactly the owner of this symbol,
* or, if this symbol is protected, a subclass of the owner?
*/
def isCorrectThisType(pre: Type): Boolean = pre match {
case pre: ThisType =>
(pre.cls eq owner) || (this is Protected) && pre.cls.derivesFrom(owner)
case pre: TermRef =>
pre.symbol.moduleClass == owner
case _ =>
false
}
/** Is protected access to target symbol permitted? */
def isProtectedAccessOK = {
def fail(str: => String): Boolean = {
if (whyNot != null) whyNot append str
false
}
val cls = owner.enclosingSubClass
if (!cls.exists)
fail(
i"""
| Access to protected $this not permitted because enclosing ${ctx.owner.enclosingClass.showLocated}
| is not a subclass of ${owner.showLocated} where target is defined""")
else if (
!( isType // allow accesses to types from arbitrary subclasses fixes #4737
|| pre.derivesFrom(cls)
|| isConstructor
|| (owner is ModuleClass) // don't perform this check for static members
))
fail(
i"""
| Access to protected ${symbol.show} not permitted because prefix type ${pre.widen.show}
| does not conform to ${cls.showLocated} where the access takes place""")
else true
}
if (pre eq NoPrefix) true
else if (info eq NoType) false
else {
val boundary = accessBoundary(owner)
( boundary.isTerm
|| boundary.isRoot
|| (accessWithin(boundary) || accessWithinLinked(boundary)) &&
( !(this is Local)
|| (owner is ImplClass) // allow private local accesses to impl class members
|| isCorrectThisType(pre)
) &&
(!(this.is(Private) && owner.is(Package)) ||
owner == ctx.owner.enclosingPackageClass)
|| (this is Protected) &&
( superAccess
|| pre.isInstanceOf[ThisType]
|| ctx.phase.erasedTypes
|| isProtectedAccessOK
)
)
}
}
/** Do members of this symbol need translation via asSeenFrom when
* accessed via prefix `pre`?
*/
def membersNeedAsSeenFrom(pre: Type)(implicit ctx: Context): Boolean =
!( this.isTerm
|| this.isStaticOwner && !this.isOpaqueCompanion
|| ctx.erasedTypes
|| (pre eq NoPrefix)
|| (pre eq thisType)
)
/** Is this symbol concrete, or that symbol deferred? */
def isAsConcrete(that: Symbol)(implicit ctx: Context): Boolean =
!(this is Deferred) || (that is Deferred)
/** Does this symbol have defined or inherited default parameters? */
def hasDefaultParams(implicit ctx: Context): Boolean =
if (this is HasDefaultParams) true
else if (this is NoDefaultParams) false
else {
val result = allOverriddenSymbols exists (_.hasDefaultParams)
setFlag(if (result) InheritedDefaultParams else NoDefaultParams)
result
}
/** Symbol is an owner that would be skipped by effectiveOwner. Skipped are
* - package objects
* - non-lazy valdefs
*/
def isWeakOwner(implicit ctx: Context): Boolean =
isPackageObject ||
isTerm && !is(MethodOrLazy) && !isLocalDummy
def isSkolem: Boolean = name == nme.SKOLEM
def isInlineMethod(implicit ctx: Context): Boolean =
is(InlineMethod, butNot = AccessorOrSynthetic) &&
name != nme.unapply // unapply methods do not count as inline methods
// we need an inline flag on them only do that
// reduceProjection gets access to their rhs
/** An erased value or an inline method, excluding @forceInline annotated methods.
* The latter have to be kept around to get to parity with Scala.
* This is necessary at least until we have full bootstrap. Right now
* dotty-bootstrapped involves running the Dotty compiler compiled with Scala 2 with
* a Dotty runtime library compiled with Dotty. If we erase @forceInline annotated
* methods, this means that the support methods in dotty.runtime.LazyVals vanish.
* But they are needed for running the lazy val implementations in the Scala-2 compiled compiler.
*/
def isEffectivelyErased(implicit ctx: Context): Boolean =
is(Erased) ||
isInlineMethod && unforcedAnnotation(defn.ForceInlineAnnot).isEmpty
/** ()T and => T types should be treated as equivalent for this symbol.
* Note: For the moment, we treat Scala-2 compiled symbols as loose matching,
* because the Scala library does not always follow the right conventions.
* Examples are: isWhole(), toInt(), toDouble() in BigDecimal, Numeric, RichInt, ScalaNumberProxy.
*/
def matchNullaryLoosely(implicit ctx: Context): Boolean = {
def test(sym: Symbol) =
sym.is(JavaDefined) ||
sym.owner == defn.AnyClass ||
sym == defn.Object_clone ||
sym.owner.is(Scala2x)
this.exists && (test(symbol) || allOverriddenSymbols.exists(test))
}
// ------ access to related symbols ---------------------------------
/* Modules and module classes are represented as follows:
*
* object X extends Y { def f() }
*
* <module> lazy val X: X$ = new X$
* <module> class X$ extends Y { this: X.type => def f() }
*
* During completion, references to moduleClass and sourceModules are stored in
* the completers.
*/
/** The class implementing this module, NoSymbol if not applicable. */
final def moduleClass(implicit ctx: Context): Symbol = {
def notFound = {
if (Config.showCompletions) println(s"missing module class for $name: $myInfo")
NoSymbol
}
if (this is ModuleVal)
myInfo match {
case info: TypeRef => info.symbol
case ExprType(info: TypeRef) => info.symbol // needed after uncurry, when module terms might be accessor defs
case info: LazyType => info.moduleClass
case t: MethodType =>
t.resultType match {
case info: TypeRef => info.symbol
case _ => notFound
}
case _ => notFound
}
else NoSymbol
}
/** The module implemented by this module class, NoSymbol if not applicable. */
final def sourceModule(implicit ctx: Context): Symbol = myInfo match {
case ClassInfo(_, _, _, _, selfType) if this is ModuleClass =>
def sourceOfSelf(tp: TypeOrSymbol): Symbol = tp match {
case tp: TermRef => tp.symbol
case tp: Symbol => sourceOfSelf(tp.info)
case tp: RefinedType => sourceOfSelf(tp.parent)
}
sourceOfSelf(selfType)
case info: LazyType =>
info.sourceModule
case _ =>
NoSymbol
}
/** The field accessed by this getter or setter, or if it does not exist, the getter */
def accessedFieldOrGetter(implicit ctx: Context): Symbol = {
val fieldName = if (isSetter) name.asTermName.getterName else name
val d = owner.info.decl(fieldName)
val field = d.suchThat(!_.is(Method)).symbol
def getter = d.suchThat(_.info.isParameterless).symbol
field orElse getter
}
/** The field accessed by a getter or setter, or
* if it does not exists, the getter of a setter, or
* if that does not exist the symbol itself.
*/
def underlyingSymbol(implicit ctx: Context): Symbol =
if (is(Accessor)) accessedFieldOrGetter orElse symbol else symbol
/** The chain of owners of this denotation, starting with the denoting symbol itself */
final def ownersIterator(implicit ctx: Context): Iterator[Symbol] = new Iterator[Symbol] {
private[this] var current = symbol
def hasNext = current.exists
def next: Symbol = {
val result = current
current = current.owner
result
}
}
/** If this is a weak owner, its owner, otherwise the denoting symbol. */
final def skipWeakOwner(implicit ctx: Context): Symbol =
if (isWeakOwner) owner.skipWeakOwner else symbol
/** The owner, skipping package objects and non-lazy valdefs. */
final def effectiveOwner(implicit ctx: Context): Symbol = owner.skipWeakOwner
/** The class containing this denotation.
* If this denotation is already a class, return itself
* Definitions flagged with JavaStatic are treated specially.
* Their enclosing class is not the lexically enclosing class,
* but in turn the enclosing class of the latter. This reflects
* the context created by `Context#superCallContext`, `Context#thisCallArgContext`
* for these definitions.
*
* Note, that as packages have ClassSymbols, top level classes will have an `enclosingClass`
* with Package flag set.
*/
final def enclosingClass(implicit ctx: Context): Symbol = {
def enclClass(sym: Symbol, skip: Boolean): Symbol = {
def newSkip = sym.is(JavaStaticTerm)
if (!sym.exists)
NoSymbol
else if (sym.isClass)
if (skip) enclClass(sym.owner, newSkip) else sym
else
enclClass(sym.owner, skip || newSkip)
}
enclClass(symbol, false)
}
/** A class that in source code would be lexically enclosing */
final def lexicallyEnclosingClass(implicit ctx: Context): Symbol =
if (!exists || isClass) symbol else owner.lexicallyEnclosingClass
/** A symbol is effectively final if it cannot be overridden in a subclass */
final def isEffectivelyFinal(implicit ctx: Context): Boolean =
is(EffectivelyFinal) || !owner.isClass || owner.is(ModuleOrFinal) || owner.isAnonymousClass
/** The class containing this denotation which has the given effective name. */
final def enclosingClassNamed(name: Name)(implicit ctx: Context): Symbol = {
val cls = enclosingClass
if (cls.effectiveName == name || !cls.exists) cls else cls.owner.enclosingClassNamed(name)
}
/** The closest enclosing method containing this definition.
* A local dummy owner is mapped to the primary constructor of the class.
*/
final def enclosingMethod(implicit ctx: Context): Symbol =
if (this.is(Method)) symbol
else if (this.isClass) primaryConstructor
else if (this.exists) owner.enclosingMethod
else NoSymbol
/** The top-level class containing this denotation,
* except for a toplevel module, where its module class is returned.
*/
final def topLevelClass(implicit ctx: Context): Symbol = {
@tailrec def topLevel(d: SymDenotation): Symbol = {
if (d.isTopLevelClass) d.symbol
else topLevel(d.owner)
}
val sym = topLevel(this)
if (sym.isClass) sym else sym.moduleClass
}
final def isTopLevelClass(implicit ctx: Context): Boolean =
!this.exists || this.isEffectiveRoot || (this is PackageClass) || (this.owner is PackageClass)
/** The package class containing this denotation */
final def enclosingPackageClass(implicit ctx: Context): Symbol =
if (this is PackageClass) symbol else owner.enclosingPackageClass
/** Register target as a companion; overridden in ClassDenotation */
def registerCompanion(target: Symbol)(implicit ctx: Context) = ()
/** The registered companion; overridden in ClassDenotation */
def registeredCompanion(implicit ctx: Context): Symbol = NoSymbol
def registeredCompanion_=(c: Symbol): Unit = ()
/** The module object with the same (term-) name as this class or module class,
* and which is also defined in the same scope and compilation unit.
* NoSymbol if this module does not exist.
*/
final def companionModule(implicit ctx: Context): Symbol =
if (is(Module)) sourceModule
else if (isOpaqueAlias)
info match {
case TypeAlias(TypeRef(prefix: TermRef, _)) => prefix.termSymbol
}
else registeredCompanion.sourceModule
private def companionType(implicit ctx: Context): Symbol =
if (is(Package)) NoSymbol
else if (is(ModuleVal)) moduleClass.denot.companionType