quickjs-capi 0.13.1

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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
//! Objects, properties and C functions: the `JS_NewObject` family.
//!
//! Everything here is a translation, not an implementation: the engine already has objects,
//! property tables, accessors and host functions (`docs/m15-plan.md` ยง5, S1). What this
//! module adds is the C API's *shapes* โ€” a `JSCFunctionListEntry` table, a `JS_CFUNC_*`
//! calling convention, `JS_SetConstructor`'s two reciprocal properties.
//!
//! # The one real decision: who owns the returned value
//!
//! A function that answers `JSValue` answers a *new reference*: the caller owns it and is
//! responsible for `JS_FreeValue`. That is why `JS_NewObject` boxes its answer with a count
//! of one and why a C function's return value is `release`d by the trampoline once the
//! engine value has been cloned out. `argv` is the opposite โ€” borrowed, never freed by us โ€”
//! which is the asymmetry [`crate::convert`] is built around.

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

use engine::interp::JsResult;
use engine::object::Property;
use engine::{ClassId, Value};

use crate::cdefs::{self, CFunctionEnum, JSCFunctionListEntry, JSCFunctionType, JSClassDef, prop};
use crate::jsvalue::{self, JsValue};
use crate::runtime::{self, JsContext, JsRuntime};
use crate::value_helpers::jsvalue_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 { runtime::argument(value) }
}

// ---------------------------------------------------------------------------
// Objects
// ---------------------------------------------------------------------------

/// `JS_NewObject`: an ordinary object inheriting `Object.prototype`.
///
/// # Safety
///
/// `ctx` must be a live context.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewObject(ctx: *mut JsContext) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    context.with_current_interp(|interp| {
        let proto = interp.realm.object_proto.clone();
        jsvalue_of(Value::Object(interp.new_object(Some(proto))))
    })
}

/// The global object (`JS_GetGlobalObject`).
///
/// # Safety
///
/// `ctx` must be a live context.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetGlobalObject(ctx: *mut JsContext) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    context.with_current_interp(|interp| {
        let global = interp.realm.global.clone();
        jsvalue_of(Value::Object(global))
    })
}

/// `JS_NewObjectProtoClass`: an instance of `class_id` whose prototype is `proto`.
///
/// # Safety
///
/// `ctx` must be a live context and `proto` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewObjectProtoClass(
    ctx: *mut JsContext,
    proto: JsValue,
    class_id: cdefs::ClassId,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(proto) = (unsafe { arg(proto) }) else {
        return runtime::throw_error(context, "TypeError", "prototype is not an object");
    };
    let Some(prototype) = proto.as_object().cloned() else {
        return runtime::throw_error(context, "TypeError", "prototype is not an object");
    };
    context.with_current_interp(|interp| {
        match interp.new_host_object(Some(prototype), ClassId::from_raw(class_id)) {
            Some(object) => jsvalue_of(Value::Object(object)),
            // The C API answers `NULL` here, which the caller reports as an exception; the
            // reference spells it as a `TypeError` from `JS_ThrowTypeErrorInvalidClass`.
            None => runtime::throw_error(
                context,
                "TypeError",
                &format!("invalid class id {class_id}"),
            ),
        }
    })
}

/// `JS_NewObjectClass`: an instance of `class_id` with the prototype installed for it.
///
/// # Safety
///
/// `ctx` must be a live context.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewObjectClass(ctx: *mut JsContext, class_id: c_int) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    context.with_current_interp(|interp| {
        match interp.new_host_object(None, ClassId::from_raw(class_id as u32)) {
            Some(object) => jsvalue_of(Value::Object(object)),
            None => runtime::throw_error(
                context,
                "TypeError",
                &format!("invalid class id {class_id}"),
            ),
        }
    })
}

/// `JS_GetPropertyStr`: read a property by name, answering a new reference.
///
/// # Safety
///
/// `ctx` must be a live context, `this_obj` a live `JSValue`, and `name` a NUL-terminated
/// string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetPropertyStr(
    ctx: *mut JsContext,
    this_obj: JsValue,
    name: *const c_char,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(target) = (unsafe { arg(this_obj) }) else {
        return runtime::throw_error(context, "TypeError", "not an object");
    };
    // SAFETY: the caller guarantees a NUL-terminated string.
    let name = unsafe { std::ffi::CStr::from_ptr(name) }.to_string_lossy();
    // `read_field` rather than `get_property`: a `JSValue` may be a string primitive, whose
    // `length` and indices the engine answers without boxing it.
    let result = context.with_current_interp(|interp| interp.read_field(&target, &name));
    runtime::result_value(context, result)
}

