shape-runtime 0.3.2

Bytecode compiler, builtins, and runtime infrastructure for Shape
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
//! Native `xml` module for XML parsing and serialization.
//!
//! Exports: xml.parse(text), xml.stringify(value)
//!
//! XML nodes are represented as Shape TypedObjects with the `XmlNode`
//! schema: `{ name: string, attributes: HashMap<string, string>,
//!            children: Array<XmlNode>, text: string }`
//!
//! W17-out-of-bundle-A-followups (2026-05-12): children rewire per the
//! C+ precedent recorded in `phase-2d-playbook.md` §3
//! ("Bundle-A checkpoint-2 amendment"). Pre-rewire, each child was an
//! `Arc<HeapValue::HashMap>` carried inside the deleted
//! `TypedArrayData::HeapValue` arm. Post-rewire, each child is an
//! `Arc<HeapValue::TypedObject>` with the registered `XmlNode` schema,
//! and the outer children array lowers to `TypedArrayData::TypedObject`
//! per ADR-006 §2.7.24 Q25.A's specialized list.
//!
//! User-visible API: `node.children[i].name` / `.attributes` / `.text`
//! continue to work via TypedObject field access (same shape as the
//! prior HashMap dispatch). The `text` field is now always present
//! (empty string when absent); the prior optional-field shape was
//! already flattened.
//!
//! Stage C HashMap-marshal P1(b) historical context (2026-05-07):
//! - `xml.parse` returns the root element as `TypedReturn::OkObjectPairs`
//!   per Cluster #4 β shape (mirrors `arrow.metadata` / http.rs precedents).
//! - `xml.stringify` takes `value: HashMap<string, *>` typed input via
//!   `Vec<(Arc<String>, Arc<HeapValue>)>` FromSlot from Step 1 P1(b)
//!   infrastructure (commit `36519f6`). Walks the recursive HeapValue
//!   tree using direct pattern matching — no marshal-boundary
//!   re-entry per element. The reader now dispatches the `children`
//!   field through `TypedArrayData::TypedObject` per the post-rewire
//!   construction shape.
//! - Attributes (`HashMap<string, string>`) carried via
//!   `ConcreteReturn::HashMapStringString` on output and read directly
//!   from `HeapValue::HashMap(d)` on input.
//!
//! Tests deleted along with the legacy ValueWord-based fixtures, mirroring
//! the csv_module migration (commit `9f6b1d3`). New typed-marshal test
//! harness arrives with the shape-vm cleanup workstream.

use crate::marshal::{register_typed_fn_1, register_typed_fn_1_full};
use crate::module_exports::{ModuleExports, ModuleParam};
use crate::type_schema::register_predeclared_any_schema;
use crate::typed_module_exports::{ConcreteReturn, ConcreteType, TypedReturn};
use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event};
use quick_xml::{Reader, Writer};
use shape_value::heap_value::{HashMapData, HeapValue, TypedObjectStorage};
use shape_value::v2::typed_array::TypedArray;
use shape_value::{HeapKind, NativeKind, ValueSlot};
use std::io::Cursor;
use std::sync::Arc;

/// XmlNode schema field order: matches `into_typed_object_arc` field-pair
/// order. The schema is auto-registered via
/// `register_predeclared_any_schema` on first use so the field list is the
/// single source of truth.
const XML_NODE_FIELDS: &[&str] = &["name", "attributes", "children", "text"];

/// Parsed XML element data: a recursive structure where each element has
/// a name, attribute pairs, child elements, and optional text content.
struct ElementData {
    name: String,
    attributes: Vec<(String, String)>,
    children: Vec<ElementData>,
    text: Option<String>,
}

