/
Implicits.scala
1784 lines (1603 loc) · 75.6 KB
/
Implicits.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 backend.sjs.JSDefinitions
import core._
import ast.{Trees, TreeTypeMap, untpd, tpd, DesugarEnums}
import util.Spans._
import util.Stats.{record, monitored}
import printing.{Showable, Printer}
import printing.Texts._
import Contexts._
import Types._
import Flags._
import Mode.ImplicitsEnabled
import NameOps._
import NameKinds.{LazyImplicitName, EvidenceParamName}
import Symbols._
import Denotations._
import Types._
import Decorators._
import Names._
import StdNames._
import Constants._
import ProtoTypes._
import ErrorReporting._
import Inferencing.{fullyDefinedType, isFullyDefined}
import Trees._
import transform.SymUtils._
import transform.TypeUtils._
import Hashable._
import util.{SourceFile, NoSource, EqHashMap, Stats}
import config.{Config, Feature}
import Feature.migrateTo3
import config.Printers.{implicits, implicitsDetailed}
import collection.mutable
import reporting._
import annotation.tailrec
import scala.annotation.internal.sharable
import scala.annotation.threadUnsafe
/** Implicit resolution */
object Implicits:
import tpd._
/** An implicit definition `implicitRef` that is visible under a different name, `alias`.
* Gets generated if an implicit ref is imported via a renaming import.
*/
class RenamedImplicitRef(val underlyingRef: TermRef, val alias: TermName) extends ImplicitRef {
def implicitName(using Context): TermName = alias
}
/** Both search candidates and successes are references with a specific nesting level. */
sealed trait RefAndLevel {
def ref: TermRef
def level: Int
}
/** An eligible implicit candidate, consisting of an implicit reference and a nesting level */
case class Candidate(implicitRef: ImplicitRef, kind: Candidate.Kind, level: Int) extends RefAndLevel {
def ref: TermRef = implicitRef.underlyingRef
def isExtension = (kind & Candidate.Extension) != 0
def isConversion = (kind & Candidate.Conversion) != 0
}
object Candidate {
type Kind = Int
final val None = 0
final val Value = 1
final val Conversion = 2
final val Extension = 4
}
/** If `expected` is a selection prototype, does `tp` have an extension
* method with the selecting name? False otherwise.
*/
def hasExtMethod(tp: Type, expected: Type)(using Context) = expected match
case selProto @ SelectionProto(selName: TermName, _, _, _) =>
tp.memberBasedOnFlags(selName, required = ExtensionMethod).exists
case _ =>
false
def strictEquality(using Context): Boolean =
ctx.mode.is(Mode.StrictEquality) || Feature.enabled(nme.strictEquality)
/** A common base class of contextual implicits and of-type implicits which
* represents a set of references to implicit definitions.
*/
abstract class ImplicitRefs(initctx: Context) {
val irefCtx =
if (initctx == NoContext) initctx else initctx.retractMode(Mode.ImplicitsEnabled)
protected given Context = irefCtx
/** The nesting level of this context. Non-zero only in ContextialImplicits */
def level: Int = 0
/** The implicit references */
def refs: List[ImplicitRef]
/** If comes from an implicit scope of a type, the companion objects making
* up that implicit scope, otherwise the empty set.
*/
def companionRefs: TermRefSet = TermRefSet.empty
private var mySingletonClass: ClassSymbol = null
/** Widen type so that it is neither a singleton type nor a type that inherits from scala.Singleton. */
private def widenSingleton(tp: Type)(using Context): Type = {
if (mySingletonClass == null) mySingletonClass = defn.SingletonClass
val wtp = tp.widenSingleton
if (wtp.derivesFrom(mySingletonClass)) defn.AnyType else wtp
}
protected def isAccessible(ref: TermRef)(using Context): Boolean
/** Return those references in `refs` that are compatible with type `pt`. */
protected def filterMatching(pt: Type)(using Context): List[Candidate] = {
record("filterMatching")
val considerExtension = pt match
case ViewProto(_, _: SelectionProto) => true
case _ => false
def candidateKind(ref: TermRef)(using Context): Candidate.Kind = { /*trace(i"candidateKind $ref $pt")*/
def viewCandidateKind(tpw: Type, argType: Type, resType: Type): Candidate.Kind = {
def methodCandidateKind(mt: MethodType, approx: Boolean) =
if (mt.isImplicitMethod)
viewCandidateKind(normalize(mt, pt), argType, resType)
else if (mt.paramInfos.lengthCompare(1) == 0 && {
var formal = widenSingleton(mt.paramInfos.head)
if (approx) formal = wildApprox(formal)
explore(argType relaxed_<:< formal.widenExpr)
})
Candidate.Conversion
else
Candidate.None
tpw match {
case mt: MethodType =>
methodCandidateKind(mt, approx = false)
case poly: PolyType =>
// We do not need to call ProtoTypes#constrained on `poly` because
// `candidateKind` is always called with mode TypevarsMissContext enabled.
poly.resultType match {
case mt: MethodType =>
methodCandidateKind(mt, approx = true)
case rtp =>
viewCandidateKind(wildApprox(rtp), argType, resType)
}
case tpw: TermRef => // can't discard overloaded refs
Candidate.Conversion
| (if considerExtension then Candidate.Extension else Candidate.None)
case tpw =>
// Only direct instances of Function1 and direct or indirect instances of <:< are eligible as views.
// However, Predef.$conforms is not eligible, because it is a no-op.
//
// In principle, it would be cleanest if only implicit methods qualified
// as implicit conversions. We could achieve that by having standard conversions like
// this in Predef:
//
// implicit def convertIfConforms[A, B](x: A)(implicit ev: A <:< B): B = ev(a)
// implicit def convertIfConverter[A, B](x: A)(implicit ev: Conversion[A, B]): B = ev(a)
//
// (Once `<:<` inherits from `Conversion` we only need the 2nd one.)
// But clauses like this currently slow down implicit search a lot, because
// they are eligible for all pairs of types, and therefore are tried too often.
// We emulate instead these conversions directly in the search.
// The reason for leaving out `Predef_conforms` is that we know it adds
// nothing since it only relates subtype with supertype.
//
// We keep the old behavior under -source 3.0-migration.
val isFunctionInS2 =
migrateTo3
&& tpw.derivesFrom(defn.Function1)
&& ref.symbol != defn.Predef_conforms
val isImplicitConversion = tpw.derivesFrom(defn.ConversionClass)
// An implementation of <:< counts as a view
val isConforms = tpw.derivesFrom(defn.SubTypeClass)
val conversionKind =
if (isFunctionInS2 || isImplicitConversion || isConforms) Candidate.Conversion
else Candidate.None
val extensionKind =
if considerExtension && hasExtMethod(tpw, resType) then Candidate.Extension
else Candidate.None
conversionKind | extensionKind
}
}
def valueTypeCandidateKind(tpw: Type): Candidate.Kind = tpw.stripPoly match {
case tpw: MethodType =>
if (tpw.isImplicitMethod) Candidate.Value else Candidate.None
case _ =>
Candidate.Value
}
/** Widen singleton arguments of implicit conversions to their underlying type.
* This is necessary so that they can be found eligible for the argument type.
* Note that we always take the underlying type of a singleton type as the argument
* type, so that we get a reasonable implicit cache hit ratio.
*/
def adjustSingletonArg(tp: Type): Type = tp.widenSingleton match
case tp: PolyType =>
val res = adjustSingletonArg(tp.resType)
if res eq tp.resType then tp else tp.derivedLambdaType(resType = res)
case tp: MethodType =>
tp.derivedLambdaType(paramInfos = tp.paramInfos.mapConserve(widenSingleton))
case _ =>
tp.baseType(defn.ConversionClass) match
case app @ AppliedType(tycon, from :: rest) =>
val wideFrom = from.widenSingleton
if wideFrom ne from then app.derivedAppliedType(tycon, wideFrom :: rest)
else tp
case _ => tp
var ckind =
if !isAccessible(ref) then
Candidate.None
else pt match {
case pt: ViewProto =>
viewCandidateKind(ref.widen, pt.argType, pt.resType)
case _: ValueTypeOrProto =>
if (defn.isFunctionType(pt)) Candidate.Value
else valueTypeCandidateKind(ref.widen)
case _ =>
Candidate.Value
}
if (ckind == Candidate.None)
record("discarded eligible")
else {
val ptNorm = normalize(pt, pt) // `pt` could be implicit function types, check i2749
val refAdjusted =
if (pt.isInstanceOf[ViewProto]) adjustSingletonArg(ref)
else ref
val refNorm = normalize(refAdjusted, pt)
Stats.record("eligible check matches")
if (!NoViewsAllowed.isCompatible(refNorm, ptNorm))
ckind = Candidate.None
}
ckind
}
if refs.isEmpty && (!considerExtension || companionRefs.isEmpty) then
Nil
else
val candidates = new mutable.ListBuffer[Candidate]
def tryCandidate(extensionOnly: Boolean)(ref: ImplicitRef) =
var ckind = exploreInFreshCtx { (ctx: FreshContext) ?=>
ctx.setMode(ctx.mode &~ Mode.SafeNulls | Mode.TypevarsMissContext)
candidateKind(ref.underlyingRef)
}
if extensionOnly then ckind &= Candidate.Extension
if ckind != Candidate.None then
candidates += Candidate(ref, ckind, level)
if considerExtension then
companionRefs.foreach(tryCandidate(extensionOnly = true))
if refs.nonEmpty then
refs.foreach(tryCandidate(extensionOnly = false))
candidates.toList
}
}
/** The implicit references coming from the implicit scope of a type.
* @param tp the type determining the implicit scope
* @param companionRefs the companion objects in the implicit scope.
*/
class OfTypeImplicits(tp: Type, override val companionRefs: TermRefSet)(initctx: Context) extends ImplicitRefs(initctx) {
assert(initctx.typer != null)
implicits.println(i"implicit scope of type $tp = ${companionRefs.showAsList}%, %")
@threadUnsafe lazy val refs: List[ImplicitRef] = {
val buf = new mutable.ListBuffer[TermRef]
for (companion <- companionRefs) buf ++= companion.implicitMembers
buf.toList
}
/** The candidates that are eligible for expected type `tp` */
@threadUnsafe lazy val eligible: List[Candidate] =
trace(i"eligible($tp), companions = ${companionRefs.showAsList}%, %", implicitsDetailed, show = true) {
if (refs.nonEmpty && monitored) record(s"check eligible refs in tpe", refs.length)
filterMatching(tp)
}
override def isAccessible(ref: TermRef)(using Context): Boolean =
ref.symbol.exists && !ref.symbol.is(Private)
override def toString: String =
i"OfTypeImplicits($tp), companions = ${companionRefs.showAsList}%, %; refs = $refs%, %."
}
/** The implicit references coming from the context.
* @param refs the implicit references made visible by the current context.
* Note: The name of the reference might be different from the name of its symbol.
* In the case of a renaming import a => b, the name of the reference is the renamed
* name, b, whereas the name of the symbol is the original name, a.
* @param outerCtx the next outer context that makes visible further implicits
*/
class ContextualImplicits(
val refs: List[ImplicitRef],
val outerImplicits: ContextualImplicits,
isImport: Boolean)(initctx: Context) extends ImplicitRefs(initctx) {
private val eligibleCache = EqHashMap[Type, List[Candidate]]()
/** The level increases if current context has a different owner or scope than
* the context of the next-outer ImplicitRefs. This is however disabled under
* Scala2 mode, since we do not want to change the implicit disambiguation then.
*/
override val level: Int =
def isSameOwner = irefCtx.owner eq outerImplicits.irefCtx.owner
def isSameScope = irefCtx.scope eq outerImplicits.irefCtx.scope
def isLazyImplicit = refs.head.implicitName.is(LazyImplicitName)
if outerImplicits == null then 1
else if migrateTo3(using irefCtx)
|| isSameOwner && (isImport || isSameScope && !isLazyImplicit)
then outerImplicits.level
else outerImplicits.level + 1
end level
/** Is this the outermost implicits? This is the case if it either the implicits
* of NoContext, or the last one before it.
*/
private def isOuterMost = {
val finalImplicits = NoContext.implicits
(this eq finalImplicits) || (outerImplicits eq finalImplicits)
}
/** The implicit references that are eligible for type `tp`. */
def eligible(tp: Type): List[Candidate] =
if (tp.hash == NotCached)
Stats.record(i"compute eligible not cached ${tp.getClass}")
Stats.record(i"compute eligible not cached")
computeEligible(tp)
else {
val eligibles = eligibleCache.lookup(tp)
if (eligibles != null) {
Stats.record("cached eligible")
eligibles
}
else if (irefCtx eq NoContext) Nil
else {
Stats.record(i"compute eligible cached")
val result = computeEligible(tp)
eligibleCache(tp) = result
result
}
}
private def computeEligible(tp: Type): List[Candidate] = /*>|>*/ trace(i"computeEligible $tp in $refs%, %", implicitsDetailed) /*<|<*/ {
if (monitored) record(s"check eligible refs in irefCtx", refs.length)
val ownEligible = filterMatching(tp)
if (isOuterMost) ownEligible
else if ownEligible.isEmpty then outerImplicits.eligible(tp)
else
val outerEligible = outerImplicits.eligible(tp)
if outerEligible.isEmpty then ownEligible
else
val shadowed = ownEligible.map(_.ref.implicitName).toSet
ownEligible ::: outerEligible.filterConserve(cand => !shadowed.contains(cand.ref.implicitName))
}
override def isAccessible(ref: TermRef)(using Context): Boolean =
ref.symbol.isAccessibleFrom(ref.prefix)
override def toString: String = {
val own = i"(implicits: $refs%, %)"
if (isOuterMost) own else own + "\n " + outerImplicits
}
/** This context, or a copy, ensuring root import from symbol `root`
* is not present in outer implicits.
*/
def exclude(root: Symbol): ContextualImplicits =
if (this == NoContext.implicits) this
else {
val outerExcluded = outerImplicits exclude root
if (irefCtx.importInfo.site.termSymbol == root) outerExcluded
else if (outerExcluded eq outerImplicits) this
else new ContextualImplicits(refs, outerExcluded, isImport)(irefCtx)
}
}
/** The result of an implicit search */
sealed abstract class SearchResult extends Showable {
def tree: Tree
def toText(printer: Printer): Text = printer.toText(this)
def recoverWith(other: SearchFailure => SearchResult): SearchResult = this match {
case _: SearchSuccess => this
case fail: SearchFailure => other(fail)
}
def isSuccess: Boolean = isInstanceOf[SearchSuccess]
}
/** A successful search
* @param tree The typed tree that needs to be inserted
* @param ref The implicit reference that succeeded
* @param level The level where the reference was found
* @param isExtension Whether the result is an extension method application
* @param tstate The typer state to be committed if this alternative is chosen
*/
case class SearchSuccess(tree: Tree, ref: TermRef, level: Int, isExtension: Boolean = false)(val tstate: TyperState, val gstate: GadtConstraint)
extends SearchResult with RefAndLevel with Showable
/** A failed search */
case class SearchFailure(tree: Tree) extends SearchResult {
final def isAmbiguous: Boolean = tree.tpe.isInstanceOf[AmbiguousImplicits]
final def reason: SearchFailureType = tree.tpe.asInstanceOf[SearchFailureType]
}
object SearchFailure {
def apply(tpe: SearchFailureType, span: Span)(using Context): SearchFailure = {
val id = tpe match
case tpe: AmbiguousImplicits =>
untpd.SearchFailureIdent(nme.AMBIGUOUS, s"/* ambiguous: ${tpe.explanation} */")
case _ =>
untpd.SearchFailureIdent(nme.MISSING, "/* missing */")
SearchFailure(id.withTypeUnchecked(tpe).withSpan(span))
}
}
abstract class SearchFailureType extends ErrorType {
def expectedType: Type
def argument: Tree
/** A "massaging" function for displayed types to give better info in error diagnostics */
def clarify(tp: Type)(using Context): Type = tp
final protected def qualify(using Context): String = expectedType match {
case SelectionProto(name, mproto, _, _) if !argument.isEmpty =>
em"provide an extension method `$name` on ${argument.tpe}"
case NoType =>
if (argument.isEmpty) em"match expected type"
else em"convert from ${argument.tpe} to expected type"
case _ =>
if (argument.isEmpty) em"match type ${clarify(expectedType)}"
else em"convert from ${argument.tpe} to ${clarify(expectedType)}"
}
/** An explanation of the cause of the failure as a string */
def explanation(using Context): String
def msg(using Context): Message = explanation
/** If search was for an implicit conversion, a note describing the failure
* in more detail - this is either empty or starts with a '\n'
*/
def whyNoConversion(using Context): String = ""
}
class NoMatchingImplicits(val expectedType: Type, val argument: Tree, constraint: Constraint = OrderingConstraint.empty)
extends SearchFailureType {
/** Replace all type parameters in constraint by their bounds, to make it clearer
* what was expected
*/
override def clarify(tp: Type)(using Context): Type =
val ctx1 = ctx.fresh.setExploreTyperState()
ctx1.typerState.constraint = constraint
inContext(ctx1) {
val map = new TypeMap {
def apply(t: Type): Type = t match {
case t: TypeParamRef =>
constraint.entry(t) match {
case NoType => t
case bounds: TypeBounds => TypeComparer.fullBounds(t)
case t1 => t1
}
case t: TypeVar =>
t.instanceOpt.orElse(apply(t.origin))
case _ =>
mapOver(t)
}
}
map(tp)
}
def explanation(using Context): String =
em"no implicit values were found that $qualify"
override def toString = s"NoMatchingImplicits($expectedType, $argument)"
}
@sharable object NoMatchingImplicits extends NoMatchingImplicits(NoType, EmptyTree, OrderingConstraint.empty)
@sharable val NoMatchingImplicitsFailure: SearchFailure =
SearchFailure(NoMatchingImplicits, NoSpan)(using NoContext)
/** An ambiguous implicits failure */
class AmbiguousImplicits(val alt1: SearchSuccess, val alt2: SearchSuccess, val expectedType: Type, val argument: Tree) extends SearchFailureType {
def explanation(using Context): String =
var str1 = err.refStr(alt1.ref)
var str2 = err.refStr(alt2.ref)
if str1 == str2 then
str1 = ctx.printer.toTextRef(alt1.ref).show
str2 = ctx.printer.toTextRef(alt2.ref).show
em"both $str1 and $str2 $qualify"
override def whyNoConversion(using Context): String =
if !argument.isEmpty && argument.tpe.widen.isRef(defn.NothingClass) then
""
else
val what = if (expectedType.isInstanceOf[SelectionProto]) "extension methods" else "conversions"
i"""
|Note that implicit $what cannot be applied because they are ambiguous;
|$explanation"""
}
class MismatchedImplicit(ref: TermRef,
val expectedType: Type,
val argument: Tree) extends SearchFailureType {
def explanation(using Context): String =
em"${err.refStr(ref)} does not $qualify"
}
class DivergingImplicit(ref: TermRef,
val expectedType: Type,
val argument: Tree) extends SearchFailureType {
def explanation(using Context): String =
em"${err.refStr(ref)} produces a diverging implicit search when trying to $qualify"
}
/** A search failure type for attempted ill-typed extension method calls */
class FailedExtension(extApp: Tree, val expectedType: Type, val whyFailed: Message) extends SearchFailureType:
def argument = EmptyTree
def explanation(using Context) = em"$extApp does not $qualify"
/** A search failure type for aborted searches of extension methods, typically
* because of a cyclic reference or similar.
*/
class NestedFailure(_msg: Message, val expectedType: Type) extends SearchFailureType:
def argument = EmptyTree
override def msg(using Context) = _msg
def explanation(using Context) = msg.toString
end Implicits
import Implicits._
/** Info relating to implicits that is kept for one run */
trait ImplicitRunInfo:
self: Run =>
private val implicitScopeCache = util.EqHashMap[Type, OfTypeImplicits]()
private def isExcluded(sym: Symbol) =
if migrateTo3 then false else sym.is(Package) || sym.isPackageObject
/** Is `sym` an anchor type for which givens may exist? Anchor types are classes,
* opaque type aliases, match aliases and abstract types, but not type parameters
* or package objects.
*/
private def isAnchor(sym: Symbol) =
sym.isClass && !isExcluded(sym)
|| sym.isOpaqueAlias
|| sym.is(Deferred, butNot = Param)
|| sym.info.isInstanceOf[MatchAlias]
private def computeIScope(rootTp: Type): OfTypeImplicits =
object collectParts extends TypeTraverser:
private var provisional: Boolean = _
private var parts: mutable.LinkedHashSet[Type] = _
private val partSeen = util.HashSet[Type]()
def traverse(t: Type) =
if partSeen.contains(t) then ()
else if implicitScopeCache.contains(t) then parts += t
else
partSeen += t
t.dealias match
case t: TypeRef =>
if isAnchor(t.symbol) then
parts += t
traverse(t.prefix)
else
traverse(t.underlying)
case t: TermRef =>
if !isExcluded(t.symbol) then
traverse(t.info)
traverse(t.prefix)
case t: ThisType if t.cls.is(Module) && t.cls.isStaticOwner =>
traverse(t.cls.sourceModule.termRef)
case t: ConstantType =>
traverse(t.underlying)
case t: TypeParamRef =>
traverse(t.underlying)
if ctx.typerState.constraint.contains(t) then provisional = true
case t: TermParamRef =>
traverse(t.underlying)
case t =>
traverseChildren(t)
def apply(tp: Type): (collection.Set[Type], Boolean) =
provisional = false
parts = mutable.LinkedHashSet()
partSeen.clear()
traverse(tp)
(parts, provisional)
end collectParts
val seen = util.HashSet[Type]()
val incomplete = util.HashSet[Type]()
def collectCompanions(tp: Type, parts: collection.Set[Type]): TermRefSet =
val companions = new TermRefSet
def iscopeRefs(t: Type): TermRefSet =
implicitScopeCache.lookup(t) match
case is: OfTypeImplicits =>
is.companionRefs
case null =>
if seen.contains(t) then
incomplete += tp // all references for `t` will be accounted for in `seen` so we return `EmptySet`.
TermRefSet.empty // on the other hand, the refs of `tp` are now inaccurate, so `tp` is marked incomplete.
else
seen += t
val is = recur(t)
if !implicitScopeCache.contains(t) then incomplete += tp
is.companionRefs
end iscopeRefs
def addCompanion(pre: Type, companion: Symbol) =
if companion.exists && !companion.isAbsent() then
companions += TermRef(pre, companion)
def addCompanions(t: Type) = implicitScopeCache.lookup(t) match
case iscope: OfTypeImplicits =>
companions ++= iscope.companionRefs
case null => t match
case t: TypeRef =>
val sym = t.symbol
val pre = t.prefix
addPath(pre)
addCompanion(pre,
if sym.isClass then sym.companionModule
else pre.member(sym.name.toTermName)
.suchThat(companion => companion.is(Module) && companion.owner == sym.owner)
.symbol)
// The companion of `js.|` defines an implicit conversions from
// `A | Unit` to `js.UndefOrOps[A]`. To keep this conversion in scope
// in Scala 3, where we re-interpret `js.|` as a real union, we inject
// it in the scope of `Unit`.
if t.isRef(defn.UnitClass) && ctx.settings.scalajs.value then
companions += JSDefinitions.jsdefn.UnionOpsModuleRef
if sym.isClass then
for p <- t.parents do companions ++= iscopeRefs(p)
else
companions ++= iscopeRefs(t.underlying)
end addCompanions
def addPath(pre: Type): Unit = pre.dealias match
case pre: ThisType if pre.cls.is(Module) && pre.cls.isStaticOwner =>
addPath(pre.cls.sourceModule.termRef)
case pre: TermRef if !isExcluded(pre.symbol) =>
pre.info match
case info: SingletonType =>
addPath(info)
case info: TypeRef if info.symbol.is(Module) =>
addCompanion(info.prefix, info.symbol.sourceModule)
addPath(info.prefix)
case _ =>
companions += pre
addPath(pre.prefix)
case _ =>
parts.foreach(addCompanions)
companions
end collectCompanions
def recur(tp: Type): OfTypeImplicits =
val (parts, provisional) = collectParts(tp)
val companions = collectCompanions(tp, parts)
val result = OfTypeImplicits(tp, companions)(runContext)
if Config.cacheImplicitScopes
&& tp.hash != NotCached
&& !provisional
&& (tp eq rootTp) // first type traversed is always cached
|| !incomplete.contains(tp) // other types are cached if they are not incomplete
then implicitScopeCache(tp) = result
result
record(i"computeIScope")
recur(rootTp)
end computeIScope
/** The implicit scope of a type `tp`, which is specified by the following definitions.
*
* A reference is an _anchor_ if it refers to an object, a class, a trait, an
* abstract type, an opaque type alias, or a match type alias. References to
* packages and package objects are anchors only under -source:3.0-migration.
*
* The _anchors_ of a type `T` is a set of references defined as follows:
*
* - If `T` is a reference to an anchor, `T` itself plus, if `T` is of the form
* `P#A`, the anchors of `P`.
* - If `T` is an alias of `U`, the anchors of `U`.
* - If `T` is a reference to a type parameter, the union of the anchors of both of its bounds.
* - If `T` is a singleton reference, the anchors of its underlying type, plus,
* if `T` is of the form `(P#x).type`, the anchors of `P`.
* - If `T` is the this-type of a static object, the anchors of a term reference to that object.
* - If `T` is some other type, the union of the anchors of each constituent type of `T`.
*
* The _implicit scope_ of a type `tp` is the smallest set S of term references (i.e. TermRefs)
* such that
*
* - If `T` is a reference to a class, S includes a reference to the companion object
* of the class, if it exists, as well as the implicit scopes of all of `T`'s parent classes.
* - If `T` is a reference to an object, S includes `T` itself as well as
* the implicit scopes of all of `T`'s parent classes.
* - If `T` is a reference to an opaque type alias named `A`, S includes
* a reference to an object `A` defined in the same scope as the type, if it exists,
* as well as the implicit scope of `T`'s underlying type or bounds.
* - If `T` is a reference to an an abstract type or match type alias named `A`,
* S includes a reference to an object `A` defined in the same scope as the type,
* if it exists, as well as the implicit scopes of `T`'s lower and upper bound,
* if present.
* - If `T` is a reference to an anchor of the form `p.A` then S also includes
* all term references on the path `p`.
* - If `T` is some other type, S includes the implicit scopes of all anchors of `T`.
*/
def implicitScope(tp: Type)(using Context): OfTypeImplicits =
implicitScopeCache.lookup(tp) match
case is: OfTypeImplicits =>
record("implicitScope cache hit")
is
case null =>
record(i"implicitScope")
val liftToAnchors = new TypeMap:
override def stopAtStatic = true
private val seen = util.HashSet[Type]()
def applyToUnderlying(t: TypeProxy) =
if seen.contains(t) then
WildcardType
else
seen += t
t.underlying match
case TypeBounds(lo, hi) =>
if lo.isBottomTypeAfterErasure then apply(hi)
else AndType.make(apply(lo), apply(hi))
case u => apply(u)
def apply(t: Type) = t.dealias match
case t: TypeRef =>
if t.symbol.isClass || isAnchor(t.symbol) then t else applyToUnderlying(t)
case t: TypeVar => apply(t.underlying)
case t: ParamRef => applyToUnderlying(t)
case t: ConstantType => apply(t.underlying)
case t => mapOver(t)
end liftToAnchors
val liftedTp = liftToAnchors(tp)
if liftedTp eq tp then
record(i"implicitScope unlifted")
computeIScope(tp)
else
record("implicitScope lifted")
val liftedIScope = implicitScopeCache.getOrElse(liftedTp, computeIScope(liftedTp))
val result = OfTypeImplicits(tp, liftedIScope.companionRefs)(runContext)
implicitScopeCache(tp) = result
result
end implicitScope
protected def reset(): Unit =
implicitScopeCache.clear()
end ImplicitRunInfo
/** The implicit resolution part of type checking */
trait Implicits:
self: Typer =>
import tpd._
override def viewExists(from: Type, to: Type)(using Context): Boolean =
!from.isError
&& !to.isError
&& !ctx.isAfterTyper
&& ctx.mode.is(Mode.ImplicitsEnabled)
&& from.isValueType
&& ( from.isValueSubType(to)
|| inferView(dummyTreeOfType(from), to)
(using ctx.fresh.addMode(Mode.ImplicitExploration).setExploreTyperState()).isSuccess
// TODO: investigate why we can't TyperState#test here
)
/** Find an implicit conversion to apply to given tree `from` so that the
* result is compatible with type `to`.
*/
def inferView(from: Tree, to: Type)(using Context): SearchResult = {
record("inferView")
val wfromtp = from.tpe.widen
if to.isAny
|| to.isAnyRef
|| to.isRef(defn.UnitClass)
|| wfromtp.isRef(defn.NothingClass)
|| wfromtp.isRef(defn.NullClass)
|| !ctx.mode.is(Mode.ImplicitsEnabled)
|| from.isInstanceOf[Super]
|| (wfromtp eq NoPrefix)
then NoMatchingImplicitsFailure
else {
def adjust(to: Type) = to.stripTypeVar.widenExpr match {
case SelectionProto(name, memberProto, compat, true) =>
SelectionProto(name, memberProto, compat, privateOK = false)
case tp => tp
}
def isOldStyleFunctionConversion(tpe: Type): Boolean =
tpe match {
case PolyType(_, resType) => isOldStyleFunctionConversion(resType)
case _ => tpe.derivesFrom(defn.FunctionClass(1)) && !tpe.derivesFrom(defn.ConversionClass) && !tpe.derivesFrom(defn.SubTypeClass)
}
try
val inferred = inferImplicit(adjust(to), from, from.span)
inferred match {
case SearchSuccess(_, ref, _, false) if isOldStyleFunctionConversion(ref.underlying) =>
report.migrationWarning(
i"The conversion ${ref} will not be applied implicitly here in Scala 3 because only implicit methods and instances of Conversion class will continue to work as implicit views.",
from
)
case _ =>
}
inferred
catch {
case ex: AssertionError =>
implicits.println(s"view $from ==> $to")
implicits.println(ctx.typerState.constraint.show)
implicits.println(TypeComparer.explained(_.isSubType(from.tpe, to)))
throw ex
}
}
}
private var synthesizer: Synthesizer = null
/** Find an implicit argument for parameter `formal`.
* Return a failure as a SearchFailureType in the type of the returned tree.
*/
def inferImplicitArg(formal: Type, span: Span)(using Context): Tree =
inferImplicit(formal, EmptyTree, span) match
case SearchSuccess(arg, _, _, _) => arg
case fail @ SearchFailure(failed) =>
if fail.isAmbiguous then failed
else
if synthesizer == null then synthesizer = Synthesizer(this)
synthesizer.tryAll(formal, span).orElse(failed)
/** Search an implicit argument and report error if not found */
def implicitArgTree(formal: Type, span: Span)(using Context): Tree = {
val arg = inferImplicitArg(formal, span)
if (arg.tpe.isInstanceOf[SearchFailureType])
report.error(missingArgMsg(arg, formal, ""), ctx.source.atSpan(span))
arg
}
/** @param arg Tree representing a failed result of implicit search
* @param pt Type for which an implicit value was searched
* @param where Description of where the search was performed. Might be empty
* @param paramSymWithMethodCallTree Symbol of the parameter for which the implicit was searched and tree of the method call that triggered the implicit search
*/
def missingArgMsg(
arg: Tree,
pt: Type,
where: String,
paramSymWithMethodCallTree: Option[(Symbol, Tree)] = None
)(using Context): String = {
def findHiddenImplicitsCtx(c: Context): Context =
if c == NoContext then c
else c.freshOver(findHiddenImplicitsCtx(c.outer)).addMode(Mode.FindHiddenImplicits)
def ignoredInstanceNormalImport = arg.tpe match
case fail: SearchFailureType =>
if (fail.expectedType eq pt) || isFullyDefined(fail.expectedType, ForceDegree.none) then
inferImplicit(fail.expectedType, fail.argument, arg.span) match {
case s: SearchSuccess => Some(s)
case f: SearchFailure =>
f.reason match {
case ambi: AmbiguousImplicits => Some(ambi.alt1)
case r => None
}
}
else
// It's unsafe to search for parts of the expected type if they are not fully defined,
// since these come with nested contexts that are lost at this point. See #7249 for an
// example where searching for a nested type causes an infinite loop.
None
val error = new ImplicitSearchError(arg, pt, where, paramSymWithMethodCallTree, ignoredInstanceNormalImport, importSuggestionAddendum(pt))
error.missingArgMsg
}
/** A string indicating the formal parameter corresponding to a missing argument */
def implicitParamString(paramName: TermName, methodStr: String, tree: Tree)(using Context): String =
tree match {
case Select(qual, nme.apply) if defn.isFunctionType(qual.tpe.widen) =>
val qt = qual.tpe.widen
val qt1 = qt.dealiasKeepAnnots
def addendum = if (qt1 eq qt) "" else (i"\nThe required type is an alias of: $qt1")
em"parameter of ${qual.tpe.widen}$addendum"
case _ =>
em"${ if paramName.is(EvidenceParamName) then "an implicit parameter"
else s"parameter $paramName" } of $methodStr"
}
/** A CanEqual[T, U] instance is assumed
* - if one of T, U is an error type, or
* - if one of T, U is a subtype of the lifted version of the other,
* unless strict equality is set.
*/
def assumedCanEqual(ltp: Type, rtp: Type)(using Context) = {
// Map all non-opaque abstract types to their upper bound.
// This is done to check whether such types might plausibly be comparable to each other.
val lift = new TypeMap {
def apply(t: Type): Type = t match {
case t: TypeRef =>
t.info match {
case TypeBounds(lo, hi) if lo.ne(hi) && !t.symbol.is(Opaque) => apply(hi)
case _ => t
}
case t: SingletonType =>
apply(t.widen)
case t: RefinedType =>
apply(t.parent)
case _ =>
if (variance > 0) mapOver(t) else t
}
}
ltp.isError
|| rtp.isError
|| !strictEquality && (ltp <:< lift(rtp) || rtp <:< lift(ltp))
}
/** Check that equality tests between types `ltp` and `rtp` make sense */
def checkCanEqual(ltp: Type, rtp: Type, span: Span)(using Context): Unit =
if (!ctx.isAfterTyper && !assumedCanEqual(ltp, rtp)) {
val res = implicitArgTree(defn.CanEqualClass.typeRef.appliedTo(ltp, rtp), span)
implicits.println(i"CanEqual witness found for $ltp / $rtp: $res: ${res.tpe}")
}
object hasSkolem extends TreeAccumulator[Boolean]:
def apply(x: Boolean, tree: Tree)(using Context): Boolean =
x || {
tree match
case tree: Ident => tree.symbol.isSkolem
case Select(qual, _) => apply(x, qual)
case Apply(fn, _) => apply(x, fn)
case TypeApply(fn, _) => apply(x, fn)
case _: This => false
case _ => foldOver(x, tree)
}
/** Find an implicit parameter or conversion.
* @param pt The expected type of the parameter or conversion.
* @param argument If an implicit conversion is searched, the argument to which
* it should be applied, EmptyTree otherwise.
* @param span The position where errors should be reported.
*/
def inferImplicit(pt: Type, argument: Tree, span: Span)(using Context): SearchResult =
trace(s"search implicit ${pt.show}, arg = ${argument.show}: ${argument.tpe.show}", implicits, show = true) {
record("inferImplicit")
assert(ctx.phase.allowsImplicitSearch,
if (argument.isEmpty) i"missing implicit parameter of type $pt after typer"
else i"type error: ${argument.tpe} does not conform to $pt${err.whyNoMatchStr(argument.tpe, pt)}")
if pt.unusableForInference
|| !argument.isEmpty && argument.tpe.unusableForInference
then return NoMatchingImplicitsFailure
val result0 =
try ImplicitSearch(pt, argument, span).bestImplicit
catch case ce: CyclicReference =>
ce.inImplicitSearch = true
throw ce
val result =
result0 match {
case result: SearchSuccess =>
if result.tstate ne ctx.typerState then
result.tstate.commit()
if result.gstate ne ctx.gadt then
ctx.gadt.restore(result.gstate)
if hasSkolem(false, result.tree) then
report.error(SkolemInInferred(result.tree, pt, argument), ctx.source.atSpan(span))
implicits.println(i"success: $result")
implicits.println(i"committing ${result.tstate.constraint} yielding ${ctx.typerState.constraint} in ${ctx.typerState}")
result
case result: SearchFailure if result.isAmbiguous =>
val deepPt = pt.deepenProto
if (deepPt ne pt) inferImplicit(deepPt, argument, span)
else if (migrateTo3 && !ctx.mode.is(Mode.OldOverloadingResolution))
withMode(Mode.OldOverloadingResolution)(inferImplicit(pt, argument, span)) match {