quickjs-capi 0.14.2

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
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
//! `JSRuntime` and `JSContext`: the objects C holds, and how a callback finds its way back.
//!
//! # The re-entrancy problem
//!
//! A C function installed by a module looks like this:
//!
//! ```c
//! static JSValue js_point_ctor(JSContext *ctx, JSValueConst new_target,
//!                              int argc, JSValueConst *argv) {
//!     JSPointData *s = js_mallocz(ctx, sizeof(*s));
//!     if (JS_ToInt32(ctx, &s->x, argv[0])) goto fail;
//!     JSValue obj = JS_NewObjectProtoClass(ctx, proto, js_point_class_id);
//!     ...
//! }
//! ```
//!
//! Every line of it calls back into us with nothing but a `JSContext *`. Meanwhile the
//! engine is *inside* a call — it holds a `&mut Interp` while it invokes the function, and
//! that same interpreter is what `JS_ToInt32` has to use. There is no second interpreter to
//! hand out.
//!
//! So a callback needs a channel back to the live interpreter that does not go through the
//! `Context` (which is mutably borrowed for the whole call). That channel is a
//! thread-local raw pointer, set around each C function invocation
//! ([`InterpGuard`]) and read by the API functions ([`current_interp`]). It is
//! expressible only with `unsafe`, and it is the reason this crate is on the `unsafe`
//! allow-list — see `docs/m15-plan.md` §3.
//!
//! # Why the context is boxed at a stable address
//!
//! `engine::Context<'rt>` borrows the runtime. `JS_NewContext` therefore has to promise the
//! borrow outlives the context, and it does so the only way an FFI layer can: the runtime
//! lives in a `Box` owned by the `JSRuntime`, and the context keeps `&'static Runtime` to
//! it. Free order is enforced — `JS_FreeRuntime` drops every context before the runtime —
//! so the reference never dangles, and the `'static` is a promise about the C handle's
//! lifetime rather than a lie about the Rust types.

use std::cell::{Cell, RefCell};
use std::rc::Rc;

use core::ffi::c_int;

use engine::Value;
use engine::interp::{Interp, JsResult, Signal};

use crate::alloc;
use crate::cdefs::{ClassFinalizer, ClassGCMark, ClassId, JSClassExoticMethods};
use crate::convert;
use crate::jsvalue::{self, JsValue};

/// The engine runtime plus the tables whose lifetime is the runtime's, not a context's.
pub struct JsRuntime {
    /// The engine runtime.
    ///
    /// Boxed twice over: the `Box` gives the address the contexts borrow, and it does not
    /// move when the `JSRuntime` itself is moved, which is what makes the `'static` borrow
    /// in `JS_NewContext` honest.
    pub(crate) engine: Box<engine::Runtime>,
    /// `JS_SetRuntimeOpaque`: the host's pointer, handed back untouched.
    opaque: Cell<*mut core::ffi::c_void>,
    /// `JS_SetRuntimeInfo`: a diagnostic label. Borrowed, per the header's lifetime note.
    info: Cell<*const core::ffi::c_char>,
    /// `JS_SetGCThreshold`: when the heap should collect.
    gc_threshold: Cell<usize>,
    /// `JS_SetInterruptHandler`'s callback and its opaque argument.
    ///
    /// One `Option` deep, not two: [`crate::cdefs::InterruptHandler`] is itself
    /// `Option<unsafe extern "C" fn>`, because that is how the header spells a nullable
    /// function pointer. Storing it with the opaque keeps the pair in one `Cell` read.
    interrupt: Cell<
        Option<(
            unsafe extern "C" fn(*mut JsRuntime, *mut core::ffi::c_void) -> core::ffi::c_int,
            *mut core::ffi::c_void,
        )>,
    >,
    /// `JS_SetCanBlock`.
    can_block: Cell<bool>,
    /// `JS_SetStripInfo`'s flags, recorded and not acted on.
    strip_info: Cell<core::ffi::c_int>,
    /// The atoms this runtime has interned.
    pub(crate) atoms: RefCell<crate::atoms::AtomTable>,
    /// `JS_SetModuleLoaderFunc`'s pair plus its opaque argument.
    module_loader: RefCell<Option<ModuleLoaderHooks>>,
    /// Every live context, so `JS_FreeRuntime` can drop them before the runtime goes.
    contexts: RefCell<Vec<*mut JsContext>>,
    /// Of those, the ones a host session owns and the runtime must not free.
    session_contexts: RefCell<Vec<*mut JsContext>>,
    /// The class table: what each id registered on this runtime does.
    ///
    /// Classes live on the runtime in the C API and on the interpreter here, so this table
    /// is the authority and each context mirrors it. That is what lets `JS_NewClass` take a
    /// `JSRuntime *` and still register somewhere a script can see.
    ///
    /// A `BTreeMap` rather than a `Vec` indexed by id, because ids are global (see
    /// [`allocate_class_id`]): a second runtime would otherwise have to allocate a slot for
    /// every id the first one ever handed out.
    classes: RefCell<std::collections::BTreeMap<ClassId, Rc<ClassDecl>>>,
}

/// What `JS_SetModuleLoaderFunc`/`JS_SetModuleLoaderFunc2` installed.
///
/// Kept on the runtime rather than pushed into a context, because the reference's signature
/// takes a `JSRuntime *` and a context created later has to inherit it.
#[derive(Clone, Copy)]
pub struct ModuleLoaderHooks {
    /// `JSModuleNormalizeFunc`.
    pub normalize: crate::cdefs::ModuleNormalizeFunc,
    /// `JSModuleLoaderFunc` — the one-argument form.
    pub loader: crate::cdefs::ModuleLoaderFunc,
    /// `JSModuleLoaderFunc2`, the form that also receives the import attributes.
    pub loader2: crate::cdefs::ModuleLoaderFunc2,
    /// `JSModuleCheckSupportedImportAttributes`.
    pub check_attrs: crate::cdefs::ModuleCheckAttrs,
    /// The host's context pointer.
    pub opaque: *mut core::ffi::c_void,
}

