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
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
//! Conversions: the `JS_To*` family, and the constructors that make a `JSValue` out of a
//! Rust primitive.
//!
//! # The rule every function here follows
//!
//! A conversion that can run script — `ToNumber` calls `valueOf`, `ToString` calls
//! `toString`, `ToPrimitive` calls either — can throw, and the C API says so by answering
//! `-1` (a `c_int`) or [`jsvalue::EXCEPTION`] (a `JSValue`) with the reason left in the
//! context's pending slot. Nothing here answers "a best guess": `JS_ToInt32` on a `Symbol` is
//! `-1`, not `0`, which is what makes `new Point(Symbol(), 0)` a `TypeError` rather than a
//! point at the origin.
//!
//! # Saturating and wrapping are different functions
//!
//! `JS_ToInt32` *wraps* (`ToInt32`: modulo 2³²), `JS_ToInt32Sat` *clamps*, `JS_ToInt64`
//! refuses a value that does not fit and `JS_ToInt64Sat` clamps. The reference keeps them
//! apart and so does this file: a `Number.MAX_VALUE` argument is `-1` from one and
//! `2147483647` from the other, and the difference is observable from a script.

use core::ffi::{c_char, c_int, c_void};

use engine::Value;

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

/// Read a `JSValue` argument.
///
/// # Safety
///
/// `value` must be a `JSValue` this crate produced, or a primitive.
pub(crate) unsafe fn arg(value: JsValue) -> Option<Value> {
    // SAFETY: the caller's contract.
    unsafe { value_of(value) }
}

/// Run `f` with the interpreter, turning a throw into a pending exception and `-1`.
///
/// Every `JS_To*` below is this shape, which is why it is one function rather than a
/// repeated match: the failure path is the part that is easy to get subtly wrong (leaving
/// the reason unconverted, or answering `0`), and it lives here once.
fn with_number<T>(
    context: &JsContext,
    value: Value,
    f: impl FnOnce(&mut engine::Interp<'static>, &Value) -> engine::interp::JsResult<T>,
) -> Result<T, ()> {
    match context.with_current_interp(|interp| f(interp, &value)) {
        Ok(answer) => Ok(answer),
        Err(signal) => {
            let _ = runtime::result_value(context, Err(signal));
            Err(())
        }
    }
}

// ---------------------------------------------------------------------------
// Constructors
// ---------------------------------------------------------------------------

/// `JS_NewStringLen`: a string from `len1` bytes.
///
/// The bytes are WTF-8, not UTF-8, which is what lets a lone surrogate survive a round trip
/// through C: `JS_ToCStringLen2` emits the same three-byte form, and a host that stores a
/// QuickJS string as bytes gets its characters back.
///
/// # Safety
///
/// `str1` must point at `len1` readable bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewStringLen(
    ctx: *mut JsContext,
    str1: *const c_char,
    len1: usize,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    if str1.is_null() && len1 != 0 {
        return runtime::throw_error(context, "TypeError", "null string");
    }
    let bytes: &[u8] = if len1 == 0 {
        &[]
    } else {
        // SAFETY: the caller guarantees `len1` readable bytes.
        unsafe { core::slice::from_raw_parts(str1.cast::<u8>(), len1) }
    };
    // A string that is not valid WTF-8 cannot have come from this engine, and inventing one
    // would be worse than refusing: the reference would store the bytes and produce a string
    // whose `length` is a guess.
    let Some(text) = engine::value::Wtf8::from_wtf8_bytes(bytes) else {
        return runtime::throw_error(context, "TypeError", "invalid string bytes");
    };
    context.with_current_interp(|interp| jsvalue_of(interp.string_wtf8(text)))
}

/// `JS_NewAtomString`: a string, interning it on the way.
///
/// The reference's version keeps the atom's identity, which is observable only through the
/// atom API; here the string is what matters and the atom is interned for
/// `JS_ValueToAtom`'s benefit.
///
/// # Safety
///
/// `str1` must be null or a NUL-terminated string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewAtomString(ctx: *mut JsContext, str1: *const c_char) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    // SAFETY: the caller guarantees a NUL-terminated string.
    let text = unsafe { c_text(str1) };
    context.with_current_interp(|interp| jsvalue_of(interp.string(text)))
}