/// `JS_SetPropertyStr`: write a property by name, answering `-1` on failure.
///
/// # Safety
///
/// `ctx` must be a live context, `this_obj` a live `JSValue`, `name` a NUL-terminated
/// string, and `value` a live `JSValue` whose reference this call consumes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetPropertyStr(
    ctx: *mut JsContext,
    this_obj: JsValue,
    name: *const c_char,
    value: JsValue,
) -> c_int {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return -1;
    };
    let Some(target) = (unsafe { arg(this_obj) }) else {
        runtime::throw_error(context, "TypeError", "not an object");
        return -1;
    };
    let Some(new_value) = (unsafe { arg(value) }) else {
        runtime::throw_error(context, "TypeError", "not a value");
        return -1;
    };
    // SAFETY: the caller guarantees a NUL-terminated string.
    let name = unsafe { std::ffi::CStr::from_ptr(name) }.to_string_lossy();
    let result = context.with_current_interp(|interp| match target.as_object() {
        Some(object) => interp.set_property(object, &name, new_value),
        None => Err(engine::Signal::Throw(interp.make_error(
            "TypeError",
            &format!("cannot set property '{name}' of a primitive"),
        ))),
    });
    // The reference takes `JSValue val` here, not `JSValueConst`: the write consumes the
    // caller's reference.
    // SAFETY: the caller's reference is ours to drop.
    unsafe { runtime::release(value) };
    match result {
        Ok(()) => 0,
        Err(signal) => {
            let _ = runtime::result_value(context, Err(signal));
            -1
        }
    }
}

/// `JS_ToBool`: the truthiness of a value, or `-1` for an exception.
///
/// # Safety
///
/// `val` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToBool(ctx: *mut JsContext, val: JsValue) -> c_int {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return -1;
    };
    match unsafe { arg(val) } {
        Some(value) => c_int::from(value.to_boolean()),
        None => {
            runtime::throw_error(context, "TypeError", "not a value");
            -1
        }
    }
}

/// `JS_ToIndex`: a valid array index, or a `RangeError`.
///
/// # Safety
///
/// `plen` must be writable and `val` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToIndex(ctx: *mut JsContext, plen: *mut u64, 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 number = match context.with_current_interp(|interp| interp.to_js_number(&value)) {
        Ok(number) => number,
        Err(signal) => {
            let _ = runtime::result_value(context, Err(signal));
            return -1;
        }
    };
    // `ToIndex`: an integer in `0 ..= 2^53 - 1`, and `-0` is `0`.
    let index = number.trunc();
    if number.is_nan() || index != number || index < 0.0 || index > 9_007_199_254_740_991.0 {
        runtime::throw_error(context, "RangeError", "invalid array index");
        return -1;
    }
    if !plen.is_null() {
        // SAFETY: the caller guarantees the pointer is writable.
        unsafe { *plen = index as u64 };
    }
    0
}

// ---------------------------------------------------------------------------
// C functions
// ---------------------------------------------------------------------------

/// The shape of every C function the API installs, as a raw pointer.
///
/// One opaque type for fourteen signatures: which one applies is decided by the
/// [`CFunctionEnum`] stored beside it, exactly as in the reference's `JSCFunctionType`
/// union.
pub type RawFunction = *const core::ffi::c_void;

/// `JS_NewCFunction2`: wrap a C function pointer as a JavaScript function.
///
/// # Safety
///
/// `ctx` must be a live context, `func` must be a function pointer of the signature
/// `cproto` names, and `name` a NUL-terminated string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewCFunction2(
    ctx: *mut JsContext,
    func: RawFunction,
    name: *const c_char,
    length: c_int,
    cproto: c_int,
    magic: c_int,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    // SAFETY: the caller guarantees a NUL-terminated string.
    let name = unsafe { std::ffi::CStr::from_ptr(name) }
        .to_string_lossy()
        .into_owned();
    let Some(kind) = u8::try_from(cproto).ok().and_then(CFunctionEnum::from_raw) else {
        return runtime::throw_error(
            context,
            "TypeError",
            &format!("unsupported JSCFunctionEnum {cproto}"),
        );
    };
    context.with_current_interp(|interp| {
        let function = make_c_function(interp, func, kind, name, length, magic);
        jsvalue_of(Value::Object(function))
    })
}

/// Build the engine function object for a C function pointer.
pub(crate) fn make_c_function(
    interp: &mut engine::Interp<'static>,
    func: RawFunction,
    kind: CFunctionEnum,
    name: String,
    length: c_int,
    magic: c_int,
) -> engine::Gc<engine::JsObject> {
    let arity = u32::try_from(length).unwrap_or(0);
    let body: engine::object::HostFn = Box::new(move |interp, this, args| {
        let context = current_context_or_null();
        call_c_function(context, interp, func, kind, magic, this, args)
    });
    // A constructor gets `own_instance`: `new` hands it `undefined` for `this` and it builds
    // its own instance from `new.target`, which is the shape `JS_CFUNC_constructor`
    // documents and the reason `point.c` reads `new_target` at all.
    if kind.is_constructor() {
        interp.new_host_ctor(name, arity, body)
    } else {
        interp.new_host_function(name, arity, body)
    }
}

