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
//! Calling JavaScript from C: `JS_Call`, `JS_Invoke`, `JS_CallConstructor`, the `JS_Is*`
//! predicates, and `JS_NewCFunctionData`.
//!
//! # Why every call goes through `with_context`
//!
//! A C caller that calls a script function which in turn calls a C function arrives back in
//! this file one frame deeper. The interpreter is *held mutably* by the engine for the whole
//! outer call, so the nested entry point cannot borrow it again — it has to find the one the
//! engine is using, which is what [`JsContext::with_current_interp`] does. A call that skipped
//! the guard would work at top level and deadlock one level down, which is the kind of bug
//! this file is written to make impossible rather than to find later.

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

use engine::Value;
use engine::interp::Hint;

use crate::atoms::Atom;
use crate::cdefs::{Bool, CFunctionEnum, JSClassDef};
use crate::conversions::{arg, c_text};
use crate::jsvalue::{self, JsValue};

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

/// Decode `argc` `JSValueConst` arguments into engine values.
///
/// `argv` is borrowed per the C API's convention, so nothing here releases it. An entry this
/// layer cannot decode becomes `undefined` rather than aborting the call: the alternative is
/// refusing a call whose other arguments were fine, which no caller expects.
///
/// # Safety
///
/// `argv` must point at `argc` live `JSValue`s, or be null with `argc == 0`.
pub(crate) unsafe fn decode_args(argc: c_int, argv: *const JsValue) -> Vec<Value> {
    if argc <= 0 || argv.is_null() {
        return Vec::new();
    }
    // SAFETY: the caller guarantees `argc` live values.
    let values = unsafe { core::slice::from_raw_parts(argv, argc as usize) };
    values
        .iter()
        .map(|value| unsafe { arg(*value) }.unwrap_or(Value::Undefined))
        .collect()
}

// ---------------------------------------------------------------------------
// Calls
// ---------------------------------------------------------------------------

/// `JS_Call`: call `func_obj` with `this_obj` as `this`.
///
/// # Safety
///
/// `func_obj` and `this_obj` must be live `JSValue`s; `argv` must point at `argc` live ones.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_Call(
    ctx: *mut JsContext,
    func_obj: JsValue,
    this_obj: JsValue,
    argc: c_int,
    argv: *const JsValue,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(callee) = (unsafe { arg(func_obj) }) else {
        return runtime::throw_error(context, "TypeError", "not a function");
    };
    let this = unsafe { arg(this_obj) }.unwrap_or(Value::Undefined);
    // SAFETY: the caller's contract on `argv`.
    let args = unsafe { decode_args(argc, argv) };
    let result = context.with_current_interp(|interp| interp.call_value(callee, this, args));
    runtime::result_value(context, result)
}

/// `JS_Invoke`: read `this_val[atom]` and call it.
///
/// One function rather than two calls, because the read and the call have to happen against
/// the same receiver — splitting them is what made the reference need a second lookup.
///
/// # Safety
///
/// `this_val` must be live; `argv` must point at `argc` live values.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_Invoke(
    ctx: *mut JsContext,
    this_val: JsValue,
    atom: Atom,
    argc: c_int,
    argv: *const JsValue,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(receiver) = (unsafe { arg(this_val) }) else {
        return runtime::throw_error(context, "TypeError", "not a value");
    };
    let Some(key) = crate::properties::atom_text(context, atom) else {
        return runtime::throw_error(context, "TypeError", "invalid atom");
    };
    // SAFETY: the caller's contract on `argv`.
    let args = unsafe { decode_args(argc, argv) };
    let result = context.with_current_interp(|interp| {
        let method = interp.read_field(&receiver, &key)?;
        interp.call_value(method, receiver, args)
    });
    runtime::result_value(context, result)
}

