From 7c5fd810115c761291a54c1cf60158eff1f0e6af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Sat, 4 Jul 2026 20:21:20 +0200 Subject: [PATCH] =?UTF-8?q?fix(runtime,codegen):=20#5907=20=E2=80=94=20cla?= =?UTF-8?q?ss=20X=20extends=20Promise=20subclass=20support?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit super(executor) now runs the Promise constructor against a hidden backing cell stashed on the subclass instance; inherited then/catch/finally, NewPromiseCapability(Subclass), and inherited builtin statics (Subclass.resolve/all/race/...) all resolve. Fixes the Promise combinator ctx-ctor + invoke-resolve-every-iteration test262 clusters. --- .../perry-codegen/src/expr/this_super_call.rs | 32 ++++ crates/perry-codegen/src/lower_call/new.rs | 14 +- .../src/lower_call/new_helpers.rs | 25 ++++ .../stdlib_ffi/streams_events.rs | 1 + .../src/object/class_registry.rs | 2 +- .../src/object/class_registry/class_meta.rs | 5 + .../src/object/class_registry/construct.rs | 42 ++++++ .../object/class_registry/parent_static.rs | 20 +++ .../object/field_get_set/get_field_by_name.rs | 40 +++++ .../src/object/native_call_method.rs | 19 +++ .../src/promise/checked_dispatch.rs | 17 ++- crates/perry-runtime/src/promise/mod.rs | 3 + .../src/promise/spec_combinators.rs | 22 ++- crates/perry-runtime/src/promise/subclass.rs | 139 ++++++++++++++++++ crates/perry-runtime/src/promise/then.rs | 24 ++- .../perry-runtime/src/value/dynamic_object.rs | 20 +++ 16 files changed, 407 insertions(+), 18 deletions(-) create mode 100644 crates/perry-runtime/src/promise/subclass.rs diff --git a/crates/perry-codegen/src/expr/this_super_call.rs b/crates/perry-codegen/src/expr/this_super_call.rs index 12c7411914..d944c682a7 100644 --- a/crates/perry-codegen/src/expr/this_super_call.rs +++ b/crates/perry-codegen/src/expr/this_super_call.rs @@ -664,6 +664,38 @@ pub(crate) fn lower(ctx: &mut FnCtx<'_>, expr: &Expr) -> Result { )?; return Ok(double_literal(f64::from_bits(crate::nanbox::TAG_UNDEFINED))); } + // `class X extends Promise` — `super(executor)` runs the + // ECMA-262 27.2.3.1 Promise constructor against a hidden + // backing `Promise` cell stashed on `this`. Inherited + // `then`/`catch`/`finally` unwrap that cell (see + // `promise::subclass::subclass_backing_promise`), so a + // subclass instance behaves as a promise while keeping its + // own `constructor`/`instanceof` identity. + if parent_name.as_str() == "Promise" { + let undef = double_literal(f64::from_bits(crate::nanbox::TAG_UNDEFINED)); + let mut lowered: Vec = Vec::with_capacity(super_args.len()); + for a in super_args { + lowered.push(lower_expr(ctx, a)?); + } + let executor = lowered.first().cloned().unwrap_or_else(|| undef.clone()); + let this_box = match ctx.this_stack.last().cloned() { + Some(slot) => ctx.block().load(DOUBLE, &slot), + None => undef.clone(), + }; + ctx.block().call( + DOUBLE, + "js_promise_subclass_init", + &[(DOUBLE, &this_box), (DOUBLE, &executor)], + ); + let current_class_name = + ctx.class_stack.last().cloned().unwrap_or_default(); + crate::lower_call::apply_field_initializers_recursive( + ctx, + ¤t_class_name, + crate::lower_call::FieldInitMode::SelfOnly, + )?; + return Ok(double_literal(f64::from_bits(crate::nanbox::TAG_UNDEFINED))); + } let fetch_subclass_fn = match parent_name.as_str() { "Request" => Some("js_request_subclass_init"), "Response" => Some("js_response_subclass_init"), diff --git a/crates/perry-codegen/src/lower_call/new.rs b/crates/perry-codegen/src/lower_call/new.rs index 554c079d68..1ec3f2877a 100644 --- a/crates/perry-codegen/src/lower_call/new.rs +++ b/crates/perry-codegen/src/lower_call/new.rs @@ -14,8 +14,9 @@ use super::lower_builtin_new; use super::new_helpers::{ collect_decl_local_ids, ctor_body_calls_super, ctor_body_closure_calls_super, ctor_body_has_value_return, ctor_body_uses_this, ctor_chain_uses_new_target, - effective_constructor_param_count, local_constructor_symbol_exists, map_set_default_super_kind, - node_stream_parent_kind, restore_imported_ctor_new_target, set_imported_ctor_new_target, + effective_constructor_param_count, emit_promise_subclass_init, local_constructor_symbol_exists, + map_set_default_super_kind, node_stream_parent_kind, restore_imported_ctor_new_target, + set_imported_ctor_new_target, }; use crate::expr::{lower_expr, lower_js_args_array, nanbox_pointer_inline, FnCtx}; use crate::nanbox::{double_literal, POINTER_MASK_I64}; @@ -1313,6 +1314,10 @@ fn lower_new_impl( } else { None }; + // `class X extends Promise {}` with no own ctor — `new X(executor)` runs the + // Promise constructor against a hidden backing cell (see new_helpers). + let promise_parent_runtime = + !has_own_ctor && !has_imported_ctor && class.extends_name.as_deref() == Some("Promise"); let map_set_parent_kind = if !has_own_ctor && !has_imported_ctor { map_set_default_super_kind(ctx.classes, class.extends_name.as_deref()) } else { @@ -1653,6 +1658,10 @@ fn lower_new_impl( ); found_inherited_ctor = true; } + if promise_parent_runtime { + emit_promise_subclass_init(ctx, &lowered_args); + found_inherited_ctor = true; + } // If no parent constructor was found (imported class with no // inlineable constructor body), call the cross-module constructor. // Refs #420: walk past empty-bodied ancestors with param_count==0 @@ -1909,6 +1918,7 @@ fn lower_new_impl( if !has_own_ctor && (has_extends || class.extends_expr.is_some()) && !has_imported_ctor { if builtin_parent_runtime.is_some() || fetch_parent_runtime.is_some() + || promise_parent_runtime || (class.extends_expr.is_some() && !has_extends) { apply_field_initializers_recursive(ctx, class_name, FieldInitMode::SelfOnly)?; diff --git a/crates/perry-codegen/src/lower_call/new_helpers.rs b/crates/perry-codegen/src/lower_call/new_helpers.rs index 3acddfd5b5..ed9cb0ccb8 100644 --- a/crates/perry-codegen/src/lower_call/new_helpers.rs +++ b/crates/perry-codegen/src/lower_call/new_helpers.rs @@ -9,6 +9,31 @@ use perry_hir::Expr; use crate::expr::FnCtx; +use crate::types::DOUBLE; + +/// Emit `js_promise_subclass_init(this, executor)` for a no-own-ctor +/// `class X extends Promise {}` on the runtime `new X(executor)` path. Runs the +/// ECMA-262 Promise constructor against a hidden backing cell stashed on the +/// freshly-allocated instance. `lowered_args` are the already-lowered `new` +/// arguments; the first is the executor. +pub(crate) fn emit_promise_subclass_init(ctx: &mut FnCtx<'_>, lowered_args: &[String]) { + let undef = crate::nanbox::double_literal(f64::from_bits(crate::nanbox::TAG_UNDEFINED)); + let executor = lowered_args + .first() + .cloned() + .unwrap_or_else(|| undef.clone()); + let this_box = ctx + .this_stack + .last() + .cloned() + .map(|slot| ctx.block().load(DOUBLE, &slot)) + .unwrap_or(undef); + ctx.block().call( + DOUBLE, + "js_promise_subclass_init", + &[(DOUBLE, &this_box), (DOUBLE, &executor)], + ); +} /// Generic "does any statement in this ctor body satisfy `stmt_pred` or /// contain an expression satisfying `expr_pred`" walker, shared by the diff --git a/crates/perry-codegen/src/runtime_decls/stdlib_ffi/streams_events.rs b/crates/perry-codegen/src/runtime_decls/stdlib_ffi/streams_events.rs index f88fac63c9..b99bb97192 100644 --- a/crates/perry-codegen/src/runtime_decls/stdlib_ffi/streams_events.rs +++ b/crates/perry-codegen/src/runtime_decls/stdlib_ffi/streams_events.rs @@ -11,6 +11,7 @@ pub(crate) fn declare_streams_events(module: &mut LlModule) { module.declare_function("js_event_emitter_subclass_init", DOUBLE, &[DOUBLE]); // #5137 EE subclass init module.declare_function("js_array_subclass_init", DOUBLE, &[DOUBLE, DOUBLE]); // class extends Array module.declare_function("js_map_set_subclass_init", DOUBLE, &[DOUBLE, I32, DOUBLE]); // class extends Map/Set + module.declare_function("js_promise_subclass_init", DOUBLE, &[DOUBLE, DOUBLE]); // class extends Promise module.declare_function("js_node_stream_readable_new", DOUBLE, &[DOUBLE]); module.declare_function( "js_node_stream_readable_subclass_init", diff --git a/crates/perry-runtime/src/object/class_registry.rs b/crates/perry-runtime/src/object/class_registry.rs index c75c2a42ae..ee338234d1 100644 --- a/crates/perry-runtime/src/object/class_registry.rs +++ b/crates/perry-runtime/src/object/class_registry.rs @@ -113,7 +113,7 @@ pub(crate) use construct::{ extends_target_must_throw, function_would_have_own_prototype, is_callable_function_value, js_value_is_constructor, lookup_prototype_method, nm_ctor_fs, nm_ctor_readline, nm_ctor_repl, nm_ctor_stream, nm_ctor_tls, nm_ctor_tty, nm_ctor_vm, nm_ctor_wasi, - ordinary_function_prototype_value_for_read, + ordinary_function_prototype_value_for_read, promise_parent_in_chain, }; pub use construct::{ js_ctor_return_override, js_function_prototype_value_for_read, js_new_function_construct, diff --git a/crates/perry-runtime/src/object/class_registry/class_meta.rs b/crates/perry-runtime/src/object/class_registry/class_meta.rs index f217d2d5ad..1c74479f6a 100644 --- a/crates/perry-runtime/src/object/class_registry/class_meta.rs +++ b/crates/perry-runtime/src/object/class_registry/class_meta.rs @@ -199,6 +199,11 @@ pub(crate) fn identify_global_builtin_constructor(func_value: f64) -> Option<&'s || func_ptr == weak_map_constructor_call_thunk as *const u8 as usize || func_ptr == weak_set_constructor_call_thunk as *const u8 as usize || func_ptr == weak_ref_constructor_call_thunk as *const u8 as usize + // `class X extends Promise` needs its parent VALUE recognized as the + // Promise constructor (for the runtime `new Subclass` / + // `NewPromiseCapability(Subclass)` path). The Promise ctor value + // carries `promise_constructor_call_thunk`. + || func_ptr == promise_constructor_call_thunk as *const u8 as usize || func_ptr == crate::messaging::js_message_channel_constructor_call_error as *const u8 as usize diff --git a/crates/perry-runtime/src/object/class_registry/construct.rs b/crates/perry-runtime/src/object/class_registry/construct.rs index 62426db2f0..a5063640e9 100644 --- a/crates/perry-runtime/src/object/class_registry/construct.rs +++ b/crates/perry-runtime/src/object/class_registry/construct.rs @@ -1374,6 +1374,34 @@ fn new_target_class_id(new_target: f64) -> Option { constructor_class_ref_id(new_target).or_else(|| class_object_class_id(new_target)) } +/// True when class `cid` (or an ancestor) `extends Promise` — its registered +/// dynamic-parent value resolves to the intrinsic `Promise` constructor. Used to +/// run `js_promise_subclass_init` on the dynamic (runtime) `new Subclass(exec)` +/// path, where codegen's `super()` Promise branch never emitted the init (e.g. +/// `NewPromiseCapability(Subclass)` inside a combinator, which calls the runtime +/// `js_new_function_construct` directly rather than a compiled `new`). +pub(crate) fn promise_parent_in_chain(class_id: u32) -> bool { + let mut cid = class_id; + let mut depth = 0u32; + while depth < 32 && cid != 0 { + let parent_val = js_get_dynamic_parent_value(cid); + if matches!( + identify_global_builtin_constructor(parent_val), + Some("Promise") + ) { + return true; + } + match get_parent_class_id(cid) { + Some(p) if p != 0 && p != cid => { + cid = p; + depth += 1; + } + _ => break, + } + } + false +} + unsafe fn construct_registered_class_ref( target_cid: u32, instance_cid: u32, @@ -1419,6 +1447,20 @@ unsafe fn construct_registered_class_ref( super::super::attach_fetch_handle_for_construction(inst, kind, args_ptr, args_len); } } + // ClassRef `new` of a Promise subclass — run the Promise constructor against + // a hidden backing cell (only when the compiled ctor's `super()` didn't + // already attach one). `NewPromiseCapability(Subclass)` reaches here. + if promise_parent_in_chain(target_cid) { + let inst_val = crate::value::js_nanbox_pointer(inst as i64); + if crate::promise::subclass_backing_promise(inst_val).is_none() { + let executor = if args_len >= 1 && !args_ptr.is_null() { + *args_ptr + } else { + f64::from_bits(crate::value::TAG_UNDEFINED) + }; + crate::promise::js_promise_subclass_init(inst_val, executor); + } + } crate::value::js_nanbox_pointer(inst as i64) } diff --git a/crates/perry-runtime/src/object/class_registry/parent_static.rs b/crates/perry-runtime/src/object/class_registry/parent_static.rs index df03e40079..846ce415d8 100644 --- a/crates/perry-runtime/src/object/class_registry/parent_static.rs +++ b/crates/perry-runtime/src/object/class_registry/parent_static.rs @@ -1197,6 +1197,26 @@ pub unsafe extern "C" fn js_class_static_method_call( { return result; } + // `class X extends Promise` — inherited builtin static (`X.all(...)`, + // `X.resolve(...)`, …). Dispatch the spec static with `this` = the subclass + // receiver so `NewPromiseCapability(X)` constructs the subclass. Resolves the + // reified static value and calls it (its thunk reads `this` from the + // implicit-this slot, already bound to `receiver` by the caller above). + if super::promise_parent_in_chain(class_id) + && crate::object::promise_static_function_spec(name).is_some() + { + let static_val = crate::object::js_promise_static_function_value(name.as_ptr(), name.len()); + if static_val.to_bits() != crate::value::TAG_UNDEFINED { + // The reified static thunk reads its `this` constructor from the + // implicit-this slot, so bind it to the subclass receiver for the + // duration of the call — `NewPromiseCapability(receiver)` then + // constructs the subclass. + let prev_this = crate::object::js_implicit_this_set(receiver); + let result = crate::closure::js_native_call_value(static_val, args_ptr, args_len); + crate::object::js_implicit_this_set(prev_this); + return result; + } + } // True miss: no static method and no callable static field resolved on the // class chain. We hand back the receiver (load-bearing for effect's // `.pipe()`-during-init chains, #687) — but that silent class-ref is exactly diff --git a/crates/perry-runtime/src/object/field_get_set/get_field_by_name.rs b/crates/perry-runtime/src/object/field_get_set/get_field_by_name.rs index 1d4a9fd9e7..e535b5619b 100644 --- a/crates/perry-runtime/src/object/field_get_set/get_field_by_name.rs +++ b/crates/perry-runtime/src/object/field_get_set/get_field_by_name.rs @@ -118,6 +118,34 @@ pub extern "C" fn js_object_get_field_by_name( } } } + // `class X extends Promise` instance — a value read of `then`/`catch`/ + // `finally` (`p.then` / `typeof p.finally`, and codegen's `p.finally(cb)` + // which reads the property first) must resolve the reified Promise prototype + // method. The generic prototype walk does not surface these builtin + // `Promise.prototype` methods for a subclass instance, so hook them here when + // no own key shadows them. The method thunks unwrap the backing cell from the + // implicit-this receiver (see `promise_prototype_receiver`). + if !key.is_null() + && ((obj as u64) >> 48) == 0 + && crate::value::addr_class::is_above_handle_band(obj as usize) + { + unsafe { + let name_ptr = (key as *const u8).add(std::mem::size_of::()); + let name_len = (*key).byte_len as usize; + let name = + std::str::from_utf8(std::slice::from_raw_parts(name_ptr, name_len)).unwrap_or(""); + if matches!(name, "then" | "catch" | "finally") + && !super::super::own_key_present(obj as *mut ObjectHeader, key) + { + let boxed = f64::from_bits(JSValue::pointer(obj as *const u8).bits()); + if crate::promise::subclass_backing_promise(boxed).is_some() { + if let Some(m) = crate::promise::promise_proto_method(name) { + return JSValue::from_bits(m.to_bits()); + } + } + } + } + } // A per-evaluation class object (`ClassExprFresh`, #1772/#1787) reaches // here as a RAW heap pointer (a real ObjectHeader, so its top 16 address // bits are 0 — distinguishing it from a `0x7FFE` class-ref value or any @@ -753,6 +781,18 @@ pub extern "C" fn js_object_get_field_by_name( let result = js_class_method_bind(class_value, heap_name, name_len); return JSValue::from_bits(result.to_bits()); } + // `class X extends Promise` — a value read of an inherited + // builtin static (`X.resolve`, `X.all`, …) resolves to the + // reified Promise static (so `X.resolve.bind(X)` works). Only + // fires when no user static shadowed it above. + if super::super::promise_parent_in_chain(class_id) + && super::super::promise_static_function_spec(name).is_some() + { + let v = super::super::js_promise_static_function_value(name_ptr, name_len); + if v.to_bits() != crate::value::TAG_UNDEFINED { + return JSValue::from_bits(v.to_bits()); + } + } if let Some(v) = super::super::class_registry::class_static_accessor_getter_value( class_id, diff --git a/crates/perry-runtime/src/object/native_call_method.rs b/crates/perry-runtime/src/object/native_call_method.rs index 13f09dd31d..42ff4d963e 100644 --- a/crates/perry-runtime/src/object/native_call_method.rs +++ b/crates/perry-runtime/src/object/native_call_method.rs @@ -1505,6 +1505,25 @@ pub unsafe extern "C" fn js_native_call_method( } } + // `class X extends Promise`: inherited `then`/`catch`/`finally` dispatch + // against the hidden backing Promise cell. A subclass override (own field / + // vtable / prototype method) has already been consulted above, so only a + // genuinely inherited builtin reaches here. Bind `this` to the instance so + // the reified thunk unwraps the backing cell and species-chains via + // `receiver.constructor`. (Covers the `X.resolve().finally().then()` chains + // that codegen dispatches straight through `js_native_call_method`.) + if jsval.is_pointer() && matches!(method_name, "then" | "catch" | "finally") { + if crate::promise::subclass_backing_promise(object).is_some() { + if let Some(m) = crate::promise::promise_proto_method(method_name) { + let args = refreshed_args(); + let prev_this = crate::object::js_implicit_this_set(object); + let result = crate::closure::js_native_call_value(m, args.as_ptr(), args.len()); + crate::object::js_implicit_this_set(prev_this); + return result; + } + } + } + // `class X extends Temporal.`: the prototype methods (`add`/`abs`/ // `toString`/…) dispatch via the Temporal brand on the underlying cell, not // the JS prototype chain. All user-defined dispatch (own fields, vtable, diff --git a/crates/perry-runtime/src/promise/checked_dispatch.rs b/crates/perry-runtime/src/promise/checked_dispatch.rs index 1c9700220b..4070589510 100644 --- a/crates/perry-runtime/src/promise/checked_dispatch.rs +++ b/crates/perry-runtime/src/promise/checked_dispatch.rs @@ -56,7 +56,12 @@ pub extern "C" fn js_promise_then_checked( crate::object::js_implicit_this_set(prev); return result; } - if promise_has_own_constructor(promise_addr) { + if promise_has_own_constructor(promise_addr) + || subclass::subclass_backing_promise(promise_val).is_some() + { + // Own `constructor` override OR a `class X extends Promise` instance: + // route through the SpeciesConstructor-aware thunk, which unwraps the + // backing cell and reads `this.constructor` for species chaining. let prev = crate::object::js_implicit_this_set(promise_val); let result = promise_prototype_then_thunk(std::ptr::null(), on_fulfilled, on_rejected); crate::object::js_implicit_this_set(prev); @@ -73,7 +78,10 @@ pub extern "C" fn js_promise_then_checked( #[no_mangle] pub extern "C" fn js_promise_catch_checked(promise_val: f64, on_rejected: f64) -> f64 { let promise_addr = (promise_val.to_bits() & crate::value::POINTER_MASK) as usize; - if promise_has_own_property(promise_addr, "then") || promise_has_own_constructor(promise_addr) { + if promise_has_own_property(promise_addr, "then") + || promise_has_own_constructor(promise_addr) + || subclass::subclass_backing_promise(promise_val).is_some() + { let prev = crate::object::js_implicit_this_set(promise_val); let result = promise_prototype_catch_thunk(std::ptr::null(), on_rejected); crate::object::js_implicit_this_set(prev); @@ -86,7 +94,10 @@ pub extern "C" fn js_promise_catch_checked(promise_val: f64, on_rejected: f64) - #[no_mangle] pub extern "C" fn js_promise_finally_checked(promise_val: f64, on_finally: f64) -> f64 { let promise_addr = (promise_val.to_bits() & crate::value::POINTER_MASK) as usize; - if promise_has_own_property(promise_addr, "then") || promise_has_own_constructor(promise_addr) { + if promise_has_own_property(promise_addr, "then") + || promise_has_own_constructor(promise_addr) + || subclass::subclass_backing_promise(promise_val).is_some() + { let prev = crate::object::js_implicit_this_set(promise_val); let result = promise_prototype_finally_thunk(std::ptr::null(), on_finally); crate::object::js_implicit_this_set(prev); diff --git a/crates/perry-runtime/src/promise/mod.rs b/crates/perry-runtime/src/promise/mod.rs index 7d5dcc75a1..54ab49bbe8 100644 --- a/crates/perry-runtime/src/promise/mod.rs +++ b/crates/perry-runtime/src/promise/mod.rs @@ -26,6 +26,7 @@ pub mod microtasks; pub mod native_async; pub mod scanners; pub mod spec_combinators; +pub mod subclass; pub mod then; // ─── Explicit named re-exports ──────────────────────────────────── @@ -67,6 +68,8 @@ pub use spec_combinators::{ js_promise_reject_spec, js_promise_resolve_spec, js_promise_try_spec, js_promise_with_resolvers_spec, }; +pub use subclass::js_promise_subclass_init; +pub(crate) use subclass::subclass_backing_promise; pub(crate) use then::{ box_promise_ptr, js_promise_attach_handlers, js_promise_attach_settle_listener, mark_rejection_handled, promise_has_own_constructor, promise_has_own_property, diff --git a/crates/perry-runtime/src/promise/spec_combinators.rs b/crates/perry-runtime/src/promise/spec_combinators.rs index ff2e2396da..2d6aa11363 100644 --- a/crates/perry-runtime/src/promise/spec_combinators.rs +++ b/crates/perry-runtime/src/promise/spec_combinators.rs @@ -645,16 +645,24 @@ pub extern "C" fn js_promise_any_spec(this_ctor: f64, iterable: f64) -> f64 { /// Spec `IsObject` — true only for heap object/function values, NOT primitives. /// Symbols are NaN-boxed pointers but are primitives, so exclude them. +/// +/// A `class X extends Promise {}` constructor arriving as `this` for +/// `Promise.resolve`/`Promise.try` is a callable *constructor* value — for user +/// classes this is an INT32-tagged ClassRef, not a POINTER_TAG heap object — so +/// it fails the plain pointer-tag test even though `Type(C) is Object` per spec. +/// Accept any constructor value here so `Promise.resolve.call(Subclass, …)` and +/// inherited-static `Subclass.resolve(…)` reach `NewPromiseCapability(C)`. fn is_object_value(value: f64) -> bool { let bits = value.to_bits(); - if (bits & crate::value::TAG_MASK) != crate::value::POINTER_TAG { - return false; - } - let raw = (bits & crate::value::POINTER_MASK) as usize; - if crate::value::addr_class::is_handle_band(raw) { - return false; + if (bits & crate::value::TAG_MASK) == crate::value::POINTER_TAG { + let raw = (bits & crate::value::POINTER_MASK) as usize; + if crate::value::addr_class::is_handle_band(raw) { + return crate::object::js_value_is_constructor(value); + } + return !crate::symbol::is_registered_symbol(raw); } - !crate::symbol::is_registered_symbol(raw) + // Non-pointer-tagged constructors (user-class ClassRefs) are still Objects. + crate::object::js_value_is_constructor(value) } /// `Promise.reject(r)` (ECMA-262 27.2.4.6) with `this` = C: build the result diff --git a/crates/perry-runtime/src/promise/subclass.rs b/crates/perry-runtime/src/promise/subclass.rs new file mode 100644 index 0000000000..8460d863d1 --- /dev/null +++ b/crates/perry-runtime/src/promise/subclass.rs @@ -0,0 +1,139 @@ +//! `class X extends Promise` — subclass backing support. +//! +//! Perry models a class instance as a plain `ObjectHeader`, not a real +//! `GC_TYPE_PROMISE` cell (a Promise carries its state in a dedicated +//! allocation, not in object fields). So `super(executor)` to a `Promise` +//! parent used to be a best-effort no-op, leaving the subclass instance with no +//! promise state — `inst.then(...)` threw "incompatible receiver" and +//! `NewPromiseCapability(Subclass)` never populated `resolve`/`reject`. +//! +//! Fix (mirrors `object::map_set_subclass`): `super(executor)` calls +//! [`js_promise_subclass_init`], which runs the ECMA-262 27.2.3.1 Promise +//! constructor steps against a fresh backing `Promise` cell — CreateResolving +//! Functions + `Call(executor, «resolve, reject»)` — and stashes the backing +//! cell's NaN-boxed pointer on the instance under a hidden field. Because it is +//! a normal object field, the GC traces + relocates it. +//! +//! `inst.then/catch/finally`, `await inst`, and `js_value_is_promise(inst)` are +//! then served by unwrapping the backing cell via [`subclass_backing_promise`] +//! at the runtime dispatch points. + +use crate::object::{js_object_get_field_by_name_f64, js_object_set_field_by_name, ObjectHeader}; +use crate::value::{JSValue, POINTER_MASK}; + +use super::Promise; + +/// Hidden field on a Promise subclass instance holding the NaN-boxed backing +/// `Promise` cell pointer. +pub(crate) const BACKING_KEY: &[u8] = b"__perry_promise_backing__"; + +fn raw_ptr_from_value(value: f64) -> usize { + let bits = value.to_bits(); + let jsval = JSValue::from_bits(bits); + if jsval.is_pointer() { + return (bits & POINTER_MASK) as usize; + } + if bits != 0 && bits < 0x0001_0000_0000_0000 { + return bits as usize; + } + 0 +} + +unsafe fn instance_object_ptr(this: f64) -> Option<*mut ObjectHeader> { + let raw = raw_ptr_from_value(this); + if raw < crate::gc::GC_HEADER_SIZE + 0x1000 { + return None; + } + // A real `Promise` cell (GC_TYPE_PROMISE) is not a subclass instance — it + // has its own dispatch. Reject registered non-object allocations before the + // header read for the same magnitude/handle-band reasons as the Map/Set path. + if crate::map::is_registered_map(raw) + || crate::set::is_registered_set(raw) + || crate::buffer::is_registered_buffer(raw) + || crate::typedarray::lookup_typed_array_kind(raw).is_some() + { + return None; + } + let header = crate::value::addr_class::try_read_gc_header(raw)?; + if header.obj_type != crate::gc::GC_TYPE_OBJECT { + return None; + } + Some(raw as *mut ObjectHeader) +} + +/// If `value` is a Promise *subclass instance* (a plain object carrying the +/// hidden backing field), return its backing `Promise` cell. Returns `None` for +/// real `Promise` cells, ordinary objects, and non-objects — so callers fall +/// through to their existing handling. +pub(crate) fn subclass_backing_promise(value: f64) -> Option<*mut Promise> { + unsafe { + let obj = instance_object_ptr(value)?; + let backing = js_object_get_field_by_name_f64( + obj as *const ObjectHeader, + crate::string::js_string_from_bytes(BACKING_KEY.as_ptr(), BACKING_KEY.len() as u32), + ); + let bjs = JSValue::from_bits(backing.to_bits()); + if !bjs.is_pointer() { + return None; + } + let raw = (backing.to_bits() & POINTER_MASK) as usize; + if raw < crate::gc::GC_HEADER_SIZE + 0x1000 { + return None; + } + // Confirm the stashed pointer is a genuine Promise cell before handing it + // back as one. + if crate::promise::js_value_is_promise(f64::from_bits(bjs.bits())) != 0 { + return Some(raw as *mut Promise); + } + None + } +} + +/// `super(executor)` for a `class X extends Promise`. Runs ECMA-262 27.2.3.1 +/// (Promise constructor): allocate a backing `Promise` cell, create its +/// resolving functions, call `executor(resolve, reject)` (catching an abrupt +/// completion into a rejection), and stash the backing cell on the instance +/// under the hidden field. `executor` is the (required-callable) first +/// constructor argument; a non-callable executor throws a `TypeError` +/// synchronously per step 2. +#[no_mangle] +pub extern "C" fn js_promise_subclass_init(this: f64, executor: f64) -> f64 { + let obj = match unsafe { instance_object_ptr(this) } { + Some(o) => o, + None => return this, + }; + + // 27.2.3.1 step 2: a non-callable executor throws a TypeError, before any + // promise is created. + if !super::spec_combinators::is_callable_value(executor) { + let msg = b"Promise resolver is not a function"; + let s = crate::string::js_string_from_bytes(msg.as_ptr(), msg.len() as u32); + let err = crate::error::js_typeerror_new(s); + let v = f64::from_bits(JSValue::pointer(err as *const u8).bits()); + crate::exception::js_throw(v); + } + + // Build the backing promise + resolving functions, run the executor. Keep a + // raw root on the backing cell across the string-key allocation below (which + // can GC) by stashing it immediately after the executor runs. + let promise = super::js_promise_new(); + let (resolve_closure, reject_closure) = super::combinators::make_resolving_functions(promise); + let resolve_f64 = crate::value::js_nanbox_pointer(resolve_closure as i64); + let reject_f64 = crate::value::js_nanbox_pointer(reject_closure as i64); + + // 27.2.3.1 step 10: run the executor; a throw rejects the promise via the + // shared resolving `reject` (so the [[AlreadyResolved]] guard makes a later + // resolve/reject a no-op). `js_native_call_value` accepts both POINTER_TAG + // closures and raw-pointer-bits closures, so `executor` is passed as-is. + let args = [resolve_f64, reject_f64]; + if let Err(reason) = super::combinators::combinator_catch_js(|| unsafe { + crate::closure::js_native_call_value(executor, args.as_ptr(), args.len()) + }) { + crate::closure::js_closure_call1(reject_closure, reason); + } + + let key = crate::string::js_string_from_bytes(BACKING_KEY.as_ptr(), BACKING_KEY.len() as u32); + let backing_bits = JSValue::pointer(promise as *const u8).bits(); + js_object_set_field_by_name(obj, key, f64::from_bits(backing_bits)); + this +} diff --git a/crates/perry-runtime/src/promise/then.rs b/crates/perry-runtime/src/promise/then.rs index 8e1311d8af..ed5bd4ae59 100644 --- a/crates/perry-runtime/src/promise/then.rs +++ b/crates/perry-runtime/src/promise/then.rs @@ -1282,6 +1282,11 @@ fn promise_prototype_receiver(method: &str) -> *mut Promise { if js_value_is_promise(receiver) != 0 { return crate::value::js_nanbox_get_pointer(receiver) as *mut Promise; } + // `class X extends Promise` instance: unwrap its hidden backing Promise cell + // so `inst.then/catch(...)` dispatches against the real promise state. + if let Some(backing) = super::subclass::subclass_backing_promise(receiver) { + return backing; + } throw_promise_prototype_incompatible_receiver(method, receiver) } @@ -1322,11 +1327,14 @@ fn throw_type_error_thunk(msg: &str) -> ! { crate::exception::js_throw(v) } -// True iff `value` is a JavaScript Object (heap-pointer tagged, not a Symbol or handle). +// True iff `value` is a JavaScript Object (heap-pointer tagged, not a Symbol or +// handle). A user-class constructor (`p.constructor` for a `class X extends +// Promise` instance) is an INT32-tagged ClassRef but is still an Object per spec, +// so accept any constructor value too — needed by SpeciesConstructor. fn is_promise_species_object(value: f64) -> bool { let bits = value.to_bits(); if (bits & crate::value::TAG_MASK) != crate::value::POINTER_TAG { - return false; + return crate::object::js_value_is_constructor(value); } let raw = (bits & crate::value::POINTER_MASK) as usize; if crate::value::addr_class::is_handle_band(raw) { @@ -1656,10 +1664,16 @@ pub(crate) extern "C" fn promise_prototype_then_thunk( ) -> f64 { ensure_spec_finally_arities_registered(); let receiver = crate::object::js_implicit_this_get(); - if js_value_is_promise(receiver) == 0 { + let promise = if js_value_is_promise(receiver) != 0 { + crate::value::js_nanbox_get_pointer(receiver) as *mut Promise + } else if let Some(backing) = super::subclass::subclass_backing_promise(receiver) { + // `class X extends Promise` instance: dispatch against its backing cell, + // but keep `receiver` for SpeciesConstructor (`receiver.constructor` is + // the subclass, so the slow path chains a subclass promise per spec). + backing + } else { throw_promise_prototype_incompatible_receiver("then", receiver); - } - let promise = crate::value::js_nanbox_get_pointer(receiver) as *mut Promise; + }; // SpeciesConstructor(promise, %Promise%) — reads this.constructor once. let c = promise_species_constructor(receiver); diff --git a/crates/perry-runtime/src/value/dynamic_object.rs b/crates/perry-runtime/src/value/dynamic_object.rs index 4eae8d67ec..30c0d6e31f 100644 --- a/crates/perry-runtime/src/value/dynamic_object.rs +++ b/crates/perry-runtime/src/value/dynamic_object.rs @@ -270,6 +270,26 @@ pub unsafe extern "C" fn js_dynamic_object_get_property( } } + // A user-class ClassRef (`class X extends Promise` etc.) reaching this + // generic dynamic getter — `GetPromiseResolve(C)`'s `Get(C, "resolve")`, a + // `Subclass.resolve.bind(Subclass)` read — must resolve through the + // class-ref-aware `js_object_get_field_by_name`, which checks a user static + // override (`Subclass.resolve = fn`) FIRST and only then falls back to the + // inherited builtin static. The plain pointer path below can't see class + // refs and would return `undefined`. + if crate::object::class_ref_id(obj_value).is_some() { + let name_slice = if property_name_ptr.is_null() { + return f64::from_bits(TAG_UNDEFINED); + } else if property_name_len > 0 { + std::slice::from_raw_parts(property_name_ptr as *const u8, property_name_len) + } else { + std::ffi::CStr::from_ptr(property_name_ptr as *const std::ffi::c_char).to_bytes() + }; + let key = crate::string::js_string_from_bytes(name_slice.as_ptr(), name_slice.len() as u32); + let class_ref_obj = obj_value.to_bits() as *const crate::object::ObjectHeader; + return crate::object::js_object_get_field_by_name_f64(class_ref_obj, key); + } + // Not a JS handle - it's a native object pointer let ptr = js_nanbox_get_pointer(obj_value);