#2797 JS static init order

go4 Thu 28 May 2020

The javascript static init order is not same with java runtime.

const class A {
  static const x := B.y
const class B {
  static const b := 1
  static const y := b

I make a change to fix this in compileJs::JsFieldExpr. The Class is initialized when a static field is accessed. For example var x = B.y become:

var x = ((B.satic$init ? B.static$init() : null), B.y);

B.static$init = function() {
  if (B.static$inited) return;
  B.static$inited = true;

brian Fri 29 May 2020

Note that Java static initializer order is quite complicated and tends to work with dependencies taken into account - see spec. However even then it doesn't always work, I often find odd cases where static initializers don't run in the order I want them to. In your code since A doesn't actually subtype from B then I don't that is safe.

I don't think the runtime should be doing anything to try and work around it. However maybe we should look if we can make the compiler smarter. I've seen places where the JS compiler doesn't order as well as the JVM does. Although its kind of an obtuse a problem and fairly easier to structure to your code to work around it. I'm almost inclined to say we disallow inter-dependencies on static fields between classes.

Login or Signup to reply.