quickjs-capi 0.13.1

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
//! `JSValue`: the 8-byte NaN-boxed value the C API hands across the boundary.
//!
//! # Why this has to be bit-compatible
//!
//! Half of `quickjs.h`'s "functions" are `static inline` and expand in the *caller*:
//!
//! ```c
//! static inline void JS_FreeValue(JSContext *ctx, JSValue v) {
//!     if (JS_VALUE_HAS_REF_COUNT(v)) {
//!         JSRefCountHeader *p = __js_rc(JS_VALUE_GET_PTR(v));   /* (uint32_t *)ptr - 1 */
//!         if (--p->ref_count <= 0) __JS_FreeValue(ctx, v);
//!     }
//! }
//! ```
//!
//! So compiled C code never asks us how a `JSValue` is laid out — it decodes the bits
//! itself and writes through the pointer. A handle table (a `JSValue` that is really an
//! index) segfaults on the first `JS_DupValue`, which is why this module reproduces the
//! reference's encoding exactly rather than round-tripping through a private form.
//!
//! Everything here is integer arithmetic: no `unsafe`, and no dependence on the engine's
//! own 16-byte `Value`. This is the *bit* half of the boundary; [`crate::alloc`] is the
//! memory half.
//!
//! # Layout
//!
//! `bits 47..64` are the tag, read as a *signed* 32-bit integer; `bits 0..47` are the
//! payload. A negative tag means the payload is a pointer to a reference-counted
//! allocation. Floats fit because the tag range `-8..=7` is checked first: anything
//! outside it is a double whose bits had [`FLOAT64_ADDEND`] subtracted on the way in.
//!
//! The constants below are the reference's, and `tests/abi.rs` pins each one against a
//! value `gcc` printed for the same expression.

/// `JS_NAN_BOX_TAG_SHIFT`: how far the tag is shifted.
pub const TAG_SHIFT: u32 = 47;

/// The payload mask: `(1 << TAG_SHIFT) - 1`.
pub const PAYLOAD_MASK: u64 = (1u64 << TAG_SHIFT) - 1;

/// `JS_FLOAT64_ADDEND`: what a double's bits have added to them so the result lands
/// outside the integer tag range.
pub const FLOAT64_ADDEND: u64 = 0x7ff8_0000_0000_0000 + (8u64 << TAG_SHIFT);

/// `JS_NAN`: the canonical NaN. Every NaN is normalised to this one value, which is what
/// makes `NaN === NaN` behaviour depend on the interpreter rather than on bit patterns.
pub const NAN: u64 = 0xfff8_0000_0000_0000 - FLOAT64_ADDEND;

/// `JS_TAG_FIRST`: the most negative tag, and the first one that carries a reference
/// count.
pub const TAG_FIRST: i32 = -8;

/// `JS_TAG_BIG_INT`.
pub const TAG_BIG_INT: i32 = -7;
/// `JS_TAG_SYMBOL`.
pub const TAG_SYMBOL: i32 = -6;
/// `JS_TAG_STRING`.
pub const TAG_STRING: i32 = -5;
/// `JS_TAG_STRING_ROPE`: the reference's concatenation node. Never produced here — the
/// engine's strings are flat — but every reader in `quickjs.h` knows the tag, so a value
/// arriving with it must be recognised rather than mistaken for a double.
pub const TAG_STRING_ROPE: i32 = -4;
/// `JS_TAG_MODULE`: internal to the reference's module table.
pub const TAG_MODULE: i32 = -3;
/// `JS_TAG_FUNCTION_BYTECODE`: internal to the reference's bytecode objects.
pub const TAG_FUNCTION_BYTECODE: i32 = -2;
/// `JS_TAG_OBJECT`.
pub const TAG_OBJECT: i32 = -1;
/// `JS_TAG_INT`.
pub const TAG_INT: i32 = 0;
/// `JS_TAG_BOOL`.
pub const TAG_BOOL: i32 = 1;
/// `JS_TAG_NULL`.
pub const TAG_NULL: i32 = 2;
/// `JS_TAG_UNDEFINED`.
pub const TAG_UNDEFINED: i32 = 3;
/// `JS_TAG_UNINITIALIZED`: a `let` before its declaration ran.
pub const TAG_UNINITIALIZED: i32 = 4;
/// `JS_TAG_CATCH_OFFSET`: the reference's operand-stack marker for a `catch` target.
pub const TAG_CATCH_OFFSET: i32 = 5;
/// `JS_TAG_EXCEPTION`: the value a failed call answers. Never observable from script.
pub const TAG_EXCEPTION: i32 = 6;
/// `JS_TAG_SHORT_BIG_INT`: a `BigInt` whose value fits in 32 bits.
pub const TAG_SHORT_BIG_INT: i32 = 7;
/// `JS_TAG_FLOAT64`.
pub const TAG_FLOAT64: i32 = 8;

