quickjs-capi 0.14.0

C ABI compatibility layer: the QuickJS C API on top of the pure-Rust engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
//! The S3 surface driven from Rust, one C API call at a time.
//!
//! These tests are deliberately not "does the engine work" — `quickjs-pure` has hundreds of
//! those. They answer the question the C ABI layer exists for: *does a C caller get the
//! behaviour the reference gives it?* So every call here is an exported function taking and
//! returning `JSValue`/`JSContext *`, and the assertions are on what a C module would
//! observe.
//!
//! They also cover the two things the C smoke test cannot: the finalizer path (which needs a
//! collection or a scope exit to run) and the pending-exception round trip.

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

use quickjs::cdefs::{
    FunctionEntry, FunctionListUnion, JS_DEF_CFUNC, JS_DEF_CGETSET_MAGIC, JSCFunctionListEntry,
    JSClassDef,
};
use quickjs::jsvalue::{EXCEPTION, JsValue, TAG_BOOL, TAG_EXCEPTION, TAG_INT, UNDEFINED};
use quickjs::runtime::{JsContext, JsRuntime};

/// `JSRuntime *` plus a context, freed together.
struct Engine {
    runtime: *mut JsRuntime,
    context: *mut JsContext,
}

impl Engine {
    fn new() -> Engine {
        // SAFETY: both pointers come from the API under test and are freed in `Drop`.
        unsafe {
            let runtime = quickjs::runtime::JS_NewRuntime();
            assert!(!runtime.is_null());
            let context = quickjs::runtime::JS_NewContext(runtime);
            assert!(!context.is_null());
            Engine { runtime, context }
        }
    }

    /// `JS_Eval` of a global script.
    fn eval(&self, source: &str) -> JsValue {
        let mut text = source.as_bytes().to_vec();
        text.push(0);
        let name = b"<test>\0";
        // SAFETY: the buffers outlive the call, and both pointers are NUL-terminated.
        unsafe {
            quickjs::runtime::JS_Eval(
                self.context,
                text.as_ptr().cast(),
                source.len(),
                name.as_ptr().cast(),
                c_int::from(0),
            )
        }
    }

    /// Evaluate and answer the completion value as a `f64`, asserting it is a number.
    fn eval_number(&self, source: &str) -> f64 {
        let value = self.eval(source);
        assert!(!value.is_exception(), "{source} threw");
        if value.norm_tag() == TAG_INT {
            return f64::from(value.to_int());
        }
        let number = value.to_float();
        // SAFETY: the value is a new reference from `JS_Eval`.
        unsafe { quickjs::runtime::release(value) };
        number
    }

    /// The text of the pending exception, via `JS_GetException` + `ToString`.
    fn pending_text(&self) -> String {
        // SAFETY: the context is live.
        unsafe {
            let exception = quickjs::runtime::JS_GetException(self.context);
            assert!(!exception.is_null(), "no pending exception");
            let text = to_string(self.context, exception);
            quickjs::runtime::release(exception);
            text
        }
    }
}

impl Drop for Engine {
    fn drop(&mut self) {
        // SAFETY: both pointers came from the constructors above, and the context is freed
        // before the runtime it borrows.
        unsafe {
            quickjs::runtime::JS_FreeContext(self.context);
            quickjs::runtime::JS_FreeRuntime(self.runtime);
        }
    }
}

/// `ToString`, through the context's own coercion (so a thrown `valueOf` is respected).
fn to_string(context: *mut JsContext, value: JsValue) -> String {
    // SAFETY: `ctx.as_ref()` is a live context, and the interpreter is not borrowed.
    unsafe {
        let context_ref = &*context;
        let mut answer = String::new();
        context_ref.with_interp(|interp| {
            if let Some(value) = quickjs::convert::decode(value) {
                answer = interp.to_js_string(&value).unwrap_or_default();
            }
        });
        answer
    }
}

/// A field the test's C-side class stores, so `JS_SetOpaque`/`JS_GetOpaque` have a payload.
#[repr(C)]
struct PointData {
    x: i32,
    y: i32,
}

