Skip to main content

quickjs/
value.rs

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