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}
470
471impl JsSymbol {
472    /// A unique symbol with `description`.
473    pub fn new(description: Option<String>) -> JsSymbol {
474        JsSymbol {
475            description,
476            registry_key: None,
477        }
478    }
479
480    /// The registry entry for `key`, as `Symbol.for` returns it.
481    pub fn registered(key: String) -> JsSymbol {
482        JsSymbol {
483            description: Some(key.clone()),
484            registry_key: Some(key),
485        }
486    }
487
488    /// The description, if there is one.
489    pub fn description(&self) -> Option<&str> {
490        self.description.as_deref()
491    }
492
493    /// The registry key, if this symbol came from `Symbol.for`.
494    pub fn registry_key(&self) -> Option<&str> {
495        self.registry_key.as_deref()
496    }
497
498    /// `Symbol.prototype.toString`: `Symbol(description)`.
499    ///
500    /// A description is inserted verbatim, so `Symbol("a)b").toString()` is
501    /// `Symbol(a)b)` — the spec does not escape it.
502    pub fn to_display_string(&self) -> String {
503        match &self.description {
504            Some(text) => format!("Symbol({text})"),
505            None => "Symbol()".to_string(),
506        }
507    }
508}
509
510impl Trace for JsSymbol {
511    fn trace(&self, _tracer: &mut Tracer) {}
512}
513
514impl fmt::Debug for JsSymbol {
515    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
516        write!(f, "{}", self.to_display_string())
517    }
518}
519
520/// A mutable binding cell, shared between closures.
521///
522/// A variable that a closure captures cannot live in a stack slot, because the
523/// slot dies with the frame while the closure outlives it. The compiler marks such
524/// bindings `is_captured` and counts them in `var_ref_count`; the interpreter
525/// allocates one of these per captured binding on entry, and every access — from
526/// the owning frame or from any closure — goes through the cell.
527pub struct Cell {
528    value: RefCell<Value>,
529}
530
531impl Cell {
532    /// A cell holding `value`.
533    pub fn new(value: Value) -> Cell {
534        Cell {
535            value: RefCell::new(value),
536        }
537    }
538
539    /// Read the cell.
540    pub fn get(&self) -> Value {
541        self.value.borrow().clone()
542    }
543
544    /// Overwrite the cell.
545    pub fn set(&self, value: Value) {
546        *self.value.borrow_mut() = value;
547    }
548}
549
550impl Trace for Cell {
551    fn trace(&self, tracer: &mut Tracer) {
552        self.value.borrow().trace(tracer);
553    }
554}
555
556/// A JavaScript value.
557#[derive(Clone)]
558pub enum Value {
559    /// `undefined`
560    Undefined,
561    /// `null`
562    Null,
563    /// `true` / `false`
564    Bool(bool),
565    /// A 32-bit integer, exact.
566    Int(i32),
567    /// A double.
568    Float(f64),
569    /// A string.
570    String(Gc<JsString>),
571    /// An object, function, or array.
572    Object(Gc<JsObject>),
573    /// A symbol: a unique property key that is not a string.
574    Symbol(Gc<JsSymbol>),
575    /// A `BigInt`: an integer of any size, stored on the GC heap.
576    ///
577    /// A separate variant rather than a number because the two never mix: `1n + 1` is a
578    /// `TypeError`, and `1n === 1` is false.
579    BigInt(Gc<crate::bigint::BigInt>),
580    /// A try-handler target, pushed by `catch` and scanned for when an exception
581    /// is raised.
582    ///
583    /// QuickJS keeps this on the value stack as a `JS_TAG_CATCH_OFFSET` value and
584    /// finds the innermost handler by walking the stack downwards, which is how
585    /// `try` needs no separate table. Offset `0` marks an enumerator (a `for-of`
586    /// loop) rather than a `catch`: it closes the iterator and keeps unwinding.
587    CatchOffset(u32),
588    /// A `gosub` return position.
589    ///
590    /// `finally` blocks are compiled as subroutines: `gosub` pushes the address to
591    /// come back to and jumps into the block, `ret` pops the address and jumps
592    /// back. QuickJS reuses the integer tag for this (and notes it as a hardening
593    /// gap); a distinct variant keeps it out of reach of arithmetic.
594    ReturnAddress(u32),
595    /// An array hole: an index that was skipped rather than filled.
596    ///
597    /// `[1,,3]` and `[1,undefined,3]` are different arrays: `forEach` skips the hole,
598    /// `in` reports it absent, and the debug printer shows `<1 empty item>`. That
599    /// distinction has to live in the element vector, and this is the marker for it.
600    /// It is never observable from JavaScript: reading the index yields `undefined`
601    /// and no language operation can produce it.
602    Hole,
603    /// The internal marker a `let`/`const` binding holds between its scope being
604    /// entered and its initialiser running.
605    ///
606    /// QuickJS calls this `JS_UNINITIALIZED`; it is deliberately not observable
607    /// from JavaScript. It only ever sits in a slot or a cell, and every read that
608    /// may see it (`get_loc_check` and friends) turns it into a `ReferenceError`.
609    Uninitialized,
610}
611
612impl Value {
613    /// A string value on `heap`.
614    pub fn string(heap: &js_gc::Heap, text: impl Into<String>) -> Value {
615        Value::String(Gc::new(heap, JsString::new(text)))
616    }
617
618    /// A string from bytes that are already WTF-8, which is how a string containing an
619    /// unpaired surrogate reaches a `Value`.
620    pub fn string_wtf8(heap: &js_gc::Heap, text: Wtf8) -> Value {
621        Value::String(Gc::new(heap, JsString::from_wtf8(text)))
622    }
623
624    /// The number as a double, widening an [`Value::Int`].
625    pub fn as_f64(&self) -> Option<f64> {
626        match self {
627            Value::Int(i) => Some(*i as f64),
628            Value::Float(f) => Some(*f),
629            _ => None,
630        }
631    }
632
633    /// The value as a string, if it is one with no unpaired surrogate.
634    pub fn as_str(&self) -> Option<&str> {
635        match self {
636            Value::String(s) => s.as_str(),
637            _ => None,
638        }
639    }
640
641    /// The value's string content as WTF-8, which covers every string including one with an
642    /// unpaired surrogate.
643    pub fn as_wtf8(&self) -> Option<&Wtf8> {
644        match self {
645            Value::String(s) => Some(s.wtf8()),
646            _ => None,
647        }
648    }
649
650    /// The symbol, if this is one.
651    pub fn as_symbol(&self) -> Option<&Gc<JsSymbol>> {
652        match self {
653            Value::Symbol(symbol) => Some(symbol),
654            _ => None,
655        }
656    }
657
658    /// The object, if this is one.
659    pub fn as_object(&self) -> Option<&Gc<JsObject>> {
660        match self {
661            Value::Object(o) => Some(o),
662            _ => None,
663        }
664    }
665
666    /// Whether this is one of the two null-ish values.
667    pub fn is_nullish(&self) -> bool {
668        matches!(self, Value::Undefined | Value::Null)
669    }
670
671    /// `typeof value`.
672    pub fn type_of(&self) -> &'static str {
673        match self {
674            Value::Undefined => "undefined",
675            Value::Null => "object",
676            Value::Bool(_) => "boolean",
677            Value::Int(_) | Value::Float(_) => "number",
678            Value::String(_) => "string",
679            Value::Symbol(_) => "symbol",
680            Value::BigInt(_) => "bigint",
681            Value::Object(object) => {
682                if object.is_callable() {
683                    "function"
684                } else {
685                    "object"
686                }
687            }
688            // The internal markers are never observable from JavaScript;
689            // reporting `undefined` keeps the answer honest if a bug lets one leak.
690            Value::Uninitialized
691            | Value::Hole
692            | Value::CatchOffset(_)
693            | Value::ReturnAddress(_) => "undefined",
694        }
695    }
696
697    /// `ToBoolean`, which is also what a conditional jump tests.
698    pub fn to_boolean(&self) -> bool {
699        match self {
700            Value::Undefined | Value::Null => false,
701            Value::Bool(b) => *b,
702            Value::Int(i) => *i != 0,
703            // `NaN` is falsy, and so is `-0`.
704            Value::Float(f) => *f != 0.0 && !f.is_nan(),
705            Value::String(s) => !s.wtf8().is_empty(),
706            // Every symbol is truthy, even the one with no description.
707            Value::Symbol(_) => true,
708            // A bigint follows the numbers: `0n` is falsy and every other width is truthy.
709            // Saying "every bigint is truthy" turned `if (b & 1n)` into an unconditional
710            // branch, which quietly corrupted every bigint algorithm that tests a bit.
711            Value::BigInt(big) => !big.is_zero(),
712            // Every object is truthy, including `new Boolean(false)`.
713            Value::Object(_) => true,
714            Value::Uninitialized
715            | Value::Hole
716            | Value::CatchOffset(_)
717            | Value::ReturnAddress(_) => false,
718        }
719    }
720
721    /// `ToNumber`, for the arithmetic operators.
722    pub fn to_number(&self) -> f64 {
723        match self {
724            Value::Undefined => f64::NAN,
725            Value::Null => 0.0,
726            Value::Bool(b) => {
727                if *b {
728                    1.0
729                } else {
730                    0.0
731                }
732            }
733            Value::Int(i) => *i as f64,
734            Value::Float(f) => *f,
735            Value::String(s) => string_to_number(&s.to_string_lossy()),
736            // `ToNumber` of a symbol or a bigint is a `TypeError`; `NaN` keeps this
737            // infallible helper total, and the operators reject them first.
738            Value::Symbol(_) => f64::NAN,
739            Value::BigInt(_) => f64::NAN,
740            // `ToNumber` of an object runs `ToPrimitive` first, which needs the
741            // value-of/valueOf machinery; until that lands an object is `NaN`
742            // rather than a panic.
743            Value::Object(_) => f64::NAN,
744            Value::Uninitialized
745            | Value::Hole
746            | Value::CatchOffset(_)
747            | Value::ReturnAddress(_) => f64::NAN,
748        }
749    }
750
751    /// `ToInt32`, the conversion the bitwise operators and `<<`/`>>`/`>>>` use.
752    pub fn to_int32(&self) -> i32 {
753        to_int32(self.to_number())
754    }
755
756    /// `ToUint32`.
757    pub fn to_uint32(&self) -> u32 {
758        self.to_int32() as u32
759    }
760
761    /// `ToString`.
762    ///
763    /// Named `to_js_string` rather than `to_string` so it does not shadow
764    /// [`std::fmt::Display`]: the two disagree on purpose (`display` keeps the sign
765    /// of `-0`), and an accidental `to_string` on a `Value` would silently pick the
766    /// wrong one.
767    pub fn to_js_string(&self) -> String {
768        match self {
769            Value::Undefined => "undefined".to_string(),
770            Value::Null => "null".to_string(),
771            Value::Bool(true) => "true".to_string(),
772            Value::Bool(false) => "false".to_string(),
773            Value::Int(i) => i.to_string(),
774            Value::Float(f) => number_to_string(*f),
775            // Lossy only for a string with an unpaired surrogate, which has no `&str`
776            // form at all; every other string borrows and copies nothing extra.
777            Value::String(s) => s.to_string_lossy().into_owned(),
778            Value::BigInt(big) => big.to_decimal_string(),
779            // `ToString` of a symbol is a `TypeError`; this descriptive form is what
780            // `String(sym)` and the error messages use. Callers that must throw go
781            // through `Interp::checked_to_string`.
782            Value::Symbol(s) => s.to_display_string(),
783            Value::Object(_) => "[object Object]".to_string(),
784            Value::Uninitialized
785            | Value::Hole
786            | Value::CatchOffset(_)
787            | Value::ReturnAddress(_) => "undefined".to_string(),
788        }
789    }
790
791    /// `===`.
792    pub fn strict_equals(&self, other: &Value) -> bool {
793        match (self, other) {
794            (Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => true,
795            (Value::Bool(a), Value::Bool(b)) => a == b,
796            // `Int` and `Float` are the same type to JavaScript, so `1 === 1.0`.
797            (Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) => {
798                let (a, b) = (self.to_number(), other.to_number());
799                a == b
800            }
801            (Value::String(a), Value::String(b)) => a.as_str() == b.as_str(),
802            // Two bigints compare by value, because the representation is canonical —
803            // `2n ** 1000n` computed twice is one value, not two handles.
804            (Value::BigInt(a), Value::BigInt(b)) => **a == **b,
805            // A symbol is equal only to itself: the same description means nothing.
806            (Value::Symbol(a), Value::Symbol(b)) => a.ptr_eq(b),
807            // Objects compare by identity, never structurally.
808            (Value::Object(a), Value::Object(b)) => a.ptr_eq(b),
809            _ => false,
810        }
811    }
812
813    /// `SameValue`, the equality `Object.is` uses and a proxy invariant needs.
814    ///
815    /// It is [`Value::same_value_zero`] plus the one extra distinction: `+0` and `-0`
816    /// are different values here, which is what makes `Object.is(0, -0)` false.
817    pub fn same_value(&self, other: &Value) -> bool {
818        if let (Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) = (self, other) {
819            let (a, b) = (self.to_number(), other.to_number());
820            if a.is_nan() && b.is_nan() {
821                return true;
822            }
823            if a == 0.0 && b == 0.0 {
824                return a.is_sign_negative() == b.is_sign_negative();
825            }
826            return a == b;
827        }
828        self.strict_equals(other)
829    }
830
831    /// `SameValueZero`, the equality a `Map` key and a `Set` element use.
832    ///
833    /// It differs from `===` in exactly one place: `NaN` equals itself. That is what makes
834    /// `map.set(NaN, 1); map.get(NaN)` work, and it is why a `Map` cannot use `strict_equals`
835    /// directly. A bigint compares by value, since its representation is canonical.
836    pub fn same_value_zero(&self, other: &Value) -> bool {
837        if let (Value::Float(a), Value::Float(b)) = (self, other)
838            && a.is_nan()
839            && b.is_nan()
840        {
841            return true;
842        }
843        self.strict_equals(other)
844    }
845
846    /// `==`, with the coercion rules.
847    ///
848    /// `NaN` compares unequal to everything including itself, which the numeric
849    /// branch already gets right. An object compares by identity against another
850    /// object and by its primitive form against a primitive.
851    pub fn loose_equals(&self, other: &Value) -> bool {
852        if matches!(self, Value::Object(_)) || matches!(other, Value::Object(_)) {
853            return match (self, other) {
854                (Value::Object(a), Value::Object(b)) => a.ptr_eq(b),
855                _ => primitive_loose_equals(&self.primitive(), &other.primitive()),
856            };
857        }
858        match (self, other) {
859            (Value::Undefined | Value::Null, Value::Undefined | Value::Null) => true,
860            (Value::Undefined | Value::Null, _) | (_, Value::Undefined | Value::Null) => false,
861            (Value::String(a), Value::String(b)) => a.as_str() == b.as_str(),
862            (Value::Symbol(a), Value::Symbol(b)) => a.ptr_eq(b),
863            (Value::Bool(a), Value::Bool(b)) => a == b,
864            // A bigint equals another bigint by value, a string that spells it exactly, or a
865            // number with the same mathematical value — that last one is why `1n == 1` is
866            // true while `1n === 1` is false.
867            (Value::BigInt(a), Value::BigInt(b)) => **a == **b,
868            (Value::BigInt(a), Value::String(b)) | (Value::String(b), Value::BigInt(a)) => {
869                crate::bigint::BigInt::from_string(&b.to_string_lossy()).as_ref() == Some(&**a)
870            }
871            (Value::BigInt(a), other) => match other {
872                Value::Int(_) | Value::Float(_) => bigint_equals_number(a, other.to_number()),
873                // A boolean is `ToNumber`ed first, so `true == 1n` is true.
874                Value::Bool(flag) => bigint_equals_number(a, if *flag { 1.0 } else { 0.0 }),
875                _ => false,
876            },
877            (other, Value::BigInt(b)) => match other {
878                Value::Int(_) | Value::Float(_) => bigint_equals_number(b, other.to_number()),
879                Value::Bool(flag) => bigint_equals_number(b, if *flag { 1.0 } else { 0.0 }),
880                _ => false,
881            },
882            // Everything else compares numerically, which covers `"1" == 1`,
883            // `true == 1` and `Int` against `Float`.
884            _ => self.to_number() == other.to_number(),
885        }
886    }
887
888    /// `ToPrimitive` with no hint.
889    ///
890    /// The result is an owned [`Primitive`] rather than a [`Value`] because a
891    /// string `Value` needs a heap handle and this path deliberately has none.
892    fn primitive(&self) -> Primitive {
893        match self {
894            Value::Undefined => Primitive::Undefined,
895            Value::Null => Primitive::Null,
896            Value::Bool(b) => Primitive::Bool(*b),
897            Value::Int(i) => Primitive::Number(*i as f64),
898            Value::Float(f) => Primitive::Number(*f),
899            Value::String(s) => Primitive::String(s.to_string_lossy().into_owned()),
900            // A symbol stays distinct from a string here so `==` does not treat it as
901            // one; only an object's `ToPrimitive` can produce a symbol from an object.
902            Value::Symbol(s) => Primitive::Symbol(s.clone()),
903            // A bigint reaches `Primitive` as its decimal text, which is enough for the
904            // loose comparisons that go through here; the operators reject it first.
905            Value::BigInt(big) => Primitive::String(big.to_decimal_string()),
906            Value::Object(_) => Primitive::String(self.to_js_string()),
907            Value::Uninitialized
908            | Value::Hole
909            | Value::CatchOffset(_)
910            | Value::ReturnAddress(_) => Primitive::Undefined,
911        }
912    }
913}
914
915/// A value with no object identity, used by [`Value::loose_equals`].
916enum Primitive {
917    Undefined,
918    Null,
919    Bool(bool),
920    Number(f64),
921    String(String),
922    /// A symbol, which is a primitive but compares by identity.
923    Symbol(Gc<JsSymbol>),
924}
925
926/// `==` once both sides are primitives.
927fn primitive_loose_equals(left: &Primitive, right: &Primitive) -> bool {
928    use Primitive::*;
929    match (left, right) {
930        (Undefined | Null, Undefined | Null) => true,
931        (Undefined | Null, _) | (_, Undefined | Null) => false,
932        // A symbol is a primitive, so `==` on two symbols is identity. Against
933        // anything else it is `false` — the only coercion that could apply is boxing,
934        // and `Object(Symbol())` is an object, not a `Primitive`.
935        (Symbol(a), Symbol(b)) => a.ptr_eq(b),
936        (Symbol(_), _) | (_, Symbol(_)) => false,
937        (String(a), String(b)) => a == b,
938        (Bool(a), Bool(b)) => a == b,
939        (Number(a), Number(b)) => a == b,
940        // A string against a number compares numerically, so `"" == 0` and
941        // `"1" == 1`.
942        (String(s), Number(n)) | (Number(n), String(s)) => string_to_number(s) == *n,
943        (Bool(b), Number(n)) | (Number(n), Bool(b)) => (if *b { 1.0 } else { 0.0 }) == *n,
944        (Bool(b), String(s)) | (String(s), Bool(b)) => {
945            string_to_number(s) == (if *b { 1.0 } else { 0.0 })
946        }
947    }
948}
949
950/// `bigint == number`, compared as whole numbers rather than through the double.
951///
952/// Going through `to_f64` made `100000000000000000001n == 1e20` true, because the double
953/// rounds both sides onto the same value; the spec compares the exact integers, and a
954/// double that is already an integer converts to one exactly.
955fn bigint_equals_number(big: &crate::bigint::BigInt, number: f64) -> bool {
956    number.is_finite()
957        && number.fract() == 0.0
958        && crate::bigint::BigInt::from_f64_truncated(number) == *big
959}
960
961/// `ToInt32`.
962///
963/// The spec's modulo-2^32 arithmetic: `NaN` and the infinities become zero, and
964/// the fractional part is dropped toward zero before the wrap.
965pub fn to_int32(value: f64) -> i32 {
966    if !value.is_finite() || value == 0.0 {
967        return 0;
968    }
969    let truncated = value.trunc();
970    let modulo = truncated.rem_euclid(4294967296.0);
971    let wrapped = if modulo >= 2147483648.0 {
972        modulo - 4294967296.0
973    } else {
974        modulo
975    };
976    wrapped as i32
977}
978
979/// `ToNumber` applied to a string.
980///
981/// Leading and trailing whitespace is allowed; anything else must be a valid
982/// numeric literal, because a failed parse is `NaN` rather than a prefix match.
983/// The empty string is `0`, which is a common source of surprise.
984pub fn string_to_number(text: &str) -> f64 {
985    let trimmed = text.trim();
986    if trimmed.is_empty() {
987        return 0.0;
988    }
989    if let Some(rest) = strip_radix_prefix(trimmed, "0x", "0X") {
990        return radix_number(rest, 16);
991    }
992    if let Some(rest) = strip_radix_prefix(trimmed, "0o", "0O") {
993        return radix_number(rest, 8);
994    }
995    if let Some(rest) = strip_radix_prefix(trimmed, "0b", "0B") {
996        return radix_number(rest, 2);
997    }
998    let (sign, digits) = match trimmed.strip_prefix(['+', '-']) {
999        Some(rest) => (&trimmed[..1], rest),
1000        None => ("", trimmed),
1001    };
1002    // `Infinity` is a literal; `inf`/`nan` are not, even though Rust parses them.
1003    if digits == "Infinity" {
1004        return if sign == "-" {
1005            f64::NEG_INFINITY
1006        } else {
1007            f64::INFINITY
1008        };
1009    }
1010    // Rust's parser accepts the literals JavaScript does not, so the shape is
1011    // checked before trusting it: digits with at most one dot, at most one
1012    // exponent, and no trailing garbage.
1013    if !is_decimal_literal(digits) {
1014        return f64::NAN;
1015    }
1016    trimmed.parse::<f64>().unwrap_or(f64::NAN)
1017}
1018
1019fn strip_radix_prefix<'a>(text: &'a str, lower: &str, upper: &str) -> Option<&'a str> {
1020    text.strip_prefix(lower)
1021        .or_else(|| text.strip_prefix(upper))
1022}
1023
1024fn radix_number(digits: &str, radix: u32) -> f64 {
1025    if digits.is_empty() || !digits.chars().all(|c| c.is_digit(radix)) {
1026        return f64::NAN;
1027    }
1028    // A long literal overflows `u64`; JavaScript then rounds, so fall back to an
1029    // accumulating double rather than reporting `NaN`.
1030    match u64::from_str_radix(digits, radix) {
1031        Ok(value) => value as f64,
1032        Err(_) => digits.chars().fold(0.0, |acc, c| {
1033            acc * radix as f64 + c.to_digit(radix).unwrap_or(0) as f64
1034        }),
1035    }
1036}
1037
1038/// Whether `text` is a decimal literal with no sign.
1039fn is_decimal_literal(text: &str) -> bool {
1040    let bytes = text.as_bytes();
1041    let mut index = 0;
1042    let mut digits = 0;
1043    while index < bytes.len() && bytes[index].is_ascii_digit() {
1044        index += 1;
1045        digits += 1;
1046    }
1047    if index < bytes.len() && bytes[index] == b'.' {
1048        index += 1;
1049        while index < bytes.len() && bytes[index].is_ascii_digit() {
1050            index += 1;
1051            digits += 1;
1052        }
1053    }
1054    if digits == 0 {
1055        return false;
1056    }
1057    if index < bytes.len() && (bytes[index] == b'e' || bytes[index] == b'E') {
1058        index += 1;
1059        if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
1060            index += 1;
1061        }
1062        let start = index;
1063        while index < bytes.len() && bytes[index].is_ascii_digit() {
1064            index += 1;
1065        }
1066        if index == start {
1067            return false;
1068        }
1069    }
1070    index == bytes.len()
1071}
1072
1073/// `ToString` applied to a number.
1074///
1075/// The thresholds are the ones the spec's `Number::toString` uses: exponential
1076/// form below `1e-6` and from `1e21` up, decimal form in between. Within the
1077/// decimal range Rust's shortest-round-trip formatter already agrees with
1078/// JavaScript digit for digit — including the notorious `0.30000000000000004` —
1079/// so only the exponent spelling has to be normalised.
1080pub fn number_to_string(value: f64) -> String {
1081    if value.is_nan() {
1082        return "NaN".to_string();
1083    }
1084    if value.is_infinite() {
1085        return if value > 0.0 {
1086            "Infinity".to_string()
1087        } else {
1088            "-Infinity".to_string()
1089        };
1090    }
1091    if value == 0.0 {
1092        // `ToString(-0)` is `"0"`; `print(-0)` is a different question, see
1093        // [`number_to_string_for_print`].
1094        return "0".to_string();
1095    }
1096    let magnitude = value.abs();
1097    if magnitude >= 1e21 || magnitude < 1e-6 {
1098        return normalise_exponent(format!("{value:e}"));
1099    }
1100    format!("{value}")
1101}
1102
1103/// `ToString` as the engine's `print` applies it, which differs from the language
1104/// one for negative zero.
1105///
1106/// `print(-0)` prints `-0` in QuickJS while `String(-0)` is `"0"`, because the host
1107/// printer takes the number's own spelling. Reproduced here so byte-for-byte output
1108/// comparisons do not trip over it.
1109pub fn number_to_string_for_print(value: f64) -> String {
1110    if value == 0.0 && value.is_sign_negative() {
1111        return "-0".to_string();
1112    }
1113    number_to_string(value)
1114}
1115
1116/// Rewrite Rust's exponent spelling as JavaScript's: always signed, never padded.
1117///
1118/// Rust writes `1e-7` and `1e21`; JavaScript writes `1e-7` and `1e+21`. The
1119/// difference is only the explicit `+`.
1120fn normalise_exponent(text: String) -> String {
1121    let Some((mantissa, exponent)) = text.split_once('e') else {
1122        return text;
1123    };
1124    if exponent.starts_with('-') {
1125        text
1126    } else {
1127        let digits = exponent.strip_prefix('+').unwrap_or(exponent);
1128        format!("{mantissa}e+{digits}")
1129    }
1130}
1131
1132impl Trace for Value {
1133    fn trace(&self, tracer: &mut Tracer) {
1134        match self {
1135            Value::String(s) => tracer.visit(s),
1136            Value::Object(o) => tracer.visit(o),
1137            Value::Symbol(s) => tracer.visit(s),
1138            _ => {}
1139        }
1140    }
1141}
1142
1143impl fmt::Debug for Value {
1144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1145        match self {
1146            Value::Undefined => f.write_str("undefined"),
1147            Value::Null => f.write_str("null"),
1148            Value::Bool(b) => write!(f, "{b}"),
1149            Value::Int(i) => write!(f, "{i}"),
1150            Value::Float(x) => write!(f, "{}", number_to_string(*x)),
1151            Value::String(s) => write!(f, "{:?}", s.as_str()),
1152            Value::Object(_) => f.write_str("[object]"),
1153            Value::Symbol(s) => f.write_str(&s.to_display_string()),
1154            Value::BigInt(big) => write!(f, "{}n", big.to_decimal_string()),
1155            Value::Uninitialized => f.write_str("<uninitialised>"),
1156            Value::Hole => f.write_str("<hole>"),
1157            Value::CatchOffset(offset) => write!(f, "<catch {offset}>"),
1158            Value::ReturnAddress(address) => write!(f, "<ret {address}>"),
1159        }
1160    }
1161}
1162
1163#[cfg(test)]
1164mod tests {
1165    use super::*;
1166
1167    #[test]
1168    fn int32_wraps_the_way_the_spec_says() {
1169        assert_eq!(to_int32(0.0), 0);
1170        assert_eq!(to_int32(f64::NAN), 0);
1171        assert_eq!(to_int32(f64::INFINITY), 0);
1172        assert_eq!(to_int32(1.9), 1);
1173        assert_eq!(to_int32(-1.9), -1);
1174        assert_eq!(to_int32(2147483648.0), -2147483648);
1175        assert_eq!(to_int32(4294967296.0), 0);
1176        assert_eq!(to_int32(-4294967297.0), -1);
1177    }
1178
1179    #[test]
1180    fn numbers_print_like_javascript() {
1181        assert_eq!(number_to_string(0.0), "0");
1182        assert_eq!(number_to_string(-0.0), "0");
1183        assert_eq!(number_to_string(1.0), "1");
1184        assert_eq!(number_to_string(-1.5), "-1.5");
1185        assert_eq!(number_to_string(1e21), "1e+21");
1186        assert_eq!(number_to_string(1e-7), "1e-7");
1187        assert_eq!(number_to_string(1e-6), "0.000001");
1188        assert_eq!(number_to_string(1e20), "100000000000000000000");
1189        assert_eq!(number_to_string(5e-324), "5e-324");
1190        // `print(-0)` differs from `String(-0)`.
1191        assert_eq!(number_to_string_for_print(-0.0), "-0");
1192        assert_eq!(number_to_string(f64::NAN), "NaN");
1193        assert_eq!(number_to_string(f64::INFINITY), "Infinity");
1194        assert_eq!(number_to_string(f64::NEG_INFINITY), "-Infinity");
1195    }
1196
1197    #[test]
1198    fn strings_parse_to_numbers_without_prefix_matching() {
1199        assert_eq!(string_to_number(""), 0.0);
1200        assert_eq!(string_to_number("  "), 0.0);
1201        assert_eq!(string_to_number(" 42 "), 42.0);
1202        assert_eq!(string_to_number("0x10"), 16.0);
1203        assert_eq!(string_to_number("0b101"), 5.0);
1204        assert_eq!(string_to_number("0o17"), 15.0);
1205        assert_eq!(string_to_number("Infinity"), f64::INFINITY);
1206        assert_eq!(string_to_number("-Infinity"), f64::NEG_INFINITY);
1207        assert_eq!(string_to_number("1e3"), 1000.0);
1208        assert_eq!(string_to_number(".5"), 0.5);
1209        assert_eq!(string_to_number("5."), 5.0);
1210        // These would all be prefix matches or Rust-only spellings.
1211        assert!(string_to_number("12px").is_nan());
1212        assert!(string_to_number("inf").is_nan());
1213        assert!(string_to_number("nan").is_nan());
1214        assert!(string_to_number("1e").is_nan());
1215        assert!(string_to_number("0x").is_nan());
1216    }
1217
1218    #[test]
1219    fn strict_equality_ignores_the_int_float_split() {
1220        assert!(Value::Int(1).strict_equals(&Value::Float(1.0)));
1221        assert!(!Value::Int(1).strict_equals(&Value::Float(1.5)));
1222        assert!(!Value::Float(f64::NAN).strict_equals(&Value::Float(f64::NAN)));
1223        assert!(Value::Int(0).strict_equals(&Value::Float(-0.0)));
1224        assert!(!Value::Int(0).strict_equals(&Value::Null));
1225        assert!(!Value::Undefined.strict_equals(&Value::Null));
1226    }
1227
1228    #[test]
1229    fn falsy_values_are_the_spec_list() {
1230        assert!(!Value::Undefined.to_boolean());
1231        assert!(!Value::Null.to_boolean());
1232        assert!(!Value::Bool(false).to_boolean());
1233        assert!(!Value::Int(0).to_boolean());
1234        assert!(!Value::Float(f64::NAN).to_boolean());
1235        assert!(!Value::Float(-0.0).to_boolean());
1236        assert!(Value::Float(0.1).to_boolean());
1237    }
1238}