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
//! The S5 surface driven from Rust, one C API call at a time.
//!
//! `JS_WriteObject`/`JS_ReadObject` are the one pair in the C API whose contract is a
//! *format*, so the tests here are about properties rather than bytes: a round trip is equal
//! by value, a shared object is still shared afterwards, a cycle survives, and a value the
//! format has no spelling for is refused instead of being silently dropped.
//!
//! The format itself is this crate's own — `tests/test_bjson.js` asserts round trips and
//! prints no hex, which is the licence for that.

use std::ffi::CString;

use quickjs::jsvalue::JsValue;
use quickjs::runtime::{self, JsContext, JsRuntime};

/// A runtime and 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 = runtime::JS_NewRuntime();
            let context = runtime::JS_NewContext(runtime);
            Engine { runtime, context }
        }
    }

    /// Evaluate `source` and answer its completion value, which the caller owns.
    fn eval(&self, source: &str) -> JsValue {
        let text = CString::new(source).expect("no NUL in a test source");
        // SAFETY: the buffers outlive the call and both pointers are NUL-terminated.
        unsafe {
            runtime::JS_Eval(
                self.context,
                text.as_ptr(),
                source.len(),
                c"<test>".as_ptr(),
                0,
            )
        }
    }

    /// Evaluate `source` and answer its result as text, for the assertions.
    fn text(&self, source: &str) -> String {
        let value = self.eval(source);
        assert!(!value.is_exception(), "{source} threw");
        // `to_text` consumes the reference, so there is nothing to release here: doing it
        // twice dropped the box's count below zero and corrupted the heap, which showed up
        // as a `SIGSEGV` inside `malloc`'s thread cleanup at process exit.
        self.to_text(value)
    }

    /// A value as text, using `String(x)` so every type has a rendering.
    ///
    /// Stashes into `__qc_tmp`, not `__qc_scratch`: the tests read their fixture back
    /// through `__qc_scratch`, and a helper that wrote there would clobber the very value
    /// the next assertion is about.
    ///
    /// Consumes `value`: `JS_SetPropertyStr` takes a `JSValue`, not a `JSValueConst`, so the
    /// reference it is handed is the one the write owns. A caller that released it again
    /// would be freeing a box twice — which is not a theoretical worry, the first version of
    /// this helper did exactly that and the test binary segfaulted.
    fn to_text(&self, value: JsValue) -> String {
        // Stashed on the global because `String` is the conversion this side already has.
        // SAFETY: the global is a new reference and `value` is live.
        unsafe {
            let global = quickjs::objects::JS_GetGlobalObject(self.context);
            quickjs::objects::JS_SetPropertyStr(self.context, global, c"__qc_tmp".as_ptr(), value);
            runtime::release(global);
        }
        let text = self.eval("String(__qc_tmp)");
        assert!(!text.is_exception(), "String(__qc_tmp) threw");
        // SAFETY: `text` is a live string and the context is live.
        let c = unsafe {
            quickjs::objects::JS_ToCStringLen2(self.context, std::ptr::null_mut(), text, 0)
        };
        let rendered = unsafe { std::ffi::CStr::from_ptr(c) }
            .to_string_lossy()
            .into_owned();
        // SAFETY: the pointer came from `JS_ToCStringLen2` and `text` is a new reference.
        unsafe {
            quickjs::objects::JS_FreeCString(self.context, c);
            runtime::release(text);
        }
        rendered
    }

    /// Serialise `value`, answering the bytes or the pending exception.
    fn write(&self, value: JsValue, flags: i32) -> Result<Vec<u8>, String> {
        let mut size = 0usize;
        // SAFETY: `size` is writable and `value` is live.
        let block =
            unsafe { quickjs::bjson::JS_WriteObject(self.context, &mut size, value, flags) };
        if block.is_null() {
            return Err(self.pending_text());
        }
        // SAFETY: the API answers `size` readable bytes it allocated for us.
        let bytes = unsafe { std::slice::from_raw_parts(block, size) }.to_vec();
        // SAFETY: `block` came from `js_malloc`, which is what `js_free` releases.
        unsafe { quickjs::js_free(self.context, block.cast()) };
        Ok(bytes)
    }

    /// Rebuild a value from `bytes`.
    fn read(&self, bytes: &[u8], flags: i32) -> JsValue {
        // SAFETY: `bytes` is live and its length is passed alongside.
        unsafe { quickjs::bjson::JS_ReadObject(self.context, bytes.as_ptr(), bytes.len(), flags) }
    }

    /// Round trip `source` and answer `String(restored)`.
    fn round_trip(&self, source: &str, flags: i32) -> String {
        let value = self.eval(source);
        assert!(!value.is_exception(), "{source} threw");
        let bytes = self
            .write(value, flags)
            .unwrap_or_else(|error| panic!("writing {source} failed: {error}"));
        // SAFETY: `value` is a new reference we no longer need.
        unsafe { runtime::release(value) };
        let restored = self.read(&bytes, flags);
        assert!(!restored.is_exception(), "reading {source} back threw");
        self.to_text(restored)
    }

    /// The pending exception, rendered as text.
    fn pending_text(&self) -> String {
        // SAFETY: the context is live.
        unsafe {
            let exception = runtime::JS_GetException(self.context);
            assert!(!exception.is_null(), "no pending exception");
            self.to_text(exception)
        }
    }
}

