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
//! Runtime and context state: limits, GC, opaque pointers, context values, memory reporting
//! and `JS_PrintValue`.
//!
//! # Which of these are real and which are "accepted and recorded"
//!
//! A limit that the engine does not enforce must not pretend to. `JS_SetMemoryLimit` and
//! `JS_SetMaxStackSize` map onto `Runtime::set_memory_limit`/`set_stack_size`, which the
//! allocator and the call-depth check already consult โ€” so those are real.
//! `JS_SetGCThreshold` maps onto the heap's threshold, also real.
//! `JS_SetInterruptHandler` is real but only checked where the engine already yields
//! (`docs/m15-plan.md` ยง5: not between every opcode), and that limit is stated in the README.
//! `JS_SetCanBlock`, `JS_SetStripInfo` and `JS_SetRuntimeInfo` are recorded and have no
//! observable effect, which is stated at each one.
//!
//! # Why the memory report is not a fabrication
//!
//! `JS_ComputeMemoryUsage` fills a `JSMemoryUsage` whose fields a C program prints. Filling
//! them with plausible-looking zeros would be worse than filling the ones that are actually
//! known: a host that logs `malloc_size` and sees `0` knows the number is unavailable, whereas
//! one that sees an invented `4096` believes it.
//!
//! Every field is now measured by the engine's own walk (`engine::memory::compute`), which
//! visits the live heap blocks and downcasts โ€” the same design as the reference's
//! `JS_ComputeMemoryUsage`, which walks its object lists. The one field pair left at zero is
//! `shape_count`/`shape_size`: this engine has no hidden-class sharing, so there is nothing to
//! count, and `JS_DumpMemoryUsage` prints it as `(not modelled)` rather than as a measured
//! zero.

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

use engine::Value;

use crate::cdefs::{Bool, JSMemoryUsage, JSPrintValueOptions, PrintValueWrite};
use crate::conversions::arg;
use crate::jsvalue::{self, JsValue};
use crate::runtime::{self, JsContext, JsRuntime};
use crate::value_helpers::jsvalue_of;

// ---------------------------------------------------------------------------
// Limits
// ---------------------------------------------------------------------------

/// `JS_SetMemoryLimit`: refuse an allocation that would take the heap past `limit` bytes.
///
/// **`0` means "no memory at all", not "no limit".** The reference's `malloc_limit` is a
/// `size_t` initialised to `-1`, and `js_malloc` fails when `malloc_size + size > limit`, so
/// a host that wants to remove a limit passes `(size_t)-1`. That is worth stating because it
/// is the opposite of what a "0 disables it" instinct expects, and getting it wrong here
/// would have made every allocation after the call fail โ€” which is exactly what happened
/// when this layer first mapped `0` onto "unlimited" and `tests/c/embed.c` caught it.
///
/// # Safety
///
/// `rt` must be a live runtime.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetMemoryLimit(rt: *mut JsRuntime, limit: usize) {
    let Some(runtime) = (unsafe { rt.as_ref() }) else {
        return;
    };
    // SAFETY: the engine runtime is boxed and this pointer is the only writer; the C API is
    // single-threaded per runtime by contract, and `&mut` through a raw pointer is how a
    // `*mut JSRuntime` reaches it.
    let engine = unsafe { &mut *(runtime.engine_ptr() as *mut engine::Runtime) };
    // `Some(limit)`, always: a limit of zero is a real limit (nothing may be allocated),
    // which is what the reference does. The engine's `Option` is only for "no limit", and
    // that arrives as `(size_t)-1` from the host.
    engine.set_memory_limit(if limit == usize::MAX {
        None
    } else {
        Some(limit)
    });
}

/// `JS_SetMaxStackSize`: cap the call depth, `0` to disable the check.
///
/// # Safety
///
/// `rt` must be a live runtime.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetMaxStackSize(rt: *mut JsRuntime, stack_size: usize) {
    let Some(runtime) = (unsafe { rt.as_ref() }) else {
        return;
    };
    // SAFETY: as `JS_SetMemoryLimit`.
    let engine = unsafe { &mut *(runtime.engine_ptr() as *mut engine::Runtime) };
    let limit = if stack_size == 0 {
        None
    } else {
        Some(stack_size)
    };
    engine.set_stack_size(limit);
    // The engine's field is what a *later* context picks up; a context that already ran
    // something owns its interpreter, and it has to be told now โ€” the same ordering problem
    // [`JS_SetMemoryLimit`] had, which the heap solves for memory and the interpreter cannot.
    if let Some(limit) = limit {
        for context in runtime.live_contexts() {
            // SAFETY: every pointer in the list is live until `JS_FreeContext`.
            if let Some(context) = unsafe { context.as_ref() } {
                context.set_stack_limit(limit);
            }
        }
    }
}