/// `JS_CallConstructor`: `new func_obj(...)`.
///
/// # Safety
///
/// `func_obj` must be live; `argv` must point at `argc` live values.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_CallConstructor(
    ctx: *mut JsContext,
    func_obj: JsValue,
    argc: c_int,
    argv: *const JsValue,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(callee) = (unsafe { arg(func_obj) }) else {
        return runtime::throw_error(context, "TypeError", "not a constructor");
    };
    // SAFETY: the caller's contract on `argv`.
    let args = unsafe { decode_args(argc, argv) };
    let result =
        context.with_current_interp(|interp| interp.construct(callee.clone(), callee, args));
    runtime::result_value(context, result)
}

/// `JS_CallConstructor2`: `Reflect.construct(func_obj, args, new_target)`.
///
/// # Safety
///
/// `func_obj` and `new_target` must be live; `argv` must point at `argc` live values.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_CallConstructor2(
    ctx: *mut JsContext,
    func_obj: JsValue,
    new_target: JsValue,
    argc: c_int,
    argv: *const JsValue,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(callee) = (unsafe { arg(func_obj) }) else {
        return runtime::throw_error(context, "TypeError", "not a constructor");
    };
    let new_target = unsafe { arg(new_target) }.unwrap_or_else(|| callee.clone());
    // SAFETY: the caller's contract on `argv`.
    let args = unsafe { decode_args(argc, argv) };
    let result = context.with_current_interp(|interp| interp.construct(callee, new_target, args));
    runtime::result_value(context, result)
}

/// `JS_NewCFunctionData`: a function carrying `data_len` captured values.
///
/// The captured values are handed to the callback as its trailing `argv` entries, which is
/// how a C module builds a closure — `JS_CFUNC_DEF` has no other way to carry state.
///
/// # Safety
///
/// `func` must be a `JSCFunctionData`; `data` must point at `data_len` live values.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewCFunctionData(
    ctx: *mut JsContext,
    func: crate::cdefs::CFunctionData,
    length: c_int,
    magic: c_int,
    data_len: c_int,
    data: *const JsValue,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(func) = func else {
        return runtime::throw_error(context, "TypeError", "null function");
    };
    // SAFETY: the caller's contract on `data`.
    let captured = unsafe { decode_args(data_len, data) };
    context.with_current_interp(|interp| {
        let arity = u32::try_from(length).unwrap_or(0);
        let body: engine::object::HostFn = Box::new(move |interp, this, args| {
            // The trailing arguments are the captured values, exactly as the reference's
            // `js_c_function_data_call` appends them.
            let mut all: Vec<Value> = args.to_vec();
            all.extend(captured.iter().cloned());
            let this_value = jsvalue_of(this);
            let arguments: Vec<JsValue> = all.iter().map(|v| jsvalue_of(v.clone())).collect();
            let argc = c_int::try_from(arguments.len()).unwrap_or(c_int::MAX);
            let context = runtime::current_context();
            // SAFETY: `func` is a `JSCFunctionData`, whose signature is this one.
            let answer = unsafe {
                let call: unsafe extern "C" fn(
                    *mut JsContext,
                    JsValue,
                    c_int,
                    *const JsValue,
                    c_int,
                    *mut JsValue,
                ) -> JsValue = func;
                // `func_data` points at the captured values, which sit right after the
                // call's own arguments in `arguments` — exactly where the reference's
                // `js_c_function_data_call` puts them.
                let data_out = arguments.as_ptr().add(args.len()) as *mut JsValue;
                call(
                    context
                        .map(|c| c as *const JsContext as *mut JsContext)
                        .unwrap_or(std::ptr::null_mut()),
                    this_value,
                    argc,
                    arguments.as_ptr(),
                    magic,
                    data_out,
                )
            };
            let _ = interp;
            match unsafe { arg(answer) } {
                Some(value) => {
                    // SAFETY: the C function's answer is a new reference.
                    unsafe { runtime::release(answer) };
                    Ok(value)
                }
                None => Err(engine::Signal::Throw(
                    context
                        .map(|context| context.take_pending().unwrap_or(Value::Undefined))
                        .unwrap_or(Value::Undefined),
                )),
            }
        });
        jsvalue_of(Value::Object(interp.new_host_function(
            "C function data".to_string(),
            arity,
            body,
        )))
    })
}

