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