/// `js_point_class_id`, as a module keeps it.
///
/// An `AtomicU32` rather than a `static mut` because the C side reads it from a callback
/// while the test thread writes it, and because a `static mut` cannot be read without
/// `unsafe` in edition 2024. A C module would spell this `static JSClassID id;`.
static POINT_CLASS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);

/// Serialises the tests in this file.
///
/// A C module keeps its class id in a `static`, so two tests registering "the" Point class at
/// the same time would overwrite each other's id — and the failure would look like a broken
/// opaque rather than a broken test. The lock is what a single-threaded host gives a module
/// for free.
static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// Take the lock, ignoring a previous test's panic.
fn serial() -> std::sync::MutexGuard<'static, ()> {
    SERIAL.lock().unwrap_or_else(|poison| poison.into_inner())
}

/// The class id the tests registered, which is also what a C module keeps in a static.
fn point_class() -> u32 {
    POINT_CLASS.load(std::sync::atomic::Ordering::SeqCst)
}

/// The outstanding payload, so the finalizer test can prove it ran exactly once.
static FINALIZED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// `js_point_finalizer`: the payload must come back and be freed exactly once.
unsafe extern "C" fn point_finalizer(_rt: *mut c_void, value: JsValue) {
    // SAFETY: the test's class stores a `PointData` it allocated with `js_mallocz`.
    let class = POINT_CLASS.load(std::sync::atomic::Ordering::SeqCst);
    let pointer = unsafe { quickjs::objects::JS_GetOpaque(value, class) };
    if pointer.is_null() {
        // `JS_SetOpaque` may never have run — the reference documents this case.
        return;
    }
    FINALIZED.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
    // SAFETY: the pointer came from `js_mallocz`, so `js_free_rt` is the matching release.
    unsafe { quickjs::js_free_rt(std::ptr::null_mut(), pointer) };
}

/// `js_point_ctor`: build an instance from `new.target.prototype`, exactly as `point.c` does.
unsafe extern "C" fn point_ctor(
    ctx: *mut JsContext,
    new_target: JsValue,
    argc: c_int,
    argv: *const JsValue,
) -> JsValue {
    // SAFETY: the arguments are live for the duration of the call.
    unsafe {
        let payload =
            quickjs::js_mallocz(ctx, core::mem::size_of::<PointData>()).cast::<PointData>();
        if payload.is_null() {
            return EXCEPTION;
        }
        let first = *argv;
        let second = if argc > 1 { *argv.add(1) } else { UNDEFINED };
        if quickjs::conversions::JS_ToInt32(ctx, &raw mut (*payload).x, first) < 0 {
            quickjs::js_free(ctx, payload.cast());
            return EXCEPTION;
        }
        if quickjs::conversions::JS_ToInt32(ctx, &raw mut (*payload).y, second) < 0 {
            quickjs::js_free(ctx, payload.cast());
            return EXCEPTION;
        }
        let proto = quickjs::objects::JS_GetPropertyStr(ctx, new_target, c"prototype".as_ptr());
        if proto.is_exception() {
            quickjs::js_free(ctx, payload.cast());
            return EXCEPTION;
        }
        let object = quickjs::objects::JS_NewObjectProtoClass(ctx, proto, point_class());
        quickjs::runtime::release(proto);
        if object.is_exception() {
            quickjs::js_free(ctx, payload.cast());
            return EXCEPTION;
        }
        quickjs::objects::JS_SetOpaque(object, payload.cast());
        object
    }
}

/// `js_point_get_xy`.
unsafe extern "C" fn point_get(ctx: *mut JsContext, this: JsValue, magic: c_int) -> JsValue {
    // SAFETY: `JS_GetOpaque2` walks the live object; the payload was stored by the ctor.
    unsafe {
        let payload = quickjs::objects::JS_GetOpaque2(ctx, this, point_class()).cast::<PointData>();
        if payload.is_null() {
            return EXCEPTION;
        }
        let number = if magic == 0 {
            (*payload).x
        } else {
            (*payload).y
        };
        quickjs::convert::encode(&engine::Value::Int(number))
    }
}

