-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathSymDenotations.scala
3081 lines (2661 loc) · 126 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.*
import Phases.{Phase, typerPhase, unfusedPhases}
import Constants.Constant
import TypeApplications.TypeParamInfo
import Scopes.Scope
import dotty.tools.io.AbstractFile
import Decorators.*
import ast.*
import ast.Trees.{LambdaTypeTree, TypeBoundsTree}
import Trees.Literal
import Variances.Variance
import annotation.tailrec
import util.SimpleIdentityMap
import util.Stats
import java.util.WeakHashMap
import scala.util.control.NonFatal
import config.Config
import reporting.*
import collection.mutable
import cc.{CapturingType, derivedCapturingType, stripCapturing}
import scala.annotation.internal.sharable
import scala.compiletime.uninitialized
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, name.isTypeName) {
//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 var myFlags: FlagSet = adaptFlags(initFlags)
private var myPrivateWithin: Symbol = initPrivateWithin
private var myAnnotations: List[Annotation] = Nil
private var myParamss: List[List[Symbol]] = Nil
/** The owner of the symbol; overridden in NoDenotation */
def owner: Symbol = maybeOwner
/** The flag set */
final def flags(using Context): FlagSet = { ensureCompleted(); myFlags }
/** The flag set without forcing symbol completion.
* Should be used only for printing.
*/
private[dotc] final def flagsUNSAFE: FlagSet = myFlags
final def flagsString(using Context): String = flags.flagsString
/** 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)
final def setStableConstructor()(using Context): Unit =
val ctorStable = if myFlags.is(Trait) then myFlags.is(NoInits) else isNoInitsRealClass
if ctorStable then primaryConstructor.setFlag(StableRealizable)
def isCurrent(fs: FlagSet)(using Context): Boolean =
def knownFlags(info: Type): FlagSet = info match
case _: SymbolLoader | _: ModuleCompleter => FromStartFlags
case _ => AfterLoadFlags
!myInfo.isInstanceOf[LazyType] || fs <= knownFlags(myInfo)
final def relevantFlagsFor(fs: FlagSet)(using Context) =
if (isCurrent(fs)) myFlags else flags
/** Has this denotation one of given flag set? */
final def is(flag: Flag)(using Context): Boolean =
(if (isCurrent(flag)) myFlags else flags).is(flag)
/** Has this denotation one of the flags in `fs` set? */
final def isOneOf(fs: FlagSet)(using Context): Boolean =
(if (isCurrent(fs)) myFlags else flags).isOneOf(fs)
/** Has this denotation the given flag set, whereas none of the flags
* in `butNot` are set?
*/
final def is(flag: Flag, butNot: FlagSet)(using Context): Boolean =
(if (isCurrent(flag) && isCurrent(butNot)) myFlags else flags).is(flag, butNot)
/** Has this denotation one of the flags in `fs` set, whereas none of the flags
* in `butNot` are set?
*/
final def isOneOf(fs: FlagSet, butNot: FlagSet)(using Context): Boolean =
(if (isCurrent(fs) && isCurrent(butNot)) myFlags else flags).isOneOf(fs, butNot)
/** Has this denotation all of the flags in `fs` set? */
final def isAllOf(fs: FlagSet)(using Context): Boolean =
(if (isCurrent(fs)) myFlags else flags).isAllOf(fs)
/** Has this denotation all of the flags in `fs` set, whereas none of the flags
* in `butNot` are set?
*/
final def isAllOf(fs: FlagSet, butNot: FlagSet)(using Context): Boolean =
(if (isCurrent(fs) && isCurrent(butNot)) myFlags else flags).isAllOf(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)(using Context): Unit =
if completer.needsCompletion(this) then
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 atPhase(validFor.firstPhaseId)(completer.complete(this))
catch {
case ex: CyclicReference =>
println(s"error while completing ${this.debugString}")
throw ex
}
finally {
indent -= 1
println(i"${" " * indent}completed $name in $owner")
}
}
else
CyclicReference.trace("compute the signature of ", symbol):
if myFlags.is(Touched) then
throw CyclicReference(this)(using ctx.withOwner(symbol))
myFlags |= Touched
atPhase(validFor.firstPhaseId)(completer.complete(this))
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(using Context): Name =
if (this.is(ModuleClass)) name.stripModuleClassSuffix
else name
/** The privateWithin boundary, NoSymbol if no boundary is given.
*/
@tailrec
final def privateWithin(using Context): Symbol = myInfo match {
case myInfo: ModuleCompleter =>
// Instead of completing the ModuleCompleter, we can get `privateWithin`
// directly from the module class, which might require less completions.
myInfo.moduleClass.privateWithin
case _: SymbolLoader =>
// Completing a SymbolLoader might call `setPrivateWithin()`
completeOnce()
privateWithin
case _ =>
// Otherwise, no completion is necessary, see the preconditions of `markAbsent()`.
myPrivateWithin
}
/** Set privateWithin, prefer setting it at symbol-creation time instead if
* possible.
* @pre `isCompleting` is false, or this is a ModuleCompleter or SymbolLoader
*/
protected[dotc] final def setPrivateWithin(pw: Symbol)(using Context): Unit = {
if (isCompleting)
assert(myInfo.isInstanceOf[ModuleCompleter | SymbolLoader],
s"Illegal call to `setPrivateWithin($pw)` while completing $this using completer $myInfo")
myPrivateWithin = pw
}
/** The annotations of this denotation */
final def annotations(using Context): List[Annotation] = {
ensureCompleted(); myAnnotations
}
/** The annotations without ensuring that the symbol is completed.
* Used for diagnostics where we don't want to force symbols.
*/
final def annotationsUNSAFE(using Context): List[Annotation] = 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)(using Context): Boolean =
dropOtherAnnotations(annotations, cls).nonEmpty
/** Apply transform `f` to all annotations of this denotation */
final def transformAnnotations(f: Annotation => Annotation)(using Context): Unit =
annotations = annotations.mapConserve(f)
/** Keep only those annotations that satisfy `p` */
final def filterAnnotations(p: Annotation => Boolean)(using Context): Unit =
annotations = annotations.filterConserve(p)
def annotationsCarrying(meta: Set[Symbol], orNoneOf: Set[Symbol] = Set.empty)(using Context): List[Annotation] =
annotations.filterConserve(_.hasOneOfMetaAnnotation(meta, orNoneOf = orNoneOf))
def keepAnnotationsCarrying(phase: DenotTransformer, meta: Set[Symbol], orNoneOf: Set[Symbol] = Set.empty)(using Context): Unit =
updateAnnotationsAfter(phase, annotationsCarrying(meta, orNoneOf = orNoneOf))
def updateAnnotationsAfter(phase: DenotTransformer, annots: List[Annotation])(using Context): Unit =
if annots ne annotations then
val cpy = copySymDenotation()
cpy.annotations = annots
cpy.installAfter(phase)
/** Optionally, the annotation matching the given class symbol */
final def getAnnotation(cls: Symbol)(using 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)(using 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
/** Add the given annotation without parameters to the annotations of this denotation */
final def addAnnotation(cls: ClassSymbol)(using Context): Unit =
addAnnotation(Annotation(cls, symbol.span))
/** Remove annotation with given class from this denotation */
final def removeAnnotation(cls: Symbol)(using Context): Unit =
annotations = myAnnotations.filterNot(_ matches cls)
/** Remove any annotations with same class as `annot`, and add `annot` */
final def updateAnnotation(annot: Annotation)(using Context): Unit = {
removeAnnotation(annot.symbol)
addAnnotation(annot)
}
/** Add all given annotations to this symbol */
final def addAnnotations(annots: IterableOnce[Annotation])(using Context): Unit =
annots.iterator.foreach(addAnnotation)
@tailrec
private def dropOtherAnnotations(anns: List[Annotation], cls: Symbol)(using Context): List[Annotation] = anns match {
case ann :: rest => if (ann matches cls) anns else dropOtherAnnotations(rest, cls)
case Nil => Nil
}
/** If this is a method, the parameter symbols, by section.
* Both type and value parameters are included. Empty sections are skipped.
*/
final def rawParamss: List[List[Symbol]] = myParamss
final def rawParamss_=(pss: List[List[Symbol]]): Unit =
myParamss = pss
final def setParamss(paramss: List[List[Symbol]])(using Context): Unit =
rawParamss = paramss.filterConserve(!_.isEmpty)
final def setParamssFromDefs(paramss: List[tpd.ParamClause])(using Context): Unit =
setParamss(paramss.map(_.map(_.symbol)))
/** The symbols of each type parameter list and value parameter list of this
* method, or Nil if this isn't a method.
*
* Makes use of `rawParamss` when present, or constructs fresh parameter symbols otherwise.
* This method can be allocation-heavy.
*/
final def paramSymss(using Context): List[List[Symbol]] =
def recurWithParamss(info: Type, paramss: List[List[Symbol]]): List[List[Symbol]] =
info match
case info: LambdaType =>
if info.paramNames.isEmpty then Nil :: recurWithParamss(info.resType, paramss)
else paramss.head :: recurWithParamss(info.resType, paramss.tail)
case _ =>
Nil
def recurWithoutParamss(info: Type): List[List[Symbol]] = info match
case info: LambdaType =>
val params = info.paramNames.lazyZip(info.paramInfos).map((pname, ptype) =>
newSymbol(symbol, pname, SyntheticParam, ptype))
val prefs = params.map(_.namedType)
for param <- params do
param.info = param.info.substParams(info, prefs)
params :: recurWithoutParamss(info.instantiate(prefs))
case _ =>
Nil
ensureCompleted()
if rawParamss.isEmpty then recurWithoutParamss(info)
else recurWithParamss(info, rawParamss)
end paramSymss
/** The extension parameter of this extension method
* @pre this symbol is an extension method
*/
final def extensionParam(using Context): Symbol =
def leadParam(paramss: List[List[Symbol]]): Symbol = paramss match
case (param :: _) :: paramss1 if param.isType => leadParam(paramss1)
case _ :: (snd :: Nil) :: _ if name.isRightAssocOperatorName => snd
case (fst :: Nil) :: _ => fst
case _ => NoSymbol
assert(isAllOf(ExtensionMethod))
ensureCompleted()
leadParam(rawParamss)
/** 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]
/** If this denotation is not completed, run the completer.
* The resulting info might be another completer.
*
* @see ensureCompleted
*/
final def completeOnce()(using Context): Unit = myInfo match {
case myInfo: LazyType =>
completeFrom(myInfo)
case _ =>
}
/** Make sure this denotation is fully completed.
*
* @see completeOnce
*/
final def ensureCompleted()(using 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(using Context): Scope = myInfo match {
case cinfo: LazyType =>
val knownDecls = cinfo.decls
if (knownDecls ne EmptyScope) knownDecls
else { completeOnce(); unforcedDecls }
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(using Context): MutableScope = myInfo match {
case pinfo: SymbolLoaders.PackageLoader => pinfo.currentDecls
case _ => unforcedDecls.openForMutations
}
/** If this is an opaque alias, replace the right hand side `info`
* by appropriate bounds and store `info` in the refinement of the
* self type of the enclosing class.
* Otherwise return `info`
*
* @param info Is assumed to be a (lambda-abstracted) right hand side TypeAlias
* of the opaque type definition.
* @param rhs The right hand side tree of the type definition
* @param tparams The type parameters with which the right-hand side bounds should be abstracted
*
*/
def opaqueToBounds(info: Type, rhs: tpd.Tree, tparams: List[TypeSymbol])(using Context): Type =
def setAlias(tp: Type) =
def recur(self: Type): Unit = self match
case RefinedType(parent, name, rinfo) => rinfo match
case TypeAlias(lzy: LazyRef) if name == this.name =>
if !lzy.completed then
lzy.update(tp)
else
throw CyclicReference(this)
case _ =>
recur(parent)
recur(owner.asClass.givenSelfType)
end setAlias
def bounds(t: tpd.Tree): TypeBounds = t match
case LambdaTypeTree(tparams, body) =>
bounds(body)
case TypeBoundsTree(lo, hi, alias) =>
assert(!alias.isEmpty)
TypeBounds(lo.tpe, hi.tpe)
case _ =>
TypeBounds.empty
info match
case info: AliasingBounds if isOpaqueAlias && owner.isClass =>
setAlias(info.alias)
HKTypeLambda.boundsFromParams(tparams, bounds(rhs))
case _ =>
info
end opaqueToBounds
// ------ Names ----------------------------------------------
/** The expanded name of this denotation. */
final def expandedName(using 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 effective name with which the denoting symbol was created */
final def originalName(using Context): Name = initial.effectiveName
/** The owner with which the denoting symbol was created. */
final def originalOwner(using Context): Symbol = initial.maybeOwner
/** 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)(using 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)(using 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) =
val qn = kind(prefix.toTermName, if (filler.isEmpty) n else termName(filler + n))
if kind == FlatName && !encl.is(JavaDefined) then qn.compactified else qn
val fn = name.replaceDeep {
case n: SimpleName => qualify(n)
}
if name.isTypeName then fn.toTypeName else fn.toTermName
}
/** The encoded flat name of this denotation, where joined names are separated by `separator` characters. */
def flatName(using Context): Name = fullNameSeparated(FlatName)
/** `fullName` where `.' is the separator character */
def fullName(using Context): Name = fullNameSeparated(QualifiedName)
/** The fully qualified name on the JVM of the class corresponding to this symbol. */
def binaryClassName(using Context): String =
val builder = new StringBuilder
val pkg = enclosingPackageClass
if !pkg.isEffectiveRoot then
builder.append(pkg.fullName.mangledString)
builder.append(".")
val flatName = this.flatName
// Some companion objects are fake (that is, they're a compiler fiction
// that doesn't correspond to a class that exists at runtime), this
// can happen in two cases:
// - If a Java class has static members.
// - If we create constructor proxies for a class (see NamerOps#addConstructorProxies).
//
// In both cases it's may be vital that we don't return the object name.
// For instance, sending it to zinc: when sbt is restarted, zinc will inspect the binary
// dependencies to see if they're still on the classpath, if it
// doesn't find them it will invalidate whatever referenced them, so
// any reference to a fake companion will lead to extra recompilations.
// Instead, use the class name since it's guaranteed to exist at runtime.
val clsFlatName = if isOneOf(JavaDefined | ConstructorProxy) then flatName.stripModuleClassSuffix else flatName
builder.append(clsFlatName.mangledString)
builder.toString
private var myTargetName: Name | Null = null
private def computeTargetName(targetNameAnnot: Option[Annotation])(using Context): Name =
targetNameAnnot match
case Some(ann) =>
ann.arguments match
case Literal(Constant(str: String)) :: Nil =>
if isType then
if is(ModuleClass) then str.toTypeName.moduleClassName
else str.toTypeName
else str.toTermName
case _ => name
case _ => name
def setTargetName(name: Name): Unit =
myTargetName = name
def hasTargetName(name: Name)(using Context): Boolean =
targetName.matchesTargetName(name)
/** The name given in a `@targetName` annotation if one is present, `name` otherwise */
def targetName(using Context): Name =
if myTargetName == null then
val carrier: SymDenotation =
if isAllOf(ModuleClass | Synthetic) then companionClass else this
val targetNameAnnot =
if carrier.isCompleting // annotations have been set already in this case
then carrier.unforcedAnnotation(defn.TargetNameAnnot)
else carrier.getAnnotation(defn.TargetNameAnnot)
myTargetName = computeTargetName(targetNameAnnot)
if name.is(SuperAccessorName) then
myTargetName = myTargetName.nn.unmangle(List(ExpandedName, SuperAccessorName, ExpandPrefixName))
myTargetName.nn
// ----- Tests -------------------------------------------------
/** Is this denotation a class? */
final def isClass: Boolean = isInstanceOf[ClassDenotation]
/** Is this denotation a non-trait class? */
final def isRealClass(using 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.
* @pre `isCompleting` is false, or this is a ModuleCompleter or SymbolLoader
*/
final def markAbsent()(using Context): Unit = {
if (isCompleting)
assert(myInfo.isInstanceOf[ModuleCompleter | SymbolLoader],
s"Illegal call to `markAbsent()` while completing $this using completer $myInfo")
myInfo = NoType
}
/** Is symbol known to not exist?
* @param canForce If this is true, the info may be forced to avoid a false-negative result
*/
@tailrec
final def isAbsent(canForce: Boolean = true)(using Context): Boolean = myInfo match {
case myInfo: ModuleCompleter =>
// Instead of completing the ModuleCompleter, we can check whether
// the module class is absent, which might require less completions.
myInfo.moduleClass.isAbsent(canForce)
case _: SymbolLoader if canForce =>
// Completing a SymbolLoader might call `markAbsent()`
completeOnce()
isAbsent(canForce)
case _ =>
// Otherwise, no completion is necessary, see the preconditions of `markAbsent()`.
(myInfo `eq` NoType)
|| is(Invisible) && ctx.isTyper
|| is(ModuleVal, butNot = Package) && moduleClass.isAbsent(canForce)
}
/** 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(using Context): Boolean =
name.toTermName == nme.EMPTY_PACKAGE && owner.isRoot
/** Is this symbol the empty package class or its companion object? */
final def isEffectiveRoot(using Context): Boolean = isRoot || isEmptyPackage
/** Is this symbol an anonymous class? */
final def isAnonymousClass(using Context): Boolean =
isClass && initial.name.isAnonymousClassName
final def isAnonymousFunction(using Context): Boolean =
this.symbol.is(Method) && initial.name.isAnonymousFunctionName
final def isAnonymousModuleVal(using Context): Boolean =
this.symbol.is(ModuleVal) && initial.name.isAnonymousClassName
/** 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(using Context): Boolean =
name.toTermName == nme.U2EVT ||
name.toTermName == nme.EVT2U
/** Is symbol a primitive value class? */
def isPrimitiveValueClass(using Context): Boolean =
maybeOwner == defn.ScalaPackageClass && defn.ScalaValueClasses().contains(symbol)
/** Is symbol a primitive numeric value class? */
def isNumericValueClass(using Context): Boolean =
maybeOwner == defn.ScalaPackageClass && defn.ScalaNumericValueClasses().contains(symbol)
/** Is symbol a class for which no runtime representation exists? */
def isNotRuntimeClass(using 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(using Context): Boolean =
name == tpnme.REFINE_CLASS
/** Is this symbol a package object or its module class? */
def isPackageObject(using Context): Boolean =
name.isPackageObjectName && owner.is(Package) && this.is(Module)
/** Is this symbol a package object containing top-level definitions? */
def isTopLevelDefinitionsObject(using Context): Boolean =
name.isTopLevelPackageObjectName && owner.is(Package) && this.is(Module)
/** Is this symbol a toplevel definition in a package object? */
def isWrappedToplevelDef(using Context): Boolean =
!isConstructor && owner.isPackageObject
/** Is this symbol an alias type? */
final def isAliasType(using Context): Boolean =
isAbstractOrAliasType && !isAbstractOrParamType
/** 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(using Context): Boolean = this.isOneOf(DeferredOrTypeParam)
/** Is this symbol a user-defined opaque alias type? */
def isOpaqueAlias(using Context): Boolean = is(Opaque) && !isClass
/** Is this symbol a module that contains opaque aliases? */
def containsOpaques(using Context): Boolean = is(Opaque) && isClass
def seesOpaques(using Context): Boolean =
containsOpaques ||
is(Module, butNot = Package) && owner.seesOpaques
def isProvisional(using Context): Boolean =
flagsUNSAFE.is(Provisional) // do not force the info to check the flag
/** 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(using Context): Boolean =
if !ctx.isBestEffort || exists then
owner.infoOrCompleter match {
case ClassInfo(_, _, _, _, selfInfo) =>
selfInfo == symbol ||
selfInfo.isInstanceOf[Type] && name == nme.WILDCARD
case _ => false
}
else false
/** Is this definition contained in `boundary`?
* Same as `ownersIterator contains boundary` but more efficient.
*/
final def isContainedIn(boundary: Symbol)(using 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)(using Context): Boolean =
symbol != boundary && isContainedIn(boundary)
/** Is this denotation static (i.e. with no outer instance)? */
final def isStatic(using 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(using 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)(using Context): Boolean =
(this.effectiveOwner == other.effectiveOwner) &&
( !this.effectiveOwner.is(PackageClass)
|| this.isAbsent(canForce = false) || other.isAbsent(canForce = false)
|| { // 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
)
}
)
/** Do this symbol and `cls` represent a pair of a given or implicit method and
* its associated class that were defined by a single definition?
* This can mean one of two things:
* - the method and class are defined in a structural given instance, or
* - the class is an implicit class and the method is its implicit conversion.
*/
final def isCoDefinedGiven(cls: Symbol)(using Context): Boolean =
is(Method) && isOneOf(GivenOrImplicit)
&& ( is(Synthetic) // previous scheme used in 3.0
|| cls.isOneOf(GivenOrImplicit) // new scheme from 3.1
)
&& name == cls.name.toTermName && owner == cls.owner
/** Is this a denotation of a stable term (or an arbitrary type)?
* Terms are stable if they are idempotent (as in TreeInfo.Idempotent): that is, they always return the same value,
* if any.
*
* A *member* is stable, basically, if it behaves like a field projection: that is, it projects a constant result
* out of its owner.
*
* However, a stable member might not yet be initialized (if it is an object or anyhow lazy).
* So the first call to a stable member might fail and/or produce side effects.
*/
final def isStableMember(using Context): Boolean = {
def isUnstableValue = isOneOf(UnstableValueFlags) || info.isInstanceOf[ExprType] || isAllOf(InlineParam)
isType || is(StableRealizable) || exists && !isUnstableValue
}
/** Is this a denotation of a real class that does not have - either direct or inherited -
* initialization code?
*/
def isNoInitsRealClass(using Context): Boolean =
isRealClass &&
(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(using Context): Boolean =
this.is(Method, butNot = Accessor) && !isAnonymousFunction
/** Is this a getter? */
final def isGetter(using Context): Boolean =
this.is(Accessor) && !originalName.isSetterName && !(originalName.isScala2LocalSuffix && symbol.owner.is(Scala2x))
/** Is this a setter? */
final def isSetter(using 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 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(using Context): Boolean =
isConstructor && owner.primaryConstructor == symbol
/** Does this symbol denote the static constructor of its enclosing class? */
final def isStaticConstructor(using Context): Boolean =
name.isStaticConstructorName
/** Is this a subclass of the given class `base`? */
def isSubClass(base: Symbol)(using 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)(using Context): Boolean = false
/** Is this a Scala or Java annotation ? */
def isAnnotation(using Context): Boolean =
isClass && (derivesFrom(defn.AnnotationClass) || is(JavaAnnotation))
/** Is this symbol a class that extends `java.io.Serializable` ? */
def isSerializable(using Context): Boolean =
isClass && derivesFrom(defn.JavaSerializableClass)
/** Is this symbol a class that extends `AnyVal`? Overridden in ClassDenotation */
def isValueClass(using Context): Boolean = false
/** Is this symbol a class of which `null` is a value? */
final def isNullableClass(using Context): Boolean =
if ctx.mode.is(Mode.SafeNulls) && !ctx.phase.erasedTypes
then symbol == defn.NullClass || symbol == defn.AnyClass || symbol == defn.MatchableClass
else isNullableClassAfterErasure
/** Is this symbol a class of which `null` is a value after erasure?
* For example, if `-Yexplicit-nulls` is set, `String` is not nullable before erasure,
* but it becomes nullable after erasure.
*/
final def isNullableClassAfterErasure(using Context): Boolean =
isClass && !isValueClass && !is(ModuleClass) && symbol != defn.NothingClass
/** Is `pre` the same as C.this, where C is exactly the owner of this symbol,
* or, if this symbol is protected, a subclass of the owner?
*/
def isAccessPrivilegedThisType(pre: Type)(using Context): 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 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.
*
* As a side effect, drop Local flags of members that are not accessed via the ThisType
* of their owner.
*/
final def isAccessibleFrom(pre: Type, superAccess: Boolean = false)(using Context): Boolean = {
/** Are we inside definition of `boundary`?
* If this symbol is Java defined, package structure is interpreted to be flat.
*/
def accessWithin(boundary: Symbol) =
ctx.owner.isContainedIn(boundary)
&& !(is(JavaDefined) && boundary.is(PackageClass) && ctx.owner.enclosingPackageClass != boundary)
/** Are we within definition of linked class of `boundary`? */
def accessWithinLinked(boundary: Symbol) = {
val linked = boundary.linkedClass
(linked ne NoSymbol) && accessWithin(linked)
}
/** Is protected access to target symbol permitted? */
def isProtectedAccessOK: Boolean =
val cls = owner.enclosingSubClass
if !cls.exists then
pre.termSymbol.isPackageObject && accessWithin(pre.termSymbol.owner)
else
// allow accesses to types from arbitrary subclasses fixes #4737
// don't perform this check for static members
isType || pre.derivesFrom(cls) || isConstructor || owner.is(ModuleClass)
end isProtectedAccessOK
if pre eq NoPrefix then true
else if isAbsent() then false
else {
val boundary = accessBoundary(owner)
( boundary.isTerm
|| boundary.isRoot
|| (accessWithin(boundary) || accessWithinLinked(boundary)) &&
( !this.is(Local)
|| isAccessPrivilegedThisType(pre)
|| canBeLocal(name, flags)
&& {
resetFlag(Local)
true
}
)
|| 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)(using Context): Boolean =
def preIsThis = pre match
case pre: ThisType => pre.sameThis(thisType)
case _ => false
!( this.isTerm
|| this.isStaticOwner && !this.seesOpaques
|| ctx.erasedTypes
|| (pre eq NoPrefix)
|| preIsThis
)
/** Is this symbol concrete, or that symbol deferred? */
def isAsConcrete(that: Symbol)(using Context): Boolean =
!this.is(Deferred) || that.is(Deferred)
/** Does this symbol have defined or inherited default parameters?
* Default parameters are recognized until erasure.
*/
def hasDefaultParams(using Context): Boolean =
if ctx.erasedTypes then false
else if is(HasDefaultParams) then true
else if is(NoDefaultParams) || !is(Method) then false
else
val result =
rawParamss.nestedExists(_.is(HasDefault))
|| allOverriddenSymbols.exists(_.hasDefaultParams)
setFlag(if result then HasDefaultParams else NoDefaultParams)
result
/** Symbol is an owner that would be skipped by effectiveOwner. Skipped are
* - package objects
* - non-lazy valdefs
*/
def isWeakOwner(using Context): Boolean =
isPackageObject ||
isTerm && !isOneOf(MethodOrLazy) && !isLocalDummy
def isSkolem: Boolean = name == nme.SKOLEM
// Java language spec: https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12.3
// Scala 2 spec: https://scala-lang.org/files/archive/spec/2.13/06-expressions.html#signature-polymorphic-methods
def isSignaturePolymorphic(using Context): Boolean =
containsSignaturePolymorphic
&& is(JavaDefined)
&& hasAnnotation(defn.NativeAnnot)
&& atPhase(typerPhase)(symbol.denot).paramSymss.match
case List(List(p)) => p.info.isRepeatedParam
case _ => false
def containsSignaturePolymorphic(using Context): Boolean =
maybeOwner == defn.MethodHandleClass
|| maybeOwner == defn.VarHandleClass