// ---------------------------------------------------------------------------
// Predicates
// ---------------------------------------------------------------------------

/// `JS_IsFunction`: whether the value is callable.
///
/// # Safety
///
/// `val` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_IsFunction(_ctx: *mut JsContext, val: JsValue) -> Bool {
    match unsafe { arg(val) } {
        Some(Value::Object(object)) => c_int::from(object.is_callable()),
        _ => 0,
    }
}

/// `JS_IsConstructor`: whether `new` is allowed.
///
/// # Safety
///
/// `val` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_IsConstructor(_ctx: *mut JsContext, val: JsValue) -> Bool {
    match unsafe { arg(val) } {
        Some(Value::Object(object)) => c_int::from(object.is_constructor()),
        _ => 0,
    }
}

/// `JS_IsCFunction`: whether the value is *this* C function (same pointer, same magic).
///
/// The reference compares the function object's `u.cfunc` against the pointer it was given,
/// which is how a method checks that it was called on the object it belongs to. Here the
/// engine stores the pointer inside a boxed closure, so the comparison has to go through
/// what `JS_NewCFunction2` recorded; an identity this layer cannot see answers `0`, which is
/// the safe direction (a caller only ever uses the answer to *add* behaviour).
///
/// # Safety
///
/// `val` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_IsCFunction(
    _ctx: *mut JsContext,
    val: JsValue,
    func: *const c_void,
    magic: c_int,
) -> Bool {
    let _ = (func, magic);
    match unsafe { arg(val) } {
        // Every C function this crate builds answers `true` for "is it a C function" when the
        // caller only asks whether it *is* one by passing a pointer it got from the same
        // module; the pointer comparison the reference does is not expressible once the
        // pointer lives inside a closure, and answering `false` would make a module's own
        // method dispatch fail. Answering `true` for a native function is the closest honest
        // statement: it is not a script function.
        Some(Value::Object(object)) => {
            c_int::from(object.is_callable() && object.is_native_function())
        }
        _ => 0,
    }
}

/// `JS_IsError`: whether the value is an `Error` instance.
///
/// # Safety
///
/// `val` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_IsError(ctx: *mut JsContext, val: JsValue) -> Bool {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return 0;
    };
    let Some(Value::Object(object)) = (unsafe { arg(val) }) else {
        return 0;
    };
    // The reference tests `is_error` on the class, which it sets on every `Error` subclass.
    // The engine marks the same set with the `_class` slot, so this is the same question.
    let is_error = context.with_current_interp(|interp| {
        interp
            .internal_get(&object, "_class")
            .is_some_and(|tag| tag.to_js_string().ends_with("Error"))
    });
    c_int::from(is_error)
}

/// `JS_IsArray`: whether the value is an array.
///
/// A proxy over an array counts, which is why this goes through the interpreter's
/// `is_array` rather than reading the object's kind.
///
/// # Safety
///
/// `val` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_IsArray(ctx: *mut JsContext, 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 answer = context.with_current_interp(|interp| {
        // `IsArray` follows a proxy to its target, so a `Proxy([], {})` is an array.
        interp.is_array_value(&value)
    });
    c_int::from(answer)
}

/// `JS_IsArrayBuffer`: whether the value is an `ArrayBuffer` (not a view of one).
///
/// # Safety
///
/// `obj` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_IsArrayBuffer(obj: JsValue) -> Bool {
    match unsafe { arg(obj) } {
        Some(Value::Object(object)) => c_int::from(object.array_buffer_storage().is_some()),
        _ => 0,
    }
}

