scala3 icon indicating copy to clipboard operation
scala3 copied to clipboard

Implicit search recovering from ambiguity with worse candidate ?

Open EugeneFlesselle opened this issue 6 months ago • 0 comments

Compiler version

Scala compiler version 3.7.1-RC1-bin-SNAPSHOT-nonbootstrapped-git-24b2dc7

Minimized code

trait P[F[_]]
trait Q[F[_]] extends P[F]

case class W[A](as: A)
object W:
  implicit def w: Q[W] = ???

def g[F[_]](using P[F]): W[F[Unit]] = ???

implicit def q0[F[_]](using Q[F]): Q[F] = ???
implicit def p1[F[_]]: P[F] = ???
implicit def p2[F[_]]: P[F] = ???

val test: W[Unit] = g.as

Test elaborates to:

  • g[W](q0[W](q0[W](W.w))).as when all q0, p1, and p2 instances are present
  • g[Nothing](p1[Nothing]).as when only q0, and p1 instances are present
  • No given instance error, when only q0 is given

p1 is selected over q0 when they are the only two available alternatives, suggesting it is a "better" candidate. Yet when we introduce an ambiguity by adding p2, we recover from it with q0, a "worse" candidate, which IIRC should not happen. Even more bafflingly, removing the p0 and p1 alternatives seems to affect the constraining of the type variable F, preventing resolution from finding any instance at all.

It is also very strange that the q0 definition is somehow relevant, since it derives Q[F] using Q[F] itself.

Minimised from the https://github.com/scala/scala3/issues/23020#issuecomment-2823801566_ by @Alex1005a. The behavior is the same before and after the changes from #23020.

EugeneFlesselle avatar May 27 '25 12:05 EugeneFlesselle