/// `JS_SetGCThreshold`: collect once the heap holds `threshold` bytes.
///
/// # Safety
///
/// `rt` must be a live runtime.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetGCThreshold(rt: *mut JsRuntime, gc_threshold: usize) {
    let Some(runtime) = (unsafe { rt.as_ref() }) else {
        return;
    };
    runtime.set_gc_threshold(gc_threshold);
    runtime.engine.heap().set_threshold(gc_threshold);
}

/// `JS_SetInterruptHandler`: call `cb` periodically while a script runs.
///
/// Returning non-zero from the callback aborts the script. The engine checks the handler at
/// the sites it already yields at (loop back-edges and calls), which is enough for "stop this
/// runaway script" and *not* enough for single-stepping โ€” see the README's limitations
/// section, where that is stated as the reason `debugger` is not implemented on top of it.
///
/// # Safety
///
/// `rt` must be a live runtime and `cb`, if non-null, a `JSInterruptHandler`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetInterruptHandler(
    rt: *mut JsRuntime,
    cb: crate::cdefs::InterruptHandler,
    opaque: *mut c_void,
) {
    let Some(runtime) = (unsafe { rt.as_ref() }) else {
        return;
    };
    runtime.set_interrupt_handler(cb, opaque);
    // A context that already ran something has a live interpreter, and it has to learn about
    // the handler now rather than at its next entry point: `JS_SetInterruptHandler` is
    // documented as taking effect for the *next* evaluation, which is also the next poll.
    for context in runtime.live_contexts() {
        // SAFETY: every pointer in the list is live until `JS_FreeContext`.
        if let Some(context) = unsafe { context.as_ref() } {
            context.install_interrupt_hook();
        }
    }
}

/// `JS_RunGC`: collect now.
///
/// # Safety
///
/// `rt` must be a live runtime.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_RunGC(rt: *mut JsRuntime) {
    let Some(runtime) = (unsafe { rt.as_ref() }) else {
        return;
    };
    runtime.engine.run_gc();
}

/// `JS_UpdateStackTop`: tell the engine where this thread's stack starts.
///
/// The engine measures depth in frames rather than bytes, so there is no stack top to update.
/// The reference needs this after a thread switch; a C host that moves a runtime between
/// threads still gets the frame-based check, which is thread-independent.
///
/// # Safety
///
/// The argument is ignored.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_UpdateStackTop(_rt: *mut JsRuntime) {}

/// `JS_SetCanBlock`: whether a blocking operation (a synchronous `Atomics.wait`) is allowed.
///
/// # Safety
///
/// `rt` must be a live runtime.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetCanBlock(rt: *mut JsRuntime, can_block: Bool) {
    let Some(runtime) = (unsafe { rt.as_ref() }) else {
        return;
    };
    runtime.set_can_block(can_block != 0);
}

/// `JS_SetStripInfo`: record how much debug info to keep.
///
/// The engine never compiles debug info away, so the flag is stored and has no effect. A host
/// that sets it still gets full stack traces, which is the safe direction (more information,
/// not less).
///
/// # Safety
///
/// `rt` must be a live runtime.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetStripInfo(rt: *mut JsRuntime, flags: c_int) {
    if let Some(runtime) = unsafe { rt.as_ref() } {
        runtime.set_strip_info(flags);
    }
}

/// `JS_GetStripInfo`: the value last given to [`JS_SetStripInfo`].
///
/// # Safety
///
/// `rt` must be a live runtime.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetStripInfo(rt: *mut JsRuntime) -> c_int {
    match unsafe { rt.as_ref() } {
        Some(runtime) => runtime.strip_info(),
        None => 0,
    }
}

/// `JS_SetRuntimeInfo`: a label for diagnostics.
///
/// # Safety
///
/// `info` must be null or NUL-terminated, and outlive the runtime as the header requires.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetRuntimeInfo(rt: *mut JsRuntime, info: *const c_char) {
    if let Some(runtime) = unsafe { rt.as_ref() } {
        runtime.set_info(info);
    }
}