/// `js_point_set_xy`.
unsafe extern "C" fn point_set(
    ctx: *mut JsContext,
    this: JsValue,
    value: JsValue,
    magic: c_int,
) -> JsValue {
    // SAFETY: as `point_get`.
    unsafe {
        let payload = quickjs::objects::JS_GetOpaque2(ctx, this, point_class()).cast::<PointData>();
        if payload.is_null() {
            return EXCEPTION;
        }
        let mut number: i32 = 0;
        if quickjs::conversions::JS_ToInt32(ctx, &mut number, value) < 0 {
            return EXCEPTION;
        }
        if magic == 0 {
            (*payload).x = number;
        } else {
            (*payload).y = number;
        }
        UNDEFINED
    }
}

/// `js_point_norm`.
unsafe extern "C" fn point_norm(
    _ctx: *mut JsContext,
    this: JsValue,
    _argc: c_int,
    _argv: *const JsValue,
) -> JsValue {
    // SAFETY: as `point_get`. No context is needed to read the payload.
    unsafe {
        let payload = quickjs::objects::JS_GetOpaque(this, point_class()).cast::<PointData>();
        if payload.is_null() {
            return EXCEPTION;
        }
        let (x, y) = (f64::from((*payload).x), f64::from((*payload).y));
        quickjs::convert::encode(&engine::Value::Float((x * x + y * y).sqrt()))
    }
}

/// The table `point.c` builds with `JS_CGETSET_MAGIC_DEF`/`JS_CFUNC_DEF`.
fn point_table() -> Vec<JSCFunctionListEntry> {
    let cgetset = |name: &'static CStr, magic: i16| JSCFunctionListEntry {
        name: name.as_ptr(),
        prop_flags: quickjs::cdefs::prop::CONFIGURABLE,
        def_type: JS_DEF_CGETSET_MAGIC,
        magic,
        _padding: [0; 4],
        u: FunctionListUnion {
            getset: core::mem::ManuallyDrop::new(quickjs::cdefs::GetSetEntry {
                get: quickjs::cdefs::JSCFunctionType {
                    pointer: point_get as *const c_void,
                },
                set: quickjs::cdefs::JSCFunctionType {
                    pointer: point_set as *const c_void,
                },
            }),
        },
    };
    vec![
        cgetset(c"x", 0),
        cgetset(c"y", 1),
        JSCFunctionListEntry {
            name: c"norm".as_ptr(),
            prop_flags: quickjs::cdefs::prop::WRITABLE | quickjs::cdefs::prop::CONFIGURABLE,
            def_type: JS_DEF_CFUNC,
            magic: 0,
            _padding: [0; 4],
            u: FunctionListUnion {
                func: core::mem::ManuallyDrop::new(FunctionEntry {
                    length: 0,
                    cproto: quickjs::cdefs::CFunctionEnum::Generic as u8,
                    _padding: [0; 6],
                    cfunc: quickjs::cdefs::JSCFunctionType {
                        pointer: point_norm as *const c_void,
                    },
                }),
            },
        },
    ]
}