/// `JS_UNDEFINED`.
pub const UNDEFINED: JsValue = JsValue::new((TAG_UNDEFINED as u64) << TAG_SHIFT);
/// `JS_NULL`.
pub const NULL: JsValue = JsValue::new((TAG_NULL as u64) << TAG_SHIFT);
/// `JS_EXCEPTION`.
pub const EXCEPTION: JsValue = JsValue::new((TAG_EXCEPTION as u64) << TAG_SHIFT);
/// `JS_UNINITIALIZED`.
pub const UNINITIALIZED: JsValue = JsValue::new((TAG_UNINITIALIZED as u64) << TAG_SHIFT);

/// A `JSValue`: the eight bytes the C API passes by value.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct JsValue(u64);

impl JsValue {
    /// Wrap raw bits. The only way to build one without going through a constructor, and
    /// what `JS_VALUE_GET_*` is on the other side of.
    #[inline]
    pub const fn new(bits: u64) -> JsValue {
        JsValue(bits)
    }

    /// The raw bits (`JS_VALUE_GET_UINT64`).
    #[inline]
    pub const fn bits(self) -> u64 {
        self.0
    }

    /// The tag, as `JS_VALUE_GET_TAG` computes it: an arithmetic shift of the whole word.
    ///
    /// A negative answer is a reference-counted payload, and only `-1` (`OBJECT`) can
    /// reach the engine: the reference's other negative tags name its own containers
    /// (strings, symbols, bytecode, modules) which live inside objects here instead.
    #[inline]
    pub const fn tag(self) -> i32 {
        ((self.0 as i64) >> TAG_SHIFT) as i32
    }

    /// `JS_VALUE_GET_NORM_TAG`: the tag with every float spelling collapsed to
    /// `JS_TAG_FLOAT64`.
    #[inline]
    pub const fn norm_tag(self) -> i32 {
        if self.is_float() {
            TAG_FLOAT64
        } else {
            self.tag()
        }
    }

    /// `JS_TAG_IS_FLOAT64(tag)`: whether a tag outside the named range means "double".
    #[inline]
    pub const fn tag_is_float(tag: i32) -> bool {
        (tag.wrapping_sub(TAG_FIRST) as u32) >= (TAG_FLOAT64 - TAG_FIRST) as u32
    }

    /// Whether this value is a double (`JS_TAG_IS_FLOAT64(JS_VALUE_GET_NORM_TAG(v))`).
    #[inline]
    pub const fn is_float(self) -> bool {
        JsValue::tag_is_float(self.tag())
    }

    /// `JS_VALUE_IS_NAN`.
    #[inline]
    pub const fn is_nan(self) -> bool {
        self.tag() == (NAN as i64 >> TAG_SHIFT) as i32
    }

    /// `JS_VALUE_HAS_REF_COUNT`: every negative tag.
    #[inline]
    pub const fn has_ref_count(self) -> bool {
        (self.tag() as u32) >= (TAG_FIRST as u32)
    }

    /// `JS_VALUE_GET_PTR`: the low 47 bits as a pointer.
    ///
    /// Matching the reference means *not* checking the range here — the mask is what C
    /// does — and rejecting an out-of-range pointer at the point it is built instead
    /// ([`JsValue::mkptr`]).
    #[inline]
    pub const fn payload(self) -> u64 {
        self.0 & PAYLOAD_MASK
    }

