Skip to content

Class private: static blocks in class bodies #399

Description

@dowdiness

Context

Tracking issue: #389 (Class private fields, methods, and static blocks)

static { … } blocks in class bodies are static initialization: code that runs once when the class is evaluated, with this bound to the class itself. They can reference static members and (per spec) super, but cannot reference instance members.

Suggested work

  1. Parser (parser/expr.mbt:2069 and friends, the static modifier handling): accept static { … } as a class-body member in addition to static field = … and static method() { … }. The static block is a list of statements executed at class evaluation time.
  2. Runtime (wherever class evaluation happens in interpreter/runtime/eval_expr.mbt or interpreter/runtime/exec_stmt.mbt):
    • At class evaluation time, after static fields are initialized and static methods are defined, execute the static block with this = the class object.
    • The block may call methods, set fields, and read other static state. It cannot read instance state (per spec) — references to this resolve to the class object.
  3. Multiple static blocks in a class body execute in source order.
  4. Subclasses inherit the parent's static block behavior. A subclass's static blocks run after the parent's.

Acceptance criteria

  • class C { static x = 1; static { this.y = 2; } }C.x is 1, C.y is 2.
  • class C { static { this.x = (() => 1)(); } }C.x is 1.
  • class C { static { this.x = 1; } static { this.x = 2; } }C.x is 2 (later block overwrites).
  • class P { static x = 1; } class C extends P { static { super.y = 2; } }P.y is 2.
  • A static block that throws causes the class declaration to throw, leaving the class in a partial state (per spec).
  • moon check && moon test clean.
  • No regression in test262-baseline.json passed_min.

Notes

Metadata

Metadata

Assignees

No one assigned

    Labels

    conformanceECMAScript conformancetest262Test262 conformance work

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions