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