Skip to content
Closed
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
1 change: 1 addition & 0 deletions changelog.d/8820-call-return-array-stores.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Array index assignments whose base is a call expression now preserve the call's statically known Array type and use the typed array-store path while evaluating the base exactly once. Strict writes through that path also honor non-writable and accessor descriptors, read-only length, and non-extensible holes.
175 changes: 175 additions & 0 deletions crates/perry-codegen/src/expr/call_return_array_index_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
use crate::{compile_module, CompileOptions};
use perry_hir::types::Type;
use perry_hir::{Class, Expr, Function, Module, Param, Stmt};

fn param(id: u32, name: &str, ty: Type) -> Param {
Param {
id,
name: name.to_string(),
ty,
default: None,
decorators: Vec::new(),
is_rest: false,
arguments_object: None,
}
}

fn function(
id: u32,
name: &str,
params: Vec<Param>,
return_type: Type,
body: Vec<Stmt>,
) -> Function {
Function {
id,
name: name.to_string(),
type_params: Vec::new(),
params,
return_type,
body,
is_async: false,
is_generator: false,
is_strict: true,
is_exported: false,
captures: Vec::new(),
decorators: Vec::new(),
was_plain_async: false,
was_unrolled: false,
}
}

fn call_get_data(selector: i64) -> Expr {
Expr::Call {
callee: Box::new(Expr::PropertyGet {
object: Box::new(Expr::This),
property: "getData".to_string(),
byte_offset: 0,
}),
args: vec![Expr::Integer(selector)],
type_args: Vec::new(),
byte_offset: 0,
}
}

fn store_class(receiver_selector: i64) -> Class {
let get_data = function(
2,
"getData",
vec![param(3, "selector", Type::Number)],
Type::Array(Box::new(Type::Any)),
vec![Stmt::Return(Some(Expr::Array(vec![Expr::Number(0.0)])))],
);
let write = function(
3,
"write",
vec![
param(1, "index", Type::Number),
param(2, "value", Type::Any),
],
Type::Void,
vec![Stmt::Expr(Expr::PutValueSet {
target: Box::new(call_get_data(0)),
key: Box::new(Expr::LocalGet(1)),
value: Box::new(Expr::LocalGet(2)),
receiver: Box::new(call_get_data(receiver_selector)),
strict: true,
})],
);
Class {
id: 1,
name: "Store".to_string(),
type_params: Vec::new(),
extends: None,
extends_name: None,
native_extends: None,
extends_expr: None,
heritage_lexically_shadowed: false,
fields: Vec::new(),
constructor: None,
methods: vec![get_data, write],
getters: Vec::new(),
setters: Vec::new(),
static_accessor_names: Vec::new(),
static_accessor_fn_ids: Vec::new(),
computed_members: Vec::new(),
static_fields: Vec::new(),
static_methods: Vec::new(),
decorators: Vec::new(),
is_exported: false,
aliases: Vec::new(),
is_nested: false,
alloc_width_hint: 0,
specialized_from: None,
}
}

fn compile_store_ir(receiver_selector: i64) -> String {
let mut module = Module::new("call_return_array_put_value.ts");
module.classes.push(store_class(receiver_selector));
let bytes = compile_module(
&module,
CompileOptions {
emit_ir_only: true,
..Default::default()
},
)
.expect("call-returned array store compiles");
String::from_utf8(bytes).expect("LLVM IR is UTF-8")
}

fn write_method_ir(ir: &str) -> &str {
let signature = "define double @perry_method_call_return_array_put_value_ts__Store__write(";
let start = ir.find(signature).expect("write method is present in IR");
let method_and_rest = &ir[start..];
let end = method_and_rest
.find("\n}\n")
.expect("write method has a closing brace");
&method_and_rest[..end + 3]
}

#[test]
fn same_call_returned_array_uses_array_index_store_and_evaluates_receiver_once() {
let ir = compile_store_ir(0);
let write_ir = write_method_ir(&ir);

assert!(
write_ir.contains("call i64 @js_typed_feedback_array_set_index_or_string("),
"a call with an Array return type must use the array-index semantic fallback:\n{write_ir}"
);
assert!(
!write_ir.contains("call double @js_put_value_set_dyn_ic("),
"the proven array receiver must not enter the generic Proxy-compatible PutValue ladder:\n{write_ir}"
);
assert_eq!(
write_ir
.matches(
"call double @perry_method_call_return_array_put_value_ts__Store__getData("
)
.count(),
1,
"the syntactically duplicated target/receiver call represents one evaluated assignment base"
);
}