    /// `JS_MKVAL(tag, val)`: a tag with a 32-bit payload.
    #[inline]
    pub const fn mkval(tag: i32, val: u32) -> JsValue {
        JsValue::new(((tag as i64 as u64) << TAG_SHIFT) | val as u64)
    }

    /// `JS_MKPTR(tag, ptr)`: a tag with a pointer payload.
    ///
    /// # Panics
    ///
    /// When `ptr` does not fit in 47 bits. That is a broken invariant rather than a
    /// recoverable error: the reference would truncate the pointer and hand C a value
    /// that reads and writes the wrong memory. Every allocator this crate controls keeps
    /// its blocks in the low half of the address space; a host that supplies its own
    /// allocator has to keep the same promise (see `docs/m15-plan.md` §3, D1).
    #[inline]
    pub fn mkptr(tag: i32, ptr: *mut ()) -> JsValue {
        let address = ptr as usize as u64;
        assert!(
            address <= PAYLOAD_MASK,
            "pointer above 47 bits cannot be NaN-boxed"
        );
        JsValue::new(((tag as i64 as u64) << TAG_SHIFT) | address)
    }

    /// `JS_IsException`.
    #[inline]
    pub const fn is_exception(self) -> bool {
        self.0 == EXCEPTION.0
    }

    /// `JS_IsUndefined`.
    #[inline]
    pub const fn is_undefined(self) -> bool {
        self.0 == UNDEFINED.0
    }

    /// `JS_IsNull`.
    #[inline]
    pub const fn is_null(self) -> bool {
        self.0 == NULL.0
    }

    /// `JS_IsBool`.
    #[inline]
    pub const fn is_bool(self) -> bool {
        self.0 == TRUE.0 || self.0 == FALSE.0
    }

    /// `JS_IsNumber`: an integer or a double.
    #[inline]
    pub const fn is_number(self) -> bool {
        self.tag() == TAG_INT || self.is_float()
    }

    /// `JS_IsObject`.
    #[inline]
    pub const fn is_object(self) -> bool {
        self.tag() == TAG_OBJECT
    }

    /// `JS_IsString`.
    #[inline]
    pub const fn is_string(self) -> bool {
        self.tag() == TAG_STRING
    }

    /// The integer payload, as `JS_VALUE_GET_INT`.
    #[inline]
    pub const fn to_int(self) -> i32 {
        self.0 as u32 as i32
    }

    /// The boolean payload, as `JS_VALUE_GET_BOOL`.
    #[inline]
    pub const fn to_bool(self) -> bool {
        (self.0 as u32 & 1) != 0
    }

    /// The double, as `JS_VALUE_GET_FLOAT64`.
    ///
    /// No tag check: the reference's macro does not have one either, and its callers
    /// always know the tag. [`JsValue::as_float`] is the checked spelling.
    #[inline]
    pub const fn to_float(self) -> f64 {
        f64::from_bits(self.0.wrapping_add(FLOAT64_ADDEND))
    }

    /// The double, when this value is one.
    #[inline]
    pub const fn as_float(self) -> Option<f64> {
        if self.is_float() {
            Some(self.to_float())
        } else {
            None
        }
    }

    /// The pointer, when this value is a reference-counted one.
    ///
    /// `None` rather than a null pointer for a non-pointer tag: the reference's macro
    /// answers garbage there, and every caller of ours would have to re-check the tag.
    #[inline]
    pub fn as_ptr(self) -> Option<*mut ()> {
        if self.has_ref_count() {
            Some(self.payload() as usize as *mut ())
        } else {
            None
        }
    }
}

/// `JS_TRUE`.
pub const TRUE: JsValue = JsValue::mkval(TAG_BOOL, 1);
/// `JS_FALSE`.
pub const FALSE: JsValue = JsValue::mkval(TAG_BOOL, 0);

/// `JS_NewInt32`: an integer, which is the bare payload with no tag bits at all.
///
/// Only 32 bits fit, which is why `JS_NewInt64` in the reference promotes anything wider
/// to a double.
#[inline]
pub const fn new_int32(value: i32) -> JsValue {
    JsValue::mkval(TAG_INT, value as u32)
}

