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