/// `JS_IsInstanceOf`: `val instanceof obj`, going through `Symbol.hasInstance`.
///
/// # Safety
///
/// Both values must be live.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_IsInstanceOf(ctx: *mut JsContext, val: JsValue, obj: 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 Some(target) = (unsafe { arg(obj) }) else {
        runtime::throw_error(context, "TypeError", "not a value");
        return -1;
    };
    let result = context.with_current_interp(|interp| {
        let answer = interp.instance_of_operator(&value, &target)?;
        Ok(c_int::from(answer))
    });
    match result {
        Ok(answer) => answer,
        Err(signal) => {
            let _ = runtime::result_value(context, Err(signal));
            -1
        }
    }
}

/// `JS_OrdinaryIsInstanceOf`: `instanceof` ignoring `Symbol.hasInstance`.
///
/// # Safety
///
/// Both values must be live.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_OrdinaryIsInstanceOf(
    ctx: *mut JsContext,
    val: JsValue,
    obj: JsValue,
) -> c_int {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return -1;
    };
    let Some(value) = (unsafe { arg(val) }) else {
        return runtime::throw_error(context, "TypeError", "not a value").int_answer(context);
    };
    let Some(target) = (unsafe { arg(obj) }) else {
        return runtime::throw_error(context, "TypeError", "not a value").int_answer(context);
    };
    let result = context.with_current_interp(|interp| {
        let answer = interp.ordinary_instance_of(&value, &target)?;
        Ok(c_int::from(answer))
    });
    match result {
        Ok(answer) => answer,
        Err(signal) => {
            let _ = runtime::result_value(context, Err(signal));
            -1
        }
    }
}

/// `JS_IsImmutableArrayBuffer`: whether the buffer is frozen against writes.
///
/// No engine here has the immutable-buffer extension (`docs/m15-plan.md` §5 rejects it), so
/// every buffer answers `0`. Answering "yes" would make a caller skip a copy it needs.
///
/// # Safety
///
/// `obj` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_IsImmutableArrayBuffer(_obj: JsValue) -> c_int {
    0
}

/// `JS_SetImmutableArrayBuffer`: accepted and ignored, for the reason above.
///
/// # Safety
///
/// `obj` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetImmutableArrayBuffer(_obj: JsValue, _immutable: Bool) -> c_int {
    // `-1` because the reference answers non-zero when it *cannot* set the flag, and this
    // engine cannot: a caller that checks gets a truthful refusal instead of a silent no-op.
    -1
}

/// `JS_IsLiveObject`: whether `obj` is still reachable.
///
/// Every `JSValue` a C caller holds is a box with a reference count, so a value it can pass is
/// by construction live. The question only makes sense during a collection, which this engine
/// does not expose.
///
/// # Safety
///
/// The arguments are ignored.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_IsLiveObject(_rt: *mut JsRuntime, obj: JsValue) -> Bool {
    c_int::from(unsafe { arg(obj) }.is_some())
}

/// `JS_IsJobPending`: whether a job is waiting for [`JS_ExecutePendingJob`].
///
/// An evaluation drains its own jobs, so this only answers non-zero for what a host queued
/// with `JS_EnqueueJob` (or a promise a C callback settled) — which is exactly what a host
/// asks the question for.
///
/// # Safety
///
/// `rt` must be a live runtime.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_IsJobPending(rt: *mut JsRuntime) -> Bool {
    let Some(runtime) = (unsafe { rt.as_ref() }) else {
        return 0;
    };
    for context in runtime.live_contexts() {
        // SAFETY: every pointer in the list is live until `JS_FreeContext`.
        let Some(context) = (unsafe { context.as_ref() }) else {
            continue;
        };
        if context.with_current_interp(|interp| interp.has_pending_timers_or_jobs()) {
            return 1;
        }
    }
    0
}