impl ElementData {
    /// Project this element into a `HeapValue::TypedObject(...)` with
    /// the `XmlNode` schema (W17-out-of-bundle-A-followups, 2026-05-12).
    /// Children are recursively projected through this method and form
    /// a `TypedArrayData::TypedObject` array — no polymorphic
    /// `Array<HashMap>` carrier. Per C+ precedent the schema is
    /// auto-registered via `register_predeclared_any_schema`.
    ///
    /// Field order matches `XML_NODE_FIELDS` (name, attributes,
    /// children, text). `text` is always present at the slot level
    /// (empty string when the source XML had no text node) so the
    /// schema is fixed-arity and the type is exhaustive — no Option
    /// indirection at the storage layer.
    fn into_typed_object_arc(self) -> Arc<HeapValue> {
        // Wave 2 Round 3b C2-joint ckpt-4 (2026-05-14): build the XML
        // attributes HashMap via the per-V mutation API on
        // `HashMapData<*const StringObj>` (V = string). Each (k, v) pair
        // becomes one fresh StringObj insert; the wrapper carries one
        // refcount share per element. ADR-006 §2.7.24 Q25.B SUPERSEDED.
        let mut attrs_data: HashMapData<*const shape_value::v2::string_obj::StringObj> =
            HashMapData::new();
        for (k, v) in &self.attributes {
            let v_obj = shape_value::v2::string_obj::StringObj::new(v.as_str())
                as *const shape_value::v2::string_obj::StringObj;
            unsafe { attrs_data.insert(k.as_str(), v_obj) };
        }
        let attrs_data: shape_value::heap_value::HashMapKindedRef =
            shape_value::heap_value::HashMapKindedRef::String(Arc::new(attrs_data));
        // Recurse: each child becomes its own TypedObject. The child raw
        // `*const TypedObjectStorage` pointers are packed into a
        // `*mut TypedArray<*const TypedObjectStorage>` flat-struct carrier
        // per V3-S5 ckpt-5-prime²c Migration shape (a) (the deleted
        // `TypedArrayData::TypedObject` enum-arm shape). The
        // `TypedObjectStorage` type impls `v2::heap_element::HeapElement`
        // (`heap_value.rs:3971`), so per-element retain/release dispatches
        // through `v2_retain` / `v2_release` on the on-header refcount.
        //
        // Each child `into_typed_object_arc()` returns an `Arc<HeapValue>`
        // wrapping `HeapValue::TypedObject(TypedObjectPtr)` — we extract
        // the inner raw pointer via `into_raw()` (transferring the
        // wrapper's one refcount share to the raw pointer, which the
        // `TypedArray` takes ownership of as an element).
        let child_ptrs: Vec<*const TypedObjectStorage> = self
            .children
            .into_iter()
            .map(|c| {
                let child_hv = c.into_typed_object_arc();
                // Extract inner TypedObjectPtr by cloning out and consuming.
                let to_ptr = match &*child_hv {
                    HeapValue::TypedObject(s) => s.clone(),
                    _ => unreachable!(
                        "into_typed_object_arc must return HeapValue::TypedObject"
                    ),
                };
                to_ptr.into_raw()
            })
            .collect();
        let children_arr: *mut TypedArray<*const TypedObjectStorage> =
            TypedArray::<*const TypedObjectStorage>::from_slice(&child_ptrs);
        // `from_slice` copies each `*const TypedObjectStorage` bit-for-bit
        // (raw pointers are Copy). The refcount shares were transferred
        // from the source `TypedObjectPtr` wrappers into raw pointers
        // already; the source `Vec<*const _>` doesn't own any share, so
        // ordinary Drop suffices for the source Vec's heap allocation.
        // Element-share ownership now lives with the array.

        let schema_id = ensure_xml_node_schema();
        // Field-order: name(0), attributes(1), children(2), text(3).
        // Heap mask: name(String), attributes(HashMap), children(TypedArray),
        // text(String) — all 4 fields are heap-resident.
        let name_arc = Arc::new(self.name);
        let attrs_arc = Arc::new(attrs_data);
        let text_arc = Arc::new(self.text.unwrap_or_default());

        let slots: Box<[ValueSlot]> = Box::new([
            ValueSlot::from_string_arc(name_arc),
            ValueSlot::from_hashmap(attrs_arc),
            // V3-S5 ckpt-5-prime²c (2026-05-15) Migration shape (a): the
            // `ValueSlot::from_typed_array(Arc<TypedArrayData>)` constructor
            // is deleted; per-element-kind constructors aren't landed yet
            // (Round 2 follow-up). Store the raw `*mut TypedArray<T>`
            // pointer directly via `ValueSlot::from_u64` — this is the
            // canonical slot-bit shape for `NativeKind::Ptr(HeapKind::
            // TypedArray)` per `docs/runtime-v2-spec.md`. The schema's
            // field_kinds[2] = `Ptr(HeapKind::TypedArray)` controls
            // drop dispatch at slot release time.
            ValueSlot::from_u64(children_arr as u64),
            ValueSlot::from_string_arc(text_arc),
        ]);
        let field_kinds: Arc<[NativeKind]> = Arc::from(
            vec![
                NativeKind::String,
                NativeKind::Ptr(HeapKind::HashMap),
                NativeKind::Ptr(HeapKind::TypedArray),
                NativeKind::String,
            ]
            .into_boxed_slice(),
        );
        let heap_mask: u64 = 0b1111; // all 4 fields heap-resident
        // Wave 2 Round 4 D4 ckpt-final-prime² (2026-05-14): variant signature
        // flipped to `HeapValue::TypedObject(TypedObjectPtr)`. The
        // `_new`-returned raw pointer (refcount=1) is wrapped in
        // `TypedObjectPtr`, transferring the share to the wrapper.
        let storage = TypedObjectStorage::_new(
            schema_id as u64,
            slots,
            heap_mask,
            field_kinds,
        );
        Arc::new(HeapValue::TypedObject(
            shape_value::heap_value::TypedObjectPtr::new(storage),
        ))
    }