/// The next class id, shared by every runtime in the process.
///
/// The reference does the same (`js_class_id_alloc` is a file-level counter behind a mutex),
/// and the reason is that a class id lives in a C module's static data: the module is loaded
/// once, its `JS_NewClassID` runs once, and the id it remembers has to mean that class in
/// whichever runtime it is later registered with.
static NEXT_CLASS_ID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);

/// Allocate a class id (`JS_NewClassID`).
///
/// Starts at 1: zero is `JS_INVALID_CLASS_ID`, and `JS_GetOpaque(val, 0)` has to match
/// nothing. Needs no runtime, which is what makes it callable from a module's `JS_InitClass`
/// before any context exists.
pub fn allocate_class_id() -> ClassId {
    NEXT_CLASS_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
}

/// One class, as the C side declared it.
///
/// A copy of the `JSClassDef` fields rather than the struct itself, because the same class
/// has to be registered into every context's interpreter, and the engine's `ClassDef` owns
/// boxed closures — it cannot be cloned and must not be shared between interpreters.
#[derive(Clone, Copy)]
pub struct ClassDecl {
    /// `JSClassDef::finalizer`, called with the payload when an instance is released.
    pub finalizer: ClassFinalizer,
    /// `JSClassDef::gc_mark`.
    pub gc_mark: ClassGCMark,
    /// `JSClassDef::exotic`.
    pub exotic: *const JSClassExoticMethods,
    /// The name, for diagnostics.
    pub name: *const core::ffi::c_char,
}

/// `JSContext`: one interpreter, its pending exception, and its runtime back-pointer.
pub struct JsContext {
    /// Where this context's interpreter comes from.
    source: ContextSource,
    /// The exception a failed API call left for `JS_GetException`.
    ///
    /// The reference keeps exactly one per context, and the rule is the same: a C function
    /// that raises stores it and answers [`jsvalue::EXCEPTION`]; the caller either
    /// propagates that (`return JS_EXCEPTION`) or clears it with `JS_GetException`.
    pending: RefCell<Option<Value>>,
    /// The runtime this context belongs to, for `JS_GetRuntime`.
    runtime: Cell<*mut JsRuntime>,
    /// The C modules this context created, so they are freed with it.
    ///
    /// `JS_NewCModule` hands C a `JSModuleDef *` that C keeps for as long as the module
    /// lives, and the reference frees it with the context. Ownership therefore sits here,
    /// with the pointers leaked on purpose until [`JsContext::free_modules`] runs.
    modules: RefCell<Vec<*mut crate::cdefs::JsModuleDef>>,
    /// `JS_SetContextOpaque`: the host's pointer.
    opaque: Cell<*mut core::ffi::c_void>,
    /// `JS_SetContextValue`'s slots, indexed by `idx` (a `BTreeMap` so a sparse index
    /// costs only the slots used).
    values: RefCell<std::collections::BTreeMap<core::ffi::c_int, Value>>,
    /// `JS_DupContext`'s count: how many `JS_FreeContext` calls are still owed.
    ///
    /// The reference keeps the same count in the context's header. Without it a host that
    /// duplicates a context it hands to a callback — the documented reason the function
    /// exists — would free the context out from under itself on the first release, which is
    /// a use-after-free that shows up as a crash somewhere else entirely.
    dups: Cell<usize>,
}

/// Where a context's interpreter comes from.
pub enum ContextSource {
    /// A context that owns one (`JS_NewContext`). The `RefCell` is what lets the API's
    /// `*mut JSContext` be a shared reference: the alternative is one long-lived `&mut` per
    /// entry point, which the re-entrant callback path would alias on every call.
    Owned(RefCell<Box<engine::Context<'static>>>),
    /// A context that *is* whatever interpreter is current — the one a `.so` module's
    /// `js_init_module` runs against.
    ///
    /// A native module is loaded from inside a running script, so its `JSContext *` has to
    /// be the interpreter the engine is already inside. There is no second interpreter to
    /// own, and owning one would be wrong: `JS_GetOpaque` and class registration have to
    /// reach the same objects the importing script sees.
    Attached,
}

thread_local! {
    /// The interpreter of the C function currently running, if any.
    ///
    /// Raw and lifetime-erased on purpose: the pointee is a `&mut Interp<'rt>` the engine
    /// is holding one frame up, and the only thing that may be done with it here is to use
    /// it for the duration of the callback. [`InterpGuard`] restores the previous value on
    /// drop, so nesting works.
    static CURRENT_INTERP: Cell<*mut Interp<'static>> = const { Cell::new(std::ptr::null_mut()) };
    /// The context of the C function currently running, if any.
    static CURRENT_CONTEXT: Cell<*mut JsContext> = const { Cell::new(std::ptr::null_mut()) };
    /// The runtime whose finalizer is running, plus the payload it was given.
    ///
    /// A finalizer is called with `(JSRuntime *, JSValue val)` and by definition the object
    /// behind `val` is already being destroyed — there is no `JSValue` left to pass. So the
    /// value handed over is a *sentinel* whose payload is [`FINALIZER_SENTINEL`], and
    /// `JS_GetOpaque` answers from this cell instead of from an object. It is the one place
    /// where "read the payload off the value" cannot work, and the reference has the same
    /// hole (it keeps the half-dead object's fields readable).
    static FINALIZING: Cell<Option<(*mut JsRuntime, ClassId, *mut ())>> = const { Cell::new(None) };
}

/// The payload of the `JSValue` a finalizer is handed.
///
/// Address 1 is never a real allocation: every block this crate allocates is at least
/// 8-byte aligned, and no allocator returns a pointer into the first page. Written as a
/// `const` dereference of the canonical dangling pointer rather than a cast, which is the
/// same address through a spelling `clippy` does not have to guess about.
pub const FINALIZER_SENTINEL: *mut () = std::ptr::dangling_mut::<()>();

impl JsRuntime {
    /// `JS_NewRuntime`.
    pub fn new() -> Box<JsRuntime> {
        Box::new(JsRuntime {
            engine: Box::new(engine::Runtime::new()),
            opaque: Cell::new(std::ptr::null_mut()),
            info: Cell::new(std::ptr::null()),
            gc_threshold: Cell::new(0),
            interrupt: Cell::new(None),
            can_block: Cell::new(true),
            strip_info: Cell::new(0),
            atoms: RefCell::new(crate::atoms::AtomTable::new()),
            module_loader: RefCell::new(None),
            contexts: RefCell::new(Vec::new()),
            session_contexts: RefCell::new(Vec::new()),
            classes: RefCell::new(std::collections::BTreeMap::new()),
        })
    }