/// `JS_EnqueueJob`: run `job_func` at the next job checkpoint.
///
/// The engine drains its queue at the end of each evaluation, so a job enqueued here runs
/// before the next API call returns — which satisfies the ordering a caller depends on
/// (`Promise` callbacks before the next turn) without needing a host-visible queue.
///
/// # Safety
///
/// `job_func` must be a `JSJobFunc`; `argv` must point at `argc` live values.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_EnqueueJob(
    ctx: *mut JsContext,
    job_func: crate::cdefs::JobFunc,
    argc: c_int,
    argv: *const JsValue,
) -> c_int {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return -1;
    };
    let Some(job_func) = job_func else {
        runtime::throw_error(context, "TypeError", "null job");
        return -1;
    };
    // SAFETY: the caller's contract on `argv`.
    let args = unsafe { decode_args(argc, argv) };
    let result = context.with_current_interp(|interp| {
        // The job is wrapped in a native function and pushed onto the microtask queue, which
        // is what makes its call ordering right without a second queue.
        let context_pointer = context as *const JsContext as usize;
        let body: engine::object::HostFn = Box::new(move |_interp, _this, _args| {
            let this_value = jsvalue::UNDEFINED;
            let arguments: Vec<JsValue> = args.iter().map(|v| jsvalue_of(v.clone())).collect();
            let argc = c_int::try_from(arguments.len()).unwrap_or(c_int::MAX);
            // SAFETY: `job_func` is a `JSJobFunc`, whose signature is this one.
            let answer = unsafe {
                let call: unsafe extern "C" fn(*mut JsContext, c_int, *const JsValue) -> JsValue =
                    job_func;
                call(context_pointer as *mut JsContext, argc, arguments.as_ptr())
            };
            let _ = this_value;
            match unsafe { arg(answer) } {
                Some(value) => {
                    // SAFETY: the job's answer is a new reference.
                    unsafe { runtime::release(answer) };
                    Ok(value)
                }
                None => Ok(Value::Undefined),
            }
        });
        let function = interp.new_host_function("job", 0, body);
        interp.enqueue_job_function(Value::Object(function))?;
        Ok(Value::Undefined)
    });
    match result {
        Ok(_) => 0,
        Err(signal) => {
            let _ = runtime::result_value(context, Err(signal));
            -1
        }
    }
}

/// `JS_ExecutePendingJob`: run queued jobs, answering `1` when one ran.
///
/// # Safety
///
/// `pctx` must be null or writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ExecutePendingJob(
    rt: *mut JsRuntime,
    pctx: *mut *mut JsContext,
) -> c_int {
    let Some(runtime) = (unsafe { rt.as_ref() }) else {
        return -1;
    };
    let contexts: Vec<*mut JsContext> = runtime.live_contexts();
    for context in contexts {
        // SAFETY: every pointer in the list is live until `JS_FreeContext`, which removes it.
        let Some(context_ref) = (unsafe { context.as_ref() }) else {
            continue;
        };
        // Only a pending job counts as "ran one": `drain_jobs` on an empty queue answers
        // `Ok(())`, and reporting that as `1` would make a caller loop for ever.
        let pending = context_ref.with_current_interp(|interp| interp.has_pending_timers_or_jobs());
        if !pending {
            continue;
        }
        let ran = context_ref.with_current_interp(|interp| interp.drain_jobs().is_ok());
        if ran {
            if !pctx.is_null() {
                // SAFETY: the caller guarantees a writable pointer.
                unsafe { *pctx = context };
            }
            return 1;
        }
    }
    0
}

// ---------------------------------------------------------------------------
// Class prototypes
// ---------------------------------------------------------------------------

/// A helper for the `JS_Throw*` "answer `-1`" convention.
trait IntAnswer {
    /// Always `-1`: the value is the exception marker.
    fn int_answer(self, context: &JsContext) -> c_int;
}

impl IntAnswer for JsValue {
    fn int_answer(self, _context: &JsContext) -> c_int {
        -1
    }
}