/// The context a function object belongs to.
///
/// A C function is always *called* through a `JSContext`, so reading the current one at call
/// time would be enough โ€” except that `make_c_function`'s closure must capture something
/// stable, and the value being built right now is being built *for* this context.
fn current_context_or_null() -> *mut JsContext {
    runtime::current_context()
        .map(|context| context as *const JsContext as *mut JsContext)
        .unwrap_or(std::ptr::null_mut())
}

/// Invoke a C function pointer with the convention `kind` names.
///
/// Arguments are handed over as an array of `JSValue`s, borrowed: the C function must not
/// free them, which is what the `JSValueConst` in its signature means. The return value is
/// owned by us, so it is decoded and then released.
fn call_c_function<'i>(
    ctx: *mut JsContext,
    interp: &mut engine::Interp<'i>,
    func: RawFunction,
    kind: CFunctionEnum,
    magic: c_int,
    this: Value,
    args: &[Value],
) -> JsResult<Value> {
    // `this` for a constructor is `new.target`, which the engine parked for exactly this
    // purpose; for everything else it is the receiver.
    let this = if kind.is_constructor() {
        interp.current_new_target()
    } else {
        this
    };
    let this_value = crate::convert::encode(&this);
    let arguments: Vec<JsValue> = args.iter().map(crate::convert::encode).collect();
    let pointer = arguments.as_ptr();
    let argc = c_int::try_from(arguments.len()).unwrap_or(c_int::MAX);
    // The `JSContext *` a C function receives is the current one; if there is none this is
    // a function that outlived its context, which the C API cannot express either.
    let context = current_context_or_null();
    let _ = ctx;

    // SAFETY: `func` is a pointer of the signature `kind` names โ€” the caller of
    // `JS_NewCFunction2` promised that. Every arm below is one of the reference's
    // `JSCFunctionType` variants spelled out.
    let answer = unsafe {
        match kind {
            CFunctionEnum::Generic => {
                let f: unsafe extern "C" fn(
                    *mut JsContext,
                    JsValue,
                    c_int,
                    *const JsValue,
                ) -> JsValue = core::mem::transmute(func);
                f(context, this_value, argc, pointer)
            }
            CFunctionEnum::GenericMagic => {
                let f: unsafe extern "C" fn(
                    *mut JsContext,
                    JsValue,
                    c_int,
                    *const JsValue,
                    c_int,
                ) -> JsValue = core::mem::transmute(func);
                f(context, this_value, argc, pointer, magic)
            }
            CFunctionEnum::Constructor | CFunctionEnum::ConstructorOrFunc => {
                let f: unsafe extern "C" fn(
                    *mut JsContext,
                    JsValue,
                    c_int,
                    *const JsValue,
                ) -> JsValue = core::mem::transmute(func);
                f(context, this_value, argc, pointer)
            }
            CFunctionEnum::ConstructorMagic | CFunctionEnum::ConstructorOrFuncMagic => {
                let f: unsafe extern "C" fn(
                    *mut JsContext,
                    JsValue,
                    c_int,
                    *const JsValue,
                    c_int,
                ) -> JsValue = core::mem::transmute(func);
                f(context, this_value, argc, pointer, magic)
            }
            CFunctionEnum::ConstructorOrFuncFlags => {
                // `(ctx, func_obj, this_val, argc, argv, flags)`: the flag says whether this
                // is a constructor call, which is the only difference from the plain form.
                let flags = if this_value.is_undefined() {
                    0
                } else {
                    cdefs::JS_CALL_FLAG_CONSTRUCTOR
                };
                let f: unsafe extern "C" fn(
                    *mut JsContext,
                    JsValue,
                    JsValue,
                    c_int,
                    *const JsValue,
                    c_int,
                ) -> JsValue = core::mem::transmute(func);
                f(context, this_value, this_value, argc, pointer, flags)
            }
            CFunctionEnum::Getter => {
                let f: unsafe extern "C" fn(*mut JsContext, JsValue) -> JsValue =
                    core::mem::transmute(func);
                f(context, this_value)
            }
            CFunctionEnum::GetterMagic => {
                let f: unsafe extern "C" fn(*mut JsContext, JsValue, c_int) -> JsValue =
                    core::mem::transmute(func);
                f(context, this_value, magic)
            }
            CFunctionEnum::Setter => {
                let f: unsafe extern "C" fn(*mut JsContext, JsValue, JsValue) -> JsValue =
                    core::mem::transmute(func);
                let value = args.first().cloned().unwrap_or(Value::Undefined);
                let encoded = crate::convert::encode(&value);
                let answer = f(context, this_value, encoded);
                runtime::release(encoded);
                answer
            }
            CFunctionEnum::SetterMagic => {
                let f: unsafe extern "C" fn(*mut JsContext, JsValue, JsValue, c_int) -> JsValue =
                    core::mem::transmute(func);
                let value = args.first().cloned().unwrap_or(Value::Undefined);
                let encoded = crate::convert::encode(&value);
                let answer = f(context, this_value, encoded, magic);
                runtime::release(encoded);
                answer
            }
            // `f_f`/`f_f_f`/`iterator_next`: not reachable from a `JSCFunctionListEntry`
            // this layer installs, and `JS_NewCFunction2` is only ever called with a
            // convention it can honour.
            CFunctionEnum::FF | CFunctionEnum::FFF | CFunctionEnum::IteratorNext => {
                return Err(engine::Signal::Throw(
                    interp.make_error("TypeError", "unsupported C function convention"),
                ));
            }
        }
    };

    // Every `JSValue` that went out is ours to free: the arguments and `this` were encoded
    // here (the C side treats them as borrowed), and the answer is a new reference.
    for value in arguments {
        // SAFETY: each was produced by `encode` in this function and is not used again.
        unsafe { runtime::release(value) };
    }
    let answer_is_this = answer.has_ref_count() && answer.payload() == this_value.payload();
    let result = finish_call(context, interp, answer);
    // `this` is released *after* the answer is decoded, and skipped when the C function
    // returned `this` itself: in that case the answer's own reference is the same box, and
    // `finish_call` already dropped it. Releasing it twice was the first version's bug โ€” it
    // showed up as a host object that never ran its finalizer, because one box kept a `Gc`
    // alive for the life of the process.
    if !answer_is_this {
        // SAFETY: `this_value` was produced by `encode` here and is not used again.
        unsafe { runtime::release(this_value) };
    }
    result
}