/// `JS_NewBool`.
#[inline]
pub const fn new_bool(value: bool) -> JsValue {
    if value { TRUE } else { FALSE }
}

/// `JS_NewFloat64` (which is the inline `__JS_NewFloat64`): a double, with every NaN
/// normalised to [`NAN`].
#[inline]
pub fn new_float64(value: f64) -> JsValue {
    JsValue::new(float64_bits(value))
}

/// The encoding [`new_float64`] performs, exposed because the allocator's tests and the
/// ABI table want the bits rather than a value.
#[inline]
pub fn float64_bits(value: f64) -> u64 {
    if value.is_nan() {
        NAN
    } else {
        value.to_bits().wrapping_sub(FLOAT64_ADDEND)
    }
}

impl Default for JsValue {
    /// `JS_UNDEFINED`, which is what a zero-initialised `JSValue` must **not** be: bits
    /// `0` decode as the integer `0`.
    fn default() -> JsValue {
        UNDEFINED
    }
}

impl core::fmt::Debug for JsValue {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self.norm_tag() {
            TAG_UNDEFINED => write!(f, "undefined"),
            TAG_NULL => write!(f, "null"),
            TAG_BOOL => write!(f, "{}", self.to_bool()),
            TAG_INT => write!(f, "{}", self.to_int()),
            TAG_FLOAT64 => write!(f, "{}", self.to_float()),
            TAG_EXCEPTION => write!(f, "<exception>"),
            TAG_OBJECT => write!(f, "object@{:#x}", self.payload()),
            tag => write!(f, "<tag {tag}>"),
        }
    }
}

// ---------------------------------------------------------------------------
// Engine values
// ---------------------------------------------------------------------------

/// The tag a reference-counted engine value is boxed under.
///
/// Every refcounted payload the C API can see is an `Object` here, including strings and
/// symbols: the engine's `Value` is a 16-byte enum, so the distinction lives *inside* the
/// box rather than in the tag. That is invisible from C — `JS_IsString` is answered by
/// asking the box, not by looking at the tag — and it keeps one allocation shape instead
/// of five.
///
/// The exception is a string, which `JS_IsString` and `JS_ToString` both need to
/// recognise, and which C-side code never dereferences beyond `ref_count`.
pub const ENGINE_BOX_TAG: i32 = TAG_OBJECT;

/// The tag an engine string is boxed under.
pub const ENGINE_STRING_TAG: i32 = TAG_STRING;