/// `JS_NewBigInt64`: a `BigInt` from an `i64`.
#[unsafe(no_mangle)]
///
/// # Safety
///
/// `ctx` must be a live context.
pub unsafe extern "C" fn JS_NewBigInt64(ctx: *mut JsContext, value: i64) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    context.with_current_interp(|interp| {
        jsvalue_of(interp.bigint(engine::bigint::BigInt::from_i64(value)))
    })
}

/// `JS_NewBigUint64`: a `BigInt` from a `u64`.
#[unsafe(no_mangle)]
///
/// # Safety
///
/// `ctx` must be a live context.
pub unsafe extern "C" fn JS_NewBigUint64(ctx: *mut JsContext, value: u64) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    context.with_current_interp(|interp| {
        jsvalue_of(interp.bigint(engine::bigint::BigInt::from_u64(value)))
    })
}

/// `JS_NewBigInt128`: a `BigInt` from a 128-bit two's-complement pair.
///
/// Built the way the reference builds it: the low and high halves are combined into limbs,
/// then the sign is applied. `low` is unsigned in the header, so a negative value arrives as
/// a high half whose top bit is set.
#[unsafe(no_mangle)]
///
/// # Safety
///
/// `ctx` must be a live context.
pub unsafe extern "C" fn JS_NewBigInt128(ctx: *mut JsContext, low: u64, high: u64) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    // Step through the decimal representation rather than a limb layout: `from_string` is the
    // one constructor this engine's `BigInt` exposes that is not width-limited, so the value
    // is assembled arithmetically.
    let magnitude = (u128::from(high) << 64) | u128::from(low);
    let negative = high >> 63 != 0;
    let unsigned = if negative {
        // Two's complement: negate in 128 bits, which is exact because the modulus is 2^128.
        (!magnitude).wrapping_add(1)
    } else {
        magnitude
    };
    let mut big = engine::bigint::BigInt::zero();
    let mut remaining = unsigned;
    let mut power = engine::bigint::BigInt::one();
    let ten = engine::bigint::BigInt::from_i64(10);
    while remaining != 0 {
        let digit = engine::bigint::BigInt::from_i64((remaining % 10) as i64);
        big = big.add(&digit.mul(&power));
        power = power.mul(&ten);
        remaining /= 10;
    }
    if negative {
        big = big.negate();
    }
    context.with_current_interp(|interp| jsvalue_of(interp.bigint(big)))
}

/// `JS_NewSymbol`: a symbol with `description`, optionally from the global registry.
///
/// # Safety
///
/// `description` must be null or a NUL-terminated string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewSymbol(
    ctx: *mut JsContext,
    description: *const c_char,
    is_global: Bool,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let text = if description.is_null() {
        None
    } else {
        // SAFETY: the caller guarantees a NUL-terminated string.
        Some(unsafe { c_text(description) })
    };
    context.with_current_interp(|interp| {
        let value = match text {
            // `Symbol.for(k)` consults the realm's registry, which is what makes two calls
            // with the same key the same symbol. The C API's `is_global` means exactly that.
            Some(key) if is_global != 0 => interp.symbol_for(&key),
            other => {
                engine::builtins::symbol::symbol_value(interp, engine::value::JsSymbol::new(other))
            }
        };
        jsvalue_of(value)
    })
}

/// `JS_NewObjectProto`: an ordinary object with `proto`.
///
/// # Safety
///
/// `proto` must be null or a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewObjectProto(ctx: *mut JsContext, proto: JsValue) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let proto = if proto.is_null() {
        None
    } else {
        match unsafe { arg(proto) } {
            Some(Value::Object(object)) => Some(object),
            Some(Value::Null) => None,
            Some(_) => return runtime::throw_error(context, "TypeError", "not an object"),
            None => return runtime::throw_error(context, "TypeError", "not a value"),
        }
    };
    context.with_current_interp(|interp| jsvalue_of(Value::Object(interp.new_object(proto))))
}