#[test]
fn distinct_call_receiver_stays_on_explicit_receiver_put_value_path() {
let ir = compile_store_ir(1);
let write_ir = write_method_ir(&ir);

assert!(
!write_ir.contains("call i64 @js_typed_feedback_array_set_index_or_string("),
"a receiver that differs from the target must not use same-receiver array lowering:\n{write_ir}"
);
assert!(
write_ir.contains("call double @js_put_value_set("),
"the distinct receiver must be passed to the generic PutValue helper:\n{write_ir}"
);
assert_eq!(
write_ir
.matches("call double @perry_method_call_return_array_put_value_ts__Store__getData(")
.count(),
2,
"target and distinct receiver calls are independently evaluated"
);
}
2 changes: 2 additions & 0 deletions crates/perry-codegen/src/expr/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,8 @@ mod write_pic_barrier_tests;
// temp alloca through the same shadow-slot emission every named local uses,
// and it now lives outside `crate::expr`.
#[cfg(test)]
mod call_return_array_index_tests;
#[cfg(test)]
mod call_spread_rooting_tests;
mod call_spread_short;
#[cfg(test)]
Expand Down
10 changes: 9 additions & 1 deletion crates/perry-codegen/src/expr/proxy_reflect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1260,7 +1260,15 @@ fn is_numeric_string_key(key: &str) -> bool {
}

fn put_value_index_fast_path(ctx: &FnCtx<'_>, target: &Expr, key: &Expr, receiver: &Expr) -> bool {
if !same_side_effect_free_receiver(target, receiver) {
// `PutValueSet` stores the assignment base in both `target` and `receiver`;
// those two HIR trees describe one source evaluation, not two evaluations
// that may be coalesced only when pure. Use the same structural-identity
// check as the generic same-receiver PutValue lowering below so expressions
// such as `this.getData()[index] = value` can retain the statically known
// Array type. `IndexSet::lower` evaluates that base once. A genuinely
// distinct receiver (including a call with different arguments) still
// fails closed to the explicit-receiver runtime path.
if !same_put_value_receiver_expr(target, receiver) {
return false;
}
if is_array_expr(ctx, target) {
Expand Down
50 changes: 44 additions & 6 deletions crates/perry-runtime/src/array/indexing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1084,10 +1084,11 @@ pub extern "C" fn js_array_set_f64(arr: *mut ArrayHeader, index: u32, value: f64
/// (`index_set` / `index` / `field_set_by_name`) routes here.
/// test262 built-ins/Array element/add on frozen|sealed|non-extensible.
/// Strict-mode guard for a would-be `arr[index] = v` element write: throws the
/// spec `Set`-with-`Throw` TypeError when `arr` is frozen (existing index →
/// read-only) or non-extensible and the index is new (→ not-extensible). No-op
/// for writable slots, buffers, and typed arrays (which own their store
/// semantics). Shared by the strict element-write entry points.
/// spec `Set`-with-`Throw` TypeError when an own data descriptor is read-only,
/// an accessor has no setter, `length` is read-only and would grow, the array
/// is frozen, or a non-extensible array would gain a new element. No-op for
/// writable slots, buffers, and typed arrays (which own their store semantics).
/// Shared by the strict element-write entry points.
#[inline]
pub(crate) fn array_strict_index_write_guard(arr: *mut ArrayHeader, index: u32) {
let clean = clean_arr_ptr_mut(arr);
Expand All @@ -1099,12 +1100,49 @@ pub(crate) fn array_strict_index_write_guard(arr: *mut ArrayHeader, index: u32)
}
let flags = array_object_flags(clean);
let length = unsafe { (*clean).length };

// A descriptor-bearing array is rare, so keep all key construction and
// side-table probes off the ordinary dense-array path. An accessor with a
// setter remains writable even when the object is frozen; return early and
// let `js_array_set_f64_extend` invoke it. Every other rejected descriptor
// must throw here because that lower-level helper deliberately retains a
// silent contract for internal DefineOwnProperty callers.
if flags & crate::gc::OBJ_FLAG_ARRAY_DESCRIPTORS != 0 {
let key = index.to_string();
if let Some(accessor) = crate::object::get_accessor_descriptor(clean as usize, &key) {
if accessor.set == 0 {
throw_frozen_array_index_write(index);
}
return;
}
if crate::object::get_property_attrs(clean as usize, &key)
.is_some_and(|attrs| !attrs.writable())
{
throw_frozen_array_index_write(index);
}
if index >= length
&& crate::object::get_property_attrs(clean as usize, "length")
.is_some_and(|attrs| !attrs.writable())
{
crate::collection_iter::throw_type_error(
"Cannot assign to read only property 'length' of object '[object Array]'",
);
}
}

if index < length {
// Existing index: only a *frozen* array's data is non-writable; a
// sealed / non-extensible array still permits overwriting it.
if flags & crate::gc::OBJ_FLAG_FROZEN != 0 {
throw_frozen_array_index_write(index);
}
// `length` includes holes. Filling one creates a new own property, so
// sealed/preventExtensions arrays must reject it even though the index
// is numerically in bounds. This probe is confined to the already-cold
// restricted-object branch.
if flags & (crate::gc::OBJ_FLAG_SEALED | crate::gc::OBJ_FLAG_NO_EXTEND) != 0
&& !unsafe { array_has_own_index(clean, index) }
{
throw_array_not_extensible_add(index);
}
} else if flags
& (crate::gc::OBJ_FLAG_FROZEN | crate::gc::OBJ_FLAG_SEALED | crate::gc::OBJ_FLAG_NO_EXTEND)
!= 0
Expand Down
Loading
Loading