/// Turn what a C function answered into an engine result.
///
/// Three cases:
///
/// * a real value โ€” decoded, and its C-side reference released;
/// * `JS_EXCEPTION` with a pending exception โ€” that becomes `Signal::Throw`, so the
///   `catch` that wraps the call sees the very object C raised;
/// * `JS_EXCEPTION` with nothing pending โ€” a bug in the C function, reported as an
///   `InternalError` rather than a silent `undefined`.
fn finish_call(
    context: *mut JsContext,
    interp: &mut engine::Interp<'_>,
    answer: JsValue,
) -> JsResult<Value> {
    if answer.is_exception() {
        // SAFETY: the pointer came from `current_context_or_null`, which answers the
        // context currently running this callback.
        let pending = unsafe { context.as_ref() }.and_then(|context| context.take_pending());
        return Err(match pending {
            Some(value) => engine::Signal::Throw(value),
            None => engine::Signal::Throw(interp.make_error(
                "InternalError",
                "C function returned JS_EXCEPTION without raising",
            )),
        });
    }
    let decoded = if answer.is_undefined() {
        Some(Value::Undefined)
    } else {
        // SAFETY: the answer is a `JSValue` this layer produced (or a primitive).
        unsafe { runtime::argument(answer) }
    };
    // SAFETY: the answer is an owned reference, and it is no longer used.
    unsafe { runtime::release(answer) };
    Ok(decoded.unwrap_or(Value::Undefined))
}

/// `JS_SetConstructor`: make `func_obj.prototype` and `proto.constructor` point at each
/// other.
///
/// # Safety
///
/// Both values must be live and both must be objects.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetConstructor(
    ctx: *mut JsContext,
    func_obj: JsValue,
    proto: JsValue,
) -> c_int {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return -1;
    };
    let (Some(function), Some(prototype)) = (unsafe { arg(func_obj) }, unsafe { arg(proto) })
    else {
        runtime::throw_error(context, "TypeError", "not an object");
        return -1;
    };
    let (Some(function), Some(prototype)) = (function.as_object(), prototype.as_object()) else {
        runtime::throw_error(context, "TypeError", "not an object");
        return -1;
    };
    // `prototype` is `{writable: true, enumerable: false, configurable: false}` and
    // `constructor` is `{writable: true, enumerable: false, configurable: true}` โ€” the two
    // shapes `JS_SetConstructor2` spells with `0` and `JS_PROP_WRITABLE|JS_PROP_CONFIGURABLE`.
    function.define(
        "prototype",
        Property {
            value: Some(Value::Object(prototype.clone())),
            writable: true,
            enumerable: false,
            configurable: false,
            ..Property::default()
        },
    );
    prototype.define(
        "constructor",
        Property::with_attributes(Value::Object(function.clone()), true, false),
    );
    0
}