    /// `JS_GetRuntimeOpaque`.
    pub fn opaque(&self) -> *mut core::ffi::c_void {
        self.opaque.get()
    }

    /// `JS_SetRuntimeOpaque`.
    pub fn set_opaque(&self, opaque: *mut core::ffi::c_void) {
        self.opaque.set(opaque);
    }

    /// `JS_GetRuntimeInfo`, which the reference does not export but `JS_SetRuntimeInfo` sets.
    pub fn info(&self) -> *const core::ffi::c_char {
        self.info.get()
    }

    /// `JS_SetRuntimeInfo`.
    pub fn set_info(&self, info: *const core::ffi::c_char) {
        self.info.set(info);
    }

    /// `JS_SetGCThreshold`. A threshold of `0` means "collect on every allocation", which is
    /// not worth reproducing; the value is kept and used by [`JsRuntime::maybe_collect`].
    pub fn set_gc_threshold(&self, threshold: usize) {
        self.gc_threshold.set(threshold);
    }

    /// `JS_GetGCThreshold`, our addition: the threshold the host set.
    pub fn gc_threshold(&self) -> usize {
        self.gc_threshold.get()
    }

    /// `JS_SetInterruptHandler`.
    pub fn set_interrupt_handler(
        &self,
        callback: crate::cdefs::InterruptHandler,
        opaque: *mut core::ffi::c_void,
    ) {
        // `callback` is already an `Option<fn>`: the header's handler pointer, null or not.
        self.interrupt
            .set(callback.map(|callback| (callback, opaque)));
    }

    /// The installed interrupt handler, if any.
    pub fn interrupt_handler(
        &self,
    ) -> Option<(
        unsafe extern "C" fn(*mut JsRuntime, *mut core::ffi::c_void) -> core::ffi::c_int,
        *mut core::ffi::c_void,
    )> {
        self.interrupt.get()
    }

    /// `JS_SetCanBlock`.
    pub fn set_can_block(&self, can_block: bool) {
        self.can_block.set(can_block);
    }

    /// Whether a blocking operation is allowed (`JS_SetCanBlock`'s answer).
    pub fn can_block(&self) -> bool {
        self.can_block.get()
    }

    /// `JS_SetModuleLoaderFunc`/`JS_SetModuleLoaderFunc2`'s state.
    pub fn module_loader_hooks(&self) -> Option<ModuleLoaderHooks> {
        *self.module_loader.borrow()
    }

    /// Record the module loader hooks.
    pub fn set_module_loader_hooks(&self, hooks: ModuleLoaderHooks) {
        *self.module_loader.borrow_mut() = Some(hooks);
    }

    /// Every live context, for the API functions that take a `JSRuntime *`.
    pub fn live_contexts(&self) -> Vec<*mut JsContext> {
        self.contexts.borrow().clone()
    }

    /// The engine runtime as a raw pointer, for the API functions that need `&mut`.
    ///
    /// A `*mut` rather than a reference because `JS_SetMemoryLimit` takes a `JSRuntime *` and
    /// has no borrow to hand out; the caller forms the `&mut` under the single-threaded-per-
    /// runtime contract the C API states.
    pub fn engine_ptr(&self) -> *const engine::Runtime {
        self.engine.as_ref() as *const engine::Runtime
    }

    /// `JS_SetStripInfo`'s recorded flags.
    pub fn strip_info(&self) -> core::ffi::c_int {
        self.strip_info.get()
    }

    /// Record the strip-info flags.
    pub fn set_strip_info(&self, flags: core::ffi::c_int) {
        self.strip_info.set(flags);
    }

    /// The engine runtime, for the context that has to borrow it.
    fn engine_ref(&self) -> &'static engine::Runtime {
        // SAFETY: `engine` is a `Box` owned by this runtime, and the borrow is handed to a
        // context that this runtime outlives — `JS_FreeRuntime` drops every context first.
        unsafe { &*(self.engine.as_ref() as *const engine::Runtime) }
    }

    /// `JS_NewClass`: register (or replace) the class under `id`.
    ///
    /// Answers `false` for `JS_INVALID_CLASS_ID`, which the C API reports as `-1`.
    pub fn define_class(&self, id: ClassId, decl: ClassDecl) -> bool {
        if id == 0 {
            return false;
        }
        self.classes.borrow_mut().insert(id, Rc::new(decl));
        // Mirror it into every live context: a class registered before a context existed,
        // or after another one did, has to be visible from all of them.
        for &context in self.contexts.borrow().iter() {
            // SAFETY: the pointer is live until `JS_FreeContext`, which removes it from
            // this list.
            unsafe { (*context).register_class(id, decl) };
        }
        true
    }

    /// The class registered under `id`, if any.
    pub fn class(&self, id: ClassId) -> Option<Rc<ClassDecl>> {
        self.classes.borrow().get(&id).cloned()
    }

    /// Whether `id` names a registered class.
    pub fn has_class(&self, id: ClassId) -> bool {
        self.class(id).is_some()
    }

    /// Track a context so it can be dropped with the runtime.
    fn adopt(&self, context: *mut JsContext) {
        self.contexts.borrow_mut().push(context);
    }

    /// Track a context the host owns, for as long as a script runs.
    ///
    /// The context is *not* dropped with the runtime: the host session owns it, and the
    /// runtime only borrows it to reach the interpreter class registration has to write to.
    /// `JS_FreeRuntime` therefore skips it, which is why this is a separate entry point from
    /// [`JsRuntime::adopt`].
    ///
    /// # Safety
    ///
    /// `context` must stay alive until [`JsRuntime::disown`] is called with it.
    pub unsafe fn adopt_for_session(&self, context: *mut JsContext) {
        self.session_contexts.borrow_mut().push(context);
        self.adopt(context);
    }

