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