/// `JS_GetRuntimeOpaque`: the host's pointer.
///
/// # Safety
///
/// `rt` must be a live runtime.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetRuntimeOpaque(rt: *mut JsRuntime) -> *mut c_void {
    match unsafe { rt.as_ref() } {
        Some(runtime) => runtime.opaque(),
        None => std::ptr::null_mut(),
    }
}

/// `JS_SetRuntimeOpaque`.
///
/// # Safety
///
/// `rt` must be a live runtime.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetRuntimeOpaque(rt: *mut JsRuntime, opaque: *mut c_void) {
    if let Some(runtime) = unsafe { rt.as_ref() } {
        runtime.set_opaque(opaque);
    }
}

/// `JS_NewRuntime2`: a runtime with the host's allocator.
///
/// The engine's allocations go through Rust's global allocator, which a C-supplied
/// `JSMallocFunctions` cannot replace without a per-runtime allocator threaded through `Gc`.
/// The runtime is created with the default allocator and the functions are ignored; a caller
/// that needs its own allocator must not use this library. Recorded in the README.
///
/// # Safety
///
/// `mf` is ignored; the answer is a live runtime, or null when allocation fails.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewRuntime2(
    _mf: *const crate::cdefs::JSMallocFunctions,
    _opaque: *mut c_void,
) -> *mut JsRuntime {
    Box::into_raw(JsRuntime::new())
}

// ---------------------------------------------------------------------------
// Contexts
// ---------------------------------------------------------------------------

/// `JS_DupContext`: raise the context's reference count and answer the same pointer.
///
/// The reference does exactly this โ€” a context is not copyable, only reference-counted โ€” and
/// the count is what makes the documented idiom safe: hand a context to a callback, release
/// it when the callback returns, and the host's own release still finds it alive.
///
/// # Safety
///
/// `ctx` must be a live context.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_DupContext(ctx: *mut JsContext) -> *mut JsContext {
    if let Some(context) = unsafe { ctx.as_ref() } {
        context.raise_refs();
    }
    ctx
}

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

/// `JS_SetContextOpaque`.
///
/// # Safety
///
/// `ctx` must be a live context.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetContextOpaque(ctx: *mut JsContext, opaque: *mut c_void) {
    if let Some(context) = unsafe { ctx.as_ref() } {
        context.set_opaque(opaque);
    }
}

/// `JS_SetContextValue`: store a value at one of the context's private slots.
///
/// # Safety
///
/// `ctx` must be a live context; `val`'s reference is consumed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetContextValue(ctx: *mut JsContext, idx: c_int, val: JsValue) {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        // SAFETY: the C API consumes the reference whatever happens.
        unsafe { runtime::release(val) };
        return;
    };
    let value = unsafe { arg(val) }.unwrap_or(Value::Undefined);
    // SAFETY: the C API consumes it.
    unsafe { runtime::release(val) };
    context.set_value(idx, value);
}

/// `JS_GetContextValue`: the value at slot `idx`, or `undefined`.
///
/// # Safety
///
/// `ctx` must be a live context.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetContextValue(ctx: *mut JsContext, idx: c_int) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    match context.value(idx) {
        Some(value) => jsvalue_of(value),
        None => jsvalue::UNDEFINED,
    }
}

/// `JS_NewContextRaw`: a context with no intrinsics installed.
///
/// The engine installs its builtins when it builds an interpreter, at which point a context
/// *has* an interpreter and the intrinsic set is no longer a choice. So this is
/// `JS_NewContext`: a raw context here still has `Object` and `Array`. A caller that wanted
/// the reduced context must not use this library; the README says so next to
/// `JS_AddIntrinsicIntl`.
///
/// # Safety
///
/// `rt` must be a live runtime.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewContextRaw(rt: *mut JsRuntime) -> *mut JsContext {
    // SAFETY: the caller's contract is `JS_NewContext`'s.
    unsafe { crate::runtime::JS_NewContext(rt) }
}

// ---------------------------------------------------------------------------
// Memory usage
// ---------------------------------------------------------------------------

