Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/perry-codegen/src/expr/new_dynamic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ pub(crate) fn lower(ctx: &mut FnCtx<'_>, expr: &Expr) -> Result<String> {
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)
Expand Down
2 changes: 1 addition & 1 deletion crates/perry-codegen/src/expr/proxy_reflect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -723,7 +723,7 @@ pub(crate) fn lower(ctx: &mut FnCtx<'_>, expr: &Expr) -> Result<String> {
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)
Expand Down
41 changes: 39 additions & 2 deletions crates/perry-codegen/src/lower_call/capture_writeback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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_<id>` 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_<outer_id>`. They are NOT in
Expand All @@ -36,11 +44,37 @@ 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::<u32>() 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<u32> = 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_<id> for
// call sites that don't supply new_args (empty slice).
.or_else(|| id_str.parse::<u32>().ok());
let Some(outer_id) = current_scope_id else {
continue;
};
// Only write back to locals that are actually in scope (same-function
Expand All @@ -62,6 +96,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);
Expand Down
18 changes: 13 additions & 5 deletions crates/perry-codegen/src/lower_call/new.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
// 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()
Expand Down Expand Up @@ -1878,10 +1885,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",
Expand Down
90 changes: 78 additions & 12 deletions crates/perry-hir/src/lower_decl/class_captures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -537,21 +537,20 @@ 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.
// 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);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
*constructor = Some(ctor);

Expand All @@ -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<Stmt>, 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 <class_name>(…)` site in
/// `expr`, descending nested closures (patching their capture lists when the
/// appended id is otherwise unreferenced). With `skip_if_present`, a site
Expand Down
30 changes: 27 additions & 3 deletions crates/perry-runtime/src/temporal/duration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand All @@ -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));
Expand Down
106 changes: 106 additions & 0 deletions crates/perry/tests/issue_5587_temporal_subclass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,109 @@ console.log("add-month:", later.month); // 8
add-month: 8\n"
);
}

#[test]
fn temporal_subclass_capture_writeback_inner_class() {
// 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(),
r#"
function check(construct: any, constructArgs: any[]) {
let called = 0;
class MySubclass extends construct {
constructor() {
super(...constructArgs);
++called; // mutates AFTER super() — exercises Bug 1a stash placement
}
}
new MySubclass();
return called;
}

// 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!(
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 {
// 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);
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)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
"#,
);
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"
);
}
Loading