/// `JS_NewArray`: an empty array.
#[unsafe(no_mangle)]
///
/// # Safety
///
/// `ctx` must be a live context.
pub unsafe extern "C" fn JS_NewArray(ctx: *mut JsContext) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    context.with_current_interp(|interp| jsvalue_of(Value::Object(interp.new_array(Vec::new()))))
}

/// `JS_NewDate`: a `Date` for `epoch_ms`.
#[unsafe(no_mangle)]
///
/// # Safety
///
/// `ctx` must be a live context.
pub unsafe extern "C" fn JS_NewDate(ctx: *mut JsContext, epoch_ms: f64) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    context.with_current_interp(|interp| {
        let proto = interp.realm.date_proto.clone();
        let object = interp.new_object(Some(proto));
        interp.internal_set(&object, "_class", interp.string("Date"));
        interp.internal_set(&object, "_date_value", Value::Float(epoch_ms));
        jsvalue_of(Value::Object(object))
    })
}

/// `JS_ThisDateValue`: `this`'s `[[DateValue]]`, or `-1` when it is not a `Date`.
///
/// # Safety
///
/// `valp` must be null or writable, and `this_val` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ThisDateValue(
    ctx: *mut JsContext,
    valp: *mut f64,
    this_val: JsValue,
) -> c_int {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return -1;
    };
    let Some(Value::Object(object)) = (unsafe { arg(this_val) }) else {
        return runtime::throw_error(context, "TypeError", "not a Date").to_int_or_minus_one();
    };
    let value = context.with_current_interp(|interp| {
        // The class tag is what makes it a `Date`; a plain object with a `_date_value`-shaped
        // symbol is not one, which is the check `Date.prototype.getTime` makes too.
        if !interp
            .internal_get(&object, "_class")
            .is_some_and(|tag| tag.to_js_string() == "Date")
        {
            return None;
        }
        interp
            .internal_get(&object, "_date_value")
            .map(|v| v.to_number())
    });
    match value {
        Some(number) => {
            if !valp.is_null() {
                // SAFETY: the caller guarantees a writable pointer.
                unsafe { *valp = number };
            }
            0
        }
        None => runtime::throw_error(context, "TypeError", "not a Date").to_int_or_minus_one(),
    }
}

/// `JS_NewError`: a plain `Error`.
#[unsafe(no_mangle)]
///
/// # Safety
///
/// `ctx` must be a live context.
pub unsafe extern "C" fn JS_NewError(ctx: *mut JsContext) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    context.with_current_interp(|interp| jsvalue_of(interp.make_error("Error", "")))
}

// ---------------------------------------------------------------------------
// ToNumber and its siblings
// ---------------------------------------------------------------------------

/// `JS_ToInt32`: `ToInt32` (wrapping), or `-1` with a pending exception.
///
/// # Safety
///
/// `pres` must be null or writable, `val` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToInt32(ctx: *mut JsContext, pres: *mut i32, val: JsValue) -> c_int {
    to_int32_like(ctx, pres.cast(), val, engine::value::to_int32)
}

/// `JS_ToInt32Sat`: `ToInt32` clamped to the `int` range instead of wrapped.
///
/// The reference's `-2^31 ..= 2^31-1` clamp, which a `DataView` offset check relies on: a
/// wrapped offset would land inside the view.
///
/// # Safety
///
/// `pres` must be null or writable, `val` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToInt32Sat(
    ctx: *mut JsContext,
    pres: *mut c_int,
    val: JsValue,
) -> c_int {
    to_int32_like(ctx, pres, val, |number| {
        if number.is_nan() {
            return 0;
        }
        number.trunc().clamp(i32::MIN as f64, i32::MAX as f64) as i32
    })
}