    /// Forget a context from [`JsRuntime::adopt_for_session`].
    ///
    /// # Safety
    ///
    /// `context` must have been adopted by `adopt_for_session` and not disowned since.
    pub unsafe fn disown(&self, context: *mut JsContext) {
        self.contexts.borrow_mut().retain(|&live| live != context);
        self.session_contexts
            .borrow_mut()
            .retain(|&live| live != context);
    }

    /// `JS_FreeRuntime`: drop every context, then the runtime.
    ///
    /// # Safety
    ///
    /// `runtime` must come from [`JsRuntime::new`] via `Box::into_raw`, and no context or
    /// class handle may be used afterwards.
    pub unsafe fn free(runtime: *mut JsRuntime) {
        if runtime.is_null() {
            return;
        }
        // SAFETY: the caller guarantees this pointer came from `Box::into_raw`.
        let runtime = unsafe { Box::from_raw(runtime) };
        // Contexts first: each one borrows the runtime, so dropping them afterwards would
        // be a use-after-free. `drain` also keeps the vector from being seen half-empty.
        let contexts: Vec<*mut JsContext> = runtime.contexts.borrow_mut().drain(..).collect();
        let borrowed: Vec<*mut JsContext> =
            runtime.session_contexts.borrow_mut().drain(..).collect();
        for context in contexts {
            if borrowed.contains(&context) {
                // A host session's context: someone else owns it, and it is about to be
                // dropped by them. Freeing it here would be a double free.
                continue;
            }
            // SAFETY: each pointer was created by `Box::into_raw` in `JsContext::new` and is
            // still owned here.
            drop(unsafe { Box::from_raw(context) });
        }
    }
}

impl JsContext {
    /// `JS_DupContext`: one more release is owed before this context dies.
    pub fn raise_refs(&self) {
        self.dups.set(self.dups.get().saturating_add(1));
    }

    /// `JS_FreeContext`: answer whether this call released the context or only a count.
    ///
    /// Split out so [`JS_FreeContext`] stays a three-line function: the count is only valid
    /// while the context is alive, so it has to be read *before* the `Box` is rebuilt.
    fn release_ref(&self) -> bool {
        let count = self.dups.get();
        if count == 0 {
            return true;
        }
        self.dups.set(count - 1);
        false
    }

    /// `JS_NewContext`.
    ///
    /// # Safety
    ///
    /// `runtime` must be a live pointer from `Box::into_raw(JsRuntime::new())`.
    pub unsafe fn new(runtime: *mut JsRuntime) -> *mut JsContext {
        // SAFETY: the caller guarantees the runtime is live.
        let runtime_ref = unsafe { &*runtime };
        let engine = engine::Context::new(runtime_ref.engine_ref());
        let context = Box::new(JsContext {
            source: ContextSource::Owned(RefCell::new(Box::new(engine))),
            pending: RefCell::new(None),
            runtime: Cell::new(runtime),
            modules: RefCell::new(Vec::new()),
            opaque: Cell::new(std::ptr::null_mut()),
            values: RefCell::new(std::collections::BTreeMap::new()),
            dups: Cell::new(0),
        });
        // The classes the runtime already knows about have to exist in this interpreter
        // too: `JS_NewClass` may well have been called before `JS_NewContext`.
        let classes: Vec<(ClassId, ClassDecl)> = runtime_ref
            .classes
            .borrow()
            .iter()
            .map(|(&id, decl)| (id, **decl))
            .collect();
        let context = context;
        for (id, decl) in classes {
            context.register_class(id, decl);
        }
        let raw = Box::into_raw(context);
        runtime_ref.adopt(raw);
        raw
    }

    /// A context standing for whatever interpreter is running.
    ///
    /// Used by the native module loader: `js_init_module` is called from inside a script's
    /// `import`, so the `JSContext *` it receives has to address the interpreter that is
    /// already executing. The returned handle borrows nothing for the same reason — it has
    /// no interpreter of its own, and only ever reads the published one.
    pub fn attached(runtime: *mut JsRuntime) -> JsContext {
        JsContext {
            source: ContextSource::Attached,
            pending: RefCell::new(None),
            runtime: Cell::new(runtime),
            modules: RefCell::new(Vec::new()),
            opaque: Cell::new(std::ptr::null_mut()),
            values: RefCell::new(std::collections::BTreeMap::new()),
            // An attached context is a borrowed view of a running interpreter; it is never
            // freed through `JS_FreeContext`, so it has no releases owed.
            dups: Cell::new(0),
        }
    }

    /// `JS_GetContextOpaque`.
    pub fn opaque(&self) -> *mut core::ffi::c_void {
        self.opaque.get()
    }

    /// `JS_SetContextOpaque`.
    pub fn set_opaque(&self, opaque: *mut core::ffi::c_void) {
        self.opaque.set(opaque);
    }

    /// `JS_GetContextValue`: the value at slot `idx`, if one was stored.
    pub fn value(&self, idx: core::ffi::c_int) -> Option<Value> {
        self.values.borrow().get(&idx).cloned()
    }

    /// `JS_SetContextValue`.
    pub fn set_value(&self, idx: core::ffi::c_int, value: Value) {
        self.values.borrow_mut().insert(idx, value);
    }

    /// The runtime this context belongs to.
    pub fn runtime(&self) -> *mut JsRuntime {
        self.runtime.get()
    }

    /// Register `decl` under `id` in this context's interpreter.
    fn register_class(&self, id: ClassId, decl: ClassDecl) {
        let definition = self.class_definition(id, decl);
        self.with_current_interp(|interp| {
            interp.define_host_class(engine::ClassId::from_raw(id), definition);
        });
    }

    /// Turn a C class declaration into the engine's `ClassDef`.
    ///
    /// The finalizer and `gc_mark` become closures that call back into C. The finalizer
    /// needs a `JSRuntime *`, which it gets from the thread-local that
    /// [`JsContext::with_interp`] set — a finalizer runs from `Drop`, at which point there
    /// is no interpreter to ask.
    fn class_definition(&self, id: ClassId, decl: ClassDecl) -> engine::ClassDef {
        let name = if decl.name.is_null() {
            format!("<class {id}>")
        } else {
            // SAFETY: `JSClassDef::class_name` is a NUL-terminated string the C module
            // keeps alive for the life of the module, which is the life of the process.
            unsafe { core::ffi::CStr::from_ptr(decl.name) }
                .to_string_lossy()
                .into_owned()
        };
        let mut definition = engine::ClassDef::new(name);
        if let Some(finalizer) = decl.finalizer {
            let runtime = self.runtime.get();
            definition = definition.with_finalizer(Box::new(move |_class_id, opaque| {
                call_finalizer(runtime, id, finalizer, opaque);
            }));
        }
        let _ = decl.gc_mark;
        let _ = decl.exotic;
        definition
    }

