镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Commit 28b0070

Browse files
committed
fix(vm): preserve class method activation scope
Admit methods and global-only deferred class members only when their VM state is exact. Heap activations now save, trace, relocate, and restore home-object and super scope; base constructors install private method brands before execution, while derived and field-initializing constructors retain a causal admission barrier. Unresolved source-level private names also reject eager computed-key lowering. Verified focused Debug and TSan tier, compiler, barrier, and moving-GC witnesses; all 1,477 unit tests across four final-binary partitions plus an isolated scheduling-witness rerun; BunPress build and 89-file link check. Test262 impact: 0 gains and 0 regressions across test/language/statements/class (4,367 cases) and test/language/expressions/object (1,170 cases), exact parent to candidate.
1 parent cff13e9 commit 28b0070

8 files changed

Lines changed: 270 additions & 40 deletions

File tree

‎docs/.data/bunpress-output-v1.json‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,8 @@
5050
},
5151
{
5252
"path": "architecture/index.html",
53-
"bytes": 167853,
54-
"sha256": "e9543567b57fa59396b1cec7b8db136ad46a4b9719b92bfc73ff0e25c8585d53"
53+
"bytes": 168344,
54+
"sha256": "94489969f062f24fbbc1736cddd4131c90a35066416acdd55cac3a04d42e8d93"
5555
},
5656
{
5757
"path": "baseline-jit/index.html",
@@ -264,5 +264,5 @@
264264
"sha256": "036254fd0141573e60c6a927672b5dbf853a640eaa5d1dbbe9a7bd74c9ad6783"
265265
}
266266
],
267-
"tree_sha256": "e6ce1bf1613e109e8fd923b966a8a46eee4ae5d2449d33fabf10973da5fa7e79"
267+
"tree_sha256": "8b46ca249662b56f686f001dcb9fde5aa78d6965da2d53f8d7664e7e49485bf5"
268268
}

‎docs/architecture.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ zig-js runs JavaScript through a tree-walking interpreter and a suspendable byte
2323
Because the VM buys capability rather than speed, tiering is deliberately narrow (`plainFunctionMayUseBytecode`, `compiler.zig`):
2424

2525
- **Generators / async / async generators** always compile to the VM — they need suspend/resume, which the tree-walker cannot express.
26-
- A **plain function** (non-method, non-generator, non-async, not using `arguments`) compiles to the VM only when it can actually benefit: it is strict and may contain a tail call, or it recurses by its own name (deep recursion that would otherwise overflow the native stack). Otherwise it stays on the tree-walker.
26+
- A **plain function or method** (non-generator, non-async, not using `arguments`) compiles to the VM only when it can actually benefit: it is strict and may contain a tail call/property operation, or it recurses by its own name (deep recursion that would otherwise overflow the native stack). Method activations preserve their exact home object and `super` constructor. Otherwise the function stays on the tree-walker.
2727
- Everything else — top-level code, and any function using a construct the compiler does not lower — tree-walks.
2828

2929
Because most code tree-walks, the VM path is comparatively under-exercised, so VM/tree-walker semantic divergences are a known bug surface (see the block-scoping note below).
@@ -32,7 +32,7 @@ Because most code tree-walks, the VM path is comparatively under-exercised, so V
3232

3333
## Lexical scoping and the slot model
3434

