quickjs-capi 0.12.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
//! `ArrayBuffer` and the typed-array views, from C.
//!
//! # Ownership, which is the whole difficulty here
//!
//! `JS_NewArrayBuffer(ctx, buf, len, free_func, opaque, is_shared)` takes ownership of a
//! *C* block and calls `free_func` when the buffer dies. `JS_NewUint8Array` does the same for
//! a view. So a buffer built this way cannot wrap an engine `Vec<u8>` without one of two
//! losses: either the C block is copied (and `free_func` has to be called immediately, which
//! contradicts the header) or the buffer holds a foreign pointer and every read goes through
//! it.
//!
//! This layer takes the first option and is explicit about it: the bytes are copied into the
//! engine's storage. What it does **not** do any more is call `free_func` right away — the
//! block is released when the buffer is collected, which is what the header says and what a
//! host that counts its own allocations can observe. The copy stays, because the alternative —
//! a foreign-pointer storage kind threaded through every typed-array operation — would be a
//! second representation of the same thing, and the callers of `JS_NewArrayBuffer` in the
//! acceptance surface (`tests/bjson.c`) hand over a block they never touch again.
//!
//! The one difference left: a host that keeps writing into its block after the call does not
//! see those writes in script, because script reads the copy. `JS_NewArrayBufferCopy` is the
//! spelling that admits the copy; the plain one now at least releases at the documented time.
//!
//! # Detachment
//!
//! `JS_DetachArrayBuffer` zeroes the storage and sets the flag, which every view reads: a
//! detached view answers `0` bytes and `undefined` elements. That is what
//! `structuredClone`'s transfer path and `postMessage` rely on.

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

use engine::Value;

use crate::atoms::Atom;
use crate::builtins_typed;
use crate::cdefs::Bool;
use crate::conversions::arg;
use crate::jsvalue::{self, JsValue};
use crate::runtime::{self, JsContext};
use crate::value_helpers::jsvalue_of;

/// `JSFreeArrayBufferDataFunc`: called when a C-supplied block is released.
pub type FreeArrayBufferDataFunc = Option<unsafe extern "C" fn(*mut c_void, *mut c_void)>;

/// The `JSTypedArrayEnum` values, in the header's order.
///
/// Kept as plain constants rather than an enum because the C side passes an `int` and the
/// reference's own values are what a module's `JSTypedArrayEnum` argument already holds.
pub mod typed_array_kind {
    /// `JS_TYPED_ARRAY_UINT8C`.
    pub const UINT8C: i32 = 0;
    /// `JS_TYPED_ARRAY_INT8`.
    pub const INT8: i32 = 1;
    /// `JS_TYPED_ARRAY_UINT8`.
    pub const UINT8: i32 = 2;
    /// `JS_TYPED_ARRAY_INT16`.
    pub const INT16: i32 = 3;
    /// `JS_TYPED_ARRAY_UINT16`.
    pub const UINT16: i32 = 4;
    /// `JS_TYPED_ARRAY_INT32`.
    pub const INT32: i32 = 5;
    /// `JS_TYPED_ARRAY_UINT32`.
    pub const UINT32: i32 = 6;
    /// `JS_TYPED_ARRAY_BIG_INT64`.
    pub const BIG_INT64: i32 = 7;
    /// `JS_TYPED_ARRAY_BIG_UINT64`.
    pub const BIG_UINT64: i32 = 8;
    /// `JS_TYPED_ARRAY_FLOAT16`.
    pub const FLOAT16: i32 = 9;
    /// `JS_TYPED_ARRAY_FLOAT32`.
    pub const FLOAT32: i32 = 10;
    /// `JS_TYPED_ARRAY_FLOAT64`.
    pub const FLOAT64: i32 = 11;
}