    /// Run `f` with the interpreter a C API call should use.
    ///
    /// Two cases, and they are the whole re-entrancy story:
    ///
    /// * a C callback is running — [`current_interp`] has the interpreter the engine is
    ///   inside, and re-borrowing this context's would panic;
    /// * nothing is running — the call came from C at top level, so this context's own
    ///   interpreter is the right one and [`JsContext::with_interp`] can lend it out.
    ///
    /// Every exported function that has to run JavaScript goes through here, which is why
    /// none of them carries its own "am I inside a callback" check.
    pub fn with_current_interp<R>(&self, f: impl FnOnce(&mut Interp<'static>) -> R) -> R {
        match current_interp() {
            Some(interp) => f(interp),
            None => self.with_interp(f),
        }
    }

    /// Run `f` with the engine context, publishing its interpreter for the C code `f` may
    /// call.
    ///
    /// Every *entry point* — `JS_Eval`, and later `JS_Call` — goes through here rather than
    /// straight to the engine. Without the guard a script that calls a C function arrives
    /// with no current context, and every API call inside that function answers an exception
    /// it cannot even describe. The failure looks like a broken C module rather than a
    /// missed guard, which is why this is the one helper everything funnels through.
    pub fn with_context<R>(&self, f: impl FnOnce(&mut engine::Context<'static>) -> R) -> R {
        let ContextSource::Owned(engine) = &self.source else {
            panic!("an attached context has no engine of its own");
        };
        let mut engine = engine.borrow_mut();
        let engine: &mut engine::Context<'static> = &mut engine;
        self.sync_interrupt_hook(engine.interp_mut());
        // SAFETY: the pointer is only used while the borrow lives, and the guard clears it
        // before this scope ends.
        let interp: *mut Interp<'static> = engine.interp_mut();
        let guard = InterpGuard::enter(interp, self);
        let result = f(engine);
        drop(guard);
        result
    }

    /// Set the interpreter's stack budget, for a limit set after the context was created.
    pub fn set_stack_limit(&self, limit: usize) {
        if matches!(self.source, ContextSource::Attached) {
            // An attached context has no engine of its own: its stack budget belongs to the
            // host's interpreter, which the host already set.
            return;
        }
        self.with_context(|engine| {
            // `with_context` installs the *interrupt* hook on the way in; the budget is a
            // plain field of the interpreter, so it is written here.
            engine.interp_mut().stack_limit = limit;
        });
    }

    /// Install the interrupt closure into this context's interpreter, if it has one.
    ///
    /// Called from `JS_SetInterruptHandler`, because a context that already evaluated
    /// something owns its interpreter and would otherwise never see a handler set afterwards.
    pub fn install_interrupt_hook(&self) {
        let runtime = self.runtime.get();
        // SAFETY: the runtime outlives this context, and the pointer is only read.
        if unsafe { runtime.as_ref() }.is_none() {
            return;
        }
        if matches!(self.source, ContextSource::Attached) {
            // An attached context has no engine of its own: it is the C API's view of the
            // interpreter the *host* is running, so the hook belongs to the host's engine.
            return;
        }
        self.with_context(|engine| {
            let _ = engine;
        });
    }

    /// Whether the runtime has no interrupt handler, read through the back-pointer.
    fn runtime_interrupt_is_unset(&self) -> bool {
        // SAFETY: the runtime outlives this context.
        match unsafe { self.runtime.get().as_ref() } {
            Some(runtime) => runtime.interrupt_handler().is_none(),
            None => true,
        }
    }

    /// Make sure the engine polls this runtime's interrupt handler.
    ///
    /// Installed once per interpreter, as a closure that re-reads the runtime's `Cell` on every
    /// poll — so a handler set *after* the first evaluation still takes effect, which is the
    /// ordering a host that sets it late expects. The pointer is the runtime's, and the runtime
    /// outlives every context it adopted, which is what makes the `'static` box sound.
    pub(crate) fn sync_interrupt_hook(&self, interp: &mut Interp<'static>) {
        if interp.interrupt.is_some() || self.runtime_interrupt_is_unset() {
            // Nothing to install, or nothing to install it *for*: a runtime whose host never
            // asked for an interrupt keeps the zero-cost path, which is every benchmark and
            // every test262 run.
            return;
        }
        // SAFETY: the runtime outlives the interpreter (a context is freed before its
        // runtime), so the raw pointer stays valid for as long as the closure can run.
        let runtime: *const JsRuntime = self.runtime.get();
        interp.interrupt = Some(Box::new(move || {
            let Some(runtime) = (unsafe { runtime.as_ref() }) else {
                return false;
            };
            match runtime.interrupt_handler() {
                // SAFETY: the callback is the host's; the header's contract is that it is a
                // `JSInterruptHandler` and the runtime is live, both of which the setter
                // guarantees.
                Some((callback, opaque)) => {
                    // SAFETY: the callback is the host's `JSInterruptHandler`, set through
                    // `JS_SetInterruptHandler`, and the runtime it was given is this one.
                    unsafe { callback(runtime as *const _ as *mut _, opaque) != 0 }
                }
                None => false,
            }
        }));
    }

    /// Run `f` with the interpreter, publishing it for the C code `f` may call.
    ///
    /// The guard is what makes a nested API call work: while `f` runs, `JS_*` functions
    /// called from C find this interpreter through [`current_interp`]. `f` receives the
    /// same `&mut` the guard published, so nothing is aliased that `f` itself did not hand
    /// to C.
    pub fn with_interp<R>(&self, f: impl FnOnce(&mut Interp<'static>) -> R) -> R {
        self.with_context(|engine| f(engine.interp_mut()))
    }

    /// `JS_GetException`: take the pending exception, if there is one.
    pub fn take_pending(&self) -> Option<Value> {
        self.pending.borrow_mut().take()
    }

    /// Store an exception for `JS_GetException` to return.
    pub fn set_pending(&self, value: Value) {
        *self.pending.borrow_mut() = Some(value);
    }

    /// Whether a call left an exception behind.
    pub fn has_pending(&self) -> bool {
        self.pending.borrow().is_some()
    }
}

/// Publishes a live interpreter for the duration of a C callback.
pub struct InterpGuard {
    previous_interp: *mut Interp<'static>,
    previous_context: *mut JsContext,
}

impl InterpGuard {
    /// Make `interp` and `context` the current ones until the guard is dropped.
    fn enter(interp: *mut Interp<'static>, context: &JsContext) -> InterpGuard {
        // The pointer C will pass back to us has to be the boxed context, not this borrow;
        // `JsContext::with_interp` is only ever reached through `*mut JSContext`, so the
        // borrow and the box are the same address.
        let pointer = context as *const JsContext as *mut JsContext;
        let previous_interp = CURRENT_INTERP.with(|cell| cell.replace(interp));
        let previous_context = CURRENT_CONTEXT.with(|cell| cell.replace(pointer));
        InterpGuard {
            previous_interp,
            previous_context,
        }
    }
}

impl Drop for InterpGuard {
    fn drop(&mut self) {
        CURRENT_INTERP.with(|cell| cell.set(self.previous_interp));
        CURRENT_CONTEXT.with(|cell| cell.set(self.previous_context));
    }
}

/// Publish `interp` (and `context`) for as long as the guard lives.
///
/// The native module loader uses this: it has the running interpreter as a `&mut` and needs
/// the C API to see it. Everything the module does — `JS_NewClass`, `JS_ToInt32`,
/// `JS_NewObject` — then runs against that interpreter rather than a second one.
pub fn publish(interp: *mut Interp<'static>, context: &JsContext) -> InterpGuard {
    InterpGuard::enter(interp, context)
}

/// The interpreter of the C code currently running.
///
/// `None` outside a callback: a C module must not call the API from its own thread with no
/// call in progress, and the reference would have no `ctx` to pass either.
pub fn current_interp() -> Option<&'static mut Interp<'static>> {
    CURRENT_INTERP.with(|cell| {
        let pointer = cell.get();
        if pointer.is_null() {
            None
        } else {
            // SAFETY: `InterpGuard` published a live interpreter for exactly the duration of
            // the callback this call is running inside; the engine's own `&mut` is
            // suspended while the callback runs.
            Some(unsafe { &mut *pointer })
        }
    })
}

/// The context of the C code currently running.
pub fn current_context() -> Option<&'static JsContext> {
    CURRENT_CONTEXT.with(|cell| {
        let pointer = cell.get();
        if pointer.is_null() {
            None
        } else {
            // SAFETY: as `current_interp` — the pointer was published for this callback.
            Some(unsafe { &*pointer })
        }
    })
}

/// Call a C finalizer, with the runtime and the sentinel value it expects.
fn call_finalizer(
    runtime: *mut JsRuntime,
    class_id: ClassId,
    finalizer: unsafe extern "C" fn(*mut core::ffi::c_void, JsValue),
    opaque: engine::Opaque,
) {
    let sentinel = JsValue::mkptr(jsvalue::TAG_OBJECT, FINALIZER_SENTINEL);
    let previous = FINALIZING.with(|cell| cell.replace(Some((runtime, class_id, opaque.as_ptr()))));
    // SAFETY: the C module registered this function pointer as a `JSClassFinalizer`, whose
    // signature it is; the sentinel is only ever read by `JS_GetOpaque`, which consults
    // `FINALIZING` rather than dereferencing it.
    unsafe { finalizer(runtime.cast(), sentinel) };
    FINALIZING.with(|cell| cell.set(previous));
}

/// The payload a finalizer's sentinel value stands for, when `class_id` matches.
pub fn finalizer_opaque(class_id: ClassId) -> Option<*mut ()> {
    FINALIZING.with(|cell| match cell.get() {
        Some((_, id, opaque)) if id == class_id => Some(opaque),
        _ => None,
    })
}

/// The runtime a finalizer is running for.
pub fn finalizer_runtime() -> Option<*mut JsRuntime> {
    FINALIZING.with(|cell| cell.get().map(|(runtime, _, _)| runtime))
}

/// Whether `value` is the sentinel a finalizer is handed.
pub fn is_finalizer_sentinel(value: JsValue) -> bool {
    value.payload() == FINALIZER_SENTINEL as usize as u64 && value.is_object()
}

// ---------------------------------------------------------------------------
// The conventions every exported function shares
// ---------------------------------------------------------------------------

/// Turn an engine result into the `JSValue` a C caller expects.
///
/// The one rule the whole API follows: an owned value becomes a boxed `JSValue`, and a
/// failure becomes [`jsvalue::EXCEPTION`] with the reason stored as the context's pending
/// exception. `JS_ToInt32(ctx, …, v)` then answers `-1`, the C function returns
/// `JS_EXCEPTION`, and the trampoline that invoked it turns the pending exception into the
/// engine's `Signal::Throw`.
pub fn result_value(context: &JsContext, result: JsResult<Value>) -> JsValue {
    match result {
        Ok(value) => convert::encode(&value),
        Err(signal) => {
            let thrown = match signal {
                Signal::Throw(value) => value,
                Signal::OutOfMemory => context.throw_out_of_memory(),
            };
            context.set_pending(thrown);
            jsvalue::EXCEPTION
        }
    }
}

impl JsContext {
    /// Free the C modules this context created.
    ///
    /// Called from `JS_FreeContext`, before the context's interpreter goes: a module's
    /// `JSModuleDef` holds export values, which are engine handles.
    fn free_modules(&self) {
        for pointer in self.modules.borrow_mut().drain(..) {
            // SAFETY: each pointer was created by `JS_NewCModule` in this context and is
            // still owned here.
            drop(unsafe { Box::from_raw(pointer) });
        }
    }

    /// The C modules this context created.
    pub fn module_table(&self) -> &RefCell<Vec<*mut crate::cdefs::JsModuleDef>> {
        &self.modules
    }

    /// A `RangeError`/`InternalError` for a failed allocation, as a pending exception.
    pub fn throw_out_of_memory(&self) -> Value {
        // Through `with_current_interp`, not `engine.borrow_mut()`: this is reached from a
        // failing allocation *inside* a callback, where the context's own borrow is already
        // held by the entry point that is running us.
        self.with_current_interp(|interp| interp.make_error("InternalError", "out of memory"))
    }
}

/// `JS_ThrowRangeError`-style error, stored as the pending exception of `context`.
pub fn throw_error(context: &JsContext, name: &str, message: &str) -> JsValue {
    // Build the error with whichever interpreter is current: this is called from inside a
    // callback as often as from a top-level API call, and the borrow has to follow.
    let value = context.with_current_interp(|interp| interp.make_error(name, message));
    context.set_pending(value);
    jsvalue::EXCEPTION
}

/// Decode an argument a C caller passed in.
///
/// A reference-counted value is a box this crate produced; the clone keeps the engine value
/// alive independently, so nothing has to be freed here. `argv` entries are *borrowed* by
/// the C API's convention and must not be released by us.
///
/// # Safety
///
/// `value` must be a `JSValue` from this crate, and a reference-counted one must be live.
pub unsafe fn argument(value: JsValue) -> Option<Value> {
    // SAFETY: the caller guarantees the value is ours and alive.
    unsafe { convert::decode(value) }
}

/// Release the reference a returned `JSValue` held, after taking what we need from it.
///
/// The C API's convention is that every function returning a `JSValue` returns a *new* reference:
/// the caller owns it and must free it. When the caller is us — the trampoline around a C
/// function, or a Rust-side test — the box has to be released once the engine value has been
/// cloned out, or the payload leaks for the life of the process.
///
/// # Safety
///
/// `value` must be an owned `JSValue` from this crate that is not used afterwards.
pub unsafe fn release(value: JsValue) {
    if !value.has_ref_count() {
        return;
    }
    if is_finalizer_sentinel(value) {
        return;
    }
    let Some(payload) = value.as_ptr() else {
        return;
    };
    // Exactly what the header's inline `JS_FreeValue` does, and for the same reason: a value
    // can have several owners. `JS_DupValue` exists precisely so that two holders can each
    // free their own claim, and handing a duplicated value to an API function that consumes
    // it must not free the other holder's payload. An earlier version of this function freed
    // unconditionally and made `JS_SetClassProto(ctx, id, JS_DupValue(ctx, ctor))` — the
    // reference's own idiom — a use-after-free.
    // SAFETY: the caller owns one reference to a live box.
    let count = unsafe { alloc::ValueBox::ref_count(payload) } - 1;
    // SAFETY: as above.
    unsafe { alloc::ValueBox::set_ref_count(payload, count) };
    if count <= 0 {
        // SAFETY: the count just reached zero, so this was the last reference.
        unsafe { alloc::free_value(payload) };
    }
}

// ---------------------------------------------------------------------------
// The exported entry points: runtime, context, evaluation, exceptions
// ---------------------------------------------------------------------------

/// `JS_NewRuntime`.
#[unsafe(no_mangle)]
pub extern "C" fn JS_NewRuntime() -> *mut JsRuntime {
    Box::into_raw(JsRuntime::new())
}

/// `JS_FreeRuntime`: drop the runtime and every context it still owns.
///
/// # Safety
///
/// `rt` must come from `JS_NewRuntime`, and every `JSContext *` derived from it must be
/// considered dead afterwards.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_FreeRuntime(rt: *mut JsRuntime) {
    // SAFETY: the caller's contract.
    unsafe { JsRuntime::free(rt) }
}

/// `JS_NewContext`.
///
/// # Safety
///
/// `rt` must be a live runtime.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewContext(rt: *mut JsRuntime) -> *mut JsContext {
    if rt.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: the caller's contract.
    unsafe { JsContext::new(rt) }
}