/// `JS_SetPropertyFunctionList`: install a static table of definitions.
///
/// The table is the module's `.data`, read entry by entry. Every `JS_DEF_*` the reference
/// documents is handled except `JS_DEF_ALIAS`/`JS_DEF_PROP_ATOM`, which nothing in the
/// acceptance surface uses and which need an atom table this layer does not have.
///
/// # Safety
///
/// `ctx` must be a live context, `obj` a live object `JSValue`, and `tab` must point at
/// `len` valid entries.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetPropertyFunctionList(
    ctx: *mut JsContext,
    obj: JsValue,
    tab: *const JSCFunctionListEntry,
    len: c_int,
) -> c_int {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return -1;
    };
    let Some(object) = (unsafe { arg(obj) }).and_then(|value| value.as_object().cloned()) else {
        runtime::throw_error(context, "TypeError", "not an object");
        return -1;
    };
    if tab.is_null() || len <= 0 {
        return 0;
    }
    context.with_current_interp(|interp| {
        for index in 0..len as usize {
            // SAFETY: the caller guarantees `tab` holds `len` entries.
            let entry = unsafe { &*tab.add(index) };
            if let Err(signal) = install_entry(interp, &object, entry) {
                let _ = runtime::result_value(context, Err(signal));
                return -1;
            }
        }
        0
    })
}

/// Install one row of a `JSCFunctionListEntry` table.
fn install_entry(
    interp: &mut engine::Interp<'static>,
    object: &engine::Gc<engine::JsObject>,
    entry: &JSCFunctionListEntry,
) -> JsResult<()> {
    if entry.name.is_null() {
        return Ok(());
    }
    // SAFETY: an entry's `name` is a NUL-terminated string in the module's static data.
    let name = unsafe { std::ffi::CStr::from_ptr(entry.name) }
        .to_string_lossy()
        .into_owned();
    // The C API's flags are a superset of the property attributes: the low three bits are
    // writable/enumerable/configurable and the rest say "this descriptor field is present",
    // which a *definition* always implies.
    let writable = entry.prop_flags & prop::WRITABLE != 0;
    let enumerable = entry.prop_flags & prop::ENUMERABLE != 0;
    let configurable = entry.prop_flags & prop::CONFIGURABLE != 0;

    let data_property = |value: Value| Property {
        value: Some(value),
        writable,
        enumerable,
        configurable,
        ..Property::default()
    };
    let accessor_property = |getter: Option<Value>, setter: Option<Value>| Property {
        getter,
        setter,
        writable: false,
        enumerable,
        configurable,
        ..Property::default()
    };

    match entry.def_type {
        cdefs::JS_DEF_CFUNC => {
            // SAFETY: `def_type` selects this arm of the union.
            let func = unsafe { &entry.u.func };
            let Some(kind) = CFunctionEnum::from_raw(func.cproto) else {
                return Err(engine::Signal::Throw(interp.make_error(
                    "TypeError",
                    &format!("unsupported JSCFunctionEnum {}", func.cproto),
                )));
            };
            // SAFETY: the pointer is the variant of `JSCFunctionType` that `cproto` names.
            let pointer = func.cfunc.as_ptr();
            // `make_c_function` decides betwen a plain function and a constructor, which is
            // what makes `JS_CFUNC_constructor` in a list `new`-able.
            let value = make_c_function(
                interp,
                pointer,
                kind,
                name.clone(),
                c_int::from(func.length),
                entry.magic as c_int,
            );
            object.define(&name, data_property(Value::Object(value)));
        }
        cdefs::JS_DEF_CGETSET | cdefs::JS_DEF_CGETSET_MAGIC => {
            let magic = entry.magic as c_int;
            // Two conventions, and choosing the wrong one is silent: `JS_CGETSET_DEF` passes
            // `(ctx, this_val)` and `JS_CGETSET_MAGIC_DEF` passes `(ctx, this_val, magic)`,
            // so calling a magic accessor through the plain convention leaves its `magic`
            // argument reading whatever the register happened to hold.
            let (getter_kind, setter_kind) = if entry.def_type == cdefs::JS_DEF_CGETSET_MAGIC {
                (CFunctionEnum::GetterMagic, CFunctionEnum::SetterMagic)
            } else {
                (CFunctionEnum::Getter, CFunctionEnum::Setter)
            };
            // SAFETY: `def_type` selects this arm.
            let pair = unsafe { &entry.u.getset };
            let getter = wrap_accessor(interp, pair.get, getter_kind, magic, "get");
            let setter = wrap_accessor(interp, pair.set, setter_kind, magic, "set");
            object.define(&entry_name(entry), accessor_property(getter, setter));
        }
        cdefs::JS_DEF_PROP_STRING => {
            // SAFETY: `def_type` selects this arm.
            let text = unsafe { entry.u.str_ };
            let value = if text.is_null() {
                Value::Undefined
            } else {
                // SAFETY: a `JS_PROP_STRING_DEF` names a NUL-terminated static string.
                let text = unsafe { std::ffi::CStr::from_ptr(text) };
                interp.string(text.to_string_lossy().into_owned())
            };
            object.define(&entry_name(entry), data_property(value));
        }
        cdefs::JS_DEF_PROP_INT32 => {
            // SAFETY: `def_type` selects this arm.
            let number = unsafe { entry.u.i32 };
            object.define(&entry_name(entry), data_property(Value::Int(number)));
        }
        cdefs::JS_DEF_PROP_INT64 => {
            // SAFETY: `def_type` selects this arm.
            let number = unsafe { entry.u.i64 };
            object.define(
                &entry_name(entry),
                data_property(Value::Float(number as f64)),
            );
        }
        cdefs::JS_DEF_PROP_DOUBLE => {
            // SAFETY: `def_type` selects this arm.
            let number = unsafe { entry.u.f64 };
            object.define(&entry_name(entry), data_property(Value::Float(number)));
        }
        cdefs::JS_DEF_PROP_UNDEFINED => {
            object.define(&entry_name(entry), data_property(Value::Undefined));
        }
        cdefs::JS_DEF_PROP_BOOL => {
            // SAFETY: `def_type` selects this arm; a bool definition stores an `i32`.
            let flag = unsafe { entry.u.i32 } != 0;
            object.define(&entry_name(entry), data_property(Value::Bool(flag)));
        }
        other => {
            return Err(engine::Signal::Throw(interp.make_error(
                "TypeError",
                &format!("unsupported JS_DEF_* {other} in a function list"),
            )));
        }
    }
    Ok(())
}