    /// Project this element's TOP-LEVEL form as a `Vec<(String,
    /// ConcreteReturn)>` pair-list, suitable for `TypedReturn::OkObjectPairs`.
    /// Used only for the root element of `xml.parse`'s return value;
    /// nested elements go through `into_typed_object_arc` instead.
    fn into_root_pairs(self) -> Vec<(String, ConcreteReturn)> {
        let attrs_pairs: Vec<(String, String)> = self.attributes;
        // Each child is now an `Arc<HeapValue::TypedObject>`. The marshal
        // boundary's `ConcreteReturn::ArrayHeapValue` consumer routes
        // through `TypedArrayData::build_specialized_from_heap_arcs`,
        // which already dispatches the `HeapValue::TypedObject` arm to
        // `TypedArrayData::TypedObject` per ADR-006 §2.7.24 Q25.A. No
        // out-of-territory follow-up: the rewire is structurally
        // resolved by C+ precedent.
        let children_arc: Vec<Arc<HeapValue>> = self
            .children
            .into_iter()
            .map(ElementData::into_typed_object_arc)
            .collect();

        let mut pairs = vec![
            ("name".to_string(), ConcreteReturn::String(self.name)),
            (
                "attributes".to_string(),
                ConcreteReturn::HashMapStringString(attrs_pairs),
            ),
            (
                "children".to_string(),
                ConcreteReturn::ArrayHeapValue(children_arc),
            ),
        ];
        // `text?` follows the regex.rs precedent: emit empty string when
        // absent. Keeps the schema fixed at 4 fields when text is present
        // and 3 fields when absent — variable-length pair list per the
        // ObjectPairs contract.
        if let Some(text) = self.text {
            pairs.push(("text".to_string(), ConcreteReturn::String(text)));
        }
        pairs
    }
}

/// Register the `XmlNode` predeclared schema (auto-registered on first
/// use; subsequent calls return the cached SchemaId via the registry's
/// own deduplication). Returns the raw `u32` schema id used by
/// `TypedObjectStorage::schema_id`.
fn ensure_xml_node_schema() -> u32 {
    let owned: Vec<String> = XML_NODE_FIELDS.iter().map(|s| s.to_string()).collect();
    register_predeclared_any_schema(&owned)
}

