Skip to main content

quickjs/
jsvalue.rs

1//! `JSValue`: the 8-byte NaN-boxed value the C API hands across the boundary.
2//!
3//! # Why this has to be bit-compatible
4//!
5//! Half of `quickjs.h`'s "functions" are `static inline` and expand in the *caller*:
6//!
7//! ```c
8//! static inline void JS_FreeValue(JSContext *ctx, JSValue v) {
9//!     if (JS_VALUE_HAS_REF_COUNT(v)) {
10//!         JSRefCountHeader *p = __js_rc(JS_VALUE_GET_PTR(v));   /* (uint32_t *)ptr - 1 */
11//!         if (--p->ref_count <= 0) __JS_FreeValue(ctx, v);
12//!     }
13//! }
14//! ```
15//!
16//! So compiled C code never asks us how a `JSValue` is laid out — it decodes the bits
17//! itself and writes through the pointer. A handle table (a `JSValue` that is really an
18//! index) segfaults on the first `JS_DupValue`, which is why this module reproduces the
19//! reference's encoding exactly rather than round-tripping through a private form.
20//!
21//! Everything here is integer arithmetic: no `unsafe`, and no dependence on the engine's
22//! own 16-byte `Value`. This is the *bit* half of the boundary; [`crate::alloc`] is the
23//! memory half.
24//!
25//! # Layout
26//!
27//! `bits 47..64` are the tag, read as a *signed* 32-bit integer; `bits 0..47` are the
28//! payload. A negative tag means the payload is a pointer to a reference-counted
29//! allocation. Floats fit because the tag range `-8..=7` is checked first: anything
30//! outside it is a double whose bits had [`FLOAT64_ADDEND`] subtracted on the way in.
31//!
32//! The constants below are the reference's, and `tests/abi.rs` pins each one against a
33//! value `gcc` printed for the same expression.
34
35/// `JS_NAN_BOX_TAG_SHIFT`: how far the tag is shifted.
36pub const TAG_SHIFT: u32 = 47;
37
38/// The payload mask: `(1 << TAG_SHIFT) - 1`.
39pub const PAYLOAD_MASK: u64 = (1u64 << TAG_SHIFT) - 1;
40
41/// `JS_FLOAT64_ADDEND`: what a double's bits have added to them so the result lands
42/// outside the integer tag range.
43pub const FLOAT64_ADDEND: u64 = 0x7ff8_0000_0000_0000 + (8u64 << TAG_SHIFT);
44
45/// `JS_NAN`: the canonical NaN. Every NaN is normalised to this one value, which is what
46/// makes `NaN === NaN` behaviour depend on the interpreter rather than on bit patterns.
47pub const NAN: u64 = 0xfff8_0000_0000_0000 - FLOAT64_ADDEND;
48
49/// `JS_TAG_FIRST`: the most negative tag, and the first one that carries a reference
50/// count.
51pub const TAG_FIRST: i32 = -8;
52
53/// `JS_TAG_BIG_INT`.
54pub const TAG_BIG_INT: i32 = -7;
55/// `JS_TAG_SYMBOL`.
56pub const TAG_SYMBOL: i32 = -6;
57/// `JS_TAG_STRING`.
58pub const TAG_STRING: i32 = -5;
59/// `JS_TAG_STRING_ROPE`: the reference's concatenation node. Never produced here — the
60/// engine's strings are flat — but every reader in `quickjs.h` knows the tag, so a value
61/// arriving with it must be recognised rather than mistaken for a double.
62pub const TAG_STRING_ROPE: i32 = -4;
63/// `JS_TAG_MODULE`: internal to the reference's module table.
64pub const TAG_MODULE: i32 = -3;
65/// `JS_TAG_FUNCTION_BYTECODE`: internal to the reference's bytecode objects.
66pub const TAG_FUNCTION_BYTECODE: i32 = -2;
67/// `JS_TAG_OBJECT`.
68pub const TAG_OBJECT: i32 = -1;
69/// `JS_TAG_INT`.
70pub const TAG_INT: i32 = 0;
71/// `JS_TAG_BOOL`.
72pub const TAG_BOOL: i32 = 1;
73/// `JS_TAG_NULL`.
74pub const TAG_NULL: i32 = 2;
75/// `JS_TAG_UNDEFINED`.
76pub const TAG_UNDEFINED: i32 = 3;
77/// `JS_TAG_UNINITIALIZED`: a `let` before its declaration ran.
78pub const TAG_UNINITIALIZED: i32 = 4;
79/// `JS_TAG_CATCH_OFFSET`: the reference's operand-stack marker for a `catch` target.
80pub const TAG_CATCH_OFFSET: i32 = 5;
81/// `JS_TAG_EXCEPTION`: the value a failed call answers. Never observable from script.
82pub const TAG_EXCEPTION: i32 = 6;
83/// `JS_TAG_SHORT_BIG_INT`: a `BigInt` whose value fits in 32 bits.
84pub const TAG_SHORT_BIG_INT: i32 = 7;
85/// `JS_TAG_FLOAT64`.
86pub const TAG_FLOAT64: i32 = 8;
87
88/// `JS_UNDEFINED`.
89pub const UNDEFINED: JsValue = JsValue::new((TAG_UNDEFINED as u64) << TAG_SHIFT);
90/// `JS_NULL`.
91pub const NULL: JsValue = JsValue::new((TAG_NULL as u64) << TAG_SHIFT);
92/// `JS_EXCEPTION`.
93pub const EXCEPTION: JsValue = JsValue::new((TAG_EXCEPTION as u64) << TAG_SHIFT);
94/// `JS_UNINITIALIZED`.
95pub const UNINITIALIZED: JsValue = JsValue::new((TAG_UNINITIALIZED as u64) << TAG_SHIFT);
96
97/// A `JSValue`: the eight bytes the C API passes by value.
98#[derive(Clone, Copy, PartialEq, Eq, Hash)]
99#[repr(transparent)]
100pub struct JsValue(u64);
101
102impl JsValue {
103    /// Wrap raw bits. The only way to build one without going through a constructor, and
104    /// what `JS_VALUE_GET_*` is on the other side of.
105    #[inline]
106    pub const fn new(bits: u64) -> JsValue {
107        JsValue(bits)
108    }
109
110    /// The raw bits (`JS_VALUE_GET_UINT64`).
111    #[inline]
112    pub const fn bits(self) -> u64 {
113        self.0
114    }
115
116    /// The tag, as `JS_VALUE_GET_TAG` computes it: an arithmetic shift of the whole word.
117    ///
118    /// A negative answer is a reference-counted payload, and only `-1` (`OBJECT`) can
119    /// reach the engine: the reference's other negative tags name its own containers
120    /// (strings, symbols, bytecode, modules) which live inside objects here instead.
121    #[inline]
122    pub const fn tag(self) -> i32 {
123        ((self.0 as i64) >> TAG_SHIFT) as i32
124    }
125
126    /// `JS_VALUE_GET_NORM_TAG`: the tag with every float spelling collapsed to
127    /// `JS_TAG_FLOAT64`.
128    #[inline]
129    pub const fn norm_tag(self) -> i32 {
130        if self.is_float() {
131            TAG_FLOAT64
132        } else {
133            self.tag()
134        }
135    }
136
137    /// `JS_TAG_IS_FLOAT64(tag)`: whether a tag outside the named range means "double".
138    #[inline]
139    pub const fn tag_is_float(tag: i32) -> bool {
140        (tag.wrapping_sub(TAG_FIRST) as u32) >= (TAG_FLOAT64 - TAG_FIRST) as u32
141    }
142
143    /// Whether this value is a double (`JS_TAG_IS_FLOAT64(JS_VALUE_GET_NORM_TAG(v))`).
144    #[inline]
145    pub const fn is_float(self) -> bool {
146        JsValue::tag_is_float(self.tag())
147    }
148
149    /// `JS_VALUE_IS_NAN`.
150    #[inline]
151    pub const fn is_nan(self) -> bool {
152        self.tag() == (NAN as i64 >> TAG_SHIFT) as i32
153    }
154
155    /// `JS_VALUE_HAS_REF_COUNT`: every negative tag.
156    #[inline]
157    pub const fn has_ref_count(self) -> bool {
158        (self.tag() as u32) >= (TAG_FIRST as u32)
159    }
160
161    /// `JS_VALUE_GET_PTR`: the low 47 bits as a pointer.
162    ///
163    /// Matching the reference means *not* checking the range here — the mask is what C
164    /// does — and rejecting an out-of-range pointer at the point it is built instead
165    /// ([`JsValue::mkptr`]).
166    #[inline]
167    pub const fn payload(self) -> u64 {
168        self.0 & PAYLOAD_MASK
169    }
170
171    /// `JS_MKVAL(tag, val)`: a tag with a 32-bit payload.
172    #[inline]
173    pub const fn mkval(tag: i32, val: u32) -> JsValue {
174        JsValue::new(((tag as i64 as u64) << TAG_SHIFT) | val as u64)
175    }
176
177    /// `JS_MKPTR(tag, ptr)`: a tag with a pointer payload.
178    ///
179    /// # Panics
180    ///
181    /// When `ptr` does not fit in 47 bits. That is a broken invariant rather than a
182    /// recoverable error: the reference would truncate the pointer and hand C a value
183    /// that reads and writes the wrong memory. Every allocator this crate controls keeps
184    /// its blocks in the low half of the address space; a host that supplies its own
185    /// allocator has to keep the same promise (see `docs/m15-plan.md` §3, D1).
186    #[inline]
187    pub fn mkptr(tag: i32, ptr: *mut ()) -> JsValue {
188        let address = ptr as usize as u64;
189        assert!(
190            address <= PAYLOAD_MASK,
191            "pointer above 47 bits cannot be NaN-boxed"
192        );
193        JsValue::new(((tag as i64 as u64) << TAG_SHIFT) | address)
194    }
195
196    /// `JS_IsException`.
197    #[inline]
198    pub const fn is_exception(self) -> bool {
199        self.0 == EXCEPTION.0
200    }
201
202    /// `JS_IsUndefined`.
203    #[inline]
204    pub const fn is_undefined(self) -> bool {
205        self.0 == UNDEFINED.0
206    }
207
208    /// `JS_IsNull`.
209    #[inline]
210    pub const fn is_null(self) -> bool {
211        self.0 == NULL.0
212    }
213
214    /// `JS_IsBool`.
215    #[inline]
216    pub const fn is_bool(self) -> bool {
217        self.0 == TRUE.0 || self.0 == FALSE.0
218    }
219
220    /// `JS_IsNumber`: an integer or a double.
221    #[inline]
222    pub const fn is_number(self) -> bool {
223        self.tag() == TAG_INT || self.is_float()
224    }
225
226    /// `JS_IsObject`.
227    #[inline]
228    pub const fn is_object(self) -> bool {
229        self.tag() == TAG_OBJECT
230    }
231
232    /// `JS_IsString`.
233    #[inline]
234    pub const fn is_string(self) -> bool {
235        self.tag() == TAG_STRING
236    }
237
238    /// The integer payload, as `JS_VALUE_GET_INT`.
239    #[inline]
240    pub const fn to_int(self) -> i32 {
241        self.0 as u32 as i32
242    }
243
244    /// The boolean payload, as `JS_VALUE_GET_BOOL`.
245    #[inline]
246    pub const fn to_bool(self) -> bool {
247        (self.0 as u32 & 1) != 0
248    }
249
250    /// The double, as `JS_VALUE_GET_FLOAT64`.
251    ///
252    /// No tag check: the reference's macro does not have one either, and its callers
253    /// always know the tag. [`JsValue::as_float`] is the checked spelling.
254    #[inline]
255    pub const fn to_float(self) -> f64 {
256        f64::from_bits(self.0.wrapping_add(FLOAT64_ADDEND))
257    }
258
259    /// The double, when this value is one.
260    #[inline]
261    pub const fn as_float(self) -> Option<f64> {
262        if self.is_float() {
263            Some(self.to_float())
264        } else {
265            None
266        }
267    }
268
269    /// The pointer, when this value is a reference-counted one.
270    ///
271    /// `None` rather than a null pointer for a non-pointer tag: the reference's macro
272    /// answers garbage there, and every caller of ours would have to re-check the tag.
273    #[inline]
274    pub fn as_ptr(self) -> Option<*mut ()> {
275        if self.has_ref_count() {
276            Some(self.payload() as usize as *mut ())
277        } else {
278            None
279        }
280    }
281}
282
283/// `JS_TRUE`.
284pub const TRUE: JsValue = JsValue::mkval(TAG_BOOL, 1);
285/// `JS_FALSE`.
286pub const FALSE: JsValue = JsValue::mkval(TAG_BOOL, 0);
287
288/// `JS_NewInt32`: an integer, which is the bare payload with no tag bits at all.
289///
290/// Only 32 bits fit, which is why `JS_NewInt64` in the reference promotes anything wider
291/// to a double.
292#[inline]
293pub const fn new_int32(value: i32) -> JsValue {
294    JsValue::mkval(TAG_INT, value as u32)
295}
296
297/// `JS_NewBool`.
298#[inline]
299pub const fn new_bool(value: bool) -> JsValue {
300    if value { TRUE } else { FALSE }
301}
302
303/// `JS_NewFloat64` (which is the inline `__JS_NewFloat64`): a double, with every NaN
304/// normalised to [`NAN`].
305#[inline]
306pub fn new_float64(value: f64) -> JsValue {
307    JsValue::new(float64_bits(value))
308}
309
310/// The encoding [`new_float64`] performs, exposed because the allocator's tests and the
311/// ABI table want the bits rather than a value.
312#[inline]
313pub fn float64_bits(value: f64) -> u64 {
314    if value.is_nan() {
315        NAN
316    } else {
317        value.to_bits().wrapping_sub(FLOAT64_ADDEND)
318    }
319}
320
321impl Default for JsValue {
322    /// `JS_UNDEFINED`, which is what a zero-initialised `JSValue` must **not** be: bits
323    /// `0` decode as the integer `0`.
324    fn default() -> JsValue {
325        UNDEFINED
326    }
327}
328
329impl core::fmt::Debug for JsValue {
330    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
331        match self.norm_tag() {
332            TAG_UNDEFINED => write!(f, "undefined"),
333            TAG_NULL => write!(f, "null"),
334            TAG_BOOL => write!(f, "{}", self.to_bool()),
335            TAG_INT => write!(f, "{}", self.to_int()),
336            TAG_FLOAT64 => write!(f, "{}", self.to_float()),
337            TAG_EXCEPTION => write!(f, "<exception>"),
338            TAG_OBJECT => write!(f, "object@{:#x}", self.payload()),
339            tag => write!(f, "<tag {tag}>"),
340        }
341    }
342}
343
344// ---------------------------------------------------------------------------
345// Engine values
346// ---------------------------------------------------------------------------
347
348/// The tag a reference-counted engine value is boxed under.
349///
350/// Every refcounted payload the C API can see is an `Object` here, including strings and
351/// symbols: the engine's `Value` is a 16-byte enum, so the distinction lives *inside* the
352/// box rather than in the tag. That is invisible from C — `JS_IsString` is answered by
353/// asking the box, not by looking at the tag — and it keeps one allocation shape instead
354/// of five.
355///
356/// The exception is a string, which `JS_IsString` and `JS_ToString` both need to
357/// recognise, and which C-side code never dereferences beyond `ref_count`.
358pub const ENGINE_BOX_TAG: i32 = TAG_OBJECT;
359
360/// The tag an engine string is boxed under.
361pub const ENGINE_STRING_TAG: i32 = TAG_STRING;
362
363/// Whether a C value's tag is one this layer can decode back into an engine value.
364pub fn is_engine_tag(tag: i32) -> bool {
365    tag == TAG_OBJECT || tag == TAG_STRING || tag == TAG_SYMBOL || tag == TAG_BIG_INT
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371
372    /// `JS_NewInt32(0)` and `JS_UNDEFINED` differ in nothing but the tag, which is why a
373    /// zeroed `JSValue` is `0` and not `undefined`.
374    #[test]
375    fn zero_bits_are_the_integer_zero() {
376        assert_eq!(JsValue::new(0).norm_tag(), TAG_INT);
377        assert_eq!(JsValue::new(0).to_int(), 0);
378        assert_ne!(JsValue::new(0), UNDEFINED);
379        assert_eq!(JsValue::default(), UNDEFINED);
380    }
381
382    #[test]
383    fn negative_integers_keep_their_sign() {
384        assert_eq!(new_int32(-1).to_int(), -1);
385        assert_eq!(new_int32(-1).tag(), TAG_INT);
386        assert_eq!(new_int32(i32::MIN).to_int(), i32::MIN);
387        // The payload is only 32 bits wide for an int, so the high tag bits stay zero.
388        assert_eq!(new_int32(-1).bits(), 0xffff_ffff);
389    }
390
391    #[test]
392    fn floats_round_trip_and_nan_is_canonical() {
393        for value in [0.0, -0.0, 1.5, -1.5, f64::MIN, f64::MAX, f64::EPSILON] {
394            let encoded = new_float64(value);
395            assert_eq!(encoded.norm_tag(), TAG_FLOAT64, "{value}");
396            assert_eq!(encoded.to_float().to_bits(), value.to_bits(), "{value}");
397        }
398        // Every NaN spelling becomes the same value, which is what makes
399        // `Object.is(NaN, NaN)` answer true without a special case.
400        let quiet = new_float64(f64::from_bits(0x7ff8_0000_0000_0001));
401        let signalling = new_float64(f64::from_bits(0x7ff0_0000_0000_0001));
402        assert_eq!(quiet, signalling);
403        assert_eq!(quiet.bits(), NAN);
404        assert!(quiet.is_nan());
405        assert!(quiet.to_float().is_nan());
406    }
407
408    #[test]
409    fn tag_is_read_as_a_signed_shift() {
410        assert_eq!(UNDEFINED.tag(), TAG_UNDEFINED);
411        assert_eq!(NULL.tag(), TAG_NULL);
412        assert_eq!(EXCEPTION.tag(), TAG_EXCEPTION);
413        assert_eq!(TRUE.tag(), TAG_BOOL);
414        assert_eq!(new_int32(7).tag(), TAG_INT);
415        // A double lands *outside* the named tag range, which is exactly how
416        // `JS_TAG_IS_FLOAT64` recognises it — the encoding is subtractive, so a positive
417        // double ends up with a large negative tag. Nothing enumerates floats.
418        assert_eq!(new_float64(1.0).norm_tag(), TAG_FLOAT64);
419        assert!(!(-8..=7).contains(&new_float64(1.0).tag()));
420    }
421
422    #[test]
423    fn every_double_is_outside_the_refcount_range() {
424        // This is why `__JS_NewFloat64` normalises NaN: a NaN whose bits are
425        // `0x7ffb_8000_0000_0000` would encode to `0xffff_8000_0000_0000`, i.e. tag `-1`,
426        // and C's `JS_VALUE_HAS_REF_COUNT` would read it as an object pointer. With every
427        // NaN mapped to one canonical value, no double can collide with the tag range.
428        let doubles = [
429            0.0,
430            -0.0,
431            1.0,
432            -1.0,
433            1.5,
434            f64::MIN,
435            f64::MAX,
436            f64::MIN_POSITIVE,
437            f64::INFINITY,
438            f64::NEG_INFINITY,
439            f64::NAN,
440            f64::from_bits(0x7ffb_8000_0000_0000),
441            f64::from_bits(0xffff_ffff_ffff_ffff),
442        ];
443        for value in doubles {
444            let encoded = new_float64(value);
445            assert!(
446                encoded.is_float(),
447                "{value} encoded as tag {}",
448                encoded.tag()
449            );
450            assert!(
451                !encoded.has_ref_count(),
452                "{value} encoded inside the reference-count tag range"
453            );
454            assert_eq!(encoded.norm_tag(), TAG_FLOAT64, "{value}");
455        }
456    }
457
458    #[test]
459    fn only_negative_tags_carry_a_reference_count() {
460        assert!(JsValue::mkptr(TAG_OBJECT, 0x1000 as *mut ()).has_ref_count());
461        assert!(JsValue::mkptr(TAG_STRING, 0x1000 as *mut ()).has_ref_count());
462        assert!(!UNDEFINED.has_ref_count());
463        assert!(!new_int32(0).has_ref_count());
464        assert!(!new_float64(1.5).has_ref_count());
465        assert_eq!(
466            JsValue::mkptr(TAG_OBJECT, 0x1000 as *mut ()).payload(),
467            0x1000
468        );
469    }
470
471    #[test]
472    fn pointers_below_47_bits_round_trip() {
473        for address in [0x1000usize, 0x7fff_ffff_ffff] {
474            let value = JsValue::mkptr(TAG_OBJECT, address as *mut ());
475            assert_eq!(value.payload() as usize, address);
476            assert_eq!(value.as_ptr().unwrap() as usize, address);
477            assert!(value.is_object());
478        }
479        // The payload is masked, so the tag bits above 47 do not leak into it.
480        assert_eq!(
481            JsValue::mkptr(TAG_OBJECT, 0x7fff_ffff_ffff as *mut ()).bits() >> TAG_SHIFT,
482            (-1i64 as u64) >> TAG_SHIFT
483        );
484        assert_eq!(UNDEFINED.as_ptr(), None);
485    }
486}