quickjs-capi 0.13.0

C ABI compatibility layer: the QuickJS C API on top of the pure-Rust engine
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
//! `JS_WriteObject`/`JS_ReadObject`: a serialised copy of a value's graph.
//!
//! # The format is ours
//!
//! The reference's binary JSON is an implementation detail of its own bytecode compiler: an
//! atom table, then a tree of tags, tuned so that a bundle of precompiled modules is small.
//! Nothing outside the engine reads it, and `tests/test_bjson.js` — the acceptance driver —
//! asserts a **round trip** (`toStr(write(x)) == toStr(read(write(x)))`) with no hard-coded
//! bytes anywhere: the one place that printed hex is inside `if (0)`.
//!
//! So this writes its own format, and says so rather than pretending to be
//!
//! ```text
//! header   : u8 version
//! tag      : one of the `TAG_*` bytes below
//! length   : unsigned LEB128
//! ```
//!
//! What it *does* keep from the reference is the property that makes the format worth
//! having at all: with `JS_WRITE_OBJ_REFERENCE`, an object is written once and referred to by
//! index afterwards, so a cycle survives a round trip and two properties that were the same
//! object are still the same object afterwards.
//!
//! # What cannot be written
//!
//! A function, a module, a proxy, a regular expression or a host class instance has no
//! serialisation: the reference answers `TypeError: unsupported object class` for exactly the
//! same set (its `default` arm in `JS_WriteObjectRec`). Writing one would need something to
//! point at in a process that may not have the code any more.

use std::collections::HashMap;

use engine::builtins::typedarray::ELEMENT_TYPES;
use engine::object::{BufferStorage, JsObject, PropertyKey};
use engine::{Gc, Interp, Value};

use crate::jsvalue::{self, JsValue};
use crate::runtime::{self, JsContext};
use crate::value_helpers::jsvalue_of;

/// The format's version byte. Bumped when a tag changes meaning, never otherwise.
const VERSION: u8 = 1;

const TAG_UNDEFINED: u8 = 1;
const TAG_NULL: u8 = 2;
const TAG_FALSE: u8 = 3;
const TAG_TRUE: u8 = 4;
const TAG_INT32: u8 = 5;
const TAG_FLOAT64: u8 = 6;
const TAG_STRING: u8 = 7;
const TAG_OBJECT: u8 = 8;
const TAG_ARRAY: u8 = 9;
const TAG_BIGINT: u8 = 10;
const TAG_TYPED_ARRAY: u8 = 11;
const TAG_ARRAY_BUFFER: u8 = 12;
const TAG_DATE: u8 = 13;
const TAG_OBJECT_VALUE: u8 = 14;
const TAG_REFERENCE: u8 = 15;

/// `JS_WRITE_OBJ_REFERENCE`: write shared objects once and refer to them by index.
pub const WRITE_OBJ_REFERENCE: i32 = 1 << 3;
/// `JS_WRITE_OBJ_BYTECODE`: accepted and ignored — this engine serialises values only.
pub const WRITE_OBJ_BYTECODE: i32 = 1 << 0;
/// `JS_READ_OBJ_REFERENCE`: resolve `TAG_REFERENCE` against the objects read so far.
pub const READ_OBJ_REFERENCE: i32 = 1 << 3;
/// `JS_READ_OBJ_BYTECODE`: accepted and ignored, like [`WRITE_OBJ_BYTECODE`].
pub const READ_OBJ_BYTECODE: i32 = 1 << 0;
/// `JS_WRITE_OBJ_SAB`/`JS_READ_OBJ_SAB`: no `SharedArrayBuffer` exists in this engine.
pub const WRITE_OBJ_SAB: i32 = 1 << 2;
/// See [`WRITE_OBJ_SAB`].
pub const READ_OBJ_SAB: i32 = 1 << 2;
/// `JS_WRITE_OBJ_BSWAP`: byte-swapped output is a big-endian host's problem, and this
/// engine writes little-endian always. Accepted, ignored.
pub const WRITE_OBJ_BSWAP: i32 = 1 << 1;

// ---------------------------------------------------------------------------
// Writing
// ---------------------------------------------------------------------------