/// Register the Point class and install it as a global `Point` constructor.
///
/// Every step is a C API call, in the order `point.c`'s `js_point_init` makes them — no
/// `with_interp` wrapper, because a C module has no such thing and because nesting one
/// inside the API would deadlock the context's borrow.
fn install_point(engine: &Engine) {
    let table = point_table();
    // SAFETY: every pointer is to `'static` data or a live context; the class definition
    // outlives the engine, and the test frees the engine last.
    unsafe {
        let context = engine.context;
        let runtime = quickjs::objects::JS_GetRuntime(context);
        assert!(!runtime.is_null(), "JS_GetRuntime answered null");

        let mut id = 0u32;
        quickjs::objects::JS_NewClassID(&raw mut id);
        POINT_CLASS.store(id, std::sync::atomic::Ordering::SeqCst);
        assert_ne!(id, 0, "JS_NewClassID answered an invalid id");

        let definition = JSClassDef {
            class_name: c"Point".as_ptr(),
            finalizer: Some(point_finalizer),
            gc_mark: None,
            call: None,
            exotic: std::ptr::null(),
        };
        assert_eq!(
            quickjs::objects::JS_NewClass(runtime, id, &definition),
            0,
            "JS_NewClass failed"
        );
        assert_eq!(
            quickjs::objects::JS_IsRegisteredClass(runtime, id),
            1,
            "the class did not register"
        );

        // `point_proto = JS_NewObject(ctx)` then the function list on it.
        let proto = quickjs::objects::JS_NewObject(context);
        assert!(!proto.is_exception(), "JS_NewObject failed");
        assert_eq!(
            quickjs::objects::JS_SetPropertyFunctionList(
                context,
                proto,
                table.as_ptr(),
                c_int::try_from(table.len()).unwrap(),
            ),
            0,
            "JS_SetPropertyFunctionList failed"
        );

        let constructor = quickjs::objects::JS_NewCFunction2(
            context,
            point_ctor as *const c_void,
            c"Point".as_ptr(),
            2,
            quickjs::cdefs::CFunctionEnum::Constructor as c_int,
            0,
        );
        assert!(!constructor.is_exception(), "JS_NewCFunction2 failed");
        // `JS_SetConstructor` borrows both, so the constructor is still ours afterwards.
        assert_eq!(
            quickjs::objects::JS_SetConstructor(context, constructor, proto),
            0,
            "JS_SetConstructor failed"
        );
        // `JS_SetClassProto` consumes its value, so it gets a second reference.
        let for_class = quickjs::convert::encode(
            &quickjs::runtime::argument(constructor).expect("the constructor decodes"),
        );
        quickjs::objects::JS_SetClassProto(context, id, for_class);

        // Install it as a global; `JS_SetPropertyStr` consumes that reference too.
        let global = quickjs::objects::JS_GetGlobalObject(context);
        assert!(!global.is_exception(), "JS_GetGlobalObject failed");
        let for_global = quickjs::convert::encode(
            &quickjs::runtime::argument(constructor).expect("the constructor decodes"),
        );
        assert_eq!(
            quickjs::objects::JS_SetPropertyStr(context, global, c"Point".as_ptr(), for_global),
            0,
            "JS_SetPropertyStr failed"
        );
        quickjs::runtime::release(global);
        quickjs::runtime::release(constructor);
        quickjs::runtime::release(proto);
    }
}

#[test]
fn the_point_class_works_from_c() {
    let _serial = serial();
    let engine = Engine::new();
    install_point(&engine);
    assert_eq!(engine.eval_number("var p = new Point(2, 3); p.x"), 2.0);
    assert_eq!(engine.eval_number("p.y"), 3.0);
    assert_eq!(engine.eval_number("p.x = 4; p.x"), 4.0);
    assert_eq!(engine.eval_number("p.norm()"), 5.0);
    // A subclass goes through `new.target.prototype`, which is why the ctor reads it.
    assert_eq!(
        engine.eval_number(
            "class ColorPoint extends Point { constructor(x, y) { super(x, y); } }\n\
             var cp = new ColorPoint(6, 8); cp.norm()"
        ),
        10.0
    );
    assert_eq!(engine.eval_number("cp instanceof Point ? 1 : 0"), 1.0);
}

#[test]
fn a_getter_and_a_setter_both_use_magic() {
    let _serial = serial();
    let engine = Engine::new();
    install_point(&engine);
    engine.eval("var q = new Point(1, 2);");
    // Two different `magic` values reach the same C function; that is the whole point of
    // `JS_CGETSET_MAGIC_DEF`.
    assert_eq!(engine.eval_number("q.x"), 1.0);
    assert_eq!(engine.eval_number("q.y"), 2.0);
    engine.eval("q.y = 20;");
    assert_eq!(engine.eval_number("q.y"), 20.0);
}

#[test]
fn the_opaque_is_per_class_and_typed() {
    let _serial = serial();
    let engine = Engine::new();
    install_point(&engine);
    engine.eval("var r = new Point(0, 0);");
    // A plain object has no payload for this class, so the getter raises rather than
    // reinterpreting a pointer: `Point.prototype.x.call({})` must be a `TypeError`.
    let value = engine.eval("Point.prototype.x.call({})");
    assert!(value.is_exception(), "a bare object answered an opaque");
    let text = engine.pending_text();
    assert!(text.contains("not a Point"), "{text}");
}