/// `JS_NewArrayBuffer`: an `ArrayBuffer` over `buf`, taking ownership of it.
///
/// `buf` may be null, which asks for a zero-filled buffer of `len` bytes — the reference's
/// behaviour, and the only way to build a buffer whose contents C fills in later.
///
/// `free_func` is called immediately after the bytes are copied; see the module docs for why.
///
/// # Safety
///
/// `buf` must be null or point at `len` readable bytes it is safe to release through
/// `free_func`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewArrayBuffer(
    ctx: *mut JsContext,
    buf: *mut u8,
    len: usize,
    free_func: FreeArrayBufferDataFunc,
    opaque: *mut c_void,
    is_shared: Bool,
) -> JsValue {
    let Some(_context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    if is_shared != 0 {
        // A shared buffer needs `SharedArrayBuffer`, which this engine installs only when a
        // host asks for atomics; the C API's `is_shared` is honoured by answering the plain
        // buffer, and the README records the gap.
        let _ = is_shared;
    }
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let bytes: Vec<u8> = if buf.is_null() {
        vec![0; len]
    } else {
        // SAFETY: the caller guarantees `len` readable bytes.
        unsafe { core::slice::from_raw_parts(buf, len) }.to_vec()
    };
    // The callback is attached to the storage and runs when *that* dies, which is when the
    // reference runs it too. The closure captures the raw pointers, and the C API's contract
    // is what makes that sound: `buf` belongs to the library from this call until `free_func`
    // runs, so nothing else may release it in between.
    let release: Option<Box<dyn FnOnce()>> = free_func.map(|free_func| {
        let buf = buf.cast::<c_void>();
        Box::new(move || {
            // SAFETY: `free_func` and `opaque` are the caller's, and the block is still
            // ours — this closure runs exactly once, from the storage's `Drop`.
            unsafe { free_func(opaque, buf) };
        }) as Box<dyn FnOnce()>
    });
    context.with_current_interp(|interp| {
        let buffer = match release {
            Some(release) => builtins_typed::new_array_buffer_with_release(interp, bytes, release),
            None => builtins_typed::new_array_buffer(interp, bytes),
        };
        jsvalue_of(Value::Object(buffer))
    })
}

/// `JS_DetachArrayBuffer`: take the storage away, leaving an empty detached buffer.
///
/// # Safety
///
/// `obj` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_DetachArrayBuffer(ctx: *mut JsContext, obj: JsValue) {
    let Some(_context) = (unsafe { ctx.as_ref() }) else {
        return;
    };
    let Some(Value::Object(object)) = (unsafe { arg(obj) }) else {
        return;
    };
    let Some(storage) = object.array_buffer_storage() else {
        return;
    };
    let mut storage = storage.borrow_mut();
    // `transfer()`'s semantics: the bytes stop being reachable through this buffer, and every
    // view over it starts answering zero length. Freeing them here rather than clearing is
    // what makes the detach observable as an allocation drop.
    storage.bytes = Vec::new();
    storage.detached = true;
}

/// `JS_NewTypedArray`: a view, built the way `new Uint8Array(...)` would be.
///
/// The arguments are the script constructor's, which is why this is one entry point rather
/// than one per element type: `argc`/`argv` are passed straight to the constructor.
///
/// # Safety
///
/// `argv` must point at `argc` live `JSValue`s.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewTypedArray(
    ctx: *mut JsContext,
    argc: c_int,
    argv: *const JsValue,
    array_type: c_int,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let element = match builtins_typed::element_from_kind(array_type) {
        Some(element) => element,
        None => {
            return runtime::throw_error(context, "TypeError", "unknown typed array kind");
        }
    };
    // SAFETY: the caller's contract on `argv`.
    let args = unsafe { crate::calls::decode_args(argc, argv) };
    let result = context
        .with_current_interp(|interp| builtins_typed::construct_typed_array(interp, element, args));
    runtime::result_value(context, result)
}

/// `JS_NewUint8Array`: a `Uint8Array` over a C block, taking ownership of it.
///
/// # Safety
///
/// `buf` must be null or point at `len` readable bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewUint8Array(
    ctx: *mut JsContext,
    buf: *mut u8,
    len: usize,
    free_func: FreeArrayBufferDataFunc,
    opaque: *mut c_void,
    is_shared: Bool,
) -> JsValue {
    // SAFETY: the caller's contract is `JS_NewArrayBuffer`'s.
    let buffer = unsafe { JS_NewArrayBuffer(ctx, buf, len, free_func, opaque, is_shared) };
    if buffer.is_exception() {
        return buffer;
    }
    // The view covers the whole buffer, which is what the reference builds.
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    context.with_current_interp(|interp| match unsafe { arg(buffer) } {
        Some(Value::Object(object)) => {
            let view = builtins_typed::new_view(interp, &object, builtins_typed::UINT8, 0, len);
            jsvalue_of(Value::Object(view))
        }
        _ => jsvalue::EXCEPTION,
    })
}

/// `JS_NewUint8ArrayCopy`: a `Uint8Array` holding a copy of `buf`.
///
/// # Safety
///
/// `buf` must be null or point at `len` readable bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewUint8ArrayCopy(
    ctx: *mut JsContext,
    buf: *const u8,
    len: usize,
) -> JsValue {
    // SAFETY: the caller's contract is `JS_NewArrayBufferCopy`'s.
    let buffer = unsafe { crate::bjson::JS_NewArrayBufferCopy(ctx, buf, len) };
    if buffer.is_exception() {
        return buffer;
    }
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    context.with_current_interp(|interp| match unsafe { arg(buffer) } {
        Some(Value::Object(object)) => {
            let view = builtins_typed::new_view(interp, &object, builtins_typed::UINT8, 0, len);
            jsvalue_of(Value::Object(view))
        }
        _ => jsvalue::EXCEPTION,
    })
}

