Skip to content

Commit 6403fc0

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 8b0762a commit 6403fc0

15 files changed

+254
-78
lines changed

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

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ object Mode {
4141
val Pattern: Mode = newMode(0, "Pattern")
4242
val Type: Mode = newMode(1, "Type")
4343

44+
val PatternOrTypeBits: Mode = Pattern | Type
45+
4446
val ImplicitsEnabled: Mode = newMode(2, "ImplicitsEnabled")
4547
val InferringReturnType: Mode = newMode(3, "InferringReturnType")
4648

@@ -101,16 +103,19 @@ object Mode {
101103
*/
102104
val CheckBoundsOrSelfType: Mode = newMode(14, "CheckBoundsOrSelfType")
103105

104-
/** Use Scala2 scheme for overloading and implicit resolution */
105-
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")
106111

107112
/** Treat CapturingTypes as plain AnnotatedTypes even in phase CheckCaptures.
108-
* Reuses the value of OldOverloadingResolution to save Mode bits.
109-
* 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
110115
* is done during phases Typer and Inlinig, and IgnoreCaptures only has an
111116
* effect during phase CheckCaptures.
112117
*/
113-
val IgnoreCaptures = OldOverloadingResolution
118+
val IgnoreCaptures = OldImplicitResolution
114119

115120
/** Allow hk applications of type lambdas to wildcard arguments;
116121
* used for checking that such applications do not normally arise
@@ -120,8 +125,6 @@ object Mode {
120125
/** Read original positions when unpickling from TASTY */
121126
val ReadPositions: Mode = newMode(17, "ReadPositions")
122127

123-
val PatternOrTypeBits: Mode = Pattern | Type
124-
125128
/** We are elaborating the fully qualified name of a package clause.
126129
* In this case, identifiers should never be imported.
127130
*/

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

Lines changed: 79 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}
@@ -1678,6 +1678,12 @@ trait Applications extends Compatibility {
16781678
/** Compare two alternatives of an overloaded call or an implicit search.
16791679
*
16801680
* @param alt1, alt2 Non-overloaded references indicating the two choices
1681+
* @param preferGeneral When comparing two value types, prefer the more general one
1682+
* over the more specific one iff `preferGeneral` is true.
1683+
* `preferGeneral` is set to `true` when we compare two given values, since
1684+
* then we want the most general evidence that matches the target
1685+
* type. It is set to `false` for overloading resolution, when we want the
1686+
* most specific type instead.
16811687
* @return 1 if 1st alternative is preferred over 2nd
16821688
* -1 if 2nd alternative is preferred over 1st
16831689
* 0 if neither alternative is preferred over the other
@@ -1693,27 +1699,28 @@ trait Applications extends Compatibility {
16931699
* an alternative that takes more implicit parameters wins over one
16941700
* that takes fewer.
16951701
*/
1696-
def compare(alt1: TermRef, alt2: TermRef)(using Context): Int = trace(i"compare($alt1, $alt2)", overload) {
1702+
def compare(alt1: TermRef, alt2: TermRef, preferGeneral: Boolean = false)(using Context): Int = trace(i"compare($alt1, $alt2)", overload) {
16971703
record("resolveOverloaded.compare")
16981704

1699-
/** Is alternative `alt1` with type `tp1` as specific as alternative
1705+
val compareGivens = alt1.symbol.is(Given) || alt2.symbol.is(Given)
1706+
1707+
/** Is alternative `alt1` with type `tp1` as good as alternative
17001708
* `alt2` with type `tp2` ?
17011709
*
1702-
* 1. A method `alt1` of type `(p1: T1, ..., pn: Tn)U` is as specific as `alt2`
1710+
* 1. A method `alt1` of type `(p1: T1, ..., pn: Tn)U` is as good as `alt2`
17031711
* if `alt1` is nullary or `alt2` is applicable to arguments (p1, ..., pn) of
17041712
* types T1,...,Tn. If the last parameter `pn` has a vararg type T*, then
17051713
* `alt1` must be applicable to arbitrary numbers of `T` parameters (which
17061714
* implies that it must be a varargs method as well).
17071715
* 2. A polymorphic member of type [a1 >: L1 <: U1, ..., an >: Ln <: Un]T is as
1708-
* specific as `alt2` of type `tp2` if T is as specific as `tp2` under the
1716+
* good as `alt2` of type `tp2` if T is as good as `tp2` under the
17091717
* assumption that for i = 1,...,n each ai is an abstract type name bounded
17101718
* from below by Li and from above by Ui.
17111719
* 3. A member of any other type `tp1` is:
1712-
* a. always as specific as a method or a polymorphic method.
1713-
* b. as specific as a member of any other type `tp2` if `tp1` is compatible
1714-
* with `tp2`.
1720+
* a. always as good as a method or a polymorphic method.
1721+
* b. as good as a member of any other type `tp2` is `asGoodValueType(tp1, tp2) = true`
17151722
*/
1716-
def isAsSpecific(alt1: TermRef, tp1: Type, alt2: TermRef, tp2: Type): Boolean = trace(i"isAsSpecific $tp1 $tp2", overload) {
1723+
def isAsGood(alt1: TermRef, tp1: Type, alt2: TermRef, tp2: Type): Boolean = trace(i"isAsSpecific $tp1 $tp2", overload) {
17171724
tp1 match
17181725
case tp1: MethodType => // (1)
17191726
tp1.paramInfos.isEmpty && tp2.isInstanceOf[LambdaType]
@@ -1735,69 +1742,89 @@ trait Applications extends Compatibility {
17351742
fullyDefinedType(tp1Params, "type parameters of alternative", alt1.symbol.srcPos)
17361743

17371744
val tparams = newTypeParams(alt1.symbol, tp1.paramNames, EmptyFlags, tp1.instantiateParamInfos(_))
1738-
isAsSpecific(alt1, tp1.instantiate(tparams.map(_.typeRef)), alt2, tp2)
1745+
isAsGood(alt1, tp1.instantiate(tparams.map(_.typeRef)), alt2, tp2)
17391746
}
17401747
case _ => // (3)
17411748
tp2 match
17421749
case tp2: MethodType => true // (3a)
17431750
case tp2: PolyType if tp2.resultType.isInstanceOf[MethodType] => true // (3a)
17441751
case tp2: PolyType => // (3b)
1745-
explore(isAsSpecificValueType(tp1, instantiateWithTypeVars(tp2)))
1752+
explore(isAsGoodValueType(tp1, instantiateWithTypeVars(tp2)))
17461753
case _ => // 3b)
1747-
isAsSpecificValueType(tp1, tp2)
1754+
isAsGoodValueType(tp1, tp2)
17481755
}
17491756

1750-
/** Test whether value type `tp1` is as specific as value type `tp2`.
1751-
* Let's abbreviate this to `tp1 <:s tp2`.
1752-
* Previously, `<:s` was the same as `<:`. This behavior is still
1753-
* available under mode `Mode.OldOverloadingResolution`. The new behavior
1754-
* is different, however. Here, `T <:s U` iff
1757+
/** Test whether value type `tp1` is as good as value type `tp2`.
1758+
* Let's abbreviate this to `tp1 <:p tp2`. The behavior depends on the Scala version
1759+
* and mode.
17551760
*
1756-
* flip(T) <: flip(U)
1761+
* - In Scala 2, `<:p` was the same as `<:`. This behavior is still
1762+
* available in 3.0-migration if mode `Mode.OldImplicitResolution` is turned on as well.
1763+
* It is used to highlight differences between Scala 2 and 3 behavior.
17571764
*
1758-
* where `flip` changes covariant occurrences of contravariant type parameters to
1759-
* covariant ones. Intuitively `<:s` means subtyping `<:`, except that all arguments
1760-
* to contravariant parameters are compared as if they were covariant. E.g. given class
1765+
* - In Scala 3.0-3.4, the behavior is as follows: `T <:p U` iff there is an impliit conversion
1766+
* from `T` to `U`, or
17611767
*
1762-
* class Cmp[-X]
1768+
* flip(T) <: flip(U)
17631769
*
1764-
* `Cmp[T] <:s Cmp[U]` if `T <: U`. On the other hand, non-variant occurrences
1765-
* of parameters are not affected. So `T <: U` would imply `Set[Cmp[U]] <:s Set[Cmp[T]]`,
1766-
* as usual, because `Set` is non-variant.
1770+
* where `flip` changes covariant occurrences of contravariant type parameters to
1771+
* covariant ones. Intuitively `<:p` means subtyping `<:`, except that all arguments
1772+
* to contravariant parameters are compared as if they were covariant. E.g. given class
17671773
*
1768-
* This relation might seem strange, but it models closely what happens for methods.
1769-
* Indeed, if we integrate the existing rules for methods into `<:s` we have now that
1774+
* class Cmp[-X]
17701775
*
1771-
* (T)R <:s (U)R
1776+
* `Cmp[T] <:p Cmp[U]` if `T <: U`. On the other hand, non-variant occurrences
1777+
* of parameters are not affected. So `T <: U` would imply `Set[Cmp[U]] <:p Set[Cmp[T]]`,
1778+
* as usual, because `Set` is non-variant.
17721779
*
1773-
* iff
1780+
* - From Scala 3.5, `T <:p U` means `T <: U` or `T` convertible to `U`
1781+
* for overloading resolution (when `preferGeneral is false), and the opposite relation
1782+
* `U <: T` or `U convertible to `T` for implicit disambiguation between givens
1783+
* (when `preferGeneral` is true). For old-style implicit values, the 3.4 behavior is kept.
17741784
*
1775-
* T => R <:s U => R
1785+
* - In Scala 3.5-migration, use the 3.5 scheme normally, and the 3.4 scheme if
1786+
* `Mode.OldImplicitResolution` is on. This is used to highlight differences in the
1787+
* two resolution schemes.
17761788
*
1777-
* Also: If a compared type refers to a given or its module class, use
1789+
* Also and only for given resolution: If a compared type refers to a given or its module class, use
17781790
* the intersection of its parent classes instead.
17791791
*/
1780-
def isAsSpecificValueType(tp1: Type, tp2: Type)(using Context) =
1781-
if (ctx.mode.is(Mode.OldOverloadingResolution))
1792+
def isAsGoodValueType(tp1: Type, tp2: Type)(using Context) =
1793+
val oldResolution = ctx.mode.is(Mode.OldImplicitResolution)
1794+
if !preferGeneral || Feature.migrateTo3 && oldResolution then
1795+
// Normal specificity test for overloading resolution (where `preferGeneral` is false)
1796+
// and in mode Scala3-migration when we compare with the old Scala 2 rules.
17821797
isCompatible(tp1, tp2)
1783-
else {
1784-
val flip = new TypeMap {
1785-
def apply(t: Type) = t match {
1786-
case t @ AppliedType(tycon, args) =>
1787-
def mapArg(arg: Type, tparam: TypeParamInfo) =
1788-
if (variance > 0 && tparam.paramVarianceSign < 0) defn.FunctionNOf(arg :: Nil, defn.UnitType)
1789-
else arg
1790-
mapOver(t.derivedAppliedType(tycon, args.zipWithConserve(tycon.typeParams)(mapArg)))
1791-
case _ => mapOver(t)
1792-
}
1793-
}
1794-
def prepare(tp: Type) = tp.stripTypeVar match {
1798+
else
1799+
def prepare(tp: Type) = tp.stripTypeVar match
17951800
case tp: NamedType if tp.symbol.is(Module) && tp.symbol.sourceModule.is(Given) =>
1796-
flip(tp.widen.widenToParents)
1797-
case _ => flip(tp)
1798-
}
1799-
(prepare(tp1) relaxed_<:< prepare(tp2)) || viewExists(tp1, tp2)
1800-
}
1801+
tp.widen.widenToParents
1802+
case _ =>
1803+
tp
1804+
1805+
val tp1p = prepare(tp1)
1806+
val tp2p = prepare(tp2)
1807+
1808+
if Feature.sourceVersion.isAtMost(SourceVersion.`3.4`)
1809+
|| oldResolution
1810+
|| !compareGivens
1811+
then
1812+
// Intermediate rules: better means specialize, but map all type arguments downwards
1813+
// These are enabled for 3.0-3.4, and for all comparisons between old-style implicits,
1814+
// and in 3.5-migration when we compare with previous rules.
1815+
val flip = new TypeMap:
1816+
def apply(t: Type) = t match
1817+
case t @ AppliedType(tycon, args) =>
1818+
def mapArg(arg: Type, tparam: TypeParamInfo) =
1819+
if (variance > 0 && tparam.paramVarianceSign < 0) defn.FunctionNOf(arg :: Nil, defn.UnitType)
1820+
else arg
1821+
mapOver(t.derivedAppliedType(tycon, args.zipWithConserve(tycon.typeParams)(mapArg)))
1822+
case _ => mapOver(t)
1823+
(flip(tp1p) relaxed_<:< flip(tp2p)) || viewExists(tp1, tp2)
1824+
else
1825+
// New rules: better means generalize
1826+
(tp2p relaxed_<:< tp1p) || viewExists(tp2, tp1)
1827+
end isAsGoodValueType
18011828

18021829
/** Widen the result type of synthetic given methods from the implementation class to the
18031830
* type that's implemented. Example
@@ -1857,9 +1884,8 @@ trait Applications extends Compatibility {
18571884

18581885
def compareWithTypes(tp1: Type, tp2: Type) =
18591886
val ownerScore = compareOwner(alt1.symbol.maybeOwner, alt2.symbol.maybeOwner)
1860-
1861-
val winsType1 = isAsSpecific(alt1, tp1, alt2, tp2)
1862-
val winsType2 = isAsSpecific(alt2, tp2, alt1, tp1)
1887+
val winsType1 = isAsGood(alt1, tp1, alt2, tp2)
1888+
val winsType2 = isAsGood(alt2, tp2, alt1, tp1)
18631889

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

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

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -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
@@ -1226,7 +1226,7 @@ trait Implicits:
12261226
assert(argument.isEmpty || argument.tpe.isValueType || argument.tpe.isInstanceOf[ExprType],
12271227
em"found: $argument: ${argument.tpe}, expected: $pt")
12281228

1229-
private def nestedContext() =
1229+
private def searchContext() =
12301230
ctx.fresh.setMode(ctx.mode &~ Mode.ImplicitsEnabled)
12311231

12321232
private def isCoherent = pt.isRef(defn.CanEqualClass)
@@ -1270,7 +1270,7 @@ trait Implicits:
12701270
else
12711271
val history = ctx.searchHistory.nest(cand, pt)
12721272
val typingCtx =
1273-
nestedContext().setNewTyperState().setFreshGADTBounds.setSearchHistory(history)
1273+
searchContext().setNewTyperState().setFreshGADTBounds.setSearchHistory(history)
12741274
val result = typedImplicit(cand, pt, argument, span)(using typingCtx)
12751275
result match
12761276
case res: SearchSuccess =>
@@ -1295,9 +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
1300-
else explore(compare(alt1.ref, alt2.ref))(using nestedContext())
1301+
else
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
13011316

13021317
/** If `alt1` is also a search success, try to disambiguate as follows:
13031318
* - If alt2 is preferred over alt1, pick alt2, otherwise return an
@@ -1333,8 +1348,8 @@ trait Implicits:
13331348
else
13341349
ctx.typerState
13351350

1336-
diff = inContext(ctx.withTyperState(comparisonState)):
1337-
compare(ref1, ref2)
1351+
diff = inContext(searchContext().withTyperState(comparisonState)):
1352+
compare(ref1, ref2, preferGeneral = true)
13381353
else // alt1 is a conversion, prefer extension alt2 over it
13391354
diff = -1
13401355
if diff < 0 then alt2

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ trait ImportSuggestions:
296296
var i = 0
297297
var diff = 0
298298
while i < filled && diff == 0 do
299-
diff = compare(ref, top(i))(using noImplicitsCtx)
299+
diff = compare(ref, top(i), preferGeneral = true)(using noImplicitsCtx)
300300
if diff > 0 then
301301
rest += top(i)
302302
top(i) = ref

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

0 commit comments

Comments
 (0)