Skip to content

Commit 1b9a7e0

Browse files
committed
Change rules for given prioritization
Consider the following program: ```scala class A class B extends A class C extends A given A = A() given B = B() given C = C() def f(using a: A, b: B, c: C) = println(a.getClass) println(b.getClass) println(c.getClass) @main def Test = f ``` With the current rules, this would fail with an ambiguity error between B and C when trying to synthesize the A parameter. This is a problem without an easy remedy. We can fix this problem by flipping the priority for implicit arguments. Instead of requiring an argument to be most _specific_, we now require it to be most _general_ while still conforming to the formal parameter. There are three justifications for this change, which at first glance seems quite drastic: - It gives us a natural way to deal with inheritance triangles like the one in the code above. Such triangles are quite common. - Intuitively, we want to get the closest possible match between required formal parameter type and synthetisized argument. The "most general" rule provides that. - We already do a crucial part of this. Namely, with current rules we interpolate all type variables in an implicit argument downwards, no matter what their variance is. This makes no sense in theory, but solves hairy problems with contravariant typeclasses like `Comparable`. Instead of this hack, we now do something more principled, by flipping the direction everywhere, preferring general over specific, instead of just flipping contravariant type parameters. The behavior is dependent on the Scala version - Old behavior: up to 3.4 - New behavior: from 3.5, 3.5-migration warns on behavior change The CB builds under the new rules. One fix was needed for a shapeless 3 deriving test. There was a typo: mkInstances instead of mkProductInstances, which previously got healed by accident because of the most specific rule. Also: Don't flip contravariant type arguments for overloading resolution Flipping contravariant type arguments was needed for implicit search where it will be replaced by a more general scheme. But it makes no sense for overloading resolution. For overloading resolution, we want to pick the most specific alternative, analogous to us picking the most specific instantiation when we force a fully defined type. Also: Disable implicit search everywhere for disambiaguation Previously, one disambiguation step missed that, whereas implicits were turned off everywhere else.
1 parent d4de2cb commit 1b9a7e0

File tree

10 files changed

+137
-67
lines changed

10 files changed

+137
-67
lines changed

compiler/src/dotty/tools/dotc/core/Mode.scala

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -103,16 +103,19 @@ object Mode {
103103
*/
104104
val CheckBoundsOrSelfType: Mode = newMode(14, "CheckBoundsOrSelfType")
105105

106-
/** Use Scala2 scheme for overloading and implicit resolution */
107-
val OldOverloadingResolution: Mode = newMode(15, "OldOverloadingResolution")
106+
/** Use previous Scheme for implicit resolution. Currently significant
107+
* in 3.0-migration where we use Scala-2's scheme instead and in 3.5-migration
108+
* where we use the previous scheme up to 3.4 instead.
109+
*/
110+
val OldImplicitResolution: Mode = newMode(15, "OldImplicitResolution")
108111

109112
/** Treat CapturingTypes as plain AnnotatedTypes even in phase CheckCaptures.
110-
* Reuses the value of OldOverloadingResolution to save Mode bits.
111-
* This is OK since OldOverloadingResolution only affects implicit search, which
113+
* Reuses the value of OldImplicitResolution to save Mode bits.
114+
* This is OK since OldImplicitResolution only affects implicit search, which
112115
* is done during phases Typer and Inlinig, and IgnoreCaptures only has an
113116
* effect during phase CheckCaptures.
114117
*/
115-
val IgnoreCaptures = OldOverloadingResolution
118+
val IgnoreCaptures = OldImplicitResolution
116119

117120
/** Allow hk applications of type lambdas to wildcard arguments;
118121
* used for checking that such applications do not normally arise

compiler/src/dotty/tools/dotc/typer/Applications.scala

Lines changed: 67 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ import ProtoTypes.*
2222
import Inferencing.*
2323
import reporting.*
2424
import Nullables.*, NullOpsDecorator.*
25-
import config.Feature
25+
import config.{Feature, SourceVersion}
2626

2727
import collection.mutable
2828
import config.Printers.{overload, typr, unapp}
@@ -1709,6 +1709,12 @@ trait Applications extends Compatibility {
17091709
/** Compare two alternatives of an overloaded call or an implicit search.
17101710
*
17111711
* @param alt1, alt2 Non-overloaded references indicating the two choices
1712+
* @param preferGeneral When comparing two value types, prefer the more general one
1713+
* over the more specific one iff `preferGeneral` is true.
1714+
* `preferGeneral` is set to `true` when we compare two given values, since
1715+
* then we want the most general evidence that matches the target
1716+
* type. It is set to `false` for overloading resolution, when we want the
1717+
* most specific type instead.
17121718
* @return 1 if 1st alternative is preferred over 2nd
17131719
* -1 if 2nd alternative is preferred over 1st
17141720
* 0 if neither alternative is preferred over the other
@@ -1727,27 +1733,25 @@ trait Applications extends Compatibility {
17271733
def compare(alt1: TermRef, alt2: TermRef, preferGeneral: Boolean = false)(using Context): Int = trace(i"compare($alt1, $alt2)", overload) {
17281734
record("resolveOverloaded.compare")
17291735

1730-
val newGivenRules =
1731-
ctx.mode.is(Mode.NewGivenRules) && alt1.symbol.is(Given)
1736+
val compareGivens = alt1.symbol.is(Given) || alt2.symbol.is(Given)
17321737

1733-
/** Is alternative `alt1` with type `tp1` as specific as alternative
1738+
/** Is alternative `alt1` with type `tp1` as good as alternative
17341739
* `alt2` with type `tp2` ?
17351740
*
1736-
* 1. A method `alt1` of type `(p1: T1, ..., pn: Tn)U` is as specific as `alt2`
1741+
* 1. A method `alt1` of type `(p1: T1, ..., pn: Tn)U` is as good as `alt2`
17371742
* if `alt1` is nullary or `alt2` is applicable to arguments (p1, ..., pn) of
17381743
* types T1,...,Tn. If the last parameter `pn` has a vararg type T*, then
17391744
* `alt1` must be applicable to arbitrary numbers of `T` parameters (which
17401745
* implies that it must be a varargs method as well).
17411746
* 2. A polymorphic member of type [a1 >: L1 <: U1, ..., an >: Ln <: Un]T is as
1742-
* specific as `alt2` of type `tp2` if T is as specific as `tp2` under the
1747+
* good as `alt2` of type `tp2` if T is as good as `tp2` under the
17431748
* assumption that for i = 1,...,n each ai is an abstract type name bounded
17441749
* from below by Li and from above by Ui.
17451750
* 3. A member of any other type `tp1` is:
1746-
* a. always as specific as a method or a polymorphic method.
1747-
* b. as specific as a member of any other type `tp2` if `tp1` is compatible
1748-
* with `tp2`.
1751+
* a. always as good as a method or a polymorphic method.
1752+
* b. as good as a member of any other type `tp2` is `asGoodValueType(tp1, tp2) = true`
17491753
*/
1750-
def isAsSpecific(alt1: TermRef, tp1: Type, alt2: TermRef, tp2: Type): Boolean = trace(i"isAsSpecific $tp1 $tp2", overload) {
1754+
def isAsGood(alt1: TermRef, tp1: Type, alt2: TermRef, tp2: Type): Boolean = trace(i"isAsSpecific $tp1 $tp2", overload) {
17511755
tp1 match
17521756
case tp1: MethodType => // (1)
17531757
tp1.paramInfos.isEmpty && tp2.isInstanceOf[LambdaType]
@@ -1769,65 +1773,60 @@ trait Applications extends Compatibility {
17691773
fullyDefinedType(tp1Params, "type parameters of alternative", alt1.symbol.srcPos)
17701774

17711775
val tparams = newTypeParams(alt1.symbol, tp1.paramNames, EmptyFlags, tp1.instantiateParamInfos(_))
1772-
isAsSpecific(alt1, tp1.instantiate(tparams.map(_.typeRef)), alt2, tp2)
1776+
isAsGood(alt1, tp1.instantiate(tparams.map(_.typeRef)), alt2, tp2)
17731777
}
17741778
case _ => // (3)
17751779
tp2 match
17761780
case tp2: MethodType => true // (3a)
17771781
case tp2: PolyType if tp2.resultType.isInstanceOf[MethodType] => true // (3a)
17781782
case tp2: PolyType => // (3b)
1779-
explore(isAsSpecificValueType(tp1, instantiateWithTypeVars(tp2)))
1783+
explore(isAsGoodValueType(tp1, instantiateWithTypeVars(tp2)))
17801784
case _ => // 3b)
1781-
isAsSpecificValueType(tp1, tp2)
1785+
isAsGoodValueType(tp1, tp2)
17821786
}
17831787

1784-
/** Test whether value type `tp1` is as specific as value type `tp2`.
1785-
* Let's abbreviate this to `tp1 <:s tp2`.
1786-
* Previously, `<:s` was the same as `<:`. This behavior is still
1787-
* available under mode `Mode.OldOverloadingResolution`. The new behavior
1788-
* is different, however. Here, `T <:s U` iff
1788+
/** Test whether value type `tp1` is as good as value type `tp2`.
1789+
* Let's abbreviate this to `tp1 <:p tp2`. The behavior depends on the Scala version
1790+
* and mode.
17891791
*
1790-
* flip(T) <: flip(U)
1792+
* - In Scala 2, `<:p` was the same as `<:`. This behavior is still
1793+
* available in 3.0-migration if mode `Mode.OldImplicitResolution` is turned on as well.
1794+
* It is used to highlight differences between Scala 2 and 3 behavior.
17911795
*
1792-
* where `flip` changes covariant occurrences of contravariant type parameters to
1793-
* covariant ones. Intuitively `<:s` means subtyping `<:`, except that all arguments
1794-
* to contravariant parameters are compared as if they were covariant. E.g. given class
1796+
* - In Scala 3.0-3.4, the behavior is as follows: `T <:p U` iff there is an impliit conversion
1797+
* from `T` to `U`, or
17951798
*
1796-
* class Cmp[-X]
1799+
* flip(T) <: flip(U)
17971800
*
1798-
* `Cmp[T] <:s Cmp[U]` if `T <: U`. On the other hand, non-variant occurrences
1799-
* of parameters are not affected. So `T <: U` would imply `Set[Cmp[U]] <:s Set[Cmp[T]]`,
1800-
* as usual, because `Set` is non-variant.
1801+
* where `flip` changes covariant occurrences of contravariant type parameters to
1802+
* covariant ones. Intuitively `<:p` means subtyping `<:`, except that all arguments
1803+
* to contravariant parameters are compared as if they were covariant. E.g. given class
18011804
*
1802-
* This relation might seem strange, but it models closely what happens for methods.
1803-
* Indeed, if we integrate the existing rules for methods into `<:s` we have now that
1805+
* class Cmp[-X]
18041806
*
1805-
* (T)R <:s (U)R
1807+
* `Cmp[T] <:p Cmp[U]` if `T <: U`. On the other hand, non-variant occurrences
1808+
* of parameters are not affected. So `T <: U` would imply `Set[Cmp[U]] <:p Set[Cmp[T]]`,
1809+
* as usual, because `Set` is non-variant.
18061810
*
1807-
* iff
1811+
* - From Scala 3.5, `T <:p U` means `T <: U` or `T` convertible to `U`
1812+
* for overloading resolution (when `preferGeneral is false), and the opposite relation
1813+
* `U <: T` or `U convertible to `T` for implicit disambiguation between givens
1814+
* (when `preferGeneral` is true). For old-style implicit values, the 3.4 behavior is kept.
18081815
*
1809-
* T => R <:s U => R
1816+
* - In Scala 3.5-migration, use the 3.5 scheme normally, and the 3.4 scheme if
1817+
* `Mode.OldImplicitResolution` is on. This is used to highlight differences in the
1818+
* two resolution schemes.
18101819
*
1811-
* Also: If a compared type refers to a given or its module class, use
1820+
* Also and only for given resolution: If a compared type refers to a given or its module class, use
18121821
* the intersection of its parent classes instead.
18131822
*/
1814-
def isAsSpecificValueType(tp1: Type, tp2: Type)(using Context) =
1815-
if !preferGeneral || ctx.mode.is(Mode.OldOverloadingResolution) then
1816-
// Normal specificity test for overloading resultion (where `preferGeneral` is false)
1823+
def isAsGoodValueType(tp1: Type, tp2: Type)(using Context) =
1824+
val oldResolution = ctx.mode.is(Mode.OldImplicitResolution)
1825+
if !preferGeneral || Feature.migrateTo3 && oldResolution then
1826+
// Normal specificity test for overloading resolution (where `preferGeneral` is false)
18171827
// and in mode Scala3-migration when we compare with the old Scala 2 rules.
18181828
isCompatible(tp1, tp2)
18191829
else
1820-
val flip = new TypeMap {
1821-
def apply(t: Type) = t match {
1822-
case t @ AppliedType(tycon, args) =>
1823-
def mapArg(arg: Type, tparam: TypeParamInfo) =
1824-
if (variance > 0 && tparam.paramVarianceSign < 0) defn.FunctionNOf(arg :: Nil, defn.UnitType)
1825-
else arg
1826-
mapOver(t.derivedAppliedType(tycon, args.zipWithConserve(tycon.typeParams)(mapArg)))
1827-
case _ => mapOver(t)
1828-
}
1829-
}
1830-
18311830
def prepare(tp: Type) = tp.stripTypeVar match
18321831
case tp: NamedType if tp.symbol.is(Module) && tp.symbol.sourceModule.is(Given) =>
18331832
tp.widen.widenToParents
@@ -1836,11 +1835,27 @@ trait Applications extends Compatibility {
18361835

18371836
val tp1p = prepare(tp1)
18381837
val tp2p = prepare(tp2)
1839-
if newGivenRules then
1840-
(tp2p relaxed_<:< tp1p) || viewExists(tp2, tp1)
1841-
else
1838+
1839+
if Feature.sourceVersion.isAtMost(SourceVersion.`3.4`)
1840+
|| oldResolution
1841+
|| !compareGivens
1842+
then
1843+
// Intermediate rules: better means specialize, but map all type arguments downwards
1844+
// These are enabled for 3.0-3.4, and for all comparisons between old-style implicits,
1845+
// and in 3.5-migration when we compare with previous rules.
1846+
val flip = new TypeMap:
1847+
def apply(t: Type) = t match
1848+
case t @ AppliedType(tycon, args) =>
1849+
def mapArg(arg: Type, tparam: TypeParamInfo) =
1850+
if (variance > 0 && tparam.paramVarianceSign < 0) defn.FunctionNOf(arg :: Nil, defn.UnitType)
1851+
else arg
1852+
mapOver(t.derivedAppliedType(tycon, args.zipWithConserve(tycon.typeParams)(mapArg)))
1853+
case _ => mapOver(t)
18421854
(flip(tp1p) relaxed_<:< flip(tp2p)) || viewExists(tp1, tp2)
1843-
end isAsSpecificValueType
1855+
else
1856+
// New rules: better means generalize
1857+
(tp2p relaxed_<:< tp1p) || viewExists(tp2, tp1)
1858+
end isAsGoodValueType
18441859

18451860
/** Widen the result type of synthetic given methods from the implementation class to the
18461861
* type that's implemented. Example
@@ -1900,9 +1915,8 @@ trait Applications extends Compatibility {
19001915

19011916
def compareWithTypes(tp1: Type, tp2: Type) =
19021917
val ownerScore = compareOwner(alt1.symbol.maybeOwner, alt2.symbol.maybeOwner)
1903-
1904-
val winsType1 = isAsSpecific(alt1, tp1, alt2, tp2)
1905-
val winsType2 = isAsSpecific(alt2, tp2, alt1, tp1)
1918+
val winsType1 = isAsGood(alt1, tp1, alt2, tp2)
1919+
val winsType2 = isAsGood(alt2, tp2, alt1, tp1)
19061920

19071921
overload.println(i"compare($alt1, $alt2)? $tp1 $tp2 $ownerScore $winsType1 $winsType2")
19081922
if winsType1 && winsType2

compiler/src/dotty/tools/dotc/typer/Implicits.scala

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -531,7 +531,7 @@ object Implicits:
531531
|must be more specific than $target""" :: Nil
532532

533533
override def msg(using Context) =
534-
super.msg.append(i"\nThe expected type $target is not specific enough, so no search was attempted")
534+
super.msg.append("\nThe expected type $target is not specific enough, so no search was attempted")
535535

536536
override def toString = s"TooUnspecific"
537537
end TooUnspecific
@@ -1110,8 +1110,8 @@ trait Implicits:
11101110
case result: SearchFailure if result.isAmbiguous =>
11111111
val deepPt = pt.deepenProto
11121112
if (deepPt ne pt) inferImplicit(deepPt, argument, span)
1113-
else if (migrateTo3 && !ctx.mode.is(Mode.OldOverloadingResolution))
1114-
withMode(Mode.OldOverloadingResolution)(inferImplicit(pt, argument, span)) match {
1113+
else if (migrateTo3 && !ctx.mode.is(Mode.OldImplicitResolution))
1114+
withMode(Mode.OldImplicitResolution)(inferImplicit(pt, argument, span)) match {
11151115
case altResult: SearchSuccess =>
11161116
report.migrationWarning(
11171117
result.reason.msg
@@ -1295,14 +1295,24 @@ trait Implicits:
12951295
* 0 if neither alternative is preferred over the other
12961296
*/
12971297
def compareAlternatives(alt1: RefAndLevel, alt2: RefAndLevel): Int =
1298+
def comp(using Context) = explore(compare(alt1.ref, alt2.ref, preferGeneral = true))
12981299
if alt1.ref eq alt2.ref then 0
12991300
else if alt1.level != alt2.level then alt1.level - alt2.level
13001301
else
1301-
val was = explore(compare(alt1.ref, alt2.ref, preferGeneral = true))(using searchContext())
1302-
val now = explore(compare(alt1.ref, alt2.ref, preferGeneral = true))(using searchContext().addMode(Mode.NewGivenRules))
1303-
if was != now then
1304-
println(i"change in preference for $pt between ${alt1.ref} and ${alt2.ref}, was: $was, now: $now at $srcPos")
1305-
now
1302+
val cmp = comp(using searchContext())
1303+
if Feature.sourceVersion == SourceVersion.`3.5-migration` then
1304+
val prev = comp(using searchContext().addMode(Mode.OldImplicitResolution))
1305+
if cmp != prev then
1306+
def choice(c: Int) = c match
1307+
case -1 => "the second alternative"
1308+
case 1 => "the first alternative"
1309+
case _ => "none - it's ambiguous"
1310+
report.warning(
1311+
em"""Change in given search preference for $pt between alternatives ${alt1.ref} and ${alt2.ref}
1312+
|Previous choice: ${choice(prev)}
1313+
|New choice : ${choice(cmp)}""", srcPos)
1314+
cmp
1315+
end compareAlternatives
13061316

13071317
/** If `alt1` is also a search success, try to disambiguate as follows:
13081318
* - If alt2 is preferred over alt1, pick alt2, otherwise return an

docs/_docs/reference/changed-features/implicit-resolution.md

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,22 @@ Condition (*) is new. It is necessary to ensure that the defined relation is tra
165165

166166
[//]: # todo: expand with precise rules
167167

168-
**9.** The following change is currently enabled in `-source future`:
168+
169+
**9.** Given disambiguation has changed. When comparing two givens that both match an expected type, we used to pick the most specific one, in alignment with
170+
overloading resolution. From Scala 3.5 on, we pick the most general one instead. Compiling with Scala 3.5-migration will print a warning in all cases where the preference has changed. Example:
171+
```scala
172+
class A
173+
class B extends A
174+
class C extends A
175+
176+
given A = A()
177+
given B = B()
178+
given C = C()
179+
180+
summon[A] // was ambiguous, will now return `given_A`
181+
```
182+
183+
**10.** The following change is currently enabled in `-source future`:
169184

170185
Implicit resolution now avoids generating recursive givens that can lead to an infinite loop at runtime. Here is an example:
171186

tests/neg/i15264.scala

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import language.`3.5`
12
object priority:
23
// lower number = higher priority
34
class Prio0 extends Prio1

tests/run/given-triangle.scala

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import language.future
2+
13
class A
24
class B extends A
35
class C extends A

tests/run/implicit-specifity.scala

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import language.`3.5`
2+
13
case class Show[T](val i: Int)
24
object Show {
35
def apply[T](implicit st: Show[T]): Int = st.i

tests/run/implied-priority.scala

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
/* These tests show various mechanisms available for implicit prioritization.
22
*/
3+
import language.`3.5`
34

45
class E[T](val str: String) // The type for which we infer terms below
56

tests/warn/given-triangle.check

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
-- Warning: tests/warn/given-triangle.scala:16:18 ----------------------------------------------------------------------
2+
16 |@main def Test = f // warn
3+
| ^
4+
| Change in given search preference for A between alternatives (given_A : A) and (given_B : B)
5+
| Previous choice: the second alternative
6+
| New choice : the first alternative

tests/warn/given-triangle.scala

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
//> using options -source 3.5-migration
2+
3+
class A
4+
class B extends A
5+
class C extends A
6+
7+
given A = A()
8+
given B = B()
9+
given C = C()
10+
11+
def f(using a: A, b: B, c: C) =
12+
println(a.getClass)
13+
println(b.getClass)
14+
println(c.getClass)
15+
16+
@main def Test = f // warn

0 commit comments

Comments
 (0)