/// `JS_ComputeMemoryUsage`: fill `s` with what this runtime occupies.
///
/// Every field is measured, by the engine's own walk (`engine::memory::compute`). It used to
/// fill two and zero the rest; now the only fields left at zero are the ones this engine
/// genuinely has no equivalent for, and each is commented where it is set below.
///
/// # Safety
///
/// `rt` must be a live runtime and `s` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ComputeMemoryUsage(rt: *mut JsRuntime, s: *mut JSMemoryUsage) {
    if s.is_null() {
        return;
    }
    let mut usage = JSMemoryUsage::default();
    if let Some(runtime) = unsafe { rt.as_ref() } {
        let (measured, _) = engine::memory::compute(runtime.engine.heap());
        usage.malloc_count = measured.malloc_count;
        usage.malloc_size = measured.malloc_size;
        usage.memory_used_count = measured.memory_used_count;
        usage.memory_used_size = measured.memory_used_size;
        // -1 for "no limit", which is the reference's `(size_t)-1` and is what the table
        // prints; `JS_SetMemoryLimit(rt, 0)` therefore reports 0, not "unlimited".
        usage.malloc_limit = measured.malloc_limit;
        usage.str_count = measured.str_count;
        usage.str_size = measured.str_size;
        usage.obj_count = measured.obj_count;
        usage.obj_size = measured.obj_size;
        usage.prop_count = measured.prop_count;
        usage.prop_size = measured.prop_size;
        usage.shape_count = measured.shape_count;
        usage.shape_size = measured.shape_size;
        usage.js_func_count = measured.js_func_count;
        usage.js_func_size = measured.js_func_size;
        usage.js_func_code_size = measured.js_func_code_size;
        usage.js_func_pc2line_count = measured.js_func_pc2line_count;
        usage.js_func_pc2line_size = measured.js_func_pc2line_size;
        usage.c_func_count = measured.c_func_count;
        usage.array_count = measured.array_count;
        usage.fast_array_count = measured.fast_array_count;
        usage.fast_array_elements = measured.fast_array_elements;
        usage.binary_object_count = measured.binary_object_count;
        usage.binary_object_size = measured.binary_object_size;
        // `atom_count`/`atom_size` are the C API's own interned names: the engine has no atom
        // table (property keys are ordinary strings there), but this layer *does* intern the
        // names a C host passes in, and a binding that leaks atoms wants to see them.
        let atoms = runtime.atoms.borrow();
        usage.atom_count = i64::try_from(atoms.len()).unwrap_or(i64::MAX);
    }
    // SAFETY: the caller guarantees a writable pointer.
    unsafe { s.write(usage) };
}

/// `JS_DumpMemoryUsage`: print the report to `fp`.
///
/// The same table `qjs -d` prints, rendered by the same function
/// (`engine::memory::dump`), so a C host and the CLI cannot drift apart. The reference's
/// `JS_DumpMemoryUsage(stdout, &stats, rt)` needs `rt` for its per-class census; the caller
/// passes the one it computed `s` from.
///
/// # Safety
///
/// `fp` must be a writable `FILE *` and `s` a filled `JSMemoryUsage`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_DumpMemoryUsage(
    fp: *mut c_void,
    s: *const JSMemoryUsage,
    rt: *mut JsRuntime,
) {
    if fp.is_null() || s.is_null() {
        return;
    }
    // SAFETY: the caller guarantees a live `FILE *` and a filled structure.
    let usage = unsafe { &*s };
    let census = match unsafe { rt.as_ref() } {
        Some(runtime) => engine::memory::compute(runtime.engine.heap()).1,
        None => engine::memory::ClassCensus::default(),
    };
    let report = engine::memory::dump(&memory_usage_of(usage), &census);
    // SAFETY: `fp` is a `FILE *` the caller opened; `fwrite` reads `len` bytes from `report`.
    unsafe { fwrite(report.as_ptr().cast(), 1, report.len(), fp) };
}

// `fwrite(3)`, declared here rather than reached through `libc`.
//
// `libc` is a `cfg(unix)` dependency of this crate โ€” its only job is `dlopen`, which has no
// Windows equivalent here (`src/modules.rs` reports native modules as unloadable there).
// `fwrite` is not in that category: it is C89 and every Windows toolchain this could be
// built with links it from the CRT, so an `extern "C"` declaration is both portable and one
// fewer platform-specific dependency.
unsafe extern "C" {
    /// The C library's buffered write.
    fn fwrite(ptr: *const c_void, size: usize, count: usize, stream: *mut c_void) -> usize;
}