/// `JS_NewUint8ArrayCopy2`: the same, optionally immutable.
///
/// This engine has no immutable-buffer extension, so `is_immutable` is refused rather than
/// silently ignored — a caller that needs the guarantee must not believe it got it.
///
/// # Safety
///
/// As [`JS_NewUint8ArrayCopy`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewUint8ArrayCopy2(
    ctx: *mut JsContext,
    buf: *const u8,
    len: usize,
    is_immutable: Bool,
) -> JsValue {
    if is_immutable != 0 {
        let Some(context) = (unsafe { ctx.as_ref() }) else {
            return jsvalue::EXCEPTION;
        };
        return runtime::throw_error(
            context,
            "TypeError",
            "immutable ArrayBuffers are not supported",
        );
    }
    // SAFETY: the caller's contract is `JS_NewUint8ArrayCopy`'s.
    unsafe { JS_NewUint8ArrayCopy(ctx, buf, len) }
}

/// `JS_GetTypedArrayBuffer`: the view's buffer and its geometry.
///
/// # Safety
///
/// The three out-pointers must be null or writable; `obj` a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetTypedArrayBuffer(
    ctx: *mut JsContext,
    obj: JsValue,
    pbyte_offset: *mut usize,
    pbyte_length: *mut usize,
    pbytes_per_element: *mut usize,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(Value::Object(object)) = (unsafe { arg(obj) }) else {
        return runtime::throw_error(context, "TypeError", "not a typed array");
    };
    let Some((buffer, element, offset, length)) = object.typed_array_parts() else {
        return runtime::throw_error(context, "TypeError", "not a typed array");
    };
    let size = element.size();
    if !pbyte_offset.is_null() {
        // SAFETY: the caller guarantees a writable pointer.
        unsafe { *pbyte_offset = offset * size };
    }
    if !pbyte_length.is_null() {
        // SAFETY: as above.
        unsafe { *pbyte_length = length * size };
    }
    if !pbytes_per_element.is_null() {
        // SAFETY: as above.
        unsafe { *pbytes_per_element = size };
    }
    jsvalue_of(Value::Object(buffer))
}

/// `JS_GetTypedArrayType`: the view's `JSTypedArrayEnum`, or `-1`.
///
/// # Safety
///
/// `obj` must be a live `JSValue`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetTypedArrayType(obj: JsValue) -> c_int {
    let Some(Value::Object(object)) = (unsafe { arg(obj) }) else {
        return -1;
    };
    match object.typed_array_element_type() {
        Some(element) => builtins_typed::kind_from_element(element),
        None => -1,
    }
}

/// `JS_AtomicsPollWaiters`: how many waiters a `SharedArrayBuffer` has.
///
/// Atomics on a shared buffer need threads this engine does not have
/// (`docs/m15-plan.md` §5 rejects the worker model), so there is never a waiter.
///
/// # Safety
///
/// `ctx` is ignored.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_AtomicsPollWaiters(_ctx: *mut JsContext) -> i64 {
    0
}

/// `JS_AtomicsSetAsyncWaker`: register a wake-up callback for `Atomics.waitAsync`.
///
/// # Safety
///
/// The arguments are ignored.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_AtomicsSetAsyncWaker(_cb: *const c_void, _opaque: *mut c_void) {}

/// `JS_SetSharedArrayBufferFunctions`: install the host's shared-memory allocator.
///
/// # Safety
///
/// `sf` is copied field-wise by the reference; here it is only recorded as "not supported".
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetSharedArrayBufferFunctions(
    _rt: *mut runtime::JsRuntime,
    _sf: *const c_void,
) {
}

/// `JS_JSONStringify`: `JSON.stringify(obj, replacer, space)`.
///
/// The engine's own `JSON.stringify` is reached through the global object rather than through
/// a Rust entry point, because the replacer can be an arbitrary script function and the
/// engine's implementation already handles every shape of it.
///
/// # Safety
///
/// All three values must be live.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_JSONStringify(
    ctx: *mut JsContext,
    obj: JsValue,
    replacer: JsValue,
    space0: JsValue,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let value = unsafe { arg(obj) }.unwrap_or(Value::Undefined);
    let replacer = unsafe { arg(replacer) }.unwrap_or(Value::Undefined);
    let space = unsafe { arg(space0) }.unwrap_or(Value::Undefined);
    let result = context.with_current_interp(|interp| {
        let global = Value::Object(interp.realm.global.clone());
        let json = interp.read_field(&global, "JSON")?;
        let stringify = interp.read_field(&json, "stringify")?;
        interp.call_value(stringify, json, vec![value, replacer, space])
    });
    runtime::result_value(context, result)
}

