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
- 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.
- 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.
- Multiple static blocks in a class body execute in source order.
- 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
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, withthisbound to the class itself. They can reference static members and (per spec)super, but cannot reference instance members.Suggested work
parser/expr.mbt:2069and friends, thestaticmodifier handling): acceptstatic { … }as a class-body member in addition tostatic field = …andstatic method() { … }. The static block is a list of statements executed at class evaluation time.interpreter/runtime/eval_expr.mbtorinterpreter/runtime/exec_stmt.mbt):this= the class object.thisresolve to the class object.Acceptance criteria
class C { static x = 1; static { this.y = 2; } }—C.xis1,C.yis2.class C { static { this.x = (() => 1)(); } }—C.xis1.class C { static { this.x = 1; } static { this.x = 2; } }—C.xis2(later block overwrites).class P { static x = 1; } class C extends P { static { super.y = 2; } }—P.yis2.moon check && moon testclean.passed_min.Notes
static { … }is unrelated to private fields. It can land in parallel with the private-fields runtime work.