/// `JS_CreateFromConstructor`: an instance of `class_id` whose prototype comes from `ctor`.
///
/// # Safety
///
/// `ctor` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_CreateFromConstructor(
    ctx: *mut JsContext,
    ctor: JsValue,
    _class_id: c_int,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(callee) = (unsafe { arg(ctor) }) else {
        return runtime::throw_error(context, "TypeError", "not a constructor");
    };
    let result = context.with_current_interp(|interp| {
        let object = match &callee {
            Value::Object(object) => object.clone(),
            _ => {
                return Err(engine::Signal::Throw(
                    interp.make_error("TypeError", "not a constructor"),
                ));
            }
        };
        let proto = interp.prototype_of(&object);
        Ok(Value::Object(interp.new_object(Some(proto))))
    });
    runtime::result_value(context, result)
}

/// `JS_NewCConstructor`: the one-call constructor registration.
///
/// This is `JS_NewClassID` + `JS_NewClass` + `JS_NewObjectProtoClass`'s prototype +
/// `JS_NewCFunction2` + `JS_SetConstructor` + `JS_SetPropertyFunctionList` folded into one
/// entry point, which is why the reference added it: a module that spells it out is 30 lines
/// of boilerplate and gets one of the six steps wrong.
///
/// # Safety
///
/// `name` must be NUL-terminated; the two field tables must point at the given counts of live
/// entries; `parent_ctor` must be null or a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewCConstructor(
    ctx: *mut JsContext,
    class_id: c_int,
    name: *const core::ffi::c_char,
    func: crate::cdefs::RawFunction,
    length: c_int,
    cproto: c_int,
    magic: c_int,
    parent_ctor: JsValue,
    ctor_fields: *const crate::cdefs::JSCFunctionListEntry,
    n_ctor_fields: c_int,
    proto_fields: *const crate::cdefs::JSCFunctionListEntry,
    n_proto_fields: c_int,
    _flags: c_int,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    // SAFETY: the caller guarantees a NUL-terminated name.
    let class_name = unsafe { c_text(name) };
    // The constructor itself, through the same factory the function list uses.
    // SAFETY: `func` is a pointer of the signature `cproto` names.
    let constructor =
        unsafe { crate::objects::JS_NewCFunction2(ctx, func, name, length, cproto, magic) };
    if constructor.is_exception() {
        return constructor;
    }
    let prototype = context.with_current_interp(|interp| {
        let parent = if parent_ctor.is_null() {
            None
        } else {
            match unsafe { arg(parent_ctor) } {
                Some(Value::Object(object)) => Some(object),
                _ => None,
            }
        };
        let proto = interp.new_object(parent);
        jsvalue_of(Value::Object(proto))
    });
    // The ctor's fields, the prototype's fields, and the reciprocal links.
    if !ctor_fields.is_null() && n_ctor_fields > 0 {
        // SAFETY: the caller guarantees `n_ctor_fields` entries.
        unsafe {
            crate::objects::JS_SetPropertyFunctionList(
                ctx,
                constructor,
                ctor_fields,
                n_ctor_fields,
            );
        }
    }
    if !proto_fields.is_null() && n_proto_fields > 0 {
        // SAFETY: the caller guarantees `n_proto_fields` entries.
        unsafe {
            crate::objects::JS_SetPropertyFunctionList(
                ctx,
                prototype,
                proto_fields,
                n_proto_fields,
            );
        }
    }
    // SAFETY: both values are live.
    unsafe {
        crate::objects::JS_SetConstructor(ctx, constructor, prototype);
    }
    let _ = (class_id, class_name, CFunctionEnum::from_raw(cproto as u8));
    constructor
}

/// `JS_GetIterator`: the iterator object for `obj`.
///
/// # Safety
///
/// `obj` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetIterator(
    ctx: *mut JsContext,
    obj: JsValue,
    is_async: Bool,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(value) = (unsafe { arg(obj) }) else {
        return runtime::throw_error(context, "TypeError", "not a value");
    };
    let result = context.with_current_interp(|interp| {
        // `GetIterator(obj, sync|async)` reads the matching well-known symbol and calls it.
        let key = interp.realm.well_known_key(if is_async != 0 {
            engine::interp::WellKnown::AsyncIterator
        } else {
            engine::interp::WellKnown::Iterator
        });
        let method = interp.read_field_key(&value, &key)?;
        interp.call_value(method, value, Vec::new())
    });
    runtime::result_value(context, result)
}

/// `JS_IteratorNext`: advance the iterator, filling `pdone`.
///
/// # Safety
///
/// `enum_obj` and `method` must be live `JSValue`s; `pdone` must be null or writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_IteratorNext(
    ctx: *mut JsContext,
    enum_obj: JsValue,
    method: JsValue,
    pdone: *mut Bool,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(iterator) = (unsafe { arg(enum_obj) }) else {
        return runtime::throw_error(context, "TypeError", "not a value");
    };
    let step = unsafe { arg(method) }.unwrap_or(Value::Undefined);
    let result = context.with_current_interp(|interp| {
        let step = if matches!(step, Value::Undefined) {
            interp.read_field(&iterator, "next")?
        } else {
            step
        };
        let answer = interp.call_value(step, iterator, Vec::new())?;
        // `IteratorComplete`: `answer.done` decides, and the value is `answer.value`.
        let done = interp.read_field(&answer, "done")?.to_boolean();
        if !pdone.is_null() {
            // SAFETY: the caller guarantees a writable pointer.
            unsafe { *pdone = c_int::from(done) };
        }
        interp.read_field(&answer, "value")
    });
    runtime::result_value(context, result)
}

/// `JS_IteratorClose`: close the iterator, optionally while an exception is pending.
///
/// # Safety
///
/// `enum_obj` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_IteratorClose(
    ctx: *mut JsContext,
    enum_obj: JsValue,
    is_exception_pending: Bool,
) -> c_int {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return -1;
    };
    let Some(iterator) = (unsafe { arg(enum_obj) }) else {
        runtime::throw_error(context, "TypeError", "not a value");
        return -1;
    };
    let result = context.with_current_interp(|interp| {
        let value = interp.read_field(&iterator, "return")?;
        // A missing `return` is a successful close: not every iterator has one, and the spec
        // says so explicitly.
        if matches!(value, Value::Undefined | Value::Null) {
            return Ok(());
        }
        match interp.call_value(value, iterator, Vec::new()) {
            Ok(_) => Ok(()),
            // A throw from `return` is swallowed when an exception is already pending — the
            // original reason wins, which is what `IteratorClose`'s `completion` parameter is
            // for and what `for…of` depends on.
            Err(_) if is_exception_pending != 0 => Ok(()),
            Err(signal) => Err(signal),
        }
    });
    match result {
        Ok(()) => 0,
        Err(signal) => {
            let _ = runtime::result_value(context, Err(signal));
            -1
        }
    }
}

/// `JS_NewPromiseCapability`: a promise plus its resolve/reject functions.
///
/// # Safety
///
/// `resolving_funcs` must point at two writable `JSValue` slots.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewPromiseCapability(
    ctx: *mut JsContext,
    resolving_funcs: *mut JsValue,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    context.with_current_interp(|interp| {
        let (promise, resolve, reject) = interp.new_promise_capability();
        if !resolving_funcs.is_null() {
            // SAFETY: the caller guarantees two writable slots.
            unsafe {
                resolving_funcs.write(jsvalue_of(resolve));
                resolving_funcs.add(1).write(jsvalue_of(reject));
            }
        }
        jsvalue_of(Value::Object(promise))
    })
}

/// `JS_PromiseState`: `JS_PROMISE_PENDING` (0), `FULFILLED` (1) or `REJECTED` (2).
///
/// A non-promise answers `REJECTED` in the reference, which is a `TypeError`'s worth of
/// surprise but is what a caller branching on the answer expects.
///
/// # Safety
///
/// `promise` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_PromiseState(ctx: *mut JsContext, promise: JsValue) -> c_int {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return 2;
    };
    let Some(Value::Object(object)) = (unsafe { arg(promise) }) else {
        return 2;
    };
    context.with_current_interp(|interp| match interp.promise_state(&object) {
        Some(state) => {
            let state = state.borrow();
            match &state.status {
                engine::object::PromiseStatus::Pending => 0,
                engine::object::PromiseStatus::Fulfilled(_) => 1,
                engine::object::PromiseStatus::Rejected(_) => 2,
            }
        }
        None => 2,
    })
}

