From 39f663f94521090c45cb5cbdea49e6a43f1843c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Fri, 17 Jul 2026 17:08:38 +0200 Subject: [PATCH 1/6] fix(runtime): capture-carrying class statics + class-object value-super (#6530) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bundled zod (next/dist/compiled/zod) broke under two related defects, both specific to classes that capture outer module-function locals (zod's ZodType family captures its parse/util helper namespaces): 1. Post-class statics assigned onto a capture-carrying class (ZodOptional.create = (e, t) => new ZodOptional(...)) land on the per-evaluation class OBJECT the class statement materializes as, while compiled sibling-method bodies (ZodType.optional()) dispatch the same static through js_class_static_method_call on an INT32 ClassRef, which consults only the class_id-keyed CLASS_DYNAMIC_PROPS table. The dispatch missed and returned the receiver — z.string().optional() evaluated to the ZodOptional CLASS REF, and .parse(undefined) then threw "Cannot read properties of undefined (reading 'errorMap')". Fix: mirror named-field writes on a marked class object into CLASS_DYNAMIC_PROPS under its template class id (skipping internal __perry_* markers). The own-field write is unchanged. 2. new ForwardClass(...) from inside another class's method takes the dynamic-parent super leg (js_fetch_or_value_super). With a class-OBJECT parent it dispatched js_native_call_value, whose W2 class-object arm CONSTRUCTS a fresh discarded parent instance instead of running the parent constructor on this — so ZodType's ctor never ran and _def and the bound methods stayed undefined (z.string().transform(f), .default(v), .catch(v), .refine(f) all returned husk instances; the record/object repro died in _getType). Fix: add a class-object arm mirroring the existing INT32 ClassRef arm — resolve the template class id stamped on the class object and run run_class_constructor_on_this_flat on this. Repro (issue #6530): z.string().optional().parse(undefined) threw; z.record(z.string(), z.object({p: z.string(), q: z.boolean().optional()})) .parse({a: {p: 'x'}}) threw; both now match node. This was the gscmaster / Next.js 16 standalone boot blocker (config-schema.js init). --- .../src/object/field_set_by_name.rs | 30 +++++++++++++++++++ .../src/object/global_this/fetch_globals.rs | 28 +++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/crates/perry-runtime/src/object/field_set_by_name.rs b/crates/perry-runtime/src/object/field_set_by_name.rs index ca377dfe070..4cb6333c6b3 100644 --- a/crates/perry-runtime/src/object/field_set_by_name.rs +++ b/crates/perry-runtime/src/object/field_set_by_name.rs @@ -799,6 +799,36 @@ pub extern "C" fn js_object_set_field_by_name( } } + // #6530: a named write on a per-evaluation CLASS OBJECT (`object_type + // == OBJECT_TYPE_CLASS` — what a capture-carrying class statement + // materializes as) must ALSO be mirrored into the class_id-keyed + // CLASS_DYNAMIC_PROPS side table. Compiled method bodies reference + // sibling classes as INT32 ClassRefs (bundled zod's + // `ZodOptional.create(this, this._def)` inside `ZodType.optional()`), + // and `js_class_static_method_call` resolves statics through that + // table only — without the mirror the dispatch missed and handed back + // the class ref itself, so `.optional()` returned the ZodOptional + // CLASS instead of an instance. The own-field write still proceeds + // below, so reads through the class-object binding (module-scope + // `ZodOptional.create`, re-exports) are unchanged. Internal + // `__perry_*` markers (the pinned-parent edge) stay object-local. + // Last-wins across evaluations of the same class statement, matching + // the established template-cid compromise. Placed BEFORE the + // store-plan fast gate below so a recorded plan for the same + // (class_id, key) can never skip the mirror on a repeat write. + if (*obj).object_type == crate::error::OBJECT_TYPE_CLASS + && (*obj).class_id != 0 + && !key.is_null() + { + let name_ptr = (key as *const u8).add(std::mem::size_of::()); + let name_len = (*key).byte_len as usize; + if let Ok(name) = std::str::from_utf8(std::slice::from_raw_parts(name_ptr, name_len)) { + if !name.is_empty() && !name.starts_with("__perry_") { + class_dynamic_prop_root_store((*obj).class_id, name.to_string(), value); + } + } + } + // Resolve the interned key EARLY (hoisted from below the interception // vet): the store-plan cache and the shape-transition cache both key // on interned pointer identity. If the key is already interned diff --git a/crates/perry-runtime/src/object/global_this/fetch_globals.rs b/crates/perry-runtime/src/object/global_this/fetch_globals.rs index cf2fb452f5e..d469ebbab01 100644 --- a/crates/perry-runtime/src/object/global_this/fetch_globals.rs +++ b/crates/perry-runtime/src/object/global_this/fetch_globals.rs @@ -737,6 +737,34 @@ pub unsafe extern "C" fn js_fetch_or_value_super( // applies to closure/object parents, not a ClassRef. return undef; } + // #6530: the parent can be a per-evaluation CLASS OBJECT — what a + // capture-carrying class statement materializes as (bundled zod's + // `class ZodEffects extends ZodType` where ZodType captures module + // helpers, registered via `js_register_class_parent_dynamic`). + // Dispatching it through `js_native_call_value` below hits that + // helper's class-object arm, which CONSTRUCTS a fresh parent + // instance — and this super leg drops the result, so the parent + // constructor never ran on `this` and every base-ctor field + // (zod's `_def`, the bound methods) stayed undefined. Route + // through the same flat constructor-on-`this` dispatch as the + // ClassRef arm above, using the template class id stamped on the + // class object at `js_object_alloc` time. + if bits & TAG_MASK == POINTER_TAG { + let p = (bits & PTR_MASK) as usize; + if super::super::class_registry::is_class_object_ptr(p as *const u8) { + let parent_cid = crate::object::js_object_get_class_id( + p as *const crate::object::ObjectHeader, + ); + if parent_cid != 0 { + if let Some(obj) = subclass_this_object_ptr(this_box) { + super::super::class_constructors::run_class_constructor_on_this_flat( + parent_cid, obj as i64, args_ptr, args_len, + ); + return undef; + } + } + } + } let usable = if bits & TAG_MASK == POINTER_TAG { let p = (bits & PTR_MASK) as usize; // A real callability test: a closure, or a per-evaluation class From e398136010e59857be2a1513a46868891092cd53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Fri, 17 Jul 2026 17:32:21 +0200 Subject: [PATCH 2/6] fix(runtime,codegen): capture-class construction args, statics mirror, constructor identity (#6530) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Completes the #6530 family. Three more defects on top of the first commit: 1. codegen (lower_call/new.rs): the bare-identifier `new C(...)` path assumed the HIR always appends the class's captures as trailing LocalGet args — but the HIR only appends them where the captured locals are in scope (the declaring function). Inside a sibling class's method (zod's ZodType.transform() { return new ZodEffects({...}) }) nothing is appended, so the tail-split stole the user args as capture fallbacks: the synthesized ctor received an empty rest array, super(...[]) ran the parent ctor with no def, and _def stayed undefined on every transform/default/catch/refine result. Now the tail is treated as appended caps only when each trailing arg is LocalGet(id) matching the synthesized __perry_cap_ param it binds to (exact id + order match, all-or-nothing like the HIR emitter). 2. runtime (.constructor identity): instances of capture-carrying classes resolved .constructor to a bound constructor-method closure (whose underlying func is the nearest ancestor ctor), so x.constructor === Sub was false even for base classes and every subclass reported the BASE name. New CLASS_OBJECT_VALUES registry (cid → marked class object, populated by js_object_mark_class, GC-rooted like the sibling side tables) lets instance.constructor return the SAME per-evaluation class object the module scope and exports hold. 3. runtime (.name inheritance): `name` is an OWN property of every constructor (ClassDefinitionEvaluation installs it per class), but three static-resolution walks inherited it from the parent edge — the classref CLASS_DYNAMIC_PROPS chain walk, the classref resolve_proto_chain_field walk, and the class-object pinned-parent recursion (#6438) — so Sub.name / z.string().constructor.name reported the base class. Skip `name` (and `prototype` on the pinned-parent recursion) in those walks; the own-name synthesis arms already answer from the receiver's class id. All three issue #6530 repros now match node byte-for-byte: z.string().optional().parse(undefined) === undefined, z.record(...).parse({a:{p:'x'}}), and constructor names ZodString/ZodObject/ZodOptional. Gap test covers the shape without the zod bundle. --- crates/perry-codegen/src/lower_call/new.rs | 49 ++++++++++ .../src/object/class_registry.rs | 21 +++-- .../src/object/class_registry/gc_roots.rs | 32 +++++++ .../object/class_registry/parent_static.rs | 6 ++ .../src/object/class_registry/state.rs | 41 ++++++++ .../object/field_get_set/get_field_by_name.rs | 59 ++++++++---- .../field_get_set/get_field_by_name_tail.rs | 14 +++ .../test_gap_class_capture_forward_static.ts | 93 +++++++++++++++++++ 8 files changed, 287 insertions(+), 28 deletions(-) create mode 100644 test-files/test_gap_class_capture_forward_static.ts diff --git a/crates/perry-codegen/src/lower_call/new.rs b/crates/perry-codegen/src/lower_call/new.rs index d7831f6bf83..c381436a206 100644 --- a/crates/perry-codegen/src/lower_call/new.rs +++ b/crates/perry-codegen/src/lower_call/new.rs @@ -243,6 +243,39 @@ fn inline_constructor_param_values_with_class( out } +/// #6530: true when the trailing args of a bare-identifier `new C(...)` site +/// are the HIR-appended capture forwards for `class`'s synthesized +/// `__perry_cap_` constructor params. The HIR `Expr::New` arm appends +/// `LocalGet(cid)` per captured id, in cap-param order, ONLY where those +/// locals are in scope (the class's declaring function) — so each trailing +/// arg must be a `LocalGet` whose id equals the id embedded in the matching +/// param name. Any mismatch (a sibling-class method's `new ZodEffects({...})` +/// carries only user args) means the caps are absent and the tail-split must +/// not steal user args as cap fallbacks. +fn new_site_args_carry_appended_caps(class: &perry_hir::Class, args: &[Expr]) -> bool { + let Some(ctor) = class.constructor.as_ref() else { + return false; + }; + let cap_params: Vec<&Param> = ctor + .params + .iter() + .filter(|p| { + p.name.starts_with("__perry_cap_") && !p.is_rest && p.arguments_object.is_none() + }) + .collect(); + if cap_params.is_empty() || args.len() < cap_params.len() { + return false; + } + let tail = &args[args.len() - cap_params.len()..]; + tail.iter().zip(cap_params.iter()).all(|(arg, p)| { + matches!(arg, Expr::LocalGet(id) + if p.name + .strip_prefix("__perry_cap_") + .and_then(|s| s.parse::().ok()) + == Some(*id)) + }) +} + fn pack_lowered_args_array(ctx: &mut FnCtx<'_>, args: &[String]) -> String { let cap = (args.len() as u32).to_string(); let mut current = ctx.block().call(I64, "js_array_alloc", &[(I32, &cap)]); @@ -677,6 +710,22 @@ fn lower_new_impl( } }; + // #6530: the HIR bare-identifier `Expr::New` arm appends the class's + // captures as trailing `LocalGet()` args only where the captured + // locals are IN SCOPE (the class's declaring function). Inside a SIBLING + // class's method nothing is appended — bundled zod's + // `ZodType.transform() { return new ZodEffects({...}) }` — but this path + // assumed the bare form always carries them, so the tail-split treated + // the trailing USER args as cap fallbacks: the synthesized ctor received + // an empty rest array, `super(...[])` ran the parent ctor with no `def`, + // and every base-ctor field (`_def`, the bound methods) stayed + // undefined. The appended form is exactly `LocalGet(id)` paired with the + // synthesized trailing param `__perry_cap_` (same id, same order — + // `expr_new.rs` pushes `LocalGet(cid)` per captured id), so verify the + // tail matches before treating it as appended caps. + let caps_absent_from_args = + caps_absent_from_args || !new_site_args_carry_appended_caps(class, args); + // Lower the args first (constructor params). let mut lowered_args: Vec = Vec::with_capacity(args.len()); for a in args { diff --git a/crates/perry-runtime/src/object/class_registry.rs b/crates/perry-runtime/src/object/class_registry.rs index bb3080722a2..45b5f677f63 100644 --- a/crates/perry-runtime/src/object/class_registry.rs +++ b/crates/perry-runtime/src/object/class_registry.rs @@ -53,19 +53,20 @@ pub(crate) use state::{ class_decl_prototype_value, class_decl_prototype_value_for_instance_class, class_delete_own_dynamic_prop, class_dynamic_prop_root_store, class_has_own_dynamic_prop, class_id_for_decl_prototype_object, class_is_key_deleted, class_mark_key_deleted, - class_own_enumerable_field_names, class_own_static_field_value, class_parent_closure, - class_parent_closure_root_store, class_prototype_method_is_enumerable, - class_prototype_method_set_enumerable, class_prototype_method_value_cache_root_store, - class_prototype_object_root_store, global_object_prototype_bits, - is_bound_native_method_closure_value, is_non_constructable_builtin_function_value, - parent_closure_in_chain, throw_non_constructable_builtin_function, + class_object_value_for_cid, class_object_value_root_store, class_own_enumerable_field_names, + class_own_static_field_value, class_parent_closure, class_parent_closure_root_store, + class_prototype_method_is_enumerable, class_prototype_method_set_enumerable, + class_prototype_method_value_cache_root_store, class_prototype_object_root_store, + global_object_prototype_bits, is_bound_native_method_closure_value, + is_non_constructable_builtin_function_value, parent_closure_in_chain, + throw_non_constructable_builtin_function, }; pub use state::{ ClassVTable, VTableMethodEntry, CLASS_DECL_PROTOTYPE_OBJECTS, CLASS_DYNAMIC_PARENT_VALUE, - CLASS_METHOD_BIND_LENGTHS, CLASS_PARENT_CLOSURES, CLASS_PROTOTYPE_METHOD_NONENUM, - CLASS_PROTOTYPE_OBJECTS, CLASS_STATIC_ACCESSORS, CLASS_STATIC_METHODS, - CLASS_STATIC_METHOD_BIND_LENGTHS, CLASS_SYMBOL_ACCESSORS, CLASS_SYMBOL_METHODS, - CLASS_VTABLE_REGISTRY, FUNCTION_CLASS_IDS, REGISTERED_CLASS_IDS, + CLASS_METHOD_BIND_LENGTHS, CLASS_OBJECT_VALUES, CLASS_PARENT_CLOSURES, + CLASS_PROTOTYPE_METHOD_NONENUM, CLASS_PROTOTYPE_OBJECTS, CLASS_STATIC_ACCESSORS, + CLASS_STATIC_METHODS, CLASS_STATIC_METHOD_BIND_LENGTHS, CLASS_SYMBOL_ACCESSORS, + CLASS_SYMBOL_METHODS, CLASS_VTABLE_REGISTRY, FUNCTION_CLASS_IDS, REGISTERED_CLASS_IDS, }; // ── prototype_objects.rs ──────────────────────────────────────────────────── diff --git a/crates/perry-runtime/src/object/class_registry/gc_roots.rs b/crates/perry-runtime/src/object/class_registry/gc_roots.rs index 3803308d8d8..4b916f2ade5 100644 --- a/crates/perry-runtime/src/object/class_registry/gc_roots.rs +++ b/crates/perry-runtime/src/object/class_registry/gc_roots.rs @@ -29,6 +29,9 @@ enum ClassSideTableRootSlot { DynamicParentValue { class_id: u32, }, + ClassObjectValue { + class_id: u32, + }, ClassSymbolMethod { class_id: u32, sym_key: usize, @@ -134,6 +137,18 @@ pub fn scan_class_side_table_roots_mut(visitor: &mut crate::gc::RuntimeRootVisit } } + // #6530: cid → per-evaluation class OBJECT (`instance.constructor` + // identity for capture-carrying classes). Same liveness/forwarding needs + // as the dynamic-parent stash above: the entries are heap objects a + // moving GC must visit + forward. + if let Ok(mut guard) = CLASS_OBJECT_VALUES.write() { + if let Some(map) = guard.as_mut() { + for value_bits in map.values_mut() { + visitor.visit_nanbox_u64_slot(value_bits); + } + } + } + scan_class_symbol_member_keys_mut(visitor); scan_function_class_id_keys_mut(visitor); } @@ -242,6 +257,16 @@ fn class_side_table_root_snapshot() -> Vec { } } + // Step twin of the CLASS_OBJECT_VALUES block in + // `scan_class_side_table_roots_mut` (#6530). + if let Ok(guard) = CLASS_OBJECT_VALUES.read() { + if let Some(map) = guard.as_ref() { + for &class_id in map.keys() { + slots.push(ClassSideTableRootSlot::ClassObjectValue { class_id }); + } + } + } + if let Ok(guard) = CLASS_SYMBOL_METHODS.read() { if let Some(map) = guard.as_ref() { for &(class_id, sym_key, is_static) in map.keys() { @@ -332,6 +357,13 @@ fn scan_class_side_table_root_slot( } } } + ClassSideTableRootSlot::ClassObjectValue { class_id } => { + if let Ok(mut guard) = CLASS_OBJECT_VALUES.write() { + if let Some(value_bits) = guard.as_mut().and_then(|map| map.get_mut(class_id)) { + visitor.visit_nanbox_u64_slot(value_bits); + } + } + } ClassSideTableRootSlot::ClassSymbolMethod { class_id, sym_key, 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 68174ea6c5b..fde16068f57 100644 --- a/crates/perry-runtime/src/object/class_registry/parent_static.rs +++ b/crates/perry-runtime/src/object/class_registry/parent_static.rs @@ -365,6 +365,12 @@ pub extern "C" fn js_object_mark_class(obj: i64) { if obj != 0 { unsafe { (*(obj as *mut ObjectHeader)).object_type = crate::error::OBJECT_TYPE_CLASS; + // #6530: record cid → class object so `instance.constructor` + // resolves to the SAME value the module scope/exports hold (see + // `CLASS_OBJECT_VALUES`). The template cid was stamped by the + // `js_object_alloc(cid, …)` call directly preceding this mark. + let cid = (*(obj as *const ObjectHeader)).class_id; + super::class_object_value_root_store(cid, obj as *mut ObjectHeader); } } } diff --git a/crates/perry-runtime/src/object/class_registry/state.rs b/crates/perry-runtime/src/object/class_registry/state.rs index 981d4f64fb0..f8dba9548b7 100644 --- a/crates/perry-runtime/src/object/class_registry/state.rs +++ b/crates/perry-runtime/src/object/class_registry/state.rs @@ -315,6 +315,47 @@ pub static CLASS_PARENT_CLOSURES: RwLock>> = RwLock:: /// (INT32-tagged) and object/closure (POINTER-tagged) parents. pub static CLASS_DYNAMIC_PARENT_VALUE: RwLock>> = RwLock::new(None); +/// #6530: maps a template class_id to the raw NaN-boxed POINTER bits of the +/// per-evaluation CLASS OBJECT the class statement materialized as (marked by +/// `js_object_mark_class`). A capture-carrying class has no INT32 ClassRef +/// value at runtime — the class VALUE is this heap object — so +/// `instance.constructor` must hand back the same object the module scope / +/// exports hold, or identity checks (`x.constructor === Sub`, bundled zod's +/// `describe()` re-construction via `this.constructor`) break. Last-wins +/// across evaluations of the same class statement, matching the template-cid +/// compromise used by the sibling tables above. +pub static CLASS_OBJECT_VALUES: RwLock>> = RwLock::new(None); + +/// Store the marked class object for its template class id (see +/// `CLASS_OBJECT_VALUES`). +pub(crate) fn class_object_value_root_store(class_id: u32, obj_ptr: *mut ObjectHeader) { + if class_id == 0 || obj_ptr.is_null() { + return; + } + let bits = crate::value::js_nanbox_pointer(obj_ptr as i64).to_bits(); + let mut guard = CLASS_OBJECT_VALUES.write().unwrap(); + if guard.is_none() { + *guard = Some(HashMap::new()); + } + guard.as_mut().unwrap().insert(class_id, bits); + crate::gc::runtime_write_barrier_root_raw_ptr(obj_ptr); +} + +/// Read back the class object registered for `class_id`, or `None` when the +/// class never materialized as a per-evaluation object (ordinary +/// ClassRef-valued classes). +pub(crate) fn class_object_value_for_cid(class_id: u32) -> Option { + if class_id == 0 { + return None; + } + CLASS_OBJECT_VALUES.read().ok().and_then(|guard| { + guard + .as_ref() + .and_then(|map| map.get(&class_id).copied()) + .map(f64::from_bits) + }) +} + pub(crate) fn class_prototype_object_root_store(class_id: u32, proto_ptr: *mut ObjectHeader) { if class_id == 0 || proto_ptr.is_null() { return; 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 e15cc3441d7..7592e61ed38 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 @@ -243,18 +243,28 @@ pub extern "C" fn js_object_get_field_by_name( { return JSValue::from_bits(v.to_bits()); } - if let Some(parent) = crate::object::class_registry::class_object_pinned_parent(obj) - { - let pbits = parent.to_bits(); - if (pbits >> 48) == 0x7FFD { - let praw = (pbits & 0x0000_FFFF_FFFF_FFFF) as *mut ObjectHeader; - if praw as usize != obj as usize - && crate::value::addr_class::is_above_handle_band(praw as usize) - && crate::object::is_valid_obj_ptr(praw as *const u8) - { - let v = js_object_get_field_by_name(praw, key); - if !v.is_undefined() { - return v; + // #6530: `name` and `prototype` are OWN properties of every + // constructor — never inherited through the parent edge. Skip + // the pinned-parent recursion for them so the generic tail + // below synthesizes both from THIS object's class_id (the + // recursion otherwise answered with the BASE class's `.name` + // for every capture-carrying subclass — bundled zod's + // identity collapse to "ZodType"). + if want != b"name" && want != b"prototype" { + if let Some(parent) = + crate::object::class_registry::class_object_pinned_parent(obj) + { + let pbits = parent.to_bits(); + if (pbits >> 48) == 0x7FFD { + let praw = (pbits & 0x0000_FFFF_FFFF_FFFF) as *mut ObjectHeader; + if praw as usize != obj as usize + && crate::value::addr_class::is_above_handle_band(praw as usize) + && crate::object::is_valid_obj_ptr(praw as *const u8) + { + let v = js_object_get_field_by_name(praw, key); + if !v.is_undefined() { + return v; + } } } } @@ -909,7 +919,13 @@ pub extern "C" fn js_object_get_field_by_name( // this covers the data-field case that was returning `undefined` // (Auth.js sets `SignInError.kind = "signIn"` and reads it off a // `CredentialsSignin` subclass to pick the sign-in vs error page). - { + // + // #6530: `name` is an OWN property of every constructor — a + // subclass never inherits its parent's `.name` (spec: + // ClassDefinitionEvaluation installs it per class). Skip the + // chain walk so the #2059 own-name synthesis below answers + // with THIS class's registered name instead of an ancestor's. + if name != "name" { let mut cid = class_id; let mut depth = 0usize; while depth < 32 { @@ -979,11 +995,18 @@ pub extern "C" fn js_object_get_field_by_name( // parent object was recorded as `class_id`'s static // prototype at `extends` time; walk that chain (also // covering multi-level `class Leaf extends Mid {}`). - if let Some(v) = - super::super::class_registry::resolve_proto_chain_field(class_id, key) - { - if !v.is_undefined() && !v.is_null() { - return v; + // #6530: except `name` — an own property of every + // constructor, never inherited; without the guard a + // subclass of a per-evaluation class object reported its + // BASE's synthesized `.name` (bundled zod: + // `z.string().constructor.name` gave "ZodType"). + if name != "name" { + if let Some(v) = + super::super::class_registry::resolve_proto_chain_field(class_id, key) + { + if !v.is_undefined() && !v.is_null() { + return v; + } } } // #36 / #321: the subclass extends a FUNCTION value diff --git a/crates/perry-runtime/src/object/field_get_set/get_field_by_name_tail.rs b/crates/perry-runtime/src/object/field_get_set/get_field_by_name_tail.rs index 1ecf7544672..6ac592413ae 100644 --- a/crates/perry-runtime/src/object/field_get_set/get_field_by_name_tail.rs +++ b/crates/perry-runtime/src/object/field_get_set/get_field_by_name_tail.rs @@ -1338,6 +1338,20 @@ pub(crate) fn get_field_by_name_object_tail( return v; } let class_id = (*obj).class_id; + // #6530: a capture-carrying class has no ClassRef value — the + // class VALUE is the per-evaluation class OBJECT registered at + // `js_object_mark_class` time. Return that same object so + // identity holds (`x.constructor === Sub`, bundled zod's + // `describe()` re-construction via `this.constructor` + // yielding the SUBCLASS instead of collapsing to the base). + // The arms below would otherwise hand back a bound + // constructor-method closure (whose underlying func is the + // nearest ancestor ctor — reporting the BASE class's name for + // every subclass) or the bare INT32 ClassRef. + if let Some(v) = super::super::class_registry::class_object_value_for_cid(class_id) + { + return JSValue::from_bits(v.to_bits()); + } // #5834: WeakMap/WeakSet instances carry a reserved class_id // (not a registered declared-class one), so none of the // arms below resolve them and `(new WeakMap()).constructor` diff --git a/test-files/test_gap_class_capture_forward_static.ts b/test-files/test_gap_class_capture_forward_static.ts new file mode 100644 index 00000000000..327b1d6fbe8 --- /dev/null +++ b/test-files/test_gap_class_capture_forward_static.ts @@ -0,0 +1,93 @@ +// #6530: forward class references from methods of a CAPTURE-CARRYING class +// (classes nested in a function whose methods reference outer locals — the +// shape of Next.js's bundled zod, where ZodType captures its helper +// namespaces). Two paths regressed: +// 1. `Sub.create(this, ...)` from a sibling method — the post-class arrow +// static lives on the per-evaluation class object, but the compiled +// method dispatches through the INT32 ClassRef static table; the miss +// silently returned the class ref itself. +// 2. `new Eff({...})` from a sibling method — the dynamic-parent value +// super leg constructed-and-dropped a fresh parent instead of running +// the parent constructor on `this`, so base-ctor fields stayed +// undefined. + +function makeModule() { + function getParsedType(x: any): string { + return typeof x; + } + const OK = (v: any) => ({ ok: true, value: v }); + + class Base { + _def: any; + parse(x: any) { + const ctx = { errorMap: this._def.errorMap, data: x, parsedType: getParsedType(x) }; + return this._parse(ctx); + } + _parse(ctx: any): any { + return "base:" + ctx.data; + } + constructor(def: any) { + this._def = def; + this.parse = this.parse.bind(this); + this.optional = this.optional.bind(this); + } + optional() { + return (Sub as any).create(this, this._def); + } + transform(f: any) { + return new Eff({ schema: this, effect: f, errorMap: "tm" }); + } + describe(d: string) { + const ctor: any = this.constructor; + return new ctor({ ...this._def, description: d }); + } + } + + class Eff extends Base { + _parse(ctx: any) { + return "eff:" + ctx.errorMap + ":" + ctx.data; + } + } + + class Sub extends Base { + _parse(ctx: any) { + const pt = getParsedType(ctx.data); + if (pt === "undefined") { + return OK(undefined).value; + } + return "sub:" + ctx.errorMap + ":" + ctx.data; + } + unwrap() { + return this._def.innerType; + } + } + (Sub as any).create = (e: any, t: any) => new Sub({ innerType: e, errorMap: "em" }); + + return { Base, Sub, Eff }; +} + +const m = makeModule(); + +const b = new m.Base({ errorMap: "bm" }); +console.log("base parse:", b.parse(1)); + +// path 1: post-class arrow static via forward ClassRef from a sibling method +const o = b.optional(); +console.log("opt typeof:", typeof o); +console.log("opt instanceof Sub:", o instanceof m.Sub); +console.log("opt _def set:", o._def !== undefined); +console.log("opt parse undef:", o.parse(undefined)); +console.log("opt parse val:", o.parse(7)); +console.log("opt unwrap is base:", o.unwrap() === b); + +// path 2: direct `new ForwardClass(...)` from a sibling method +const v = b.transform((x: any) => x); +console.log("eff instanceof Eff:", v instanceof m.Eff); +console.log("eff _def set:", v._def !== undefined); +console.log("eff parse:", v.parse(3)); +console.log("eff schema is base:", v._def.schema === b); + +// direct static call from outside (worked before, must keep working) +const s2 = (m.Sub as any).create(b, b._def); +console.log("direct _def set:", s2._def !== undefined); +console.log("direct parse:", s2.parse(9)); From b1e192f8f0ebc1c94da6edd6e8b14ef09d387f8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Fri, 17 Jul 2026 19:11:33 +0200 Subject: [PATCH 3/6] review: mirror class-object statics only on successful own-data writes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CodeRabbit finding on #6537: the CLASS_DYNAMIC_PROPS mirror ran before the accessor walk and frozen/writable gates, so a setter-intercepted or rejected assignment could desync the ClassRef read path from the class object's real state. Move the mirror into a helper invoked at every own-data write completion of js_object_set_field_by_name: the first-key path, the sidecar-hash and linear-scan overwrite paths (inline slot + overflow map), all three append variants, and the shape-transition-cache hit path — that last one matters in practice: class objects repeat identical key sequences (bundled zod assigns .create onto ~40 sibling class objects), so from the second class on the write lands on the cache-hit fast path. Also document the soundness invariant behind the appended-caps tail check (LocalIds come from a single module-wide counter, so the __perry_cap_ match cannot collide with user args outside the scopes where the HIR appends caps anyway). --- crates/perry-codegen/src/lower_call/new.rs | 9 +++ .../src/object/field_set_by_name.rs | 80 ++++++++++++------- 2 files changed, 59 insertions(+), 30 deletions(-) diff --git a/crates/perry-codegen/src/lower_call/new.rs b/crates/perry-codegen/src/lower_call/new.rs index c381436a206..0e0c299fbde 100644 --- a/crates/perry-codegen/src/lower_call/new.rs +++ b/crates/perry-codegen/src/lower_call/new.rs @@ -252,6 +252,15 @@ fn inline_constructor_param_values_with_class( /// param name. Any mismatch (a sibling-class method's `new ZodEffects({...})` /// carries only user args) means the caps are absent and the tail-split must /// not steal user args as cap fallbacks. +/// +/// Soundness of the id match: `LocalId`s come from a single MODULE-WIDE +/// counter (`LoweringContext::fresh_local` — never reset per function), so +/// `LocalGet(id)` anywhere in the module denotes the one local with that id. +/// A user expression can therefore only produce the cap-matching ids (all of +/// them, in declaration order) by referencing the captured locals themselves +/// — possible only in scopes where they are visible, which are exactly the +/// scopes where the HIR appends the caps anyway (and there the appended tail +/// follows the user args, so the tail-split still binds correctly). fn new_site_args_carry_appended_caps(class: &perry_hir::Class, args: &[Expr]) -> bool { let Some(ctor) = class.constructor.as_ref() else { return false; diff --git a/crates/perry-runtime/src/object/field_set_by_name.rs b/crates/perry-runtime/src/object/field_set_by_name.rs index 4cb6333c6b3..1a4042303f0 100644 --- a/crates/perry-runtime/src/object/field_set_by_name.rs +++ b/crates/perry-runtime/src/object/field_set_by_name.rs @@ -199,6 +199,43 @@ unsafe fn string_key_eq(key: *const crate::StringHeader, expected: &[u8]) -> boo /// `writable: false`); `Object.defineProperty(Function.prototype, k, {...})` /// round-trips via `closure_set_via_function_prototype_descriptor` before /// falling back to a plain own-property write. +/// #6530: mirror a SUCCESSFUL own-data write on a per-evaluation CLASS OBJECT +/// (`object_type == OBJECT_TYPE_CLASS` — what a capture-carrying class +/// statement materializes as) into the class_id-keyed `CLASS_DYNAMIC_PROPS` +/// side table. Compiled method bodies reference sibling classes as INT32 +/// ClassRefs (bundled zod's `ZodOptional.create(this, this._def)` inside +/// `ZodType.optional()`), and `js_class_static_method_call` resolves statics +/// through that table only — without the mirror the dispatch missed and +/// handed back the class ref itself, so `.optional()` returned the +/// ZodOptional CLASS instead of an instance. +/// +/// Called ONLY at the own-data write completions in +/// `js_object_set_field_by_name` (after the accessor walk, frozen/sealed +/// gates, and writable checks have all passed), so a setter-intercepted or +/// rejected assignment never desyncs the ClassRef read path from the class +/// object's real state. Internal `__perry_*` markers (the pinned-parent +/// edge) stay object-local. Last-wins across evaluations of the same class +/// statement, matching the established template-cid compromise. +unsafe fn mirror_class_object_static_write( + obj: *const ObjectHeader, + key: *const crate::StringHeader, + value: f64, +) { + if (*obj).object_type != crate::error::OBJECT_TYPE_CLASS + || (*obj).class_id == 0 + || key.is_null() + { + return; + } + let name_ptr = (key as *const u8).add(std::mem::size_of::()); + let name_len = (*key).byte_len as usize; + if let Ok(name) = std::str::from_utf8(std::slice::from_raw_parts(name_ptr, name_len)) { + if !name.is_empty() && !name.starts_with("__perry_") { + class_dynamic_prop_root_store((*obj).class_id, name.to_string(), value); + } + } +} + unsafe fn closure_set_field_by_name( obj: *mut ObjectHeader, key: *const crate::StringHeader, @@ -799,36 +836,6 @@ pub extern "C" fn js_object_set_field_by_name( } } - // #6530: a named write on a per-evaluation CLASS OBJECT (`object_type - // == OBJECT_TYPE_CLASS` — what a capture-carrying class statement - // materializes as) must ALSO be mirrored into the class_id-keyed - // CLASS_DYNAMIC_PROPS side table. Compiled method bodies reference - // sibling classes as INT32 ClassRefs (bundled zod's - // `ZodOptional.create(this, this._def)` inside `ZodType.optional()`), - // and `js_class_static_method_call` resolves statics through that - // table only — without the mirror the dispatch missed and handed back - // the class ref itself, so `.optional()` returned the ZodOptional - // CLASS instead of an instance. The own-field write still proceeds - // below, so reads through the class-object binding (module-scope - // `ZodOptional.create`, re-exports) are unchanged. Internal - // `__perry_*` markers (the pinned-parent edge) stay object-local. - // Last-wins across evaluations of the same class statement, matching - // the established template-cid compromise. Placed BEFORE the - // store-plan fast gate below so a recorded plan for the same - // (class_id, key) can never skip the mirror on a repeat write. - if (*obj).object_type == crate::error::OBJECT_TYPE_CLASS - && (*obj).class_id != 0 - && !key.is_null() - { - let name_ptr = (key as *const u8).add(std::mem::size_of::()); - let name_len = (*key).byte_len as usize; - if let Ok(name) = std::str::from_utf8(std::slice::from_raw_parts(name_ptr, name_len)) { - if !name.is_empty() && !name.starts_with("__perry_") { - class_dynamic_prop_root_store((*obj).class_id, name.to_string(), value); - } - } - } - // Resolve the interned key EARLY (hoisted from below the interception // vet): the store-plan cache and the shape-transition cache both key // on interned pointer identity. If the key is already interned @@ -1088,6 +1095,12 @@ pub extern "C" fn js_object_set_field_by_name( // Deliberately do NOT bump field_count here — see // above. } + // #6530: this shape-cache hit is a successful own-data + // write; class objects repeat identical key sequences + // (bundled zod assigns `create` onto ~40 sibling class + // objects), so from the SECOND class on the write lands + // here — the mirror must fire on this path too. + mirror_class_object_static_write(obj, key, value); return; } } @@ -1112,6 +1125,7 @@ pub extern "C" fn js_object_set_field_by_name( // Reallocate fields to hold at least one value // Note: We assume the object has enough field slots pre-allocated js_object_set_field(obj, 0, JSValue::from_bits(value.to_bits())); + mirror_class_object_static_write(obj, key, value); // Bump field_count so Object.keys()/values()/entries() see the new property. if (*obj).field_count == 0 { (*obj).field_count = 1; @@ -1223,6 +1237,7 @@ pub extern "C" fn js_object_set_field_by_name( }; overflow_set(obj as usize, i, vbits); } + mirror_class_object_static_write(obj, key, value); return; } // Miss path: the linear scan below will confirm and then @@ -1285,6 +1300,7 @@ pub extern "C" fn js_object_set_field_by_name( set_object_keys_array(obj, new_keys); super::mark_object_dynamic_shape_unknown(obj); overflow_set(obj as usize, new_index, vbits); + mirror_class_object_static_write(obj, key, value); transition_cache_insert( prev_keys_usize, interned_key, @@ -1311,6 +1327,7 @@ pub extern "C" fn js_object_set_field_by_name( set_object_keys_array(obj, new_keys); super::mark_object_dynamic_shape_unknown(obj); js_object_set_field(obj, new_index as u32, JSValue::from_bits(value.to_bits())); + mirror_class_object_static_write(obj, key, value); if new_index as u32 >= (*obj).field_count { (*obj).field_count = new_index as u32 + 1; } @@ -1392,6 +1409,7 @@ pub extern "C" fn js_object_set_field_by_name( }; overflow_set(obj as usize, i, vbits); } + mirror_class_object_static_write(obj, key, value); return; } } @@ -1475,6 +1493,7 @@ pub extern "C" fn js_object_set_field_by_name( set_object_keys_array(obj, new_keys); super::mark_object_dynamic_shape_unknown(obj); overflow_set(obj as usize, new_index, vbits); + mirror_class_object_static_write(obj, key, value); // Record the shape transition so the next object sharing // `prev_keys` that adds the same key hits the fast path. // The cached target is stamped `GC_FLAG_SHAPE_SHARED` by @@ -1503,6 +1522,7 @@ pub extern "C" fn js_object_set_field_by_name( // Set the field at the new index and update logical field_count js_object_set_field(obj, new_index as u32, JSValue::from_bits(value.to_bits())); + mirror_class_object_static_write(obj, key, value); // Bump field_count to reflect the newly added property if new_index as u32 >= (*obj).field_count { (*obj).field_count = new_index as u32 + 1; From 15c5f05c5ecdffc5e011b356251a7e9494317f0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Fri, 17 Jul 2026 19:42:30 +0200 Subject: [PATCH 4/6] chore: size-gate splits for files grown past 2000 lines MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit lint's check_file_size.sh flagged lower_call/new.rs (2048) and field_get_set/get_field_by_name_tail.rs (2006) after the #6530 additions. Pure relocations per the split recipe: - new.rs → new_ctor_args.rs: inline-ctor param binding/restore scope, the CaptureFill user-arg vs __perry_cap tail split (incl. the #6530 new_site_args_carry_appended_caps check), rest/arguments packing, imported-ctor marshaling, and the standalone ctor-symbol call path. lower_call/mod.rs re-exports re-pointed; the dead zero-caller inline_constructor_param_values wrapper dropped. - get_field_by_name_tail.rs → class_object_props.rs: instance_constructor_value — the 'constructor' special-key resolution arm (own field, WeakMap/WeakSet, #6530 class-object registry, vtable ctor method, boxed primitives, anon shapes, function-class table, ClassRef synthesis), returning None to fall through to the generic walk exactly as the inline arm did. --- crates/perry-codegen/src/lower_call/mod.rs | 7 +- crates/perry-codegen/src/lower_call/new.rs | 427 +---------------- .../src/lower_call/new_ctor_args.rs | 432 ++++++++++++++++++ .../field_get_set/class_object_props.rs | 94 ++++ .../field_get_set/get_field_by_name_tail.rs | 83 +--- 5 files changed, 536 insertions(+), 507 deletions(-) create mode 100644 crates/perry-codegen/src/lower_call/new_ctor_args.rs diff --git a/crates/perry-codegen/src/lower_call/mod.rs b/crates/perry-codegen/src/lower_call/mod.rs index b3781e988af..53ac3f64e49 100644 --- a/crates/perry-codegen/src/lower_call/mod.rs +++ b/crates/perry-codegen/src/lower_call/mod.rs @@ -50,6 +50,7 @@ mod native; mod native_module_dispatch; mod native_table; mod new; +mod new_ctor_args; mod new_helpers; mod omitted_native_params; mod options; @@ -109,9 +110,9 @@ pub(crate) use native::lower_native_method_call; // (codegen.rs / expr.rs / stmt.rs) so `crate::lower_call::lower_new` // etc. keep resolving after the split. pub(crate) use field_init::{apply_field_initializers_recursive, FieldInitMode}; -pub(crate) use new::{ - bind_inline_constructor_params, emit_class_capture_writeback, lower_new, - lower_new_member_captured, restore_inline_constructor_scope, CaptureFill, +pub(crate) use new::{emit_class_capture_writeback, lower_new, lower_new_member_captured}; +pub(crate) use new_ctor_args::{ + bind_inline_constructor_params, 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 diff --git a/crates/perry-codegen/src/lower_call/new.rs b/crates/perry-codegen/src/lower_call/new.rs index 0e0c299fbde..ed5f0de9536 100644 --- a/crates/perry-codegen/src/lower_call/new.rs +++ b/crates/perry-codegen/src/lower_call/new.rs @@ -11,6 +11,11 @@ use perry_types::Type as HirType; use super::field_init::{apply_field_initializers_recursive, FieldInitMode}; use super::lower_builtin_new; +use super::new_ctor_args::{ + bind_inline_constructor_params, call_local_constructor_symbol, lower_constructor_arg, + marshal_imported_ctor_args, new_site_args_carry_appended_caps, + restore_inline_constructor_scope, CaptureFill, +}; 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_new_target, ctor_body_uses_this, @@ -21,428 +26,6 @@ use crate::expr::{lower_expr, lower_js_args_array, nanbox_pointer_inline, FnCtx} use crate::nanbox::{double_literal, POINTER_MASK_I64}; use crate::types::{DOUBLE, I32, I64, I8, PTR}; -pub(crate) struct InlineConstructorScope { - locals: std::collections::HashMap, - local_types: std::collections::HashMap, - boxed_vars: std::collections::HashSet, -} - -pub(crate) fn restore_inline_constructor_scope(ctx: &mut FnCtx<'_>, saved: InlineConstructorScope) { - ctx.locals = saved.locals; - ctx.local_types = saved.local_types; - ctx.boxed_vars = saved.boxed_vars; -} - -pub(crate) fn bind_inline_constructor_params( - ctx: &mut FnCtx<'_>, - params: &[Param], - lowered_args: &[String], - capture_fill: Option, -) -> InlineConstructorScope { - let saved = InlineConstructorScope { - locals: ctx.locals.clone(), - local_types: ctx.local_types.clone(), - boxed_vars: ctx.boxed_vars.clone(), - }; - - crate::codegen::arguments::add_arguments_mapped_boxes(params, &mut ctx.boxed_vars); - let values = - inline_constructor_param_values_with_class(ctx, params, lowered_args, capture_fill); - for (param, arg_val) in params.iter().zip(values.iter()) { - let boxed_param = ctx.boxed_vars.contains(¶m.id) && param.arguments_object.is_none(); - let slot = ctx - .func - .alloca_entry(if boxed_param { I64 } else { DOUBLE }); - if boxed_param { - let arg_bits = ctx.block().bitcast_double_to_i64(arg_val); - let box_ptr = ctx - .block() - .call(I64, "js_box_alloc_bits", &[(I64, &arg_bits)]); - ctx.block().store(I64, &box_ptr, &slot); - } else { - ctx.block().store(DOUBLE, arg_val, &slot); - } - ctx.locals.insert(param.id, slot); - ctx.local_types.insert(param.id, param.ty.clone()); - } - - crate::codegen::arguments::materialize_arguments_object( - ctx, - params, - crate::codegen::arguments::ArgumentsCallee::Undefined, - ); - - saved -} - -fn inline_constructor_param_values( - ctx: &mut FnCtx<'_>, - params: &[Param], - lowered_args: &[String], -) -> Vec { - inline_constructor_param_values_with_class(ctx, params, lowered_args, None) -} - -/// Where a synthesized `__perry_cap_` param's value comes from when the -/// `new` site did not supply it as an appended arg. -#[derive(Clone, Copy)] -pub(crate) struct CaptureFill { - /// The constructing class's id, used to read its DECL-SITE capture - /// snapshot (`js_class_capture_value(cid, slot)`). - cid: u32, - /// `true` when `lowered_args` does NOT contain appended cap values — the - /// member-callee `new ns.C(...)` path. Then ALL `lowered_args` are user - /// args and EVERY cap param fills from the snapshot. `false` for the - /// bare-identifier `new C(...)` path, where the HIR appended the caps as - /// trailing args (tail-split keeps binding them); the snapshot then only - /// backfills a cap the HIR didn't append. - caps_absent_from_args: bool, -} - -impl CaptureFill { - /// Snapshot-only BACKFILL for a cap param the caller's args did not - /// supply: the `lowered_args` still carry their appended cap values - /// (tail-split keeps binding them). Used by the `super(...)` inline path, - /// which explicitly forwards parent caps as args. - pub(crate) fn backfill(cid: u32) -> Self { - CaptureFill { - cid, - caps_absent_from_args: false, - } - } -} - -/// As [`inline_constructor_param_values`], but fills a synthesized -/// `__perry_cap_` param that the `new` site did not supply from the -/// class's DECL-SITE capture snapshot (`js_class_capture_value(cid, slot)`) -/// instead of `undefined`. -/// -/// #5437 (W6): a member-callee construct `new ns.C()` of a function-nested -/// class that captured an enclosing local is statically routed to -/// `lower_new("C", [])` (the `#740` object-field-alias arm in -/// `expr/new_dynamic.rs`) — the captures are NOT appended as trailing args -/// (that only happens for the bare-identifier `new C()` HIR arm). With no -/// cap args the cap params bound to `undefined` and every method reading a -/// captured local saw `undefined`. The bare-`new C()` HIR-append cannot be -/// reused for `new ns.C()`: at the outer (member) `new` site the captured -/// enclosing local is OUT OF SCOPE, so `LocalGet(cid)` would itself read -/// `undefined`. The decl-site snapshot (registered at the class's -/// declaration by `js_class_register_capture_values`) holds the correct -/// captured values. `fill = None` keeps the prior `undefined` fill (no -/// behavior change for non-capturing/unknown classes). -fn inline_constructor_param_values_with_class( - ctx: &mut FnCtx<'_>, - params: &[Param], - lowered_args: &[String], - capture_fill: Option, -) -> Vec { - let undef = double_literal(f64::from_bits(crate::nanbox::TAG_UNDEFINED)); - // Synthesized `__perry_cap_` capture params are always TRAILING - // params, and `Expr::New` sites always append the capture values after - // the user args — but the two sides need not agree on the USER arity. - // A no-user-ctor capturing class has zero user params while the `new` - // site may pass user args (`new ZodString({})` — the vendored-zod - // bundle), so positional binding put the user arg into the capture - // slot. Bind capture params from the args TAIL and user params from - // the head. - // - // #5437: when a decl-site snapshot is available (`capture_fill = Some`), - // EVERY synthesized cap param is filled from that snapshot — the - // authoritative decl-site capture value — regardless of whether the `new` - // site appended cap args. This is what closes W6: the bundle's bare-`new - // uS(...)` appends a MIS-BOXED `uw` cap (the multi-level capture chain - // materialized the wrong value), while `uS`'s decl-site snapshot holds the - // correct module-exports object; preferring the snapshot makes - // `new uw.SharedCacheControls` resolve. - // - // The split between user args and the (now ignored) appended cap args - // still matters for the USER params: - // - member-callee `new ns.C(...)`: caps are NOT appended, so ALL - // `lowered_args` are user args → `n_caps = 0`. (`new ns.C("ARG")` - // binds the user param to `"ARG"`, the cap to the snapshot.) - // - bare-identifier `new C(...)`: the HIR appended the caps as trailing - // args, so strip them (tail-split) to recover the leading user args; - // the stripped cap values are discarded in favour of the snapshot. - let caps_absent = matches!( - capture_fill, - Some(CaptureFill { - caps_absent_from_args: true, - .. - }) - ); - let n_caps = if caps_absent { - 0 - } else { - params - .iter() - .filter(|p| { - p.name.starts_with("__perry_cap_") && !p.is_rest && p.arguments_object.is_none() - }) - .count() - .min(lowered_args.len()) - }; - let user_len = lowered_args.len() - n_caps; - let (user_args, cap_args) = lowered_args.split_at(user_len); - let mut cap_iter = cap_args.iter(); - - let mut out = Vec::with_capacity(params.len()); - let mut visible_index = 0usize; - // The cap-slot index of the NEXT cap param: the index of the value in - // the decl-site snapshot (registered in `captures_vec` / cap-param - // declaration order, which is the same order they appear here). - let mut cap_slot = 0u32; - for param in params { - if param.name.starts_with("__perry_cap_") - && !param.is_rest - && param.arguments_object.is_none() - { - let slot = cap_slot; - cap_slot += 1; - // Consume the appended cap arg so the tail stays aligned. When a - // decl-site snapshot is registered for `cid`, it is authoritative - // (W6: the appended arg may be a mis-boxed multi-level capture); - // otherwise (e.g. an inline anonymous class capturing a - // `require(...)`-derived local — #5437 OTel `trace`) NO snapshot is - // registered, so fall back to the appended cap arg rather than - // dropping it to `undefined`. - let appended = cap_iter.next(); - out.push(match capture_fill { - Some(CaptureFill { cid, .. }) => { - let fallback = appended.cloned().unwrap_or_else(|| undef.clone()); - ctx.block().call( - DOUBLE, - "js_class_capture_value_or", - &[ - (I32, &cid.to_string()), - (I32, &slot.to_string()), - (DOUBLE, &fallback), - ], - ) - } - None => appended.cloned().unwrap_or_else(|| undef.clone()), - }); - } else if param.arguments_object.is_some() { - out.push(pack_lowered_args_array(ctx, user_args)); - } else if param.is_rest { - let tail = if visible_index < user_args.len() { - &user_args[visible_index..] - } else { - &[] - }; - out.push(pack_lowered_args_array(ctx, tail)); - } else { - out.push( - user_args - .get(visible_index) - .cloned() - .unwrap_or_else(|| undef.clone()), - ); - visible_index += 1; - } - } - out -} - -/// #6530: true when the trailing args of a bare-identifier `new C(...)` site -/// are the HIR-appended capture forwards for `class`'s synthesized -/// `__perry_cap_` constructor params. The HIR `Expr::New` arm appends -/// `LocalGet(cid)` per captured id, in cap-param order, ONLY where those -/// locals are in scope (the class's declaring function) — so each trailing -/// arg must be a `LocalGet` whose id equals the id embedded in the matching -/// param name. Any mismatch (a sibling-class method's `new ZodEffects({...})` -/// carries only user args) means the caps are absent and the tail-split must -/// not steal user args as cap fallbacks. -/// -/// Soundness of the id match: `LocalId`s come from a single MODULE-WIDE -/// counter (`LoweringContext::fresh_local` — never reset per function), so -/// `LocalGet(id)` anywhere in the module denotes the one local with that id. -/// A user expression can therefore only produce the cap-matching ids (all of -/// them, in declaration order) by referencing the captured locals themselves -/// — possible only in scopes where they are visible, which are exactly the -/// scopes where the HIR appends the caps anyway (and there the appended tail -/// follows the user args, so the tail-split still binds correctly). -fn new_site_args_carry_appended_caps(class: &perry_hir::Class, args: &[Expr]) -> bool { - let Some(ctor) = class.constructor.as_ref() else { - return false; - }; - let cap_params: Vec<&Param> = ctor - .params - .iter() - .filter(|p| { - p.name.starts_with("__perry_cap_") && !p.is_rest && p.arguments_object.is_none() - }) - .collect(); - if cap_params.is_empty() || args.len() < cap_params.len() { - return false; - } - let tail = &args[args.len() - cap_params.len()..]; - tail.iter().zip(cap_params.iter()).all(|(arg, p)| { - matches!(arg, Expr::LocalGet(id) - if p.name - .strip_prefix("__perry_cap_") - .and_then(|s| s.parse::().ok()) - == Some(*id)) - }) -} - -fn pack_lowered_args_array(ctx: &mut FnCtx<'_>, args: &[String]) -> String { - let cap = (args.len() as u32).to_string(); - let mut current = ctx.block().call(I64, "js_array_alloc", &[(I32, &cap)]); - for value in args { - current = ctx.block().call( - I64, - "js_array_push_f64", - &[(I64, ¤t), (DOUBLE, value.as_str())], - ); - } - nanbox_pointer_inline(ctx.block(), ¤t) -} - -fn lower_constructor_arg(ctx: &mut FnCtx<'_>, arg: &Expr) -> Result { - let prev_discard = ctx.discard_expr_value; - ctx.discard_expr_value = false; - let lowered = lower_expr(ctx, arg); - ctx.discard_expr_value = prev_discard; - lowered -} - -/// Marshal the lowered `new`-site args into the value list a cross-module -/// imported constructor symbol expects. The source module compiled the -/// standalone `_constructor(this, p0, …)` with `ctor.param_count` -/// explicit slots. When the constructor's last param is `...rest` -/// (`ctor.has_rest`), that final slot must receive a PACKED ARRAY of every -/// trailing arg — not the first trailing arg passed raw. Mirrors the -/// inline-ctor `inline_constructor_param_values` rest packing and the -/// `method_has_rest` path for imported methods (#672). Returns exactly -/// `ctor.param_count` value strings; missing leading args are padded with -/// `undefined`. -fn marshal_imported_ctor_args( - ctx: &mut FnCtx<'_>, - ctor: &crate::codegen::ImportedCtor, - lowered_args: &[String], -) -> Vec { - let undef = double_literal(f64::from_bits(crate::nanbox::TAG_UNDEFINED)); - let param_count = ctor.param_count; - if ctor.has_rest && param_count > 0 { - // The first `param_count - 1` slots are positional; the last slot is - // the rest array packing every remaining arg. - let n_positional = param_count - 1; - let mut out: Vec = Vec::with_capacity(param_count); - for i in 0..n_positional { - out.push( - lowered_args - .get(i) - .cloned() - .unwrap_or_else(|| undef.clone()), - ); - } - let tail: Vec = lowered_args.iter().skip(n_positional).cloned().collect(); - out.push(pack_lowered_args_array(ctx, &tail)); - out - } else { - // No rest: positional, padded to `param_count` with `undefined`. - let mut out: Vec = lowered_args.to_vec(); - while out.len() < param_count { - out.push(undef.clone()); - } - out.truncate(param_count.max(out.len())); - out - } -} - -/// The effective constructor arity for `new (...)`: the class's own -/// ctor params, else — for a subclass with no own ctor — the closest -/// ancestor-with-a-ctor's param count (the synthesized default ctor forwards -/// `super(...args)`). Matches the standalone-ctor signature emitted in -/// `codegen/artifacts.rs`, so callers pass the right number of args. - -/// Emit a call to the shared standalone `_constructor` symbol and -/// return the raw value it produced. The standalone ctor function returns -/// `undefined` for an ordinary constructor (implicit `return this`) or the -/// explicitly-returned value for a `return ` body — the caller applies -/// `js_ctor_return_override` to that raw value to honor ECMAScript's -/// constructor-return-override rule (a returned object/function replaces the -/// freshly-allocated `this`). Returns `None` when no standalone symbol exists. -fn call_local_constructor_symbol( - ctx: &mut FnCtx<'_>, - class: &perry_hir::Class, - obj_box: &str, - lowered_args: &[String], - caps_absent_from_args: bool, -) -> Option { - let ctor_method_name = format!("{}_constructor", class.name); - let ctor_name = ctx - .methods - .get(&(class.name.clone(), ctor_method_name)) - .cloned()?; - // The standalone `_constructor` symbol's signature is the class's - // OWN ctor params, OR — when the class has no own ctor — the closest - // ancestor-with-a-ctor's params (codegen/artifacts.rs synthesizes the - // default ctor `constructor(...args) { super(...args) }` with that adopted - // signature). Mirror that here so we pass the constructor arguments through - // this nested-construction path. Reading `param_count` from `class.constructor` - // alone yielded 0 for a no-own-ctor subclass, so `new Sub(arg)` issued inside a - // method of `Sub` (the recursion-guarded symbol-call path) dropped every arg — - // the synthesized ctor's forwarded params then read uninitialized and the - // inherited `this.x = arg` stored garbage. Pervasive in zod (`new ZodNumber({…})` - // from `_addCheck`, where ZodNumber has no own ctor and ZodType does). - let param_count = effective_constructor_param_count(ctx, class); - let undef_lit = double_literal(f64::from_bits(crate::nanbox::TAG_UNDEFINED)); - // When the ctor's signature is statically known, build per-param values - // with the SAME packing rules the inline path uses — a rest param or the - // synthesized `arguments` param receives a PACKED ARRAY, not a raw - // positional value. Pre-fix, `new Kid({...})` from a method of Kid (the - // recursion-guarded symbol-call path) shoved the user arg RAW into the - // ctor's synthetic `arguments` slot; `super(...arguments)` then spread - // an object with no `length` and the parent ctor saw zero args - // (vendored zod's `z.number().int()` chain — `_addCheck` → - // `new ZodNumber({…})` → `constructor(){ super(...arguments) }`). - let effective_params: Option> = { - let mut found = class.constructor.as_ref().map(|c| c.params.clone()); - if found.is_none() { - let mut parent = class.extends_name.as_deref().map(|s| s.to_string()); - while let Some(pname) = parent { - match ctx.classes.get(&pname).copied() { - Some(pc) => { - if let Some(pctor) = pc.constructor.as_ref() { - found = Some(pctor.params.clone()); - break; - } - parent = pc.extends_name.as_deref().map(|s| s.to_string()); - } - None => break, - } - } - } - found - }; - let capture_fill = ctx - .class_ids - .get(&class.name) - .copied() - .map(|cid| CaptureFill { - cid, - caps_absent_from_args, - }); - let mut ctor_values = if let Some(params) = effective_params { - inline_constructor_param_values_with_class(ctx, ¶ms, lowered_args, capture_fill) - } else { - lowered_args.to_vec() - }; - ctor_values.truncate(param_count); - while ctor_values.len() < param_count { - ctor_values.push(undef_lit.clone()); - } - - let mut ctor_args: Vec<(crate::types::LlvmType, &str)> = - Vec::with_capacity(1 + ctor_values.len()); - ctor_args.push((DOUBLE, obj_box)); - for arg in &ctor_values { - ctor_args.push((DOUBLE, arg.as_str())); - } - Some(ctx.block().call(DOUBLE, &ctor_name, &ctor_args)) -} - /// Emit the `js_gc_init_typed_shape_layout` call that registers the freshly /// constructed instance's raw-f64 / pointer slot masks with the GC so the /// typed-feedback class-field fast path engages. Must run AFTER the constructor diff --git a/crates/perry-codegen/src/lower_call/new_ctor_args.rs b/crates/perry-codegen/src/lower_call/new_ctor_args.rs new file mode 100644 index 00000000000..b3911102ac6 --- /dev/null +++ b/crates/perry-codegen/src/lower_call/new_ctor_args.rs @@ -0,0 +1,432 @@ +//! Constructor-argument marshaling for `new` lowering (#6537 size-gate split +//! from `new.rs` — pure relocation, no behavior change). +//! +//! Holds the inline-ctor param binding/restore scope, the user-arg vs +//! synthesized `__perry_cap_` tail split (`CaptureFill`, +//! `inline_constructor_param_values_with_class`, +//! `new_site_args_carry_appended_caps` — #6530), rest/`arguments` packing, +//! imported-ctor arg marshaling, and the standalone +//! `_constructor`-symbol call path. + +use anyhow::Result; +use perry_hir::{Expr, Param}; +use perry_types::Type as HirType; + +use super::new_helpers::effective_constructor_param_count; +use crate::expr::{lower_expr, nanbox_pointer_inline, FnCtx}; +use crate::nanbox::double_literal; +use crate::types::{DOUBLE, I32, I64}; + +pub(crate) struct InlineConstructorScope { + locals: std::collections::HashMap, + local_types: std::collections::HashMap, + boxed_vars: std::collections::HashSet, +} + +pub(crate) fn restore_inline_constructor_scope(ctx: &mut FnCtx<'_>, saved: InlineConstructorScope) { + ctx.locals = saved.locals; + ctx.local_types = saved.local_types; + ctx.boxed_vars = saved.boxed_vars; +} + +pub(crate) fn bind_inline_constructor_params( + ctx: &mut FnCtx<'_>, + params: &[Param], + lowered_args: &[String], + capture_fill: Option, +) -> InlineConstructorScope { + let saved = InlineConstructorScope { + locals: ctx.locals.clone(), + local_types: ctx.local_types.clone(), + boxed_vars: ctx.boxed_vars.clone(), + }; + + crate::codegen::arguments::add_arguments_mapped_boxes(params, &mut ctx.boxed_vars); + let values = + inline_constructor_param_values_with_class(ctx, params, lowered_args, capture_fill); + for (param, arg_val) in params.iter().zip(values.iter()) { + let boxed_param = ctx.boxed_vars.contains(¶m.id) && param.arguments_object.is_none(); + let slot = ctx + .func + .alloca_entry(if boxed_param { I64 } else { DOUBLE }); + if boxed_param { + let arg_bits = ctx.block().bitcast_double_to_i64(arg_val); + let box_ptr = ctx + .block() + .call(I64, "js_box_alloc_bits", &[(I64, &arg_bits)]); + ctx.block().store(I64, &box_ptr, &slot); + } else { + ctx.block().store(DOUBLE, arg_val, &slot); + } + ctx.locals.insert(param.id, slot); + ctx.local_types.insert(param.id, param.ty.clone()); + } + + crate::codegen::arguments::materialize_arguments_object( + ctx, + params, + crate::codegen::arguments::ArgumentsCallee::Undefined, + ); + + saved +} + +/// Where a synthesized `__perry_cap_` param's value comes from when the +/// `new` site did not supply it as an appended arg. +#[derive(Clone, Copy)] +pub(crate) struct CaptureFill { + /// The constructing class's id, used to read its DECL-SITE capture + /// snapshot (`js_class_capture_value(cid, slot)`). + pub(crate) cid: u32, + /// `true` when `lowered_args` does NOT contain appended cap values — the + /// member-callee `new ns.C(...)` path. Then ALL `lowered_args` are user + /// args and EVERY cap param fills from the snapshot. `false` for the + /// bare-identifier `new C(...)` path, where the HIR appended the caps as + /// trailing args (tail-split keeps binding them); the snapshot then only + /// backfills a cap the HIR didn't append. + pub(crate) caps_absent_from_args: bool, +} + +impl CaptureFill { + /// Snapshot-only BACKFILL for a cap param the caller's args did not + /// supply: the `lowered_args` still carry their appended cap values + /// (tail-split keeps binding them). Used by the `super(...)` inline path, + /// which explicitly forwards parent caps as args. + pub(crate) fn backfill(cid: u32) -> Self { + CaptureFill { + cid, + caps_absent_from_args: false, + } + } +} + +/// As [`inline_constructor_param_values`], but fills a synthesized +/// `__perry_cap_` param that the `new` site did not supply from the +/// class's DECL-SITE capture snapshot (`js_class_capture_value(cid, slot)`) +/// instead of `undefined`. +/// +/// #5437 (W6): a member-callee construct `new ns.C()` of a function-nested +/// class that captured an enclosing local is statically routed to +/// `lower_new("C", [])` (the `#740` object-field-alias arm in +/// `expr/new_dynamic.rs`) — the captures are NOT appended as trailing args +/// (that only happens for the bare-identifier `new C()` HIR arm). With no +/// cap args the cap params bound to `undefined` and every method reading a +/// captured local saw `undefined`. The bare-`new C()` HIR-append cannot be +/// reused for `new ns.C()`: at the outer (member) `new` site the captured +/// enclosing local is OUT OF SCOPE, so `LocalGet(cid)` would itself read +/// `undefined`. The decl-site snapshot (registered at the class's +/// declaration by `js_class_register_capture_values`) holds the correct +/// captured values. `fill = None` keeps the prior `undefined` fill (no +/// behavior change for non-capturing/unknown classes). +fn inline_constructor_param_values_with_class( + ctx: &mut FnCtx<'_>, + params: &[Param], + lowered_args: &[String], + capture_fill: Option, +) -> Vec { + let undef = double_literal(f64::from_bits(crate::nanbox::TAG_UNDEFINED)); + // Synthesized `__perry_cap_` capture params are always TRAILING + // params, and `Expr::New` sites always append the capture values after + // the user args — but the two sides need not agree on the USER arity. + // A no-user-ctor capturing class has zero user params while the `new` + // site may pass user args (`new ZodString({})` — the vendored-zod + // bundle), so positional binding put the user arg into the capture + // slot. Bind capture params from the args TAIL and user params from + // the head. + // + // #5437: when a decl-site snapshot is available (`capture_fill = Some`), + // EVERY synthesized cap param is filled from that snapshot — the + // authoritative decl-site capture value — regardless of whether the `new` + // site appended cap args. This is what closes W6: the bundle's bare-`new + // uS(...)` appends a MIS-BOXED `uw` cap (the multi-level capture chain + // materialized the wrong value), while `uS`'s decl-site snapshot holds the + // correct module-exports object; preferring the snapshot makes + // `new uw.SharedCacheControls` resolve. + // + // The split between user args and the (now ignored) appended cap args + // still matters for the USER params: + // - member-callee `new ns.C(...)`: caps are NOT appended, so ALL + // `lowered_args` are user args → `n_caps = 0`. (`new ns.C("ARG")` + // binds the user param to `"ARG"`, the cap to the snapshot.) + // - bare-identifier `new C(...)`: the HIR appended the caps as trailing + // args, so strip them (tail-split) to recover the leading user args; + // the stripped cap values are discarded in favour of the snapshot. + let caps_absent = matches!( + capture_fill, + Some(CaptureFill { + caps_absent_from_args: true, + .. + }) + ); + let n_caps = if caps_absent { + 0 + } else { + params + .iter() + .filter(|p| { + p.name.starts_with("__perry_cap_") && !p.is_rest && p.arguments_object.is_none() + }) + .count() + .min(lowered_args.len()) + }; + let user_len = lowered_args.len() - n_caps; + let (user_args, cap_args) = lowered_args.split_at(user_len); + let mut cap_iter = cap_args.iter(); + + let mut out = Vec::with_capacity(params.len()); + let mut visible_index = 0usize; + // The cap-slot index of the NEXT cap param: the index of the value in + // the decl-site snapshot (registered in `captures_vec` / cap-param + // declaration order, which is the same order they appear here). + let mut cap_slot = 0u32; + for param in params { + if param.name.starts_with("__perry_cap_") + && !param.is_rest + && param.arguments_object.is_none() + { + let slot = cap_slot; + cap_slot += 1; + // Consume the appended cap arg so the tail stays aligned. When a + // decl-site snapshot is registered for `cid`, it is authoritative + // (W6: the appended arg may be a mis-boxed multi-level capture); + // otherwise (e.g. an inline anonymous class capturing a + // `require(...)`-derived local — #5437 OTel `trace`) NO snapshot is + // registered, so fall back to the appended cap arg rather than + // dropping it to `undefined`. + let appended = cap_iter.next(); + out.push(match capture_fill { + Some(CaptureFill { cid, .. }) => { + let fallback = appended.cloned().unwrap_or_else(|| undef.clone()); + ctx.block().call( + DOUBLE, + "js_class_capture_value_or", + &[ + (I32, &cid.to_string()), + (I32, &slot.to_string()), + (DOUBLE, &fallback), + ], + ) + } + None => appended.cloned().unwrap_or_else(|| undef.clone()), + }); + } else if param.arguments_object.is_some() { + out.push(pack_lowered_args_array(ctx, user_args)); + } else if param.is_rest { + let tail = if visible_index < user_args.len() { + &user_args[visible_index..] + } else { + &[] + }; + out.push(pack_lowered_args_array(ctx, tail)); + } else { + out.push( + user_args + .get(visible_index) + .cloned() + .unwrap_or_else(|| undef.clone()), + ); + visible_index += 1; + } + } + out +} + +/// #6530: true when the trailing args of a bare-identifier `new C(...)` site +/// are the HIR-appended capture forwards for `class`'s synthesized +/// `__perry_cap_` constructor params. The HIR `Expr::New` arm appends +/// `LocalGet(cid)` per captured id, in cap-param order, ONLY where those +/// locals are in scope (the class's declaring function) — so each trailing +/// arg must be a `LocalGet` whose id equals the id embedded in the matching +/// param name. Any mismatch (a sibling-class method's `new ZodEffects({...})` +/// carries only user args) means the caps are absent and the tail-split must +/// not steal user args as cap fallbacks. +/// +/// Soundness of the id match: `LocalId`s come from a single MODULE-WIDE +/// counter (`LoweringContext::fresh_local` — never reset per function), so +/// `LocalGet(id)` anywhere in the module denotes the one local with that id. +/// A user expression can therefore only produce the cap-matching ids (all of +/// them, in declaration order) by referencing the captured locals themselves +/// — possible only in scopes where they are visible, which are exactly the +/// scopes where the HIR appends the caps anyway (and there the appended tail +/// follows the user args, so the tail-split still binds correctly). +pub(super) fn new_site_args_carry_appended_caps(class: &perry_hir::Class, args: &[Expr]) -> bool { + let Some(ctor) = class.constructor.as_ref() else { + return false; + }; + let cap_params: Vec<&Param> = ctor + .params + .iter() + .filter(|p| { + p.name.starts_with("__perry_cap_") && !p.is_rest && p.arguments_object.is_none() + }) + .collect(); + if cap_params.is_empty() || args.len() < cap_params.len() { + return false; + } + let tail = &args[args.len() - cap_params.len()..]; + tail.iter().zip(cap_params.iter()).all(|(arg, p)| { + matches!(arg, Expr::LocalGet(id) + if p.name + .strip_prefix("__perry_cap_") + .and_then(|s| s.parse::().ok()) + == Some(*id)) + }) +} + +fn pack_lowered_args_array(ctx: &mut FnCtx<'_>, args: &[String]) -> String { + let cap = (args.len() as u32).to_string(); + let mut current = ctx.block().call(I64, "js_array_alloc", &[(I32, &cap)]); + for value in args { + current = ctx.block().call( + I64, + "js_array_push_f64", + &[(I64, ¤t), (DOUBLE, value.as_str())], + ); + } + nanbox_pointer_inline(ctx.block(), ¤t) +} + +pub(super) fn lower_constructor_arg(ctx: &mut FnCtx<'_>, arg: &Expr) -> Result { + let prev_discard = ctx.discard_expr_value; + ctx.discard_expr_value = false; + let lowered = lower_expr(ctx, arg); + ctx.discard_expr_value = prev_discard; + lowered +} + +/// Marshal the lowered `new`-site args into the value list a cross-module +/// imported constructor symbol expects. The source module compiled the +/// standalone `_constructor(this, p0, …)` with `ctor.param_count` +/// explicit slots. When the constructor's last param is `...rest` +/// (`ctor.has_rest`), that final slot must receive a PACKED ARRAY of every +/// trailing arg — not the first trailing arg passed raw. Mirrors the +/// inline-ctor `inline_constructor_param_values` rest packing and the +/// `method_has_rest` path for imported methods (#672). Returns exactly +/// `ctor.param_count` value strings; missing leading args are padded with +/// `undefined`. +pub(super) fn marshal_imported_ctor_args( + ctx: &mut FnCtx<'_>, + ctor: &crate::codegen::ImportedCtor, + lowered_args: &[String], +) -> Vec { + let undef = double_literal(f64::from_bits(crate::nanbox::TAG_UNDEFINED)); + let param_count = ctor.param_count; + if ctor.has_rest && param_count > 0 { + // The first `param_count - 1` slots are positional; the last slot is + // the rest array packing every remaining arg. + let n_positional = param_count - 1; + let mut out: Vec = Vec::with_capacity(param_count); + for i in 0..n_positional { + out.push( + lowered_args + .get(i) + .cloned() + .unwrap_or_else(|| undef.clone()), + ); + } + let tail: Vec = lowered_args.iter().skip(n_positional).cloned().collect(); + out.push(pack_lowered_args_array(ctx, &tail)); + out + } else { + // No rest: positional, padded to `param_count` with `undefined`. + let mut out: Vec = lowered_args.to_vec(); + while out.len() < param_count { + out.push(undef.clone()); + } + out.truncate(param_count.max(out.len())); + out + } +} + +/// The effective constructor arity for `new (...)`: the class's own +/// ctor params, else — for a subclass with no own ctor — the closest +/// ancestor-with-a-ctor's param count (the synthesized default ctor forwards +/// `super(...args)`). Matches the standalone-ctor signature emitted in +/// `codegen/artifacts.rs`, so callers pass the right number of args. + +/// Emit a call to the shared standalone `_constructor` symbol and +/// return the raw value it produced. The standalone ctor function returns +/// `undefined` for an ordinary constructor (implicit `return this`) or the +/// explicitly-returned value for a `return ` body — the caller applies +/// `js_ctor_return_override` to that raw value to honor ECMAScript's +/// constructor-return-override rule (a returned object/function replaces the +/// freshly-allocated `this`). Returns `None` when no standalone symbol exists. +pub(super) fn call_local_constructor_symbol( + ctx: &mut FnCtx<'_>, + class: &perry_hir::Class, + obj_box: &str, + lowered_args: &[String], + caps_absent_from_args: bool, +) -> Option { + let ctor_method_name = format!("{}_constructor", class.name); + let ctor_name = ctx + .methods + .get(&(class.name.clone(), ctor_method_name)) + .cloned()?; + // The standalone `_constructor` symbol's signature is the class's + // OWN ctor params, OR — when the class has no own ctor — the closest + // ancestor-with-a-ctor's params (codegen/artifacts.rs synthesizes the + // default ctor `constructor(...args) { super(...args) }` with that adopted + // signature). Mirror that here so we pass the constructor arguments through + // this nested-construction path. Reading `param_count` from `class.constructor` + // alone yielded 0 for a no-own-ctor subclass, so `new Sub(arg)` issued inside a + // method of `Sub` (the recursion-guarded symbol-call path) dropped every arg — + // the synthesized ctor's forwarded params then read uninitialized and the + // inherited `this.x = arg` stored garbage. Pervasive in zod (`new ZodNumber({…})` + // from `_addCheck`, where ZodNumber has no own ctor and ZodType does). + let param_count = effective_constructor_param_count(ctx, class); + let undef_lit = double_literal(f64::from_bits(crate::nanbox::TAG_UNDEFINED)); + // When the ctor's signature is statically known, build per-param values + // with the SAME packing rules the inline path uses — a rest param or the + // synthesized `arguments` param receives a PACKED ARRAY, not a raw + // positional value. Pre-fix, `new Kid({...})` from a method of Kid (the + // recursion-guarded symbol-call path) shoved the user arg RAW into the + // ctor's synthetic `arguments` slot; `super(...arguments)` then spread + // an object with no `length` and the parent ctor saw zero args + // (vendored zod's `z.number().int()` chain — `_addCheck` → + // `new ZodNumber({…})` → `constructor(){ super(...arguments) }`). + let effective_params: Option> = { + let mut found = class.constructor.as_ref().map(|c| c.params.clone()); + if found.is_none() { + let mut parent = class.extends_name.as_deref().map(|s| s.to_string()); + while let Some(pname) = parent { + match ctx.classes.get(&pname).copied() { + Some(pc) => { + if let Some(pctor) = pc.constructor.as_ref() { + found = Some(pctor.params.clone()); + break; + } + parent = pc.extends_name.as_deref().map(|s| s.to_string()); + } + None => break, + } + } + } + found + }; + let capture_fill = ctx + .class_ids + .get(&class.name) + .copied() + .map(|cid| CaptureFill { + cid, + caps_absent_from_args, + }); + let mut ctor_values = if let Some(params) = effective_params { + inline_constructor_param_values_with_class(ctx, ¶ms, lowered_args, capture_fill) + } else { + lowered_args.to_vec() + }; + ctor_values.truncate(param_count); + while ctor_values.len() < param_count { + ctor_values.push(undef_lit.clone()); + } + + let mut ctor_args: Vec<(crate::types::LlvmType, &str)> = + Vec::with_capacity(1 + ctor_values.len()); + ctor_args.push((DOUBLE, obj_box)); + for arg in &ctor_values { + ctor_args.push((DOUBLE, arg.as_str())); + } + Some(ctx.block().call(DOUBLE, &ctor_name, &ctor_args)) +} diff --git a/crates/perry-runtime/src/object/field_get_set/class_object_props.rs b/crates/perry-runtime/src/object/field_get_set/class_object_props.rs index cc6fdc05bbd..a8b7d358f14 100644 --- a/crates/perry-runtime/src/object/field_get_set/class_object_props.rs +++ b/crates/perry-runtime/src/object/field_get_set/class_object_props.rs @@ -39,3 +39,97 @@ pub(super) unsafe fn class_object_name_value( crate::js_nanbox_string(s as i64).to_bits(), )) } + +/// #6530 (size-gate split from `get_field_by_name_tail.rs` — pure +/// relocation): resolve the `constructor` special key for an instance +/// receiver. Own `constructor` data field wins; then WeakMap/WeakSet, +/// the per-evaluation class-object registry (capture-carrying classes), +/// vtable `constructor` methods, boxed primitives, anon shapes, the +/// function-class table, and the INT32 ClassRef synthesis. `None` means +/// "not resolved here" — the caller falls through to the generic walk. +pub(super) unsafe fn instance_constructor_value( + obj: *const ObjectHeader, + key: *const crate::StringHeader, +) -> Option { + if let Some(v) = own_data_field_by_name(obj, key) { + return Some(v); + } + let class_id = (*obj).class_id; + // #6530: a capture-carrying class has no ClassRef value — the + // class VALUE is the per-evaluation class OBJECT registered at + // `js_object_mark_class` time. Return that same object so + // identity holds (`x.constructor === Sub`, bundled zod's + // `describe()` re-construction via `this.constructor` + // yielding the SUBCLASS instead of collapsing to the base). + // The arms below would otherwise hand back a bound + // constructor-method closure (whose underlying func is the + // nearest ancestor ctor — reporting the BASE class's name for + // every subclass) or the bare INT32 ClassRef. + if let Some(v) = super::super::class_registry::class_object_value_for_cid(class_id) { + return Some(JSValue::from_bits(v.to_bits())); + } + // #5834: WeakMap/WeakSet instances carry a reserved class_id + // (not a registered declared-class one), so none of the + // arms below resolve them and `(new WeakMap()).constructor` + // fell through to `undefined`. + if class_id == crate::weakref::CLASS_ID_WEAKMAP || class_id == crate::weakref::CLASS_ID_WEAKSET + { + let name: &[u8] = if class_id == crate::weakref::CLASS_ID_WEAKMAP { + b"WeakMap" + } else { + b"WeakSet" + }; + let v = js_get_global_this_builtin_value(name.as_ptr(), name.len()); + return Some(JSValue::from_bits(v.to_bits())); + } + if class_id != 0 && class_has_own_method(class_id, "constructor") { + let value = class_prototype_method_value_for_name(class_id, "constructor"); + return Some(JSValue::from_bits(value.to_bits())); + } + if matches!( + class_id, + CLASS_ID_BOXED_NUMBER + | CLASS_ID_BOXED_STRING + | CLASS_ID_BOXED_BOOLEAN + | CLASS_ID_BOXED_BIGINT + | CLASS_ID_BOXED_SYMBOL + ) { + let name = match class_id { + CLASS_ID_BOXED_NUMBER => b"Number".as_slice(), + CLASS_ID_BOXED_STRING => b"String".as_slice(), + CLASS_ID_BOXED_BOOLEAN => b"Boolean".as_slice(), + CLASS_ID_BOXED_BIGINT => b"BigInt".as_slice(), + CLASS_ID_BOXED_SYMBOL => b"Symbol".as_slice(), + _ => unreachable!(), + }; + let v = js_get_global_this_builtin_value(name.as_ptr(), name.len()); + return Some(JSValue::from_bits(v.to_bits())); + } + // Object-literal instances (`{ x: 1 }`) carry a synthetic + // `__AnonShape_*` class id. Spec says their `.constructor` + // is the global `Object`, not the synthetic class — so + // resolve through the globalThis singleton so the value + // matches the bare `Object` identifier (`x.constructor + // === Object`, date-fns `constructFrom`, drizzle's + // `isPlainObject` duck check). + if class_id != 0 && is_anon_shape_class_id(class_id) { + let v = js_get_global_this_builtin_value(b"Object".as_ptr(), 6); + return Some(JSValue::from_bits(v.to_bits())); + } + if let Some(func_value) = super::super::class_registry::function_value_for_class_id(class_id) { + return Some(JSValue::from_bits(func_value.to_bits())); + } + if class_id != 0 && is_class_id_registered(class_id) { + let bits = 0x7FFE_0000_0000_0000u64 | (class_id as u64); + return Some(JSValue::from_bits(bits)); + } + // class_id == 0 fallback: plain ObjectHeader allocated + // without an HIR shape (Object.create(null) hybrids, raw + // empty `{}` produced by JSON.parse, etc.). Report + // `Object` so duck-type tests don't trip undefined. + if class_id == 0 { + let v = js_get_global_this_builtin_value(b"Object".as_ptr(), 6); + return Some(JSValue::from_bits(v.to_bits())); + } + None +} diff --git a/crates/perry-runtime/src/object/field_get_set/get_field_by_name_tail.rs b/crates/perry-runtime/src/object/field_get_set/get_field_by_name_tail.rs index 6ac592413ae..3afb24a0940 100644 --- a/crates/perry-runtime/src/object/field_get_set/get_field_by_name_tail.rs +++ b/crates/perry-runtime/src/object/field_get_set/get_field_by_name_tail.rs @@ -1334,90 +1334,9 @@ pub(crate) fn get_field_by_name_object_tail( } } if key_bytes == b"constructor" { - if let Some(v) = own_data_field_by_name(obj, key) { + if let Some(v) = super::class_object_props::instance_constructor_value(obj, key) { return v; } - let class_id = (*obj).class_id; - // #6530: a capture-carrying class has no ClassRef value — the - // class VALUE is the per-evaluation class OBJECT registered at - // `js_object_mark_class` time. Return that same object so - // identity holds (`x.constructor === Sub`, bundled zod's - // `describe()` re-construction via `this.constructor` - // yielding the SUBCLASS instead of collapsing to the base). - // The arms below would otherwise hand back a bound - // constructor-method closure (whose underlying func is the - // nearest ancestor ctor — reporting the BASE class's name for - // every subclass) or the bare INT32 ClassRef. - if let Some(v) = super::super::class_registry::class_object_value_for_cid(class_id) - { - return JSValue::from_bits(v.to_bits()); - } - // #5834: WeakMap/WeakSet instances carry a reserved class_id - // (not a registered declared-class one), so none of the - // arms below resolve them and `(new WeakMap()).constructor` - // fell through to `undefined`. - if class_id == crate::weakref::CLASS_ID_WEAKMAP - || class_id == crate::weakref::CLASS_ID_WEAKSET - { - let name: &[u8] = if class_id == crate::weakref::CLASS_ID_WEAKMAP { - b"WeakMap" - } else { - b"WeakSet" - }; - let v = js_get_global_this_builtin_value(name.as_ptr(), name.len()); - return JSValue::from_bits(v.to_bits()); - } - if class_id != 0 && class_has_own_method(class_id, "constructor") { - let value = class_prototype_method_value_for_name(class_id, "constructor"); - return JSValue::from_bits(value.to_bits()); - } - if matches!( - class_id, - CLASS_ID_BOXED_NUMBER - | CLASS_ID_BOXED_STRING - | CLASS_ID_BOXED_BOOLEAN - | CLASS_ID_BOXED_BIGINT - | CLASS_ID_BOXED_SYMBOL - ) { - let name = match class_id { - CLASS_ID_BOXED_NUMBER => b"Number".as_slice(), - CLASS_ID_BOXED_STRING => b"String".as_slice(), - CLASS_ID_BOXED_BOOLEAN => b"Boolean".as_slice(), - CLASS_ID_BOXED_BIGINT => b"BigInt".as_slice(), - CLASS_ID_BOXED_SYMBOL => b"Symbol".as_slice(), - _ => unreachable!(), - }; - let v = js_get_global_this_builtin_value(name.as_ptr(), name.len()); - return JSValue::from_bits(v.to_bits()); - } - // Object-literal instances (`{ x: 1 }`) carry a synthetic - // `__AnonShape_*` class id. Spec says their `.constructor` - // is the global `Object`, not the synthetic class — so - // resolve through the globalThis singleton so the value - // matches the bare `Object` identifier (`x.constructor - // === Object`, date-fns `constructFrom`, drizzle's - // `isPlainObject` duck check). - if class_id != 0 && is_anon_shape_class_id(class_id) { - let v = js_get_global_this_builtin_value(b"Object".as_ptr(), 6); - return JSValue::from_bits(v.to_bits()); - } - if let Some(func_value) = - super::super::class_registry::function_value_for_class_id(class_id) - { - return JSValue::from_bits(func_value.to_bits()); - } - if class_id != 0 && is_class_id_registered(class_id) { - let bits = 0x7FFE_0000_0000_0000u64 | (class_id as u64); - return JSValue::from_bits(bits); - } - // class_id == 0 fallback: plain ObjectHeader allocated - // without an HIR shape (Object.create(null) hybrids, raw - // empty `{}` produced by JSON.parse, etc.). Report - // `Object` so duck-type tests don't trip undefined. - if class_id == 0 { - let v = js_get_global_this_builtin_value(b"Object".as_ptr(), 6); - return JSValue::from_bits(v.to_bits()); - } } } From 557773ed995172dcf578d56a55305220a0df632f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Fri, 17 Jul 2026 19:51:48 +0200 Subject: [PATCH 5/6] review: imported-ctor arity truncation + null-proto constructor semantics Two pre-existing defects the size-gate relocation exposed to review (CodeRabbit on #6537), both in relocated code: - marshal_imported_ctor_args: out.truncate(param_count.max(out.len())) was a no-op (from #5398), so call sites passing more args than the imported ctor's fixed arity emitted excess operands, violating the documented 'returns exactly ctor.param_count' contract. Truncate for real; JS ignores extra ctor args and the compiled symbol has exactly param_count post-this params. - instance_constructor_value: the class_id==0 fallback reported global Object for EVERY shapeless object, including explicit null-prototype objects (Object.create(null)), whose .constructor must be undefined. Gate the fallback on OBJ_FLAG_NULL_PROTO; ordinary shapeless objects (raw {} from JSON.parse) keep the spec-correct Object report. Verified: Object.create(null).constructor === undefined, ({}).constructor === Object, JSON.parse('{}').constructor === Object all match node. --- .../perry-codegen/src/lower_call/new_ctor_args.rs | 8 +++++++- .../src/object/field_get_set/class_object_props.rs | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/perry-codegen/src/lower_call/new_ctor_args.rs b/crates/perry-codegen/src/lower_call/new_ctor_args.rs index b3911102ac6..8a198d5967d 100644 --- a/crates/perry-codegen/src/lower_call/new_ctor_args.rs +++ b/crates/perry-codegen/src/lower_call/new_ctor_args.rs @@ -333,7 +333,13 @@ pub(super) fn marshal_imported_ctor_args( while out.len() < param_count { out.push(undef.clone()); } - out.truncate(param_count.max(out.len())); + // #6537 review: `param_count.max(out.len())` made this a no-op, so a + // call site passing MORE args than the imported ctor's fixed arity + // emitted excess operands — violating the documented "returns exactly + // `ctor.param_count`" contract (the compiled `_constructor` + // symbol has exactly that many post-`this` params; JS ignores extra + // ctor args). Truncate for real. + out.truncate(param_count); out } } diff --git a/crates/perry-runtime/src/object/field_get_set/class_object_props.rs b/crates/perry-runtime/src/object/field_get_set/class_object_props.rs index a8b7d358f14..df9d7e81234 100644 --- a/crates/perry-runtime/src/object/field_get_set/class_object_props.rs +++ b/crates/perry-runtime/src/object/field_get_set/class_object_props.rs @@ -128,6 +128,20 @@ pub(super) unsafe fn instance_constructor_value( // empty `{}` produced by JSON.parse, etc.). Report // `Object` so duck-type tests don't trip undefined. if class_id == 0 { + // #6537 review: an EXPLICIT null-prototype object + // (`Object.create(null)` / `js_object_alloc_null_proto`, marked with + // `OBJ_FLAG_NULL_PROTO` on the GC header) has NO `constructor` — + // fall through (→ undefined) instead of reporting `Object`. The + // `Object` report stays for ordinary shapeless objects (raw `{}` + // from JSON.parse etc.), which spec-correctly inherit + // `Object.prototype.constructor`. + if (obj as usize) >= crate::gc::GC_HEADER_SIZE + 0x1000 { + let gc_header = + (obj as *const u8).sub(crate::gc::GC_HEADER_SIZE) as *const crate::gc::GcHeader; + if (*gc_header)._reserved & crate::gc::OBJ_FLAG_NULL_PROTO != 0 { + return None; + } + } let v = js_get_global_this_builtin_value(b"Object".as_ptr(), 6); return Some(JSValue::from_bits(v.to_bits())); } From 94e7ed2e060e40f7a3ae6b5b40f0c4261686e1f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Fri, 17 Jul 2026 19:57:51 +0200 Subject: [PATCH 6/6] review: use try_read_gc_header for the null-proto flag probe (addr-class ratchet) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit lint's addr-class ratchet rejected the hand-rolled address floor added in 557773e — a bare GC_HEADER_SIZE+0x1000 floor doesn't reject the fetch/zlib/proxy handle bands, and back-reading a handle id as a GcHeader segfaults on Linux (macOS masks it — #1843/#4004/#6271). Route through the sanctioned crate::value::addr_class::try_read_gc_header predicate, which also rejects small-buffer slab addrs that carry no GcHeader. Behavior verified unchanged: Object.create(null).constructor === undefined, ({}).constructor === Object, JSON.parse('{}').constructor === Object. --- .../src/object/field_get_set/class_object_props.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/crates/perry-runtime/src/object/field_get_set/class_object_props.rs b/crates/perry-runtime/src/object/field_get_set/class_object_props.rs index df9d7e81234..1507efec92f 100644 --- a/crates/perry-runtime/src/object/field_get_set/class_object_props.rs +++ b/crates/perry-runtime/src/object/field_get_set/class_object_props.rs @@ -135,10 +135,8 @@ pub(super) unsafe fn instance_constructor_value( // `Object` report stays for ordinary shapeless objects (raw `{}` // from JSON.parse etc.), which spec-correctly inherit // `Object.prototype.constructor`. - if (obj as usize) >= crate::gc::GC_HEADER_SIZE + 0x1000 { - let gc_header = - (obj as *const u8).sub(crate::gc::GC_HEADER_SIZE) as *const crate::gc::GcHeader; - if (*gc_header)._reserved & crate::gc::OBJ_FLAG_NULL_PROTO != 0 { + if let Some(gc_header) = crate::value::addr_class::try_read_gc_header(obj as usize) { + if gc_header._reserved & crate::gc::OBJ_FLAG_NULL_PROTO != 0 { return None; } }