/// The property name of an entry, as a `String`.
fn entry_name(entry: &JSCFunctionListEntry) -> String {
    if entry.name.is_null() {
        return String::new();
    }
    // SAFETY: an entry's `name` is a NUL-terminated string in the module's static data.
    unsafe { std::ffi::CStr::from_ptr(entry.name) }
        .to_string_lossy()
        .into_owned()
}

/// Wrap one half of a getter/setter pair as a JavaScript accessor function.
///
/// A null pointer means "this half does not exist", which the property system already
/// spells as `None` โ€” so an entry with only a getter is read-only rather than a function
/// that returns `undefined`.
fn wrap_accessor(
    interp: &mut engine::Interp<'static>,
    function: JSCFunctionType,
    kind: CFunctionEnum,
    magic: c_int,
    which: &str,
) -> Option<Value> {
    if function.is_null() {
        return None;
    }
    let pointer = function.as_ptr();
    let body: engine::object::HostFn = Box::new(move |interp, this, args| {
        let context = current_context_or_null();
        call_c_function(context, interp, pointer, kind, magic, this, args)
    });
    Some(Value::Object(interp.new_host_function(which, 0, body)))
}

// ---------------------------------------------------------------------------
// Classes
// ---------------------------------------------------------------------------

/// `JS_NewClassID`: allocate an id, storing it in `*pclass_id`.
///
/// Mirrors the reference: an id that is already non-zero is kept, so a second call is not a
/// second allocation. That is what makes a module's static `JSClassID` idempotent.
///
/// # Safety
///
/// `pclass_id` must be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewClassID(pclass_id: *mut cdefs::ClassId) -> cdefs::ClassId {
    let Some(slot) = (unsafe { pclass_id.as_mut() }) else {
        return 0;
    };
    if *slot != 0 {
        return *slot;
    }
    // No runtime needed: ids are global, exactly as in the reference, because the id a
    // module remembers has to keep meaning the same class in every runtime it is
    // registered with.
    *slot = runtime::allocate_class_id();
    *slot
}

/// `JS_NewClass`: register a class with the runtime.
///
/// # Safety
///
/// `rt` must be a live runtime and `class_def` a valid `JSClassDef` whose strings and
/// function pointers outlive the class.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewClass(
    rt: *mut JsRuntime,
    class_id: cdefs::ClassId,
    class_def: *const JSClassDef,
) -> c_int {
    let (Some(runtime), Some(definition)) = (unsafe { rt.as_ref() }, unsafe { class_def.as_ref() })
    else {
        return -1;
    };
    let declaration = runtime::ClassDecl {
        finalizer: definition.finalizer,
        gc_mark: definition.gc_mark,
        exotic: definition.exotic,
        name: definition.class_name,
    };
    -c_int::from(!runtime.define_class(class_id, declaration))
}