/// The state one `JS_WriteObject` call carries.
struct Writer {
    out: Vec<u8>,
    /// Objects already written, by address, so a second sighting becomes a reference.
    ///
    /// Address, not `Gc` identity by contents: two distinct objects with equal contents must
    /// stay two objects, which is the whole point of the reference mode.
    seen: HashMap<usize, u64>,
    /// Whether references are allowed at all. Without them a shared object is an error,
    /// because a copy would change the graph's shape silently.
    allow_reference: bool,
    /// Objects on the current path, so a cycle *without* reference mode is caught here
    /// rather than recursing until the stack ends.
    marks: Vec<usize>,
}

/// Serialise `value`.
///
/// # Errors
///
/// The reference's own messages: `circular reference` for a cycle without
/// `JS_WRITE_OBJ_REFERENCE`, `only value properties are supported` for an enumerable
/// accessor, and `unsupported object class` for anything with no serialisation.
pub fn write(interp: &Interp<'_>, value: &Value, flags: i32) -> Result<Vec<u8>, String> {
    let mut writer = Writer {
        out: vec![VERSION],
        seen: HashMap::new(),
        allow_reference: flags & WRITE_OBJ_REFERENCE != 0,
        marks: Vec::new(),
    };
    writer.value(interp, value)?;
    Ok(writer.out)
}

impl Writer {
    fn byte(&mut self, byte: u8) {
        self.out.push(byte);
    }

    fn bytes(&mut self, bytes: &[u8]) {
        self.out.extend_from_slice(bytes);
    }

    fn leb(&mut self, mut value: u64) {
        loop {
            let byte = (value & 0x7f) as u8;
            value >>= 7;
            if value == 0 {
                self.byte(byte);
                return;
            }
            self.byte(byte | 0x80);
        }
    }

    fn string(&mut self, text: &engine::value::Wtf8) {
        let bytes = text.as_bytes();
        self.leb(bytes.len() as u64);
        let bytes = bytes.to_vec();
        self.bytes(&bytes);
    }

    fn value(&mut self, interp: &Interp<'_>, value: &Value) -> Result<(), String> {
        match value {
            Value::Undefined => self.byte(TAG_UNDEFINED),
            Value::Null => self.byte(TAG_NULL),
            Value::Bool(false) => self.byte(TAG_FALSE),
            Value::Bool(true) => self.byte(TAG_TRUE),
            // `-0.0` and `NaN` only survive as a float, and `1.0` and `1` are the same
            // number to every reader — so an integral `f64` is written as an int when it
            // fits, which is what keeps a round trip's `typeof` stable.
            Value::Int(number) => {
                self.byte(TAG_INT32);
                self.bytes(&number.to_le_bytes());
            }
            Value::Float(number) => {
                if number.fract() == 0.0
                    && *number >= i32::MIN as f64
                    && *number <= i32::MAX as f64
                    && !(*number == 0.0 && number.is_sign_negative())
                {
                    self.byte(TAG_INT32);
                    self.bytes(&(*number as i32).to_le_bytes());
                } else {
                    self.byte(TAG_FLOAT64);
                    self.bytes(&number.to_le_bytes());
                }
            }
            Value::String(text) => {
                self.byte(TAG_STRING);
                self.string(text.wtf8());
            }
            Value::BigInt(big) => {
                // Decimal text, not limbs: the format stays readable and the conversion is
                // one call each way rather than a private limb layout leaking into a file
                // format.
                self.byte(TAG_BIGINT);
                self.byte(u8::from(big.is_negative()));
                let text = big.abs().to_decimal_string();
                self.leb(text.len() as u64);
                self.bytes(text.as_bytes());
            }
            Value::Symbol(_) => return Err("unsupported tag (symbol)".to_string()),
            Value::Object(object) => self.object(interp, object)?,
            // An array's hole is `undefined` to every reader but `in` and `forEach`, and the
            // reference's writer does the same: its fast-array loop writes `JS_UNDEFINED`
            // for the slots past the dense prefix, so `[1,,3]` round-trips to `[1,undefined,3]`
            // — the same elements, one of which is now present. Reporting a hole as an
            // unsupported tag instead made the acceptance driver fail on `[1, , 2, , 3]`.
            Value::Hole => self.byte(TAG_UNDEFINED),
            // The two operand-stack markers and `Uninitialized` never reach a serialiser; a
            // caller that hands one over is a bug in this layer.
            Value::CatchOffset(_) | Value::ReturnAddress(_) | Value::Uninitialized => {
                return Err(format!("unsupported tag (internal marker {value:?})"));
            }
        }
        Ok(())
    }

