scala/scala3

Scala.js backend cannot emit static fields

Open

#14,710 opened on Mar 18, 2022

View on GitHub
 (1 comment) (0 reactions) (1 assignee)Scala (6,247 stars) (1,159 forks)batch import
area:backendarea:scala.jsexp:advancedhelp wanteditype:enhancement

Description

Compiler version

3.1.1

Minimized code

import scala.annotation.static

object Invoker:
  @static val x = ""
  @static def f(): Unit = println(x)

Output

 java.lang.IllegalArgumentException: requirement failed: a member can have a static constructor name iff it is in the static constructor namespace
Error:  	at scala.Predef$.require(Predef.scala:337)
Error:  	at org.scalajs.ir.Trees$MethodDef.<init>(Trees.scala:1148)
Error:  	at org.scalajs.ir.Trees$MethodDef$.apply(Trees.scala:1134)
Error:  	at dotty.tools.backend.sjs.JSCodeGen.genMethodDef(JSCodeGen.scala:1563)
Error:  	at dotty.tools.backend.sjs.JSCodeGen.genMethodWithCurrentLocalNameScope$$anonfun$1(JSCodeGen.scala:1529)
Error:  	at dotty.tools.backend.sjs.JSCodeGen.withPerMethodBodyState$$anonfun$1(JSCodeGen.scala:106)
Error:  	at dotty.tools.backend.sjs.ScopedVar$.withScopedVars(ScopedVar.scala:33)
Error:  	at dotty.tools.backend.sjs.JSCodeGen.withPerMethodBodyState(JSCodeGen.scala:107)
Error:  	at dotty.tools.backend.sjs.JSCodeGen.genMethodWithCurrentLocalNameScope(JSCodeGen.scala:1535)
...

Expectation

It should work with val just like it does with defs. The following compiles fine:

object Invoker:
  @static def x = "" // methods work fine
  @static def f(): Unit = println(x)

Contributor guide