/// `JS_FreeContext`: drop one context, leaving its runtime alive.
///
/// # Safety
///
/// `ctx` must come from `JS_NewContext` and not have been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_FreeContext(ctx: *mut JsContext) {
    if ctx.is_null() {
        return;
    }
    // A duplicated context is not freed until every `JS_DupContext` has been paired with a
    // release, which is the reference's contract and the whole point of the function.
    if let Some(context) = unsafe { ctx.as_ref() } {
        if !context.release_ref() {
            return;
        }
    }
    // SAFETY: the caller's contract.
    let context = unsafe { Box::from_raw(ctx) };
    context.free_modules();
    // SAFETY: the runtime outlives every context it adopted — `JS_FreeRuntime` drops
    // contexts first — so the back-pointer is still valid here.
    if let Some(runtime) = unsafe { context.runtime().as_ref() } {
        // SAFETY: `ctx` is the context being freed, and it is removed from the runtime's
        // lists before the runtime could ever reach it again.
        unsafe { runtime.disown(ctx) };
    }
}

/// `JS_GetException`: the pending exception as a new reference, or `null` when there is
/// none.
///
/// # Safety
///
/// `ctx` must be a live context.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetException(ctx: *mut JsContext) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::NULL;
    };
    match context.take_pending() {
        Some(value) => convert::encode(&value),
        // The reference answers `JS_NULL` rather than `JS_UNDEFINED`, so a script that
        // reads `.message` off it gets a `TypeError` instead of `undefined`.
        None => jsvalue::NULL,
    }
}