    fn object(&mut self, interp: &Interp<'_>, object: &Gc<JsObject>) -> Result<(), String> {
        let address = object.address();
        if self.allow_reference {
            if let Some(&index) = self.seen.get(&address) {
                self.byte(TAG_REFERENCE);
                self.leb(index);
                return Ok(());
            }
            self.seen.insert(address, self.seen.len() as u64);
        } else {
            if self.marks.contains(&address) {
                return Err("circular reference".to_string());
            }
            self.marks.push(address);
        }
        let result = self.object_body(interp, object);
        if !self.allow_reference {
            self.marks.pop();
        }
        result
    }

    fn object_body(&mut self, interp: &Interp<'_>, object: &Gc<JsObject>) -> Result<(), String> {
        // A function, a module namespace, a proxy or a host-class instance has no
        // serialisation. Checked before the shapes below, because a *callable* object is an
        // ordinary one in every other respect — without this a function was written as an
        // empty object, which is a silent copy of the wrong thing rather than the reference's
        // `unsupported object class`.
        if object.is_callable()
            || object.host_class_id().is_some()
            || object.proxy_state().is_some()
            || object.is_regexp()
        {
            return Err("unsupported object class".to_string());
        }
        if object.is_array() {
            self.byte(TAG_ARRAY);
            let length = object.array_length().unwrap_or(0);
            self.leb(length as u64);
            for index in 0..length {
                // A hole and an explicit `undefined` are the same element to every reader
                // that is not `in`/`forEach`, and the reference writes a hole as
                // `JS_UNDEFINED` too.
                let element = object.array_get(index).unwrap_or(Value::Undefined);
                self.value(interp, &element)?;
            }
            return Ok(());
        }
        if let Some(storage) = object.array_buffer_storage() {
            self.array_buffer(&storage)?;
            return Ok(());
        }
        if let Some((buffer, element, offset, length)) = object.typed_array_parts() {
            self.byte(TAG_TYPED_ARRAY);
            self.byte(element as u8);
            self.leb(length as u64);
            self.leb(offset as u64);
            // The buffer goes last because it may be a reference to one already written —
            // which is exactly the case a set of views over one buffer produces.
            self.object(interp, &buffer)?;
            return Ok(());
        }
        if interp
            .internal_get(object, "_class")
            .is_some_and(|tag| tag.to_js_string() == "Date")
        {
            self.byte(TAG_DATE);
            let value = interp
                .internal_get(object, "_date_value")
                .map(|value| value.to_number())
                .unwrap_or(f64::NAN);
            self.value(interp, &Value::Float(value))?;
            return Ok(());
        }
        if let Some(boxed) = interp.internal_get(object, "_value") {
            // `new Number(1)`, `new String("ab")`, `new Boolean(true)` and `Object(1n)` are
            // wrappers: the primitive is the whole content, so the read side rebuilds the
            // wrapper from it rather than storing a class id.
            self.byte(TAG_OBJECT_VALUE);
            self.value(interp, &boxed)?;
            return Ok(());
        }
        self.byte(TAG_OBJECT);
        // Only enumerable own string properties, which is what the reference writes: a
        // symbol key cannot be represented in a format that has no symbol table, and a
        // non-enumerable one is not part of the object's data in any JSON-like sense.
        let mut entries: Vec<(engine::value::Wtf8, Value)> = Vec::new();
        for key in object.own_property_keys_in_definition_order() {
            if key.is_symbol() {
                continue;
            }
            let Some(property) = object.own_property_key(&key) else {
                continue;
            };
            if !property.enumerable {
                continue;
            }
            if property.is_accessor() {
                return Err("only value properties are supported".to_string());
            }
            let Some(value) = property.value else {
                continue;
            };
            let PropertyKey::String(text) = &key else {
                continue;
            };
            entries.push((text.clone(), value));
        }
        self.leb(entries.len() as u64);
        for (key, value) in entries {
            self.string(&key);
            self.value(interp, &value)?;
        }
        Ok(())
    }

