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
23 changes: 23 additions & 0 deletions crates/perry-codegen/src/expr/new_dynamic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,29 @@ pub(crate) fn lower(ctx: &mut FnCtx<'_>, expr: &Expr) -> Result<String> {
"js_new_function_construct_apply",
&[(DOUBLE, &func_double), (DOUBLE, &args_box)],
);
// Write-back: when the callee is a statically-known user class,
// propagate constructor mutations (e.g. `++called`) back to the
// outer captured locals. The runtime construction path stores
// mutations to `inst.__perry_cap_*` but cannot reach the caller's
// outer alloca slots directly.
// Also handles `LocalGet(id)` where the local was assigned a
// ClassRef (e.g. `const ctor = C; new (ctor as any)(...args)`).
let class_name: Option<String> = match callee.as_ref() {
Expr::ClassRef(cn) => Some(cn.clone()),
Expr::LocalGet(id) => ctx
.local_id_to_name
.get(id)
.and_then(|name| ctx.local_class_aliases.get(name))
.cloned(),
_ => None,
};
if let Some(cn) = class_name {
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);
Comment on lines +160 to +162

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Don’t read capture fields from the return-override result.

result is the value returned by js_new_function_construct_apply; for constructors that explicitly return an object/function, it may not be the allocated receiver that received this.__perry_cap_*. Reading write-back fields from result can write undefined/wrong data back to outer locals. The write-back needs access to the actual constructed receiver before return override, or equivalent runtime support.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/perry-codegen/src/expr/new_dynamic.rs` around lines 160 - 162, The
write-back in new_dynamic::js_new_function_construct_apply is incorrectly
reading capture fields from the return-override value `result`, which may not be
the actual constructed receiver. Update the logic around
`emit_class_capture_writeback` so it uses the real allocated receiver before any
return override (or equivalent runtime support) when extracting `__perry_cap_*`
data, rather than bitcasting `result` into `inst_handle`. Ensure the fix is
applied in the constructor lowering path where `ctx.block()` computes `bits` and
`inst_handle`.

}
}
Ok(result)
}

Expand Down
27 changes: 25 additions & 2 deletions crates/perry-codegen/src/expr/proxy_reflect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -699,11 +699,34 @@ pub(crate) fn lower(ctx: &mut FnCtx<'_>, expr: &Expr) -> Result<String> {
let t = lower_expr(ctx, target)?;
let a = lower_expr(ctx, args)?;
let nt = lower_expr(ctx, new_target)?;
Ok(ctx.block().call(
let result = ctx.block().call(
DOUBLE,
"js_reflect_construct",
&[(DOUBLE, &t), (DOUBLE, &a), (DOUBLE, &nt)],
))
);
// Write-back captured outer locals: when `target` is a
// statically-known user class, the constructor body stores
// mutations to `this.__perry_cap_*` but can't reach the
// caller's outer alloca slots. Read the fields back here
// (e.g. `++called` in a subclass constructor is visible
// after `Reflect.construct(Sub, args)` returns).
let class_name: Option<String> = match target.as_ref() {
Expr::ClassRef(cn) => Some(cn.clone()),
Expr::LocalGet(id) => ctx
.local_id_to_name
.get(id)
.and_then(|name| ctx.local_class_aliases.get(name))
.cloned(),
_ => None,
};
if let Some(cn) = class_name {
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);
Comment on lines +724 to +726

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Use the constructed receiver, not Reflect.construct’s final result.

If the target constructor returns an object/function, result is that override value, while the capture fields were written on the receiver used as this. Reading __perry_cap_* from result can corrupt the caller’s captured locals. Plumb the original receiver out of the runtime construct path or perform write-back before applying return override.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/perry-codegen/src/expr/proxy_reflect.rs` around lines 724 - 726, The
writeback in proxy_reflect’s construct path is using Reflect.construct’s final
result instead of the actual receiver object, so captured locals may be read
from the wrong instance. Update the `emit_class_capture_writeback` flow to use
the constructed receiver that was passed as `this` (or move the writeback before
any return-value override is applied), and trace the value through the
`ctx.block()`, `bitcast_double_to_i64`, and `inst_handle` path so
`__perry_cap_*` fields are read from the receiver rather than `result`.

}
}
Ok(result)
}
Expr::ReflectDefineProperty {
target,
Expand Down
82 changes: 82 additions & 0 deletions crates/perry-codegen/src/lower_call/capture_writeback.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
//! Post-construction capture write-back.
//!
//! After a `new ClassName(args…)` or `Reflect.construct(…)` that inlines a
//! constructor which may mutate captured outer locals, this module reads the
//! updated value back from the instance's `__perry_cap_<id>` fields and stores
//! it to the outer local's LLVM alloca slot so the mutation is visible to the
//! caller.

use crate::expr::FnCtx;
use crate::nanbox::POINTER_MASK_I64;
use crate::types::{DOUBLE, I32, I64};

/// After construction of a class whose constructor may have mutated captured
/// outer locals (via `++captured_var`, `captured_var = x`, etc.), read back
/// each `__perry_cap_<id>` field from the freshly-constructed instance and
/// store the updated value to the outer local's LLVM slot.
///
/// ECMAScript requires shared-binding semantics for captured variables: a
/// class nested inside a function shares the SAME binding as the outer scope.
/// Perry's capture mechanism passes the captured value as an extra constructor
/// param (by value), so `++called` inside the constructor only updates the
/// constructor-local copy. After construction completes, this helper reads the
/// mutated value back from `this.__perry_cap_*` and writes it to the outer
/// local's alloca slot, making the mutation visible to the caller.
///
/// `obj_handle` is the raw i64 object pointer (not nanboxed).
pub(crate) fn emit_class_capture_writeback(
ctx: &mut FnCtx<'_>,
class: &perry_hir::Class,
obj_handle: &str,
) {
// Cap params are synthesized in `synthesize_class_captures` as extra
// constructor params with name `__perry_cap_<outer_id>`. They are NOT in
// `class.fields` — they are PropertySet stmts on `this` in the ctor body.
// Iterate ctor params to find which outer locals were captured.
let Some(ctor) = class.constructor.as_ref() else {
return;
};
for param in &ctor.params {
let Some(id_str) = param.name.strip_prefix("__perry_cap_") else {
continue;
};
let Ok(outer_id) = id_str.parse::<u32>() else {
continue;
};
// Only write back to locals that are actually in scope (same-function
// construction). Cross-module construction has no accessible outer local.
let Some(outer_slot) = ctx.locals.get(&outer_id).cloned() else {
continue;
};
// Read the updated capture value from the instance field.
let field_name = &param.name;
let key_idx = ctx.strings.intern(field_name);
let key_handle_global = format!("@{}", ctx.strings.entry(key_idx).handle_global);
let key_box = ctx.block().load(DOUBLE, &key_handle_global);
let key_bits = ctx.block().bitcast_double_to_i64(&key_box);
let key_handle = ctx.block().and(I64, &key_bits, POINTER_MASK_I64);
let val = ctx.block().call(
DOUBLE,
"js_object_get_field_by_name_f64",
&[(I64, obj_handle), (I64, &key_handle)],
);
// Store the updated value. Handle boxed locals (shared across multiple
// closures) via js_box_set; plain locals via a direct slot store.
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);
ctx.block()
.call_void("js_box_set", &[(I64, &box_ptr), (DOUBLE, &val)]);
} else {
ctx.block().store(DOUBLE, &val, &outer_slot);
// If this local also has an i32 fast-path slot (counter / integer
// local), keep it in sync. Use fptosi→i64→trunc→i32 to handle
// unsigned values safely (direct fptosi→i32 is UB above INT32_MAX).
if let Some(i32_slot) = ctx.i32_counter_slots.get(&outer_id).cloned() {
let v_i64 = ctx.block().fptosi(DOUBLE, &val, crate::types::I64);
let v_i32 = ctx.block().trunc(crate::types::I64, &v_i64, I32);
ctx.block().store(I32, &v_i32, &i32_slot);
Comment on lines +75 to +78

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Avoid fptosi on arbitrary JS values.

val comes from an object field and can be any NaN-boxed JS value; converting NaN-boxed pointers/strings/undefined with fptosi can generate poison/UB and corrupt the i32 fast-path slot. Reuse the normal local-write/type-guard path here, or only update i32_counter_slots after proving the value is numeric and representable.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/perry-codegen/src/lower_call/capture_writeback.rs` around lines 75 -
78, The i32 fast-path in capture_writeback is using fptosi/trunc on val before
storing into i32_counter_slots, but val may be any JS NaN-boxed value. Update
the logic in capture_writeback to avoid converting arbitrary values directly:
either route through the existing local-write/type-guard path used for normal
assignments, or add a numeric/representable check before doing the DOUBLE to
I64/I32 conversion and store only when safe. Keep the fix scoped to the
i32_counter_slots update path and the surrounding value handling in
capture_writeback.

}
}
}
}
5 changes: 3 additions & 2 deletions crates/perry-codegen/src/lower_call/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ use crate::expr::{variant_name, FnCtx};
mod atomics;
mod buffer_intrinsic;
mod builtin;
mod capture_writeback;
mod closure_analysis;
mod console_promise;
mod early_branches;
Expand Down Expand Up @@ -103,8 +104,8 @@ pub(crate) use native::lower_native_method_call;
// etc. keep resolving after the split.
pub(crate) use field_init::{apply_field_initializers_recursive, FieldInitMode};
pub(crate) use new::{
bind_inline_constructor_params, lower_new, lower_new_member_captured,
restore_inline_constructor_scope, CaptureFill,
bind_inline_constructor_params, emit_class_capture_writeback, lower_new,
lower_new_member_captured, restore_inline_constructor_scope, CaptureFill,
};
// The derived-ctor no-super static-throw predicates (shared with the
// standalone-ctor-symbol path in `codegen/method.rs`, which is the default
Expand Down
9 changes: 9 additions & 0 deletions crates/perry-codegen/src/lower_call/new.rs
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,8 @@ fn emit_typed_shape_layout_init(ctx: &mut FnCtx<'_>, class_name: &str, obj_handl
);
}

pub(crate) use super::capture_writeback::emit_class_capture_writeback;

/// Lower `new ClassName(args…)` — Phase C.1.
///
/// Strategy: allocate an anonymous object via `js_object_alloc(0, N)`
Expand Down Expand Up @@ -1226,6 +1228,13 @@ fn lower_new_impl(
// The inline-ctor path does this at its tail (below); this
// standalone-symbol path returns here, so it must do it too.
emit_typed_shape_layout_init(ctx, class_name, &obj_handle);
// Write-back: propagate constructor mutations to outer captured locals.
// The standalone constructor symbol receives captured values by value
// and stores mutations to `this.__perry_cap_*` fields, but never
// 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);
Comment on lines +1231 to +1237

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Mirror write-back on the inline constructor path.

This call fixes only the standalone-symbol branch. The inlined constructor branch later restores constructor locals and returns without emit_class_capture_writeback, so PERRY_INLINE_CTOR=1 or any inline-only constructor path can still lose ++captured mutations. Add the same write-back after constructor scope restoration and before return-override finalization.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/perry-codegen/src/lower_call/new.rs` around lines 1231 - 1237, The
inline constructor path in the new-call lowering is missing the same capture
write-back that the standalone constructor branch already performs. Update the
constructor handling in lower_call/new.rs so that the inline constructor flow
also calls emit_class_capture_writeback(ctx, class, &obj_handle) after
constructor locals are restored and before any return-override finalization,
ensuring mutated captured locals (like ++captured) are propagated back to the
outer scope.

let is_derived = class.extends.is_some()
|| class.extends_name.is_some()
|| class.native_extends.is_some()
Expand Down
18 changes: 18 additions & 0 deletions crates/perry-runtime/src/temporal/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,24 @@ pub fn temporal_value_ref<'a>(value: f64) -> Option<&'a TemporalValue> {
unsafe { Some(&*(*(addr as *const TemporalCell)).value) }
}

/// Like [`temporal_value_ref`] but also resolves `class X extends Temporal.<Type>`
/// subclass instances by reading the stashed `__perry_temporal_cell__` field.
/// Use this in `ToTemporalXxx` coercions so `compare`/`from`/`until`/`since`
/// use internal slots instead of property getters. (#5587)
#[cfg(feature = "temporal")]
#[inline]
#[allow(clippy::needless_lifetimes)]
pub fn temporal_value_ref_or_subclass<'a>(value: f64) -> Option<&'a TemporalValue> {
temporal_value_ref(value).or_else(|| {
let bits = value.to_bits();
if !crate::value::JSValue::from_bits(bits).is_pointer() {
return None;
}
let addr = (bits & NANBOX_PTR_MASK) as usize;
unsafe { crate::object::temporal_subclass_cell(addr) }.and_then(temporal_value_ref)
Comment on lines +266 to +272

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Require a real Temporal-subclass brand here.

This fallback trusts any object that has a __perry_temporal_cell__ field whose value looks like a TemporalValue. Without a brand/prototype check, an ordinary object can be misclassified as a Temporal subclass and bypass the property-bag / observable-getter path in the updated coercions. Please key this off an unforgeable runtime brand (or hidden side-table entry), not just the presence of that string-named field.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/perry-runtime/src/temporal/mod.rs` around lines 266 - 272, The
fallback in temporal_value_ref currently treats any object with a
__perry_temporal_cell__-like field as a Temporal subclass, which is forgeable.
Update the lookup to require an unforgeable runtime brand or hidden side-table
entry in the temporal_subclass_cell path before returning a TemporalValue, and
only use the fallback when that brand check passes. Keep the existing
pointer/value checks intact, but ensure ordinary objects cannot be misclassified
by relying on the string-named field alone.

})
}

/// The brand sub-kind of a Temporal value, or `None` if not a Temporal cell.
#[inline]
pub fn temporal_kind(value: f64) -> Option<TemporalKind> {
Expand Down
8 changes: 5 additions & 3 deletions crates/perry-runtime/src/temporal/plain_date.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
//! a calendar id string selects another (`temporal_rs` owns the calendar math).

use super::dispatch::{self, boolean, ok_or_throw, raw_arg, string, undefined};
use super::{alloc_temporal_cell, temporal_value_ref, TemporalValue};
use super::{
alloc_temporal_cell, temporal_value_ref, temporal_value_ref_or_subclass, TemporalValue,
};
use crate::value::JSValue;
use temporal_rs::{Calendar, PlainDate, PlainTime, TimeZone};

Expand Down Expand Up @@ -58,7 +60,7 @@ fn coerce_date_with_overflow(
v: f64,
overflow: Option<temporal_rs::options::Overflow>,
) -> PlainDate {
match temporal_value_ref(v) {
match temporal_value_ref_or_subclass(v) {
Some(TemporalValue::PlainDate(d)) => return d.clone(),
Some(TemporalValue::PlainDateTime(dt)) => return dt.to_plain_date(),
Some(TemporalValue::ZonedDateTime(z)) => return z.to_plain_date(),
Expand Down Expand Up @@ -92,7 +94,7 @@ pub fn from_static(args: &[f64]) -> f64 {
let _ = super::options::overflow(opts);
return wrap(d);
}
match temporal_value_ref(item) {
match temporal_value_ref_or_subclass(item) {
Some(TemporalValue::PlainDate(d)) => {
let _ = super::options::overflow(opts);
return wrap(d.clone());
Expand Down
6 changes: 4 additions & 2 deletions crates/perry-runtime/src/temporal/plain_date_time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
use super::dispatch::{
self, boolean, field_u16, field_u8, ok_or_throw, raw_arg, string, undefined,
};
use super::{alloc_temporal_cell, temporal_value_ref, TemporalValue};
use super::{
alloc_temporal_cell, temporal_value_ref, temporal_value_ref_or_subclass, TemporalValue,
};
use crate::value::JSValue;
use temporal_rs::{Calendar, PlainDateTime};

Expand Down Expand Up @@ -65,7 +67,7 @@ fn coerce_dt(v: f64) -> PlainDateTime {
/// throws before options are read, and a bag reads its fields first). `opts` is
/// `undefined` for `compare`/`until`/`since` (no options arg).
fn coerce_dt_with_opts(v: f64, opts: f64) -> PlainDateTime {
match temporal_value_ref(v) {
match temporal_value_ref_or_subclass(v) {
Some(TemporalValue::PlainDateTime(dt)) => {
let dt = dt.clone();
let _ = super::options::overflow(opts);
Expand Down
8 changes: 5 additions & 3 deletions crates/perry-runtime/src/temporal/plain_time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
//! the plain types.

use super::dispatch::{self, field_u16, field_u8, ok_or_throw, raw_arg, string};
use super::{alloc_temporal_cell, temporal_value_ref, TemporalValue};
use super::{
alloc_temporal_cell, temporal_value_ref, temporal_value_ref_or_subclass, TemporalValue,
};
use crate::value::JSValue;
use temporal_rs::options::ToStringRoundingOptions;
use temporal_rs::PlainTime;
Expand Down Expand Up @@ -52,7 +54,7 @@ fn coerce_time_overflow(v: f64, overflow: temporal_rs::options::Overflow) -> Pla
// its internal slot — NO observable property getter calls
// (`argument-plaindatetime`'s fast-path assertion). Reading `hour`…`second`
// off such a value as a bag (the old fallthrough) called the getters.
match temporal_value_ref(v) {
match temporal_value_ref_or_subclass(v) {
Some(TemporalValue::PlainTime(t)) => return *t,
Some(TemporalValue::PlainDateTime(dt)) => return dt.to_plain_time(),
Some(TemporalValue::ZonedDateTime(z)) => return z.to_plain_time(),
Expand Down Expand Up @@ -107,7 +109,7 @@ pub fn from_static(args: &[f64]) -> f64 {
let _ = super::options::overflow(opts);
return wrap(t);
}
match temporal_value_ref(item) {
match temporal_value_ref_or_subclass(item) {
Some(TemporalValue::PlainTime(t)) => {
let _ = super::options::overflow(opts);
return wrap(*t);
Expand Down
8 changes: 5 additions & 3 deletions crates/perry-runtime/src/temporal/plain_year_month.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
//! A calendar year + month (e.g. a billing period), no day/time/timezone.

use super::dispatch::{self, boolean, ok_or_throw, raw_arg, string, undefined};
use super::{alloc_temporal_cell, temporal_value_ref, TemporalValue};
use super::{
alloc_temporal_cell, temporal_value_ref, temporal_value_ref_or_subclass, TemporalValue,
};
use crate::value::JSValue;
use temporal_rs::PlainYearMonth;

Expand Down Expand Up @@ -47,7 +49,7 @@ pub fn construct(args: &[f64]) -> f64 {
/// (read in spec order with `constrain` overflow). No recognized field, a
/// Symbol, or any non-string primitive → TypeError.
fn coerce_ym(v: f64) -> PlainYearMonth {
if let Some(TemporalValue::PlainYearMonth(ym)) = temporal_value_ref(v) {
if let Some(TemporalValue::PlainYearMonth(ym)) = temporal_value_ref_or_subclass(v) {
return ym.clone();
}
let jv = JSValue::from_bits(v.to_bits());
Expand Down Expand Up @@ -81,7 +83,7 @@ pub fn from_static(args: &[f64]) -> f64 {
let _ = super::options::overflow(opts);
return wrap(ym);
}
if let Some(TemporalValue::PlainYearMonth(ym)) = temporal_value_ref(item) {
if let Some(TemporalValue::PlainYearMonth(ym)) = temporal_value_ref_or_subclass(item) {
let _ = super::options::overflow(opts);
return wrap(ym.clone());
}
Expand Down
Loading