35-
The VM gives each compiled function one **flat, block-transparent slot array**: locals are frame slots indexed in O(1), and closures capture the defining frame. This is fast but does not model per-block lexical scope, so the compiler keeps functions on the tree-walker whenever correct block scoping would matter — a `let`/`const` that shadows another binding, a read in the Temporal Dead Zone (before a binding's declaration), or a `for (let …)` head captured per-iteration by a body closure. The tree-walker's `Environment` chain enforces those correctly. Proper per-block slot scoping on the VM (which would let those functions tier) is possible but unbuilt; it is only worthwhile if the VM becomes a genuine performance tier.
35+
The VM gives each compiled function one **flat, block-transparent slot array**: locals are frame slots indexed in O(1), and closures capture the defining frame. This is fast but does not model per-block lexical scope, so the compiler keeps functions on the tree-walker whenever correct block scoping would matter — a `let`/`const` that shadows another binding, a read in the Temporal Dead Zone (before a binding's declaration), or a `for (let …)` head captured per-iteration by a body closure. Deferred class members are admitted when they use only globals, but a member that captures one of these frame slots rejects its enclosing function. Base constructors without fields can use bytecode; derived constructors and constructors with field initialization retain an explicit tree-walker barrier until bytecode activations model their initialization state. The tree-walker's `Environment` chain enforces the rejected cases correctly. Proper per-block slot scoping on the VM (which would let those functions tier) is possible but unbuilt; it is only worthwhile if the VM becomes a genuine performance tier.
3636

3737
Admission is observable rather than inferred from a null chunk. Every runtime
3838
`Function` retains a stable `BytecodeAdmissionReason`, and

‎src/ast.zig‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,10 @@ pub const FunctionNode = struct {
109109
/// A MethodDefinition (concise method, getter, or setter in an object literal
110110
/// or class body). Such functions get a [[HomeObject]] so `super` resolves.
111111
is_method: bool = false,
112+
/// Runtime-synthesized class constructor whose derived/field initialization
113+
/// state is not yet represented by a bytecode activation. Parsed functions
114+
/// leave this false; `buildClass` sets it only for that exact barrier.
115+
requires_tree_walk_class_constructor: bool = false,
112116
};
113117

114118
/// A `class` member: a method (`func` is a `.function` node) or a field

‎src/compiler.zig‎

Lines changed: 86 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -449,15 +449,31 @@ fn stmtListContainsNestedFuncDecl(stmts: []*Node) bool {
449449
return false;
450450
}
451451

452-
/// A class member with a deferred body — a method/getter/setter (`func`), a
453-
/// field initializer (`field_init`), or a `static { … }` block. Such bodies are
454-
/// evaluated by the shared tree-walker (`eval_class`) and close over the current
455-
/// `Environment`, so in a tiered (frame-mode) function they cannot see the
456-
/// frame's slot-locals. A class with none of these (only computed keys, which
457-
/// are lowered as VM ops) captures nothing and stays tierable.
458-
fn classHasMemberBody(members: []const ast.ClassMember) bool {
452+
/// Whether a deferred class member body references `name`. Computed keys are
453+
/// deliberately excluded: they execute eagerly as VM operations, so closures
454+
/// created there capture frame slots normally. Methods, field initializers, and
455+
/// static blocks execute later through `eval_class` and can only resolve names
456+
/// available through its Environment chain.
457+
fn classDeferredBodiesCaptureName(members: []const ast.ClassMember, name: []const u8) bool {
459458
for (members) |m| {
460-
if (m.func != null or m.field_init != null or m.static_block != null) return true;
459+
if (m.func) |func| if (nameRefInClosure(func, name, true)) return true;
460+
if (m.field_init) |init| if (nameRefInClosure(init, name, true)) return true;
461+
if (m.static_block) |block| if (nameRefInClosure(block, name, true)) return true;
462+
}
463+
return false;
464+
}
465+
466+
/// `eval_class` can safely build deferred members from a VM activation when
467+
/// none of them closes over a slot in that activation or an enclosing VM frame.
468+
/// Global-only methods therefore remain bytecode-eligible; a real frame capture
469+
/// still rejects the whole function before execution.
470+
fn classDeferredBodiesCaptureFrame(scope: *const FnScope, members: []const ast.ClassMember) bool {
471+
var current: ?*const FnScope = scope;
472+
while (current) |frame_scope| : (current = frame_scope.parent) {
473+
var names = frame_scope.names.keyIterator();
474+
while (names.next()) |name| {
475+
if (classDeferredBodiesCaptureName(members, name.*)) return true;
476+
}
461477
}
462478
return false;
463479
}
@@ -1764,6 +1780,16 @@ pub const Compiler = struct {
17641780
/// BEFORE the iterator advances (the spec evaluates the reference first).
17651781
/// Returns the temp names, or null when `target` is not a member.
17661782
const MemberRef = struct { obj: []const u8, key: ?[]const u8 };
1783+
1784+
/// Runtime class construction rewrites `#name` to its unique storage key
1785+
/// before compiling method bodies. An unreplaced source name can still
1786+
/// appear in an eagerly compiled computed class key; lowering it as an
1787+
/// ordinary property would erase PrivateFieldGet's required brand check.
1788+
fn addMemberName(self: *Compiler, name: []const u8) CompileError!u32 {
1789+
if (value_mod.isRawPrivateName(name) and !value_mod.isPrivateKey(name))
1790+
return error.Unsupported;
1791+
return self.chunk.addName(try value_mod.encodeStringKey(self.arena, name));
1792+
}
17671793
fn preEvalMemberRef(self: *Compiler, target: ?*Node) CompileError!?MemberRef {
17681794
const t = target orelse return null;
17691795
if (t.* != .member) return null;
@@ -1791,7 +1817,7 @@ pub const Compiler = struct {
17911817
_ = try self.chunk.emit(.set_index, 0);
17921818
} else {
17931819
try self.emitLoad(val); // [obj, val]
1794-
_ = try self.chunk.emit(.set_prop, try self.chunk.addName(try value_mod.encodeStringKey(self.arena, m.property)));
1820+
_ = try self.chunk.emit(.set_prop, try self.addMemberName(m.property));
17951821
}
17961822
_ = try self.chunk.emit(.pop, 0); // discard the set result
17971823
}
@@ -2039,7 +2065,7 @@ pub const Compiler = struct {
20392065
// Fetch the method (RequireObjectCoercible on the receiver) BEFORE the
20402066
// args, per spec order, then tail-call with this = recv.
20412067
const m = c.callee.member;
2042-
const ni = try self.chunk.addName(try value_mod.encodeStringKey(self.arena, m.property));
2068+
const ni = try self.addMemberName(m.property);
20432069
try self.compileExpr(m.object);
20442070
_ = try self.chunk.emit(.dup, 0);
20452071
_ = try self.chunk.emit(.get_prop, ni);
@@ -2079,7 +2105,7 @@ pub const Compiler = struct {
20792105
// `obj.tag`...`` → this = obj. Fetch the tag (RequireObjectCoercible +
20802106
// any getter) BEFORE the arguments, per spec order.
20812107
const m = tag.member;
2082-
const ni = try self.chunk.addName(try value_mod.encodeStringKey(self.arena, m.property));
2108+
const ni = try self.addMemberName(m.property);
20832109
try self.compileExpr(m.object);
20842110
_ = try self.chunk.emit(.dup, 0);
20852111
_ = try self.chunk.emit(.get_prop, ni);
@@ -2167,7 +2193,8 @@ pub const Compiler = struct {
21672193
.shr => .shr,
21682194
.ushr => .ushr,
21692195
};
2170-
if (b.op == .in_op and b.left.* == .identifier and value_mod.isPrivateKey(b.left.identifier)) {
2196+
if (b.op == .in_op and b.left.* == .identifier and value_mod.isRawPrivateName(b.left.identifier)) {
2197+
if (!value_mod.isPrivateKey(b.left.identifier)) return error.Unsupported;
21712198
try self.compileExpr(b.right);
21722199
_ = try self.chunk.emit(.private_in, try self.chunk.addName(b.left.identifier));
21732200
return;
@@ -2206,7 +2233,7 @@ pub const Compiler = struct {
22062233
_ = try self.chunk.emit(.set_index, 0);
22072234
} else {
22082235
try self.compileExpr(a.value);
2209-
const ni = try self.chunk.addName(try value_mod.encodeStringKey(self.arena, m.property));
2236+
const ni = try self.addMemberName(m.property);
22102237
_ = try self.chunk.emit(.set_prop, ni);
22112238
}
22122239
},
@@ -2278,18 +2305,12 @@ pub const Compiler = struct {
22782305
// element names. Lower those key expressions in source order, then
22792306
// let the VM delegate class construction to the shared interpreter.
22802307
if (c.superclass != null) return error.Unsupported;
2281-
// `eval_class` delegates member bodies (methods, field
2282-
// initializers, static blocks) to the tree-walker, which closes
2283-
// them over `self.env`. In a frame-mode (tiered) function the
2284-
// frame's slot-locals do NOT live in that env, so a member reading
2285-
// an enclosing local resolves it wrong (stale/global) or throws
2286-
// ReferenceError. Bail the whole function to the tree-walker, where
2287-
// those locals live in the Environment and the capture is correct.
2288-
// (In env-mode — `self.scope == null`, e.g. a generator body — the
2289-
// members capture through the Environment chain already.) Computed
2290-
// keys are excluded: they are lowered here as VM ops and captured
2291-
// as values, not deferred.
2292-
if (self.scope != null and classHasMemberBody(c.members)) return error.Unsupported;
2308+
// `eval_class` delegates deferred member bodies to the
2309+
// tree-walker. Reject only when one actually reads a frame local;
2310+
// global-only methods need no frame Environment and are safe.
2311+
// (Env-mode generators already expose locals in that chain.)
2312+
if (self.scope) |scope|
2313+
if (classDeferredBodiesCaptureFrame(scope, c.members)) return error.Unsupported;
22932314
const computed_count = try self.compileClassComputedKeys(c.members);
22942315
_ = try self.chunk.emitAB(.eval_class, try self.chunk.addClass(node), computed_count);
22952316
},
@@ -2313,7 +2334,7 @@ pub const Compiler = struct {
23132334
} else if (c.callee.* == .member and c.callee.member.computed == null) {
23142335
// `recv.name(args)`: bind `this = recv` at the call site.
23152336
const m = c.callee.member;
2316-
const ni = try self.chunk.addName(try value_mod.encodeStringKey(self.arena, m.property));
2337+
const ni = try self.addMemberName(m.property);
23172338
if (spread) {
23182339
try self.compileExpr(m.object);
23192340
_ = try self.chunk.emit(.dup, 0);
@@ -2372,7 +2393,7 @@ pub const Compiler = struct {
23722393
try self.compileExpr(ce);
23732394
_ = try self.chunk.emit(.get_index, 0);
23742395
} else {
2375-
const ni = try self.chunk.addName(try value_mod.encodeStringKey(self.arena, m.property));
2396+
const ni = try self.addMemberName(m.property);
23762397
_ = try self.chunk.emit(.get_prop, ni);
23772398
}
23782399
},
@@ -3049,6 +3070,44 @@ test "compiler reports stable plain-function admission reasons" {
30493070
}
30503071
}
30513072

3073+
test "compiler admits global-only class members and rejects frame captures" {
3074+
var safe_arena = std.heap.ArenaAllocator.init(std.testing.allocator);
3075+
defer safe_arena.deinit();
3076+
var safe_parser = try @import("parser.zig").Parser.init(
3077+
safe_arena.allocator(),
3078+
"function f(seed){ class Box { constructor(value){ this.value = value; } read(){ return this.value; } } return new Box(seed).read(); }",
3079+
);
3080+
const safe_program = try safe_parser.parseProgram();
3081+
switch (try Compiler.admitPlainFunction(safe_arena.allocator(), safe_program.program[0].func_decl)) {
3082+
.compiled => |compiled| try std.testing.expect(compiled.chunk.code.items.len != 0),
3083+
.rejected => return error.TestUnexpectedResult,
3084+
}
3085+
3086+
var capture_arena = std.heap.ArenaAllocator.init(std.testing.allocator);
3087+
defer capture_arena.deinit();
3088+
var capture_parser = try @import("parser.zig").Parser.init(
3089+
capture_arena.allocator(),
3090+
"function f(seed){ class Box { read(){ return seed; } } return new Box().read(); }",
3091+
);
3092+
const capture_program = try capture_parser.parseProgram();
3093+
switch (try Compiler.admitPlainFunction(capture_arena.allocator(), capture_program.program[0].func_decl)) {
3094+
.compiled => return error.TestUnexpectedResult,
3095+
.rejected => |reason| try std.testing.expectEqual(Compiler.PlainFunctionRejection.unsupported_lowering, reason),
3096+
}
3097+
3098+
var private_key_arena = std.heap.ArenaAllocator.init(std.testing.allocator);
3099+
defer private_key_arena.deinit();
3100+
var private_key_parser = try @import("parser.zig").Parser.init(
3101+
private_key_arena.allocator(),
3102+
"function f(){ class Box { #value; [globalThis.#value] = 1; } }",
3103+
);
3104+
const private_key_program = try private_key_parser.parseProgram();
3105+
switch (try Compiler.admitPlainFunction(private_key_arena.allocator(), private_key_program.program[0].func_decl)) {
3106+
.compiled => return error.TestUnexpectedResult,
3107+
.rejected => |reason| try std.testing.expectEqual(Compiler.PlainFunctionRejection.unsupported_lowering, reason),
3108+
}
3109+
}
3110+
30523111
test "compiler reports stable program admission reasons" {
30533112
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
30543113
defer arena.deinit();

0 commit comments

Comments
 (0)