/// `JS_IsRegisteredClass`.
///
/// # Safety
///
/// `rt` must be a live runtime.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_IsRegisteredClass(
    rt: *mut JsRuntime,
    class_id: cdefs::ClassId,
) -> c_int {
    match unsafe { rt.as_ref() } {
        Some(runtime) => c_int::from(runtime.has_class(class_id)),
        None => 0,
    }
}

/// `JS_GetClassID`: the class an object belongs to, or `JS_INVALID_CLASS_ID`.
///
/// # Safety
///
/// `value` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetClassID(value: JsValue) -> cdefs::ClassId {
    let Some(value) = (unsafe { arg(value) }) else {
        return 0;
    };
    value
        .as_object()
        .and_then(|object| object.host_class_id())
        .map_or(0, |id| id.get())
}

/// `JS_SetClassProto`: the prototype `JS_NewObjectClass` uses for `class_id`.
///
/// # Safety
///
/// `ctx` must be a live context and `obj` a live object `JSValue` whose reference this call
/// consumes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetClassProto(
    ctx: *mut JsContext,
    class_id: cdefs::ClassId,
    obj: JsValue,
) {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return;
    };
    let Some(prototype) = (unsafe { arg(obj) }).and_then(|value| value.as_object().cloned()) else {
        return;
    };
    // SAFETY: the C API consumes the reference it was handed.
    unsafe { runtime::release(obj) };
    context.with_current_interp(|interp| {
        interp.set_host_class_proto(ClassId::from_raw(class_id), prototype);
    });
}

/// `JS_GetClassProto`: the prototype installed for `class_id`, as a new reference.
///
/// # Safety
///
/// `ctx` must be a live context.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetClassProto(
    ctx: *mut JsContext,
    class_id: cdefs::ClassId,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    context.with_interp(
        |interp| match interp.host_class_proto(ClassId::from_raw(class_id)) {
            Some(proto) => jsvalue_of(Value::Object(proto)),
            None => jsvalue::UNDEFINED,
        },
    )
}

/// `JS_SetOpaque`: attach a payload pointer to a host-class instance.
///
/// # Safety
///
/// `obj` must be a live `JSValue`; `opaque` is the host's to own.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetOpaque(obj: JsValue, opaque: *mut core::ffi::c_void) {
    let Some(value) = (unsafe { arg(obj) }) else {
        return;
    };
    let Some(object) = value.as_object() else {
        return;
    };
    object.set_host_opaque(engine::Opaque::new(opaque.cast()));
}

/// `JS_GetOpaque`: the payload of `obj` when it is an instance of `class_id`.
///
/// The one place in this file that answers from somewhere other than a live object: while a
/// finalizer runs there is no object left, so the value C was handed is a sentinel and the
/// payload comes from the finalizer's own frame. See [`crate::runtime`].
///
/// # Safety
///
/// `obj` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetOpaque(
    obj: JsValue,
    class_id: cdefs::ClassId,
) -> *mut core::ffi::c_void {
    if runtime::is_finalizer_sentinel(obj) {
        return runtime::finalizer_opaque(class_id)
            .map(|opaque| opaque.cast())
            .unwrap_or(std::ptr::null_mut());
    }
    let Some(value) = (unsafe { arg(obj) }) else {
        return std::ptr::null_mut();
    };
    let Some(object) = value.as_object() else {
        return std::ptr::null_mut();
    };
    if object.host_class_id().is_none_or(|id| id.get() != class_id) {
        return std::ptr::null_mut();
    }
    object
        .host_opaque()
        .map_or(std::ptr::null_mut(), |opaque| opaque.as_ptr().cast())
}

/// `JS_GetOpaque2`: [`JS_GetOpaque`], raising a `TypeError` instead of answering null.
///
/// # Safety
///
/// `ctx` must be a live context and `obj` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetOpaque2(
    ctx: *mut JsContext,
    obj: JsValue,
    class_id: cdefs::ClassId,
) -> *mut core::ffi::c_void {
    // SAFETY: the caller's contract.
    let opaque = unsafe { JS_GetOpaque(obj, class_id) };
    if !opaque.is_null() {
        return opaque;
    }
    if let Some(context) = unsafe { ctx.as_ref() } {
        // The reference names the class in its message ("not a Point"), which is what tells
        // a script author which `this` was wrong.
        // SAFETY: the runtime pointer is live for as long as the context is.
        let runtime = unsafe { context.runtime().as_ref() };
        let name = runtime
            .and_then(|runtime| runtime.class(class_id))
            .map(|decl| class_name(decl.name))
            .unwrap_or_else(|| format!("class {class_id}"));
        runtime::throw_error(context, "TypeError", &format!("not a {name}"));
    }
    std::ptr::null_mut()
}

