scala / scala3

The Scala 3 compiler, also known as Dotty.
https://dotty.epfl.ch
Apache License 2.0
5.87k stars 1.06k forks source link

`-Wunused` false positive in for-comprehension (2.13.15 regression) #21874

Closed myazinn closed 4 hours ago

myazinn commented 4 hours ago

Compiler version

2.13.15

Minimized code

object FalsePositiveUnused {

  def notOk1() =
    List(1).foldLeft(List(0)) { case (_, _) =>
      for {
        result <- List(1)
        usedVariable = result
      } yield usedVariable
    }

  def notOk2() =
    List(1).flatMap { case _ =>
      for {
        result <- List(1)
        usedVariable = result
      } yield usedVariable
    }

  def ok1() =
    for {
      result <- List(1)
      usedVariable = result
    } yield usedVariable

  def ok2() =
    List(1).flatMap { _ =>
      for {
        result <- List(1)
        usedVariable = result
      } yield usedVariable
    }

}

https://scastie.scala-lang.org/4Kbf4Z8VTHiwFJehlnp1jA

Output

[error] Applicable -Wconf / @nowarn filters for this fatal warning: msg=<part of the message>, cat=unused-pat-vars, site=FalsePositiveUnused.notOk1.$anonfun.$anonfun.usedVariable
[error]         usedVariable = result
[error] Applicable -Wconf / @nowarn filters for this fatal warning: msg=<part of the message>, cat=unused-pat-vars, site=FalsePositiveUnused.notOk2.$anonfun.$anonfun.usedVariable
[error]         usedVariable = result

Expectation

Code snippet should compile fine with "-Ywarn-unused", "-Xfatal-warnings". The compiler complains that usedVariable is unused, but it definitely is. The code breaks only when for-comprehension is wrapped in partial function (at least from what I've found). Because List(1).flatMap { _ => works fine, while List(1).flatMap { case _ => does not 🤔

Same code works fine with 2.13.14 https://scastie.scala-lang.org/DVK5oQ3LQgGAFI7hzHjMrw Scala 3 also works fine.

I guess the issue was introduced because of this ticket https://github.com/scala/scala3/issues/18289 (thank you for that BTW, it's very appreciated despite this bug) . Maybe something went wrong during back porting to Scala 2.

myazinn commented 4 hours ago

ooops, wrong place, sorry

som-snytt commented 45 minutes ago

Duplicate of https://github.com/scala/bug/issues/13041 which is fixed