#[test]
fn the_finalizer_runs_exactly_once() {
    let _serial = serial();
    let engine = Engine::new();
    install_point(&engine);
    let before = FINALIZED.load(std::sync::atomic::Ordering::SeqCst);
    // The trailing `0` matters: a script's completion value is retained by the engine (it is
    // what `JS_Eval` answers), so ending on `new Point(…)` would keep the last instance alive
    // and its finalizer would legitimately not have run yet.
    engine.eval("for (var i = 0; i < 3; i++) { new Point(i, i); } 0");
    // Nothing has been collected yet: each instance died at the end of its statement, and
    // the engine's reference counting releases it right there.
    let after = FINALIZED.load(std::sync::atomic::Ordering::SeqCst);
    assert_eq!(
        after - before,
        3,
        "the finalizer did not run once per instance"
    );
}

#[test]
fn a_nulled_global_releases_its_instance() {
    let _serial = serial();
    let engine = Engine::new();
    install_point(&engine);
    let before = FINALIZED.load(std::sync::atomic::Ordering::SeqCst);

    // Four ways an instance is used and then dropped, each of which has to release it. The
    // last two are the ones that caught a real bug: calling a C function with the instance
    // as `this` encodes `this` into a box, and the first version of the trampoline never
    // released it — so every object a host method had touched stayed alive for the life of
    // the process, and its finalizer never ran.
    let mut counts = Vec::new();
    for script in [
        "var a = new Point(2, 3); a = null;",
        "var b = new Point(2, 3); b.x; b = null;",
        "var c = new Point(2, 3); c.tag = 1; c = null;",
        "var d = new Point(2, 3); d.norm(); d = null;",
    ] {
        engine.eval(script);
        let now = FINALIZED.load(std::sync::atomic::Ordering::SeqCst);
        counts.push(now - before);
        // Each round adds exactly one, so the check is cumulative.
        assert_eq!(
            counts.last().copied().unwrap_or(0),
            counts.len(),
            "{script}: an instance was retained"
        );
    }
}

#[test]
fn js_to_int32_coerces_and_reports_type_errors() {
    let engine = Engine::new();
    // A string coerces; `ToInt32` is not a cast.
    assert_eq!(engine.eval_number("new Number(7) | 0"), 7.0);
    assert_eq!(engine.eval_number("('12' | 0) + ('0x10' | 0)"), 28.0);
    assert_eq!(engine.eval_number("(1e30 | 0) === (1e30 | 0) ? 1 : 0"), 1.0);
}

#[test]
fn an_exception_from_c_keeps_its_object() {
    let _serial = serial();
    let engine = Engine::new();
    install_point(&engine);
    // `new Point(Symbol(), 0)`: `ToInt32` fails, the ctor returns `JS_EXCEPTION`, and the
    // object `ToInt32` raised has to be the one the `catch` sees.
    let thrown = engine.eval("try { new Point(Symbol('nope'), 0) } catch (e) { e.name }");
    let text = to_string(engine.context, thrown);
    assert_eq!(
        text, "TypeError",
        "the C function's exception lost its identity"
    );
    // SAFETY: a new reference from `JS_Eval`.
    unsafe { quickjs::runtime::release(thrown) };
}

#[test]
fn eval_reports_syntax_errors_as_exception_objects() {
    let _serial = serial();
    let engine = Engine::new();
    let value = engine.eval("var = ;");
    assert!(value.is_exception());
    let text = engine.pending_text();
    assert!(text.contains("SyntaxError"), "{text}");
}

#[test]
fn a_boolean_and_an_index_convert() {
    let _serial = serial();
    let engine = Engine::new();
    assert_eq!(engine.eval_number("[] ? 1 : 0"), 1.0);
    assert_eq!(engine.eval_number("'' ? 1 : 0"), 0.0);
    assert_eq!(engine.eval_number("NaN ? 1 : 0"), 0.0);
}

#[test]
fn the_value_tags_line_up_with_the_header() {
    let _serial = serial();
    assert_eq!(UNDEFINED.norm_tag(), quickjs::jsvalue::TAG_UNDEFINED);
    assert_eq!(EXCEPTION.norm_tag(), TAG_EXCEPTION);
    assert_eq!(TAG_BOOL, 1);
    assert_eq!(TAG_INT, 0);
    // A closed-over `c"…"` literal is a `&'static CStr`, which is what a module's static
    // strings are; the cast keeps clippy from asking about the redundant `as`.
    let _: *const c_char = c"x".as_ptr();
}