Skip to main content

quickjs/
value.rs

1//! JavaScript values, and the conversions between them.
2//!
3//! A [`Value`] is what the VM's stack and every property hold. The number split
4//! between [`Value::Int`] and [`Value::Float`] mirrors QuickJS's `JS_TAG_INT` /
5//! `JS_TAG_FLOAT64`: keeping small integers as `i32` makes array indices and loop
6//! counters exact and cheap. Every arithmetic result that does not fit `i32`
7//! becomes a `Float`, so the two are interchangeable numerically and only
8//! [`Value::strict_equals`] has to care about which one it has.
9
10use std::cell::RefCell;
11use std::fmt;
12
13use js_gc::{Gc, Trace, Tracer};
14
15use crate::object::JsObject;
16
17/// An immutable string, stored on the GC heap.
18///
19/// QuickJS interns strings (`JSString`) and shares them between values, so a
20/// `Value` only ever holds a handle. Strings here are not yet interned as atoms —
21/// that arrives with the property-key work in M4 — so two equal strings are two
22/// allocations that compare by content.
23pub struct JsString {
24    text: String,
25}
26
27impl JsString {
28    /// Wrap `text`.
29    pub fn new(text: String) -> JsString {
30        JsString { text }
31    }
32
33    /// The text.
34    pub fn as_str(&self) -> &str {
35        &self.text
36    }
37
38    /// Length in UTF-16 code units, which is what `String.prototype.length` and
39    /// the string indexing rules count.
40    pub fn utf16_len(&self) -> usize {
41        self.text.encode_utf16().count()
42    }
43}
44
45impl Trace for JsString {
46    fn trace(&self, _tracer: &mut Tracer) {}
47}
48
49impl fmt::Debug for JsString {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        write!(f, "{:?}", self.text)
52    }
53}
54
55/// A mutable binding cell, shared between closures.
56///
57/// A variable that a closure captures cannot live in a stack slot, because the
58/// slot dies with the frame while the closure outlives it. The compiler marks such
59/// bindings `is_captured` and counts them in `var_ref_count`; the interpreter
60/// allocates one of these per captured binding on entry, and every access — from
61/// the owning frame or from any closure — goes through the cell.
62pub struct Cell {
63    value: RefCell<Value>,
64}
65
66impl Cell {
67    /// A cell holding `value`.
68    pub fn new(value: Value) -> Cell {
69        Cell {
70            value: RefCell::new(value),
71        }
72    }
73
74    /// Read the cell.
75    pub fn get(&self) -> Value {
76        self.value.borrow().clone()
77    }
78
79    /// Overwrite the cell.
80    pub fn set(&self, value: Value) {
81        *self.value.borrow_mut() = value;
82    }
83}
84
85impl Trace for Cell {
86    fn trace(&self, tracer: &mut Tracer) {
87        self.value.borrow().trace(tracer);
88    }
89}
90
91/// A JavaScript value.
92#[derive(Clone)]
93pub enum Value {
94    /// `undefined`
95    Undefined,
96    /// `null`
97    Null,
98    /// `true` / `false`
99    Bool(bool),
100    /// A 32-bit integer, exact.
101    Int(i32),
102    /// A double.
103    Float(f64),
104    /// A string.
105    String(Gc<JsString>),
106    /// An object, function, or array.
107    Object(Gc<JsObject>),
108    /// A try-handler target, pushed by `catch` and scanned for when an exception
109    /// is raised.
110    ///
111    /// QuickJS keeps this on the value stack as a `JS_TAG_CATCH_OFFSET` value and
112    /// finds the innermost handler by walking the stack downwards, which is how
113    /// `try` needs no separate table. Offset `0` marks an enumerator (a `for-of`
114    /// loop) rather than a `catch`: it closes the iterator and keeps unwinding.
115    CatchOffset(u32),
116    /// A `gosub` return position.
117    ///
118    /// `finally` blocks are compiled as subroutines: `gosub` pushes the address to
119    /// come back to and jumps into the block, `ret` pops the address and jumps
120    /// back. QuickJS reuses the integer tag for this (and notes it as a hardening
121    /// gap); a distinct variant keeps it out of reach of arithmetic.
122    ReturnAddress(u32),
123    /// An array hole: an index that was skipped rather than filled.
124    ///
125    /// `[1,,3]` and `[1,undefined,3]` are different arrays: `forEach` skips the hole,
126    /// `in` reports it absent, and the debug printer shows `<1 empty item>`. That
127    /// distinction has to live in the element vector, and this is the marker for it.
128    /// It is never observable from JavaScript: reading the index yields `undefined`
129    /// and no language operation can produce it.
130    Hole,
131    /// The internal marker a `let`/`const` binding holds between its scope being
132    /// entered and its initialiser running.
133    ///
134    /// QuickJS calls this `JS_UNINITIALIZED`; it is deliberately not observable
135    /// from JavaScript. It only ever sits in a slot or a cell, and every read that
136    /// may see it (`get_loc_check` and friends) turns it into a `ReferenceError`.
137    Uninitialized,
138}
139
140impl Value {
141    /// A string value on `heap`.
142    pub fn string(heap: &js_gc::Heap, text: impl Into<String>) -> Value {
143        Value::String(Gc::new(heap, JsString::new(text.into())))
144    }
145
146    /// The number as a double, widening an [`Value::Int`].
147    pub fn as_f64(&self) -> Option<f64> {
148        match self {
149            Value::Int(i) => Some(*i as f64),
150            Value::Float(f) => Some(*f),
151            _ => None,
152        }
153    }
154
155    /// The value as a string, if it is one.
156    pub fn as_str(&self) -> Option<&str> {
157        match self {
158            Value::String(s) => Some(s.as_str()),
159            _ => None,
160        }
161    }
162
163    /// The object, if this is one.
164    pub fn as_object(&self) -> Option<&Gc<JsObject>> {
165        match self {
166            Value::Object(o) => Some(o),
167            _ => None,
168        }
169    }
170
171    /// Whether this is one of the two null-ish values.
172    pub fn is_nullish(&self) -> bool {
173        matches!(self, Value::Undefined | Value::Null)
174    }
175
176    /// `typeof value`.
177    pub fn type_of(&self) -> &'static str {
178        match self {
179            Value::Undefined => "undefined",
180            Value::Null => "object",
181            Value::Bool(_) => "boolean",
182            Value::Int(_) | Value::Float(_) => "number",
183            Value::String(_) => "string",
184            Value::Object(object) => {
185                if object.is_callable() {
186                    "function"
187                } else {
188                    "object"
189                }
190            }
191            // The internal markers are never observable from JavaScript;
192            // reporting `undefined` keeps the answer honest if a bug lets one leak.
193            Value::Uninitialized
194            | Value::Hole
195            | Value::CatchOffset(_)
196            | Value::ReturnAddress(_) => "undefined",
197        }
198    }
199
200    /// `ToBoolean`, which is also what a conditional jump tests.
201    pub fn to_boolean(&self) -> bool {
202        match self {
203            Value::Undefined | Value::Null => false,
204            Value::Bool(b) => *b,
205            Value::Int(i) => *i != 0,
206            // `NaN` is falsy, and so is `-0`.
207            Value::Float(f) => *f != 0.0 && !f.is_nan(),
208            Value::String(s) => !s.as_str().is_empty(),
209            // Every object is truthy, including `new Boolean(false)`.
210            Value::Object(_) => true,
211            Value::Uninitialized
212            | Value::Hole
213            | Value::CatchOffset(_)
214            | Value::ReturnAddress(_) => false,
215        }
216    }
217
218    /// `ToNumber`, for the arithmetic operators.
219    pub fn to_number(&self) -> f64 {
220        match self {
221            Value::Undefined => f64::NAN,
222            Value::Null => 0.0,
223            Value::Bool(b) => {
224                if *b {
225                    1.0
226                } else {
227                    0.0
228                }
229            }
230            Value::Int(i) => *i as f64,
231            Value::Float(f) => *f,
232            Value::String(s) => string_to_number(s.as_str()),
233            // `ToNumber` of an object runs `ToPrimitive` first, which needs the
234            // value-of/valueOf machinery; until that lands an object is `NaN`
235            // rather than a panic.
236            Value::Object(_) => f64::NAN,
237            Value::Uninitialized
238            | Value::Hole
239            | Value::CatchOffset(_)
240            | Value::ReturnAddress(_) => f64::NAN,
241        }
242    }
243
244    /// `ToInt32`, the conversion the bitwise operators and `<<`/`>>`/`>>>` use.
245    pub fn to_int32(&self) -> i32 {
246        to_int32(self.to_number())
247    }
248
249    /// `ToUint32`.
250    pub fn to_uint32(&self) -> u32 {
251        self.to_int32() as u32
252    }
253
254    /// `ToString`.
255    ///
256    /// Named `to_js_string` rather than `to_string` so it does not shadow
257    /// [`std::fmt::Display`]: the two disagree on purpose (`display` keeps the sign
258    /// of `-0`), and an accidental `to_string` on a `Value` would silently pick the
259    /// wrong one.
260    pub fn to_js_string(&self) -> String {
261        match self {
262            Value::Undefined => "undefined".to_string(),
263            Value::Null => "null".to_string(),
264            Value::Bool(true) => "true".to_string(),
265            Value::Bool(false) => "false".to_string(),
266            Value::Int(i) => i.to_string(),
267            Value::Float(f) => number_to_string(*f),
268            Value::String(s) => s.as_str().to_string(),
269            Value::Object(_) => "[object Object]".to_string(),
270            Value::Uninitialized
271            | Value::Hole
272            | Value::CatchOffset(_)
273            | Value::ReturnAddress(_) => "undefined".to_string(),
274        }
275    }
276
277    /// `===`.
278    pub fn strict_equals(&self, other: &Value) -> bool {
279        match (self, other) {
280            (Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => true,
281            (Value::Bool(a), Value::Bool(b)) => a == b,
282            // `Int` and `Float` are the same type to JavaScript, so `1 === 1.0`.
283            (Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) => {
284                let (a, b) = (self.to_number(), other.to_number());
285                a == b
286            }
287            (Value::String(a), Value::String(b)) => a.as_str() == b.as_str(),
288            // Objects compare by identity, never structurally.
289            (Value::Object(a), Value::Object(b)) => a.ptr_eq(b),
290            _ => false,
291        }
292    }
293
294    /// `==`, with the coercion rules.
295    ///
296    /// `NaN` compares unequal to everything including itself, which the numeric
297    /// branch already gets right. An object compares by identity against another
298    /// object and by its primitive form against a primitive.
299    pub fn loose_equals(&self, other: &Value) -> bool {
300        if matches!(self, Value::Object(_)) || matches!(other, Value::Object(_)) {
301            return match (self, other) {
302                (Value::Object(a), Value::Object(b)) => a.ptr_eq(b),
303                _ => primitive_loose_equals(&self.primitive(), &other.primitive()),
304            };
305        }
306        match (self, other) {
307            (Value::Undefined | Value::Null, Value::Undefined | Value::Null) => true,
308            (Value::Undefined | Value::Null, _) | (_, Value::Undefined | Value::Null) => false,
309            (Value::String(a), Value::String(b)) => a.as_str() == b.as_str(),
310            (Value::Bool(a), Value::Bool(b)) => a == b,
311            // Everything else compares numerically, which covers `"1" == 1`,
312            // `true == 1` and `Int` against `Float`.
313            _ => self.to_number() == other.to_number(),
314        }
315    }
316
317    /// `ToPrimitive` with no hint.
318    ///
319    /// The result is an owned [`Primitive`] rather than a [`Value`] because a
320    /// string `Value` needs a heap handle and this path deliberately has none.
321    fn primitive(&self) -> Primitive {
322        match self {
323            Value::Undefined => Primitive::Undefined,
324            Value::Null => Primitive::Null,
325            Value::Bool(b) => Primitive::Bool(*b),
326            Value::Int(i) => Primitive::Number(*i as f64),
327            Value::Float(f) => Primitive::Number(*f),
328            Value::String(s) => Primitive::String(s.as_str().to_string()),
329            Value::Object(_) => Primitive::String(self.to_js_string()),
330            Value::Uninitialized
331            | Value::Hole
332            | Value::CatchOffset(_)
333            | Value::ReturnAddress(_) => Primitive::Undefined,
334        }
335    }
336}
337
338/// A value with no object identity, used by [`Value::loose_equals`].
339enum Primitive {
340    Undefined,
341    Null,
342    Bool(bool),
343    Number(f64),
344    String(String),
345}
346
347/// `==` once both sides are primitives.
348fn primitive_loose_equals(left: &Primitive, right: &Primitive) -> bool {
349    use Primitive::*;
350    match (left, right) {
351        (Undefined | Null, Undefined | Null) => true,
352        (Undefined | Null, _) | (_, Undefined | Null) => false,
353        (String(a), String(b)) => a == b,
354        (Bool(a), Bool(b)) => a == b,
355        (Number(a), Number(b)) => a == b,
356        // A string against a number compares numerically, so `"" == 0` and
357        // `"1" == 1`.
358        (String(s), Number(n)) | (Number(n), String(s)) => string_to_number(s) == *n,
359        (Bool(b), Number(n)) | (Number(n), Bool(b)) => (if *b { 1.0 } else { 0.0 }) == *n,
360        (Bool(b), String(s)) | (String(s), Bool(b)) => {
361            string_to_number(s) == (if *b { 1.0 } else { 0.0 })
362        }
363    }
364}
365
366/// `ToInt32`.
367///
368/// The spec's modulo-2^32 arithmetic: `NaN` and the infinities become zero, and
369/// the fractional part is dropped toward zero before the wrap.
370pub fn to_int32(value: f64) -> i32 {
371    if !value.is_finite() || value == 0.0 {
372        return 0;
373    }
374    let truncated = value.trunc();
375    let modulo = truncated.rem_euclid(4294967296.0);
376    let wrapped = if modulo >= 2147483648.0 {
377        modulo - 4294967296.0
378    } else {
379        modulo
380    };
381    wrapped as i32
382}
383
384/// `ToNumber` applied to a string.
385///
386/// Leading and trailing whitespace is allowed; anything else must be a valid
387/// numeric literal, because a failed parse is `NaN` rather than a prefix match.
388/// The empty string is `0`, which is a common source of surprise.
389pub fn string_to_number(text: &str) -> f64 {
390    let trimmed = text.trim();
391    if trimmed.is_empty() {
392        return 0.0;
393    }
394    if let Some(rest) = strip_radix_prefix(trimmed, "0x", "0X") {
395        return radix_number(rest, 16);
396    }
397    if let Some(rest) = strip_radix_prefix(trimmed, "0o", "0O") {
398        return radix_number(rest, 8);
399    }
400    if let Some(rest) = strip_radix_prefix(trimmed, "0b", "0B") {
401        return radix_number(rest, 2);
402    }
403    let (sign, digits) = match trimmed.strip_prefix(['+', '-']) {
404        Some(rest) => (&trimmed[..1], rest),
405        None => ("", trimmed),
406    };
407    // `Infinity` is a literal; `inf`/`nan` are not, even though Rust parses them.
408    if digits == "Infinity" {
409        return if sign == "-" {
410            f64::NEG_INFINITY
411        } else {
412            f64::INFINITY
413        };
414    }
415    // Rust's parser accepts the literals JavaScript does not, so the shape is
416    // checked before trusting it: digits with at most one dot, at most one
417    // exponent, and no trailing garbage.
418    if !is_decimal_literal(digits) {
419        return f64::NAN;
420    }
421    trimmed.parse::<f64>().unwrap_or(f64::NAN)
422}
423
424fn strip_radix_prefix<'a>(text: &'a str, lower: &str, upper: &str) -> Option<&'a str> {
425    text.strip_prefix(lower)
426        .or_else(|| text.strip_prefix(upper))
427}
428
429fn radix_number(digits: &str, radix: u32) -> f64 {
430    if digits.is_empty() || !digits.chars().all(|c| c.is_digit(radix)) {
431        return f64::NAN;
432    }
433    // A long literal overflows `u64`; JavaScript then rounds, so fall back to an
434    // accumulating double rather than reporting `NaN`.
435    match u64::from_str_radix(digits, radix) {
436        Ok(value) => value as f64,
437        Err(_) => digits.chars().fold(0.0, |acc, c| {
438            acc * radix as f64 + c.to_digit(radix).unwrap_or(0) as f64
439        }),
440    }
441}
442
443/// Whether `text` is a decimal literal with no sign.
444fn is_decimal_literal(text: &str) -> bool {
445    let bytes = text.as_bytes();
446    let mut index = 0;
447    let mut digits = 0;
448    while index < bytes.len() && bytes[index].is_ascii_digit() {
449        index += 1;
450        digits += 1;
451    }
452    if index < bytes.len() && bytes[index] == b'.' {
453        index += 1;
454        while index < bytes.len() && bytes[index].is_ascii_digit() {
455            index += 1;
456            digits += 1;
457        }
458    }
459    if digits == 0 {
460        return false;
461    }
462    if index < bytes.len() && (bytes[index] == b'e' || bytes[index] == b'E') {
463        index += 1;
464        if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
465            index += 1;
466        }
467        let start = index;
468        while index < bytes.len() && bytes[index].is_ascii_digit() {
469            index += 1;
470        }
471        if index == start {
472            return false;
473        }
474    }
475    index == bytes.len()
476}
477
478/// `ToString` applied to a number.
479///
480/// The thresholds are the ones the spec's `Number::toString` uses: exponential
481/// form below `1e-6` and from `1e21` up, decimal form in between. Within the
482/// decimal range Rust's shortest-round-trip formatter already agrees with
483/// JavaScript digit for digit — including the notorious `0.30000000000000004` —
484/// so only the exponent spelling has to be normalised.
485pub fn number_to_string(value: f64) -> String {
486    if value.is_nan() {
487        return "NaN".to_string();
488    }
489    if value.is_infinite() {
490        return if value > 0.0 {
491            "Infinity".to_string()
492        } else {
493            "-Infinity".to_string()
494        };
495    }
496    if value == 0.0 {
497        // `ToString(-0)` is `"0"`; `print(-0)` is a different question, see
498        // [`number_to_string_for_print`].
499        return "0".to_string();
500    }
501    let magnitude = value.abs();
502    if magnitude >= 1e21 || magnitude < 1e-6 {
503        return normalise_exponent(format!("{value:e}"));
504    }
505    format!("{value}")
506}
507
508/// `ToString` as the engine's `print` applies it, which differs from the language
509/// one for negative zero.
510///
511/// `print(-0)` prints `-0` in QuickJS while `String(-0)` is `"0"`, because the host
512/// printer takes the number's own spelling. Reproduced here so byte-for-byte output
513/// comparisons do not trip over it.
514pub fn number_to_string_for_print(value: f64) -> String {
515    if value == 0.0 && value.is_sign_negative() {
516        return "-0".to_string();
517    }
518    number_to_string(value)
519}
520
521/// Rewrite Rust's exponent spelling as JavaScript's: always signed, never padded.
522///
523/// Rust writes `1e-7` and `1e21`; JavaScript writes `1e-7` and `1e+21`. The
524/// difference is only the explicit `+`.
525fn normalise_exponent(text: String) -> String {
526    let Some((mantissa, exponent)) = text.split_once('e') else {
527        return text;
528    };
529    if exponent.starts_with('-') {
530        text
531    } else {
532        let digits = exponent.strip_prefix('+').unwrap_or(exponent);
533        format!("{mantissa}e+{digits}")
534    }
535}
536
537impl Trace for Value {
538    fn trace(&self, tracer: &mut Tracer) {
539        match self {
540            Value::String(s) => tracer.visit(s),
541            Value::Object(o) => tracer.visit(o),
542            _ => {}
543        }
544    }
545}
546
547impl fmt::Debug for Value {
548    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
549        match self {
550            Value::Undefined => f.write_str("undefined"),
551            Value::Null => f.write_str("null"),
552            Value::Bool(b) => write!(f, "{b}"),
553            Value::Int(i) => write!(f, "{i}"),
554            Value::Float(x) => write!(f, "{}", number_to_string(*x)),
555            Value::String(s) => write!(f, "{:?}", s.as_str()),
556            Value::Object(_) => f.write_str("[object]"),
557            Value::Uninitialized => f.write_str("<uninitialised>"),
558            Value::Hole => f.write_str("<hole>"),
559            Value::CatchOffset(offset) => write!(f, "<catch {offset}>"),
560            Value::ReturnAddress(address) => write!(f, "<ret {address}>"),
561        }
562    }
563}
564
565#[cfg(test)]
566mod tests {
567    use super::*;
568
569    #[test]
570    fn int32_wraps_the_way_the_spec_says() {
571        assert_eq!(to_int32(0.0), 0);
572        assert_eq!(to_int32(f64::NAN), 0);
573        assert_eq!(to_int32(f64::INFINITY), 0);
574        assert_eq!(to_int32(1.9), 1);
575        assert_eq!(to_int32(-1.9), -1);
576        assert_eq!(to_int32(2147483648.0), -2147483648);
577        assert_eq!(to_int32(4294967296.0), 0);
578        assert_eq!(to_int32(-4294967297.0), -1);
579    }
580
581    #[test]
582    fn numbers_print_like_javascript() {
583        assert_eq!(number_to_string(0.0), "0");
584        assert_eq!(number_to_string(-0.0), "0");
585        assert_eq!(number_to_string(1.0), "1");
586        assert_eq!(number_to_string(-1.5), "-1.5");
587        assert_eq!(number_to_string(1e21), "1e+21");
588        assert_eq!(number_to_string(1e-7), "1e-7");
589        assert_eq!(number_to_string(1e-6), "0.000001");
590        assert_eq!(number_to_string(1e20), "100000000000000000000");
591        assert_eq!(number_to_string(5e-324), "5e-324");
592        // `print(-0)` differs from `String(-0)`.
593        assert_eq!(number_to_string_for_print(-0.0), "-0");
594        assert_eq!(number_to_string(f64::NAN), "NaN");
595        assert_eq!(number_to_string(f64::INFINITY), "Infinity");
596        assert_eq!(number_to_string(f64::NEG_INFINITY), "-Infinity");
597    }
598
599    #[test]
600    fn strings_parse_to_numbers_without_prefix_matching() {
601        assert_eq!(string_to_number(""), 0.0);
602        assert_eq!(string_to_number("  "), 0.0);
603        assert_eq!(string_to_number(" 42 "), 42.0);
604        assert_eq!(string_to_number("0x10"), 16.0);
605        assert_eq!(string_to_number("0b101"), 5.0);
606        assert_eq!(string_to_number("0o17"), 15.0);
607        assert_eq!(string_to_number("Infinity"), f64::INFINITY);
608        assert_eq!(string_to_number("-Infinity"), f64::NEG_INFINITY);
609        assert_eq!(string_to_number("1e3"), 1000.0);
610        assert_eq!(string_to_number(".5"), 0.5);
611        assert_eq!(string_to_number("5."), 5.0);
612        // These would all be prefix matches or Rust-only spellings.
613        assert!(string_to_number("12px").is_nan());
614        assert!(string_to_number("inf").is_nan());
615        assert!(string_to_number("nan").is_nan());
616        assert!(string_to_number("1e").is_nan());
617        assert!(string_to_number("0x").is_nan());
618    }
619
620    #[test]
621    fn strict_equality_ignores_the_int_float_split() {
622        assert!(Value::Int(1).strict_equals(&Value::Float(1.0)));
623        assert!(!Value::Int(1).strict_equals(&Value::Float(1.5)));
624        assert!(!Value::Float(f64::NAN).strict_equals(&Value::Float(f64::NAN)));
625        assert!(Value::Int(0).strict_equals(&Value::Float(-0.0)));
626        assert!(!Value::Int(0).strict_equals(&Value::Null));
627        assert!(!Value::Undefined.strict_equals(&Value::Null));
628    }
629
630    #[test]
631    fn falsy_values_are_the_spec_list() {
632        assert!(!Value::Undefined.to_boolean());
633        assert!(!Value::Null.to_boolean());
634        assert!(!Value::Bool(false).to_boolean());
635        assert!(!Value::Int(0).to_boolean());
636        assert!(!Value::Float(f64::NAN).to_boolean());
637        assert!(!Value::Float(-0.0).to_boolean());
638        assert!(Value::Float(0.1).to_boolean());
639    }
640}