/// A class's name, from the C string it was registered with.
fn class_name(name: *const c_char) -> String {
    if name.is_null() {
        return "<anonymous>".to_string();
    }
    // SAFETY: `JSClassDef::class_name` is a NUL-terminated string the module keeps alive.
    unsafe { std::ffi::CStr::from_ptr(name) }
        .to_string_lossy()
        .into_owned()
}

/// `JS_GetRuntime`: the runtime a context belongs to.
///
/// # Safety
///
/// `ctx` must be a live context.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetRuntime(ctx: *mut JsContext) -> *mut JsRuntime {
    match unsafe { ctx.as_ref() } {
        Some(context) => context.runtime(),
        None => std::ptr::null_mut(),
    }
}

/// `JS_ThrowRangeError`: raise a `RangeError` with the given message.
///
/// The reference's version is variadic (`fmt, ...`). Ours reads only `fmt`, which is correct
/// for every call in the acceptance surface โ€” none of them carry a `%` conversion. A
/// variadic Rust function is not expressible on stable, and a wrong-arity call would be
/// worse than one that ignores surplus arguments: on x86-64 SysV the surplus ones are simply
/// not read.
///
/// # Safety
///
/// `ctx` must be a live context and `message` a NUL-terminated string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ThrowRangeError(
    ctx: *mut JsContext,
    message: *const c_char,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let message = if message.is_null() {
        String::new()
    } else {
        // SAFETY: the caller guarantees a NUL-terminated string.
        unsafe { std::ffi::CStr::from_ptr(message) }
            .to_string_lossy()
            .into_owned()
    };
    runtime::throw_error(context, "RangeError", &message)
}

// ---------------------------------------------------------------------------
// Coercions that are not int32s
// ---------------------------------------------------------------------------

/// `JS_ToFloat64`: `ToNumber`, or `-1` with a pending exception.
///
/// # Safety
///
/// `pres` must be writable and `val` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToFloat64(ctx: *mut JsContext, pres: *mut f64, 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 context.with_current_interp(|interp| interp.to_js_number(&value)) {
        Ok(number) => {
            if !pres.is_null() {
                // SAFETY: the caller guarantees the pointer is writable.
                unsafe { *pres = number };
            }
            0
        }
        Err(signal) => {
            let _ = runtime::result_value(context, Err(signal));
            -1
        }
    }
}

/// `JS_ToCStringLen2`: the value as a NUL-terminated UTF-8 string, allocated by
/// [`crate::js_mallocz`]'s allocator so `JS_FreeCString` can release it.
///
/// `cesu8` is ignored: the engine's strings carry WTF-8 (lone surrogates preserved as three
/// bytes), which is what the reference emits for `cesu8 = 0` as well.
///
/// # Safety
///
/// `ctx` must be a live context, `val` a live `JSValue`, and `plen` null or writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ToCStringLen2(
    ctx: *mut JsContext,
    plen: *mut usize,
    val: JsValue,
    _cesu8: c_int,
) -> *mut c_char {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return std::ptr::null_mut();
    };
    let Some(value) = (unsafe { arg(val) }) else {
        runtime::throw_error(context, "TypeError", "not a value");
        return std::ptr::null_mut();
    };
    let text = match context.with_current_interp(|interp| interp.to_js_string(&value)) {
        Ok(text) => text,
        Err(signal) => {
            let _ = runtime::result_value(context, Err(signal));
            return std::ptr::null_mut();
        }
    };
    let bytes = text.as_bytes();
    // SAFETY: `alloc_raw_zeroed` gives a zeroed block of the requested size, which is the
    // same allocator `js_mallocz` uses and therefore the one `js_free`/`JS_FreeCString`
    // expects.
    let buffer = unsafe { crate::alloc::alloc_raw_zeroed(bytes.len() + 1) };
    if buffer.is_null() {
        runtime::throw_error(context, "InternalError", "out of memory");
        return std::ptr::null_mut();
    }
    // SAFETY: the block holds `bytes.len() + 1` writable bytes, and the last one was zeroed.
    unsafe {
        std::ptr::copy_nonoverlapping(bytes.as_ptr(), buffer, bytes.len());
    }
    if !plen.is_null() {
        // SAFETY: the caller guarantees the pointer is writable.
        unsafe { *plen = bytes.len() };
    }
    buffer.cast()
}

/// `JS_FreeCString`: release a string from [`JS_ToCStringLen2`].
///
/// # Safety
///
/// `ptr` must be null or a live pointer from `JS_ToCStringLen2`, and must not be used again.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_FreeCString(_ctx: *mut JsContext, ptr: *const c_char) {
    // SAFETY: the caller's contract; the allocator checks the header before freeing.
    unsafe { crate::alloc::free_raw(ptr.cast_mut().cast()) }
}