/// The shared body of `JS_ToInt32` and `JS_ToInt32Sat`: convert, then store.
fn to_int32_like(
    ctx: *mut JsContext,
    pres: *mut c_int,
    val: JsValue,
    convert: impl Fn(f64) -> i32 + Copy,
) -> c_int {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return -1;
    };
    let Some(value) = (unsafe { arg(val) }) else {
        runtime::throw_error(context, "TypeError", "not a value");
        return -1;
    };
    match with_number(context, value, |interp, value| interp.to_js_number(value)) {
        Ok(number) => {
            if !pres.is_null() {
                // SAFETY: the caller guarantees a writable `int`; `c_int` is `i32`.
                unsafe { pres.write(convert(number)) };
            }
            0
        }
        Err(()) => -1,
    }
}

/// `JS_ToInt64`: `ToInt64`, refusing a value outside the `i64` range.
///
/// # Safety
///
/// `pres` must be null or writable, `val` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToInt64(ctx: *mut JsContext, pres: *mut i64, val: JsValue) -> c_int {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return -1;
    };
    let Some(value) = (unsafe { arg(val) }) else {
        runtime::throw_error(context, "TypeError", "not a value");
        return -1;
    };
    match with_number(context, value, |interp, value| interp.to_js_number(value)) {
        Ok(number) => {
            // `ToInt64` is "the value if it is an integer in range, otherwise fail" — it
            // truncates first (so `1.5` is `1`) and then refuses anything that does not fit.
            let truncated = if number.is_nan() || number.is_infinite() {
                return runtime::throw_error(context, "TypeError", "not an integer")
                    .to_int_or_minus_one();
            } else {
                number.trunc()
            };
            if truncated < i64::MIN as f64 || truncated >= -(i64::MIN as f64) {
                return runtime::throw_error(context, "TypeError", "not an integer")
                    .to_int_or_minus_one();
            }
            if !pres.is_null() {
                // SAFETY: the caller guarantees a writable pointer.
                unsafe { *pres = truncated as i64 };
            }
            0
        }
        Err(()) => -1,
    }
}

/// `JS_ToInt64Sat`: `ToInt64` clamped to the `i64` range.
///
/// # Safety
///
/// `pres` must be null or writable, `val` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToInt64Sat(ctx: *mut JsContext, pres: *mut i64, val: JsValue) -> c_int {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return -1;
    };
    let Some(value) = (unsafe { arg(val) }) else {
        runtime::throw_error(context, "TypeError", "not a value");
        return -1;
    };
    match with_number(context, value, |interp, value| interp.to_js_number(value)) {
        Ok(number) => {
            let clamped = if number.is_nan() {
                0
            } else {
                number.trunc().clamp(i64::MIN as f64, i64::MAX as f64) as i64
            };
            if !pres.is_null() {
                // SAFETY: the caller guarantees a writable pointer.
                unsafe { *pres = clamped };
            }
            0
        }
        Err(()) => -1,
    }
}

/// `JS_ToInt64Clamp`: `JS_ToInt64Sat` and then an affine shift, which is how the reference
/// reads a `Date`'s time value with a timezone correction.
///
/// # Safety
///
/// `pres` must be null or writable, `val` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToInt64Clamp(
    ctx: *mut JsContext,
    pres: *mut i64,
    val: JsValue,
    min: i64,
    max: i64,
    neg_offset: i64,
) -> c_int {
    let status = unsafe { JS_ToInt64Sat(ctx, pres, val) };
    if status != 0 {
        return status;
    }
    if pres.is_null() {
        return 0;
    }
    // SAFETY: `JS_ToInt64Sat` just wrote it, so the pointer is live.
    let value = unsafe { *pres };
    let adjusted = if value < 0 {
        value.saturating_add(neg_offset)
    } else {
        value
    };
    // A clamped result is the answer, not an error: the reference's callers use this to bound
    // a time value and expect the bound rather than a `RangeError`.
    unsafe { *pres = adjusted.clamp(min, max) };
    0
}

