Skip to content

Commit 09f6913

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 4c2305d commit 09f6913

15 files changed

+254
-78
lines changed

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

+10-7
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

+79-53
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}
@@ -1665,6 +1665,12 @@ trait Applications extends Compatibility {
16651665
/** Compare two alternatives of an overloaded call or an implicit search.
16661666
*
16671667
* @param alt1, alt2 Non-overloaded references indicating the two choices
1668+
* @param preferGeneral When comparing two value types, prefer the more general one
1669+
* over the more specific one iff `preferGeneral` is true.
1670+
* `preferGeneral` is set to `true` when we compare two given values, since
1671+
* then we want the most general evidence that matches the target
1672+
* type. It is set to `false` for overloading resolution, when we want the
1673+
* most specific type instead.
16681674
* @return 1 if 1st alternative is preferred over 2nd
16691675
* -1 if 2nd alternative is preferred over 1st
16701676
* 0 if neither alternative is preferred over the other
@@ -1680,27 +1686,28 @@ trait Applications extends Compatibility {
16801686
* an alternative that takes more implicit parameters wins over one
16811687
* that takes fewer.
16821688
*/
1683-
def compare(alt1: TermRef, alt2: TermRef)(using Context): Int = trace(i"compare($alt1, $alt2)", overload) {
1689+
def compare(alt1: TermRef, alt2: TermRef, preferGeneral: Boolean = false)(using Context): Int = trace(i"compare($alt1, $alt2)", overload) {
16841690
record("resolveOverloaded.compare")
16851691

1686-
/** Is alternative `alt1` with type `tp1` as specific as alternative
1692+
val compareGivens = alt1.symbol.is(Given) || alt2.symbol.is(Given)
1693+
1694+
/** Is alternative `alt1` with type `tp1` as good as alternative
16871695
* `alt2` with type `tp2` ?
16881696
*
1689-
* 1. A method `alt1` of type `(p1: T1, ..., pn: Tn)U` is as specific as `alt2`
1697+
* 1. A method `alt1` of type `(p1: T1, ..., pn: Tn)U` is as good as `alt2`
16901698
* if `alt1` is nullary or `alt2` is applicable to arguments (p1, ..., pn) of
16911699
* types T1,...,Tn. If the last parameter `pn` has a vararg type T*, then
16921700
* `alt1` must be applicable to arbitrary numbers of `T` parameters (which
16931701
* implies that it must be a varargs method as well).
16941702
* 2. A polymorphic member of type [a1 >: L1 <: U1, ..., an >: Ln <: Un]T is as
1695-
* specific as `alt2` of type `tp2` if T is as specific as `tp2` under the
1703+
* good as `alt2` of type `tp2` if T is as good as `tp2` under the
16961704
* assumption that for i = 1,...,n each ai is an abstract type name bounded
16971705
* from below by Li and from above by Ui.
16981706
* 3. A member of any other type `tp1` is:
1699-
* a. always as specific as a method or a polymorphic method.
1700-
* b. as specific as a member of any other type `tp2` if `tp1` is compatible
1701-
* with `tp2`.
1707+
* a. always as good as a method or a polymorphic method.
1708+
* b. as good as a member of any other type `tp2` is `asGoodValueType(tp1, tp2) = true`
17021709
*/
1703-
def isAsSpecific(alt1: TermRef, tp1: Type, alt2: TermRef, tp2: Type): Boolean = trace(i"isAsSpecific $tp1 $tp2", overload) {
1710+
def isAsGood(alt1: TermRef, tp1: Type, alt2: TermRef, tp2: Type): Boolean = trace(i"isAsSpecific $tp1 $tp2", overload) {
17041711
tp1 match
17051712
case tp1: MethodType => // (1)
17061713
tp1.paramInfos.isEmpty && tp2.isInstanceOf[LambdaType]
@@ -1722,69 +1729,89 @@ trait Applications extends Compatibility {
17221729
fullyDefinedType(tp1Params, "type parameters of alternative", alt1.symbol.srcPos)
17231730

17241731
val tparams = newTypeParams(alt1.symbol, tp1.paramNames, EmptyFlags, tp1.instantiateParamInfos(_))
1725-
isAsSpecific(alt1, tp1.instantiate(tparams.map(_.typeRef)), alt2, tp2)
1732+
isAsGood(alt1, tp1.instantiate(tparams.map(_.typeRef)), alt2, tp2)
17261733
}
17271734
case _ => // (3)
17281735
tp2 match
17291736
case tp2: MethodType => true // (3a)
17301737
case tp2: PolyType if tp2.resultType.isInstanceOf[MethodType] => true // (3a)
17311738
case tp2: PolyType => // (3b)
1732-
explore(isAsSpecificValueType(tp1, instantiateWithTypeVars(tp2)))
1739+
explore(isAsGoodValueType(tp1, instantiateWithTypeVars(tp2)))
17331740
case _ => // 3b)
1734-
isAsSpecificValueType(tp1, tp2)
1741+
isAsGoodValueType(tp1, tp2)
17351742
}
17361743

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

17891816
/** Widen the result type of synthetic given methods from the implementation class to the
17901817
* type that's implemented. Example
@@ -1844,9 +1871,8 @@ trait Applications extends Compatibility {
18441871

18451872
def compareWithTypes(tp1: Type, tp2: Type) =
18461873
val ownerScore = compareOwner(alt1.symbol.maybeOwner, alt2.symbol.maybeOwner)
1847-
1848-
val winsType1 = isAsSpecific(alt1, tp1, alt2, tp2)
1849-
val winsType2 = isAsSpecific(alt2, tp2, alt1, tp1)
1874+
val winsType1 = isAsGood(alt1, tp1, alt2, tp2)
1875+
val winsType2 = isAsGood(alt2, tp2, alt1, tp1)
18501876

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

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

+22-7
Original file line numberDiff line numberDiff line change
@@ -1105,8 +1105,8 @@ trait Implicits:
11051105
case result: SearchFailure if result.isAmbiguous =>
11061106
val deepPt = pt.deepenProto
11071107
if (deepPt ne pt) inferImplicit(deepPt, argument, span)
1108-
else if (migrateTo3 && !ctx.mode.is(Mode.OldOverloadingResolution))
1109-
withMode(Mode.OldOverloadingResolution)(inferImplicit(pt, argument, span)) match {
1108+
else if (migrateTo3 && !ctx.mode.is(Mode.OldImplicitResolution))
1109+
withMode(Mode.OldImplicitResolution)(inferImplicit(pt, argument, span)) match {
11101110
case altResult: SearchSuccess =>
11111111
report.migrationWarning(
11121112
result.reason.msg
@@ -1221,7 +1221,7 @@ trait Implicits:
12211221
assert(argument.isEmpty || argument.tpe.isValueType || argument.tpe.isInstanceOf[ExprType],
12221222
em"found: $argument: ${argument.tpe}, expected: $pt")
12231223

1224-
private def nestedContext() =
1224+
private def searchContext() =
12251225
ctx.fresh.setMode(ctx.mode &~ Mode.ImplicitsEnabled)
12261226

12271227
private def isCoherent = pt.isRef(defn.CanEqualClass)
@@ -1265,7 +1265,7 @@ trait Implicits:
12651265
else
12661266
val history = ctx.searchHistory.nest(cand, pt)
12671267
val typingCtx =
1268-
nestedContext().setNewTyperState().setFreshGADTBounds.setSearchHistory(history)
1268+
searchContext().setNewTyperState().setFreshGADTBounds.setSearchHistory(history)
12691269
val result = typedImplicit(cand, pt, argument, span)(using typingCtx)
12701270
result match
12711271
case res: SearchSuccess =>
@@ -1290,9 +1290,24 @@ trait Implicits:
12901290
* 0 if neither alternative is preferred over the other
12911291
*/
12921292
def compareAlternatives(alt1: RefAndLevel, alt2: RefAndLevel): Int =
1293+
def comp(using Context) = explore(compare(alt1.ref, alt2.ref, preferGeneral = true))
12931294
if alt1.ref eq alt2.ref then 0
12941295
else if alt1.level != alt2.level then alt1.level - alt2.level
1295-
else explore(compare(alt1.ref, alt2.ref))(using nestedContext())
1296+
else
1297+
val cmp = comp(using searchContext())
1298+
if Feature.sourceVersion == SourceVersion.`3.5-migration` then
1299+
val prev = comp(using searchContext().addMode(Mode.OldImplicitResolution))
1300+
if cmp != prev then
1301+
def choice(c: Int) = c match
1302+
case -1 => "the second alternative"
1303+
case 1 => "the first alternative"
1304+
case _ => "none - it's ambiguous"
1305+
report.warning(
1306+
em"""Change in given search preference for $pt between alternatives ${alt1.ref} and ${alt2.ref}
1307+
|Previous choice: ${choice(prev)}
1308+
|New choice : ${choice(cmp)}""", srcPos)
1309+
cmp
1310+
end compareAlternatives
12961311

12971312
/** If `alt1` is also a search success, try to disambiguate as follows:
12981313
* - If alt2 is preferred over alt1, pick alt2, otherwise return an
@@ -1328,8 +1343,8 @@ trait Implicits:
13281343
else
13291344
ctx.typerState
13301345

1331-
diff = inContext(ctx.withTyperState(comparisonState)):
1332-
compare(ref1, ref2)
1346+
diff = inContext(searchContext().withTyperState(comparisonState)):
1347+
compare(ref1, ref2, preferGeneral = true)
13331348
else // alt1 is a conversion, prefer extension alt2 over it
13341349
diff = -1
13351350
if diff < 0 then alt2

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

+1-1
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

+16-1
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)