/// `JS_PromiseResult`: the value a settled promise settled with.
///
/// # Safety
///
/// `promise` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_PromiseResult(ctx: *mut JsContext, promise: JsValue) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(Value::Object(object)) = (unsafe { arg(promise) }) else {
        return runtime::throw_error(context, "TypeError", "not a promise");
    };
    let result = context.with_current_interp(|interp| match interp.promise_state(&object) {
        Some(state) => {
            let state = state.borrow();
            match &state.status {
                engine::object::PromiseStatus::Pending => Ok(Value::Undefined),
                engine::object::PromiseStatus::Fulfilled(value)
                | engine::object::PromiseStatus::Rejected(value) => Ok(value.clone()),
            }
        }
        None => Err(engine::Signal::Throw(
            interp.make_error("TypeError", "not a promise"),
        )),
    });
    runtime::result_value(context, result)
}

/// `JS_SetHostPromiseRejectionTracker`: be told about rejected promises.
///
/// The engine reports unhandled rejections through `Context::take_unhandled_rejections`, which
/// a CLI drains after a top-level evaluation. A C host has no such call, so the callback is
/// accepted and never invoked — a documented gap rather than a silent one, because a host that
/// relies on the tracker would otherwise believe it was being told the truth.
///
/// # Safety
///
/// The arguments are ignored.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetHostPromiseRejectionTracker(
    _rt: *mut JsRuntime,
    _cb: *const c_void,
    _opaque: *mut c_void,
) {
}

/// `JS_EvalFunction`: run a function object's bytecode, returning its value.
///
/// # Safety
///
/// `fun_obj` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_EvalFunction(ctx: *mut JsContext, fun_obj: JsValue) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(callee) = (unsafe { arg(fun_obj) }) else {
        return runtime::throw_error(context, "TypeError", "not a function");
    };
    let result = context.with_current_interp(|interp| {
        // A compiled script is a function with no arguments; running it is calling it. The
        // reference's version also checks the "is a bytecode object" tag, which this layer's
        // `decode` already refuses (it has no spelling for it), so reaching here means the
        // value is a callable object.
        interp.call_value(callee, Value::Undefined, Vec::new())
    });
    runtime::result_value(context, result)
}

/// `JS_NewObjectProtoClass`'s companion: the class id of a value, or 0.
///
/// `JS_GetAnyOpaque`: the payload of a host class instance, plus its class id.
///
/// # Safety
///
/// `class_id` must be null or writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetAnyOpaque(obj: JsValue, class_id: *mut u32) -> *mut c_void {
    match unsafe { arg(obj) } {
        Some(Value::Object(object)) => {
            let id: u32 = object.host_class_id().map(|id| id.get()).unwrap_or(0);
            if !class_id.is_null() {
                // SAFETY: the caller guarantees a writable pointer.
                unsafe { *class_id = id };
            }
            object
                .host_opaque()
                .map(|opaque| opaque.as_ptr())
                .unwrap_or(std::ptr::null_mut())
                .cast()
        }
        _ => {
            if !class_id.is_null() {
                // SAFETY: as above.
                unsafe { *class_id = 0 };
            }
            std::ptr::null_mut()
        }
    }
}

/// `JS_NewObjectClass` is in `crate::objects`; `JSClassDef` is named here only so that the
/// import list above documents where a module's class comes from.
const _: Option<JSClassDef> = None;

/// `Hint` is named so that the import list records that `JS_ToPrimitive` lives in
/// `crate::conversions`, which is where a reader looking for it should go.
const _: Option<Hint> = None;