-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Namers.scala
2222 lines (1971 loc) · 99.2 KB
/
Namers.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.tools.nsc
package typechecker
import scala.annotation.{nowarn, tailrec}
import scala.collection.mutable
import symtab.Flags._
import scala.reflect.internal.util.ListOfNil
import scala.tools.nsc.Reporting.WarningCategory
import scala.util.chaining._
/** This trait declares methods to create symbols and to enter them into scopes.
*
* @author Martin Odersky
*/
trait Namers extends MethodSynthesis {
self: Analyzer =>
import global._
import definitions._
/** Replaces any Idents for which cond is true with fresh TypeTrees().
* Does the same for any trees containing EmptyTrees.
*/
private class TypeTreeSubstituter(cond: Name => Boolean) extends AstTransformer {
override def transform(tree: Tree): Tree = tree match {
case Ident(name) if cond(name) => TypeTree()
case _ => super.transform(tree)
}
def apply(tree: Tree) = {
val r = transform(tree)
if (r exists { case tt: TypeTree => tt.isEmpty case _ => false })
TypeTree()
else r
}
}
private def isTemplateContext(ctx: Context): Boolean = ctx.tree match {
case Template(_, _, _) => true
case Import(_, _) => isTemplateContext(ctx.outer)
case _ => false
}
private class NormalNamer(context: Context) extends Namer(context)
def newNamer(context: Context): Namer = new NormalNamer(context)
abstract class Namer(val context: Context) extends MethodSynth with NamerContextErrors { thisNamer =>
// overridden by the presentation compiler
def saveDefaultGetter(meth: Symbol, default: Symbol): Unit = { }
def expandMacroAnnotations(stats: List[Tree]): List[Tree] = stats
import NamerErrorGen._
val typer = newTyper(context)
private lazy val innerNamer =
if (isTemplateContext(context)) createInnerNamer() else this
def createNamer(tree: Tree): Namer = {
val sym = tree match {
case ModuleDef(_, _, _) => tree.symbol.moduleClass
case _ => tree.symbol
}
def isConstrParam(vd: ValDef) = {
(sym hasFlag PARAM | PRESUPER) &&
!vd.mods.isJavaDefined &&
sym.owner.isConstructor
}
val ownerCtx = tree match {
case vd: ValDef if isConstrParam(vd) =>
context.makeConstructorContext
case _ =>
context
}
newNamer(ownerCtx.makeNewScope(tree, sym))
}
def createInnerNamer() = {
newNamer(context.make(context.tree, owner, newScope))
}
def createPrimaryConstructorParameterNamer: Namer = { //todo: can we merge this with SCCmode?
val classContext = context.enclClass
val outerContext = classContext.outer.outer
val paramContext = outerContext.makeNewScope(outerContext.tree, outerContext.owner)
owner.unsafeTypeParams foreach (paramContext.scope enter _)
newNamer(paramContext)
}
def enclosingNamerWithScope(scope: Scope) = {
var cx = context
while (cx != NoContext && cx.scope != scope) cx = cx.outer
if (cx == NoContext || cx == context) thisNamer
else newNamer(cx)
}
def enterValueParams(vparamss: List[List[ValDef]]): List[List[Symbol]] =
mmap(vparamss) { param =>
enterInScope(assignMemberSymbol(param, mask = ValueParameterFlags)) setInfo monoTypeCompleter(param)
}
protected def owner = context.owner
def contextFile = context.unit.source.file
def typeErrorHandler[T](tree: Tree, alt: T): PartialFunction[Throwable, T] = {
case ex: TypeError if !global.propagateCyclicReferences =>
// H@ need to ensure that we handle only cyclic references
TypeSigError(tree, ex)
alt
}
// All lazy vals need accessors, including those owned by terms (e.g., in method) or private[this] in a class
def deriveAccessors(vd: ValDef) = (vd.mods.isLazy || owner.isTrait || (owner.isClass && deriveAccessorsInClass(vd)))
private def deriveAccessorsInClass(vd: ValDef) =
!vd.mods.isPrivateLocal && // note, private[this] lazy vals do get accessors -- see outer disjunction of deriveAccessors
!(vd.name startsWith nme.OUTER) && // outer accessors are added later, in explicitouter
!isEnumConstant(vd) // enums can only occur in classes, so only check here
/** Determines whether this field holds an enum constant.
* To qualify, the following conditions must be met:
* - The field's class has the ENUM flag set
* - The field's class extends java.lang.Enum
* - The field has the ENUM flag set
* - The field is static
* - The field is stable
*/
def isEnumConstant(vd: ValDef) = {
val ownerHasEnumFlag =
// Necessary to check because scalac puts Java's static members into the companion object
// while Scala's enum constants live directly in the class.
// We don't check for clazz.superClass == JavaEnumClass, because this causes an illegal
// cyclic reference error. See the commit message for details.
if (context.unit.isJava) owner.companionClass.hasJavaEnumFlag else owner.hasJavaEnumFlag
vd.mods.hasAllFlags(JAVA_ENUM | STABLE | STATIC) && ownerHasEnumFlag
}
def setPrivateWithin[T <: Symbol](tree: Tree, sym: T, mods: Modifiers): T =
if (sym.isPrivateLocal) sym
else {
val qualClass = if (mods.hasAccessBoundary)
typer.qualifyingClass(tree, mods.privateWithin, packageOK = true, immediate = false)
else
NoSymbol
sym setPrivateWithin qualClass
}
def setPrivateWithin(tree: MemberDef, sym: Symbol): Symbol =
setPrivateWithin(tree, sym, tree.mods)
def inConstructorFlag: Long = {
@tailrec def go(context: Context): Long =
if (context eq NoContext) 0L else {
val owner = context.owner
if (!owner.isTerm || owner.isAnonymousFunction) 0L
else if (owner.isConstructor) if (context.inConstructorSuffix) 0L else INCONSTRUCTOR
else if (owner.isEarlyInitialized) INCONSTRUCTOR
else go(context.outer)
}
go(context)
}
def moduleClassFlags(moduleFlags: Long) =
(moduleFlags & ModuleToClassFlags) | inConstructorFlag
def updatePosFlags(sym: Symbol, pos: Position, flags: Long): Symbol = {
debuglog("[overwrite] " + sym)
val newFlags = (sym.flags & LOCKED) | flags
// !!! needed for: pos/t5954d; the uniques type cache will happily serve up the same TypeRef
// over this mutated symbol, and we witness a stale cache for `parents`.
invalidateCaches(sym.rawInfo, sym :: sym.moduleClass :: Nil)
sym reset NoType setFlag newFlags setPos pos
sym.moduleClass andAlso (updatePosFlags(_, pos, moduleClassFlags(flags)))
if (sym.isTopLevel) {
companionSymbolOf(sym, context) andAlso { companion =>
val assignNoType = companion.rawInfo match {
case _: SymLoader => true
case tp => tp.isComplete && (runId(sym.validTo) != currentRunId)
}
// pre-set linked symbol to NoType, in case it is not loaded together with this symbol.
if (assignNoType)
companion setInfo NoType
}
}
sym
}
def namerOf(sym: Symbol): Namer = {
val usePrimary = sym.isTerm && (
(sym.isParamAccessor)
|| (sym.isParameter && sym.owner.isPrimaryConstructor)
)
if (usePrimary) createPrimaryConstructorParameterNamer
else innerNamer
}
// FIXME - this logic needs to be thoroughly explained
// and justified. I know it's wrong with respect to package
// objects, but I think it's also wrong in other ways.
protected def conflict(newS: Symbol, oldS: Symbol) = (
( !oldS.isSourceMethod
|| nme.isSetterName(newS.name)
|| newS.isTopLevel
) &&
!( // @M: allow repeated use of `_` for higher-order type params
(newS.owner.isTypeParameter || newS.owner.isAbstractType)
// FIXME: name comparisons not successful, are these underscores
// sometimes nme.WILDCARD and sometimes tpnme.WILDCARD?
&& (newS.name string_== nme.WILDCARD)
)
)
private def allowsOverload(sym: Symbol) = (
sym.isSourceMethod && sym.owner.isClass && !sym.isTopLevel
)
private def inCurrentScope(m: Symbol): Boolean = {
if (owner.isClass) owner == m.owner
else context.scope.lookupSymbolEntry(m) match {
case null => false
case entry => entry.owner eq context.scope
}
}
/** Enter symbol into context's scope and return symbol itself */
def enterInScope(sym: Symbol): Symbol = enterInScope(sym, context.scope)
/** Enter symbol into given scope and return symbol itself */
def enterInScope(sym: Symbol, scope: Scope): Symbol = {
// FIXME - this is broken in a number of ways.
//
// 1) If "sym" allows overloading, that is not itself sufficient to skip
// the check, because "prev.sym" also must allow overloading.
//
// 2) There is nothing which reconciles a package's scope with
// the package object's scope. This is the source of many bugs
// with e.g. defining a case class in a package object. When
// compiling against classes, the class symbol is created in the
// package and in the package object, and the conflict is undetected.
// There is also a non-deterministic outcome for situations like
// an object with the same name as a method in the package object.
// allow for overloaded methods
if (!allowsOverload(sym)) {
val prev = scope.lookupEntry(sym.name)
if ((prev ne null) && prev.owner == scope && conflict(sym, prev.sym)) {
if (sym.isSynthetic || prev.sym.isSynthetic) {
handleSyntheticNameConflict(sym, prev.sym)
handleSyntheticNameConflict(prev.sym, sym)
}
DoubleDefError(sym, prev.sym)
sym setInfo ErrorType
scope unlink prev.sym // let them co-exist...
// FIXME: The comment "let them co-exist" is confusing given that the
// line it comments unlinks one of them. What does it intend?
}
}
if (sym.isModule && sym.isSynthetic && sym.owner.isClass && !sym.isTopLevel) {
val entry = scope.lookupEntry(sym.name.toTypeName)
if (entry eq null)
scope enter sym
else
scope.enterBefore(sym, entry)
} else
scope enter sym
}
/** Logic to handle name conflicts of synthetically generated symbols
* We handle right now: t6227
*/
def handleSyntheticNameConflict(sym1: Symbol, sym2: Symbol) = {
if (sym1.isImplicit && sym1.isMethod && sym2.isModule && sym2.companionClass.isCaseClass)
validate(sym2.companionClass)
}
def enterSym(tree: Tree): Context = pluginsEnterSym(this, tree)
/** Default implementation of `enterSym`.
* Can be overridden by analyzer plugins (see AnalyzerPlugins.pluginsEnterSym for more details)
*/
def standardEnterSym(tree: Tree): Context = {
def dispatch() = {
var returnContext = this.context
tree match {
case tree @ PackageDef(_, _) => enterPackage(tree)
case tree @ ClassDef(_, _, _, _) => enterClassDef(tree)
case tree @ ModuleDef(_, _, _) => enterModuleDef(tree)
case tree @ ValDef(_, _, _, _) => enterValDef(tree)
case tree @ DefDef(_, _, _, _, _, _) => enterDefDef(tree)
case tree @ TypeDef(_, _, _, _) => enterTypeDef(tree)
case DocDef(_, defn) => enterSym(defn)
case tree @ Import(_, _) => enterImport(tree); returnContext = context.makeImportContext(tree)
case _ =>
}
returnContext
}
tree.symbol match {
case NoSymbol => try dispatch() catch typeErrorHandler(tree, this.context)
case sym =>
tree match {
case tree@Import(_, _) => enterExistingSym(sym, tree).make(tree)
case _ => enterExistingSym(sym, tree)
}
}
}
def assignMemberSymbol(tree: MemberDef, mask: Long = -1L): Symbol = {
val sym = createMemberSymbol(tree, tree.name, mask)
setPrivateWithin(tree, sym)
tree.symbol = sym
sym
}
def assignAndEnterFinishedSymbol(tree: MemberDef): Symbol = {
val sym = enterInScope(assignMemberSymbol(tree))
sym setInfo completerOf(tree)
// log("[+info] " + sym.fullLocationString)
sym
}
def createMethod(accessQual: MemberDef, name: TermName, pos: Position, flags: Long): MethodSymbol = {
val sym = owner.newMethod(name, pos, flags)
setPrivateWithin(accessQual, sym)
sym
}
/** Create a new symbol at the context owner based on the given tree.
* A different name can be given. If the modifier flags should not be
* be transferred to the symbol as they are, supply a mask containing
* the flags to keep.
*/
def createMemberSymbol(tree: MemberDef, name: Name, mask: Long): Symbol = {
val pos = tree.pos
val isParameter = tree.mods.isParameter
val flags = tree.mods.flags & mask
tree match {
case TypeDef(_, _, _, _) if isParameter => owner.newTypeParameter(name.toTypeName, pos, flags)
case TypeDef(_, _, _, _) => owner.newTypeSymbol(name.toTypeName, pos, flags)
case DefDef(_, nme.CONSTRUCTOR, _, _, _, _) => owner.newConstructor(pos, flags)
case DefDef(_, _, _, _, _, _) => owner.newMethod(name.toTermName, pos, flags)
case ClassDef(_, _, _, _) => owner.newClassSymbol(name.toTypeName, pos, flags)
case ModuleDef(_, _, _) => owner.newModule(name.toTermName, pos, flags)
case PackageDef(pid, _) => createPackageSymbol(pos, pid)
case ValDef(_, _, _, _) =>
if (isParameter) owner.newValueParameter(name.toTermName, pos, flags)
else owner.newValue(name.toTermName, pos, flags)
}
}
def createImportSymbol(tree: Import) =
NoSymbol.newImport(tree.pos) setInfo (namerOf(tree.symbol) importTypeCompleter tree)
/** All PackageClassInfoTypes come from here. */
def createPackageSymbol(pos: Position, pid: RefTree): Symbol = {
val pkgOwner = pid match {
case Ident(_) => if (owner.isEmptyPackageClass) rootMirror.RootClass else owner
case Select(qual: RefTree, _) => createPackageSymbol(pos, qual).moduleClass
case x => throw new MatchError(x)
}
val existing = pkgOwner.info.decls.lookup(pid.name)
if (existing.hasPackageFlag && pkgOwner == existing.owner)
existing
else {
val pkg = pkgOwner.newPackage(pid.name.toTermName, pos)
val pkgClass = pkg.moduleClass
val pkgClassInfo = new PackageClassInfoType(newPackageScope(pkgClass), pkgClass)
pkgClass setInfo pkgClassInfo
pkg setInfo pkgClass.tpe
enterInScope(pkg, pkgOwner.info.decls)
}
}
private def enterClassSymbol(tree: ClassDef, clazz: ClassSymbol): Symbol = {
var sourceFile = clazz.sourceFile
if (sourceFile != null && sourceFile != contextFile)
devWarning(s"Source file mismatch in $clazz: ${sourceFile} vs. $contextFile")
clazz.associatedFile = contextFile
sourceFile = clazz.sourceFile
if (sourceFile != null) {
assert(currentRun.canRedefine(clazz) || sourceFile == currentRun.symSource(clazz), sourceFile)
currentRun.symSource(clazz) = sourceFile
}
registerTopLevelSym(clazz)
assert(clazz.name.toString.indexOf('(') < 0, clazz.name) // )
clazz
}
def enterClassSymbol(tree: ClassDef): Symbol = {
val existing = context.scope.lookup(tree.name)
val isRedefinition = (
existing.isType
&& existing.isTopLevel
&& context.scope == existing.owner.info.decls
&& currentRun.canRedefine(existing)
)
val clazz: Symbol = {
if (isRedefinition) {
updatePosFlags(existing, tree.pos, tree.mods.flags)
setPrivateWithin(tree, existing)
clearRenamedCaseAccessors(existing)
existing
}
else enterInScope(assignMemberSymbol(tree)) setFlag inConstructorFlag
}
clazz match {
case csym: ClassSymbol if csym.isTopLevel => enterClassSymbol(tree, csym)
case _ => clazz
}
}
/** Given a ClassDef or ModuleDef, verifies there isn't a companion which
* has been defined in a separate file.
*/
@nowarn("cat=lint-nonlocal-return")
def validateCompanionDefs(tree: ImplDef): Unit = {
val sym = tree.symbol orElse { return }
val ctx = if (context.owner.isPackageObjectClass) context.outer else context
val module = if (sym.isModule) sym else ctx.scope lookupModule tree.name
val clazz = if (sym.isClass) sym else ctx.scope lookupClass tree.name
val fails = (
module.isModule
&& clazz.isClass
&& !module.isSynthetic
&& !clazz.isSynthetic
&& (clazz.sourceFile ne null)
&& (module.sourceFile ne null)
&& !(module isCoDefinedWith clazz)
&& module.exists
&& clazz.exists
&& (currentRun.compiles(clazz) == currentRun.compiles(module))
)
if (fails) {
reporter.error(tree.pos, (
s"Companions '$clazz' and '$module' must be defined in same file:\n"
+ s" Found in ${clazz.sourceFile.canonicalPath} and ${module.sourceFile.canonicalPath}")
)
}
}
def enterModuleDef(tree: ModuleDef) = {
val sym = enterModuleSymbol(tree)
sym.moduleClass setInfo namerOf(sym).moduleClassTypeCompleter(tree)
sym setInfo completerOf(tree)
validateCompanionDefs(tree)
sym
}
/** Enter a module symbol.
*/
def enterModuleSymbol(tree : ModuleDef): Symbol = {
val moduleFlags = tree.mods.flags | MODULE
val existingModule = context.scope lookupModule tree.name
if (existingModule.isModule && !existingModule.hasPackageFlag && inCurrentScope(existingModule) && (currentRun.canRedefine(existingModule) || existingModule.isSynthetic)) {
updatePosFlags(existingModule, tree.pos, moduleFlags)
setPrivateWithin(tree, existingModule)
existingModule.moduleClass andAlso (setPrivateWithin(tree, _))
context.unit.synthetics -= existingModule
tree.symbol = existingModule
}
else {
enterInScope(assignMemberSymbol(tree))
val m = tree.symbol
m.moduleClass setFlag moduleClassFlags(moduleFlags)
setPrivateWithin(tree, m.moduleClass)
}
val m = tree.symbol
if (m.isTopLevel && !m.hasPackageFlag) {
// TODO: I've seen crashes where m.moduleClass == NoSymbol
m.moduleClass.associatedFile = contextFile
currentRun.symSource(m) = m.moduleClass.sourceFile
registerTopLevelSym(m)
}
m
}
def enterSyms(trees: List[Tree]): Namer =
trees.foldLeft(this: Namer) { (namer, t) =>
val ctx = namer enterSym t
// for Import trees, enterSym returns a changed context, so we need a new namer
if (ctx eq namer.context) namer
else newNamer(ctx)
}
def applicableTypeParams(owner: Symbol): List[Symbol] =
if (owner.isTerm || owner.isPackageClass) Nil
else applicableTypeParams(owner.owner) ::: owner.typeParams
/** If no companion object for clazz exists yet, create one by applying `creator` to
* class definition tree.
* @return the companion object symbol.
*/
def ensureCompanionObject(cdef: ClassDef, creator: ClassDef => Tree = companionModuleDef(_)): Symbol =
pluginsEnsureCompanionObject(this, cdef, creator)
/** Default implementation of `ensureCompanionObject`.
* Can be overridden by analyzer plugins (see AnalyzerPlugins.pluginsEnsureCompanionObject for more details)
*/
def standardEnsureCompanionObject(cdef: ClassDef, creator: ClassDef => Tree = companionModuleDef(_)): Symbol = {
val m = companionSymbolOf(cdef.symbol, context)
// @luc: not sure why "currentRun.compiles(m)" is needed, things breaks
// otherwise. documentation welcome.
//
// @PP: I tried to reverse engineer said documentation. The only tests
// which fail are buildmanager tests, as follows. Given A.scala:
// case class Foo()
// If you recompile A.scala, the Changes Map is
// Map(class Foo -> Nil, object Foo -> Nil)
// But if you remove the 'currentRun.compiles(m)' condition, it is
// Map(class Foo -> Nil)
// What exactly this implies and whether this is a sensible way to
// enforce it, I don't know.
//
// @martin: currentRun.compiles is needed because we might have a stale
// companion object from another run in scope. In that case we should still
// overwrite the object. I.e.
// Compile run #1: object Foo { ... }
// Compile run #2: case class Foo ...
// The object Foo is still in scope, but because it is not compiled in current run
// it should be ditched and a new one created.
if (m != NoSymbol && currentRun.compiles(m)) m
else enterSyntheticSym(atPos(cdef.pos.focus)(creator(cdef)))
}
private def checkSelectors(tree: Import): Unit = {
import DuplicatesErrorKinds._
val Import(expr, selectors) = tree
val base = expr.tpe
// warn proactively if specific import loses to definition in scope,
// since it may result in desired implicit not imported into scope.
def checkNotRedundant(pos: Position, from: Name, to0: Name): Unit = {
def check(to: Name): Unit = {
val e = context.scope.lookupEntry(to)
if (e != null && e.owner == context.scope && e.sym.exists) {
if (!context.isPackageOwnedInDifferentUnit(e.sym))
typer.permanentlyHiddenWarning(pos, to0, e.sym)
} else if (context ne context.enclClass) {
val defSym = context.prefix.member(to) filter (
sym => sym.exists && context.isAccessible(sym, context.prefix, superAccess = false))
defSym andAlso (typer.permanentlyHiddenWarning(pos, to0, _))
}
}
if (!tree.symbol.isSynthetic && expr.symbol != null && !expr.symbol.isInterpreterWrapper) {
if (base.member(from).exists)
check(to0)
if (base.member(from.toTypeName).exists)
check(to0.toTypeName)
}
}
def checkSelector(s: ImportSelector) = {
val ImportSelector(from, fromPos, to, _) = s
def isValid(original: Name, base: Type) = {
def lookup(name: Name) =
if (context.unit.isJava)
NoContext.javaFindMember(base, name, _ => true)._2
else
base.nonLocalMember(name)
lookup(original.toTermName) != NoSymbol || lookup(original.toTypeName) != NoSymbol
}
if (!s.isWildcard && base != ErrorType) {
val okay = isValid(from, base) || context.unit.isJava && ( // Java code...
(nme.isModuleName(from) && isValid(from.dropModule, base)) // - importing Scala module classes
|| isValid(from, base.companion) // - importing type members from types
)
if (!okay) typer.TyperErrorGen.NotAMemberError(tree, expr, from, context.outer)
// Setting the position at the import means that if there is
// more than one hidden name, the second will not be warned.
// So it is the position of the actual hidden name.
//
// Note: java imports have precedence over definitions in the same package
// so don't warn for them. There is a corresponding special treatment
// in the shadowing rules in typedIdent to (scala/bug#7232). In any case,
// we shouldn't be emitting warnings for .java source files.
if (!context.unit.isJava)
checkNotRedundant(tree.pos withPoint fromPos, from, to)
}
}
selectors foreach checkSelector
def noDuplicates(): Unit = {
def loop(xs: List[ImportSelector]): Unit = xs match {
case Nil => ()
case hd :: tl =>
if (!hd.isWildcard && tl.exists(x => !x.isWildcard && x.name == hd.name))
DuplicatesError(tree, hd.name, RenamedTwice)
else if (hd.isRename && tl.exists(x => x.isRename && x.rename == hd.rename))
DuplicatesError(tree, hd.rename, AppearsTwice)
else loop(tl)
}
loop(selectors)
}
// checks on the whole set
noDuplicates()
}
def copyMethodCompleter(copyDef: DefDef): TypeCompleter = {
/* Assign the types of the class parameters to the parameters of the
* copy method. See comment in `Unapplies.caseClassCopyMeth`
*/
def assignParamTypes(copyDef: DefDef, sym: Symbol): Unit = {
val clazz = sym.owner
val constructorType = clazz.primaryConstructor.tpe
val subst = SubstSymMap(clazz.typeParams, copyDef.tparams.map(_.symbol))
val classParamss = constructorType.paramss
foreach2(copyDef.vparamss, classParamss)((copyParams, classParams) =>
foreach2(copyParams, classParams)((copyP, classP) =>
copyP.tpt setType subst(classP.tpe)
)
)
}
new CompleterWrapper(completerOf(copyDef)) {
override def complete(sym: Symbol): Unit = {
assignParamTypes(tree.asInstanceOf[DefDef], sym)
super.complete(sym)
}
}
}
// for apply/unapply, which may need to disappear when they clash with a user-defined method of matching signature
def applyUnapplyMethodCompleter(un_applyDef: DefDef, companionContext: Context): TypeCompleter =
new CompleterWrapper(completerOf(un_applyDef)) {
override def complete(sym: Symbol): Unit = {
assert(sym hasAllFlags CASE | SYNTHETIC, sym.defString)
super.complete(sym)
// don't propagate e.g. @volatile annot to apply's argument
def retainOnlyParamAnnots(param: Symbol) =
param setAnnotations (param.annotations filter AnnotationInfo.mkFilter(ParamTargetClass, defaultRetention = false))
sym.info.paramss.foreach(_.foreach(retainOnlyParamAnnots))
// owner won't be locked
val ownerInfo = companionContext.owner.info
// If there's a same-named locked symbol, we're currently completing its signature.
// If `scopePartiallyCompleted`, the program is known to have a type error, since
// this means a user-defined method is missing a result type while its rhs refers to `sym` or an overload.
// This is an error because overloaded/recursive methods must have a result type.
// The method would be overloaded if its signature, once completed, would not match the synthetic method's,
// or recursive if it turned out we should unlink our synthetic method (matching sig).
// In any case, error out. We don't unlink the symbol so that `symWasOverloaded` says yes,
// which would be wrong if the method is in fact recursive, but it seems less confusing.
val scopePartiallyCompleted = new HasMember(ownerInfo, sym.name, BridgeFlags | SYNTHETIC, LOCKED).apply()
// Check `scopePartiallyCompleted` first to rule out locked symbols from the owner.info.member call,
// as FindMember will call info on a locked symbol (while checking type matching to assemble an overloaded type),
// and throw a TypeError, so that we are aborted.
// Do not consider deferred symbols, as suppressing our concrete implementation would be an error regardless
// of whether the signature matches (if it matches, we omitted a valid implementation, if it doesn't,
// we would get an error for the missing implementation it isn't implemented by some overload other than our synthetic one)
val suppress = scopePartiallyCompleted || {
// can't exclude deferred members using DEFERRED flag here (TODO: why?)
val userDefined = ownerInfo.memberBasedOnName(sym.name, BridgeFlags | SYNTHETIC)
(userDefined != NoSymbol) && {
assert(userDefined != sym, "userDefined symbol cannot be the same as symbol of which it is a member")
val alts = userDefined.alternatives // could be just the one, if this member isn't overloaded
// don't compute any further `memberInfo`s if there's an error somewhere
alts.exists(_.isErroneous) || {
val self = companionContext.owner.thisType
val memberInfo = self.memberInfo(sym)
alts.exists(alt => !alt.isDeferred && (self.memberInfo(alt) matches memberInfo))
}
}
}
if (suppress) {
sym setInfo ErrorType
// There are two ways in which we exclude the symbol from being added in typedStats::addSynthetics,
// because we don't know when the completer runs with respect to this loop in addSynthetics
// for (sym <- scope)
// for (tree <- context.unit.synthetics.get(sym) if shouldAdd(sym)) {
// if (!sym.initialize.hasFlag(IS_ERROR))
// newStats += typedStat(tree)
// If we're already in the loop, set the IS_ERROR flag and trigger the condition `sym.initialize.hasFlag(IS_ERROR)`
sym setFlag IS_ERROR
// Or, if we are not yet in the addSynthetics loop, we can just retract our symbol from the synthetics for this unit.
companionContext.unit.synthetics -= sym
// Don't unlink in an error situation to generate less confusing error messages.
// Ideally, our error reporting would distinguish overloaded from recursive user-defined apply methods without signature,
// but this would require some form of partial-completion of method signatures, so that we can
// know what the argument types were, even though we can't complete the result type, because
// we hit a cycle while trying to compute it (when we get here with locked user-defined symbols, we
// are in the complete for that symbol, and thus the locked symbol has not yet received enough info;
// I hesitate to provide more info, because it would involve a WildCard or something for its result type,
// which could upset other code paths)
if (!scopePartiallyCompleted)
companionContext.scope.unlink(sym)
for (a <- sym.attachments.get[CaseApplyDefaultGetters]; defaultGetter <- a.defaultGetters) {
companionContext.unit.synthetics -= defaultGetter
companionContext.scope.unlink(defaultGetter)
}
}
sym.removeAttachment[CaseApplyDefaultGetters] // no longer needed once the completer is done
}
}
def completerOf(tree: MemberDef): TypeCompleter = {
val mono = namerOf(tree.symbol) monoTypeCompleter tree
val tparams = treeInfo.typeParameters(tree)
if (tparams.isEmpty) mono
else {
/* @M! TypeDef's type params are handled differently, e.g., in `type T[A[x <: B], B]`, A and B are entered
* first as both are in scope in the definition of x. x is only in scope in `A[x <: B]`.
* No symbols are created for the abstract type's params at this point, i.e. the following assertion holds:
* !tree.symbol.isAbstractType || { tparams.forall(_.symbol == NoSymbol)
* (tested with the above example, `trait C { type T[A[X <: B], B] }`). See also comment in PolyTypeCompleter.
*/
if (!tree.symbol.isAbstractType) //@M TODO: change to isTypeMember ?
createNamer(tree) enterSyms tparams
new PolyTypeCompleter(tparams, mono, context) //@M
}
}
def enterValDef(tree: ValDef): Unit = {
val isScala = !context.unit.isJava
if (isScala) {
if (nme.isSetterName(tree.name)) ValOrVarWithSetterSuffixError(tree)
if (tree.mods.isPrivateLocal && tree.mods.isCaseAccessor) PrivateThisCaseClassParameterError(tree)
}
if (isScala && deriveAccessors(tree)) enterGetterSetter(tree)
else assignAndEnterFinishedSymbol(tree)
if (isEnumConstant(tree)) {
tree.symbol setInfo ConstantType(Constant(tree.symbol))
tree.symbol.owner.linkedClassOfClass addChild tree.symbol
}
}
def enterPackage(tree: PackageDef): Unit = {
val sym = createPackageSymbol(tree.pos, tree.pid)
tree.symbol = sym
newNamer(context.make(tree, sym.moduleClass, sym.info.decls)) enterSyms tree.stats
}
private def enterImport(tree: Import) = {
val sym = createImportSymbol(tree)
tree.symbol = sym
}
def enterTypeDef(tree: TypeDef) = assignAndEnterFinishedSymbol(tree)
def enterDefDef(tree: DefDef): Unit = {
tree match {
case DefDef(_, nme.CONSTRUCTOR, _, _, _, _) =>
assignAndEnterFinishedSymbol(tree)
case DefDef(mods, name, _, _, _, _) =>
val sym = enterInScope(assignMemberSymbol(tree))
val completer =
if (sym hasFlag SYNTHETIC) {
if (name == nme.copy) copyMethodCompleter(tree)
else if (sym hasFlag CASE) applyUnapplyMethodCompleter(tree, context)
else completerOf(tree)
} else completerOf(tree)
sym setInfo completer
}
if (mexists(tree.vparamss)(_.mods.hasDefault))
enterDefaultGetters(tree.symbol, tree, tree.vparamss, tree.tparams)
}
def enterClassDef(tree: ClassDef): Unit = {
val ClassDef(mods, _, _, impl) = tree
val primaryConstructorArity = treeInfo.firstConstructorArgs(impl.body).size
tree.symbol = enterClassSymbol(tree)
tree.symbol setInfo completerOf(tree)
if (mods.isCase) {
val m = ensureCompanionObject(tree, caseModuleDef)
m.moduleClass.updateAttachment(new ClassForCaseCompanionAttachment(tree))
}
val hasDefault = impl.body exists treeInfo.isConstructorWithDefault
if (hasDefault) {
val m = ensureCompanionObject(tree)
m.updateAttachment(new ConstructorDefaultsAttachment(tree, null))
}
val owner = tree.symbol.owner
if (settings.warnPackageObjectClasses && owner.isPackageObjectClass && !mods.isImplicit) {
context.warning(tree.pos,
"it is not recommended to define classes/objects inside of package objects.\n" +
"If possible, define " + tree.symbol + " in " + owner.skipPackageObject + " instead.",
WarningCategory.LintPackageObjectClasses)
}
// Suggested location only.
if (mods.isImplicit) {
if (primaryConstructorArity == 1) {
log("enter implicit wrapper "+tree+", owner = "+owner)
enterImplicitWrapper(tree)
}
else reporter.error(tree.pos, "implicit classes must accept exactly one primary constructor parameter")
}
validateCompanionDefs(tree)
}
// Hooks which are overridden in the presentation compiler
def enterExistingSym(sym: Symbol, tree: Tree): Context = {
this.context
}
def enterIfNotThere(sym: Symbol): Unit = { }
def enterSyntheticSym(tree: Tree): Symbol = {
enterSym(tree)
context.unit.synthetics(tree.symbol) = tree
tree.symbol
}
// --- Lazy Type Assignment --------------------------------------------------
@nowarn("cat=lint-nonlocal-return")
def findCyclicalLowerBound(tp: Type): Symbol = {
tp match {
case TypeBounds(lo, _) =>
// check that lower bound is not an F-bound
// but carefully: class Foo[T <: Bar[_ >: T]] should be allowed
for (tp1 @ TypeRef(_, sym, _) <- lo) {
if (settings.breakCycles.value) {
if (!sym.maybeInitialize) {
log(s"Cycle inspecting $lo for possible f-bounds: ${sym.fullLocationString}")
return sym
}
}
else sym.initialize
}
case _ =>
}
NoSymbol
}
def monoTypeCompleter(tree: MemberDef) = new MonoTypeCompleter(tree)
class MonoTypeCompleter(tree: MemberDef) extends TypeCompleterBase(tree) {
override def completeImpl(sym: Symbol): Unit = {
// this early test is there to avoid infinite baseTypes when
// adding setters and getters --> bug798
// It is a def in an attempt to provide some insulation against
// uninitialized symbols misleading us. It is not a certainty
// this accomplishes anything, but performance is a non-consideration
// on these flag checks so it can't hurt.
def needsCycleCheck = sym.isNonClassType && !sym.isParameter && !sym.isExistential
val annotations = annotSig(tree.mods.annotations, tree, _ => true)
val tp = typeSig(tree, annotations)
findCyclicalLowerBound(tp) andAlso { sym =>
if (needsCycleCheck) {
// neg/t1224: trait C[T] ; trait A { type T >: C[T] <: C[C[T]] }
// To avoid an infinite loop on the above, we cannot break all cycles
log(s"Reinitializing info of $sym to catch any genuine cycles")
sym reset sym.info
sym.initialize
}
}
sym.setInfo(if (!sym.isJavaDefined) tp else RestrictJavaArraysMap(tp))
if (needsCycleCheck) {
log(s"Needs cycle check: ${sym.debugLocationString}")
if (!typer.checkNonCyclic(tree.pos, tp))
sym setInfo ErrorType
}
validate(sym)
}
}
def moduleClassTypeCompleter(tree: ModuleDef) = new ModuleClassTypeCompleter(tree)
class ModuleClassTypeCompleter(tree: ModuleDef) extends TypeCompleterBase(tree) {
override def completeImpl(sym: Symbol): Unit = {
val moduleSymbol = tree.symbol
assert(moduleSymbol.moduleClass == sym, moduleSymbol.moduleClass)
moduleSymbol.info // sets moduleClass info as a side effect.
}
}
def importTypeCompleter(tree: Import) = new ImportTypeCompleter(tree)
class ImportTypeCompleter(imp: Import) extends TypeCompleterBase(imp) {
override def completeImpl(sym: Symbol): Unit = {
sym setInfo importSig(imp)
}
}
import AnnotationInfo.{mkFilter => annotationFilter}
def implicitFactoryMethodCompleter(tree: DefDef, classSym: Symbol) = new CompleterWrapper(completerOf(tree)) {
override def complete(methSym: Symbol): Unit = {
super.complete(methSym)
val annotations = classSym.initialize.annotations
methSym setAnnotations (annotations filter annotationFilter(MethodTargetClass, defaultRetention = false))
classSym setAnnotations (annotations filter annotationFilter(ClassTargetClass, defaultRetention = true))
}
}
// complete the type of a value definition (may have a method symbol, for those valdefs that never receive a field,
// as specified by Field.noFieldFor)
def valTypeCompleter(tree: ValDef) = new ValTypeCompleter(tree)
class ValTypeCompleter(tree: ValDef) extends TypeCompleterBase(tree) {
override def completeImpl(fieldOrGetterSym: Symbol): Unit = {
val mods = tree.mods
val isGetter = fieldOrGetterSym.isMethod
val annots =
if (mods.annotations.isEmpty) Nil
else {
// if this is really a getter, retain annots targeting either field/getter
val pred: AnnotationInfo => Boolean =
if (isGetter) accessorAnnotsFilter(tree.mods)
else annotationFilter(FieldTargetClass, !mods.isParamAccessor)
annotSig(mods.annotations, tree, pred)
}
// must use typeSig, not memberSig (TODO: when do we need to switch namers?)
val sig = typeSig(tree, annots)
fieldOrGetterSym setInfo (if (isGetter) NullaryMethodType(sig) else sig)
checkBeanAnnot(tree, annots)
validate(fieldOrGetterSym)
}
}
// knowing `isBean`, we could derive `isSetter` from `valDef.name`
def accessorTypeCompleter(valDef: ValDef, missingTpt: Boolean, isBean: Boolean, isSetter: Boolean) = new AccessorTypeCompleter(valDef, missingTpt, isBean, isSetter)
class AccessorTypeCompleter(valDef: ValDef, missingTpt: Boolean, isBean: Boolean, isSetter: Boolean) extends TypeCompleterBase(valDef) {
override def completeImpl(accessorSym: Symbol): Unit = {
context.unit.synthetics get accessorSym match {
case Some(ddef: DefDef) =>
// `accessorSym` is the accessor for which we're completing the info (tree == ddef),
// while `valDef` is the field definition that spawned the accessor
// NOTE: `valTypeCompleter` handles abstract vals, trait vals and lazy vals, where the ValDef carries the getter's symbol
valDef.symbol.rawInfo match {
case c: ValTypeCompleter =>
// If the field and accessor symbols are distinct, i.e., we're not in a trait, invoke the
// valTypeCompleter. This ensures that field annotations are set correctly (scala/bug#10471).
c.completeImpl(valDef.symbol)
case _ =>
}
val valSig =
if (valDef.symbol.isInitialized) valDef.symbol.info // re-use an already computed type
else typeSig(valDef, Nil) // Don't pass any annotations to set on the valDef.symbol, just compute the type sig (TODO: dig deeper and see if we can use memberSig)
// patch up the accessor's tree if the valdef's tpt was not known back when the tree was synthesized
// can't look at `valDef.tpt` here because it may have been completed by now (this is why we pass in `missingTpt`)
// HACK: a param accessor `ddef.tpt.tpe` somehow gets out of whack with `accessorSym.info`, so always patch it back...
// (the tpt is typed in the wrong namer, using the class as owner instead of the outer context, which is where param accessors should be typed)
if (missingTpt || accessorSym.isParamAccessor) {
if (!isSetter) ddef.tpt setType valSig
else if (ddef.vparamss.nonEmpty && ddef.vparamss.head.nonEmpty) ddef.vparamss.head.head.tpt setType valSig
else throw new TypeError(valDef.pos, s"Internal error: could not complete parameter/return type for $ddef from $accessorSym")
}
val mods = valDef.mods
val annots =
if (mods.annotations.isEmpty) Nil
else annotSig(mods.annotations, valDef, accessorAnnotsFilter(valDef.mods, isSetter, isBean))
// for a setter, call memberSig to attribute the parameter (for a bean, we always use the regular method sig completer since they receive method types)
// for a regular getter, make sure it gets a NullaryMethodType (also, no need to recompute it: we already have the valSig)
val sig =
if (isSetter || isBean) typeSig(ddef, annots)
else {
if (annots.nonEmpty) annotate(accessorSym, annots)
NullaryMethodType(valSig)
}