From 320ea842d66f3c75ec1e9ac41e6e781b71097d83 Mon Sep 17 00:00:00 2001 From: Ralph Date: Tue, 30 Jun 2026 06:02:17 -0700 Subject: [PATCH 1/3] =?UTF-8?q?fix(codegen+hir+runtime):=20#5587=20?= =?UTF-8?q?=E2=80=94=20Temporal=20subclass=20dispatch,=20cap=20writeback?= =?UTF-8?q?=20in=20inlined=20scope,=20Duration=20f64=20precision?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three bugs fixed in the Temporal subclass test262 gap (#5587): **Bug 1a — class capture stash must come AFTER constructor body** `synthesize_class_captures` was inserting `this.__perry_cap_ = param` immediately after the `super()` call. If the constructor body later ran `++called`, the stash recorded the PRE-mutation value. Fixed by appending the stash statements at the END of the constructor body (after all user code but still after `super()`). **Bug 1b — cap writeback uses wrong local ID after module-level inlining** `emit_class_capture_writeback` extracted the outer-scope local ID from the `__perry_cap_` name suffix, then did `ctx.locals.get(&id)`. When the enclosing function is inlined at module level, Perry alpha-renames every local — `called` might be id=2 inside `check()` but id=9 in module-init. The suffix lookup (`ctx.locals.get(&2)`) returns `None`, silently skipping the writeback. Fix: accept `new_args: &[perry_hir::Expr]` and use the position of the cap arg in the `New` node's args to find the current-scope id via `LocalGet(id)`. Call sites updated: `new.rs` passes `args`; `new_dynamic.rs` and `proxy_reflect.rs` pass `&[]` (suffix fallback). **Bug 2 — Duration add/subtract/round diverges from ECMAScript f64 rounding** ECMAScript spec coerces Duration fields through ℝ(𝔽(·)) after arithmetic, so sub-float64 precision is lost. `temporal_rs` operates in i128 and stores exact results (e.g. `MAX_SAFE + (MAX_SAFE - 1) = 18014398509481981`). `toString()` then printed `PT18014398509.481981S` while the `microseconds` getter showed `18014398509481980` (because `i128 as f64` rounded). Added `f64_round_duration()` applied after `add`, `subtract`, and `round` so the stored value equals the spec's ℝ(𝔽(·))-rounded result. Regression tests: 6 tests in `crates/perry/tests/issue_5587_temporal_subclass.rs` covering Duration subclasses, PlainDate subclasses, aliased heritage, no-ctor subclasses, the module-level-inlining capture writeback case, and the f64 precision edge. Co-Authored-By: Claude Sonnet 4.6 --- crates/perry-codegen/src/expr/new_dynamic.rs | 2 +- .../perry-codegen/src/expr/proxy_reflect.rs | 2 +- .../src/lower_call/capture_writeback.rs | 42 ++++++++- crates/perry-codegen/src/lower_call/new.rs | 11 ++- .../src/lower_decl/class_captures.rs | 24 ++--- crates/perry-runtime/src/temporal/duration.rs | 30 +++++- .../tests/issue_5587_temporal_subclass.rs | 94 +++++++++++++++++++ 7 files changed, 181 insertions(+), 24 deletions(-) diff --git a/crates/perry-codegen/src/expr/new_dynamic.rs b/crates/perry-codegen/src/expr/new_dynamic.rs index 0c2b0ccc7f3..1b01a34ccb1 100644 --- a/crates/perry-codegen/src/expr/new_dynamic.rs +++ b/crates/perry-codegen/src/expr/new_dynamic.rs @@ -162,7 +162,7 @@ pub(crate) fn lower(ctx: &mut FnCtx<'_>, expr: &Expr) -> Result { if let Some(class) = ctx.classes.get(cn.as_str()).copied() { let bits = ctx.block().bitcast_double_to_i64(&result); let inst_handle = ctx.block().and(I64, &bits, POINTER_MASK_I64); - crate::lower_call::emit_class_capture_writeback(ctx, class, &inst_handle); + crate::lower_call::emit_class_capture_writeback(ctx, class, &inst_handle, &[]); } } Ok(result) diff --git a/crates/perry-codegen/src/expr/proxy_reflect.rs b/crates/perry-codegen/src/expr/proxy_reflect.rs index c97ec165bc2..617d0e478f4 100644 --- a/crates/perry-codegen/src/expr/proxy_reflect.rs +++ b/crates/perry-codegen/src/expr/proxy_reflect.rs @@ -723,7 +723,7 @@ pub(crate) fn lower(ctx: &mut FnCtx<'_>, expr: &Expr) -> Result { if let Some(class) = ctx.classes.get(cn.as_str()).copied() { let bits = ctx.block().bitcast_double_to_i64(&result); let inst_handle = ctx.block().and(I64, &bits, POINTER_MASK_I64); - crate::lower_call::emit_class_capture_writeback(ctx, class, &inst_handle); + crate::lower_call::emit_class_capture_writeback(ctx, class, &inst_handle, &[]); } } Ok(result) diff --git a/crates/perry-codegen/src/lower_call/capture_writeback.rs b/crates/perry-codegen/src/lower_call/capture_writeback.rs index 7b672564650..46479fb4014 100644 --- a/crates/perry-codegen/src/lower_call/capture_writeback.rs +++ b/crates/perry-codegen/src/lower_call/capture_writeback.rs @@ -24,10 +24,18 @@ use crate::types::{DOUBLE, I32, I64}; /// local's alloca slot, making the mutation visible to the caller. /// /// `obj_handle` is the raw i64 object pointer (not nanboxed). +/// +/// `new_args` is the full `args` slice from the HIR `New` node — the LAST +/// `n_cap_params` elements are the cap args in the same order as the +/// constructor's `__perry_cap_*` params. Used to resolve the *current*-scope +/// local ID for each capture, which may differ from the numeric suffix in +/// `__perry_cap_` when the class was defined inside a function that was +/// later inlined into a different scope (where local IDs are alpha-renamed). pub(crate) fn emit_class_capture_writeback( ctx: &mut FnCtx<'_>, class: &perry_hir::Class, obj_handle: &str, + new_args: &[perry_hir::Expr], ) { // Cap params are synthesized in `synthesize_class_captures` as extra // constructor params with name `__perry_cap_`. They are NOT in @@ -36,11 +44,38 @@ pub(crate) fn emit_class_capture_writeback( let Some(ctor) = class.constructor.as_ref() else { return; }; - for param in &ctor.params { + // Collect the cap params (those with __perry_cap_ prefix) in declaration + // order so we can index them positionally against new_args. + let cap_params: Vec<_> = ctor + .params + .iter() + .filter(|p| p.name.starts_with("__perry_cap_")) + .collect(); + // The cap args occupy the last cap_params.len() slots of new_args. + let cap_args_start = new_args.len().saturating_sub(cap_params.len()); + + for (cap_idx, param) in cap_params.iter().enumerate() { let Some(id_str) = param.name.strip_prefix("__perry_cap_") else { continue; }; - let Ok(outer_id) = id_str.parse::() else { + // Prefer position-based lookup using new_args: the arg at index + // cap_args_start + cap_idx is a LocalGet whose id is the + // *current-scope* id — correct even when the class was inlined into a + // different scope and local IDs were alpha-renamed. + let current_scope_id: Option = + new_args + .get(cap_args_start + cap_idx) + .and_then(|arg| { + if let perry_hir::Expr::LocalGet(id) = arg { + Some(*id) + } else { + None + } + }) + // Fallback to the numeric suffix from __perry_cap_ for + // call sites that don't supply new_args (empty slice). + .or_else(|| id_str.parse::().ok()); + let Some(outer_id) = current_scope_id else { continue; }; // Only write back to locals that are actually in scope (same-function @@ -62,6 +97,9 @@ pub(crate) fn emit_class_capture_writeback( ); // Store the updated value. Handle boxed locals (shared across multiple // closures) via js_box_set; plain locals via a direct slot store. + // `outer_id` here is the current-scope id (resolved via new_args or + // the __perry_cap_ suffix), so boxed_vars / i32_counter_slots lookups + // correctly resolve to the current context's tracking structures. if ctx.boxed_vars.contains(&outer_id) { let box_dbl = ctx.block().load(DOUBLE, &outer_slot); let box_ptr = ctx.block().bitcast_double_to_i64(&box_dbl); diff --git a/crates/perry-codegen/src/lower_call/new.rs b/crates/perry-codegen/src/lower_call/new.rs index 948846f73e0..50b0bfcc2a3 100644 --- a/crates/perry-codegen/src/lower_call/new.rs +++ b/crates/perry-codegen/src/lower_call/new.rs @@ -1245,7 +1245,7 @@ fn lower_new_impl( // updates the outer local's alloca slot. Read the fields back here so // the enclosing scope sees the updated values (e.g. `++called` in a // subclass constructor is visible after `new SubClass(...)` returns). - emit_class_capture_writeback(ctx, class, &obj_handle); + emit_class_capture_writeback(ctx, class, &obj_handle, args); let is_derived = class.extends.is_some() || class.extends_name.is_some() || class.native_extends.is_some() @@ -1878,10 +1878,11 @@ fn lower_new_impl( )); (ptr_reg, lowered_args.len().to_string()) }; - let this_box = match ctx.this_stack.last().cloned() { - Some(slot) => ctx.block().load(DOUBLE, &slot), - None => undef_lit.clone(), - }; + // Bug #5587: in the no-own-ctor path, `this_stack` was never + // pushed for this `new` call, so `last()` would return the + // outer function's `this` (or undef at module scope). Use + // `obj_box` — the freshly-allocated object — directly. + let this_box = obj_box.clone(); let _ = ctx.block().call( DOUBLE, "js_fetch_or_value_super", diff --git a/crates/perry-hir/src/lower_decl/class_captures.rs b/crates/perry-hir/src/lower_decl/class_captures.rs index 8082ee4e673..bb6bc536d33 100644 --- a/crates/perry-hir/src/lower_decl/class_captures.rs +++ b/crates/perry-hir/src/lower_decl/class_captures.rs @@ -537,21 +537,21 @@ pub fn synthesize_class_captures( // ctor may read a captured outer before calling `super()`, and that read // must already see the recovered value. Only the `this.__perry_cap_* = // param` field STASHES must wait until after `super()` (no `this` exists - // before super). A non-derived ctor has no `super`, so both groups land at - // entry (assignments right after the rebinds). - let rebind_count = rebind_stmts.len(); + // before super) AND after all user stmts (see comment below). for (i, stmt) in rebind_stmts.into_iter().enumerate() { ctor.body.insert(i, stmt); } - // `super_pos` is recomputed AFTER inserting the rebinds (they shifted the - // body), so the assignments land just past the (now-relocated) `super()`. - let super_pos = ctor - .body - .iter() - .position(|s| matches!(s, Stmt::Expr(Expr::SuperCall(_) | Expr::SuperCallSpread(_)))); - let assignment_insert_at = super_pos.map(|p| p + 1).unwrap_or(rebind_count); - for (i, stmt) in assignment_stmts.into_iter().enumerate() { - ctor.body.insert(assignment_insert_at + i, stmt); + // The field STASHES (`this.__perry_cap_* = param`) must come AFTER + // `super()` (no `this` exists before super in derived classes) AND after + // ALL user body stmts — user code may mutate the outer-local after + // `super()` (e.g. `++called` in the TemporalHelpers sub-check pattern). + // Inserting immediately after `super()` captured the pre-mutation value. + // Appending at the end ensures the stash records the final value, which + // `emit_class_capture_writeback` then propagates back to the outer slot. + // Note: constructors with early `return` are not handled here (the stash + // would not fire on the early-exit path); that is a separate concern. + for stmt in assignment_stmts { + ctor.body.push(stmt); } *constructor = Some(ctor); diff --git a/crates/perry-runtime/src/temporal/duration.rs b/crates/perry-runtime/src/temporal/duration.rs index 87ef76d5791..b5105c2bb7a 100644 --- a/crates/perry-runtime/src/temporal/duration.rs +++ b/crates/perry-runtime/src/temporal/duration.rs @@ -22,6 +22,26 @@ pub(crate) fn wrap(d: Duration) -> f64 { alloc_temporal_cell(TemporalValue::Duration(d)) } +/// Round each Duration field to its nearest float64-representable integer. +/// The ECMAScript spec coerces Duration fields through ℝ(𝔽(·)) after arithmetic +/// (add, subtract, round) so the stored value never carries sub-float64 precision +/// that JS Numbers cannot represent. temporal_rs works in i128, so without this +/// step `toString()` and subsequent arithmetic would diverge from the spec. +fn f64_round_duration(d: Duration) -> Duration { + ok_or_throw(Duration::new( + (d.years() as f64) as i64, + (d.months() as f64) as i64, + (d.weeks() as f64) as i64, + (d.days() as f64) as i64, + (d.hours() as f64) as i64, + (d.minutes() as f64) as i64, + (d.seconds() as f64) as i64, + (d.milliseconds() as f64) as i64, + (d.microseconds() as f64) as i128, + (d.nanoseconds() as f64) as i128, + )) +} + /// `new Temporal.Duration(years?, months?, …, nanoseconds?)` — every argument /// is an optional integer defaulting to 0. pub fn construct(args: &[f64]) -> f64 { @@ -193,8 +213,12 @@ pub fn call(recv: f64, d: &Duration, name: &str, args: &[f64]) -> f64 { match name { "negated" => wrap(d.negated()), "abs" => wrap(d.abs()), - "add" => wrap(ok_or_throw(d.add(&coerce_duration(raw_arg(args, 0))))), - "subtract" => wrap(ok_or_throw(d.subtract(&coerce_duration(raw_arg(args, 0))))), + "add" => wrap(f64_round_duration(ok_or_throw( + d.add(&coerce_duration(raw_arg(args, 0))), + ))), + "subtract" => wrap(f64_round_duration(ok_or_throw( + d.subtract(&coerce_duration(raw_arg(args, 0))), + ))), "with" => with(d, raw_arg(args, 0)), // `toString` honors a `{ fractionalSecondDigits, smallestUnit, // roundingMode }` options bag; `toJSON`/`toLocaleString` always use the @@ -208,7 +232,7 @@ pub fn call(recv: f64, d: &Duration, name: &str, args: &[f64]) -> f64 { "valueOf" => dispatch::throw_value_of(TYPE_NAME), "round" => { let (opts, rel) = super::options::duration_round_options(raw_arg(args, 0)); - wrap(ok_or_throw(d.round(opts, rel))) + wrap(f64_round_duration(ok_or_throw(d.round(opts, rel)))) } "total" => { let (unit, rel) = super::options::total_options(raw_arg(args, 0)); diff --git a/crates/perry/tests/issue_5587_temporal_subclass.rs b/crates/perry/tests/issue_5587_temporal_subclass.rs index 16bce13b0ec..49534b90d6d 100644 --- a/crates/perry/tests/issue_5587_temporal_subclass.rs +++ b/crates/perry/tests/issue_5587_temporal_subclass.rs @@ -187,3 +187,97 @@ console.log("add-month:", later.month); // 8 add-month: 8\n" ); } + +#[test] +fn temporal_subclass_capture_writeback_inner_class() { + // Regression for #5587: when a class is declared INSIDE a function and + // extends a Temporal type, the constructor mutates a captured outer local + // (`++called`) AFTER calling `super()`. Prior to the fix, the + // `this.__perry_cap_` stash was inserted immediately after `super()`, + // recording the pre-mutation value 0; `emit_class_capture_writeback` + // then wrote 0 back to the outer slot, making `called` appear untouched. + // The fix moves the stash to the END of the constructor body. + let dir = tempfile::tempdir().expect("tempdir"); + let stdout = compile_and_run( + dir.path(), + r#" +function check(construct: any, constructArgs: any[]) { + let called = 0; + class MySubclass extends construct { + constructor() { + ++called; + super(...constructArgs); + } + } + const instance = new MySubclass(); + return called; +} + +console.log("duration called:", check(Temporal.Duration, [0, 0, 0, -4])); // 1 +console.log("plain-date called:", check(Temporal.PlainDate, [2021, 7, 20])); // 1 +"#, + ); + assert_eq!( + stdout, + "duration called: 1\n\ + plain-date called: 1\n" + ); +} + +#[test] +fn temporal_plain_date_no_ctor_subclass_cell_stashed() { + // Regression for #5587: a subclass with NO explicit constructor that + // overrides getters must still have the Temporal cell stashed so that + // `compare()` / `instanceof` / inherited methods use internal slots, not + // the (potentially throwing) getter overrides. + let dir = tempfile::tempdir().expect("tempdir"); + let stdout = compile_and_run( + dir.path(), + r#" +class AvoidGettersDate extends Temporal.PlainDate { + get year() { return -99; } +} + +const a = new AvoidGettersDate(2000, 5, 2); +const b = new Temporal.PlainDate(2006, 3, 25); +console.log("instanceof:", a instanceof Temporal.PlainDate); // true +// compare() must use internal slots, NOT the overridden .year getter +const cmp = Temporal.PlainDate.compare(a, b); +console.log("compare:", cmp); // -1 (2000 < 2006) +"#, + ); + assert_eq!( + stdout, + "instanceof: true\n\ + compare: -1\n" + ); +} + +#[test] +fn duration_add_f64_representable_precision() { + // Regression for #5587 / test262 float64-representable-integer: + // After `add()`, `subtract()`, and `round()`, Duration fields must be + // clamped to their nearest float64-representable value — they must not + // carry sub-float64 precision that JS Numbers can't express. + let dir = tempfile::tempdir().expect("tempdir"); + let stdout = compile_and_run( + dir.path(), + r#" +// 9007199254740991 + 9007199254740990 = 18014398509481981 (not f64-exact) +// ℝ(𝔽(18014398509481981)) = 18014398509481980 +const d = new Temporal.Duration(0, 0, 0, 0, 0, 0, 0, 0, Number.MAX_SAFE_INTEGER, 0); +const result = d.add({ microseconds: Number.MAX_SAFE_INTEGER - 1 }); + +console.log("microseconds:", result.microseconds); // 18014398509481980 +console.log("toString:", result.toString()); // PT18014398509.48198S +// subsequent add of 1 µs must still compare equal (internal value = 18014398509481980) +console.log("compare:", Temporal.Duration.compare(result.add({ microseconds: 1 }), result)); // 0 +"#, + ); + assert_eq!( + stdout, + "microseconds: 18014398509481980\n\ + toString: PT18014398509.48198S\n\ + compare: 0\n" + ); +} From 836fe8d2c699a03f4afcb85cea6c1d2a0cd73b41 Mon Sep 17 00:00:00 2001 From: Ralph Date: Tue, 30 Jun 2026 06:03:21 -0700 Subject: [PATCH 2/3] style: rustfmt capture_writeback.rs Co-Authored-By: Claude Sonnet 4.6 --- .../src/lower_call/capture_writeback.rs | 25 +++++++++---------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/crates/perry-codegen/src/lower_call/capture_writeback.rs b/crates/perry-codegen/src/lower_call/capture_writeback.rs index 46479fb4014..2cdc7b85426 100644 --- a/crates/perry-codegen/src/lower_call/capture_writeback.rs +++ b/crates/perry-codegen/src/lower_call/capture_writeback.rs @@ -62,19 +62,18 @@ pub(crate) fn emit_class_capture_writeback( // cap_args_start + cap_idx is a LocalGet whose id is the // *current-scope* id — correct even when the class was inlined into a // different scope and local IDs were alpha-renamed. - let current_scope_id: Option = - new_args - .get(cap_args_start + cap_idx) - .and_then(|arg| { - if let perry_hir::Expr::LocalGet(id) = arg { - Some(*id) - } else { - None - } - }) - // Fallback to the numeric suffix from __perry_cap_ for - // call sites that don't supply new_args (empty slice). - .or_else(|| id_str.parse::().ok()); + let current_scope_id: Option = new_args + .get(cap_args_start + cap_idx) + .and_then(|arg| { + if let perry_hir::Expr::LocalGet(id) = arg { + Some(*id) + } else { + None + } + }) + // Fallback to the numeric suffix from __perry_cap_ for + // call sites that don't supply new_args (empty slice). + .or_else(|| id_str.parse::().ok()); let Some(outer_id) = current_scope_id else { continue; }; From 3c7e75d77771468b2c38b6a13014917b7c78f018 Mon Sep 17 00:00:00 2001 From: Ralph Date: Tue, 30 Jun 2026 07:00:19 -0700 Subject: [PATCH 3/3] fix+test: address CodeRabbit review on #5587 PR MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four fixes from CodeRabbit review: 1. **caps_absent_from_args → pass &[] to emit_class_capture_writeback** (`crates/perry-codegen/src/lower_call/new.rs`) When `caps_absent_from_args` is true (member-callee `new ns.C()` path), ALL lowered_args are user args — no cap args were appended. Passing the raw HIR `args` let the position-based cap-lookup misidentify a user `LocalGet` as a capture arg and write to the wrong outer slot. Fix: pass `&[]` so the suffix-based fallback is used instead. 2. **Insert stash before every explicit `return` in constructor body** (`crates/perry-hir/src/lower_decl/class_captures.rs`) The `this.__perry_cap_* = param` stash was only appended at the end of the body; an early `return` in the constructor would skip it and leave `emit_class_capture_writeback` with a stale value. Added `insert_stashes_before_returns()` which recursively inserts the stash immediately before every `Stmt::Return` inside `if`/`while`/`for`/ `try`/`switch`, covering all early-exit paths. 3. **PlainDate compare test: getter must throw, not return a plausible value** (`crates/perry/tests/issue_5587_temporal_subclass.rs`) The `get year() { return -99; }` override still produced an ordering consistent with the expected result, so the test passed even if `compare()` wrongly read the getter. Changed to `throw` so any erroneous accessor call fails the test observably. 4. **Capture writeback test: `++called` must be AFTER `super()`** (`crates/perry/tests/issue_5587_temporal_subclass.rs`) With `++called` BEFORE `super()`, the old stash-after-super code also recorded value 1 (increment happened before the stash), so the test passed regardless of the Bug 1a fix. Moved `++called` to after `super(...constructArgs)` to actually exercise the stash-at-end fix. Co-Authored-By: Claude Sonnet 4.6 --- crates/perry-codegen/src/lower_call/new.rs | 9 ++- .../src/lower_decl/class_captures.rs | 74 ++++++++++++++++++- .../tests/issue_5587_temporal_subclass.rs | 36 ++++++--- 3 files changed, 102 insertions(+), 17 deletions(-) diff --git a/crates/perry-codegen/src/lower_call/new.rs b/crates/perry-codegen/src/lower_call/new.rs index 50b0bfcc2a3..c1059bcff66 100644 --- a/crates/perry-codegen/src/lower_call/new.rs +++ b/crates/perry-codegen/src/lower_call/new.rs @@ -1245,7 +1245,14 @@ fn lower_new_impl( // updates the outer local's alloca slot. Read the fields back here so // the enclosing scope sees the updated values (e.g. `++called` in a // subclass constructor is visible after `new SubClass(...)` returns). - emit_class_capture_writeback(ctx, class, &obj_handle, args); + // When `caps_absent_from_args` is true (member-callee `new ns.C()` + // path), the HIR `args` slice contains ONLY user args — the cap args + // were NOT appended. Passing `args` to `emit_class_capture_writeback` + // would let the position-based lookup misidentify a user `LocalGet` as + // a cap arg and write to the wrong outer slot. Fall back to suffix-based + // lookup (empty slice) in that case. + let writeback_args = if caps_absent_from_args { &[][..] } else { args }; + emit_class_capture_writeback(ctx, class, &obj_handle, writeback_args); let is_derived = class.extends.is_some() || class.extends_name.is_some() || class.native_extends.is_some() diff --git a/crates/perry-hir/src/lower_decl/class_captures.rs b/crates/perry-hir/src/lower_decl/class_captures.rs index bb6bc536d33..2bc7e0adf37 100644 --- a/crates/perry-hir/src/lower_decl/class_captures.rs +++ b/crates/perry-hir/src/lower_decl/class_captures.rs @@ -546,10 +546,9 @@ pub fn synthesize_class_captures( // ALL user body stmts — user code may mutate the outer-local after // `super()` (e.g. `++called` in the TemporalHelpers sub-check pattern). // Inserting immediately after `super()` captured the pre-mutation value. - // Appending at the end ensures the stash records the final value, which - // `emit_class_capture_writeback` then propagates back to the outer slot. - // Note: constructors with early `return` are not handled here (the stash - // would not fire on the early-exit path); that is a separate concern. + // Insert stashes before each explicit `return` so they run on every exit + // path, then append at the end for the fall-through path. + insert_stashes_before_returns(&mut ctor.body, &assignment_stmts); for stmt in assignment_stmts { ctor.body.push(stmt); } @@ -578,6 +577,73 @@ pub fn synthesize_class_captures( ctx.register_class_captures(name.to_string(), captures_vec); } +/// Recursively insert `stashes` immediately before every `Stmt::Return` in +/// `body` so that cap-field stash assignments run on EVERY early-exit path, +/// not just the fall-through. Does not descend into nested function +/// expressions (closures defined inside the constructor) — only direct +/// control-flow of the constructor body itself. +fn insert_stashes_before_returns(body: &mut Vec, stashes: &[Stmt]) { + let mut i = 0; + while i < body.len() { + // Check via shared ref first to decide what to do. + let is_return = matches!(body[i], Stmt::Return(_)); + if is_return { + for (j, s) in stashes.iter().enumerate() { + body.insert(i + j, s.clone()); + } + i += stashes.len() + 1; + continue; + } + // Recurse into nested control-flow via mutable ref. + match &mut body[i] { + Stmt::If { + then_branch, + else_branch, + .. + } => { + insert_stashes_before_returns(then_branch, stashes); + if let Some(eb) = else_branch { + insert_stashes_before_returns(eb, stashes); + } + } + Stmt::While { body: wb, .. } | Stmt::DoWhile { body: wb, .. } => { + insert_stashes_before_returns(wb, stashes); + } + Stmt::For { body: fb, .. } => { + insert_stashes_before_returns(fb, stashes); + } + Stmt::Labeled { body: lb, .. } => match lb.as_mut() { + Stmt::While { body: wb, .. } + | Stmt::DoWhile { body: wb, .. } + | Stmt::For { body: wb, .. } => { + insert_stashes_before_returns(wb, stashes); + } + _ => {} + }, + Stmt::Try { + body: tb, + catch, + finally, + } => { + insert_stashes_before_returns(tb, stashes); + if let Some(c) = catch { + insert_stashes_before_returns(&mut c.body, stashes); + } + if let Some(f) = finally { + insert_stashes_before_returns(f, stashes); + } + } + Stmt::Switch { cases, .. } => { + for case in cases { + insert_stashes_before_returns(&mut case.body, stashes); + } + } + _ => {} + } + i += 1; + } +} + /// Append `cap_args` (the `.1` ids) to every `new (…)` site in /// `expr`, descending nested closures (patching their capture lists when the /// appended id is otherwise unreferenced). With `skip_if_present`, a site diff --git a/crates/perry/tests/issue_5587_temporal_subclass.rs b/crates/perry/tests/issue_5587_temporal_subclass.rs index 49534b90d6d..210fc83f943 100644 --- a/crates/perry/tests/issue_5587_temporal_subclass.rs +++ b/crates/perry/tests/issue_5587_temporal_subclass.rs @@ -190,13 +190,22 @@ console.log("add-month:", later.month); // 8 #[test] fn temporal_subclass_capture_writeback_inner_class() { - // Regression for #5587: when a class is declared INSIDE a function and - // extends a Temporal type, the constructor mutates a captured outer local - // (`++called`) AFTER calling `super()`. Prior to the fix, the - // `this.__perry_cap_` stash was inserted immediately after `super()`, - // recording the pre-mutation value 0; `emit_class_capture_writeback` - // then wrote 0 back to the outer slot, making `called` appear untouched. - // The fix moves the stash to the END of the constructor body. + // Regression for #5587 (Bug 1a + Bug 1b): + // + // Bug 1a — stash placement: the `this.__perry_cap_called = param` stash + // was inserted immediately after `super()`. When user code runs `++called` + // AFTER `super()` the stash recorded the pre-mutation value 0 and + // `emit_class_capture_writeback` wrote 0 back to the outer slot. + // Fix: append stash at END of ctor body (after all user stmts). + // + // Bug 1b — inlined-scope ID mismatch: when `check(...)` is called at + // module level, Perry inlines its body into module-init and alpha-renames + // locals (`called` id=2 → id=9). The old suffix-based writeback looked + // up `ctx.locals[2]` (not found) and silently skipped. Fix: position- + // based cap-arg lookup resolves the current-scope id from the `New` args. + // + // Two variants: post-super mutation (Bug 1a) and module-level inlining + // (Bug 1b, exercised by calling check() at module level below). let dir = tempfile::tempdir().expect("tempdir"); let stdout = compile_and_run( dir.path(), @@ -205,16 +214,17 @@ function check(construct: any, constructArgs: any[]) { let called = 0; class MySubclass extends construct { constructor() { - ++called; super(...constructArgs); + ++called; // mutates AFTER super() — exercises Bug 1a stash placement } } - const instance = new MySubclass(); + new MySubclass(); return called; } -console.log("duration called:", check(Temporal.Duration, [0, 0, 0, -4])); // 1 -console.log("plain-date called:", check(Temporal.PlainDate, [2021, 7, 20])); // 1 +// Called at module level → inlined into module-init (Bug 1b: alpha-renamed ids) +console.log("duration called:", check(Temporal.Duration, [0, 0, 0, -4])); // 1 +console.log("plain-date called:", check(Temporal.PlainDate, [2021, 7, 20])); // 1 "#, ); assert_eq!( @@ -235,7 +245,9 @@ fn temporal_plain_date_no_ctor_subclass_cell_stashed() { dir.path(), r#" class AvoidGettersDate extends Temporal.PlainDate { - get year() { return -99; } + // Throw so that any call to this getter causes an observable failure — + // compare() must use internal slots and never invoke this accessor. + get year() { throw new Error("year accessor must not be called by compare()"); } } const a = new AvoidGettersDate(2000, 5, 2);