impl Drop for Engine {
    fn drop(&mut self) {
        // SAFETY: both pointers come from the constructors and are freed once.
        unsafe {
            runtime::JS_FreeContext(self.context);
            runtime::JS_FreeRuntime(self.runtime);
        }
    }
}

#[test]
fn primitives_round_trip() {
    let engine = Engine::new();
    for (source, expected) in [
        ("null", "null"),
        ("undefined", "undefined"),
        ("true", "true"),
        ("false", "false"),
        ("0", "0"),
        ("-7", "-7"),
        ("1.5", "1.5"),
        ("-0", "0"),
        ("NaN", "NaN"),
        ("-Infinity", "-Infinity"),
        (r#""ab""#, "ab"),
        ("10n", "10"),
    ] {
        assert_eq!(
            engine.round_trip(source, 0),
            expected,
            "{source} round-tripped wrong"
        );
    }
}

#[test]
fn an_object_and_an_array_keep_their_contents() {
    let engine = Engine::new();
    // `String()` on an array joins with commas and on an object says `[object Object]`, so
    // the assertion goes through `JSON.stringify` — which is also the strictest comparison
    // already implemented on this side, since it orders keys and renders types.
    assert_eq!(engine.round_trip("[1, 2, 3]", 0), "1,2,3");
    assert_eq!(
        engine.round_trip_json(r#"({x:1, y:2, if:3})"#),
        r#"{"x":1,"y":2,"if":3}"#
    );
    assert_eq!(engine.round_trip_json("[1, , 2]"), "[1,null,2]");
}

#[test]
fn a_shared_object_stays_shared_with_reference_mode() {
    let engine = Engine::new();
    // One object in two slots. Without the flag the writer copies it and the identity is
    // lost; with the flag the reader resolves both slots to one object, which is what
    // `bjson_test_reference` asserts for a 16-node cycle.
    let source = "var shared = {v: 1}; [shared, shared]";
    // The control: without the flag, two sightings of one object become two objects, which
    // is what a copy means and what makes the flag's effect meaningful.
    assert_eq!(engine.round_trip("({v: 1}).v", 0), "1");
    let value = engine.eval(source);
    let bytes = engine.write(value, quickjs::bjson::WRITE_OBJ_REFERENCE);
    // SAFETY: `value` is a new reference.
    unsafe { runtime::release(value) };
    let bytes = bytes.expect("writing a shared pair");
    let restored = engine.read(&bytes, quickjs::bjson::READ_OBJ_REFERENCE);
    assert!(!restored.is_exception(), "reading a shared pair back threw");
    // SAFETY: both are new references / live values.
    unsafe {
        let global = quickjs::objects::JS_GetGlobalObject(engine.context);
        quickjs::objects::JS_SetPropertyStr(
            engine.context,
            global,
            c"__qc_scratch".as_ptr(),
            restored,
        );
        runtime::release(global);
    }
    assert_eq!(
        engine.text("__qc_scratch[0] === __qc_scratch[1] ? 'same' : 'copies'"),
        "same"
    );
}

#[test]
fn a_cycle_survives_and_a_cycle_without_reference_mode_is_refused() {
    let engine = Engine::new();
    let value = engine.eval("var o = {}; o.self = o; o");
    assert!(!value.is_exception());
    // SAFETY: `value` is a new reference.
    let plain = engine.write(value, 0);
    unsafe { runtime::release(value) };
    let message = plain.expect_err("a cycle without reference mode cannot be written");
    assert!(message.contains("circular reference"), "{message}");

    let value = engine.eval("var o = {}; o.self = o; o");
    let bytes = engine.write(value, quickjs::bjson::WRITE_OBJ_REFERENCE);
    // SAFETY: `value` is a new reference.
    unsafe { runtime::release(value) };
    let bytes = bytes.expect("a cycle with reference mode writes");
    let restored = engine.read(&bytes, quickjs::bjson::READ_OBJ_REFERENCE);
    assert!(!restored.is_exception(), "reading a cycle back threw");
    // SAFETY: both are new references / live values.
    unsafe {
        let global = quickjs::objects::JS_GetGlobalObject(engine.context);
        quickjs::objects::JS_SetPropertyStr(
            engine.context,
            global,
            c"__qc_scratch".as_ptr(),
            restored,
        );
        runtime::release(global);
    }
    assert_eq!(
        engine.text("__qc_scratch.self === __qc_scratch ? 'cycle' : 'broken'"),
        "cycle"
    );
}

#[test]
fn a_function_is_refused_like_any_unsupported_class() {
    let engine = Engine::new();
    let value = engine.eval("(function f(){})");
    // SAFETY: `value` is a new reference.
    let written = engine.write(value, 0);
    unsafe { runtime::release(value) };
    let message = written.expect_err("a function has no serialisation");
    assert!(message.contains("unsupported"), "{message}");
}

#[test]
fn an_array_buffer_keeps_its_resizability() {
    let engine = Engine::new();
    // The two numbers being equal does not make two buffers the same, which is the case
    // `bjson_test_arraybuffer` exercises: a fixed 4-byte buffer and a resizable 4/4 one both
    // report 4 and 4, and only `resizable` tells them apart.
    assert_eq!(
        engine.round_trip("new ArrayBuffer(4).resizable ? 'yes' : 'no'", 0),
        "no"
    );
    let value =
        engine.eval("var b = new ArrayBuffer(4, {maxByteLength: 8}); new Uint8Array(b)[0] = 9; b");
    let bytes = engine.write(value, 0).expect("writing a buffer");
    // SAFETY: `value` is a new reference.
    unsafe { runtime::release(value) };
    let restored = engine.read(&bytes, 0);
    assert!(!restored.is_exception(), "reading a buffer back threw");
    // SAFETY: both are new references / live values.
    unsafe {
        let global = quickjs::objects::JS_GetGlobalObject(engine.context);
        quickjs::objects::JS_SetPropertyStr(
            engine.context,
            global,
            c"__qc_scratch".as_ptr(),
            restored,
        );
        runtime::release(global);
    }
    assert_eq!(
        engine.text("__qc_scratch.byteLength + ' ' + __qc_scratch.maxByteLength + ' ' + __qc_scratch.resizable"),
        "4 8 true"
    );
    assert_eq!(engine.text("new Uint8Array(__qc_scratch)[0]"), "9");
}

#[test]
fn a_typed_array_shares_the_buffer_it_was_built_from() {
    let engine = Engine::new();
    let value =
        engine.eval("var ab = new ArrayBuffer(4); var v = new Uint8Array(ab, 2, 1); [ab, v]");
    let bytes = engine
        .write(value, quickjs::bjson::WRITE_OBJ_REFERENCE)
        .expect("writing a buffer and a view");
    // SAFETY: `value` is a new reference.
    unsafe { runtime::release(value) };
    let restored = engine.read(&bytes, quickjs::bjson::READ_OBJ_REFERENCE);
    assert!(!restored.is_exception());
    // SAFETY: both are new references / live values.
    unsafe {
        let global = quickjs::objects::JS_GetGlobalObject(engine.context);
        quickjs::objects::JS_SetPropertyStr(
            engine.context,
            global,
            c"__qc_scratch".as_ptr(),
            restored,
        );
        runtime::release(global);
    }
    // Both slots have to resolve to the *one* buffer that was written, or a write through
    // the view would stop being visible through the buffer.
    assert_eq!(
        engine.text("__qc_scratch[1].buffer === __qc_scratch[0] ? 'shared' : 'copied'"),
        "shared"
    );
    assert_eq!(
        engine.text("__qc_scratch[1].byteOffset + ' ' + __qc_scratch[1].length"),
        "2 1"
    );
}

#[test]
fn a_wrapper_round_trips_as_a_wrapper() {
    let engine = Engine::new();
    assert_eq!(engine.round_trip("new String('ab').valueOf()", 0), "ab");
    let value = engine.eval("new Number(7)");
    let bytes = engine.write(value, 0).expect("writing a wrapper");
    // SAFETY: `value` is a new reference.
    unsafe { runtime::release(value) };
    let restored = engine.read(&bytes, 0);
    assert!(!restored.is_exception());
    // SAFETY: both are new references / live values.
    unsafe {
        let global = quickjs::objects::JS_GetGlobalObject(engine.context);
        quickjs::objects::JS_SetPropertyStr(
            engine.context,
            global,
            c"__qc_scratch".as_ptr(),
            restored,
        );
        runtime::release(global);
    }
    // `instanceof` is the assertion that it is a wrapper and not the number it wraps.
    assert_eq!(
        engine.text("(__qc_scratch instanceof Number) + ' ' + __qc_scratch.valueOf()"),
        "true 7"
    );
}

#[test]
fn a_date_round_trips_as_a_date() {
    let engine = Engine::new();
    let value = engine.eval("new Date(1234)");
    let bytes = engine.write(value, 0).expect("writing a date");
    // SAFETY: `value` is a new reference.
    unsafe { runtime::release(value) };
    let restored = engine.read(&bytes, 0);
    assert!(!restored.is_exception());
    // SAFETY: both are new references / live values.
    unsafe {
        let global = quickjs::objects::JS_GetGlobalObject(engine.context);
        quickjs::objects::JS_SetPropertyStr(
            engine.context,
            global,
            c"__qc_scratch".as_ptr(),
            restored,
        );
        runtime::release(global);
    }
    assert_eq!(
        engine.text("(__qc_scratch instanceof Date) + ' ' + __qc_scratch.getTime()"),
        "true 1234"
    );
}

impl Engine {
    /// Round trip `source` and answer `JSON.stringify(restored)`.
    fn round_trip_json(&self, source: &str) -> String {
        let value = self.eval(source);
        assert!(!value.is_exception(), "{source} threw");
        let bytes = self
            .write(value, 0)
            .unwrap_or_else(|error| panic!("writing {source} failed: {error}"));
        // SAFETY: `value` is a new reference.
        unsafe { runtime::release(value) };
        let restored = self.read(&bytes, 0);
        assert!(!restored.is_exception(), "reading {source} back threw");
        // SAFETY: both are new references / live values.
        unsafe {
            let global = quickjs::objects::JS_GetGlobalObject(self.context);
            quickjs::objects::JS_SetPropertyStr(
                self.context,
                global,
                c"__qc_scratch".as_ptr(),
                restored,
            );
            runtime::release(global);
        }
        self.text("JSON.stringify(__qc_scratch)")
    }
}