/// Whether a C value's tag is one this layer can decode back into an engine value.
pub fn is_engine_tag(tag: i32) -> bool {
    tag == TAG_OBJECT || tag == TAG_STRING || tag == TAG_SYMBOL || tag == TAG_BIG_INT
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `JS_NewInt32(0)` and `JS_UNDEFINED` differ in nothing but the tag, which is why a
    /// zeroed `JSValue` is `0` and not `undefined`.
    #[test]
    fn zero_bits_are_the_integer_zero() {
        assert_eq!(JsValue::new(0).norm_tag(), TAG_INT);
        assert_eq!(JsValue::new(0).to_int(), 0);
        assert_ne!(JsValue::new(0), UNDEFINED);
        assert_eq!(JsValue::default(), UNDEFINED);
    }

    #[test]
    fn negative_integers_keep_their_sign() {
        assert_eq!(new_int32(-1).to_int(), -1);
        assert_eq!(new_int32(-1).tag(), TAG_INT);
        assert_eq!(new_int32(i32::MIN).to_int(), i32::MIN);
        // The payload is only 32 bits wide for an int, so the high tag bits stay zero.
        assert_eq!(new_int32(-1).bits(), 0xffff_ffff);
    }

    #[test]
    fn floats_round_trip_and_nan_is_canonical() {
        for value in [0.0, -0.0, 1.5, -1.5, f64::MIN, f64::MAX, f64::EPSILON] {
            let encoded = new_float64(value);
            assert_eq!(encoded.norm_tag(), TAG_FLOAT64, "{value}");
            assert_eq!(encoded.to_float().to_bits(), value.to_bits(), "{value}");
        }
        // Every NaN spelling becomes the same value, which is what makes
        // `Object.is(NaN, NaN)` answer true without a special case.
        let quiet = new_float64(f64::from_bits(0x7ff8_0000_0000_0001));
        let signalling = new_float64(f64::from_bits(0x7ff0_0000_0000_0001));
        assert_eq!(quiet, signalling);
        assert_eq!(quiet.bits(), NAN);
        assert!(quiet.is_nan());
        assert!(quiet.to_float().is_nan());
    }

    #[test]
    fn tag_is_read_as_a_signed_shift() {
        assert_eq!(UNDEFINED.tag(), TAG_UNDEFINED);
        assert_eq!(NULL.tag(), TAG_NULL);
        assert_eq!(EXCEPTION.tag(), TAG_EXCEPTION);
        assert_eq!(TRUE.tag(), TAG_BOOL);
        assert_eq!(new_int32(7).tag(), TAG_INT);
        // A double lands *outside* the named tag range, which is exactly how
        // `JS_TAG_IS_FLOAT64` recognises it — the encoding is subtractive, so a positive
        // double ends up with a large negative tag. Nothing enumerates floats.
        assert_eq!(new_float64(1.0).norm_tag(), TAG_FLOAT64);
        assert!(!(-8..=7).contains(&new_float64(1.0).tag()));
    }

    #[test]
    fn every_double_is_outside_the_refcount_range() {
        // This is why `__JS_NewFloat64` normalises NaN: a NaN whose bits are
        // `0x7ffb_8000_0000_0000` would encode to `0xffff_8000_0000_0000`, i.e. tag `-1`,
        // and C's `JS_VALUE_HAS_REF_COUNT` would read it as an object pointer. With every
        // NaN mapped to one canonical value, no double can collide with the tag range.
        let doubles = [
            0.0,
            -0.0,
            1.0,
            -1.0,
            1.5,
            f64::MIN,
            f64::MAX,
            f64::MIN_POSITIVE,
            f64::INFINITY,
            f64::NEG_INFINITY,
            f64::NAN,
            f64::from_bits(0x7ffb_8000_0000_0000),
            f64::from_bits(0xffff_ffff_ffff_ffff),
        ];
        for value in doubles {
            let encoded = new_float64(value);
            assert!(
                encoded.is_float(),
                "{value} encoded as tag {}",
                encoded.tag()
            );
            assert!(
                !encoded.has_ref_count(),
                "{value} encoded inside the reference-count tag range"
            );
            assert_eq!(encoded.norm_tag(), TAG_FLOAT64, "{value}");
        }
    }

    #[test]
    fn only_negative_tags_carry_a_reference_count() {
        assert!(JsValue::mkptr(TAG_OBJECT, 0x1000 as *mut ()).has_ref_count());
        assert!(JsValue::mkptr(TAG_STRING, 0x1000 as *mut ()).has_ref_count());
        assert!(!UNDEFINED.has_ref_count());
        assert!(!new_int32(0).has_ref_count());
        assert!(!new_float64(1.5).has_ref_count());
        assert_eq!(
            JsValue::mkptr(TAG_OBJECT, 0x1000 as *mut ()).payload(),
            0x1000
        );
    }

    #[test]
    fn pointers_below_47_bits_round_trip() {
        for address in [0x1000usize, 0x7fff_ffff_ffff] {
            let value = JsValue::mkptr(TAG_OBJECT, address as *mut ());
            assert_eq!(value.payload() as usize, address);
            assert_eq!(value.as_ptr().unwrap() as usize, address);
            assert!(value.is_object());
        }
        // The payload is masked, so the tag bits above 47 do not leak into it.
        assert_eq!(
            JsValue::mkptr(TAG_OBJECT, 0x7fff_ffff_ffff as *mut ()).bits() >> TAG_SHIFT,
            (-1i64 as u64) >> TAG_SHIFT
        );
        assert_eq!(UNDEFINED.as_ptr(), None);
    }
}