/// `JS_ParseJSON`: parse `buf_len` bytes as JSON.
///
/// # Safety
///
/// `buf` must point at `buf_len` readable bytes; `filename` may be null.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ParseJSON(
    ctx: *mut JsContext,
    buf: *const core::ffi::c_char,
    buf_len: usize,
    filename: *const core::ffi::c_char,
) -> JsValue {
    // SAFETY: the caller's contract is `JS_ParseJSON2`'s with `flags == 0`.
    unsafe { JS_ParseJSON2(ctx, buf, buf_len, filename, 0) }
}

/// `JS_ParseJSON2`: parse JSON, optionally as extended JSON.
///
/// `JS_PARSE_JSON_EXT` (bit 0) enables the reference's extension — comments, single quotes,
/// trailing commas and `NaN`/`Infinity` — which the engine has as `parse_ext_json`.
///
/// # Safety
///
/// As [`JS_ParseJSON`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ParseJSON2(
    ctx: *mut JsContext,
    buf: *const core::ffi::c_char,
    buf_len: usize,
    _filename: *const core::ffi::c_char,
    flags: c_int,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    if buf.is_null() {
        return runtime::throw_error(context, "SyntaxError", "null JSON");
    }
    // SAFETY: the caller guarantees `buf_len` readable bytes.
    let bytes = unsafe { core::slice::from_raw_parts(buf.cast::<u8>(), buf_len) };
    let text = String::from_utf8_lossy(bytes).into_owned();
    const JS_PARSE_JSON_EXT: c_int = 1 << 0;
    let extended = flags & JS_PARSE_JSON_EXT != 0;
    let result = context
        .with_current_interp(|interp| engine::builtins::json::parse_text(interp, &text, extended));
    runtime::result_value(context, result)
}

/// `JS_ParseJSON3`: the same, plus a record of where each value came from.
///
/// The parse record is a debug/IDE feature (source positions for a JSON document); this layer
/// does not produce one, so it parses and leaves `pr` untouched. A caller that needs the record
/// must not use this library — recorded in the README rather than pretended.
///
/// # Safety
///
/// As [`JS_ParseJSON2`]; `pr` may be null.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ParseJSON3(
    ctx: *mut JsContext,
    buf: *const core::ffi::c_char,
    buf_len: usize,
    filename: *const core::ffi::c_char,
    flags: c_int,
    _pr: *mut c_void,
) -> JsValue {
    // SAFETY: the caller's contract is `JS_ParseJSON2`'s.
    unsafe { JS_ParseJSON2(ctx, buf, buf_len, filename, flags) }
}

/// `JS_SameValue`: `Object.is(a, b)`.
///
/// # Safety
///
/// Both values must be live.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SameValue(_ctx: *mut JsContext, op1: JsValue, op2: JsValue) -> Bool {
    match (unsafe { arg(op1) }, unsafe { arg(op2) }) {
        (Some(left), Some(right)) => c_int::from(left.same_value(&right)),
        _ => 0,
    }
}

/// `JS_SameValueZero`: `SameValueZero` — `Object.is` except that `±0` are equal.
///
/// # Safety
///
/// Both values must be live.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SameValueZero(
    _ctx: *mut JsContext,
    op1: JsValue,
    op2: JsValue,
) -> Bool {
    match (unsafe { arg(op1) }, unsafe { arg(op2) }) {
        (Some(left), Some(right)) => c_int::from(left.same_value_zero(&right)),
        _ => 0,
    }
}

/// `JS_StrictEq`: `a === b`.
///
/// # Safety
///
/// Both values must be live.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_StrictEq(_ctx: *mut JsContext, op1: JsValue, op2: JsValue) -> Bool {
    match (unsafe { arg(op1) }, unsafe { arg(op2) }) {
        (Some(left), Some(right)) => c_int::from(left.strict_equals(&right)),
        _ => 0,
    }
}

/// `JS_NewSymbol`'s atom-keyed cousin: nothing here, but `Atom` is imported so a reader
/// looking for the atom-keyed property family finds the reason it lives next door.
const _: Option<Atom> = None;