/// `JS_Throw`: replace the pending exception with `obj`, answering `JS_EXCEPTION`.
///
/// # Safety
///
/// `ctx` must be a live context and `obj` a live `JSValue` whose reference this call
/// consumes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_Throw(ctx: *mut JsContext, obj: JsValue) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let value = unsafe { argument(obj) }.unwrap_or(Value::Undefined);
    // SAFETY: the C API consumes the reference it was handed.
    unsafe { release(obj) };
    context.set_pending(value);
    jsvalue::EXCEPTION
}

/// `JS_Eval`: compile and run `input` as global (or module) code.
///
/// The thrown value travels through the pending-exception slot rather than being turned
/// into text, which is the whole point: `JS_GetException` then hands C the object the script
/// threw, with its `message`, its `stack` and any property a host put on it.
///
/// Module evaluation needs a module loader, which is S4's `dlopen` work; a module eval here
/// reports a `TypeError` instead of pretending to have run.
///
/// # Safety
///
/// `ctx` must be a live context, and `input` must point at `input_len` readable bytes;
/// `filename` may be null or a NUL-terminated string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_Eval(
    ctx: *mut JsContext,
    input: *const core::ffi::c_char,
    input_len: usize,
    filename: *const core::ffi::c_char,
    eval_flags: core::ffi::c_int,
) -> JsValue {
    // SAFETY: the caller's contract is this function's.
    unsafe { eval_with_this_raw(ctx, input, input_len, filename, eval_flags, None) }
}