/// The C struct, as the engine's own structure โ€” field for field, so the renderer takes one
/// type rather than two.
fn memory_usage_of(usage: &JSMemoryUsage) -> engine::memory::MemoryUsage {
    engine::memory::MemoryUsage {
        malloc_count: usage.malloc_count,
        malloc_size: usage.malloc_size,
        memory_used_count: usage.memory_used_count,
        memory_used_size: usage.memory_used_size,
        malloc_limit: usage.malloc_limit,
        str_count: usage.str_count,
        str_size: usage.str_size,
        obj_count: usage.obj_count,
        obj_size: usage.obj_size,
        prop_count: usage.prop_count,
        prop_size: usage.prop_size,
        shape_count: usage.shape_count,
        shape_size: usage.shape_size,
        js_func_count: usage.js_func_count,
        js_func_size: usage.js_func_size,
        js_func_code_size: usage.js_func_code_size,
        js_func_pc2line_count: usage.js_func_pc2line_count,
        js_func_pc2line_size: usage.js_func_pc2line_size,
        c_func_count: usage.c_func_count,
        array_count: usage.array_count,
        fast_array_count: usage.fast_array_count,
        fast_array_elements: usage.fast_array_elements,
        binary_object_count: usage.binary_object_count,
        binary_object_size: usage.binary_object_size,
    }
}

// ---------------------------------------------------------------------------
// Printing a value
// ---------------------------------------------------------------------------

/// `JS_PrintValueSetDefaultOptions`: the options a fresh `JSPrintValueOptions` should hold.
///
/// **Not** zeros: the reference fills in `max_depth = 2`, `max_string_length = 1000` and
/// `max_item_count = 100`. This function used to write zeros and the symbol table said that
/// was "the header's default" โ€” the header says nothing of the kind, and its implementation
/// in `quickjs.c` is five lines of explicit assignment. A host that called this and then
/// `JS_PrintValue` got an unbounded dump where the reference truncates at depth 2.
///
/// # Safety
///
/// `options` must be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_PrintValueSetDefaultOptions(options: *mut JSPrintValueOptions) {
    if options.is_null() {
        return;
    }
    // SAFETY: the caller guarantees a writable pointer.
    unsafe {
        options.write(JSPrintValueOptions {
            show_hidden: 0,
            raw_dump: 0,
            max_depth: 2,
            max_string_length: 1000,
            max_item_count: 100,
        });
    }
}

/// `JS_PrintValue`: render `val` through `write_func`.
///
/// The rendering is the engine's own `describe` (the one a REPL uses), which prints strings
/// quoted, objects as `{ a: 1 }` and functions as `[Function: f]`. The options are accepted
/// but only `show_hidden` is honoured, by way of the same describe; the three limits are not,
/// and a caller relying on `max_depth` gets an unbounded rendering โ€” stated in the README.
///
/// # Safety
///
/// `write_func` must be a `JSPrintValueWrite`; `val` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_PrintValue(
    ctx: *mut JsContext,
    write_func: PrintValueWrite,
    write_opaque: *mut c_void,
    val: JsValue,
    options: *const JSPrintValueOptions,
) {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return;
    };
    let Some(value) = (unsafe { arg(val) }) else {
        return;
    };
    // `options` may be null, and then the reference's defaults apply (depth 2, 1000
    // characters, 100 items) โ€” the same numbers `JS_PrintValueSetDefaultOptions` writes.
    let limits = if options.is_null() {
        engine::print::PrintLimits::default()
    } else {
        // SAFETY: the caller guarantees the pointer is readable for the duration of the call.
        let options = unsafe { &*options };
        engine::print::PrintLimits {
            // Zero does **not** mean "print nothing": the header says "0 = no limit", so it
            // has to become a number large enough to never trigger. The fields are
            // `uint32_t` in the header, which is why `as usize` is a widening conversion.
            max_depth: if options.max_depth == 0 {
                usize::MAX
            } else {
                options.max_depth as usize
            },
            max_string_length: if options.max_string_length == 0 {
                usize::MAX
            } else {
                options.max_string_length as usize
            },
            max_item_count: if options.max_item_count == 0 {
                usize::MAX
            } else {
                options.max_item_count as usize
            },
        }
    };
    let text = context.with_current_interp(|interp| {
        match engine::print::sprint_limited(interp, &value, limits) {
            Ok(text) => text,
            // A printer that fails must not take the reporter down with it; the reference falls
            // back to the class name, and so does this.
            Err(_) => format!("[{}]", value.type_of()),
        }
    });
    emit(write_func, write_opaque, &text);
}