/// Parse an XML element recursively from a quick-xml reader.
fn parse_element(
    reader: &mut Reader<&[u8]>,
    start: &BytesStart,
) -> Result<ElementData, String> {
    let name = std::str::from_utf8(start.name().as_ref())
        .map_err(|e| format!("Invalid UTF-8 in element name: {}", e))?
        .to_string();

    let mut attributes = Vec::new();
    for attr in start.attributes() {
        let attr = attr.map_err(|e| format!("Invalid attribute: {}", e))?;
        let key = std::str::from_utf8(attr.key.as_ref())
            .map_err(|e| format!("Invalid UTF-8 in attribute key: {}", e))?
            .to_string();
        let value = attr
            .unescape_value()
            .map_err(|e| format!("Invalid attribute value: {}", e))?
            .to_string();
        attributes.push((key, value));
    }

    let mut children = Vec::new();
    let mut text_parts = Vec::new();
    let mut buf = Vec::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(ref e)) => {
                let child = parse_element(reader, e)?;
                children.push(child);
            }
            Ok(Event::Empty(ref e)) => {
                let child = parse_empty_element(e)?;
                children.push(child);
            }
            Ok(Event::Text(ref e)) => {
                let t = e
                    .unescape()
                    .map_err(|err| format!("Error unescaping text: {}", err))?
                    .to_string();
                let trimmed = t.trim().to_string();
                if !trimmed.is_empty() {
                    text_parts.push(trimmed);
                }
            }
            Ok(Event::CData(ref e)) => {
                let t = std::str::from_utf8(e.as_ref())
                    .map_err(|err| format!("Invalid UTF-8 in CDATA: {}", err))?
                    .to_string();
                if !t.trim().is_empty() {
                    text_parts.push(t);
                }
            }
            Ok(Event::End(_)) => break,
            Ok(Event::Eof) => {
                return Err("Unexpected end of XML".to_string());
            }
            Ok(_) => {} // Skip comments, PI, etc.
            Err(e) => return Err(format!("XML parse error: {}", e)),
        }
        buf.clear();
    }

    Ok(ElementData {
        name,
        attributes,
        children,
        text: if text_parts.is_empty() {
            None
        } else {
            Some(text_parts.join(""))
        },
    })
}

/// Parse a self-closing XML element (e.g. `<br/>`).
fn parse_empty_element(start: &BytesStart) -> Result<ElementData, String> {
    let name = std::str::from_utf8(start.name().as_ref())
        .map_err(|e| format!("Invalid UTF-8 in element name: {}", e))?
        .to_string();

    let mut attributes = Vec::new();
    for attr in start.attributes() {
        let attr = attr.map_err(|e| format!("Invalid attribute: {}", e))?;
        let key = std::str::from_utf8(attr.key.as_ref())
            .map_err(|e| format!("Invalid UTF-8 in attribute key: {}", e))?
            .to_string();
        let value = attr
            .unescape_value()
            .map_err(|e| format!("Invalid attribute value: {}", e))?
            .to_string();
        attributes.push((key, value));
    }

    Ok(ElementData {
        name,
        attributes,
        children: Vec::new(),
        text: None,
    })
}

/// Walk a top-level node — represented as a `(keys, values)` pair-list
/// from the marshal boundary — and emit the corresponding XML via the
/// writer. The top-level input from `xml.stringify` is still keyed by
/// field name (the `Vec<(Arc<String>, Arc<HeapValue>)>` FromSlot
/// shape); children recurse through `write_typed_object_node` against
/// `HeapValue::TypedObject` arms now that `into_typed_object_arc`
/// produces TypedObject per child (W17-out-of-bundle-A-followups,
/// 2026-05-12).
fn write_node_pairs(
    writer: &mut Writer<Cursor<Vec<u8>>>,
    pairs: &[(Arc<String>, Arc<HeapValue>)],
) -> Result<(), String> {
    // V3-S5 ckpt-5-prime²c (2026-05-15) SURFACE: the top-level pair-list
    // shape carries `Arc<HeapValue>` values, but the `HeapValue::TypedArray`
    // outer arm is deleted (V3-S5 ckpt-5). The `children` field now arrives
    // as a `*mut TypedArray<TypedObjectPtr>` raw pointer, which has no
    // `HeapValue::*` wrapper — `Vec<(Arc<String>, Arc<HeapValue>)>` cannot
    // express it. xml.stringify's top-level reader thus requires the Round 2
    // `Vec<Arc<HeapValue>>` rewire follow-up to add a per-element-T marshal
    // path (pairs with `from_typed_array_<T>` constructor wave at
    // `crates/shape-value/src/slot.rs:142`).
    let _ = (writer, pairs);
    let _ = write_xml_element; // keep helper reachable
    Err(
        "xml.method stringify() -> V3-S5 ckpt-5-prime²c SURFACE — top-level \
         pair-list reader needs Vec<Arc<HeapValue>> rewire for the deleted \
         outer-array-arm. Round 2 follow-up (pairs with per-element-kind \
         constructor wave). ADR-006 §2.7.24 Q25.A SUPERSEDED."
            .to_string(),
    )
}

