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
33 changes: 33 additions & 0 deletions crates/perry-hir/src/lower/expr_object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,39 @@ fn lower_method_prop(
ctx.exit_scope(scope_mark);
ctx.in_nonarrow_fn = saved_in_nonarrow_fn;

// #5846: retain the method's own source for `Function.prototype.toString`.
// Per spec a concise/object-literal method's toString is
// `PropertyName ( params ) { body }` — no "function" keyword — so slice
// from the key's start (the `[` for a computed key) through the function
// body's closing brace, mirroring `capture_function_source`'s use for
// declarations/expressions/arrows. Without this, `{ a(){} }.a` fell back
// to the synthesized `function a() { [native code] }` form, which is
// wrong when that source is itself used (e.g. as a ToPropertyKey
// coercion target for a computed key elsewhere) — test262
// toString/method-computed-property-name.
//
// Scoped to plain (non-async, non-generator) methods only: an
// `async`/`*` modifier sits BEFORE the key in source (`async *[k](){}`),
// so `method_key_span.lo` would truncate it off the front — and
// toString/{async,generator}-method* were already passing via the
// synthesized-native-form fallback (which conforms to the loose
// NativeFunction-syntax check `assertToStringOrNativeFunction` falls
// back to on an exact-match miss); capturing a truncated real slice here
// would regress them to neither an exact match nor valid NativeFunction
// syntax. TODO: extend to async/generator methods once the modifier
// (and any comments before the key) can be included in the span.
if !method.function.is_async && !method.function.is_generator {
let method_key_span = match &method.key {
ast::PropName::Ident(i) => i.span,
ast::PropName::Str(s) => s.span,
ast::PropName::Num(n) => n.span,
ast::PropName::Computed(c) => c.span,
ast::PropName::BigInt(b) => b.span,
};
let method_src_span = swc_common::Span::new(method_key_span.lo, method.function.span.hi);
super::capture_function_source(ctx, func_id, &method_src_span, false);
}

// Capture analysis (same pattern as arrow/function expressions)
let mut all_refs = Vec::new();
let mut visited_closures = std::collections::HashSet::new();
Expand Down
51 changes: 51 additions & 0 deletions crates/perry-hir/src/lower/fn_ctor_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,17 @@ pub(crate) fn dyn_fn_ctor_kind_of(
while let ast::Expr::Paren(p) = obj {
obj = p.expr.as_ref();
}
// `Object.getPrototypeOf(<fn-literal>).constructor` — the standard idiom
// for reaching the hidden `AsyncFunction`/`GeneratorFunction`/
// `AsyncGeneratorFunction` global constructors, which (unlike `Function`)
// aren't reachable as named globals. `Object.getPrototypeOf(fnExpr)`
// yields fnExpr's `[[Prototype]]` (e.g. `%GeneratorFunction.prototype%`
// for a generator literal), and `.constructor` on THAT is the matching
// hidden constructor — same kind as `fnExpr` itself (test262
// toString/GeneratorFunction.js).
if let Some(kind) = dyn_fn_ctor_kind_via_get_prototype_of(obj, known_literals) {
return Some(kind);
}
if let Some(kind) = fn_literal_kind_of(obj) {
return Some(kind);
}
Expand All @@ -120,6 +131,46 @@ pub(crate) fn dyn_fn_ctor_kind_of(
None
}

/// Match `Object.getPrototypeOf(<arg>)` and resolve `<arg>`'s dynamic-ctor
/// kind (function literal or known single-assignment variable).
fn dyn_fn_ctor_kind_via_get_prototype_of(
obj: &ast::Expr,
known_literals: &HashMap<String, DynFnCtorKind>,
) -> Option<DynFnCtorKind> {
let ast::Expr::Call(call) = obj else {
return None;
};
if call.args.len() != 1 || call.args[0].spread.is_some() {
return None;
}
let ast::Callee::Expr(callee) = &call.callee else {
return None;
};
let mut c = callee.as_ref();
while let ast::Expr::Paren(p) = c {
c = p.expr.as_ref();
}
let ast::Expr::Member(gm) = c else {
return None;
};
let is_get_proto = matches!(&gm.prop, ast::MemberProp::Ident(id) if id.sym.as_ref() == "getPrototypeOf")
&& matches!(gm.obj.as_ref(), ast::Expr::Ident(oid) if oid.sym.as_ref() == "Object");
if !is_get_proto {
return None;
}
let mut inner = call.args[0].expr.as_ref();
while let ast::Expr::Paren(p) = inner {
inner = p.expr.as_ref();
}
if let Some(kind) = fn_literal_kind_of(inner) {
return Some(kind);
}
if let ast::Expr::Ident(id) = inner {
return known_literals.get(id.sym.as_str()).copied();
}
None
}

/// The retained `return`/`throw` statement of a recorded `toString` method.
#[derive(Debug, Clone)]
pub(crate) struct ToStringBody {
Expand Down
157 changes: 157 additions & 0 deletions crates/perry-runtime/src/object/class_registry/construct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,19 @@ pub unsafe extern "C" fn js_new_function_construct(
);
}
}
// `new boundFn(...)` — delegate entirely to the newTarget-aware path,
// which unwinds the bind chain to the real target before re-dispatching
// (see `unwrap_bound_construct_chain`). `new`'s implicit newTarget is
// `func_value` itself, matching spec step "If NewTarget is not present,
// set newTarget to F" for a plain `new`. Bypasses everything below —
// primitive/proxy/non-constructable/native-module checks all re-run on
// the UNWRAPPED target, which is what they need to see (a bound wrapper
// around `Date`, a bound wrapper around a non-constructor, etc.).
if is_bound_function_closure_value(func_value) {
return js_new_function_construct_with_new_target(
func_value, args_ptr, args_len, func_value,
);
}
// `new (new String(""))` / `new (new Number(1))` — a boxed primitive WRAPPER
// object is an ordinary object, never a constructor, so `new` on it throws
// `TypeError` (Test262 `S15.5.5_A2`). Without this it fell through to the
Expand Down Expand Up @@ -1013,6 +1026,12 @@ fn constructor_class_ref_id(value: f64) -> Option<u32> {
/// (non-arrow, non-builtin-method) function closures; false for primitives,
/// arrow functions, and non-constructable builtin functions (e.g. `eval`).
pub(crate) fn js_value_is_constructor(value: f64) -> bool {
// A bound function is a constructor iff its ultimate target is (10.4.1.3
// BoundFunctionExoticObjects don't have their own [[Construct]] slot
// independent of the target's constructibility) — resolve through any
// number of `.bind()` layers first so the checks below (class ref,
// proxy, arrow, non-constructable builtin) see the real callee.
let value = resolve_bound_target(value);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if constructor_class_ref_id(value).is_some() {
return true;
}
Expand All @@ -1025,6 +1044,18 @@ pub(crate) fn js_value_is_constructor(value: f64) -> bool {
if is_arrow_function_value(value) {
return false;
}
// %Function.prototype% itself is callable but has no [[Construct]] slot
// (ECMA-262 20.2.3) — `is_non_constructable_builtin_function_value` only
// covers the separate "reified builtin closure" registry (`eval`, a
// reified `.apply`/`.call`/`.bind` value, …), not this singleton, so it
// needs its own check here too (mirrors `js_new_function_construct`'s
// dedicated `is_function_prototype_object_value` guard). Without this, a
// bound wrapper around it — `Function.prototype.bind()` — would resolve
// through `resolve_bound_target` to Function.prototype and read back as
// constructible.
if super::super::global_this::is_function_prototype_object_value(value) {
return false;
}
if is_non_constructable_builtin_function_value(value) {
return false;
}
Expand Down Expand Up @@ -1093,6 +1124,103 @@ pub(crate) fn extends_target_must_throw(value: f64) -> bool {
false
}

/// Whether `value` is itself a `Function.prototype.bind` result (not
/// recursive — a single-layer tag check).
///
/// `get_valid_func_ptr` re-validates the address range and `CLOSURE_MAGIC`
/// tag itself before touching `func_ptr`, so it's safe to call on ANY
/// pointer-shaped `JSValue` — including a small-handle-band id (Fetch/ws/
/// proxy registry ids) or an otherwise-invalid heap address — without a
/// separate `is_closure_ptr` pre-check. A prior version of this helper
/// dereferenced `(*ptr).type_tag` directly first, which is exactly the
/// unguarded-pointer-shaped-value read this codebase has been bitten by
/// before (#4740-class SIGSEGV on a mis-boxed/handle-band value).
fn bound_function_target_ptr(value: f64) -> Option<*mut crate::closure::ClosureHeader> {
let jv = crate::value::JSValue::from_bits(value.to_bits());
if !jv.is_pointer() {
return None;
}
let ptr = jv.as_pointer::<crate::closure::ClosureHeader>();
if crate::closure::get_valid_func_ptr(ptr) == crate::closure::BOUND_FUNCTION_FUNC_PTR {
Some(ptr as *mut crate::closure::ClosureHeader)
} else {
None
}
}

fn is_bound_function_closure_value(value: f64) -> bool {
bound_function_target_ptr(value).is_some()
}

/// Walk through any number of `Function.prototype.bind` wrapper layers to the
/// ultimate non-bound target. Returns `value` unchanged when it isn't a bound
/// closure (including when it isn't a closure at all) — cheap no-op on the
/// overwhelmingly common non-bound path.
fn resolve_bound_target(value: f64) -> f64 {
let mut cur = value;
loop {
let Some(ptr) = bound_function_target_ptr(cur) else {
return cur;
};
cur = crate::closure::js_closure_get_capture_f64(ptr, 0);
}
}

/// Unwind a `Function.prototype.bind` construct chain of any depth per
/// `BoundFunctionExoticObjects.[[Construct]]` (10.4.1.2): each layer
/// prepends its own bound args to the call-time args before delegating to
/// its target, and resets `newTarget` to the unwrapped target whenever it
/// `SameValue`s the layer being unwound (so a plain `new boundFn()` — where
/// `newTarget` starts out equal to `boundFn` itself — cascades all the way
/// down to the ultimate target, while a `Reflect.construct(boundFn, args,
/// OtherCtor)` leaves `OtherCtor` untouched).
///
/// Returns `None` (no-op, no allocation) when `func_value` isn't a bound
/// closure. Otherwise returns `(target, combined_args, resolved_new_target)`
/// — the caller should re-dispatch construction on `target` with these.
unsafe fn unwrap_bound_construct_chain(
func_value: f64,
args_ptr: *const f64,
args_len: usize,
new_target: f64,
) -> Option<(f64, Vec<f64>, f64)> {
let mut cur = func_value;
let mut nt = new_target;
let mut unwrapped = false;
let mut args: Vec<f64> = if args_ptr.is_null() {
Vec::new()
} else {
std::slice::from_raw_parts(args_ptr, args_len).to_vec()
};
loop {
let Some(ptr) = bound_function_target_ptr(cur) else {
break;
};
unwrapped = true;
let target = crate::closure::js_closure_get_capture_f64(ptr, 0);
if nt.to_bits() == cur.to_bits() {
nt = target;
}
let bound_args_ptr =
crate::closure::js_closure_get_capture_ptr(ptr, 2) as *const crate::array::ArrayHeader;
if !bound_args_ptr.is_null() {
let n = crate::array::js_array_length(bound_args_ptr) as usize;
let mut prefix: Vec<f64> = Vec::with_capacity(n + args.len());
for i in 0..n {
prefix.push(crate::array::js_array_get_f64(bound_args_ptr, i as u32));
}
prefix.extend(args);
args = prefix;
}
cur = target;
}
if unwrapped {
Some((cur, args, nt))
} else {
None
}
}

fn class_object_class_id(value: f64) -> Option<u32> {
if !is_class_object_value(value) {
return None;
Expand Down Expand Up @@ -1214,6 +1342,24 @@ pub unsafe extern "C" fn js_new_function_construct_with_new_target(
} else {
new_target
};
// Unwind any `Function.prototype.bind` wrapper chain BEFORE the
// `nt == func_value` shortcut below — a plain `new boundFn()` arrives
// here with `nt == func_value == boundFn`, and re-dispatching that
// through `js_new_function_construct(boundFn, ...)` would just loop back
// into this same bound closure. Unwrapping first replaces `func_value`
// with the real (non-bound) target and resolves `nt` per
// `BoundFunctionExoticObjects.[[Construct]]`, so the shortcut below (and
// everything after it) sees the real target either way.
if let Some((target, combined_args, resolved_nt)) =
unwrap_bound_construct_chain(func_value, args_ptr, args_len, nt)
{
let (ptr, len) = if combined_args.is_empty() {
(std::ptr::null::<f64>(), 0usize)
} else {
(combined_args.as_ptr(), combined_args.len())
};
return js_new_function_construct_with_new_target(target, ptr, len, resolved_nt);
}
if nt.to_bits() == func_value.to_bits() {
return js_new_function_construct(func_value, args_ptr, args_len);
}
Expand Down Expand Up @@ -1273,6 +1419,17 @@ pub unsafe extern "C" fn js_new_function_construct_with_new_target(
if !is_callable_function_value(func_value) {
return js_new_function_construct(func_value, args_ptr, args_len);
}
// %Function.prototype% has no [[Construct]] slot (ECMA-262 20.2.3) but
// isn't covered by `is_non_constructable_builtin_function_value` (a
// separate "reified builtin closure" registry) — reachable here directly
// via `Reflect.construct(Function.prototype, …, distinctNewTarget)`, or
// after `unwrap_bound_construct_chain` resolves a bound wrapper down to
// it with a non-cascading newTarget.
if super::super::global_this::is_function_prototype_object_value(func_value)
|| super::super::global_this::is_function_prototype_object_value(nt)
{
throw_non_constructable_builtin_function();
}
if is_non_constructable_builtin_function_value(func_value)
|| is_non_constructable_builtin_function_value(nt)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,19 @@ pub extern "C" fn js_set_function_prototype(func: f64, proto: f64) -> u32 {
// DROPPED: store it as the closure's `prototype` dynamic prop so reads
// reflect it and `js_new_function_construct` links instances to it
// (test262 filter/15.4.4.20-6-*, some/15.4.4.17-8-*, map/15.4.4.19-9-3).
if obj_type == crate::gc::GC_TYPE_ARRAY || obj_type == crate::gc::GC_TYPE_LAZY_ARRAY {
// `foo.prototype = someOtherFunction` — a function/closure-valued
// prototype can't join the class-id machinery either (it has no
// ObjectHeader): store it the same way as the array case so
// `js_new_function_construct`'s `linked_user_proto` check links new
// instances to it (test262 built-ins/Function/prototype/apply/
// S15.3.4.3_A1_T1, call/S15.3.4.4_A1_T1 — `FACTORY.prototype =
// Function()` was silently dropped, so `new FACTORY` instances kept
// the auto-created empty prototype instead of inheriting the real
// function's methods).
if obj_type == crate::gc::GC_TYPE_ARRAY
|| obj_type == crate::gc::GC_TYPE_LAZY_ARRAY
|| obj_type == crate::gc::GC_TYPE_CLOSURE
{
let func_ptr = (func_bits & crate::value::POINTER_MASK) as usize;
if func_ptr != 0 && crate::closure::is_closure_ptr(func_ptr) {
crate::closure::closure_set_dynamic_prop(func_ptr, "prototype", proto);
Expand Down
2 changes: 1 addition & 1 deletion crates/perry-runtime/src/object/global_this.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub(crate) use array_error::{
array_prototype_shift_thunk, array_prototype_slice_thunk, array_prototype_sort_thunk,
array_prototype_splice_thunk, array_prototype_unshift_thunk, date_prototype_to_string_thunk,
error_prototype_to_string_thunk, function_prototype_apply_thunk, function_prototype_bind_thunk,
function_prototype_call_thunk, function_prototype_to_string_thunk,
function_prototype_call_thunk, function_prototype_to_string_thunk, generic_array_like_to_vec,
global_this_clear_immediate_thunk, global_this_clear_interval_thunk,
global_this_clear_timeout_thunk, global_this_queue_microtask_thunk,
global_this_rest_array_values, global_this_set_immediate_thunk, global_this_set_interval_thunk,
Expand Down
Loading
Loading