/// The body of `JS_Eval` and `JS_EvalThis`, which differ only in the receiver.
///
/// Split out rather than duplicated because everything below — the null and module checks,
/// the choice between the running interpreter and this context's own, the pending-exception
/// protocol — has to be identical for the two. A second copy is how `JS_EvalThis` came to
/// ignore its `this_obj` in the first place.
///
/// # Safety
///
/// As [`JS_Eval`]; `this` must be a live engine value when present.
pub(crate) unsafe fn eval_with_this_raw(
    ctx: *mut JsContext,
    input: *const core::ffi::c_char,
    input_len: usize,
    filename: *const core::ffi::c_char,
    eval_flags: core::ffi::c_int,
    this: Option<Value>,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    if input.is_null() {
        return throw_error(context, "TypeError", "null source");
    }
    // SAFETY: the caller guarantees `input_len` readable bytes.
    let bytes = unsafe { core::slice::from_raw_parts(input.cast::<u8>(), input_len) };
    let source = String::from_utf8_lossy(bytes).into_owned();
    let name = if filename.is_null() {
        "<input>".to_string()
    } else {
        // SAFETY: the caller guarantees a NUL-terminated string.
        unsafe { core::ffi::CStr::from_ptr(filename) }
            .to_string_lossy()
            .into_owned()
    };

    const JS_EVAL_TYPE_MODULE: core::ffi::c_int = 1 << 0;
    if eval_flags & JS_EVAL_TYPE_MODULE != 0 {
        return throw_error(
            context,
            "TypeError",
            "module evaluation arrives with native module loading (M15 S4)",
        );
    }

    // A nested `JS_Eval` — one called from inside a C function the engine is running — must
    // use the interpreter the engine already holds; borrowing the context's own would panic
    // with "RefCell already borrowed". `with_current_interp` picks the right one, and answers
    // the same result shape, so the match below is shared.
    if let Some(interp) = current_interp() {
        // Re-entrant: the engine is inside a call, so this is the eval path — a script
        // compiled with `run_script_with_this` would be a *second* top-level script, and a
        // script cannot start while another is running.
        let outcome = match this {
            Some(this) => interp.eval_script_with_this(&source, &name, this),
            None => interp.eval_in_global_named(&source, &name, false),
        };
        return match outcome {
            Ok(value) => convert::encode(&value),
            Err(Signal::Throw(value)) => {
                context.set_pending(value);
                jsvalue::EXCEPTION
            }
            Err(Signal::OutOfMemory) => {
                let error = interp.make_error("InternalError", "out of memory");
                context.set_pending(error);
                jsvalue::EXCEPTION
            }
        };
    }

    // No receiver asked for: `JS_Eval`'s own path, unchanged. It parses with
    // `parse_script` rather than as an eval body, and the difference is visible — a `class`
    // in an eval body is a *lexical* declaration confined to that eval, while a script's
    // class is script-scoped. `tests/objects.rs` caught exactly that when this function
    // served both entry points.
    if this.is_none() {
        return context.with_context(|engine| match engine.eval_detailed(&source, &name) {
            Ok(value) => convert::encode(&value),
            Err(engine::EvalError::Throw(value)) => {
                context.set_pending(value);
                jsvalue::EXCEPTION
            }
            Err(engine::EvalError::Syntax(text)) => {
                // A compile error has no object behind it, so the pending exception is a
                // `SyntaxError` built from the message — which is what the reference does too
                // (`JS_ThrowSyntaxError` from the compiler).
                let error = engine.interp_mut().make_error("SyntaxError", &text);
                context.set_pending(error);
                jsvalue::EXCEPTION
            }
            Err(engine::EvalError::OutOfMemory) => {
                let error = engine
                    .interp_mut()
                    .make_error("InternalError", "out of memory");
                context.set_pending(error);
                jsvalue::EXCEPTION
            }
        });
    }

    // `JS_EvalThis`: the script path with the caller's receiver, which is what the
    // reference does — its `this_obj` reaches the same evaluation `JS_Eval` uses.
    context.with_context(|engine| {
        let interp = engine.interp_mut();
        match interp.eval_script_with_this(&source, &name, this.unwrap_or(Value::Undefined)) {
            Ok(value) => convert::encode(&value),
            Err(Signal::Throw(value)) => {
                context.set_pending(value);
                jsvalue::EXCEPTION
            }
            Err(Signal::OutOfMemory) => {
                let error = interp.make_error("InternalError", "out of memory");
                context.set_pending(error);
                jsvalue::EXCEPTION
            }
        }
    })
}

/// `JS_EvalThis`'s entry point into the shared body.
///
/// # Safety
///
/// As [`JS_Eval`].
pub(crate) unsafe fn eval_with_this(
    context: &JsContext,
    input: *const core::ffi::c_char,
    input_len: usize,
    filename: *const core::ffi::c_char,
    eval_flags: core::ffi::c_int,
    this: Option<Value>,
) -> JsValue {
    // SAFETY: `context` came from a live `JSContext`; the rest is the caller's contract.
    unsafe {
        eval_with_this_raw(
            context as *const JsContext as *mut JsContext,
            input,
            input_len,
            filename,
            eval_flags,
            this,
        )
    }
}

/// `JS_IsException` — exported for the rare caller that takes its address.
///
/// The header spells this one `static inline`, so no C object refers to it; it is here
/// because a Rust-side test and a future `--symbols` entry may want it.
#[unsafe(no_mangle)]
pub extern "C" fn JS_IsException(value: JsValue) -> c_int {
    c_int::from(value.is_exception())
}