/// Walk a child node — represented as an `Arc<TypedObjectStorage>` with
/// the `XmlNode` schema. Reads each field via `field_index_in_schema`
/// since the schema is auto-registered and field-order is locked to
/// `XML_NODE_FIELDS`.
///
/// W17-out-of-bundle-A-followups (2026-05-12): replaces the previous
/// `write_node_heap` HashMap-element reader. The construction side
/// (`ElementData::into_typed_object_arc`) builds TypedObjects per
/// child, so the array's elements arrive here as TypedObjects, not
/// HashMaps.
fn write_typed_object_node(
    writer: &mut Writer<Cursor<Vec<u8>>>,
    storage: &TypedObjectStorage,
) -> Result<(), String> {
    // Match field order from `XML_NODE_FIELDS`. The construction side
    // writes slots in this exact order; the schema registration uses
    // the same field list, so positional access is sound.
    if storage.slots.len() != XML_NODE_FIELDS.len() {
        return Err(format!(
            "xml.stringify(): child TypedObject has {} slots, expected {}",
            storage.slots.len(),
            XML_NODE_FIELDS.len()
        ));
    }
    let name_slot = &storage.slots[0];
    let attrs_slot = &storage.slots[1];
    let children_slot = &storage.slots[2];
    let text_slot = &storage.slots[3];

    // SAFETY for each slot: the construction-side contract in
    // `ElementData::into_typed_object_arc` writes each slot as
    // `ValueSlot::from_string_arc` / `from_hashmap` / `from_typed_array`
    // — the bits are `Arc::into_raw::<T>` for the matching `T`. We
    // bump the strong count, recover via `Arc::from_raw`, then drop the
    // bumped share after extracting a clone of the payload (the
    // storage's own share remains intact; this is the canonical
    // 5-arm receiver-recovery shape from `3ac2f11`).
    let name: String = unsafe {
        let bits = name_slot.raw();
        if bits == 0 {
            return Err("xml.method stringify() -> TypedObject name slot is null".to_string());
        }
        let arc_ptr = bits as *const String;
        Arc::increment_strong_count(arc_ptr);
        let arc = Arc::from_raw(arc_ptr);
        let owned = (*arc).clone();
        // `arc` Drop here releases our bumped share; storage's share
        // is untouched.
        owned
    };
    let attrs_kref: Option<shape_value::heap_value::HashMapKindedRef> = unsafe {
        let bits = attrs_slot.raw();
        if bits == 0 {
            None
        } else {
            // Wave 2 Round 3b C2-joint ckpt-2 (2026-05-14): the
            // `ValueSlot::from_hashmap` shape stores
            // `Arc::into_raw(Arc<HashMapKindedRef>)` per ADR-006
            // §2.7.24 Q25.B SUPERSEDED. Bump and clone-out the
            // kinded ref (single Arc share); the storage's share
            // is untouched (`5-arm receiver-recovery` shape from
            // `3ac2f11`).
            let arc_ptr = bits as *const shape_value::heap_value::HashMapKindedRef;
            Arc::increment_strong_count(arc_ptr);
            let arc = Arc::from_raw(arc_ptr);
            let cloned = (*arc).clone();
            // `arc` Drop here releases our bumped outer Arc share.
            Some(cloned)
        }
    };
    // V3-S5 ckpt-5-prime²c (2026-05-15): the children slot now holds a
    // raw `*mut TypedArray<*const TypedObjectStorage>` per Migration
    // shape (a) — no outer Arc/wrapper. Element-kind enforcement is by
    // the storage's `field_kinds[2] = Ptr(HeapKind::TypedArray)` +
    // body-side element-`T` choice. `TypedObjectStorage` impls
    // `v2::heap_element::HeapElement` (`heap_value.rs:3971`), so the
    // element pointers carry on-header refcount shares.
    let children_ptr: *const TypedArray<*const TypedObjectStorage> = {
        let bits = children_slot.raw();
        if bits == 0 {
            std::ptr::null()
        } else {
            bits as usize as *const TypedArray<*const TypedObjectStorage>
        }
    };
    let text: Option<String> = unsafe {
        let bits = text_slot.raw();
        if bits == 0 {
            None
        } else {
            let arc_ptr = bits as *const String;
            Arc::increment_strong_count(arc_ptr);
            let arc = Arc::from_raw(arc_ptr);
            let owned = (*arc).clone();
            if owned.is_empty() {
                None
            } else {
                Some(owned)
            }
        }
    };

    write_xml_element(
        writer,
        Some(name),
        attrs_kref.as_ref(),
        children_ptr,
        text.as_deref(),
    )
}