/// `JS_PrintValueRT`: the same, found through a runtime rather than a context.
///
/// # Safety
///
/// `write_func` must be a `JS_PrintValueWrite`; `val` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_PrintValueRT(
    rt: *mut JsRuntime,
    write_func: PrintValueWrite,
    write_opaque: *mut c_void,
    val: JsValue,
    options: *const JSPrintValueOptions,
) {
    let Some(runtime) = (unsafe { rt.as_ref() }) else {
        return;
    };
    // Whichever context exists is the one whose realm the value belongs to; a value with no
    // context is printed by the first one, which is right because every context in a runtime
    // shares its atoms and its class table.
    let contexts = runtime.live_contexts();
    if let Some(&context) = contexts.first() {
        // SAFETY: the pointer is live until `JS_FreeContext`.
        unsafe { JS_PrintValue(context, write_func, write_opaque, val, options) }
    }
}

/// Hand `text` to a C write callback.
fn emit(write_func: PrintValueWrite, write_opaque: *mut c_void, text: &str) {
    let Some(write_func) = write_func else {
        return;
    };
    // SAFETY: the caller guarantees the callback matches the header's signature, and the
    // slice outlives the call.
    unsafe { write_func(write_opaque, text.as_ptr().cast(), text.len()) };
}

/// `JS_HasException`: whether a call left an exception behind.
///
/// # Safety
///
/// `ctx` must be a live context.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_HasException(ctx: *mut JsContext) -> Bool {
    match unsafe { ctx.as_ref() } {
        Some(context) => c_int::from(context.has_pending()),
        None => 0,
    }
}

/// `JS_ThrowOutOfMemory`: raise the engine's out-of-memory error.
///
/// # Safety
///
/// `ctx` must be a live context.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ThrowOutOfMemory(ctx: *mut JsContext) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let value = context.throw_out_of_memory();
    context.set_pending(value);
    jsvalue::EXCEPTION
}

/// `JS_ThrowSyntaxError`, `JS_ThrowTypeError`, `JS_ThrowReferenceError`,
/// `JS_ThrowInternalError`: the four `JS_Throw*` spellings not already exported.
///
/// Each one is variadic in the header. Ours reads only `fmt`, for the reason
/// `JS_ThrowRangeError` documents: a variadic Rust function is not expressible on stable, and
/// a wrong-arity call would be worse than one that ignores surplus arguments.
///
/// # Safety
///
/// `ctx` must be a live context, `fmt` null or NUL-terminated.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ThrowSyntaxError(ctx: *mut JsContext, fmt: *const c_char) -> JsValue {
    // SAFETY: the caller's contract is `throw_named`'s.
    unsafe { throw_named(ctx, "SyntaxError", fmt) }
}

/// `JS_ThrowTypeError`. See [`JS_ThrowSyntaxError`].
///
/// # Safety
///
/// As [`JS_ThrowSyntaxError`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ThrowTypeError(ctx: *mut JsContext, fmt: *const c_char) -> JsValue {
    // SAFETY: the caller's contract is `throw_named`'s.
    unsafe { throw_named(ctx, "TypeError", fmt) }
}

/// `JS_ThrowReferenceError`. See [`JS_ThrowSyntaxError`].
///
/// # Safety
///
/// As [`JS_ThrowSyntaxError`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ThrowReferenceError(
    ctx: *mut JsContext,
    fmt: *const c_char,
) -> JsValue {
    // SAFETY: the caller's contract is `throw_named`'s.
    unsafe { throw_named(ctx, "ReferenceError", fmt) }
}

/// `JS_ThrowInternalError`. See [`JS_ThrowSyntaxError`].
///
/// # Safety
///
/// As [`JS_ThrowSyntaxError`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ThrowInternalError(ctx: *mut JsContext, fmt: *const c_char) -> JsValue {
    // SAFETY: the caller's contract is `throw_named`'s.
    unsafe { throw_named(ctx, "InternalError", fmt) }
}

/// The shared body of the four above.
unsafe fn throw_named(ctx: *mut JsContext, name: &str, fmt: *const c_char) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    // SAFETY: the caller guarantees a NUL-terminated format string.
    let message = unsafe { crate::conversions::c_text(fmt) };
    runtime::throw_error(context, name, &message)
}