-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Namer.scala
1907 lines (1722 loc) · 83.9 KB
/
Namer.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 typer
import core._
import ast._
import Trees._, StdNames._, Scopes._, Denotations._, NamerOps._, ContextOps._
import Contexts._, Symbols._, Types._, SymDenotations._, Names._, NameOps._, Flags._
import Decorators._, Comments.{_, given}
import NameKinds.DefaultGetterName
import ast.desugar, ast.desugar._
import ProtoTypes._
import util.Spans._
import util.Property
import collection.mutable
import tpd.tpes
import Variances.alwaysInvariant
import config.{Config, Feature}
import config.Printers.typr
import parsing.JavaParsers.JavaParser
import parsing.Parsers.Parser
import Annotations._
import Inferencing._
import transform.ValueClasses._
import transform.TypeUtils._
import transform.SymUtils._
import TypeErasure.erasure
import reporting._
import config.Feature.sourceVersion
import config.SourceVersion._
/** This class creates symbols from definitions and imports and gives them
* lazy types.
*
* Timeline:
*
* During enter, trees are expanded as necessary, populating the expandedTree map.
* Symbols are created, and the symOfTree map is set up.
*
* Symbol completion causes some trees to be already typechecked and typedTree
* entries are created to associate the typed trees with the untyped expanded originals.
*
* During typer, original trees are first expanded using expandedTree. For each
* expanded member definition or import we extract and remove the corresponding symbol
* from the symOfTree map and complete it. We then consult the typedTree map to see
* whether a typed tree exists already. If yes, the typed tree is returned as result.
* Otherwise, we proceed with regular type checking.
*
* The scheme is designed to allow sharing of nodes, as long as each duplicate appears
* in a different method.
*/
class Namer { typer: Typer =>
import untpd._
val TypedAhead : Property.Key[tpd.Tree] = new Property.Key
val ExpandedTree : Property.Key[untpd.Tree] = new Property.Key
val ExportForwarders: Property.Key[List[tpd.MemberDef]] = new Property.Key
val SymOfTree : Property.Key[Symbol] = new Property.Key
val AttachedDeriver : Property.Key[Deriver] = new Property.Key
// was `val Deriver`, but that gave shadowing problems with constructor proxies
/** A partial map from unexpanded member and pattern defs and to their expansions.
* Populated during enterSyms, emptied during typer.
*/
//lazy val expandedTree = new mutable.AnyRefMap[DefTree, Tree]
/*{
override def default(tree: DefTree) = tree // can't have defaults on AnyRefMaps :-(
}*/
/** A map from expanded MemberDef, PatDef or Import trees to their symbols.
* Populated during enterSyms, emptied at the point a typed tree
* with the same symbol is created (this can be when the symbol is completed
* or at the latest when the tree is typechecked.
*/
//lazy val symOfTree = new mutable.AnyRefMap[Tree, Symbol]
/** A map from expanded trees to their typed versions.
* Populated when trees are typechecked during completion (using method typedAhead).
*/
// lazy val typedTree = new mutable.AnyRefMap[Tree, tpd.Tree]
/** A map from method symbols to nested typers.
* Populated when methods are completed. Emptied when they are typechecked.
* The nested typer contains new versions of the four maps above including this
* one, so that trees that are shared between different DefDefs can be independently
* used as indices. It also contains a scope that contains nested parameters.
*/
lazy val nestedTyper: mutable.AnyRefMap[Symbol, Typer] = new mutable.AnyRefMap
/** We are entering symbols coming from a SourceLoader */
private var lateCompile = false
/** The symbol of the given expanded tree. */
def symbolOfTree(tree: Tree)(using Context): Symbol = {
val xtree = expanded(tree)
xtree.getAttachment(TypedAhead) match {
case Some(ttree) => ttree.symbol
case none =>
xtree.getAttachment(SymOfTree) match
case Some(sym) => sym
case _ => throw IllegalArgumentException(i"$xtree does not have a symbol")
}
}
def hasDefinedSymbol(tree: Tree)(using Context): Boolean =
val xtree = expanded(tree)
xtree.hasAttachment(TypedAhead) || xtree.hasAttachment(SymOfTree)
/** The enclosing class with given name; error if none exists */
def enclosingClassNamed(name: TypeName, span: Span)(using Context): Symbol =
if (name.isEmpty) NoSymbol
else {
val cls = ctx.owner.enclosingClassNamed(name)
if (!cls.exists)
report.error(UnknownNamedEnclosingClassOrObject(name), ctx.source.atSpan(span))
cls
}
/** Record `sym` as the symbol defined by `tree` */
def recordSym(sym: Symbol, tree: Tree)(using Context): Symbol = {
for (refs <- tree.removeAttachment(References); ref <- refs) ref.watching(sym)
tree.pushAttachment(SymOfTree, sym)
sym
}
/** Check that a new definition with given name and privacy status
* in current context would not conflict with existing currently
* compiled definitions.
* The logic here is very subtle and fragile due to the fact that
* we are not allowed to force anything.
*/
def checkNoConflict(name: Name, isPrivate: Boolean, span: Span)(using Context): Name =
val owner = ctx.owner
var conflictsDetected = false
def conflict(conflicting: Symbol) =
val other =
if conflicting.is(ConstructorProxy) then conflicting.companionClass
else conflicting
report.error(AlreadyDefined(name, owner, other), ctx.source.atSpan(span))
conflictsDetected = true
def checkNoConflictIn(owner: Symbol) =
val preExisting = owner.unforcedDecls.lookup(name)
if (preExisting.isDefinedInCurrentRun || preExisting.lastKnownDenotation.is(Package))
&& (!preExisting.lastKnownDenotation.is(Private) || preExisting.owner.is(Package))
&& (!preExisting.lastKnownDenotation.isPackageObject
|| preExisting.associatedFile != ctx.source.file)
// isDefinedInCurrentRun does not work correctly for package objects, because
// package objects are updated to the new run earlier than normal classes, everytime
// some member of the enclosing package is accessed. Therefore, we use another
// test: conflict if package objects have the same name but come from different
// sources. See i9252.
then conflict(preExisting)
def pkgObjs(pkg: Symbol) =
pkg.denot.asInstanceOf[PackageClassDenotation].packageObjs.map(_.symbol)
if owner.is(PackageClass) then
checkNoConflictIn(owner)
for pkgObj <- pkgObjs(owner) do
checkNoConflictIn(pkgObj)
else
def preExisting = ctx.effectiveScope.lookup(name)
if (!owner.isClass || name.isTypeName) && preExisting.exists then
conflict(preExisting)
else if owner.isPackageObject && !isPrivate && name != nme.CONSTRUCTOR then
checkNoConflictIn(owner.owner)
for pkgObj <- pkgObjs(owner.owner) if pkgObj != owner do
checkNoConflictIn(pkgObj)
if conflictsDetected then name.freshened else name
end checkNoConflict
/** If this tree is a member def or an import, create a symbol of it
* and store in symOfTree map.
*/
def createSymbol(tree: Tree)(using Context): Symbol = {
def privateWithinClass(mods: Modifiers) =
enclosingClassNamed(mods.privateWithin, tree.span)
/** Check that flags are OK for symbol. This is done early to avoid
* catastrophic failure when we create a TermSymbol with TypeFlags, or vice versa.
* A more complete check is done in checkWellFormed.
* Also, speculatively add a Local flag to private members that can be Local if
* referred to exclusively from their owner's this-type. The Local flag is retracted in
* `isAccessibleFrom` if the access not from such a this-type.
*/
def checkFlags(flags: FlagSet) =
if (flags.isEmpty) flags
else {
val (ok, adapted, kind) = tree match {
case tree: TypeDef => (flags.isTypeFlags, flags.toTypeFlags, "type")
case _ => (flags.isTermFlags, flags.toTermFlags, "value")
}
def canBeLocal = tree match
case tree: MemberDef => SymDenotations.canBeLocal(tree.name, flags)
case _ => false
if !ok then
report.error(i"modifier(s) `${flags.flagsString}` incompatible with $kind definition", tree.srcPos)
if adapted.is(Private) && canBeLocal then adapted | Local else adapted
}
/** Add moduleClass/sourceModule to completer if it is for a module val or class */
def adjustIfModule(completer: LazyType, tree: MemberDef) =
if (tree.mods.is(Module)) adjustModuleCompleter(completer, tree.name)
else completer
typr.println(i"creating symbol for $tree in ${ctx.mode}")
/** Create new symbol or redefine existing symbol under lateCompile. */
def createOrRefine[S <: Symbol](
tree: MemberDef, name: Name, flags: FlagSet, owner: Symbol, infoFn: S => Type,
symFn: (FlagSet, S => Type, Symbol) => S): Symbol = {
val prev =
if (lateCompile && ctx.owner.is(Package)) ctx.effectiveScope.lookup(name)
else NoSymbol
var flags1 = flags
var privateWithin = privateWithinClass(tree.mods)
val effectiveOwner = owner.skipWeakOwner
if (flags.is(Private) && effectiveOwner.is(Package)) {
// If effective owner is a package p, widen private to private[p]
flags1 = flags1 &~ PrivateLocal
privateWithin = effectiveOwner
}
val sym =
if (prev.exists) {
prev.flags = flags1
prev.info = infoFn(prev.asInstanceOf[S])
prev.setPrivateWithin(privateWithin)
prev
}
else symFn(flags1, infoFn, privateWithin)
recordSym(sym, tree)
}
tree match {
case tree: TypeDef if tree.isClassDef =>
val flags = checkFlags(tree.mods.flags)
val name = checkNoConflict(tree.name, flags.is(Private), tree.span).asTypeName
val cls =
createOrRefine[ClassSymbol](tree, name, flags, ctx.owner,
cls => adjustIfModule(new ClassCompleter(cls, tree)(ctx), tree),
newClassSymbol(ctx.owner, name, _, _, _, tree.nameSpan, ctx.source.file))
cls.completer.asInstanceOf[ClassCompleter].init()
cls
case tree: MemberDef =>
var flags = checkFlags(tree.mods.flags)
val name = checkNoConflict(tree.name, flags.is(Private), tree.span)
tree match
case tree: ValOrDefDef =>
if tree.isInstanceOf[ValDef] && !flags.is(Param) && name.endsWith("_=") then
report.error("Names of vals or vars may not end in `_=`", tree.namePos)
if tree.unforcedRhs == EmptyTree
&& !flags.isOneOf(TermParamOrAccessor)
&& !tree.name.isConstructorName
then
flags |= Deferred
if (tree.isInstanceOf[DefDef]) flags |= Method
else if flags.isAllOf(EnumValue) && ctx.owner.isStaticOwner then flags |= JavaStatic
case tree: TypeDef =>
def analyzeRHS(rhs: Tree): Unit = rhs match
case _: TypeBoundsTree | _: MatchTypeTree =>
flags |= Deferred // Typedefs with Match rhs classify as abstract
case LambdaTypeTree(_, body) =>
analyzeRHS(body)
case _ =>
if rhs.isEmpty || flags.is(Opaque) then flags |= Deferred
analyzeRHS(tree.rhs)
// to complete a constructor, move one context further out -- this
// is the context enclosing the class. Note that the context in which a
// constructor is recorded and the context in which it is completed are
// different: The former must have the class as owner (because the
// constructor is owned by the class), the latter must not (because
// constructor parameters are interpreted as if they are outside the class).
// Don't do this for Java constructors because they need to see the import
// of the companion object, and it is not necessary for them because they
// have no implementation.
val cctx = if (tree.name == nme.CONSTRUCTOR && !flags.is(JavaDefined)) ctx.outer else ctx
val completer = tree match
case tree: TypeDef => TypeDefCompleter(tree)(cctx)
case _ => Completer(tree)(cctx)
val info = adjustIfModule(completer, tree)
createOrRefine[Symbol](tree, name, flags, ctx.owner, _ => info,
(fs, _, pwithin) => newSymbol(ctx.owner, name, fs, info, pwithin, tree.nameSpan))
case tree: Import =>
recordSym(newImportSymbol(ctx.owner, Completer(tree)(ctx), tree.span), tree)
case _ =>
NoSymbol
}
}
/** If `sym` exists, enter it in effective scope. Check that
* package members are not entered twice in the same run.
*/
def enterSymbol(sym: Symbol)(using Context): Unit =
// We do not enter Scala 2 macros defined in Scala 3 as they have an equivalent Scala 3 inline method.
if sym.exists && !sym.isScala2MacroInScala3 then
typr.println(s"entered: $sym in ${ctx.owner}")
ctx.enter(sym)
/** Create package if it does not yet exist. */
private def createPackageSymbol(pid: RefTree)(using Context): Symbol = {
val pkgOwner = pid match {
case Ident(_) => if (ctx.owner eq defn.EmptyPackageClass) defn.RootClass else ctx.owner
case Select(qual: RefTree, _) => createPackageSymbol(qual).moduleClass
}
val existing = pkgOwner.info.decls.lookup(pid.name)
if (existing.is(Package) && (pkgOwner eq existing.owner)) {
existing.moduleClass.denot match {
case d: PackageClassDenotation =>
// Remove existing members coming from a previous compilation of this file,
// they are obsolete.
d.unlinkFromFile(ctx.source.file)
case _ =>
}
existing
}
else {
/** If there's already an existing type, then the package is a dup of this type */
val existingType = pkgOwner.info.decls.lookup(pid.name.toTypeName)
if (existingType.exists) {
report.error(PkgDuplicateSymbol(existingType), pid.srcPos)
newCompletePackageSymbol(pkgOwner, (pid.name ++ "$_error_").toTermName).entered
}
else newCompletePackageSymbol(pkgOwner, pid.name.asTermName).entered
}
}
/** Expand tree and store in `expandedTree` */
def expand(tree: Tree)(using Context): Unit = {
def record(expanded: Tree) =
if (expanded `ne` tree) {
typr.println(i"Expansion: $tree expands to $expanded")
tree.pushAttachment(ExpandedTree, expanded)
}
tree match {
case tree: DefTree => record(desugar.defTree(tree))
case tree: PackageDef => record(desugar.packageDef(tree))
case tree: ExtMethods => record(desugar.extMethods(tree))
case _ =>
}
}
/** The expanded version of this tree, or tree itself if not expanded */
def expanded(tree: Tree)(using Context): Tree = tree match {
case _: DefTree | _: PackageDef | _: ExtMethods => tree.attachmentOrElse(ExpandedTree, tree)
case _ => tree
}
/** For all class definitions `stat` in `xstats`: If the companion class is
* not also defined in `xstats`, invalidate it by setting its info to
* NoType.
*/
def invalidateCompanions(pkg: Symbol, xstats: List[untpd.Tree])(using Context): Unit = {
val definedNames = xstats collect { case stat: NameTree => stat.name }
def invalidate(name: TypeName) =
if (!(definedNames contains name)) {
val member = pkg.info.decl(name).asSymDenotation
if (member.isClass && !(member.is(Package))) member.markAbsent()
}
xstats foreach {
case stat: TypeDef if stat.isClassDef =>
invalidate(stat.name.moduleClassName)
case _ =>
}
}
/** Expand tree and create top-level symbols for statement and enter them into symbol table */
def index(stat: Tree)(using Context): Context = {
expand(stat)
indexExpanded(stat)
}
/** Create top-level symbols for all statements in the expansion of this statement and
* enter them into symbol table
*/
def indexExpanded(origStat: Tree)(using Context): Context = {
def recur(stat: Tree): Context = stat match {
case pcl: PackageDef =>
val pkg = createPackageSymbol(pcl.pid)
index(pcl.stats)(using ctx.fresh.setOwner(pkg.moduleClass))
invalidateCompanions(pkg, Trees.flatten(pcl.stats map expanded))
setDocstring(pkg, stat)
ctx
case imp: Import =>
ctx.importContext(imp, createSymbol(imp))
case mdef: DefTree =>
val sym = createSymbol(mdef)
enterSymbol(sym)
setDocstring(sym, origStat)
addEnumConstants(mdef, sym)
ctx
case stats: Thicket =>
stats.toList.foreach(recur)
ctx
case _ =>
ctx
}
recur(expanded(origStat))
}
/** Determines whether this field holds an enum constant. */
def isEnumConstant(vd: ValDef)(using Context): Boolean =
vd.mods.isAllOf(JavaEnumValue)
/** Ensure that the first type in a list of parent types Ps points to a non-trait class.
* If that's not already the case, add one. The added class type CT is determined as follows.
* First, let C be the unique class such that
* - there is a parent P_i such that P_i derives from C, and
* - for every class D: If some parent P_j, j <= i derives from D, then C derives from D.
* Then, let CT be the smallest type which
* - has C as its class symbol, and
* - for all parents P_i: If P_i derives from C then P_i <:< CT.
*
* Tweak: It could be that at the point where the method is called, some superclass
* is still missing its parents. Parents are set to Nil when completion starts and are
* set to the actual parents later. If a superclass completes a subclass in one
* of its parents, the parents of the superclass or some intervening class might
* not yet be set. This situation can be detected by asking for the baseType of Any -
* if that type does not exist, one of the base classes of this class misses its parents.
* If this situation arises, the computation of the superclass might be imprecise.
* For instance, in i12722.scala, the superclass of `IPersonalCoinOps` is computed
* as `Object`, where `JsObject` would be correct. The problem cannot be solved locally,
* but we detect the situaton and mark the superclass with a `@ProvisionalSuperClass`
* annotation in this case. When typechecking the class, we then run ensureFirstIsClass
* again and possibly improve the computed super class.
* An alternatiev fix would compute superclasses at typer instead at completion. But
* that breaks too many invariants. For instance, we rely on correct @Child annotations
* after completion, and these in turn need the superclass.
*/
def ensureFirstIsClass(cls: ClassSymbol, parents: List[Type])(using Context): List[Type] =
def realClassParent(sym: Symbol): ClassSymbol =
if !sym.isClass then defn.ObjectClass
else if !sym.is(Trait) then sym.asClass
else sym.info.parents match
case parentRef :: _ => realClassParent(parentRef.typeSymbol)
case nil => defn.ObjectClass
def improve(candidate: ClassSymbol, parent: Type): ClassSymbol =
val pcls = realClassParent(parent.classSymbol)
if (pcls derivesFrom candidate) pcls else candidate
parents match
case p :: _ if p.classSymbol.isRealClass => parents
case _ =>
val pcls = parents.foldLeft(defn.ObjectClass)(improve)
typr.println(i"ensure first is class $parents%, % --> ${parents map (_ baseType pcls)}%, %")
val bases = parents.map(_.baseType(pcls))
var first = TypeComparer.glb(defn.ObjectType :: bases)
val isProvisional = parents.exists(!_.baseType(defn.AnyClass).exists)
if isProvisional then
typr.println(i"provisional superclass $first for $cls")
first = AnnotatedType(first, Annotation(defn.ProvisionalSuperClassAnnot))
checkFeasibleParent(first, cls.srcPos, em" in inferred superclass $first") :: parents
end ensureFirstIsClass
/** Add child annotation for `child` to annotations of `cls`. The annotation
* is added at the correct insertion point, so that Child annotations appear
* in reverse order of their start positions.
* @pre `child` must have a position.
*/
final def addChild(cls: Symbol, child: Symbol)(using Context): Unit = {
val childStart = if (child.span.exists) child.span.start else -1
def insertInto(annots: List[Annotation]): List[Annotation] =
annots.find(_.symbol == defn.ChildAnnot) match {
case Some(Annotation.Child(other)) if other.span.exists && childStart <= other.span.start =>
if (child == other)
annots // can happen if a class has several inaccessible children
else {
assert(childStart != other.span.start, i"duplicate child annotation $child / $other")
val (prefix, otherAnnot :: rest) = annots.span(_.symbol != defn.ChildAnnot): @unchecked
prefix ::: otherAnnot :: insertInto(rest)
}
case _ =>
Annotation.Child(child, cls.span.startPos) :: annots
}
cls.annotations = insertInto(cls.annotations)
}
/** Add java enum constants */
def addEnumConstants(mdef: DefTree, sym: Symbol)(using Context): Unit = mdef match {
case vdef: ValDef if (isEnumConstant(vdef)) =>
val enumClass = sym.owner.linkedClass
if (!enumClass.is(Sealed)) enumClass.setFlag(Flags.AbstractSealed)
addChild(enumClass, sym)
case _ =>
}
def setDocstring(sym: Symbol, tree: Tree)(using Context): Unit = tree match {
case t: MemberDef if t.rawComment.isDefined =>
ctx.docCtx.foreach(_.addDocstring(sym, t.rawComment))
case t: ExtMethods =>
for meth <- t.methods.find(_.span.point == sym.span.point) do
setDocstring(sym, meth)
case _ => ()
}
/** Create top-level symbols for statements and enter them into symbol table
* @return A context that reflects all imports in `stats`.
*/
def index(stats: List[Tree])(using Context): Context = {
// module name -> (stat, moduleCls | moduleVal)
val moduleClsDef = mutable.Map[TypeName, (Tree, TypeDef)]()
val moduleValDef = mutable.Map[TermName, (Tree, ValDef)]()
/** Remove the subtree `tree` from the expanded tree of `mdef` */
def removeInExpanded(mdef: Tree, tree: Tree): Unit = {
val Thicket(trees) = expanded(mdef): @unchecked
mdef.putAttachment(ExpandedTree, Thicket(trees.filter(_ != tree)))
}
/** Transfer all references to `from` to `to` */
def transferReferences(from: ValDef, to: ValDef): Unit = {
val fromRefs = from.removeAttachment(References).getOrElse(Nil)
val toRefs = to.removeAttachment(References).getOrElse(Nil)
to.putAttachment(References, fromRefs ++ toRefs)
}
/** Merge the module class `modCls` in the expanded tree of `mdef` with the
* body and derived clause of the synthetic module class `fromCls`.
*/
def mergeModuleClass(mdef: Tree, modCls: TypeDef, fromCls: TypeDef): TypeDef = {
var res: TypeDef | Null = null
val Thicket(trees) = expanded(mdef): @unchecked
val merged = trees.map { tree =>
if (tree == modCls) {
val fromTempl = fromCls.rhs.asInstanceOf[Template]
val modTempl = modCls.rhs.asInstanceOf[Template]
res = cpy.TypeDef(modCls)(
rhs = cpy.Template(modTempl)(
derived = if (fromTempl.derived.nonEmpty) fromTempl.derived else modTempl.derived,
body = fromTempl.body ++ modTempl.body))
if (fromTempl.derived.nonEmpty) {
if (modTempl.derived.nonEmpty)
report.error(em"a class and its companion cannot both have `derives` clauses", mdef.srcPos)
// `res` is inside a closure, so the flow-typing doesn't work here.
res.uncheckedNN.putAttachment(desugar.DerivingCompanion, fromTempl.srcPos.startPos)
}
res.uncheckedNN
}
else tree
}
mdef.putAttachment(ExpandedTree, Thicket(merged))
res.nn
}
/** Merge `fromCls` of `fromStat` into `toCls` of `toStat`
* if the former is synthetic and the latter not.
*
* Note:
* 1. `fromStat` and `toStat` could be the same stat
* 2. `fromCls` and `toCls` are necessarily different
*/
def mergeIfSynthetic(fromStat: Tree, fromCls: TypeDef, toStat: Tree, toCls: TypeDef): Unit =
if (fromCls.mods.is(Synthetic) && !toCls.mods.is(Synthetic)) {
removeInExpanded(fromStat, fromCls)
val mcls = mergeModuleClass(toStat, toCls, fromCls)
mcls.setMods(toCls.mods)
moduleClsDef(fromCls.name) = (toStat, mcls)
}
/** Merge the definitions of a synthetic companion generated by a case class
* and the real companion, if both exist.
*/
def mergeCompanionDefs() = {
def valid(mdef: MemberDef): Boolean = mdef.mods.is(Module, butNot = Package)
for (stat <- stats)
expanded(stat) match {
case Thicket(trees) => // companion object always expands to thickets
trees.map {
case mcls @ TypeDef(name, impl: Template) if valid(mcls) =>
(moduleClsDef.get(name): @unchecked) match {
case Some((stat1, mcls1@TypeDef(_, impl1: Template))) =>
mergeIfSynthetic(stat, mcls, stat1, mcls1)
mergeIfSynthetic(stat1, mcls1, stat, mcls)
case None =>
moduleClsDef(name) = (stat, mcls)
}
case vdef @ ValDef(name, _, _) if valid(vdef) =>
moduleValDef.get(name) match {
case Some((stat1, vdef1)) =>
if (vdef.mods.is(Synthetic) && !vdef1.mods.is(Synthetic)) {
transferReferences(vdef, vdef1)
removeInExpanded(stat, vdef)
}
else if (!vdef.mods.is(Synthetic) && vdef1.mods.is(Synthetic)) {
transferReferences(vdef1, vdef)
removeInExpanded(stat1, vdef1)
moduleValDef(name) = (stat, vdef)
}
else {
// double definition of objects or case classes, handled elsewhere
}
case None =>
moduleValDef(name) = (stat, vdef)
}
case _ =>
}
case _ =>
}
}
val classDef = mutable.Map[TypeName, TypeDef]()
val moduleDef = mutable.Map[TypeName, TypeDef]()
/** Create links between companion object and companion class.
* Populate `moduleDef` and `classDef` as a side effect.
*/
def createCompanionLinks()(using Context): Unit = {
def updateCache(cdef: TypeDef): Unit =
if (cdef.isClassDef && !cdef.mods.is(Package))
if (cdef.mods.is(ModuleClass)) moduleDef(cdef.name) = cdef
else classDef(cdef.name) = cdef
def createLinks(classTree: TypeDef, moduleTree: TypeDef)(using Context) = {
val claz = ctx.effectiveScope.lookup(classTree.name)
val modl = ctx.effectiveScope.lookup(moduleTree.name)
modl.registerCompanion(claz)
claz.registerCompanion(modl)
}
for (stat <- stats)
expanded(stat) match {
case cdef : TypeDef => updateCache(cdef)
case Thicket(trees) =>
trees.map {
case cdef: TypeDef => updateCache(cdef)
case _ =>
}
case _ =>
}
for (cdef @ TypeDef(name, _) <- classDef.values)
moduleDef.getOrElse(name.moduleClassName, EmptyTree) match {
case t: TypeDef =>
createLinks(cdef, t)
case EmptyTree =>
}
}
/** If a top-level object or class has no companion in the current run, we
* enter a dummy companion (`denot.isAbsent` returns true) or constructor
* proxy in scope. This ensures that we never use a companion from a previous
* run or from thenclass path. See tests/pos/false-companion for an example
* where this matters.
* Also: We add constructor proxies for classes in some local scope, i.e.
* that are not members of other classes. Constructor proxies for member
* classes are added in addConstructorProxies.
*/
def addAbsentCompanions()(using Context): Unit =
if ctx.owner.isTerm then
for case cdef @ TypeDef(className, _) <- classDef.values do
val classSym = ctx.effectiveScope.lookup(className)
val moduleName = className.toTermName
if needsConstructorProxies(classSym) && ctx.effectiveScope.lookupEntry(moduleName) == null then
enterSymbol(classConstructorCompanion(classSym.asClass))
else if ctx.owner.is(PackageClass) then
for case cdef @ TypeDef(moduleName, _) <- moduleDef.values do
val moduleSym = ctx.effectiveScope.lookup(moduleName)
if moduleSym.isDefinedInCurrentRun then
val className = moduleName.stripModuleClassSuffix.toTypeName
val classSym = ctx.effectiveScope.lookup(className)
if !classSym.isDefinedInCurrentRun then
val absentClassSymbol = newClassSymbol(ctx.owner, className, EmptyFlags, _ => NoType)
enterSymbol(absentClassSymbol)
for case cdef @ TypeDef(className, _) <- classDef.values do
val classSym = ctx.effectiveScope.lookup(className.encode)
if classSym.isDefinedInCurrentRun then
val moduleName = className.toTermName
val companionVals = ctx.effectiveScope.lookupAll(moduleName.encode)
if companionVals.isEmpty && needsConstructorProxies(classSym) then
enterSymbol(classConstructorCompanion(classSym.asClass))
else
for moduleSym <- companionVals do
if moduleSym.is(Module) && !moduleSym.isDefinedInCurrentRun then
val companion =
if needsConstructorProxies(classSym) then
classConstructorCompanion(classSym.asClass)
else newModuleSymbol(
ctx.owner, moduleName, EmptyFlags, EmptyFlags, (_, _) => NoType)
enterSymbol(companion)
end addAbsentCompanions
stats.foreach(expand)
mergeCompanionDefs()
val ctxWithStats = stats.foldLeft(ctx)((ctx, stat) => indexExpanded(stat)(using ctx))
inContext(ctxWithStats) {
createCompanionLinks()
addAbsentCompanions()
}
ctxWithStats
}
/** Parse the source and index symbols in the compilation unit's untpdTree
* while asserting the `lateCompile` flag. This will cause any old
* top-level symbol with the same fully qualified name as a newly created
* symbol to be replaced.
*
* Will call the callback with an implementation of type checking
* That will set the tpdTree and root tree for the compilation unit.
*/
def lateEnterUnit(typeCheckCB: (() => Unit) => Unit)(using Context) =
val unit = ctx.compilationUnit
/** Index symbols in unit.untpdTree with lateCompile flag = true */
def lateEnter()(using Context): Context =
val saved = lateCompile
lateCompile = true
try index(unit.untpdTree :: Nil) finally lateCompile = saved
/** Set the tpdTree and root tree of the compilation unit */
def lateTypeCheck()(using Context) =
unit.tpdTree = typer.typedExpr(unit.untpdTree)
val phase = new transform.SetRootTree()
phase.run
unit.untpdTree =
if (unit.isJava) new JavaParser(unit.source).parse()
else new Parser(unit.source).parse()
atPhase(Phases.typerPhase) {
inContext(PrepareInlineable.initContext(ctx)) {
// inline body annotations are set in namer, capturing the current context
// we need to prepare the context for inlining.
lateEnter()
typeCheckCB { () =>
lateTypeCheck()
}
}
}
end lateEnterUnit
/** The type bound on wildcard imports of an import list, with special values
* Nothing if no wildcard imports of this kind exist
* Any if there are unbounded wildcard imports of this kind
*/
def importBound(sels: List[untpd.ImportSelector], isGiven: Boolean)(using Context): Type =
sels.foldLeft(defn.NothingType: Type) { (bound, sel) =>
if sel.isWildcard && sel.isGiven == isGiven then
if sel.bound.isEmpty then defn.AnyType
else bound | typedAheadType(sel.bound).tpe
else bound
}
def missingType(sym: Symbol, modifier: String)(using Context): Unit = {
report.error(s"${modifier}type of implicit definition needs to be given explicitly", sym.srcPos)
sym.resetFlag(GivenOrImplicit)
}
/** The completer of a symbol defined by a member def or import (except ClassSymbols) */
class Completer(val original: Tree)(ictx: Context) extends LazyType with SymbolLoaders.SecondCompleter {
protected def localContext(owner: Symbol): FreshContext = ctx.fresh.setOwner(owner).setTree(original)
/** The context with which this completer was created */
given creationContext: Context = ictx
// make sure testing contexts are not captured by completers
assert(!ictx.reporter.isInstanceOf[ExploringReporter])
protected def typeSig(sym: Symbol): Type = original match
case original: ValDef =>
if (sym.is(Module)) moduleValSig(sym)
else valOrDefDefSig(original, sym, Nil, identity)(using localContext(sym).setNewScope)
case original: DefDef =>
val typer1 = ctx.typer.newLikeThis(ctx.nestingLevel + 1)
nestedTyper(sym) = typer1
typer1.defDefSig(original, sym, this)(using localContext(sym).setTyper(typer1))
case imp: Import =>
try
val expr1 = typedImportQualifier(imp, typedAheadExpr(_, _)(using ctx.withOwner(sym)))
ImportType(expr1)
catch case ex: CyclicReference =>
typr.println(s"error while completing ${imp.expr}")
throw ex
final override def complete(denot: SymDenotation)(using Context): Unit = {
if (Config.showCompletions && ctx.typerState != creationContext.typerState) {
def levels(c: Context): Int =
if (c.typerState eq creationContext.typerState) 0
else if (c.outer.typerState == c.typerState) levels(c.outer)
else levels(c.outer) + 1
println(s"!!!completing ${denot.symbol.showLocated} in buried typerState, gap = ${levels(ctx)}")
}
val creationRunId = creationContext.runId
if ctx.runId > creationRunId then
assert(ctx.mode.is(Mode.Interactive), s"completing $denot in wrong run ${ctx.runId}, was created in $creationRunId")
denot.info = UnspecifiedErrorType
else
try
completeInCreationContext(denot)
if (denot.isCompleted) registerIfChild(denot)
catch
case ex: CompilationUnit.SuspendException =>
val completer = SuspendCompleter()
denot.info = completer
completer.complete(denot)
}
private var completedTypeParamSyms: List[TypeSymbol] | Null = null
def setCompletedTypeParams(tparams: List[TypeSymbol]) =
completedTypeParamSyms = tparams
override def completerTypeParams(sym: Symbol)(using Context): List[TypeSymbol] =
if completedTypeParamSyms != null then completedTypeParamSyms.uncheckedNN
else Nil
protected def addAnnotations(sym: Symbol): Unit = original match {
case original: untpd.MemberDef =>
lazy val annotCtx = annotContext(original, sym)
for (annotTree <- original.mods.annotations) {
val cls = typedAheadAnnotationClass(annotTree)(using annotCtx)
if (cls eq sym)
report.error("An annotation class cannot be annotated with iself", annotTree.srcPos)
else {
val ann = Annotation.deferred(cls)(typedAheadAnnotation(annotTree)(using annotCtx))
sym.addAnnotation(ann)
}
}
case _ =>
}
private def addInlineInfo(sym: Symbol) = original match {
case original: untpd.DefDef if sym.isInlineMethod =>
def rhsToInline(using Context): tpd.Tree =
if !original.symbol.exists && !hasDefinedSymbol(original) then
throw
if sym.isCompleted then Inliner.MissingInlineInfo()
else CyclicReference(sym)
val mdef = typedAheadExpr(original).asInstanceOf[tpd.DefDef]
PrepareInlineable.wrapRHS(original, mdef.tpt, mdef.rhs)
PrepareInlineable.registerInlineInfo(sym, rhsToInline)(using localContext(sym))
case _ =>
}
/** Invalidate `denot` by overwriting its info with `NoType` if
* `denot` is a compiler generated case class method that clashes
* with a user-defined method in the same scope with a matching type.
*/
private def invalidateIfClashingSynthetic(denot: SymDenotation): Unit =
def isCaseClassOrCompanion(owner: Symbol) =
owner.isClass && {
if (owner.is(Module)) owner.linkedClass.is(CaseClass)
else owner.is(CaseClass)
}
def definesMember =
denot.owner.info.decls.lookupAll(denot.name).exists(alt =>
alt != denot.symbol && alt.info.matchesLoosely(denot.info))
def inheritsConcreteMember =
denot.owner.asClass.info.parents.exists(parent =>
parent.member(denot.name).hasAltWith(sd =>
!sd.symbol.is(Deferred) && sd.matches(denot)))
val isClashingSynthetic =
denot.is(Synthetic, butNot = ConstructorProxy)
&& desugar.isRetractableCaseClassMethodName(denot.name)
&& isCaseClassOrCompanion(denot.owner)
&& (definesMember || inheritsConcreteMember)
if isClashingSynthetic then
typr.println(i"invalidating clashing $denot in ${denot.owner}")
denot.markAbsent()
end invalidateIfClashingSynthetic
/** If completed symbol is an enum value or a named class, register it as a child
* in all direct parent classes which are sealed.
*/
def registerIfChild(denot: SymDenotation)(using Context): Unit = {
val sym = denot.symbol
def register(child: Symbol, parentCls: ClassSymbol) = {
if (parentCls.is(Sealed))
if ((child.isInaccessibleChildOf(parentCls) || child.isAnonymousClass) && !sym.hasAnonymousChild)
addChild(parentCls, parentCls)
else if (!parentCls.is(ChildrenQueried))
addChild(parentCls, child)
else
report.error(em"""children of $parentCls were already queried before $sym was discovered.
|As a remedy, you could move $sym on the same nesting level as $parentCls.""",
child.srcPos)
}
if denot.isClass && !sym.isEnumAnonymClass && !sym.isRefinementClass then
val child = if (denot.is(Module)) denot.sourceModule else denot.symbol
denot.info.parents.foreach { parent => register(child, parent.classSymbol.asClass) }
else if denot.is(CaseVal, butNot = Method | Module) then
assert(denot.is(Enum), denot)
denot.info.classSymbols.foreach { parent => register(denot.symbol, parent) }
end if
}
/** Intentionally left without `implicit ctx` parameter. We need
* to pick up the context at the point where the completer was created.
*/
def completeInCreationContext(denot: SymDenotation): Unit = {
val sym = denot.symbol
addAnnotations(sym)
addInlineInfo(sym)
denot.info = typeSig(sym)
invalidateIfClashingSynthetic(denot)
Checking.checkWellFormed(sym)
denot.info = avoidPrivateLeaks(sym)
}
}
class TypeDefCompleter(original: TypeDef)(ictx: Context)
extends Completer(original)(ictx) with TypeParamsCompleter {
private var myTypeParams: List[TypeSymbol] | Null = null
private var nestedCtx: Context | Null = null
assert(!original.isClassDef)
/** If completion of the owner of the to be completed symbol has not yet started,
* complete the owner first and check again. This prevents cyclic references
* where we need to copmplete a type parameter that has an owner that is not
* yet completed. Test case is pos/i10967.scala.
*/
override def needsCompletion(symd: SymDenotation)(using Context): Boolean =
val owner = symd.owner
!owner.exists
|| owner.is(Touched)
|| {
owner.ensureCompleted()
!symd.isCompleted
}
override def completerTypeParams(sym: Symbol)(using Context): List[TypeSymbol] =
if myTypeParams == null then
//println(i"completing type params of $sym in ${sym.owner}")
nestedCtx = localContext(sym).setNewScope
given Context = nestedCtx.uncheckedNN
def typeParamTrees(tdef: Tree): List[TypeDef] = tdef match
case TypeDef(_, original) =>
original match
case LambdaTypeTree(tparams, _) => tparams
case original: DerivedFromParamTree => typeParamTrees(original.watched)
case _ => Nil
case _ => Nil
val tparams = typeParamTrees(original)
index(tparams)
myTypeParams = tparams.map(symbolOfTree(_).asType)
for param <- tparams do typedAheadExpr(param)
end if
myTypeParams.uncheckedNN
end completerTypeParams
override final def typeSig(sym: Symbol): Type =
val tparamSyms = completerTypeParams(sym)(using ictx)
given ctx: Context = nestedCtx.nn
def abstracted(tp: TypeBounds): TypeBounds =
HKTypeLambda.boundsFromParams(tparamSyms, tp)
val dummyInfo1 = abstracted(TypeBounds.empty)
sym.info = dummyInfo1
sym.setFlag(Provisional)
// Temporarily set info of defined type T to ` >: Nothing <: Any.
// This is done to avoid cyclic reference errors for F-bounds.
// This is subtle: `sym` has now an empty TypeBounds, but is not automatically
// made an abstract type. If it had been made an abstract type, it would count as an
// abstract type of its enclosing class, which might make that class an invalid
// prefix. I verified this would lead to an error when compiling io.ClassPath.
// A distilled version is in pos/prefix.scala.
//
// The scheme critically relies on an implementation detail of isRef, which
// inspects a TypeRef's info, instead of simply dealiasing alias types.
val isDerived = original.rhs.isInstanceOf[untpd.DerivedTypeTree]
val rhs = original.rhs match {
case LambdaTypeTree(_, body) => body
case rhs => rhs
}
// For match types: approximate with upper bound while evaluating the rhs.
val dummyInfo2 = rhs match {
case MatchTypeTree(bound, _, _) if !bound.isEmpty =>
abstracted(TypeBounds.upper(typedAheadType(bound).tpe))