/// `JS_ToInt64Ext`: `ToInt64`, but a `BigInt` is accepted too.
///
/// # Safety
///
/// `pres` must be null or writable, `val` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToInt64Ext(ctx: *mut JsContext, pres: *mut i64, val: JsValue) -> c_int {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return -1;
    };
    let Some(value) = (unsafe { arg(val) }) else {
        runtime::throw_error(context, "TypeError", "not a value");
        return -1;
    };
    if let Value::BigInt(big) = &value {
        // `ToBigInt64`: modulo 2^64, which is what a `BigInt64Array` store does.
        let numeric = big.to_i64_wrapping();
        if !pres.is_null() {
            // SAFETY: the caller guarantees a writable pointer.
            unsafe { *pres = numeric };
        }
        return 0;
    }
    // SAFETY: the pointer and value contracts are `JS_ToInt64`'s.
    unsafe { JS_ToInt64(ctx, pres, val) }
}

/// `JS_ToBigInt64`: a `BigInt` (or a number) as an `i64`, modulo 2^64.
///
/// # Safety
///
/// `pres` must be null or writable, `val` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToBigInt64(ctx: *mut JsContext, pres: *mut i64, val: JsValue) -> c_int {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return -1;
    };
    let Some(value) = (unsafe { arg(val) }) else {
        runtime::throw_error(context, "TypeError", "not a value");
        return -1;
    };
    match value {
        Value::BigInt(big) => {
            if !pres.is_null() {
                // SAFETY: the caller guarantees a writable pointer.
                unsafe { *pres = big.to_i64_wrapping() };
            }
            0
        }
        // A Number is a `TypeError`, exactly as `ToBigInt` says: `1n + 1` throws.
        _ => runtime::throw_error(context, "TypeError", "cannot convert to BigInt")
            .to_int_or_minus_one(),
    }
}

/// `JS_ToBigInt128`: a `BigInt` as a 128-bit two's-complement pair.
///
/// # Safety
///
/// `plow`/`phigh` must be null or writable, `val` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToBigInt128(
    ctx: *mut JsContext,
    plow: *mut u64,
    phigh: *mut u64,
    val: JsValue,
) -> c_int {
    // SAFETY: the caller's contract is `to_bigint128`'s.
    unsafe { to_bigint128(ctx, plow, phigh, val, false) }
}

/// `JS_ToBigInt128Sat`: [`JS_ToBigInt128`] clamped to the 128-bit range.
///
/// # Safety
///
/// As [`JS_ToBigInt128`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToBigInt128Sat(
    ctx: *mut JsContext,
    plow: *mut u64,
    phigh: *mut u64,
    val: JsValue,
) -> c_int {
    // SAFETY: as above.
    unsafe { to_bigint128(ctx, plow, phigh, val, true) }
}

