scala3 icon indicating copy to clipboard operation
scala3 copied to clipboard

warning regression from scala 2 to scala 3: Reference to uninitialized value

Open bjornregnell opened this issue 3 years ago • 4 comments

Compiler version

3.2.0

Minimized code

There is a regression from Scala 2 to Scala 3 in that forward reference warnings are not given.

object shouldwarn {
  val a = b
  val b = 42
  def main(args: Array[String]) = println(a)
}

Output

$ scala-cli run . -S 3.2.0
0
$ scala-cli run . -S 2.13
Compiling project (Scala 2.13.8, JVM)
[warn] ./shouldwarn.scala:2:11: Reference to uninitialized value b
[warn]   val a = b
[warn]           ^
Compiled project (Scala 2.13.8, JVM)
0

Expectation

This should give the same warning as in Scala 2 out of the box. There is an experimental flag -Ysafe-init in Scala 3 but according to this doc page it does not seem to be supposed to be on by default when promoted from experimental to official, but people coming from Scala 2 (presumably) have the expectation that a warning will be given at least for the same cases as in Scala 2 (or even more cases, but not less). This kind of thing needs a warning out-of-the-box as bad things might happen...

bjornregnell avatar Sep 21 '22 11:09 bjornregnell

@bjornregnell Are you suggesting to enable -Ysafe-init by default?

liufengyun avatar Sep 21 '22 18:09 liufengyun

Scala 2 gave warnings when forward referencing. I'm not sure what differs -Ysafe-init in Scala 3 from the warnings in Scala 2, but I'd expect Scala 3 to be at least as helpful in its warnings as Scala 2, which had this warning out-of-the-box. So yes @liufengyun I'm am suggesting that -Ysafe-init is enabled by default, given that it is at least as good as the old warning, where goodness could e.g. interpreted as precision to pinpoint risk/bug.

bjornregnell avatar Sep 21 '22 21:09 bjornregnell

Thank you for your feedback @bjornregnell . I'm not sure if a SIP process is required for enabling it by default. One concern with enabling -Ysafe-init by default is that it requires loading TASTy from libraries, and thus incurs some overhead. Though the runtime overhead is negligible from our benchmarks (including Dotty), loading TASTy from libraries still raises concerns about resource consumption.

Maybe we can have a quick mode, where it performs the check best effort without loading TASTy? We don't have TASTy for Scala 2 and Java code either in the checker.

WDYT? /cc: @olhotak

liufengyun avatar Sep 22 '22 14:09 liufengyun

A quick mode with similar capacity as the Scala 2 warning sounds great! It is the regression from Scala 2, that I'm worried about: to not get any hint out of the box when fields are initialized with their default values due to forward referencing seems a potentially dangerous thing not to warn about as such bugs are hard to find...

bjornregnell avatar Sep 22 '22 16:09 bjornregnell