forked from scala/scala
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Typers.scala
6373 lines (5753 loc) · 310 KB
/
Typers.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
package tools.nsc
package typechecker
import scala.annotation.tailrec
import scala.collection.mutable
import scala.reflect.internal.{Chars, TypesStats}
import scala.reflect.internal.util.{FreshNameCreator, ListOfNil, Statistics}
import scala.tools.nsc.Reporting.{MessageFilter, Suppression, WConf, WarningCategory}
import scala.util.chaining._
import mutable.ListBuffer
import symtab.Flags._
import Mode._
/** A provider of methods to assign types to trees.
*
* @author Martin Odersky
*/
trait Typers extends Adaptations with Tags with TypersTracking with PatternTypers {
self: Analyzer =>
import global._
import definitions._
import statistics._
final def forArgMode(fun: Tree, mode: Mode) =
if (treeInfo.isSelfOrSuperConstrCall(fun)) mode | SCCmode else mode
final val shortenImports = false
// All typechecked RHS of ValDefs for right-associative operator desugaring
private val rightAssocValDefs = new mutable.AnyRefMap[Symbol, Tree]
// Symbols of ValDefs for right-associative operator desugaring which are passed by name and have been inlined
private val inlinedRightAssocValDefs = new mutable.HashSet[Symbol]
// For each class, we collect a mapping from constructor param accessors that are aliases of their superclass
// param accessors. At the end of the typer phase, when this information is available all the way up the superclass
// chain, this is used to determine which are true aliases, ones where the field can be elided from this class.
// And yes, if you were asking, this is yet another binary fragility, as we bake knowledge of the super class into
// this class.
private val superConstructorCalls: mutable.AnyRefMap[Symbol, collection.Map[Symbol, Symbol]] = perRunCaches.newAnyRefMap()
// allows override of the behavior of the resetTyper method w.r.t comments
def resetDocComments() = clearDocComments()
def resetTyper(): Unit = {
//println("resetTyper called")
resetContexts()
resetImplicits()
resetDocComments()
rightAssocValDefs.clear()
inlinedRightAssocValDefs.clear()
superConstructorCalls.clear()
}
sealed abstract class SilentResult[+T] {
def isEmpty: Boolean
def nonEmpty = !isEmpty
@inline final def fold[U](none: => U)(f: T => U): U = this match {
case SilentResultValue(value) => f(value)
case _ => none
}
@inline final def map[U](f: T => U): SilentResult[U] = this match {
case SilentResultValue(value) => SilentResultValue(f(value))
case x: SilentTypeError => x
}
@inline final def filter(p: T => Boolean): SilentResult[T] = this match {
case SilentResultValue(value) if !p(value) => SilentTypeError(TypeErrorWrapper(new TypeError(NoPosition, "!p")))
case _ => this
}
@inline final def orElse[T1 >: T](f: Seq[AbsTypeError] => T1): T1 = this match {
case SilentResultValue(value) => value
case s : SilentTypeError => f(s.reportableErrors)
}
}
class SilentTypeError private(val errors: List[AbsTypeError], val warnings: List[(Position, String, WarningCategory, Symbol)]) extends SilentResult[Nothing] {
override def isEmpty = true
def err: AbsTypeError = errors.head
def reportableErrors = errors match {
case (e1: AmbiguousImplicitTypeError) :: _ =>
List(e1) // DRYer error reporting for neg/t6436b.scala
case all =>
all
}
}
object SilentTypeError {
def apply(errors: AbsTypeError*): SilentTypeError = apply(errors.toList, Nil)
def apply(errors: List[AbsTypeError], warnings: List[(Position, String, WarningCategory, Symbol)]): SilentTypeError = new SilentTypeError(errors, warnings)
// todo: this extracts only one error, should be a separate extractor.
def unapply(error: SilentTypeError): Option[AbsTypeError] = error.errors.headOption
}
// todo: should include reporter warnings in SilentResultValue.
// e.g. tryTypedApply could print warnings on arguments when the typing succeeds.
case class SilentResultValue[+T](value: T) extends SilentResult[T] { override def isEmpty = false }
def newTyper(context: Context): Typer = new NormalTyper(context)
private class NormalTyper(context : Context) extends Typer(context)
// A transient flag to mark members of anonymous classes
// that are turned private by typedBlock
private final val SYNTHETIC_PRIVATE = TRANS_FLAG
private final val InterpolatorCodeRegex = """\$\{\s*(.*?)\s*\}""".r
private final val InterpolatorIdentRegex = """\$[$\w]+""".r // note that \w doesn't include $
/** Check that type of given tree does not contain local or private
* components.
*/
object checkNoEscaping extends TypeMap {
private var owner: Symbol = _
private var scope: Scope = _
private var hiddenSymbols: List[Symbol] = _
/** Check that type `tree` does not refer to private
* components unless itself is wrapped in something private
* (`owner` tells where the type occurs).
*/
def privates[T <: Tree](typer: Typer, owner: Symbol, tree: T): T =
if (owner.isJavaDefined) tree else check(typer, owner, EmptyScope, WildcardType, tree)
@tailrec
private def check[T <: Tree](typer: Typer, owner: Symbol, scope: Scope, pt: Type, tree: T): T = {
this.owner = owner
this.scope = scope
hiddenSymbols = Nil
import typer.TyperErrorGen._
val tp1 = apply(tree.tpe)
if (hiddenSymbols.isEmpty) tree setType tp1
else if (hiddenSymbols exists (_.isErroneous)) HiddenSymbolWithError(tree)
else if (isFullyDefined(pt)) tree setType pt
else if (tp1.typeSymbol.isAnonymousClass)
check(typer, owner, scope, pt, tree setType tp1.typeSymbol.classBound)
else if (owner == NoSymbol)
tree setType packSymbols(hiddenSymbols.reverse, tp1)
else if (!isPastTyper) { // privates
val badSymbol = hiddenSymbols.head
SymbolEscapesScopeError(tree, badSymbol)
} else tree
}
def addHidden(sym: Symbol) =
if (!(hiddenSymbols contains sym)) hiddenSymbols = sym :: hiddenSymbols
override def apply(t: Type): Type = {
def checkNoEscape(sym: Symbol): Unit = {
if (sym.isPrivate && !sym.hasFlag(SYNTHETIC_PRIVATE)) {
var o = owner
while (o != NoSymbol && o != sym.owner && o != sym.owner.linkedClassOfClass &&
!o.isLocalToBlock && !o.isPrivate &&
!o.privateWithin.hasTransOwner(sym.owner))
o = o.owner
if (o == sym.owner || o == sym.owner.linkedClassOfClass)
addHidden(sym)
} else if (sym.owner.isTerm && !sym.isTypeParameterOrSkolem) {
var e = scope.lookupEntry(sym.name)
var found = false
while (!found && (e ne null) && e.owner == scope) {
if (e.sym == sym) {
found = true
addHidden(sym)
} else {
e = scope.lookupNextEntry(e)
}
}
}
}
mapOver(
t match {
case TypeRef(_, sym, args) =>
checkNoEscape(sym)
if (!hiddenSymbols.isEmpty && hiddenSymbols.head == sym &&
sym.isAliasType && sameLength(sym.typeParams, args)) {
hiddenSymbols = hiddenSymbols.tail
t.dealias
} else t
case SingleType(_, sym) =>
checkNoEscape(sym)
t
case _ =>
t
})
}
}
private final val typerFreshNameCreators = perRunCaches.newAnyRefMap[Symbol, FreshNameCreator]()
def freshNameCreatorFor(context: Context) = typerFreshNameCreators.getOrElseUpdate(context.outermostContextAtCurrentPos.enclClassOrMethod.owner, new FreshNameCreator)
abstract class Typer(context0: Context) extends TyperDiagnostics with Adaptation with Tag with PatternTyper with TyperContextErrors {
private def unit = context.unit
import typeDebug.ptTree
import TyperErrorGen._
implicit def fresh: FreshNameCreator = freshNameCreatorFor(context)
private def transformed: mutable.Map[Tree, Tree] = unit.transformed
val infer = new Inferencer {
def context = Typer.this.context
// See scala/bug#3281 re undoLog
override def isCoercible(tp: Type, pt: Type) = undoLog undo viewExists(tp, pt)
}
/** Overridden to false in scaladoc and/or interactive. */
def canAdaptConstantTypeToLiteral = true
def canTranslateEmptyListToNil = true
def missingSelectErrorTree(tree: Tree, qual: Tree, name: Name): Tree = tree
// used to exempt synthetic accessors (i.e. those that are synthesized by the compiler to access a field)
// from skolemization because there's a weird bug that causes spurious type mismatches
// (it seems to have something to do with existential abstraction over values
// https://github.com/scala/scala-dev/issues/165
// when we're past typer, lazy accessors are synthetic, but before they are user-defined
// to make this hack less hacky, we could rework our flag assignment to allow for
// requiring both the ACCESSOR and the SYNTHETIC bits to trigger the exemption
private def isSyntheticAccessor(sym: Symbol) = sym.isAccessor && (!sym.isLazy || isPastTyper)
// when type checking during erasure, generate erased types in spots that aren't transformed by erasure
// (it erases in TypeTrees, but not in, e.g., the type a Function node)
def phasedAppliedType(sym: Symbol, args: List[Type]) = {
val tp = appliedType(sym, args)
if (phase.erasedTypes) erasure.specialScalaErasureFor(sym)(tp) else tp
}
def typedDocDef(docDef: DocDef, mode: Mode, pt: Type): Tree =
typed(docDef.definition, mode, pt)
/** Find implicit arguments and pass them to given tree.
*/
def applyImplicitArgs(fun: Tree): Tree = fun.tpe match {
case MethodType(params, _) =>
val argResultsBuff = new ListBuffer[SearchResult]()
val argBuff = new ListBuffer[Tree]()
// paramFailed cannot be initialized with params.exists(_.tpe.isError) because that would
// hide some valid errors for params preceding the erroneous one.
var paramFailed = false
var mkArg: (Name, Tree) => Tree = (_, tree) => tree
// DEPMETTODO: instantiate type vars that depend on earlier implicit args (see adapt (4.1))
//
// apply the substitutions (undet type param -> type) that were determined
// by implicit resolution of implicit arguments on the left of this argument
for(param <- params) {
var paramTp = param.tpe
for(ar <- argResultsBuff)
paramTp = paramTp.subst(ar.subst.from, ar.subst.to)
val res =
if (paramFailed || (paramTp.isErroneous && {paramFailed = true; true})) SearchFailure
else inferImplicitFor(paramTp, fun, context, reportAmbiguous = context.reportErrors)
argResultsBuff += res
if (res.isSuccess) {
argBuff += mkArg(param.name, res.tree)
} else {
mkArg = gen.mkNamedArg // don't pass the default argument (if any) here, but start emitting named arguments for the following args
if (!param.hasDefault && !paramFailed) {
context.reporter.reportFirstDivergentError(fun, param, paramTp)(context)
paramFailed = true
}
/* else {
TODO: alternative (to expose implicit search failure more) -->
resolve argument, do type inference, keep emitting positional args, infer type params based on default value for arg
for (ar <- argResultsBuff) ar.subst traverse defaultVal
val targs = exprTypeArgs(context.undetparams, defaultVal.tpe, paramTp)
substExpr(tree, tparams, targs, pt)
}*/
}
}
val args = argBuff.toList
for (ar <- argResultsBuff) {
ar.subst traverse fun
for (arg <- args) ar.subst traverse arg
}
new ApplyToImplicitArgs(fun, args) setPos fun.pos
case ErrorType =>
fun
case x => throw new MatchError(x)
}
def viewExists(from: Type, to: Type): Boolean = (
!from.isError
&& !to.isError
&& context.implicitsEnabled
&& (inferView(context.tree, from, to, reportAmbiguous = false) != EmptyTree)
// scala/bug#8230 / scala/bug#8463 We'd like to change this to `saveErrors = false`, but can't.
// For now, we can at least pass in `context.tree` rather then `EmptyTree` so as
// to avoid unpositioned type errors.
)
// Get rid of any special ProtoTypes, so that implicit search won't have to deal with them
private def normalizeProtoForView(proto: Type): Type = proto match {
case proto: OverloadedArgProto => proto.underlying
case pt => pt
}
/** Infer an implicit conversion (`view`) between two types.
* @param tree The tree which needs to be converted.
* @param from The source type of the conversion
* @param to The target type of the conversion
* @param reportAmbiguous Should ambiguous implicit errors be reported?
* False iff we search for a view to find out
* whether one type is coercible to another.
* @param saveErrors Should ambiguous and divergent implicit errors that were buffered
* during the inference of a view be put into the original buffer.
* False iff we don't care about them.
*/
def inferView(tree: Tree, from: Type, to: Type, reportAmbiguous: Boolean = true, saveErrors: Boolean = true): Tree =
if (isPastTyper || from.isInstanceOf[MethodType] || from.isInstanceOf[OverloadedType] || from.isInstanceOf[PolyType]) EmptyTree
else {
debuglog(s"Inferring view from $from to $to for $tree (reportAmbiguous= $reportAmbiguous, saveErrors=$saveErrors)")
val fromNoAnnot = from.withoutAnnotations
val toNorm = normalizeProtoForView(to)
val result = inferImplicitView(fromNoAnnot, toNorm, tree, context, reportAmbiguous, saveErrors) match {
case fail if fail.isFailure => inferImplicitView(byNameType(fromNoAnnot), toNorm, tree, context, reportAmbiguous, saveErrors)
case ok => ok
}
if (result.subst != EmptyTreeTypeSubstituter) {
result.subst traverse tree
notifyUndetparamsInferred(result.subst.from, result.subst.to)
}
result.tree
}
import infer._
private var namerCache: Namer = null
def namer: Namer = {
if ((namerCache eq null) || namerCache.context != context)
namerCache = newNamer(context)
namerCache
}
var context = context0
def context1 = context
def dropExistential(tp: Type): Type = tp match {
case ExistentialType(tparams, _) =>
new SubstWildcardMap(tparams).apply(tp)
case TypeRef(_, sym, _) if sym.isAliasType =>
val tp0 = tp.dealias
if (tp eq tp0) {
devWarning(s"dropExistential did not progress dealiasing $tp, see scala/bug#7126")
tp
} else {
val tp1 = dropExistential(tp0)
if (tp1 eq tp0) tp else tp1
}
case _ => tp
}
private def errorNotClass(tpt: Tree, found: Type) = { ClassTypeRequiredError(tpt, found); false }
private def errorNotStable(tpt: Tree, found: Type) = { TypeNotAStablePrefixError(tpt, found); false }
/** Check that `tpt` refers to a non-refinement class or module type */
def checkClassOrModuleType(tpt: Tree): Boolean = {
val tpe = unwrapToClass(tpt.tpe)
def isModule = tpe match {
case SingleType(_, sym) => sym.isModule
case _ => false
}
isNonRefinementClassType(tpe) || isModule || errorNotClass(tpt, tpe)
}
/** Check that `tpt` refers to a class type with a stable prefix. */
def checkStablePrefixClassType(tpt: Tree): Boolean = {
val tpe = unwrapToStableClass(tpt.tpe)
def prefixIsStable = {
def checkPre = tpe match {
case TypeRef(pre, _, _) => pre.isStable || errorNotStable(tpt, pre)
case _ => false
}
// A type projection like X#Y can get by the stable check if the
// prefix is singleton-bounded, so peek at the tree too.
def checkTree = tpt match {
case SelectFromTypeTree(qual, _) => isSingleType(qual.tpe) || errorNotClass(tpt, tpe)
case _ => true
}
checkPre && checkTree
}
( (isNonRefinementClassType(tpe) || errorNotClass(tpt, tpe))
&& (isPastTyper || prefixIsStable)
)
}
/** Check that type `tp` is not a subtype of itself.
*/
def checkNonCyclic(pos: Position, tp: Type): Boolean = {
def checkNotLocked(sym: Symbol) = {
sym.initialize.lockOK || { CyclicAliasingOrSubtypingError(pos, sym); false }
}
tp match {
case TypeRef(pre, sym, args) =>
checkNotLocked(sym) &&
((!sym.isNonClassType) || checkNonCyclic(pos, appliedType(pre.memberInfo(sym), args), sym))
// @M! info for a type ref to a type parameter now returns a polytype
// @M was: checkNonCyclic(pos, pre.memberInfo(sym).subst(sym.typeParams, args), sym)
case SingleType(_, sym) =>
checkNotLocked(sym)
case st: SubType =>
checkNonCyclic(pos, st.supertype)
case ct: CompoundType =>
ct.parents forall (x => checkNonCyclic(pos, x))
case _ =>
true
}
}
def checkNonCyclic(pos: Position, tp: Type, lockedSym: Symbol): Boolean = try {
if (!lockedSym.lock(CyclicReferenceError(pos, tp, lockedSym))) false
else checkNonCyclic(pos, tp)
} finally {
lockedSym.unlock()
}
def checkNonCyclic(sym: Symbol): Unit = {
if (!checkNonCyclic(sym.pos, sym.tpe_*)) sym.setInfo(ErrorType)
}
def checkNonCyclic(defn: Tree, tpt: Tree): Unit = {
if (!checkNonCyclic(defn.pos, tpt.tpe, defn.symbol)) {
tpt setType ErrorType
defn.symbol.setInfo(ErrorType)
}
}
def reenterValueParams(vparamss: List[List[ValDef]]): Unit = {
for (vparams <- vparamss)
for (vparam <- vparams)
context.scope enter vparam.symbol
}
def reenterTypeParams(tparams: List[TypeDef]): List[Symbol] =
for (tparam <- tparams) yield {
context.scope enter tparam.symbol
tparam.symbol.deSkolemize
}
/** The qualifying class
* of a this or super with prefix `qual`.
* packageOk is equal false when qualifying class symbol
*/
def qualifyingClass(tree: Tree, qual: Name, packageOK: Boolean, immediate: Boolean) =
context.enclClass.owner.ownersIterator.find(o => qual.isEmpty || o.isClass && o.name == qual) match {
case Some(c) if packageOK || !c.isPackageClass => c
case _ =>
QualifyingClassError(tree, qual)
// Delay `setError` in namer, scala/bug#10748
if (immediate) setError(tree) else unit.toCheck += (() => setError(tree))
NoSymbol
}
/** The typer for an expression, depending on where we are. If we are before a superclass
* call, this is a typer over a constructor context; otherwise it is the current typer.
*/
final def constrTyperIf(inConstr: Boolean): Typer =
if (inConstr) {
assert(context.undetparams.isEmpty, context.undetparams)
newTyper(context.makeConstructorContext)
} else this
@inline
final def withCondConstrTyper[T](inConstr: Boolean)(f: Typer => T): T =
if (inConstr) {
assert(context.undetparams.isEmpty, context.undetparams)
val c = context.makeConstructorContext
typerWithLocalContext(c)(f)
} else {
f(this)
}
@inline
final def typerWithCondLocalContext[T](c: => Context)(cond: Boolean)(f: Typer => T): T =
if (cond) typerWithLocalContext(c)(f) else f(this)
@inline
final def typerWithLocalContext[T](c: Context)(f: Typer => T): T = {
try f(newTyper(c))
finally c.reporter.propagateErrorsTo(context.reporter)
}
/** The typer for a label definition. If this is part of a template we
* first have to enter the label definition.
*/
def labelTyper(ldef: LabelDef): Typer =
if (ldef.symbol == NoSymbol) { // labeldef is part of template
val typer1 = newTyper(context.makeNewScope(ldef, context.owner))
typer1.enterLabelDef(ldef)
typer1
} else this
/** Is symbol defined and not stale?
*/
def reallyExists(sym: Symbol) = {
if (isStale(sym)) sym.setInfo(NoType)
sym.exists
}
/** A symbol is stale if it is toplevel, to be loaded from a classfile, and
* the classfile is produced from a sourcefile which is compiled in the current run.
*/
def isStale(sym: Symbol): Boolean = {
sym.rawInfo.isInstanceOf[loaders.ClassfileLoader] && {
sym.rawInfo.load(sym)
(sym.sourceFile ne null) &&
(currentRun.compiledFiles contains sym.sourceFile.path)
}
}
/** Does the context of tree `tree` require a stable type?
*/
private def isStableContext(tree: Tree, mode: Mode, pt: Type) = {
def ptSym = pt.typeSymbol
def expectsStable = (
pt.isStable
|| mode.inQualMode && !tree.symbol.isConstant
|| !(tree.tpe <:< pt) && (ptSym.isAbstractType && pt.lowerBound.isStable || ptSym.isRefinementClass)
)
( isNarrowable(tree.tpe)
&& mode.typingExprNotLhs
&& expectsStable
)
}
/** Make symbol accessible. This means:
* If symbol refers to package object, insert `.package` as second to last selector.
* (exception for some symbols in scala package which are dealiased immediately)
* Call checkAccessible, which sets tree's attributes.
* Also note that checkAccessible looks up sym on pre without checking that pre is well-formed
* (illegal type applications in pre will be skipped -- that's why typedSelect wraps the resulting tree in a TreeWithDeferredChecks)
* @return modified tree and new prefix type
*/
private def makeAccessible(tree: Tree, sym: Symbol, pre: Type, site: Tree): Any /*Type | (Tree, Type)*/ =
if (!unit.isJava && context.isInPackageObject(sym, pre.typeSymbol)) {
val qual = typedQualifier { atPos(tree.pos.makeTransparent) {
tree match {
case Ident(_) =>
val packageObject =
if (!sym.isOverloaded && sym.owner.isModuleClass) sym.owner.sourceModule // historical optimization, perhaps no longer needed
else pre.typeSymbol.packageObject
Ident(packageObject)
case Select(qual, _) => Select(qual, nme.PACKAGEkw)
case SelectFromTypeTree(qual, _) => Select(qual, nme.PACKAGEkw)
case x => throw new MatchError(x)
}
}}
val tree1 = atPos(tree.pos) {
tree match {
case Ident(name) => Select(qual, name)
case Select(_, name) => Select(qual, name)
case SelectFromTypeTree(_, name) => SelectFromTypeTree(qual, name)
case x => throw new MatchError(x)
}
}
(checkAccessible(tree1, sym, qual.tpe, qual, unit.isJava), qual.tpe)
} else {
checkAccessible(tree, sym, pre, site, unit.isJava)
}
/** Post-process an identifier or selection node, performing the following:
* 1. Check that non-function pattern expressions are stable (ignoring volatility concerns -- scala/bug#6815)
* (and narrow the type of modules: a module reference in a pattern has type Foo.type, not "object Foo")
* 2. Check that packages and static modules are not used as values
* 3. Turn tree type into stable type if possible and required by context.
* 4. Give getClass calls a more precise type based on the type of the target of the call.
*/
protected def stabilize(tree: Tree, pre: Type, mode: Mode, pt: Type): Tree = {
// Side effect time! Don't be an idiot like me and think you
// can move "val sym = tree.symbol" before this line, because
// inferExprAlternative side-effects the tree's symbol.
if (tree.symbol.isOverloaded && !mode.inFunMode)
inferExprAlternative(tree, pt)
val sym = tree.symbol
val isStableIdPattern = mode.typingPatternNotConstructor && tree.isTerm
def isModuleTypedExpr = (
treeInfo.admitsTypeSelection(tree)
&& (isStableContext(tree, mode, pt) || sym.isModuleNotMethod)
)
def isStableValueRequired = (
isStableIdPattern
|| mode.in(all = EXPRmode, none = QUALmode) && !phase.erasedTypes
)
// To fully benefit from special casing the return type of
// getClass, we have to catch it immediately so expressions like
// x.getClass().newInstance() are typed with the type of x. TODO: If the
// type of the qualifier is inaccessible, we can cause private types to
// escape scope here, e.g. pos/t1107. I'm not sure how to properly handle
// this so for now it requires the type symbol be public.
def isGetClassCall = isGetClass(sym) && pre.typeSymbol.isPublic
def narrowIf(tree: Tree, condition: Boolean) =
if (condition) tree setType singleType(pre, sym) else tree
def checkStable(tree: Tree): Tree =
if (treeInfo.isStableIdentifierPattern(tree)) tree
else UnstableTreeError(tree)
if (tree.isErrorTyped)
tree
else if (!sym.isValue && isStableValueRequired) // (2)
NotAValueError(tree, sym)
else if (isStableIdPattern) // (1)
// A module reference in a pattern has type Foo.type, not "object Foo"
narrowIf(checkStable(tree), sym.isModuleNotMethod)
else if (isModuleTypedExpr) // (3)
narrowIf(tree, true)
else if (isGetClassCall) // (4)
tree setType MethodType(Nil, getClassReturnType(pre))
else
tree
}
private def isNarrowable(tpe: Type): Boolean = unwrapWrapperTypes(tpe) match {
case TypeRef(_, _, _) | RefinedType(_, _) => true
case _ => !phase.erasedTypes
}
def stabilizeFun(tree: Tree, mode: Mode, pt: Type): Tree = {
val sym = tree.symbol
val pre = tree match {
case Select(qual, _) => qual.tpe
case _ => NoPrefix
}
def stabilizable = (
pre.isStable
&& sym.tpe.params.isEmpty
&& (isStableContext(tree, mode, pt) || sym.isModule)
)
tree.tpe match {
case MethodType(_, _) if stabilizable => tree setType MethodType(Nil, singleType(pre, sym)) // TODO: should this be a NullaryMethodType?
case _ => tree
}
}
@deprecated("Use the overload accepting a Type.", "2.12.9")
def member(qual: Tree, name: Name): Symbol = member(qual.tpe, name)
/** The member with given name of given qualifier type */
def member(qual: Type, name: Name): Symbol = {
def callSiteWithinClass(clazz: Symbol) = context.enclClass.owner hasTransOwner clazz
val includeLocals = qual match {
case ThisType(clazz) if callSiteWithinClass(clazz) => true
case SuperType(clazz, _) if callSiteWithinClass(clazz.typeSymbol) => true
case _ => phase.next.erasedTypes
}
if (includeLocals) qual member name
else qual nonLocalMember name
}
def silent[T](op: Typer => T,
reportAmbiguousErrors: Boolean = context.ambiguousErrors,
newtree: Tree = context.tree): SilentResult[T] = {
val findMemberStart = if (settings.areStatisticsEnabled) statistics.startCounter(findMemberFailed) else null
val subtypeStart = if (settings.areStatisticsEnabled) statistics.startCounter(subtypeFailed) else null
val failedSilentStart = if (settings.areStatisticsEnabled) statistics.startTimer(failedSilentNanos) else null
def stopStats() = {
if (settings.areStatisticsEnabled) statistics.stopCounter(findMemberFailed, findMemberStart)
if (settings.areStatisticsEnabled) statistics.stopCounter(subtypeFailed, subtypeStart)
if (settings.areStatisticsEnabled) statistics.stopTimer(failedSilentNanos, failedSilentStart)
}
@inline def wrapResult(reporter: ContextReporter, result: T) =
if (reporter.hasErrors) {
stopStats()
SilentTypeError(reporter.errors.toList, reporter.warnings.toList)
} else SilentResultValue(result)
try {
if (context.reportErrors ||
reportAmbiguousErrors != context.ambiguousErrors ||
newtree != context.tree) {
val context1 = context.makeSilent(reportAmbiguousErrors, newtree)
context1.undetparams = context.undetparams
context1.savedTypeBounds = context.savedTypeBounds
context1.pendingStabilizers = context.pendingStabilizers
val typer1 = newTyper(context1)
val result = op(typer1)
context.undetparams = context1.undetparams
context.savedTypeBounds = context1.savedTypeBounds
context.pendingStabilizers = context1.pendingStabilizers
// If we have a successful result, emit any warnings it created.
if (!context1.reporter.hasErrors)
context1.reporter.emitWarnings()
wrapResult(context1.reporter, result)
} else {
assert(context.bufferErrors || isPastTyper, "silent mode is not available past typer")
context.reporter.withFreshErrorBuffer {
wrapResult(context.reporter, op(this))
}
}
} catch {
case ex: CyclicReference => throw ex
case ex: TypeError =>
// fallback in case TypeError is still thrown
// @H this happens for example in cps annotation checker
stopStats()
SilentTypeError(TypeErrorWrapper(ex))
}
}
/** Check whether feature given by `featureTrait` is enabled.
* If it is not, issue an error or a warning depending on whether the feature is required.
* @param construct A string expression that is substituted for "#" in the feature description string
* @param immediate When set, feature check is run immediately, otherwise it is run
* at the end of the typechecking run for the enclosing unit. This
* is done to avoid potential cyclic reference errors by implicits
* that are forced too early.
* @return if feature check is run immediately: true if feature is enabled, false otherwise
* if feature check is delayed or suppressed because we are past typer: true
*/
def checkFeature(pos: Position, featureTrait: Symbol, construct: => String = "", immediate: Boolean = false): Boolean =
isPastTyper || {
val nestedOwners =
featureTrait.owner.ownerChain.takeWhile(_ != languageFeatureModule.moduleClass).reverse
val featureName = nestedOwners.map(s => s"${s.name}.").mkString + featureTrait.name
def action(): Boolean = {
def hasImport = inferImplicitByType(featureTrait.tpe, context).isSuccess
def hasOption = settings.language.contains(featureName)
hasOption || hasImport || {
val Some(AnnotationInfo(_, List(Literal(Constant(featureDesc: String)), Literal(Constant(required: Boolean))), _)) =
featureTrait.getAnnotation(LanguageFeatureAnnot): @unchecked
context.featureWarning(pos, featureName, featureDesc, featureTrait, construct, required)
false
}
}
if (immediate) {
action()
} else {
unit.toCheck += (() => action(): Unit)
true
}
}
def checkExistentialsFeature(pos: Position, tpe: Type, prefix: String) = tpe match {
case extp: ExistentialType if !extp.isRepresentableWithWildcards && !tpe.isError =>
checkFeature(pos, currentRun.runDefinitions.ExistentialsFeature, prefix+" "+tpe)
case _ =>
}
/** Perform the following adaptations of expression, pattern or type `tree` wrt to
* given mode `mode` and given prototype `pt`:
* (-1) For expressions with annotated types, let AnnotationCheckers decide what to do
* (0) Convert expressions with constant types to literals (unless in interactive/scaladoc mode)
* (1) Resolve overloading, unless mode contains FUNmode
* (2) Apply parameterless functions
* (3) Apply polymorphic types to fresh instances of their type parameters and
* store these instances in context.undetparams,
* unless followed by explicit type application.
* (4) Do the following to unapplied methods used as values:
* (4.1) If the method has only implicit parameters, pass implicit arguments (see adaptToImplicitMethod)
* (4.2) otherwise, if the method is 0-ary and it can be auto-applied (see checkCanAutoApply), apply it to ()
* (4.3) otherwise, if the method is not a constructor, and can be eta-expanded (see checkCanEtaExpand), eta-expand
* otherwise issue an error
* (5) Convert constructors in a pattern as follows:
* (5.1) If constructor refers to a case class factory, set tree's type to the unique
* instance of its primary constructor that is a subtype of the expected type.
* (5.2) If constructor refers to an extractor, convert to application of
* unapply or unapplySeq method.
*
* (6) Convert all other types to TypeTree nodes.
* (7) When in TYPEmode but not FUNmode or HKmode, check that types are fully parameterized
* (7.1) In HKmode, higher-kinded types are allowed, but they must have the expected kind-arity
* (8) When in both EXPRmode and FUNmode, add apply method calls to values of object type.
* (9) If there are undetermined type variables and not POLYmode, infer expression instance
* Then, if tree's type is not a subtype of expected type, try the following adaptations:
* (10) If the expected type is Byte, Short or Char, and the expression
* is an integer fitting in the range of that type, convert it to that type.
* (11) Widen numeric literals to their expected type, if necessary
* (12) When in mode EXPRmode, convert E to { E; () } if expected type is scala.Unit.
* (13) When in mode EXPRmode, apply AnnotationChecker conversion if expected type is annotated.
* (14) When in mode EXPRmode, do SAM conversion
* (15) When in mode EXPRmode, apply a view
* If all this fails, error
*
* Note: the `original` tree parameter is for re-typing implicit method invocations (see below)
* and should not be used otherwise. TODO: can it be replaced with a tree attachment?
*/
protected def adapt(tree: Tree, mode: Mode, pt: Type, original: Tree = EmptyTree): Tree = {
def hasUndets = !context.undetparams.isEmpty
def hasUndetsInMonoMode = hasUndets && !mode.inPolyMode
def adaptToImplicitMethod(mt: MethodType): Tree = {
if (hasUndets) { // (9) -- should revisit dropped condition `hasUndetsInMonoMode`
// dropped so that type args of implicit method are inferred even if polymorphic expressions are allowed
// needed for implicits in 2.8 collection library -- maybe once #3346 is fixed, we can reinstate the condition?
context.undetparams = inferExprInstance(tree, context.extractUndetparams(), pt,
// approximate types that depend on arguments since dependency on implicit argument is like dependency on type parameter
mt.approximate,
keepNothings = false,
useWeaklyCompatible = true) // #3808
}
// avoid throwing spurious DivergentImplicit errors
if (context.reporter.hasErrors)
setError(tree)
else
withCondConstrTyper(treeInfo.isSelfOrSuperConstrCall(tree))(typer1 =>
if (original != EmptyTree && !pt.isWildcard) {
typer1 silent { tpr =>
val withImplicitArgs = tpr.applyImplicitArgs(tree)
if (tpr.context.reporter.hasErrors) tree // silent will wrap it in SilentTypeError anyway
else tpr.typed(withImplicitArgs, mode, pt)
} orElse { originalErrors =>
// Re-try typing (applying to implicit args) without expected type. Add in 53d98e7d42 to
// for better error message (scala/bug#2180, https://www.scala-lang.org/old/node/3453.html)
val resetTree = resetAttrs(original)
resetTree match {
case treeInfo.Applied(fun, _, _) =>
if (fun.symbol != null && fun.symbol.isError)
// scala/bug#9041 Without this, we leak error symbols past the typer!
// because the fallback typechecking notices the error-symbol,
// refuses to re-attempt typechecking, and presumes that someone
// else was responsible for issuing the related type error!
fun.setSymbol(NoSymbol)
case _ =>
}
debuglog(s"fallback on implicits: $tree/$resetTree")
// scala/bug#10066 Need to patch the enclosing tree in the context to make translation of Dynamic
// work during fallback typechecking below.
val resetContext: Context = {
object substResetForOriginal extends AstTransformer {
override def transform(tree: Tree): Tree = {
if (tree eq original) resetTree
else super.transform(tree)
}
}
context.make(substResetForOriginal.transform(context.tree))
}
typerWithLocalContext(resetContext) { typer1 =>
typer1.silent { typer1 =>
val tree1 = typer1.typed(resetTree, mode)
// Q: `typed` already calls `pluginsTyped` and `adapt`. the only difference here is that
// we pass `EmptyTree` as the `original`. intended? added in 2009 (53d98e7d42) by martin.
tree1 setType pluginsTyped(tree1.tpe, typer1, tree1, mode, pt)
if (tree1.isEmpty) tree1 else typer1.adapt(tree1, mode, pt, original = EmptyTree)
} orElse { _ =>
originalErrors.foreach(context.issue)
setError(tree)
}
}
}
}
else
typer1.typed(typer1.applyImplicitArgs(tree), mode, pt)
)
}
def adaptMethodTypeToExpr(mt: MethodType): Tree = {
val meth =
tree match {
// a partial named application is a block (see comment in EtaExpansion)
// How about user-written blocks? Can they ever have a MethodType?
case Block(_, tree1) => tree1.symbol
case _ => tree.symbol
}
val arity = mt.params.length
def warnTree = original orElse tree
def warnEtaZero(): Boolean = {
if (!settings.warnEtaZero) return true
context.warning(tree.pos,
s"""An unapplied 0-arity method was eta-expanded (due to the expected type $pt), rather than applied to `()`.
|Write ${Apply(warnTree, Nil)} to invoke method ${meth.decodedName}, or change the expected type.""".stripMargin,
WarningCategory.LintEtaZero)
true
}
def warnEtaSam(): Boolean = {
if (!settings.warnEtaSam) return true
val sam = samOf(pt)
val samClazz = sam.owner
// TODO: we allow a Java class as a SAM type, whereas Java only allows the @FunctionalInterface on interfaces -- align?
if (sam.exists && (!samClazz.hasFlag(JAVA) || samClazz.hasFlag(INTERFACE)) && !samClazz.hasAnnotation(definitions.FunctionalInterfaceClass))
context.warning(tree.pos,
s"""Eta-expansion performed to meet expected type $pt, which is SAM-equivalent to ${samToFunctionType(pt)},
|even though $samClazz is not annotated with `@FunctionalInterface`;
|to suppress warning, add the annotation or write out the equivalent function literal.""".stripMargin,
WarningCategory.LintEtaSam)
true
}
// note that isFunctionProto(pt) does not work properly for Function0
lazy val ptUnderlying =
(pt match {
case oapt: OverloadedArgProto => oapt.underlying
case pt => pt
}).dealiasWiden
// (4.3) condition for eta-expansion by arity & -Xsource level
//
// for arity == 0:
// - if Function0 is expected -- SAM types do not eta-expand because it could be an accidental SAM scala/bug#9489
// for arity > 0:
// - 2.13: if function or sam type is expected
// - 3.0: unconditionally
//
// warnings:
// - for arity == 0: eta-expansion of zero-arg methods was deprecated (scala/bug#7187)
// - for arity > 0: expected type is a SAM that is not annotated with `@FunctionalInterface`
def checkCanEtaExpand(): Boolean = {
def expectingSamOfArity = {
val sam = samOf(ptUnderlying)
sam.exists && sam.info.params.lengthIs == arity
}
val expectingFunctionOfArity = {
val ptSym = ptUnderlying.typeSymbolDirect
(ptSym eq FunctionClass(arity)) || (arity > 0 && (ptSym eq FunctionClass(1))) // allowing for tupling conversion
}
if (arity == 0)
expectingFunctionOfArity && warnEtaZero()
else
expectingFunctionOfArity || expectingSamOfArity && warnEtaSam() || currentRun.isScala3
}
def matchNullaryLoosely: Boolean = {
def test(sym: Symbol) = sym.isJavaDefined || sym.owner == AnyClass
test(meth) || meth.overrides.exists(test)
}
// (4.2) condition for auto-application
//
// Currently the condition is more involved to give slack to Scala methods overriding Java-defined ones;
// I (moors) think we should resolve that by introducing slack in overriding e.g. a Java-defined `def toString()` by a Scala-defined `def toString`.
// This also works better for dealing with accessors overriding Java-defined methods. The current strategy in methodSig is problematic:
// > // Add a () parameter section if this overrides some method with () parameters
// > val vparamSymssOrEmptyParamsFromOverride =
// This means an accessor that overrides a Java-defined method gets a MethodType instead of a NullaryMethodType, which breaks lots of assumptions about accessors)
def checkCanAutoApply(): Boolean = {
if (!isPastTyper && !matchNullaryLoosely) {
context.deprecationWarning(tree.pos, NoSymbol, s"Auto-application to `()` is deprecated. Supply the empty argument list `()` explicitly to invoke method ${meth.decodedName},\n" +
s"or remove the empty argument list from its definition (Java-defined methods are exempt).\n"+
s"In Scala 3, an unapplied method like this will be eta-expanded into a function.", "2.13.3")
}
true
}
if (!meth.isConstructor && checkCanEtaExpand()) typedEtaExpansion(tree, mode, pt)
else if (arity == 0 && checkCanAutoApply()) {
val apply = Apply(tree, Nil).setPos(tree.pos).updateAttachment(AutoApplicationAttachment)
if (tree.hasAttachment[PostfixAttachment.type]) apply.updateAttachment(InfixAttachment)
adapt(typed(apply), mode, pt, original)
} else
if (context.implicitsEnabled) MissingArgsForMethodTpeError(tree, meth) // `context.implicitsEnabled` implies we are not in a pattern
else UnstableTreeError(tree)
}
def adaptType(): Tree = {
// @M When not typing a type constructor (!context.inTypeConstructorAllowed)
// or raw type, types must be of kind *,
// and thus parameterized types must be applied to their type arguments
// @M TODO: why do kind-* tree's have symbols, while higher-kinded ones don't?
def properTypeRequired = (
tree.hasSymbolField
&& !context.inTypeConstructorAllowed
&& !context.unit.isJava
)
// @M: don't check tree.tpe.symbol.typeParams. check tree.tpe.typeParams!!!
// (e.g., m[Int] --> tree.tpe.symbol.typeParams.length == 1, tree.tpe.typeParams.length == 0!)
// @M: removed check for tree.hasSymbolField and replace tree.symbol by tree.tpe.symbol
// (TypeTree's must also be checked here, and they don't directly have a symbol)
def kindArityMismatch = (
context.inTypeConstructorAllowed
&& !sameLength(tree.tpe.typeParams, pt.typeParams)
)
// Note that we treat Any and Nothing as kind-polymorphic.
// We can't perform this check when typing type arguments to an overloaded method before the overload is resolved
// (or in the case of an error type) -- this is indicated by pt == WildcardType (see case TypeApply in typed1).
def kindArityMismatchOk = tree.tpe.typeSymbol match {
case NothingClass | AnyClass => true
case _ => pt == WildcardType