/// The shared body of the two 128-bit conversions.
///
/// The value is read through its decimal text, which is the only width-free view this
/// engine's `BigInt` offers. That is slower than reading limbs, and it is exact — which
/// matters more for an API whose whole job is to be the same number the script has.
unsafe fn to_bigint128(
    ctx: *mut JsContext,
    plow: *mut u64,
    phigh: *mut u64,
    val: JsValue,
    saturate: bool,
) -> c_int {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return -1;
    };
    let Some(value) = (unsafe { arg(val) }) else {
        runtime::throw_error(context, "TypeError", "not a value");
        return -1;
    };
    let Value::BigInt(big) = &value else {
        return runtime::throw_error(context, "TypeError", "cannot convert to BigInt")
            .to_int_or_minus_one();
    };
    let negative = big.is_negative();
    let text = big.abs().to_decimal_string();
    // Accumulate in `i128` so an out-of-range value is visible rather than wrapped: the whole
    // difference between `JS_ToBigInt128` and its `Sat` sibling is what happens here.
    let mut magnitude: Option<i128> = Some(0);
    for byte in text.bytes() {
        if !byte.is_ascii_digit() {
            return runtime::throw_error(context, "TypeError", "not an integer")
                .to_int_or_minus_one();
        }
        magnitude = magnitude.and_then(|current| {
            current
                .checked_mul(10)?
                .checked_add(i128::from(byte - b'0'))
        });
    }
    let Some(magnitude) = magnitude else {
        // Too wide for 128 bits. Saturating answers the extreme value, which is what a
        // `DataView` bounds check wants; the exact one refuses.
        if !saturate {
            return runtime::throw_error(context, "TypeError", "BigInt out of range")
                .to_int_or_minus_one();
        }
        let (low, high) = if negative {
            (0u64, u64::MAX)
        } else {
            (u64::MAX, i64::MAX as u64)
        };
        if !plow.is_null() {
            unsafe { *plow = low };
        }
        if !phigh.is_null() {
            unsafe { *phigh = high };
        }
        return 0;
    };
    let bits = if negative {
        // Two's complement in 128 bits, sign-extended into a `u128` by the cast.
        magnitude.wrapping_neg() as u128
    } else {
        magnitude as u128
    };
    // No range check is needed here: `magnitude` is already an `i128`, and the accumulation
    // above refused anything that would not fit. The `saturate` flag only decides what an
    // *overflow* answers, which is the branch above.
    let _ = saturate;
    if !plow.is_null() {
        // SAFETY: the caller guarantees a writable pointer.
        unsafe { *plow = bits as u64 };
    }
    if !phigh.is_null() {
        // SAFETY: as above.
        unsafe { *phigh = (bits >> 64) as u64 };
    }
    0
}

/// `JS_ToObject`: `ToObject`, boxing a primitive and refusing `null`/`undefined`.
///
/// # Safety
///
/// `val` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToObject(ctx: *mut JsContext, val: JsValue) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(value) = (unsafe { arg(val) }) else {
        return runtime::throw_error(context, "TypeError", "not a value");
    };
    match context.with_current_interp(|interp| interp.object_from(&value)) {
        Ok(object) => context.with_current_interp(|interp| {
            let _ = interp;
            jsvalue_of(Value::Object(object))
        }),
        Err(signal) => runtime::result_value(context, Err(signal)),
    }
}

/// `JS_ToPrimitive`: `ToPrimitive` with a `hint` (`0` default, `1` number, `2` string).
///
/// # Safety
///
/// `val` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToPrimitive(ctx: *mut JsContext, val: JsValue, hint: c_int) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(value) = (unsafe { arg(val) }) else {
        return runtime::throw_error(context, "TypeError", "not a value");
    };
    let hint = match hint {
        // `JS_HINT_NUMBER` / `JS_HINT_STRING` / `JS_HINT_DEFAULT`, in the header's order.
        0 => engine::interp::Hint::Number,
        1 => engine::interp::Hint::String,
        _ => engine::interp::Hint::Default,
    };
    let result = context.with_current_interp(|interp| interp.to_primitive(value, hint));
    runtime::result_value(context, result)
}

/// `JS_ToString`: `ToString`, which calls `toString`/`valueOf` and so can throw.
///
/// # Safety
///
/// `val` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToString(ctx: *mut JsContext, val: JsValue) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(value) = (unsafe { arg(val) }) else {
        return runtime::throw_error(context, "TypeError", "not a value");
    };
    let result = context.with_current_interp(|interp| {
        let text = interp.checked_to_string(&value)?;
        Ok(interp.string(text))
    });
    runtime::result_value(context, result)
}

/// `JS_ToPropertyKey`: `ToPropertyKey`, which keeps a symbol as a symbol.
///
/// # Safety
///
/// `val` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToPropertyKey(ctx: *mut JsContext, val: JsValue) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(value) = (unsafe { arg(val) }) else {
        return runtime::throw_error(context, "TypeError", "not a value");
    };
    let converted = context
        .with_current_interp(|interp| interp.to_primitive(value, engine::interp::Hint::String));
    match converted {
        Ok(Value::Symbol(_)) => {
            let value = converted.expect("just matched");
            context.with_current_interp(|interp| {
                let _ = interp;
                jsvalue_of(value)
            })
        }
        Ok(value) => {
            let result = context.with_current_interp(|interp| {
                let text = interp.checked_to_string(&value)?;
                Ok(interp.string(text))
            });
            runtime::result_value(context, result)
        }
        Err(signal) => runtime::result_value(context, Err(signal)),
    }
}

