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/// A JavaScript string's bytes, in **WTF-8**.
18///
19/// A JS string is a sequence of UTF-16 *code units*, and that sequence may contain an
20/// unpaired surrogate: `String.fromCharCode(0xD800)` produces exactly one, and
21/// `"\uD800".length` is 1. Rust's `String` cannot represent that, so the bytes here are
22/// WTF-8 — ordinary UTF-8, except that a code unit with no partner is written as the
23/// three-byte sequence UTF-8 would use for U+D800..U+DFFF.
24///
25/// # The encoding is canonical, and that is load-bearing
26///
27/// A *surrogate pair* is written as the single four-byte sequence of the astral code point
28/// it spells, never as two three-byte sequences. Without that rule the bytes of `"\uD800" +
29/// "\uDC00"` would differ from the bytes of `"\u{10000}"` while the two strings are
30/// observably identical — same length, same `charCodeAt` at every index — and every
31/// equality, property key and `switch` arm in the engine would disagree with the language.
32///
33/// The canonical form makes **byte equality exactly code-unit equality**, which is what lets
34/// a property key be compared without decoding it.
35#[derive(Clone)]
36pub struct Wtf8 {
37    /// The WTF-8 bytes.
38    bytes: Box<[u8]>,
39    /// Whether `bytes` is valid UTF-8, meaning the string has no unpaired surrogate.
40    ///
41    /// A `Wtf8` is immutable, so this stays correct for its whole life.
42    valid: bool,
43}
44
45impl Wtf8 {
46    /// Wrap a Rust string, which is valid UTF-8 by construction.
47    pub fn new(text: impl Into<String>) -> Wtf8 {
48        Wtf8 {
49            bytes: text.into().into_bytes().into_boxed_slice(),
50            valid: true,
51        }
52    }
53
54    /// Build from UTF-16 code units, which is the form a JS string really has.
55    ///
56    /// An unpaired surrogate survives; a pair is folded into its astral code point.
57    pub fn from_units(units: &[u16]) -> Wtf8 {
58        let mut bytes = Vec::with_capacity(units.len());
59        let mut valid = true;
60        let mut index = 0;
61        while index < units.len() {
62            let unit = units[index];
63            match units.get(index + 1) {
64                Some(&low) if is_high(unit) && is_low(low) => {
65                    push_code_point(&mut bytes, combine(unit, low));
66                    index += 2;
67                }
68                _ if is_surrogate(unit) => {
69                    // A lone surrogate keeps its own three-byte form, so it round-trips and
70                    // still counts as one code unit.
71                    valid = false;
72                    push_surrogate(&mut bytes, unit);
73                    index += 1;
74                }
75                _ => {
76                    push_code_point(&mut bytes, unit as u32);
77                    index += 1;
78                }
79            }
80        }
81        Wtf8 {
82            bytes: bytes.into_boxed_slice(),
83            valid,
84        }
85    }
86
87    /// The text, when it is valid UTF-8.
88    ///
89    /// `None` only for a string containing an unpaired surrogate — there is no `&str` for
90    /// one. Callers that only need to display or compare use [`Wtf8::to_string_lossy`].
91    pub fn as_str(&self) -> Option<&str> {
92        if self.valid {
93            // SAFETY: `valid` is only set by the encoder above, which produces valid UTF-8
94            // exactly when no surrogate was written on its own, and the bytes never change.
95            Some(unsafe { std::str::from_utf8_unchecked(&self.bytes) })
96        } else {
97            None
98        }
99    }
100
101    /// The text with unpaired surrogates replaced by U+FFFD.
102    ///
103    /// Borrowed, and therefore free, for the ordinary string that has no surrogate.
104    pub fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
105        match self.as_str() {
106            Some(text) => std::borrow::Cow::Borrowed(text),
107            None => String::from_utf8_lossy(&self.bytes),
108        }
109    }
110
111    /// The WTF-8 bytes. Two `Wtf8`s are equal exactly when these are.
112    pub fn as_bytes(&self) -> &[u8] {
113        &self.bytes
114    }
115
116    /// The UTF-16 code units, which is what indexing and `charCodeAt` count.
117    pub fn to_units(&self) -> Vec<u16> {
118        let mut units = Vec::with_capacity(self.utf16_len());
119        self.push_units(&mut units);
120        units
121    }
122
123    /// Length in UTF-16 code units, which is what `String.prototype.length` reports.
124    ///
125    /// Counted from the encoding rather than by decoding, so it does not allocate: a
126    /// four-byte sequence is a surrogate pair and therefore two units, everything else is
127    /// one.
128    pub fn utf16_len(&self) -> usize {
129        self.bytes
130            .iter()
131            .filter(|byte| (**byte & 0xC0) != 0x80)
132            .map(|byte| if *byte >= 0xF0 { 2 } else { 1 })
133            .sum()
134    }
135
136    /// The code unit at `index`, or `None` past the end.
137    pub fn code_unit_at(&self, index: usize) -> Option<u16> {
138        // Walking instead of decoding keeps `charCodeAt` in a loop linear rather than
139        // quadratic, which matters because that is exactly how a script inspects a string.
140        let mut position = 0;
141        let mut at = 0;
142        while at < self.bytes.len() {
143            let (units, count, width) = self.sequence_at(at);
144            if position + count > index {
145                return Some(units[index - position]);
146            }
147            position += count;
148            at += width;
149        }
150        None
151    }
152
153    /// Whether the string is empty.
154    pub fn is_empty(&self) -> bool {
155        self.bytes.is_empty()
156    }
157
158    /// One code unit as a string, which is what `s[i]` yields.
159    ///
160    /// A single unit, not a code point: `"\u{1F600}"[0]` is the lone high surrogate, because
161    /// indexing a string in JS works on code units.
162    pub fn unit_at(&self, index: usize) -> Option<Wtf8> {
163        self.code_unit_at(index)
164            .map(|unit| Wtf8::from_units(&[unit]))
165    }
166
167    /// The code units `start..end`, re-encoded canonically.
168    pub fn slice_units(&self, start: usize, end: usize) -> Wtf8 {
169        let units = self.to_units();
170        let start = start.min(units.len());
171        let end = end.clamp(start, units.len());
172        Wtf8::from_units(&units[start..end])
173    }
174
175    /// One element per code *point*, which is how a string is iterated.
176    ///
177    /// Iteration and indexing disagree on purpose: `[...str]` splits an astral character
178    /// into one element while `str[0]` splits it into half a surrogate pair.
179    pub fn code_points(&self) -> Vec<Wtf8> {
180        let mut out = Vec::new();
181        let mut at = 0;
182        while at < self.bytes.len() {
183            let (_, _, width) = self.sequence_at(at);
184            let mut bytes = Vec::with_capacity(width);
185            bytes.extend_from_slice(&self.bytes[at..at + width]);
186            // A single sequence is always canonical on its own: a four-byte one is already
187            // an astral code point and a three-byte one is a BMP code point or a lone
188            // surrogate.
189            out.push(Wtf8 {
190                valid: std::str::from_utf8(&bytes).is_ok(),
191                bytes: bytes.into_boxed_slice(),
192            });
193            at += width;
194        }
195        out
196    }
197
198    /// Concatenate, keeping the encoding canonical.
199    ///
200    /// Byte concatenation is already canonical *except* where a high surrogate at the end of
201    /// `self` meets a low surrogate at the start of `other`: those two must fold into one
202    /// astral sequence, or the result would be a different string from the one the language
203    /// says `+` produces.
204    pub fn concat(&self, other: &Wtf8) -> Wtf8 {
205        let bridges =
206            ends_with_high_surrogate(&self.bytes) && starts_with_low_surrogate(&other.bytes);
207        if !bridges {
208            let mut bytes = Vec::with_capacity(self.bytes.len() + other.bytes.len());
209            bytes.extend_from_slice(&self.bytes);
210            bytes.extend_from_slice(&other.bytes);
211            return Wtf8 {
212                bytes: bytes.into_boxed_slice(),
213                valid: self.valid && other.valid,
214            };
215        }
216        let mut units = self.to_units();
217        units.extend(other.to_units());
218        Wtf8::from_units(&units)
219    }
220
221    /// Append the code units to `out`.
222    fn push_units(&self, out: &mut Vec<u16>) {
223        let mut at = 0;
224        while at < self.bytes.len() {
225            let (units, count, width) = self.sequence_at(at);
226            out.extend_from_slice(&units[..count]);
227            at += width;
228        }
229    }
230
231    /// The code units the sequence starting at `at` stands for, how many of them there are,
232    /// and its byte width.
233    fn sequence_at(&self, at: usize) -> ([u16; 2], usize, usize) {
234        let byte = self.bytes[at];
235        let byte_at = |offset: usize| self.bytes.get(at + offset).copied().unwrap_or(0) as u32;
236        if byte < 0x80 {
237            ([byte as u16, 0], 1, 1)
238        } else if byte >> 5 == 0b110 {
239            (
240                [
241                    (((byte as u32 & 0x1F) << 6) | (byte_at(1) & 0x3F)) as u16,
242                    0,
243                ],
244                1,
245                2,
246            )
247        } else if byte >> 4 == 0b1110 {
248            // A three-byte sequence is either a BMP code point or a lone surrogate; either
249            // way it is exactly one code unit.
250            (
251                [
252                    ((byte as u32 & 0x0F) << 12 | ((byte_at(1) & 0x3F) << 6) | (byte_at(2) & 0x3F))
253                        as u16,
254                    0,
255                ],
256                1,
257                3,
258            )
259        } else {
260            let code = (byte as u32 & 0x07) << 18
261                | ((byte_at(1) & 0x3F) << 12)
262                | ((byte_at(2) & 0x3F) << 6)
263                | (byte_at(3) & 0x3F);
264            let code = code.wrapping_sub(0x10000);
265            (
266                [
267                    0xD800u16.wrapping_add((code >> 10) as u16),
268                    0xDC00u16.wrapping_add((code & 0x3FF) as u16),
269                ],
270                2,
271                4,
272            )
273        }
274    }
275}
276
277fn is_surrogate(unit: u16) -> bool {
278    (0xD800..0xE000).contains(&unit)
279}
280
281fn is_high(unit: u16) -> bool {
282    (0xD800..0xDC00).contains(&unit)
283}
284
285fn is_low(unit: u16) -> bool {
286    (0xDC00..0xE000).contains(&unit)
287}
288
289/// The astral code point a surrogate pair spells.
290fn combine(high: u16, low: u16) -> u32 {
291    0x10000 + ((high as u32 - 0xD800) << 10) + (low as u32 - 0xDC00)
292}
293
294/// Write a code point as UTF-8.
295fn push_code_point(out: &mut Vec<u8>, code: u32) {
296    if code < 0x80 {
297        out.push(code as u8);
298    } else if code < 0x800 {
299        out.push(0xC0 | (code >> 6) as u8);
300        out.push(0x80 | (code & 0x3F) as u8);
301    } else if code < 0x10000 {
302        out.push(0xE0 | (code >> 12) as u8);
303        out.push(0x80 | ((code >> 6) & 0x3F) as u8);
304        out.push(0x80 | (code & 0x3F) as u8);
305    } else {
306        out.push(0xF0 | (code >> 18) as u8);
307        out.push(0x80 | ((code >> 12) & 0x3F) as u8);
308        out.push(0x80 | ((code >> 6) & 0x3F) as u8);
309        out.push(0x80 | (code & 0x3F) as u8);
310    }
311}
312
313/// Write an unpaired surrogate as the three-byte sequence WTF-8 gives it.
314fn push_surrogate(out: &mut Vec<u8>, unit: u16) {
315    out.push(0xE0 | (unit >> 12) as u8);
316    out.push(0x80 | ((unit >> 6) & 0x3F) as u8);
317    out.push(0x80 | (unit & 0x3F) as u8);
318}
319
320/// Whether the bytes end with an unpaired high surrogate.
321///
322/// High surrogates are `ED A0..AF 80..BF` and low ones `ED B0..BF 80..BF`, so the test is on
323/// the second byte of the trailing three-byte sequence.
324fn ends_with_high_surrogate(bytes: &[u8]) -> bool {
325    let len = bytes.len();
326    len >= 3 && bytes[len - 3] == 0xED && (0xA0..0xB0).contains(&bytes[len - 2])
327}
328
329/// Whether the bytes start with an unpaired low surrogate.
330fn starts_with_low_surrogate(bytes: &[u8]) -> bool {
331    bytes.len() >= 3 && bytes[0] == 0xED && (0xB0..0xC0).contains(&bytes[1])
332}
333
334impl PartialEq for Wtf8 {
335    /// Byte equality, which the canonical encoding makes equal to code-unit equality.
336    fn eq(&self, other: &Self) -> bool {
337        self.bytes == other.bytes
338    }
339}
340
341impl Eq for Wtf8 {}
342
343impl fmt::Debug for Wtf8 {
344    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
345        write!(f, "{:?}", self.to_string_lossy())
346    }
347}
348
349/// An immutable string, stored on the GC heap.
350///
351/// The content is a [`Wtf8`]; the wrapper exists so a `Value` can hold a `Gc` handle rather
352/// than the bytes.
353pub struct JsString {
354    text: Wtf8,
355    /// The code units, built on first use.
356    ///
357    /// Indexing is the one operation a script performs in a loop over a whole string —
358    /// `for (i = 0; i < s.length; i++) s.charCodeAt(i)` — and decoding from the start each
359    /// time would make that quadratic. Built once, it makes every later access `O(1)`.
360    /// Nothing here is a GC value, so the cache needs no tracing.
361    units: RefCell<Option<std::rc::Rc<Vec<u16>>>>,
362}
363
364impl JsString {
365    /// Wrap `text`.
366    pub fn new(text: impl Into<String>) -> JsString {
367        JsString {
368            text: Wtf8::new(text),
369            units: RefCell::new(None),
370        }
371    }
372
373    /// Wrap WTF-8 that is already encoded.
374    pub fn from_wtf8(text: Wtf8) -> JsString {
375        JsString {
376            text,
377            units: RefCell::new(None),
378        }
379    }
380
381    /// The code units, decoding once and remembering the result.
382    pub fn units_cached(&self) -> std::rc::Rc<Vec<u16>> {
383        if let Some(units) = self.units.borrow().as_ref() {
384            return units.clone();
385        }
386        let units = std::rc::Rc::new(self.text.to_units());
387        *self.units.borrow_mut() = Some(units.clone());
388        units
389    }
390
391    /// The code unit at `index`, in `O(1)` once the cache is warm.
392    pub fn code_unit_at(&self, index: usize) -> Option<u16> {
393        self.units_cached().get(index).copied()
394    }
395
396    /// The string's bytes.
397    pub fn wtf8(&self) -> &Wtf8 {
398        &self.text
399    }
400
401    /// The text, when it has no unpaired surrogate.
402    pub fn as_str(&self) -> Option<&str> {
403        self.text.as_str()
404    }
405
406    /// The text with unpaired surrogates replaced by U+FFFD.
407    pub fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
408        self.text.to_string_lossy()
409    }
410
411    /// The UTF-16 code units.
412    pub fn to_units(&self) -> Vec<u16> {
413        self.units_cached().as_ref().clone()
414    }
415
416    /// Length in UTF-16 code units, which is what `String.prototype.length` and
417    /// the string indexing rules count.
418    pub fn utf16_len(&self) -> usize {
419        // Cheap from the encoding, and the common case never builds the cache.
420        self.text.utf16_len()
421    }
422}
423
424impl Trace for JsString {
425    fn trace(&self, _tracer: &mut Tracer) {}
426}
427
428impl fmt::Debug for JsString {
429    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
430        write!(f, "{:?}", self.text)
431    }
432}
433
434/// A JavaScript symbol, stored on the GC heap.
435///
436/// A symbol is a *unique* property key that is not a string. Its identity is the
437/// allocation, not the description: `Symbol("a") !== Symbol("a")`, and two symbols with
438/// the same description still key two different properties. Only `Symbol.for` produces
439/// the same symbol twice, and it does so by looking the key up in the realm's registry
440/// rather than by comparing descriptions.
441pub struct JsSymbol {
442    /// The description shown by `Symbol.prototype.toString` and `description`.
443    ///
444    /// `Symbol()` and the well-known symbols have none, which is why this is an
445    /// `Option` and not an empty string — `Symbol().description` is `undefined`.
446    description: Option<String>,
447    /// The registry key, when the symbol came from `Symbol.for`.
448    ///
449    /// `Symbol.keyFor` answers `undefined` for every symbol without one, including the
450    /// well-known symbols, so the presence of this field is exactly what it tests.
451    registry_key: Option<String>,
452}
453
454impl JsSymbol {
455    /// A unique symbol with `description`.
456    pub fn new(description: Option<String>) -> JsSymbol {
457        JsSymbol {
458            description,
459            registry_key: None,
460        }
461    }
462
463    /// The registry entry for `key`, as `Symbol.for` returns it.
464    pub fn registered(key: String) -> JsSymbol {
465        JsSymbol {
466            description: Some(key.clone()),
467            registry_key: Some(key),
468        }
469    }
470
471    /// The description, if there is one.
472    pub fn description(&self) -> Option<&str> {
473        self.description.as_deref()
474    }
475
476    /// The registry key, if this symbol came from `Symbol.for`.
477    pub fn registry_key(&self) -> Option<&str> {
478        self.registry_key.as_deref()
479    }
480
481    /// `Symbol.prototype.toString`: `Symbol(description)`.
482    ///
483    /// A description is inserted verbatim, so `Symbol("a)b").toString()` is
484    /// `Symbol(a)b)` — the spec does not escape it.
485    pub fn to_display_string(&self) -> String {
486        match &self.description {
487            Some(text) => format!("Symbol({text})"),
488            None => "Symbol()".to_string(),
489        }
490    }
491}
492
493impl Trace for JsSymbol {
494    fn trace(&self, _tracer: &mut Tracer) {}
495}
496
497impl fmt::Debug for JsSymbol {
498    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
499        write!(f, "{}", self.to_display_string())
500    }
501}
502
503/// A mutable binding cell, shared between closures.
504///
505/// A variable that a closure captures cannot live in a stack slot, because the
506/// slot dies with the frame while the closure outlives it. The compiler marks such
507/// bindings `is_captured` and counts them in `var_ref_count`; the interpreter
508/// allocates one of these per captured binding on entry, and every access — from
509/// the owning frame or from any closure — goes through the cell.
510pub struct Cell {
511    value: RefCell<Value>,
512}
513
514impl Cell {
515    /// A cell holding `value`.
516    pub fn new(value: Value) -> Cell {
517        Cell {
518            value: RefCell::new(value),
519        }
520    }
521
522    /// Read the cell.
523    pub fn get(&self) -> Value {
524        self.value.borrow().clone()
525    }
526
527    /// Overwrite the cell.
528    pub fn set(&self, value: Value) {
529        *self.value.borrow_mut() = value;
530    }
531}
532
533impl Trace for Cell {
534    fn trace(&self, tracer: &mut Tracer) {
535        self.value.borrow().trace(tracer);
536    }
537}
538
539/// A JavaScript value.
540#[derive(Clone)]
541pub enum Value {
542    /// `undefined`
543    Undefined,
544    /// `null`
545    Null,
546    /// `true` / `false`
547    Bool(bool),
548    /// A 32-bit integer, exact.
549    Int(i32),
550    /// A double.
551    Float(f64),
552    /// A string.
553    String(Gc<JsString>),
554    /// An object, function, or array.
555    Object(Gc<JsObject>),
556    /// A symbol: a unique property key that is not a string.
557    Symbol(Gc<JsSymbol>),
558    /// A `BigInt`: an integer of any size, stored on the GC heap.
559    ///
560    /// A separate variant rather than a number because the two never mix: `1n + 1` is a
561    /// `TypeError`, and `1n === 1` is false.
562    BigInt(Gc<crate::bigint::BigInt>),
563    /// A try-handler target, pushed by `catch` and scanned for when an exception
564    /// is raised.
565    ///
566    /// QuickJS keeps this on the value stack as a `JS_TAG_CATCH_OFFSET` value and
567    /// finds the innermost handler by walking the stack downwards, which is how
568    /// `try` needs no separate table. Offset `0` marks an enumerator (a `for-of`
569    /// loop) rather than a `catch`: it closes the iterator and keeps unwinding.
570    CatchOffset(u32),
571    /// A `gosub` return position.
572    ///
573    /// `finally` blocks are compiled as subroutines: `gosub` pushes the address to
574    /// come back to and jumps into the block, `ret` pops the address and jumps
575    /// back. QuickJS reuses the integer tag for this (and notes it as a hardening
576    /// gap); a distinct variant keeps it out of reach of arithmetic.
577    ReturnAddress(u32),
578    /// An array hole: an index that was skipped rather than filled.
579    ///
580    /// `[1,,3]` and `[1,undefined,3]` are different arrays: `forEach` skips the hole,
581    /// `in` reports it absent, and the debug printer shows `<1 empty item>`. That
582    /// distinction has to live in the element vector, and this is the marker for it.
583    /// It is never observable from JavaScript: reading the index yields `undefined`
584    /// and no language operation can produce it.
585    Hole,
586    /// The internal marker a `let`/`const` binding holds between its scope being
587    /// entered and its initialiser running.
588    ///
589    /// QuickJS calls this `JS_UNINITIALIZED`; it is deliberately not observable
590    /// from JavaScript. It only ever sits in a slot or a cell, and every read that
591    /// may see it (`get_loc_check` and friends) turns it into a `ReferenceError`.
592    Uninitialized,
593}
594
595impl Value {
596    /// A string value on `heap`.
597    pub fn string(heap: &js_gc::Heap, text: impl Into<String>) -> Value {
598        Value::String(Gc::new(heap, JsString::new(text)))
599    }
600
601    /// A string from bytes that are already WTF-8, which is how a string containing an
602    /// unpaired surrogate reaches a `Value`.
603    pub fn string_wtf8(heap: &js_gc::Heap, text: Wtf8) -> Value {
604        Value::String(Gc::new(heap, JsString::from_wtf8(text)))
605    }
606
607    /// The number as a double, widening an [`Value::Int`].
608    pub fn as_f64(&self) -> Option<f64> {
609        match self {
610            Value::Int(i) => Some(*i as f64),
611            Value::Float(f) => Some(*f),
612            _ => None,
613        }
614    }
615
616    /// The value as a string, if it is one with no unpaired surrogate.
617    pub fn as_str(&self) -> Option<&str> {
618        match self {
619            Value::String(s) => s.as_str(),
620            _ => None,
621        }
622    }
623
624    /// The value's string content as WTF-8, which covers every string including one with an
625    /// unpaired surrogate.
626    pub fn as_wtf8(&self) -> Option<&Wtf8> {
627        match self {
628            Value::String(s) => Some(s.wtf8()),
629            _ => None,
630        }
631    }
632
633    /// The symbol, if this is one.
634    pub fn as_symbol(&self) -> Option<&Gc<JsSymbol>> {
635        match self {
636            Value::Symbol(symbol) => Some(symbol),
637            _ => None,
638        }
639    }
640
641    /// The object, if this is one.
642    pub fn as_object(&self) -> Option<&Gc<JsObject>> {
643        match self {
644            Value::Object(o) => Some(o),
645            _ => None,
646        }
647    }
648
649    /// Whether this is one of the two null-ish values.
650    pub fn is_nullish(&self) -> bool {
651        matches!(self, Value::Undefined | Value::Null)
652    }
653
654    /// `typeof value`.
655    pub fn type_of(&self) -> &'static str {
656        match self {
657            Value::Undefined => "undefined",
658            Value::Null => "object",
659            Value::Bool(_) => "boolean",
660            Value::Int(_) | Value::Float(_) => "number",
661            Value::String(_) => "string",
662            Value::Symbol(_) => "symbol",
663            Value::BigInt(_) => "bigint",
664            Value::Object(object) => {
665                if object.is_callable() {
666                    "function"
667                } else {
668                    "object"
669                }
670            }
671            // The internal markers are never observable from JavaScript;
672            // reporting `undefined` keeps the answer honest if a bug lets one leak.
673            Value::Uninitialized
674            | Value::Hole
675            | Value::CatchOffset(_)
676            | Value::ReturnAddress(_) => "undefined",
677        }
678    }
679
680    /// `ToBoolean`, which is also what a conditional jump tests.
681    pub fn to_boolean(&self) -> bool {
682        match self {
683            Value::Undefined | Value::Null => false,
684            Value::Bool(b) => *b,
685            Value::Int(i) => *i != 0,
686            // `NaN` is falsy, and so is `-0`.
687            Value::Float(f) => *f != 0.0 && !f.is_nan(),
688            Value::String(s) => !s.wtf8().is_empty(),
689            // Every symbol is truthy, even the one with no description.
690            Value::Symbol(_) => true,
691            // A bigint follows the numbers: `0n` is falsy and every other width is truthy.
692            // Saying "every bigint is truthy" turned `if (b & 1n)` into an unconditional
693            // branch, which quietly corrupted every bigint algorithm that tests a bit.
694            Value::BigInt(big) => !big.is_zero(),
695            // Every object is truthy, including `new Boolean(false)`.
696            Value::Object(_) => true,
697            Value::Uninitialized
698            | Value::Hole
699            | Value::CatchOffset(_)
700            | Value::ReturnAddress(_) => false,
701        }
702    }
703
704    /// `ToNumber`, for the arithmetic operators.
705    pub fn to_number(&self) -> f64 {
706        match self {
707            Value::Undefined => f64::NAN,
708            Value::Null => 0.0,
709            Value::Bool(b) => {
710                if *b {
711                    1.0
712                } else {
713                    0.0
714                }
715            }
716            Value::Int(i) => *i as f64,
717            Value::Float(f) => *f,
718            Value::String(s) => string_to_number(&s.to_string_lossy()),
719            // `ToNumber` of a symbol or a bigint is a `TypeError`; `NaN` keeps this
720            // infallible helper total, and the operators reject them first.
721            Value::Symbol(_) => f64::NAN,
722            Value::BigInt(_) => f64::NAN,
723            // `ToNumber` of an object runs `ToPrimitive` first, which needs the
724            // value-of/valueOf machinery; until that lands an object is `NaN`
725            // rather than a panic.
726            Value::Object(_) => f64::NAN,
727            Value::Uninitialized
728            | Value::Hole
729            | Value::CatchOffset(_)
730            | Value::ReturnAddress(_) => f64::NAN,
731        }
732    }
733
734    /// `ToInt32`, the conversion the bitwise operators and `<<`/`>>`/`>>>` use.
735    pub fn to_int32(&self) -> i32 {
736        to_int32(self.to_number())
737    }
738
739    /// `ToUint32`.
740    pub fn to_uint32(&self) -> u32 {
741        self.to_int32() as u32
742    }
743
744    /// `ToString`.
745    ///
746    /// Named `to_js_string` rather than `to_string` so it does not shadow
747    /// [`std::fmt::Display`]: the two disagree on purpose (`display` keeps the sign
748    /// of `-0`), and an accidental `to_string` on a `Value` would silently pick the
749    /// wrong one.
750    pub fn to_js_string(&self) -> String {
751        match self {
752            Value::Undefined => "undefined".to_string(),
753            Value::Null => "null".to_string(),
754            Value::Bool(true) => "true".to_string(),
755            Value::Bool(false) => "false".to_string(),
756            Value::Int(i) => i.to_string(),
757            Value::Float(f) => number_to_string(*f),
758            // Lossy only for a string with an unpaired surrogate, which has no `&str`
759            // form at all; every other string borrows and copies nothing extra.
760            Value::String(s) => s.to_string_lossy().into_owned(),
761            Value::BigInt(big) => big.to_decimal_string(),
762            // `ToString` of a symbol is a `TypeError`; this descriptive form is what
763            // `String(sym)` and the error messages use. Callers that must throw go
764            // through `Interp::checked_to_string`.
765            Value::Symbol(s) => s.to_display_string(),
766            Value::Object(_) => "[object Object]".to_string(),
767            Value::Uninitialized
768            | Value::Hole
769            | Value::CatchOffset(_)
770            | Value::ReturnAddress(_) => "undefined".to_string(),
771        }
772    }
773
774    /// `===`.
775    pub fn strict_equals(&self, other: &Value) -> bool {
776        match (self, other) {
777            (Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => true,
778            (Value::Bool(a), Value::Bool(b)) => a == b,
779            // `Int` and `Float` are the same type to JavaScript, so `1 === 1.0`.
780            (Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) => {
781                let (a, b) = (self.to_number(), other.to_number());
782                a == b
783            }
784            (Value::String(a), Value::String(b)) => a.as_str() == b.as_str(),
785            // Two bigints compare by value, because the representation is canonical —
786            // `2n ** 1000n` computed twice is one value, not two handles.
787            (Value::BigInt(a), Value::BigInt(b)) => **a == **b,
788            // A symbol is equal only to itself: the same description means nothing.
789            (Value::Symbol(a), Value::Symbol(b)) => a.ptr_eq(b),
790            // Objects compare by identity, never structurally.
791            (Value::Object(a), Value::Object(b)) => a.ptr_eq(b),
792            _ => false,
793        }
794    }
795
796    /// `SameValue`, the equality `Object.is` uses and a proxy invariant needs.
797    ///
798    /// It is [`Value::same_value_zero`] plus the one extra distinction: `+0` and `-0`
799    /// are different values here, which is what makes `Object.is(0, -0)` false.
800    pub fn same_value(&self, other: &Value) -> bool {
801        if let (Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) = (self, other) {
802            let (a, b) = (self.to_number(), other.to_number());
803            if a.is_nan() && b.is_nan() {
804                return true;
805            }
806            if a == 0.0 && b == 0.0 {
807                return a.is_sign_negative() == b.is_sign_negative();
808            }
809            return a == b;
810        }
811        self.strict_equals(other)
812    }
813
814    /// `SameValueZero`, the equality a `Map` key and a `Set` element use.
815    ///
816    /// It differs from `===` in exactly one place: `NaN` equals itself. That is what makes
817    /// `map.set(NaN, 1); map.get(NaN)` work, and it is why a `Map` cannot use `strict_equals`
818    /// directly. A bigint compares by value, since its representation is canonical.
819    pub fn same_value_zero(&self, other: &Value) -> bool {
820        if let (Value::Float(a), Value::Float(b)) = (self, other)
821            && a.is_nan()
822            && b.is_nan()
823        {
824            return true;
825        }
826        self.strict_equals(other)
827    }
828
829    /// `==`, with the coercion rules.
830    ///
831    /// `NaN` compares unequal to everything including itself, which the numeric
832    /// branch already gets right. An object compares by identity against another
833    /// object and by its primitive form against a primitive.
834    pub fn loose_equals(&self, other: &Value) -> bool {
835        if matches!(self, Value::Object(_)) || matches!(other, Value::Object(_)) {
836            return match (self, other) {
837                (Value::Object(a), Value::Object(b)) => a.ptr_eq(b),
838                _ => primitive_loose_equals(&self.primitive(), &other.primitive()),
839            };
840        }
841        match (self, other) {
842            (Value::Undefined | Value::Null, Value::Undefined | Value::Null) => true,
843            (Value::Undefined | Value::Null, _) | (_, Value::Undefined | Value::Null) => false,
844            (Value::String(a), Value::String(b)) => a.as_str() == b.as_str(),
845            (Value::Symbol(a), Value::Symbol(b)) => a.ptr_eq(b),
846            (Value::Bool(a), Value::Bool(b)) => a == b,
847            // A bigint equals another bigint by value, a string that spells it exactly, or a
848            // number with the same mathematical value — that last one is why `1n == 1` is
849            // true while `1n === 1` is false.
850            (Value::BigInt(a), Value::BigInt(b)) => **a == **b,
851            (Value::BigInt(a), Value::String(b)) | (Value::String(b), Value::BigInt(a)) => {
852                crate::bigint::BigInt::from_string(&b.to_string_lossy()).as_ref() == Some(&**a)
853            }
854            (Value::BigInt(a), other) => match other {
855                Value::Int(_) | Value::Float(_) => bigint_equals_number(a, other.to_number()),
856                // A boolean is `ToNumber`ed first, so `true == 1n` is true.
857                Value::Bool(flag) => bigint_equals_number(a, if *flag { 1.0 } else { 0.0 }),
858                _ => false,
859            },
860            (other, Value::BigInt(b)) => match other {
861                Value::Int(_) | Value::Float(_) => bigint_equals_number(b, other.to_number()),
862                Value::Bool(flag) => bigint_equals_number(b, if *flag { 1.0 } else { 0.0 }),
863                _ => false,
864            },
865            // Everything else compares numerically, which covers `"1" == 1`,
866            // `true == 1` and `Int` against `Float`.
867            _ => self.to_number() == other.to_number(),
868        }
869    }
870
871    /// `ToPrimitive` with no hint.
872    ///
873    /// The result is an owned [`Primitive`] rather than a [`Value`] because a
874    /// string `Value` needs a heap handle and this path deliberately has none.
875    fn primitive(&self) -> Primitive {
876        match self {
877            Value::Undefined => Primitive::Undefined,
878            Value::Null => Primitive::Null,
879            Value::Bool(b) => Primitive::Bool(*b),
880            Value::Int(i) => Primitive::Number(*i as f64),
881            Value::Float(f) => Primitive::Number(*f),
882            Value::String(s) => Primitive::String(s.to_string_lossy().into_owned()),
883            // A symbol stays distinct from a string here so `==` does not treat it as
884            // one; only an object's `ToPrimitive` can produce a symbol from an object.
885            Value::Symbol(s) => Primitive::Symbol(s.clone()),
886            // A bigint reaches `Primitive` as its decimal text, which is enough for the
887            // loose comparisons that go through here; the operators reject it first.
888            Value::BigInt(big) => Primitive::String(big.to_decimal_string()),
889            Value::Object(_) => Primitive::String(self.to_js_string()),
890            Value::Uninitialized
891            | Value::Hole
892            | Value::CatchOffset(_)
893            | Value::ReturnAddress(_) => Primitive::Undefined,
894        }
895    }
896}
897
898/// A value with no object identity, used by [`Value::loose_equals`].
899enum Primitive {
900    Undefined,
901    Null,
902    Bool(bool),
903    Number(f64),
904    String(String),
905    /// A symbol, which is a primitive but compares by identity.
906    Symbol(Gc<JsSymbol>),
907}
908
909/// `==` once both sides are primitives.
910fn primitive_loose_equals(left: &Primitive, right: &Primitive) -> bool {
911    use Primitive::*;
912    match (left, right) {
913        (Undefined | Null, Undefined | Null) => true,
914        (Undefined | Null, _) | (_, Undefined | Null) => false,
915        // A symbol is a primitive, so `==` on two symbols is identity. Against
916        // anything else it is `false` — the only coercion that could apply is boxing,
917        // and `Object(Symbol())` is an object, not a `Primitive`.
918        (Symbol(a), Symbol(b)) => a.ptr_eq(b),
919        (Symbol(_), _) | (_, Symbol(_)) => false,
920        (String(a), String(b)) => a == b,
921        (Bool(a), Bool(b)) => a == b,
922        (Number(a), Number(b)) => a == b,
923        // A string against a number compares numerically, so `"" == 0` and
924        // `"1" == 1`.
925        (String(s), Number(n)) | (Number(n), String(s)) => string_to_number(s) == *n,
926        (Bool(b), Number(n)) | (Number(n), Bool(b)) => (if *b { 1.0 } else { 0.0 }) == *n,
927        (Bool(b), String(s)) | (String(s), Bool(b)) => {
928            string_to_number(s) == (if *b { 1.0 } else { 0.0 })
929        }
930    }
931}
932
933/// `bigint == number`, compared as whole numbers rather than through the double.
934///
935/// Going through `to_f64` made `100000000000000000001n == 1e20` true, because the double
936/// rounds both sides onto the same value; the spec compares the exact integers, and a
937/// double that is already an integer converts to one exactly.
938fn bigint_equals_number(big: &crate::bigint::BigInt, number: f64) -> bool {
939    number.is_finite()
940        && number.fract() == 0.0
941        && crate::bigint::BigInt::from_f64_truncated(number) == *big
942}
943
944/// `ToInt32`.
945///
946/// The spec's modulo-2^32 arithmetic: `NaN` and the infinities become zero, and
947/// the fractional part is dropped toward zero before the wrap.
948pub fn to_int32(value: f64) -> i32 {
949    if !value.is_finite() || value == 0.0 {
950        return 0;
951    }
952    let truncated = value.trunc();
953    let modulo = truncated.rem_euclid(4294967296.0);
954    let wrapped = if modulo >= 2147483648.0 {
955        modulo - 4294967296.0
956    } else {
957        modulo
958    };
959    wrapped as i32
960}
961
962/// `ToNumber` applied to a string.
963///
964/// Leading and trailing whitespace is allowed; anything else must be a valid
965/// numeric literal, because a failed parse is `NaN` rather than a prefix match.
966/// The empty string is `0`, which is a common source of surprise.
967pub fn string_to_number(text: &str) -> f64 {
968    let trimmed = text.trim();
969    if trimmed.is_empty() {
970        return 0.0;
971    }
972    if let Some(rest) = strip_radix_prefix(trimmed, "0x", "0X") {
973        return radix_number(rest, 16);
974    }
975    if let Some(rest) = strip_radix_prefix(trimmed, "0o", "0O") {
976        return radix_number(rest, 8);
977    }
978    if let Some(rest) = strip_radix_prefix(trimmed, "0b", "0B") {
979        return radix_number(rest, 2);
980    }
981    let (sign, digits) = match trimmed.strip_prefix(['+', '-']) {
982        Some(rest) => (&trimmed[..1], rest),
983        None => ("", trimmed),
984    };
985    // `Infinity` is a literal; `inf`/`nan` are not, even though Rust parses them.
986    if digits == "Infinity" {
987        return if sign == "-" {
988            f64::NEG_INFINITY
989        } else {
990            f64::INFINITY
991        };
992    }
993    // Rust's parser accepts the literals JavaScript does not, so the shape is
994    // checked before trusting it: digits with at most one dot, at most one
995    // exponent, and no trailing garbage.
996    if !is_decimal_literal(digits) {
997        return f64::NAN;
998    }
999    trimmed.parse::<f64>().unwrap_or(f64::NAN)
1000}
1001
1002fn strip_radix_prefix<'a>(text: &'a str, lower: &str, upper: &str) -> Option<&'a str> {
1003    text.strip_prefix(lower)
1004        .or_else(|| text.strip_prefix(upper))
1005}
1006
1007fn radix_number(digits: &str, radix: u32) -> f64 {
1008    if digits.is_empty() || !digits.chars().all(|c| c.is_digit(radix)) {
1009        return f64::NAN;
1010    }
1011    // A long literal overflows `u64`; JavaScript then rounds, so fall back to an
1012    // accumulating double rather than reporting `NaN`.
1013    match u64::from_str_radix(digits, radix) {
1014        Ok(value) => value as f64,
1015        Err(_) => digits.chars().fold(0.0, |acc, c| {
1016            acc * radix as f64 + c.to_digit(radix).unwrap_or(0) as f64
1017        }),
1018    }
1019}
1020
1021/// Whether `text` is a decimal literal with no sign.
1022fn is_decimal_literal(text: &str) -> bool {
1023    let bytes = text.as_bytes();
1024    let mut index = 0;
1025    let mut digits = 0;
1026    while index < bytes.len() && bytes[index].is_ascii_digit() {
1027        index += 1;
1028        digits += 1;
1029    }
1030    if index < bytes.len() && bytes[index] == b'.' {
1031        index += 1;
1032        while index < bytes.len() && bytes[index].is_ascii_digit() {
1033            index += 1;
1034            digits += 1;
1035        }
1036    }
1037    if digits == 0 {
1038        return false;
1039    }
1040    if index < bytes.len() && (bytes[index] == b'e' || bytes[index] == b'E') {
1041        index += 1;
1042        if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
1043            index += 1;
1044        }
1045        let start = index;
1046        while index < bytes.len() && bytes[index].is_ascii_digit() {
1047            index += 1;
1048        }
1049        if index == start {
1050            return false;
1051        }
1052    }
1053    index == bytes.len()
1054}
1055
1056/// `ToString` applied to a number.
1057///
1058/// The thresholds are the ones the spec's `Number::toString` uses: exponential
1059/// form below `1e-6` and from `1e21` up, decimal form in between. Within the
1060/// decimal range Rust's shortest-round-trip formatter already agrees with
1061/// JavaScript digit for digit — including the notorious `0.30000000000000004` —
1062/// so only the exponent spelling has to be normalised.
1063pub fn number_to_string(value: f64) -> String {
1064    if value.is_nan() {
1065        return "NaN".to_string();
1066    }
1067    if value.is_infinite() {
1068        return if value > 0.0 {
1069            "Infinity".to_string()
1070        } else {
1071            "-Infinity".to_string()
1072        };
1073    }
1074    if value == 0.0 {
1075        // `ToString(-0)` is `"0"`; `print(-0)` is a different question, see
1076        // [`number_to_string_for_print`].
1077        return "0".to_string();
1078    }
1079    let magnitude = value.abs();
1080    if magnitude >= 1e21 || magnitude < 1e-6 {
1081        return normalise_exponent(format!("{value:e}"));
1082    }
1083    format!("{value}")
1084}
1085
1086/// `ToString` as the engine's `print` applies it, which differs from the language
1087/// one for negative zero.
1088///
1089/// `print(-0)` prints `-0` in QuickJS while `String(-0)` is `"0"`, because the host
1090/// printer takes the number's own spelling. Reproduced here so byte-for-byte output
1091/// comparisons do not trip over it.
1092pub fn number_to_string_for_print(value: f64) -> String {
1093    if value == 0.0 && value.is_sign_negative() {
1094        return "-0".to_string();
1095    }
1096    number_to_string(value)
1097}
1098
1099/// Rewrite Rust's exponent spelling as JavaScript's: always signed, never padded.
1100///
1101/// Rust writes `1e-7` and `1e21`; JavaScript writes `1e-7` and `1e+21`. The
1102/// difference is only the explicit `+`.
1103fn normalise_exponent(text: String) -> String {
1104    let Some((mantissa, exponent)) = text.split_once('e') else {
1105        return text;
1106    };
1107    if exponent.starts_with('-') {
1108        text
1109    } else {
1110        let digits = exponent.strip_prefix('+').unwrap_or(exponent);
1111        format!("{mantissa}e+{digits}")
1112    }
1113}
1114
1115impl Trace for Value {
1116    fn trace(&self, tracer: &mut Tracer) {
1117        match self {
1118            Value::String(s) => tracer.visit(s),
1119            Value::Object(o) => tracer.visit(o),
1120            Value::Symbol(s) => tracer.visit(s),
1121            _ => {}
1122        }
1123    }
1124}
1125
1126impl fmt::Debug for Value {
1127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1128        match self {
1129            Value::Undefined => f.write_str("undefined"),
1130            Value::Null => f.write_str("null"),
1131            Value::Bool(b) => write!(f, "{b}"),
1132            Value::Int(i) => write!(f, "{i}"),
1133            Value::Float(x) => write!(f, "{}", number_to_string(*x)),
1134            Value::String(s) => write!(f, "{:?}", s.as_str()),
1135            Value::Object(_) => f.write_str("[object]"),
1136            Value::Symbol(s) => f.write_str(&s.to_display_string()),
1137            Value::BigInt(big) => write!(f, "{}n", big.to_decimal_string()),
1138            Value::Uninitialized => f.write_str("<uninitialised>"),
1139            Value::Hole => f.write_str("<hole>"),
1140            Value::CatchOffset(offset) => write!(f, "<catch {offset}>"),
1141            Value::ReturnAddress(address) => write!(f, "<ret {address}>"),
1142        }
1143    }
1144}
1145
1146#[cfg(test)]
1147mod tests {
1148    use super::*;
1149
1150    #[test]
1151    fn int32_wraps_the_way_the_spec_says() {
1152        assert_eq!(to_int32(0.0), 0);
1153        assert_eq!(to_int32(f64::NAN), 0);
1154        assert_eq!(to_int32(f64::INFINITY), 0);
1155        assert_eq!(to_int32(1.9), 1);
1156        assert_eq!(to_int32(-1.9), -1);
1157        assert_eq!(to_int32(2147483648.0), -2147483648);
1158        assert_eq!(to_int32(4294967296.0), 0);
1159        assert_eq!(to_int32(-4294967297.0), -1);
1160    }
1161
1162    #[test]
1163    fn numbers_print_like_javascript() {
1164        assert_eq!(number_to_string(0.0), "0");
1165        assert_eq!(number_to_string(-0.0), "0");
1166        assert_eq!(number_to_string(1.0), "1");
1167        assert_eq!(number_to_string(-1.5), "-1.5");
1168        assert_eq!(number_to_string(1e21), "1e+21");
1169        assert_eq!(number_to_string(1e-7), "1e-7");
1170        assert_eq!(number_to_string(1e-6), "0.000001");
1171        assert_eq!(number_to_string(1e20), "100000000000000000000");
1172        assert_eq!(number_to_string(5e-324), "5e-324");
1173        // `print(-0)` differs from `String(-0)`.
1174        assert_eq!(number_to_string_for_print(-0.0), "-0");
1175        assert_eq!(number_to_string(f64::NAN), "NaN");
1176        assert_eq!(number_to_string(f64::INFINITY), "Infinity");
1177        assert_eq!(number_to_string(f64::NEG_INFINITY), "-Infinity");
1178    }
1179
1180    #[test]
1181    fn strings_parse_to_numbers_without_prefix_matching() {
1182        assert_eq!(string_to_number(""), 0.0);
1183        assert_eq!(string_to_number("  "), 0.0);
1184        assert_eq!(string_to_number(" 42 "), 42.0);
1185        assert_eq!(string_to_number("0x10"), 16.0);
1186        assert_eq!(string_to_number("0b101"), 5.0);
1187        assert_eq!(string_to_number("0o17"), 15.0);
1188        assert_eq!(string_to_number("Infinity"), f64::INFINITY);
1189        assert_eq!(string_to_number("-Infinity"), f64::NEG_INFINITY);
1190        assert_eq!(string_to_number("1e3"), 1000.0);
1191        assert_eq!(string_to_number(".5"), 0.5);
1192        assert_eq!(string_to_number("5."), 5.0);
1193        // These would all be prefix matches or Rust-only spellings.
1194        assert!(string_to_number("12px").is_nan());
1195        assert!(string_to_number("inf").is_nan());
1196        assert!(string_to_number("nan").is_nan());
1197        assert!(string_to_number("1e").is_nan());
1198        assert!(string_to_number("0x").is_nan());
1199    }
1200
1201    #[test]
1202    fn strict_equality_ignores_the_int_float_split() {
1203        assert!(Value::Int(1).strict_equals(&Value::Float(1.0)));
1204        assert!(!Value::Int(1).strict_equals(&Value::Float(1.5)));
1205        assert!(!Value::Float(f64::NAN).strict_equals(&Value::Float(f64::NAN)));
1206        assert!(Value::Int(0).strict_equals(&Value::Float(-0.0)));
1207        assert!(!Value::Int(0).strict_equals(&Value::Null));
1208        assert!(!Value::Undefined.strict_equals(&Value::Null));
1209    }
1210
1211    #[test]
1212    fn falsy_values_are_the_spec_list() {
1213        assert!(!Value::Undefined.to_boolean());
1214        assert!(!Value::Null.to_boolean());
1215        assert!(!Value::Bool(false).to_boolean());
1216        assert!(!Value::Int(0).to_boolean());
1217        assert!(!Value::Float(f64::NAN).to_boolean());
1218        assert!(!Value::Float(-0.0).to_boolean());
1219        assert!(Value::Float(0.1).to_boolean());
1220    }
1221}