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, shared.
38    ///
39    /// `Rc<[u8]>` rather than `Box<[u8]>` because cloning a `Wtf8` is one of the hottest
40    /// operations in the engine: every property key comparison, every atom lookup and every
41    /// `Value::String` copy did it, and with a `Box` each clone deep-copied the bytes. That
42    /// is a heap allocation plus a memcpy per property read, which is why
43    /// `property:monomorphic` was 16× slower than the reference before this.
44    ///
45    /// Being `Rc` makes `Wtf8` `!Send`, which it effectively already was: it lives behind
46    /// `Gc`, which uses a non-atomic refcount.
47    bytes: std::rc::Rc<[u8]>,
48    /// Whether `bytes` is valid UTF-8, meaning the string has no unpaired surrogate.
49    ///
50    /// A `Wtf8` is immutable, so this stays correct for its whole life.
51    valid: bool,
52}
53
54impl Wtf8 {
55    /// Wrap a Rust string, which is valid UTF-8 by construction.
56    pub fn new(text: impl Into<String>) -> Wtf8 {
57        Wtf8 {
58            bytes: text.into().into_bytes().into(),
59            valid: true,
60        }
61    }
62
63    /// Build from a `&str` without copying it.
64    ///
65    /// `Wtf8::new` takes `impl Into<String>`, which copies. A property atom is a `&str` that
66    /// already lives in the compiled code and outlives every use of the key, so sharing the
67    /// bytes is free — and this is on the path of every property access.
68    pub fn from_rc_str(text: &str) -> Wtf8 {
69        Wtf8 {
70            bytes: std::rc::Rc::from(text.as_bytes()),
71            valid: true,
72        }
73    }
74
75    /// Build from bytes that are already WTF-8, with `valid` saying whether they contain an
76    /// unpaired surrogate.
77    ///
78    /// Used by the rope's flattening path, which has just concatenated children whose
79    /// validity it knows.
80    pub fn from_parts(bytes: Vec<u8>, valid: bool) -> Wtf8 {
81        Wtf8 {
82            bytes: bytes.into(),
83            valid,
84        }
85    }
86
87    /// Whether the bytes are valid UTF-8, i.e. the string has no unpaired surrogate.
88    pub fn is_valid(&self) -> bool {
89        self.valid
90    }
91
92    /// Build from UTF-16 code units, which is the form a JS string really has.
93    ///
94    /// An unpaired surrogate survives; a pair is folded into its astral code point.
95    pub fn from_units(units: &[u16]) -> Wtf8 {
96        let mut bytes = Vec::with_capacity(units.len());
97        let mut valid = true;
98        let mut index = 0;
99        while index < units.len() {
100            let unit = units[index];
101            match units.get(index + 1) {
102                Some(&low) if is_high(unit) && is_low(low) => {
103                    push_code_point(&mut bytes, combine(unit, low));
104                    index += 2;
105                }
106                _ if is_surrogate(unit) => {
107                    // A lone surrogate keeps its own three-byte form, so it round-trips and
108                    // still counts as one code unit.
109                    valid = false;
110                    push_surrogate(&mut bytes, unit);
111                    index += 1;
112                }
113                _ => {
114                    push_code_point(&mut bytes, unit as u32);
115                    index += 1;
116                }
117            }
118        }
119        Wtf8 {
120            bytes: bytes.into(),
121            valid,
122        }
123    }
124
125    /// The text, when it is valid UTF-8.
126    ///
127    /// `None` only for a string containing an unpaired surrogate — there is no `&str` for
128    /// one. Callers that only need to display or compare use [`Wtf8::to_string_lossy`].
129    pub fn as_str(&self) -> Option<&str> {
130        if self.valid {
131            // SAFETY: `valid` is only set by the encoder above, which produces valid UTF-8
132            // exactly when no surrogate was written on its own, and the bytes never change.
133            Some(unsafe { std::str::from_utf8_unchecked(&self.bytes) })
134        } else {
135            None
136        }
137    }
138
139    /// The text with unpaired surrogates replaced by U+FFFD.
140    ///
141    /// Borrowed, and therefore free, for the ordinary string that has no surrogate.
142    pub fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
143        match self.as_str() {
144            Some(text) => std::borrow::Cow::Borrowed(text),
145            None => String::from_utf8_lossy(&self.bytes),
146        }
147    }
148
149    /// The WTF-8 bytes. Two `Wtf8`s are equal exactly when these are.
150    pub fn as_bytes(&self) -> &[u8] {
151        &self.bytes
152    }
153
154    /// The UTF-16 code units, which is what indexing and `charCodeAt` count.
155    pub fn to_units(&self) -> Vec<u16> {
156        let mut units = Vec::with_capacity(self.utf16_len());
157        self.push_units(&mut units);
158        units
159    }
160
161    /// Length in UTF-16 code units, which is what `String.prototype.length` reports.
162    ///
163    /// Counted from the encoding rather than by decoding, so it does not allocate: a
164    /// four-byte sequence is a surrogate pair and therefore two units, everything else is
165    /// one.
166    pub fn utf16_len(&self) -> usize {
167        self.bytes
168            .iter()
169            .filter(|byte| (**byte & 0xC0) != 0x80)
170            .map(|byte| if *byte >= 0xF0 { 2 } else { 1 })
171            .sum()
172    }
173
174    /// The code unit at `index`, or `None` past the end.
175    pub fn code_unit_at(&self, index: usize) -> Option<u16> {
176        // Walking instead of decoding keeps `charCodeAt` in a loop linear rather than
177        // quadratic, which matters because that is exactly how a script inspects a string.
178        let mut position = 0;
179        let mut at = 0;
180        while at < self.bytes.len() {
181            let (units, count, width) = self.sequence_at(at);
182            if position + count > index {
183                return Some(units[index - position]);
184            }
185            position += count;
186            at += width;
187        }
188        None
189    }
190
191    /// Whether the string is empty.
192    pub fn is_empty(&self) -> bool {
193        self.bytes.is_empty()
194    }
195
196    /// One code unit as a string, which is what `s[i]` yields.
197    ///
198    /// A single unit, not a code point: `"\u{1F600}"[0]` is the lone high surrogate, because
199    /// indexing a string in JS works on code units.
200    pub fn unit_at(&self, index: usize) -> Option<Wtf8> {
201        self.code_unit_at(index)
202            .map(|unit| Wtf8::from_units(&[unit]))
203    }
204
205    /// The code units `start..end`, re-encoded canonically.
206    pub fn slice_units(&self, start: usize, end: usize) -> Wtf8 {
207        let units = self.to_units();
208        let start = start.min(units.len());
209        let end = end.clamp(start, units.len());
210        Wtf8::from_units(&units[start..end])
211    }
212
213    /// One element per code *point*, which is how a string is iterated.
214    ///
215    /// Iteration and indexing disagree on purpose: `[...str]` splits an astral character
216    /// into one element while `str[0]` splits it into half a surrogate pair.
217    pub fn code_points(&self) -> Vec<Wtf8> {
218        let mut out = Vec::new();
219        let mut at = 0;
220        while at < self.bytes.len() {
221            let (_, _, width) = self.sequence_at(at);
222            let mut bytes = Vec::with_capacity(width);
223            bytes.extend_from_slice(&self.bytes[at..at + width]);
224            // A single sequence is always canonical on its own: a four-byte one is already
225            // an astral code point and a three-byte one is a BMP code point or a lone
226            // surrogate.
227            out.push(Wtf8 {
228                valid: std::str::from_utf8(&bytes).is_ok(),
229                bytes: bytes.into(),
230            });
231            at += width;
232        }
233        out
234    }
235
236    /// Concatenate, keeping the encoding canonical.
237    ///
238    /// Byte concatenation is already canonical *except* where a high surrogate at the end of
239    /// `self` meets a low surrogate at the start of `other`: those two must fold into one
240    /// astral sequence, or the result would be a different string from the one the language
241    /// says `+` produces.
242    pub fn concat(&self, other: &Wtf8) -> Wtf8 {
243        let bridges =
244            ends_with_high_surrogate(&self.bytes) && starts_with_low_surrogate(&other.bytes);
245        if !bridges {
246            let mut bytes = Vec::with_capacity(self.bytes.len() + other.bytes.len());
247            bytes.extend_from_slice(&self.bytes);
248            bytes.extend_from_slice(&other.bytes);
249            return Wtf8 {
250                bytes: bytes.into(),
251                valid: self.valid && other.valid,
252            };
253        }
254        let mut units = self.to_units();
255        units.extend(other.to_units());
256        Wtf8::from_units(&units)
257    }
258
259    /// Append the code units to `out`.
260    fn push_units(&self, out: &mut Vec<u16>) {
261        let mut at = 0;
262        while at < self.bytes.len() {
263            let (units, count, width) = self.sequence_at(at);
264            out.extend_from_slice(&units[..count]);
265            at += width;
266        }
267    }
268
269    /// The code points the regular expression engine matches against.
270    ///
271    /// This is [`Wtf8::code_points`] flattened to `u32`, with a lone surrogate kept as its
272    /// own value rather than becoming U+FFFD: `\p{Cs}` has to match it, and no `char` can
273    /// hold it. A valid pair is one code point, so an offset into this list is still a code
274    /// point boundary.
275    pub fn code_point_values(&self) -> Vec<u32> {
276        self.code_points()
277            .into_iter()
278            .map(|point| match point.as_str() {
279                Some(text) => text.chars().next().map_or(0xFFFD, |c| c as u32),
280                // A lone surrogate: three bytes, one code unit, which *is* the value.
281                None => point.to_units().first().copied().map_or(0xFFFD, u32::from),
282            })
283            .collect()
284    }
285
286    /// The code units the sequence starting at `at` stands for, how many of them there are,
287    /// and its byte width.
288    fn sequence_at(&self, at: usize) -> ([u16; 2], usize, usize) {
289        let byte = self.bytes[at];
290        let byte_at = |offset: usize| self.bytes.get(at + offset).copied().unwrap_or(0) as u32;
291        if byte < 0x80 {
292            ([byte as u16, 0], 1, 1)
293        } else if byte >> 5 == 0b110 {
294            (
295                [
296                    (((byte as u32 & 0x1F) << 6) | (byte_at(1) & 0x3F)) as u16,
297                    0,
298                ],
299                1,
300                2,
301            )
302        } else if byte >> 4 == 0b1110 {
303            // A three-byte sequence is either a BMP code point or a lone surrogate; either
304            // way it is exactly one code unit.
305            (
306                [
307                    ((byte as u32 & 0x0F) << 12 | ((byte_at(1) & 0x3F) << 6) | (byte_at(2) & 0x3F))
308                        as u16,
309                    0,
310                ],
311                1,
312                3,
313            )
314        } else {
315            let code = (byte as u32 & 0x07) << 18
316                | ((byte_at(1) & 0x3F) << 12)
317                | ((byte_at(2) & 0x3F) << 6)
318                | (byte_at(3) & 0x3F);
319            let code = code.wrapping_sub(0x10000);
320            (
321                [
322                    0xD800u16.wrapping_add((code >> 10) as u16),
323                    0xDC00u16.wrapping_add((code & 0x3FF) as u16),
324                ],
325                2,
326                4,
327            )
328        }
329    }
330}
331
332fn is_surrogate(unit: u16) -> bool {
333    (0xD800..0xE000).contains(&unit)
334}
335
336fn is_high(unit: u16) -> bool {
337    (0xD800..0xDC00).contains(&unit)
338}
339
340fn is_low(unit: u16) -> bool {
341    (0xDC00..0xE000).contains(&unit)
342}
343
344/// The astral code point a surrogate pair spells.
345fn combine(high: u16, low: u16) -> u32 {
346    0x10000 + ((high as u32 - 0xD800) << 10) + (low as u32 - 0xDC00)
347}
348
349/// Write a code point as UTF-8.
350fn push_code_point(out: &mut Vec<u8>, code: u32) {
351    if code < 0x80 {
352        out.push(code as u8);
353    } else if code < 0x800 {
354        out.push(0xC0 | (code >> 6) as u8);
355        out.push(0x80 | (code & 0x3F) as u8);
356    } else if code < 0x10000 {
357        out.push(0xE0 | (code >> 12) as u8);
358        out.push(0x80 | ((code >> 6) & 0x3F) as u8);
359        out.push(0x80 | (code & 0x3F) as u8);
360    } else {
361        out.push(0xF0 | (code >> 18) as u8);
362        out.push(0x80 | ((code >> 12) & 0x3F) as u8);
363        out.push(0x80 | ((code >> 6) & 0x3F) as u8);
364        out.push(0x80 | (code & 0x3F) as u8);
365    }
366}
367
368/// Write an unpaired surrogate as the three-byte sequence WTF-8 gives it.
369fn push_surrogate(out: &mut Vec<u8>, unit: u16) {
370    out.push(0xE0 | (unit >> 12) as u8);
371    out.push(0x80 | ((unit >> 6) & 0x3F) as u8);
372    out.push(0x80 | (unit & 0x3F) as u8);
373}
374
375/// Whether the bytes end with an unpaired high surrogate.
376///
377/// High surrogates are `ED A0..AF 80..BF` and low ones `ED B0..BF 80..BF`, so the test is on
378/// the second byte of the trailing three-byte sequence.
379fn ends_with_high_surrogate(bytes: &[u8]) -> bool {
380    let len = bytes.len();
381    len >= 3 && bytes[len - 3] == 0xED && (0xA0..0xB0).contains(&bytes[len - 2])
382}
383
384/// Whether the bytes start with an unpaired low surrogate.
385fn starts_with_low_surrogate(bytes: &[u8]) -> bool {
386    bytes.len() >= 3 && bytes[0] == 0xED && (0xB0..0xC0).contains(&bytes[1])
387}
388
389impl PartialEq for Wtf8 {
390    /// Byte equality, which the canonical encoding makes equal to code-unit equality.
391    fn eq(&self, other: &Self) -> bool {
392        self.bytes == other.bytes
393    }
394}
395
396impl Eq for Wtf8 {}
397
398impl fmt::Debug for Wtf8 {
399    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
400        write!(f, "{:?}", self.to_string_lossy())
401    }
402}
403
404/// An immutable string, stored on the GC heap.
405///
406/// The content is a [`Wtf8`]; the wrapper exists so a `Value` can hold a `Gc` handle rather
407/// than the bytes.
408pub struct JsString {
409    repr: Repr,
410    /// The code units, built on first use.
411    ///
412    /// Indexing is the one operation a script performs in a loop over a whole string —
413    /// `for (i = 0; i < s.length; i++) s.charCodeAt(i)` — and decoding from the start each
414    /// time would make that quadratic. Built once, it makes every later access `O(1)`.
415    /// Nothing here is a GC value, so the cache needs no tracing.
416    units: RefCell<Option<std::rc::Rc<Vec<u16>>>>,
417}
418
419/// How a string stores its content.
420///
421/// Flat is the common case and costs nothing extra; a rope is what makes repeated
422/// concatenation `O(1)` per append instead of a copy of the whole left side.
423enum Repr {
424    /// The bytes themselves.
425    Flat(Wtf8),
426    /// Two strings joined, with the lengths precomputed so `length` is `O(1)` without
427    /// flattening — which matters, because a loop that appends and then checks `.length`
428    /// must not flatten on every iteration.
429    Rope {
430        left: Gc<JsString>,
431        right: Gc<JsString>,
432        /// Byte length of `left` plus `right`.
433        bytes: usize,
434        /// UTF-16 length of `left` plus `right`.
435        units: usize,
436        /// Height of this subtree.
437        ///
438        /// Needed because a rope can grow into a list rather than a tree: `s = c + s` in a
439        /// loop puts every new character on the *left*, and the merge-into-the-right-child
440        /// trick above cannot help. Depth is what catches that, so the tree is flattened
441        /// before a read would recurse 100,000 frames deep.
442        depth: u16,
443        /// The flattened bytes, built once.
444        ///
445        /// `OnceCell`, not `RefCell<Option<_>>`: reads hand out `&Wtf8` (see
446        /// [`JsString::wtf8`]), and a `RefCell` borrow cannot outlive the accessor. A
447        /// `OnceCell` gives a reference tied to `&self` with no runtime flag, which is what
448        /// keeps every existing caller of `wtf8()`/`as_str()` unchanged.
449        flat: std::cell::OnceCell<Wtf8>,
450    },
451}
452
453/// Appending at most this many code units to a string of at most
454/// [`ROPE_SHORT2_LEN`] units concatenates flat; anything larger becomes a rope.
455///
456/// The reference's `JS_STRING_ROPE_SHORT_LEN` and `JS_STRING_ROPE_SHORT2_LEN`. Copied rather
457/// than derived, because the exact values are not load-bearing: what matters is that both
458/// thresholds exist and sit far below the sizes where copying starts to dominate.
459const ROPE_SHORT_LEN: usize = 512;
460const ROPE_SHORT2_LEN: usize = 8192;
461
462/// How deep a rope may get before it is flattened.
463///
464/// The reference rebalances at 60. Flattening is the simpler answer, and the bound has to be
465/// **much larger** than 60 for it to stay cheap: once a chain of appends stops finding room
466/// in a right child, every append adds a node, so the depth grows by one per append and a
467/// flatten costs the whole string. At 60 that is `O(n²/60)` — measured, 200,000 appends took
468/// 469 ms instead of 156 ms. At 2048 it is `O(n²/2048)`: 11 ms of copying, and the recursion
469/// depth is still bounded (2048 frames of a few dozen bytes).
470///
471/// The bound cannot be removed: without it the tree becomes a list, and reading it recurses
472/// once per character — upstream's `test_rope` prepends 100,000 times.
473const ROPE_MAX_DEPTH: u16 = 2048;
474
475/// The longest string this engine will build, which is the reference's
476/// `JS_STRING_LEN_MAX`. `text += text` in a loop is the program that reaches it, and the
477/// ceiling is what turns that into `InternalError: string too long` instead of an overflow.
478pub const JS_STRING_LEN_MAX: usize = (1 << 30) - 1;
479
480impl JsString {
481    /// Wrap `text`.
482    pub fn new(text: impl Into<String>) -> JsString {
483        JsString {
484            repr: Repr::Flat(Wtf8::new(text)),
485            units: RefCell::new(None),
486        }
487    }
488
489    /// Wrap WTF-8 that is already encoded.
490    pub fn from_wtf8(text: Wtf8) -> JsString {
491        JsString {
492            repr: Repr::Flat(text),
493            units: RefCell::new(None),
494        }
495    }
496
497    /// Join two strings, flat or as a rope.
498    ///
499    /// The policy is the reference's, and its second half is what keeps the tree shallow:
500    /// when the left side is already a rope whose right child is short, the new text goes
501    /// **into that child** instead of growing the spine. A loop of appends therefore sits at
502    /// depth two, not at depth n.
503    /// `None` when the result would exceed [`JS_STRING_LEN_MAX`], which is the reference's
504    /// `InternalError: string too long` — the ceiling exists so a doubling loop stops
505    /// instead of overflowing.
506    pub fn concat(
507        heap: &js_gc::Heap,
508        left: &Gc<JsString>,
509        right: &Gc<JsString>,
510    ) -> Option<JsString> {
511        // Appending nothing is the identity, and `x + ""` is a common shape.
512        if right.utf16_len() == 0 {
513            return Some(JsString::from_wtf8(left.flat().clone()));
514        }
515        if left.utf16_len() == 0 {
516            return Some(JsString::from_wtf8(right.flat().clone()));
517        }
518        if left.utf16_len() + right.utf16_len() > JS_STRING_LEN_MAX {
519            return None;
520        }
521        let short_append = right.utf16_len() <= ROPE_SHORT_LEN;
522        if short_append && left.utf16_len() <= ROPE_SHORT2_LEN {
523            return Some(JsString::from_wtf8(left.flat().concat(right.flat())));
524        }
525        // A rope whose right child can still absorb the new text **by copying**: merge there
526        // instead of growing the spine, so a chain of short appends stays at depth two.
527        //
528        // The `ROPE_SHORT_LEN` condition is load-bearing. Merging unconditionally rebuilds
529        // every node on the spine for each append — measured, 200,000 appends: 18 s against
530        // 156 ms. Merging only while the child is small costs one new node per append once
531        // the child is full, which the depth bound below then bounds.
532        if short_append
533            && let Repr::Rope {
534                left: outer_left,
535                right: last,
536                ..
537            } = &left.repr
538            && last.utf16_len() <= ROPE_SHORT_LEN
539        {
540            let merged = JsString::concat(heap, last, right)?;
541            return Some(JsString::rope(
542                heap,
543                outer_left.clone(),
544                Gc::new(heap, merged),
545            ));
546        }
547        // A tree taller than the bound is flattened rather than grown. This is what keeps
548        // left-deep accumulation (`s = c + s`) from becoming a linked list.
549        if left.depth().max(right.depth()) + 1 > ROPE_MAX_DEPTH {
550            return Some(JsString::from_wtf8(left.flat().concat(right.flat())));
551        }
552        Some(JsString::rope(heap, left.clone(), right.clone()))
553    }
554
555    fn rope(_heap: &js_gc::Heap, left: Gc<JsString>, right: Gc<JsString>) -> JsString {
556        let bytes = left.byte_len() + right.byte_len();
557        let units = left.utf16_len() + right.utf16_len();
558        let depth = left.depth().max(right.depth()) + 1;
559        JsString {
560            repr: Repr::Rope {
561                left,
562                right,
563                bytes,
564                units,
565                depth,
566                flat: std::cell::OnceCell::new(),
567            },
568            units: RefCell::new(None),
569        }
570    }
571
572    /// Height of this string's rope, 1 for a flat string.
573    fn depth(&self) -> u16 {
574        match &self.repr {
575            Repr::Flat(_) => 1,
576            Repr::Rope { depth, .. } => *depth,
577        }
578    }
579
580    /// The bytes, flattening a rope the first time and keeping the result.
581    fn flat(&self) -> &Wtf8 {
582        match &self.repr {
583            Repr::Flat(text) => text,
584            Repr::Rope { .. } => self.rope_flat(),
585        }
586    }
587
588    fn rope_flat(&self) -> &Wtf8 {
589        let Repr::Rope {
590            left,
591            right,
592            bytes,
593            flat,
594            ..
595        } = &self.repr
596        else {
597            unreachable!("only called for a rope")
598        };
599        flat.get_or_init(|| {
600            let mut out = Vec::with_capacity(*bytes);
601            left.append_flat_to(&mut out);
602            right.append_flat_to(&mut out);
603            let valid = left.flat().is_valid() && right.flat().is_valid();
604            Wtf8::from_parts(out, valid)
605        })
606    }
607
608    /// Append this string's bytes to `out`, flattening subtrees as it goes.
609    fn append_flat_to(&self, out: &mut Vec<u8>) {
610        match &self.repr {
611            Repr::Flat(text) => out.extend_from_slice(text.as_bytes()),
612            Repr::Rope { left, right, .. } => {
613                left.append_flat_to(out);
614                right.append_flat_to(out);
615            }
616        }
617    }
618
619    /// Byte length, without flattening.
620    pub fn byte_len(&self) -> usize {
621        match &self.repr {
622            Repr::Flat(text) => text.as_bytes().len(),
623            Repr::Rope { bytes, .. } => *bytes,
624        }
625    }
626
627    /// The code units, decoding once and remembering the result.
628    pub fn units_cached(&self) -> std::rc::Rc<Vec<u16>> {
629        if let Some(units) = self.units.borrow().as_ref() {
630            return units.clone();
631        }
632        let units = std::rc::Rc::new(self.flat().to_units());
633        *self.units.borrow_mut() = Some(units.clone());
634        units
635    }
636
637    /// The code unit at `index`, in `O(1)` once the cache is warm.
638    pub fn code_unit_at(&self, index: usize) -> Option<u16> {
639        self.units_cached().get(index).copied()
640    }
641
642    /// The string's bytes.
643    pub fn wtf8(&self) -> &Wtf8 {
644        self.flat()
645    }
646
647    /// The text, when it has no unpaired surrogate.
648    pub fn as_str(&self) -> Option<&str> {
649        self.flat().as_str()
650    }
651
652    /// The text with unpaired surrogates replaced by U+FFFD.
653    pub fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
654        self.flat().to_string_lossy()
655    }
656
657    /// The UTF-16 code units.
658    pub fn to_units(&self) -> Vec<u16> {
659        self.units_cached().as_ref().clone()
660    }
661
662    /// Length in UTF-16 code units, which is what `String.prototype.length` and
663    /// the string indexing rules count.
664    pub fn utf16_len(&self) -> usize {
665        // A rope knows its length without flattening, which is what keeps `s.length` in an
666        // append loop free. Flat strings compute it from the encoding, which is cheap and
667        // never builds the `u16` cache.
668        match &self.repr {
669            Repr::Flat(text) => text.utf16_len(),
670            Repr::Rope { units, .. } => *units,
671        }
672    }
673}
674
675impl Trace for JsString {
676    fn trace(&self, _tracer: &mut Tracer) {}
677
678    /// The encoded bytes, plus the `u16` cache once it has been built.
679    ///
680    /// The cache counts because it is not free: `s.charCodeAt(i)` over a long string builds
681    /// one `Rc<Vec<u16>>` of twice the byte length, and a script can make thousands of such
682    /// strings. Reporting only the bytes would let a `--memory-limit` run reach twice the
683    /// limit it asked for.
684    fn external_bytes(&self) -> usize {
685        let units = self
686            .units
687            .try_borrow()
688            .ok()
689            .and_then(|units| units.as_ref().map(|units| units.len() * 2))
690            .unwrap_or(0);
691        // Measured without flattening: a rope's leaves are separate boxes and are counted
692        // there, and this box owns only the flattened copy once one exists. Calling
693        // `flat()` here would allocate the full buffer of every rope just to weigh it.
694        let own = match &self.repr {
695            Repr::Flat(text) => text.as_bytes().len(),
696            Repr::Rope { flat, .. } => flat.get().map(|text| text.as_bytes().len()).unwrap_or(0),
697        };
698        own + units
699    }
700}
701
702impl fmt::Debug for JsString {
703    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
704        write!(f, "{:?}", self.flat())
705    }
706}
707
708/// A JavaScript symbol, stored on the GC heap.
709///
710/// A symbol is a *unique* property key that is not a string. Its identity is the
711/// allocation, not the description: `Symbol("a") !== Symbol("a")`, and two symbols with
712/// the same description still key two different properties. Only `Symbol.for` produces
713/// the same symbol twice, and it does so by looking the key up in the realm's registry
714/// rather than by comparing descriptions.
715pub struct JsSymbol {
716    /// The description shown by `Symbol.prototype.toString` and `description`.
717    ///
718    /// `Symbol()` and the well-known symbols have none, which is why this is an
719    /// `Option` and not an empty string — `Symbol().description` is `undefined`.
720    description: Option<String>,
721    /// The registry key, when the symbol came from `Symbol.for`.
722    ///
723    /// `Symbol.keyFor` answers `undefined` for every symbol without one, including the
724    /// well-known symbols, so the presence of this field is exactly what it tests.
725    registry_key: Option<String>,
726    /// Whether this is a *private* symbol, the key a class's `#x` property lives under.
727    ///
728    /// The reference marks these with `JS_ATOM_TYPE_PRIVATE` and keeps them out of every
729    /// enumeration path, which is what makes `#x` inaccessible from outside the class: the
730    /// property exists on the object, but nothing can name it. Two consequences that are
731    /// easy to get wrong — `Object.getOwnPropertySymbols` must not report it, and neither
732    /// must `Reflect.ownKeys`; and a private symbol can never equal a `Symbol()` the script
733    /// made, because there is no way to obtain one.
734    private: bool,
735}
736
737impl JsSymbol {
738    /// A unique symbol with `description`.
739    pub fn new(description: Option<String>) -> JsSymbol {
740        JsSymbol {
741            description,
742            registry_key: None,
743            private: false,
744        }
745    }
746
747    /// A private symbol: the key of a class's `#name` property.
748    ///
749    /// `JS_NewSymbolFromAtom(ctx, atom, JS_ATOM_TYPE_PRIVATE)`, where the atom is the
750    /// property name *including* its `#` — `JS_ATOM_hash_constructor` is the string
751    /// `"#constructor"`, which is how the reference rejects that name. The description is
752    /// therefore `#x`, and every message that prints this symbol gets the `#` for free.
753    pub fn new_private(name: &str) -> JsSymbol {
754        JsSymbol {
755            description: Some(name.to_string()),
756            registry_key: None,
757            private: true,
758        }
759    }
760
761    /// Whether this symbol is a class-private name.
762    pub fn is_private(&self) -> bool {
763        self.private
764    }
765
766    /// The registry entry for `key`, as `Symbol.for` returns it.
767    pub fn registered(key: String) -> JsSymbol {
768        JsSymbol {
769            description: Some(key.clone()),
770            registry_key: Some(key),
771            private: false,
772        }
773    }
774
775    /// The description, if there is one.
776    /// A stable number for this symbol's identity, for hashing.
777    ///
778    /// A symbol's identity *is* its allocation — `Symbol("a")` and `Symbol("a")` are two
779    /// different keys — so the address is the right hash, and it is only ever hashed.
780    #[must_use]
781    pub fn identity(&self) -> usize {
782        self as *const JsSymbol as usize
783    }
784
785    /// The description shown by `Symbol.prototype.description` and `toString`.
786    #[must_use]
787    pub fn description(&self) -> Option<&str> {
788        self.description.as_deref()
789    }
790
791    /// The registry key, if this symbol came from `Symbol.for`.
792    pub fn registry_key(&self) -> Option<&str> {
793        self.registry_key.as_deref()
794    }
795
796    /// `Symbol.prototype.toString`: `Symbol(description)`.
797    ///
798    /// A description is inserted verbatim, so `Symbol("a)b").toString()` is
799    /// `Symbol(a)b)` — the spec does not escape it.
800    pub fn to_display_string(&self) -> String {
801        match &self.description {
802            Some(text) => format!("Symbol({text})"),
803            None => "Symbol()".to_string(),
804        }
805    }
806}
807
808impl Trace for JsSymbol {
809    fn trace(&self, _tracer: &mut Tracer) {}
810}
811
812impl fmt::Debug for JsSymbol {
813    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
814        write!(f, "{}", self.to_display_string())
815    }
816}
817
818/// A mutable binding cell, shared between closures.
819///
820/// A variable that a closure captures cannot live in a stack slot, because the
821/// slot dies with the frame while the closure outlives it. The compiler marks such
822/// bindings `is_captured` and counts them in `var_ref_count`; the interpreter
823/// allocates one of these per captured binding on entry, and every access — from
824/// the owning frame or from any closure — goes through the cell.
825pub struct Cell {
826    value: RefCell<Value>,
827}
828
829impl Cell {
830    /// A cell holding `value`.
831    pub fn new(value: Value) -> Cell {
832        Cell {
833            value: RefCell::new(value),
834        }
835    }
836
837    /// Read the cell.
838    pub fn get(&self) -> Value {
839        self.value.borrow().clone()
840    }
841
842    /// Overwrite the cell.
843    pub fn set(&self, value: Value) {
844        *self.value.borrow_mut() = value;
845    }
846}
847
848impl Trace for Cell {
849    fn trace(&self, tracer: &mut Tracer) {
850        self.value.borrow().trace(tracer);
851    }
852}
853
854/// A JavaScript value.
855#[derive(Clone)]
856pub enum Value {
857    /// `undefined`
858    Undefined,
859    /// `null`
860    Null,
861    /// `true` / `false`
862    Bool(bool),
863    /// A 32-bit integer, exact.
864    Int(i32),
865    /// A double.
866    Float(f64),
867    /// A string.
868    String(Gc<JsString>),
869    /// An object, function, or array.
870    Object(Gc<JsObject>),
871    /// A symbol: a unique property key that is not a string.
872    Symbol(Gc<JsSymbol>),
873    /// A `BigInt`: an integer of any size, stored on the GC heap.
874    ///
875    /// A separate variant rather than a number because the two never mix: `1n + 1` is a
876    /// `TypeError`, and `1n === 1` is false.
877    BigInt(Gc<crate::bigint::BigInt>),
878    /// A try-handler target, pushed by `catch` and scanned for when an exception
879    /// is raised.
880    ///
881    /// QuickJS keeps this on the value stack as a `JS_TAG_CATCH_OFFSET` value and
882    /// finds the innermost handler by walking the stack downwards, which is how
883    /// `try` needs no separate table. Offset `0` marks an enumerator (a `for-of`
884    /// loop) rather than a `catch`: it closes the iterator and keeps unwinding.
885    CatchOffset(u32),
886    /// A `gosub` return position.
887    ///
888    /// `finally` blocks are compiled as subroutines: `gosub` pushes the address to
889    /// come back to and jumps into the block, `ret` pops the address and jumps
890    /// back. QuickJS reuses the integer tag for this (and notes it as a hardening
891    /// gap); a distinct variant keeps it out of reach of arithmetic.
892    ReturnAddress(u32),
893    /// An array hole: an index that was skipped rather than filled.
894    ///
895    /// `[1,,3]` and `[1,undefined,3]` are different arrays: `forEach` skips the hole,
896    /// `in` reports it absent, and the debug printer shows `<1 empty item>`. That
897    /// distinction has to live in the element vector, and this is the marker for it.
898    /// It is never observable from JavaScript: reading the index yields `undefined`
899    /// and no language operation can produce it.
900    Hole,
901    /// The internal marker a `let`/`const` binding holds between its scope being
902    /// entered and its initialiser running.
903    ///
904    /// QuickJS calls this `JS_UNINITIALIZED`; it is deliberately not observable
905    /// from JavaScript. It only ever sits in a slot or a cell, and every read that
906    /// may see it (`get_loc_check` and friends) turns it into a `ReferenceError`.
907    Uninitialized,
908}
909
910impl Value {
911    /// A string value on `heap`.
912    pub fn string(heap: &js_gc::Heap, text: impl Into<String>) -> Value {
913        Value::String(Gc::new(heap, JsString::new(text)))
914    }
915
916    /// A string from bytes that are already WTF-8, which is how a string containing an
917    /// unpaired surrogate reaches a `Value`.
918    pub fn string_wtf8(heap: &js_gc::Heap, text: Wtf8) -> Value {
919        Value::String(Gc::new(heap, JsString::from_wtf8(text)))
920    }
921
922    /// The number as a double, widening an [`Value::Int`].
923    pub fn as_f64(&self) -> Option<f64> {
924        match self {
925            Value::Int(i) => Some(*i as f64),
926            Value::Float(f) => Some(*f),
927            _ => None,
928        }
929    }
930
931    /// The value as a string, if it is one with no unpaired surrogate.
932    pub fn as_str(&self) -> Option<&str> {
933        match self {
934            Value::String(s) => s.as_str(),
935            _ => None,
936        }
937    }
938
939    /// The value's string content as WTF-8, which covers every string including one with an
940    /// unpaired surrogate.
941    pub fn as_wtf8(&self) -> Option<&Wtf8> {
942        match self {
943            Value::String(s) => Some(s.wtf8()),
944            _ => None,
945        }
946    }
947
948    /// The symbol, if this is one.
949    pub fn as_symbol(&self) -> Option<&Gc<JsSymbol>> {
950        match self {
951            Value::Symbol(symbol) => Some(symbol),
952            _ => None,
953        }
954    }
955
956    /// The object, if this is one.
957    pub fn as_object(&self) -> Option<&Gc<JsObject>> {
958        match self {
959            Value::Object(o) => Some(o),
960            _ => None,
961        }
962    }
963
964    /// Whether this is one of the two null-ish values.
965    pub fn is_nullish(&self) -> bool {
966        matches!(self, Value::Undefined | Value::Null)
967    }
968
969    /// `typeof value`.
970    pub fn type_of(&self) -> &'static str {
971        match self {
972            Value::Undefined => "undefined",
973            Value::Null => "object",
974            Value::Bool(_) => "boolean",
975            Value::Int(_) | Value::Float(_) => "number",
976            Value::String(_) => "string",
977            Value::Symbol(_) => "symbol",
978            Value::BigInt(_) => "bigint",
979            Value::Object(object) => {
980                if object.is_callable() {
981                    "function"
982                } else {
983                    "object"
984                }
985            }
986            // The internal markers are never observable from JavaScript;
987            // reporting `undefined` keeps the answer honest if a bug lets one leak.
988            Value::Uninitialized
989            | Value::Hole
990            | Value::CatchOffset(_)
991            | Value::ReturnAddress(_) => "undefined",
992        }
993    }
994
995    /// `ToBoolean`, which is also what a conditional jump tests.
996    pub fn to_boolean(&self) -> bool {
997        match self {
998            Value::Undefined | Value::Null => false,
999            Value::Bool(b) => *b,
1000            Value::Int(i) => *i != 0,
1001            // `NaN` is falsy, and so is `-0`.
1002            Value::Float(f) => *f != 0.0 && !f.is_nan(),
1003            Value::String(s) => !s.wtf8().is_empty(),
1004            // Every symbol is truthy, even the one with no description.
1005            Value::Symbol(_) => true,
1006            // A bigint follows the numbers: `0n` is falsy and every other width is truthy.
1007            // Saying "every bigint is truthy" turned `if (b & 1n)` into an unconditional
1008            // branch, which quietly corrupted every bigint algorithm that tests a bit.
1009            Value::BigInt(big) => !big.is_zero(),
1010            // Every object is truthy, including `new Boolean(false)`.
1011            Value::Object(_) => true,
1012            Value::Uninitialized
1013            | Value::Hole
1014            | Value::CatchOffset(_)
1015            | Value::ReturnAddress(_) => false,
1016        }
1017    }
1018
1019    /// `ToNumber`, for the arithmetic operators.
1020    pub fn to_number(&self) -> f64 {
1021        match self {
1022            Value::Undefined => f64::NAN,
1023            Value::Null => 0.0,
1024            Value::Bool(b) => {
1025                if *b {
1026                    1.0
1027                } else {
1028                    0.0
1029                }
1030            }
1031            Value::Int(i) => *i as f64,
1032            Value::Float(f) => *f,
1033            Value::String(s) => string_to_number(&s.to_string_lossy()),
1034            // `ToNumber` of a symbol or a bigint is a `TypeError`; `NaN` keeps this
1035            // infallible helper total, and the operators reject them first.
1036            Value::Symbol(_) => f64::NAN,
1037            Value::BigInt(_) => f64::NAN,
1038            // `ToNumber` of an object runs `ToPrimitive` first, which needs the
1039            // value-of/valueOf machinery; until that lands an object is `NaN`
1040            // rather than a panic.
1041            Value::Object(_) => f64::NAN,
1042            Value::Uninitialized
1043            | Value::Hole
1044            | Value::CatchOffset(_)
1045            | Value::ReturnAddress(_) => f64::NAN,
1046        }
1047    }
1048
1049    /// `ToInt32`, the conversion the bitwise operators and `<<`/`>>`/`>>>` use.
1050    pub fn to_int32(&self) -> i32 {
1051        to_int32(self.to_number())
1052    }
1053
1054    /// `ToUint32`.
1055    pub fn to_uint32(&self) -> u32 {
1056        self.to_int32() as u32
1057    }
1058
1059    /// `ToString`.
1060    ///
1061    /// Named `to_js_string` rather than `to_string` so it does not shadow
1062    /// [`std::fmt::Display`]: the two disagree on purpose (`display` keeps the sign
1063    /// of `-0`), and an accidental `to_string` on a `Value` would silently pick the
1064    /// wrong one.
1065    pub fn to_js_string(&self) -> String {
1066        match self {
1067            Value::Undefined => "undefined".to_string(),
1068            Value::Null => "null".to_string(),
1069            Value::Bool(true) => "true".to_string(),
1070            Value::Bool(false) => "false".to_string(),
1071            Value::Int(i) => i.to_string(),
1072            Value::Float(f) => number_to_string(*f),
1073            // Lossy only for a string with an unpaired surrogate, which has no `&str`
1074            // form at all; every other string borrows and copies nothing extra.
1075            Value::String(s) => s.to_string_lossy().into_owned(),
1076            Value::BigInt(big) => big.to_decimal_string(),
1077            // `ToString` of a symbol is a `TypeError`; this descriptive form is what
1078            // `String(sym)` and the error messages use. Callers that must throw go
1079            // through `Interp::checked_to_string`.
1080            Value::Symbol(s) => s.to_display_string(),
1081            Value::Object(_) => "[object Object]".to_string(),
1082            Value::Uninitialized
1083            | Value::Hole
1084            | Value::CatchOffset(_)
1085            | Value::ReturnAddress(_) => "undefined".to_string(),
1086        }
1087    }
1088
1089    /// `===`.
1090    pub fn strict_equals(&self, other: &Value) -> bool {
1091        match (self, other) {
1092            (Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => true,
1093            (Value::Bool(a), Value::Bool(b)) => a == b,
1094            // `Int` and `Float` are the same type to JavaScript, so `1 === 1.0`.
1095            (Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) => {
1096                let (a, b) = (self.to_number(), other.to_number());
1097                a == b
1098            }
1099            (Value::String(a), Value::String(b)) => a.as_str() == b.as_str(),
1100            // Two bigints compare by value, because the representation is canonical —
1101            // `2n ** 1000n` computed twice is one value, not two handles.
1102            (Value::BigInt(a), Value::BigInt(b)) => **a == **b,
1103            // A symbol is equal only to itself: the same description means nothing.
1104            (Value::Symbol(a), Value::Symbol(b)) => a.ptr_eq(b),
1105            // Objects compare by identity, never structurally.
1106            (Value::Object(a), Value::Object(b)) => a.ptr_eq(b),
1107            _ => false,
1108        }
1109    }
1110
1111    /// `SameValue`, the equality `Object.is` uses and a proxy invariant needs.
1112    ///
1113    /// It is [`Value::same_value_zero`] plus the one extra distinction: `+0` and `-0`
1114    /// are different values here, which is what makes `Object.is(0, -0)` false.
1115    pub fn same_value(&self, other: &Value) -> bool {
1116        if let (Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) = (self, other) {
1117            let (a, b) = (self.to_number(), other.to_number());
1118            if a.is_nan() && b.is_nan() {
1119                return true;
1120            }
1121            if a == 0.0 && b == 0.0 {
1122                return a.is_sign_negative() == b.is_sign_negative();
1123            }
1124            return a == b;
1125        }
1126        self.strict_equals(other)
1127    }
1128
1129    /// `SameValueZero`, the equality a `Map` key and a `Set` element use.
1130    ///
1131    /// It differs from `===` in exactly one place: `NaN` equals itself. That is what makes
1132    /// `map.set(NaN, 1); map.get(NaN)` work, and it is why a `Map` cannot use `strict_equals`
1133    /// directly. A bigint compares by value, since its representation is canonical.
1134    pub fn same_value_zero(&self, other: &Value) -> bool {
1135        if let (Value::Float(a), Value::Float(b)) = (self, other)
1136            && a.is_nan()
1137            && b.is_nan()
1138        {
1139            return true;
1140        }
1141        self.strict_equals(other)
1142    }
1143
1144    /// `==`, with the coercion rules.
1145    ///
1146    /// `NaN` compares unequal to everything including itself, which the numeric
1147    /// branch already gets right. An object compares by identity against another
1148    /// object and by its primitive form against a primitive.
1149    pub fn loose_equals(&self, other: &Value) -> bool {
1150        if matches!(self, Value::Object(_)) || matches!(other, Value::Object(_)) {
1151            return match (self, other) {
1152                (Value::Object(a), Value::Object(b)) => a.ptr_eq(b),
1153                _ => primitive_loose_equals(&self.primitive(), &other.primitive()),
1154            };
1155        }
1156        match (self, other) {
1157            (Value::Undefined | Value::Null, Value::Undefined | Value::Null) => true,
1158            (Value::Undefined | Value::Null, _) | (_, Value::Undefined | Value::Null) => false,
1159            (Value::String(a), Value::String(b)) => a.as_str() == b.as_str(),
1160            (Value::Symbol(a), Value::Symbol(b)) => a.ptr_eq(b),
1161            (Value::Bool(a), Value::Bool(b)) => a == b,
1162            // A bigint equals another bigint by value, a string that spells it exactly, or a
1163            // number with the same mathematical value — that last one is why `1n == 1` is
1164            // true while `1n === 1` is false.
1165            (Value::BigInt(a), Value::BigInt(b)) => **a == **b,
1166            (Value::BigInt(a), Value::String(b)) | (Value::String(b), Value::BigInt(a)) => {
1167                crate::bigint::BigInt::from_string(&b.to_string_lossy()).as_ref() == Some(&**a)
1168            }
1169            (Value::BigInt(a), other) => match other {
1170                Value::Int(_) | Value::Float(_) => bigint_equals_number(a, other.to_number()),
1171                // A boolean is `ToNumber`ed first, so `true == 1n` is true.
1172                Value::Bool(flag) => bigint_equals_number(a, if *flag { 1.0 } else { 0.0 }),
1173                _ => false,
1174            },
1175            (other, Value::BigInt(b)) => match other {
1176                Value::Int(_) | Value::Float(_) => bigint_equals_number(b, other.to_number()),
1177                Value::Bool(flag) => bigint_equals_number(b, if *flag { 1.0 } else { 0.0 }),
1178                _ => false,
1179            },
1180            // Everything else compares numerically, which covers `"1" == 1`,
1181            // `true == 1` and `Int` against `Float`.
1182            _ => self.to_number() == other.to_number(),
1183        }
1184    }
1185
1186    /// `ToPrimitive` with no hint.
1187    ///
1188    /// The result is an owned [`Primitive`] rather than a [`Value`] because a
1189    /// string `Value` needs a heap handle and this path deliberately has none.
1190    fn primitive(&self) -> Primitive {
1191        match self {
1192            Value::Undefined => Primitive::Undefined,
1193            Value::Null => Primitive::Null,
1194            Value::Bool(b) => Primitive::Bool(*b),
1195            Value::Int(i) => Primitive::Number(*i as f64),
1196            Value::Float(f) => Primitive::Number(*f),
1197            Value::String(s) => Primitive::String(s.to_string_lossy().into_owned()),
1198            // A symbol stays distinct from a string here so `==` does not treat it as
1199            // one; only an object's `ToPrimitive` can produce a symbol from an object.
1200            Value::Symbol(s) => Primitive::Symbol(s.clone()),
1201            // A bigint reaches `Primitive` as its decimal text, which is enough for the
1202            // loose comparisons that go through here; the operators reject it first.
1203            Value::BigInt(big) => Primitive::String(big.to_decimal_string()),
1204            Value::Object(_) => Primitive::String(self.to_js_string()),
1205            Value::Uninitialized
1206            | Value::Hole
1207            | Value::CatchOffset(_)
1208            | Value::ReturnAddress(_) => Primitive::Undefined,
1209        }
1210    }
1211}
1212
1213/// A value with no object identity, used by [`Value::loose_equals`].
1214enum Primitive {
1215    Undefined,
1216    Null,
1217    Bool(bool),
1218    Number(f64),
1219    String(String),
1220    /// A symbol, which is a primitive but compares by identity.
1221    Symbol(Gc<JsSymbol>),
1222}
1223
1224/// `==` once both sides are primitives.
1225fn primitive_loose_equals(left: &Primitive, right: &Primitive) -> bool {
1226    use Primitive::*;
1227    match (left, right) {
1228        (Undefined | Null, Undefined | Null) => true,
1229        (Undefined | Null, _) | (_, Undefined | Null) => false,
1230        // A symbol is a primitive, so `==` on two symbols is identity. Against
1231        // anything else it is `false` — the only coercion that could apply is boxing,
1232        // and `Object(Symbol())` is an object, not a `Primitive`.
1233        (Symbol(a), Symbol(b)) => a.ptr_eq(b),
1234        (Symbol(_), _) | (_, Symbol(_)) => false,
1235        (String(a), String(b)) => a == b,
1236        (Bool(a), Bool(b)) => a == b,
1237        (Number(a), Number(b)) => a == b,
1238        // A string against a number compares numerically, so `"" == 0` and
1239        // `"1" == 1`.
1240        (String(s), Number(n)) | (Number(n), String(s)) => string_to_number(s) == *n,
1241        (Bool(b), Number(n)) | (Number(n), Bool(b)) => (if *b { 1.0 } else { 0.0 }) == *n,
1242        (Bool(b), String(s)) | (String(s), Bool(b)) => {
1243            string_to_number(s) == (if *b { 1.0 } else { 0.0 })
1244        }
1245    }
1246}
1247
1248/// `bigint == number`, compared as whole numbers rather than through the double.
1249///
1250/// Going through `to_f64` made `100000000000000000001n == 1e20` true, because the double
1251/// rounds both sides onto the same value; the spec compares the exact integers, and a
1252/// double that is already an integer converts to one exactly.
1253fn bigint_equals_number(big: &crate::bigint::BigInt, number: f64) -> bool {
1254    number.is_finite()
1255        && number.fract() == 0.0
1256        && crate::bigint::BigInt::from_f64_truncated(number) == *big
1257}
1258
1259/// `ToInt32`.
1260///
1261/// The spec's modulo-2^32 arithmetic: `NaN` and the infinities become zero, and
1262/// the fractional part is dropped toward zero before the wrap.
1263pub fn to_int32(value: f64) -> i32 {
1264    if !value.is_finite() || value == 0.0 {
1265        return 0;
1266    }
1267    let truncated = value.trunc();
1268    let modulo = truncated.rem_euclid(4294967296.0);
1269    let wrapped = if modulo >= 2147483648.0 {
1270        modulo - 4294967296.0
1271    } else {
1272        modulo
1273    };
1274    wrapped as i32
1275}
1276
1277/// `ToNumber` applied to a string.
1278///
1279/// Leading and trailing whitespace is allowed; anything else must be a valid
1280/// numeric literal, because a failed parse is `NaN` rather than a prefix match.
1281/// The empty string is `0`, which is a common source of surprise.
1282pub fn string_to_number(text: &str) -> f64 {
1283    let trimmed = text.trim();
1284    if trimmed.is_empty() {
1285        return 0.0;
1286    }
1287    if let Some(rest) = strip_radix_prefix(trimmed, "0x", "0X") {
1288        return radix_number(rest, 16);
1289    }
1290    if let Some(rest) = strip_radix_prefix(trimmed, "0o", "0O") {
1291        return radix_number(rest, 8);
1292    }
1293    if let Some(rest) = strip_radix_prefix(trimmed, "0b", "0B") {
1294        return radix_number(rest, 2);
1295    }
1296    let (sign, digits) = match trimmed.strip_prefix(['+', '-']) {
1297        Some(rest) => (&trimmed[..1], rest),
1298        None => ("", trimmed),
1299    };
1300    // `Infinity` is a literal; `inf`/`nan` are not, even though Rust parses them.
1301    if digits == "Infinity" {
1302        return if sign == "-" {
1303            f64::NEG_INFINITY
1304        } else {
1305            f64::INFINITY
1306        };
1307    }
1308    // Rust's parser accepts the literals JavaScript does not, so the shape is
1309    // checked before trusting it: digits with at most one dot, at most one
1310    // exponent, and no trailing garbage.
1311    if !is_decimal_literal(digits) {
1312        return f64::NAN;
1313    }
1314    trimmed.parse::<f64>().unwrap_or(f64::NAN)
1315}
1316
1317fn strip_radix_prefix<'a>(text: &'a str, lower: &str, upper: &str) -> Option<&'a str> {
1318    text.strip_prefix(lower)
1319        .or_else(|| text.strip_prefix(upper))
1320}
1321
1322fn radix_number(digits: &str, radix: u32) -> f64 {
1323    if digits.is_empty() || !digits.chars().all(|c| c.is_digit(radix)) {
1324        return f64::NAN;
1325    }
1326    // A long literal overflows `u64`; JavaScript then rounds, so fall back to an
1327    // accumulating double rather than reporting `NaN`.
1328    match u64::from_str_radix(digits, radix) {
1329        Ok(value) => value as f64,
1330        Err(_) => digits.chars().fold(0.0, |acc, c| {
1331            acc * radix as f64 + c.to_digit(radix).unwrap_or(0) as f64
1332        }),
1333    }
1334}
1335
1336/// Whether `text` is a decimal literal with no sign.
1337fn is_decimal_literal(text: &str) -> bool {
1338    let bytes = text.as_bytes();
1339    let mut index = 0;
1340    let mut digits = 0;
1341    while index < bytes.len() && bytes[index].is_ascii_digit() {
1342        index += 1;
1343        digits += 1;
1344    }
1345    if index < bytes.len() && bytes[index] == b'.' {
1346        index += 1;
1347        while index < bytes.len() && bytes[index].is_ascii_digit() {
1348            index += 1;
1349            digits += 1;
1350        }
1351    }
1352    if digits == 0 {
1353        return false;
1354    }
1355    if index < bytes.len() && (bytes[index] == b'e' || bytes[index] == b'E') {
1356        index += 1;
1357        if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
1358            index += 1;
1359        }
1360        let start = index;
1361        while index < bytes.len() && bytes[index].is_ascii_digit() {
1362            index += 1;
1363        }
1364        if index == start {
1365            return false;
1366        }
1367    }
1368    index == bytes.len()
1369}
1370
1371/// `ToString` applied to a number.
1372///
1373/// The thresholds are the ones the spec's `Number::toString` uses: exponential
1374/// form below `1e-6` and from `1e21` up, decimal form in between. Within the
1375/// decimal range Rust's shortest-round-trip formatter already agrees with
1376/// JavaScript digit for digit — including the notorious `0.30000000000000004` —
1377/// so only the exponent spelling has to be normalised.
1378pub fn number_to_string(value: f64) -> String {
1379    if value.is_nan() {
1380        return "NaN".to_string();
1381    }
1382    if value.is_infinite() {
1383        return if value > 0.0 {
1384            "Infinity".to_string()
1385        } else {
1386            "-Infinity".to_string()
1387        };
1388    }
1389    if value == 0.0 {
1390        // `ToString(-0)` is `"0"`; `print(-0)` is a different question, see
1391        // [`number_to_string_for_print`].
1392        return "0".to_string();
1393    }
1394    let magnitude = value.abs();
1395    if magnitude >= 1e21 || magnitude < 1e-6 {
1396        return normalise_exponent(format!("{value:e}"));
1397    }
1398    format!("{value}")
1399}
1400
1401/// `ToString` as the engine's `print` applies it, which differs from the language
1402/// one for negative zero.
1403///
1404/// `print(-0)` prints `-0` in QuickJS while `String(-0)` is `"0"`, because the host
1405/// printer takes the number's own spelling. Reproduced here so byte-for-byte output
1406/// comparisons do not trip over it.
1407pub fn number_to_string_for_print(value: f64) -> String {
1408    if value == 0.0 && value.is_sign_negative() {
1409        return "-0".to_string();
1410    }
1411    number_to_string(value)
1412}
1413
1414/// Rewrite Rust's exponent spelling as JavaScript's: always signed, never padded.
1415///
1416/// Rust writes `1e-7` and `1e21`; JavaScript writes `1e-7` and `1e+21`. The
1417/// difference is only the explicit `+`.
1418fn normalise_exponent(text: String) -> String {
1419    let Some((mantissa, exponent)) = text.split_once('e') else {
1420        return text;
1421    };
1422    if exponent.starts_with('-') {
1423        text
1424    } else {
1425        let digits = exponent.strip_prefix('+').unwrap_or(exponent);
1426        format!("{mantissa}e+{digits}")
1427    }
1428}
1429
1430impl Trace for Value {
1431    fn trace(&self, tracer: &mut Tracer) {
1432        match self {
1433            Value::String(s) => tracer.visit(s),
1434            Value::Object(o) => tracer.visit(o),
1435            Value::Symbol(s) => tracer.visit(s),
1436            _ => {}
1437        }
1438    }
1439}
1440
1441impl fmt::Debug for Value {
1442    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1443        match self {
1444            Value::Undefined => f.write_str("undefined"),
1445            Value::Null => f.write_str("null"),
1446            Value::Bool(b) => write!(f, "{b}"),
1447            Value::Int(i) => write!(f, "{i}"),
1448            Value::Float(x) => write!(f, "{}", number_to_string(*x)),
1449            Value::String(s) => write!(f, "{:?}", s.as_str()),
1450            Value::Object(_) => f.write_str("[object]"),
1451            Value::Symbol(s) => f.write_str(&s.to_display_string()),
1452            Value::BigInt(big) => write!(f, "{}n", big.to_decimal_string()),
1453            Value::Uninitialized => f.write_str("<uninitialised>"),
1454            Value::Hole => f.write_str("<hole>"),
1455            Value::CatchOffset(offset) => write!(f, "<catch {offset}>"),
1456            Value::ReturnAddress(address) => write!(f, "<ret {address}>"),
1457        }
1458    }
1459}
1460
1461#[cfg(test)]
1462mod tests {
1463    use super::*;
1464
1465    #[test]
1466    fn int32_wraps_the_way_the_spec_says() {
1467        assert_eq!(to_int32(0.0), 0);
1468        assert_eq!(to_int32(f64::NAN), 0);
1469        assert_eq!(to_int32(f64::INFINITY), 0);
1470        assert_eq!(to_int32(1.9), 1);
1471        assert_eq!(to_int32(-1.9), -1);
1472        assert_eq!(to_int32(2147483648.0), -2147483648);
1473        assert_eq!(to_int32(4294967296.0), 0);
1474        assert_eq!(to_int32(-4294967297.0), -1);
1475    }
1476
1477    #[test]
1478    fn numbers_print_like_javascript() {
1479        assert_eq!(number_to_string(0.0), "0");
1480        assert_eq!(number_to_string(-0.0), "0");
1481        assert_eq!(number_to_string(1.0), "1");
1482        assert_eq!(number_to_string(-1.5), "-1.5");
1483        assert_eq!(number_to_string(1e21), "1e+21");
1484        assert_eq!(number_to_string(1e-7), "1e-7");
1485        assert_eq!(number_to_string(1e-6), "0.000001");
1486        assert_eq!(number_to_string(1e20), "100000000000000000000");
1487        assert_eq!(number_to_string(5e-324), "5e-324");
1488        // `print(-0)` differs from `String(-0)`.
1489        assert_eq!(number_to_string_for_print(-0.0), "-0");
1490        assert_eq!(number_to_string(f64::NAN), "NaN");
1491        assert_eq!(number_to_string(f64::INFINITY), "Infinity");
1492        assert_eq!(number_to_string(f64::NEG_INFINITY), "-Infinity");
1493    }
1494
1495    #[test]
1496    fn strings_parse_to_numbers_without_prefix_matching() {
1497        assert_eq!(string_to_number(""), 0.0);
1498        assert_eq!(string_to_number("  "), 0.0);
1499        assert_eq!(string_to_number(" 42 "), 42.0);
1500        assert_eq!(string_to_number("0x10"), 16.0);
1501        assert_eq!(string_to_number("0b101"), 5.0);
1502        assert_eq!(string_to_number("0o17"), 15.0);
1503        assert_eq!(string_to_number("Infinity"), f64::INFINITY);
1504        assert_eq!(string_to_number("-Infinity"), f64::NEG_INFINITY);
1505        assert_eq!(string_to_number("1e3"), 1000.0);
1506        assert_eq!(string_to_number(".5"), 0.5);
1507        assert_eq!(string_to_number("5."), 5.0);
1508        // These would all be prefix matches or Rust-only spellings.
1509        assert!(string_to_number("12px").is_nan());
1510        assert!(string_to_number("inf").is_nan());
1511        assert!(string_to_number("nan").is_nan());
1512        assert!(string_to_number("1e").is_nan());
1513        assert!(string_to_number("0x").is_nan());
1514    }
1515
1516    #[test]
1517    fn strict_equality_ignores_the_int_float_split() {
1518        assert!(Value::Int(1).strict_equals(&Value::Float(1.0)));
1519        assert!(!Value::Int(1).strict_equals(&Value::Float(1.5)));
1520        assert!(!Value::Float(f64::NAN).strict_equals(&Value::Float(f64::NAN)));
1521        assert!(Value::Int(0).strict_equals(&Value::Float(-0.0)));
1522        assert!(!Value::Int(0).strict_equals(&Value::Null));
1523        assert!(!Value::Undefined.strict_equals(&Value::Null));
1524    }
1525
1526    #[test]
1527    fn falsy_values_are_the_spec_list() {
1528        assert!(!Value::Undefined.to_boolean());
1529        assert!(!Value::Null.to_boolean());
1530        assert!(!Value::Bool(false).to_boolean());
1531        assert!(!Value::Int(0).to_boolean());
1532        assert!(!Value::Float(f64::NAN).to_boolean());
1533        assert!(!Value::Float(-0.0).to_boolean());
1534        assert!(Value::Float(0.1).to_boolean());
1535    }
1536}