/// `JS_ToUTF32String`: the code points of a string, as a `js_malloc` block.
///
/// # Safety
///
/// `pbuf` must be null or writable, `val` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToUTF32String(
    ctx: *mut JsContext,
    pbuf: *mut *mut u32,
    val: JsValue,
) -> c_int {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return -1;
    };
    let Some(value) = (unsafe { arg(val) }) else {
        runtime::throw_error(context, "TypeError", "not a value");
        return -1;
    };
    let text = match context.with_current_interp(|interp| interp.checked_to_wtf8(&value)) {
        Ok(text) => text,
        Err(signal) => {
            let _ = runtime::result_value(context, Err(signal));
            return -1;
        }
    };
    let points: Vec<u32> = text.code_point_values();
    if pbuf.is_null() {
        return 0;
    }
    // The block is `js_malloc`'s because the caller frees it with `js_free`, and a `Vec`'s
    // pointer is not something that function understands. One extra element holds the NUL
    // terminator the reference writes, which is not part of the returned count.
    // SAFETY: `alloc_raw` has no preconditions beyond a size.
    let block = unsafe { crate::alloc::alloc_raw((points.len() + 1) * 4) };
    if block.is_null() {
        runtime::throw_error(context, "InternalError", "out of memory");
        return -1;
    }
    // SAFETY: the block is `(len + 1) * 4` writable bytes, and `points` is `len` elements.
    unsafe {
        let out = block.cast::<u32>();
        for (index, point) in points.iter().enumerate() {
            out.add(index).write(*point);
        }
        out.add(points.len()).write(0);
        pbuf.write(out);
    }
    0
}

/// `JS_ToCStringNZ`: [`crate::objects::JS_ToCStringLen2`] without the length.
///
/// # Safety
///
/// `val1` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToCStringNZ(ctx: *mut JsContext, val1: JsValue) -> *const c_char {
    // SAFETY: the caller's contract is `JS_ToCStringLen2`'s with a null length pointer.
    unsafe { crate::objects::JS_ToCStringLen2(ctx, std::ptr::null_mut(), val1, 0) }
}

/// The text of a NUL-terminated string argument, or the empty string for null.
///
/// # Safety
///
/// `pointer` must be null or NUL-terminated.
pub(crate) unsafe fn c_text(pointer: *const c_char) -> String {
    if pointer.is_null() {
        return String::new();
    }
    // SAFETY: the caller guarantees a NUL-terminated string.
    unsafe { core::ffi::CStr::from_ptr(pointer) }
        .to_string_lossy()
        .into_owned()
}

/// A `JSValue`'s payload as `c_int`, for the "`-1` on failure" convention.
trait IntOrMinusOne {
    /// `-1` when the value is not an integer, which every failure path here is.
    fn to_int_or_minus_one(self) -> c_int;
}

impl IntOrMinusOne for JsValue {
    fn to_int_or_minus_one(self) -> c_int {
        // The failure paths above all answer `EXCEPTION`, whose payload is not a number; the
        // convention is that the caller only ever sees `-1`.
        let _ = self;
        -1
    }
}

/// `JS_MarkValue`: stop the collector from reclaiming `val`.
///
/// The reference's mark phase is explicit; this engine's is reference-counting plus a cycle
/// collector, so a live `JSValue` box already keeps its payload alive and there is nothing to
/// mark. The function exists because a `JSClassDef::gc_mark` implementation calls it, and a
/// missing symbol would stop such a module from loading at all.
///
/// # Safety
///
/// The arguments are ignored; the reference's contract is on `val` only.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_MarkValue(
    _rt: *mut runtime::JsRuntime,
    _val: JsValue,
    _mark_func: *mut c_void,
) {
}