    fn array_buffer(
        &mut self,
        storage: &std::rc::Rc<std::cell::RefCell<BufferStorage>>,
    ) -> Result<(), String> {
        let storage = storage.borrow();
        if storage.detached {
            return Err("ArrayBuffer is detached".to_string());
        }
        self.byte(TAG_ARRAY_BUFFER);
        self.leb(storage.bytes.len() as u64);
        // Resizability needs its own byte: `new ArrayBuffer(4, {maxByteLength: 4})` and
        // `new ArrayBuffer(4)` have the same two numbers and are still different buffers —
        // one accepts `resize`, the other throws. Inferring the flag by comparing the lengths
        // made `assert(ab.resizable)` fail for exactly that case.
        match storage.max_byte_length {
            Some(max) => {
                self.byte(1);
                self.leb(max as u64);
            }
            None => self.byte(0),
        }
        let bytes = storage.bytes.clone();
        drop(storage);
        self.bytes(&bytes);
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Reading
// ---------------------------------------------------------------------------

/// The state one `JS_ReadObject` call carries.
struct Reader<'a, 'h, 'i> {
    input: &'a [u8],
    position: usize,
    /// Two lifetimes because an `Interp` is itself borrowed from a heap: `'h` is the heap,
    /// `'i` the borrow of the interpreter.
    interp: &'i mut Interp<'h>,
    allow_reference: bool,
    /// Every object created so far, in creation order: `TAG_REFERENCE` indexes this.
    created: Vec<Gc<JsObject>>,
}

/// Read a value written by [`write`].
///
/// # Errors
///
/// Truncated input, an unknown tag, or a reference when references were not allowed. A
/// corrupt buffer must never be able to make the engine read past its end, which is why
/// every field is bounds-checked here rather than by the caller.
pub fn read<'h, 'i>(interp: &'i mut Interp<'h>, input: &[u8], flags: i32) -> Result<Value, String> {
    if input.is_empty() {
        return Err("invalid object format".to_string());
    }
    if input[0] != VERSION {
        return Err(format!("unsupported object version ({})", input[0]));
    }
    let mut reader = Reader {
        input,
        position: 1,
        interp,
        allow_reference: flags & READ_OBJ_REFERENCE != 0,
        created: Vec::new(),
    };
    reader.value()
}

impl<'a, 'h, 'i> Reader<'a, 'h, 'i> {
    fn byte(&mut self) -> Result<u8, String> {
        let byte = *self
            .input
            .get(self.position)
            .ok_or_else(|| "invalid object format".to_string())?;
        self.position += 1;
        Ok(byte)
    }

    fn bytes(&mut self, count: usize) -> Result<&'a [u8], String> {
        let end = self
            .position
            .checked_add(count)
            .ok_or_else(|| "invalid object format".to_string())?;
        let slice = self
            .input
            .get(self.position..end)
            .ok_or_else(|| "invalid object format".to_string())?;
        self.position = end;
        // SAFETY-free widening: the slice borrows from `self.input`, whose lifetime is
        // `'a`, and `self.position` is only a cursor.
        Ok(slice)
    }

    fn leb(&mut self) -> Result<u64, String> {
        let mut value = 0u64;
        let mut shift = 0;
        loop {
            let byte = self.byte()?;
            value |= u64::from(byte & 0x7f)
                .checked_shl(shift)
                .ok_or_else(|| "invalid object format".to_string())?;
            if byte & 0x80 == 0 {
                return Ok(value);
            }
            shift += 7;
            if shift > 63 {
                return Err("invalid object format".to_string());
            }
        }
    }

    fn leb_usize(&mut self) -> Result<usize, String> {
        let value = self.leb()?;
        usize::try_from(value).map_err(|_| "invalid object format".to_string())
    }