/// Shared element-writer body — emits the XML representation of a node
/// given the four parsed XmlNode fields. Pulled out so the top-level
/// `write_node_pairs` path and the recursive
/// `write_typed_object_node` path share the same output discipline.
///
/// V3-S5 ckpt-5-prime²c (2026-05-15): `children` is the raw
/// `*const TypedArray<TypedObjectPtr>` carrier per Migration shape (a).
/// Null pointer means "no children".
fn write_xml_element(
    writer: &mut Writer<Cursor<Vec<u8>>>,
    name: Option<String>,
    attrs: Option<&shape_value::heap_value::HashMapKindedRef>,
    children: *const TypedArray<*const TypedObjectStorage>,
    text: Option<&str>,
) -> Result<(), String> {
    let name = name.ok_or_else(|| "xml.stringify(): node missing 'name' field".to_string())?;

    let mut elem = BytesStart::new(name.clone());

    if let Some(attrs) = attrs {
        // Wave 2 Round 3b C2-joint ckpt-4 (2026-05-14): per-V walk —
        // attributes are always `HashMap<string, string>` (V = String).
        // Other V variants are a producer-side type error (xml.stringify
        // declares the attribute slot type at the marshal boundary).
        use shape_value::heap_value::HashMapKindedRef;
        match attrs {
            HashMapKindedRef::String(arc) => {
                let n = arc.len();
                for i in 0..n {
                    let key: String = unsafe {
                        let ptr = shape_value::v2::typed_array::TypedArray::get_unchecked(
                            arc.keys, i as u32,
                        );
                        shape_value::v2::string_obj::StringObj::as_str(ptr).to_owned()
                    };
                    let val: String = unsafe {
                        let v_ptr: *const shape_value::v2::string_obj::StringObj =
                            *(*arc.values).data.add(i);
                        shape_value::v2::string_obj::StringObj::as_str(v_ptr).to_owned()
                    };
                    elem.push_attribute((key.as_bytes(), val.as_bytes()));
                }
            }
            other => {
                return Err(format!(
                    "xml.stringify(): attributes HashMap must be HashMap<string, string>, \
                     got V={:?}",
                    other.values_kind()
                ));
            }
        }
    }

    // V3-S5 ckpt-5-prime²c (2026-05-15) Migration shape (a): children
    // carrier is `*const TypedArray<TypedObjectPtr>`. Null means "no
    // children". Element discriminator is the body-side `T` choice +
    // schema's `field_kinds[2] = Ptr(HeapKind::TypedArray)`.
    let child_count: u32 = if children.is_null() {
        0
    } else {
        unsafe { TypedArray::<*const TypedObjectStorage>::len(children) }
    };
    let has_children = child_count > 0;
    let has_text = text.is_some();

    if !has_children && !has_text {
        writer
            .write_event(Event::Empty(elem))
            .map_err(|e| format!("xml.stringify() write error: {}", e))?;
    } else {
        writer
            .write_event(Event::Start(elem.clone()))
            .map_err(|e| format!("xml.stringify() write error: {}", e))?;

        if let Some(text) = text {
            writer
                .write_event(Event::Text(BytesText::new(text)))
                .map_err(|e| format!("xml.stringify() write error: {}", e))?;
        }

        if has_children {
            // SAFETY: `children` is non-null (checked above) and points to
            // a live `TypedArray<*const TypedObjectStorage>` per the
            // construction contract in `ElementData::into_typed_object_arc`.
            let slice = unsafe {
                TypedArray::<*const TypedObjectStorage>::as_slice(children)
            };
            for &child_ptr in slice.iter() {
                // SAFETY: per the construction contract each element is a
                // live `*const TypedObjectStorage` with refcount >= 1 owed
                // to the array's element slot.
                unsafe {
                    write_typed_object_node(writer, &*child_ptr)?;
                }
            }
        }

        writer
            .write_event(Event::End(BytesEnd::new(name)))
            .map_err(|e| format!("xml.stringify() write error: {}", e))?;
    }

    Ok(())
}

