scala / bug

Scala 2 bug reports only. Please, no questions — proper bug reports only.
https://scala-lang.org
230 stars 21 forks source link

scala runner renames main object #12889

Open som-snytt opened 8 months ago

som-snytt commented 8 months ago

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).

som-snytt commented 8 months ago

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
som-snytt commented 7 months ago

Another example https://github.com/scala/bug/issues/9790

som-snytt commented 2 months ago

Relatedly and not coincidentally https://github.com/scala/bug/issues/10252