    fn value(&mut self) -> Result<Value, String> {
        let tag = self.byte()?;
        match tag {
            TAG_UNDEFINED => Ok(Value::Undefined),
            TAG_NULL => Ok(Value::Null),
            TAG_FALSE => Ok(Value::Bool(false)),
            TAG_TRUE => Ok(Value::Bool(true)),
            TAG_INT32 => {
                let bytes = self.bytes(4)?;
                Ok(Value::Int(i32::from_le_bytes([
                    bytes[0], bytes[1], bytes[2], bytes[3],
                ])))
            }
            TAG_FLOAT64 => {
                let bytes = self.bytes(8)?;
                Ok(Value::Float(f64::from_le_bytes([
                    bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
                ])))
            }
            TAG_STRING => {
                let length = self.leb_usize()?;
                let bytes = self.bytes(length)?;
                let text = engine::value::Wtf8::from_wtf8_bytes(bytes)
                    .ok_or_else(|| "invalid object format".to_string())?;
                Ok(Value::string_wtf8(self.interp.heap, text))
            }
            TAG_BIGINT => {
                let negative = self.byte()? != 0;
                let length = self.leb_usize()?;
                let bytes = self.bytes(length)?;
                let text =
                    std::str::from_utf8(bytes).map_err(|_| "invalid object format".to_string())?;
                let big = engine::bigint::BigInt::from_string(text)
                    .ok_or_else(|| "invalid object format".to_string())?;
                Ok(self
                    .interp
                    .bigint(if negative { big.negate() } else { big }))
            }
            TAG_ARRAY => {
                let length = self.leb_usize()?;
                // Created *empty and registered* before its elements are read. The index a
                // `TAG_REFERENCE` carries is the order of first sighting on the *write*
                // side, which registers an object before writing its body — so a reader
                // that registered after filling would number the objects differently and
                // every reference past the first would land on the wrong one. That is what
                // `bjson_test_reference` caught: the cycle resolved to the wrong objects.
                let array = JsObject::array(
                    self.interp.heap,
                    Some(self.interp.realm.array_proto.clone()),
                    0,
                );
                self.created.push(array.clone());
                for _ in 0..length {
                    let element = self.value()?;
                    array.array_push(self.interp.heap, element);
                }
                Ok(Value::Object(array))
            }
            TAG_OBJECT => {
                let count = self.leb_usize()?;
                // Created *before* its properties are read, so a property that refers back
                // to this object finds it: that is what makes a self-referential `o.x = o`
                // survive with reference mode on.
                let proto = self.interp.realm.object_proto.clone();
                let object = self.interp.new_object(Some(proto));
                self.created.push(object.clone());
                for _ in 0..count {
                    let length = self.leb_usize()?;
                    let key_bytes = self.bytes(length)?;
                    let key = engine::value::Wtf8::from_wtf8_bytes(key_bytes)
                        .ok_or_else(|| "invalid object format".to_string())?
                        .to_string_lossy()
                        .into_owned();
                    let value = self.value()?;
                    object.define(&key, engine::Property::with_attributes(value, true, true));
                }
                Ok(Value::Object(object))
            }
            TAG_ARRAY_BUFFER => {
                let byte_length = self.leb_usize()?;
                let resizable = self.byte()? != 0;
                // The order is the writer's: flag, then the ceiling, then the bytes.
                let max = if resizable {
                    Some(self.leb_usize()?)
                } else {
                    None
                };
                let proto = self
                    .interp
                    .realm
                    .array_buffer_proto
                    .clone()
                    .unwrap_or_else(|| self.interp.realm.object_proto.clone());
                let buffer = self.interp.new_object(Some(proto));
                // Registered before the bytes are read, for the same reason the array is:
                // the index is first-sighting order on both sides.
                self.created.push(buffer.clone());
                let bytes = self.bytes(byte_length)?.to_vec();
                let storage = match max {
                    Some(max) => BufferStorage::resizable(bytes, max),
                    None => BufferStorage::fixed(bytes),
                };
                buffer.set_array_buffer(std::rc::Rc::new(std::cell::RefCell::new(storage)));
                Ok(Value::Object(buffer))
            }
            TAG_TYPED_ARRAY => {
                let element = ELEMENT_TYPES
                    .get(self.byte()? as usize)
                    .map(|(element, _)| *element)
                    .ok_or_else(|| "invalid object format".to_string())?;
                let length = self.leb_usize()?;
                let offset = self.leb_usize()?;
                let proto = self
                    .interp
                    .realm
                    .typed_array_protos
                    .get(element as usize)
                    .cloned()
                    .or_else(|| self.interp.realm.typed_array_proto.clone())
                    .unwrap_or_else(|| self.interp.realm.object_proto.clone());
                // The view is registered as a plain object first and becomes a view once its
                // buffer has been read: the writer registered *it* before writing the
                // buffer, so a reference to the view may appear inside the buffer's own
                // subtree and has to resolve to this object.
                let view = self.interp.new_object(Some(proto));
                self.created.push(view.clone());
                let buffer = self.value()?;
                let Some(buffer) = buffer.as_object().cloned() else {
                    return Err("invalid object format".to_string());
                };
                view.set_typed_array(buffer, element, offset, length);
                Ok(Value::Object(view))
            }
            TAG_DATE => {
                let proto = self.interp.realm.date_proto.clone();
                let object = self.interp.new_object(Some(proto));
                self.created.push(object.clone());
                self.interp
                    .internal_set(&object, "_class", self.interp.string("Date"));
                let value = self.value()?.to_number();
                self.interp
                    .internal_set(&object, "_date_value", Value::Float(value));
                Ok(Value::Object(object))
            }
            TAG_OBJECT_VALUE => {
                // A wrapper is rebuilt by `object_from`, the same function `Object(x)` uses,
                // so `instanceof String` and `.valueOf()` work on the result without a
                // second implementation of boxing.
                // Created and registered *before* the primitive is read, because that is
                // the order the writer registered them in: it reserves the index when it
                // first sees the wrapper, then writes the primitive.
                let object = self.interp.new_object(None);
                self.created.push(object.clone());
                let primitive = self.value()?;
                self.interp
                    .fill_wrapper(&object, &primitive)
                    .map_err(|_| "invalid object format".to_string())?;
                Ok(Value::Object(object))
            }
            TAG_REFERENCE => {
                if !self.allow_reference {
                    return Err("invalid object format".to_string());
                }
                let index = self.leb_usize()?;
                let object = self
                    .created
                    .get(index)
                    .cloned()
                    .ok_or_else(|| "invalid object format".to_string())?;
                Ok(Value::Object(object))
            }
            other => Err(format!("unsupported tag ({other})")),
        }
    }
}

