bug
bug copied to clipboard
scala runner renames main object
Reproduction steps
Scala version: 2.13.12
➜ snips cat mainly.scala
class C(private val c: Int)
object C {
def main(args: Array[String]): Unit = {
println(new C(42).c)
}
}
➜ snips scalac -d /tmp/sandbox mainly.scala
➜ snips scala -Vprint mainly.scala
mainly.scala:6: error: value c in class C cannot be accessed as a member of C from object Main
println(new C(42).c)
^
[[syntax trees at end of typer]] // mainly.scala
package <empty> {
class C extends scala.AnyRef {
<paramaccessor> private[this] val c: Int = _;
<stable> <accessor> <paramaccessor> private def c: Int = C.this.c;
def <init>(c: Int): C = {
C.super.<init>();
()
}
};
object Main extends scala.AnyRef {
def <init>(): Main.type = {
Main.super.<init>();
()
};
def main(args: Array[String]): Unit = scala.Predef.println(new C(42).<c: error>)
}
}
Problem
For some reason, the scala runner rudely assumes it can rename my object that has a main method.
Probably I am the last person on Earth to use the old scala runner.
Noticed while trying out a snippet submitted for a Dotty bug (a different bug).
The ancient comment underestimates the liberty that was taken:
/* If there is only a single object template in the file and it has a
* suitable main method, we will use it rather than building another object
* around it. Since objects are loaded lazily the whole script would have
* been a no-op, so we're not taking much liberty.
*/
// If we detect a main module with an arbitrary name, rename it to the expected name.
The workaround is to name it.
scala -Xscript C mainly.scala
Another example https://github.com/scala/bug/issues/9790
Relatedly and not coincidentally https://github.com/scala/bug/issues/10252