/// Create the `xml` module with XML parsing and serialization functions.
pub fn create_xml_module() -> ModuleExports {
    let mut module = ModuleExports::new("std::core::xml");
    module.description = "XML parsing and serialization".to_string();

    // xml.parse(text: string) -> Result<HashMap>
    register_typed_fn_1::<_, Arc<String>>(
        &mut module,
        "parse",
        "Parse an XML string into a Shape HashMap node",
        "text",
        "string",
        ConcreteType::Result(Box::new(ConcreteType::HashMap)),
        |text, _ctx| {
            let mut reader = Reader::from_str(text.as_str());
            reader.config_mut().trim_text(true);
            let mut buf = Vec::new();

            loop {
                match reader.read_event_into(&mut buf) {
                    Ok(Event::Start(ref e)) => {
                        let inner = parse_element(&mut reader, e)?;
                        return Ok(TypedReturn::OkObjectPairs(inner.into_root_pairs()));
                    }
                    Ok(Event::Empty(ref e)) => {
                        let inner = parse_empty_element(e)?;
                        return Ok(TypedReturn::OkObjectPairs(inner.into_root_pairs()));
                    }
                    Ok(Event::Eof) => {
                        return Err("xml.parse(): no root element found".to_string());
                    }
                    Ok(_) => {} // Skip declaration, comments, PI
                    Err(e) => {
                        return Err(format!("xml.parse() failed: {}", e));
                    }
                }
                buf.clear();
            }
        },
    );

    // xml.stringify(value: HashMap<string, any>) -> Result<string>
    register_typed_fn_1_full::<_, Vec<(Arc<String>, Arc<HeapValue>)>>(
        &mut module,
        "stringify",
        "Serialize a Shape HashMap node to an XML string",
        [ModuleParam {
            name: "value".to_string(),
            type_name: "HashMap<string, any>".to_string(),
            required: true,
            description:
                "Node value to serialize (with name, attributes, children, text? fields)"
                    .to_string(),
            ..Default::default()
        }],
        ConcreteType::Result(Box::new(ConcreteType::String)),
        |pairs: Vec<(Arc<String>, Arc<HeapValue>)>, _ctx| {
            let mut writer = Writer::new(Cursor::new(Vec::new()));
            write_node_pairs(&mut writer, &pairs)?;

            let output = String::from_utf8(writer.into_inner().into_inner())
                .map_err(|e| format!("xml.stringify(): invalid UTF-8 output: {}", e))?;

            Ok(TypedReturn::Ok(ConcreteReturn::String(output)))
        },
    );

    module
}