// ---------------------------------------------------------------------------
// The C API
// ---------------------------------------------------------------------------

/// `JS_WriteObject`: serialise `obj` into a block the caller frees with `js_free`.
///
/// # Safety
///
/// `psize` must be null or writable, and `obj` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_WriteObject(
    ctx: *mut JsContext,
    psize: *mut usize,
    obj: JsValue,
    flags: i32,
) -> *mut u8 {
    if !psize.is_null() {
        // SAFETY: the caller guarantees a writable pointer.
        unsafe { *psize = 0 };
    }
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return std::ptr::null_mut();
    };
    let Some(value) = (unsafe { runtime::argument(obj) }) else {
        runtime::throw_error(context, "TypeError", "not a value");
        return std::ptr::null_mut();
    };
    let written = context.with_current_interp(|interp| write(interp, &value, flags));
    let bytes = match written {
        Ok(bytes) => bytes,
        Err(message) => {
            // The reference puts almost every one of these in a `TypeError`, and the driver
            // checks `e instanceof TypeError` for the circular case.
            runtime::throw_error(context, "TypeError", &message);
            return std::ptr::null_mut();
        }
    };
    // The block comes from `js_malloc`, because the C side frees it with `js_free` and a
    // `Vec`'s pointer is not something that function understands.
    // SAFETY: `alloc_raw` has no preconditions beyond a size.
    let block = unsafe { crate::alloc::alloc_raw(bytes.len()) };
    if block.is_null() {
        runtime::throw_error(context, "InternalError", "out of memory");
        return std::ptr::null_mut();
    }
    // SAFETY: `block` is `bytes.len()` bytes of writable storage by `alloc_raw`'s contract.
    unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), block, bytes.len()) };
    if !psize.is_null() {
        // SAFETY: the caller guarantees a writable pointer.
        unsafe { *psize = bytes.len() };
    }
    block
}

/// `JS_ReadObject`: rebuild the value `buf` describes.
///
/// # Safety
///
/// `buf` must point at `buf_len` readable bytes that stay alive for the call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ReadObject(
    ctx: *mut JsContext,
    buf: *const u8,
    buf_len: usize,
    flags: i32,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    if buf.is_null() {
        runtime::throw_error(context, "TypeError", "invalid object format");
        return jsvalue::EXCEPTION;
    }
    // SAFETY: the caller guarantees `buf_len` readable bytes.
    let input = unsafe { std::slice::from_raw_parts(buf, buf_len) };
    let read = context.with_current_interp(|interp| read(interp, input, flags));
    match read {
        Ok(value) => jsvalue_of(value),
        Err(message) => runtime::throw_error(context, "TypeError", &message),
    }
}

/// `JS_GetArrayBuffer`: the bytes of an `ArrayBuffer`, for a C module to read.
///
/// The pointer is borrowed, not owned: it stays valid until the buffer is detached, resized
/// or collected, which is exactly the contract the reference's own getter has. A resizable
/// or fixed buffer answers the same way — a resize may move the bytes, and the caller is
/// expected to re-fetch after asking a script to run.
///
/// # Safety
///
/// `psize` must be null or writable, and `obj` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetArrayBuffer(
    ctx: *mut JsContext,
    psize: *mut usize,
    obj: JsValue,
) -> *mut u8 {
    if !psize.is_null() {
        // SAFETY: the caller guarantees a writable pointer.
        unsafe { *psize = 0 };
    }
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return std::ptr::null_mut();
    };
    let Some(value) = (unsafe { runtime::argument(obj) }) else {
        runtime::throw_error(context, "TypeError", "not a value");
        return std::ptr::null_mut();
    };
    let Some(storage) = value
        .as_object()
        .and_then(|object| object.array_buffer_storage())
    else {
        runtime::throw_error(context, "TypeError", "not an ArrayBuffer");
        return std::ptr::null_mut();
    };
    let storage = storage.borrow();
    if storage.detached {
        runtime::throw_error(context, "TypeError", "ArrayBuffer is detached");
        return std::ptr::null_mut();
    }
    if !psize.is_null() {
        // SAFETY: the caller guarantees a writable pointer.
        unsafe { *psize = storage.bytes.len() };
    }
    // Borrowed out of the storage's `Vec`: the reference hands out `abuf->data` the same
    // way, and the lifetime is the buffer's, not the borrow's.
    let bytes = storage.bytes.as_ptr() as *mut u8;
    drop(storage);
    bytes
}

/// `JS_NewArrayBufferCopy`: a new `ArrayBuffer` holding a copy of `len` bytes at `buf`.
///
/// # Safety
///
/// `buf` must point at `len` readable bytes, or be null with `len == 0`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewArrayBufferCopy(
    ctx: *mut JsContext,
    buf: *const u8,
    len: usize,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    if buf.is_null() && len != 0 {
        runtime::throw_error(context, "TypeError", "null pointer");
        return jsvalue::EXCEPTION;
    }
    let bytes = if len == 0 {
        Vec::new()
    } else {
        // SAFETY: the caller guarantees `len` readable bytes.
        unsafe { std::slice::from_raw_parts(buf, len) }.to_vec()
    };
    context.with_current_interp(|interp| {
        let proto = interp
            .realm
            .array_buffer_proto
            .clone()
            .unwrap_or_else(|| interp.realm.object_proto.clone());
        let buffer = interp.new_object(Some(proto));
        buffer.set_array_buffer(std::rc::Rc::new(std::cell::RefCell::new(
            BufferStorage::fixed(bytes),
        )));
        jsvalue_of(Value::Object(buffer))
    })
}