1use std::cell::RefCell;
11use std::fmt;
12
13use js_gc::{Gc, Trace, Tracer};
14
15use crate::object::JsObject;
16
17#[derive(Clone)]
36pub struct Wtf8 {
37 bytes: Box<[u8]>,
39 valid: bool,
43}
44
45impl Wtf8 {
46 pub fn new(text: impl Into<String>) -> Wtf8 {
48 Wtf8 {
49 bytes: text.into().into_bytes().into_boxed_slice(),
50 valid: true,
51 }
52 }
53
54 pub fn from_units(units: &[u16]) -> Wtf8 {
58 let mut bytes = Vec::with_capacity(units.len());
59 let mut valid = true;
60 let mut index = 0;
61 while index < units.len() {
62 let unit = units[index];
63 match units.get(index + 1) {
64 Some(&low) if is_high(unit) && is_low(low) => {
65 push_code_point(&mut bytes, combine(unit, low));
66 index += 2;
67 }
68 _ if is_surrogate(unit) => {
69 valid = false;
72 push_surrogate(&mut bytes, unit);
73 index += 1;
74 }
75 _ => {
76 push_code_point(&mut bytes, unit as u32);
77 index += 1;
78 }
79 }
80 }
81 Wtf8 {
82 bytes: bytes.into_boxed_slice(),
83 valid,
84 }
85 }
86
87 pub fn as_str(&self) -> Option<&str> {
92 if self.valid {
93 Some(unsafe { std::str::from_utf8_unchecked(&self.bytes) })
96 } else {
97 None
98 }
99 }
100
101 pub fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
105 match self.as_str() {
106 Some(text) => std::borrow::Cow::Borrowed(text),
107 None => String::from_utf8_lossy(&self.bytes),
108 }
109 }
110
111 pub fn as_bytes(&self) -> &[u8] {
113 &self.bytes
114 }
115
116 pub fn to_units(&self) -> Vec<u16> {
118 let mut units = Vec::with_capacity(self.utf16_len());
119 self.push_units(&mut units);
120 units
121 }
122
123 pub fn utf16_len(&self) -> usize {
129 self.bytes
130 .iter()
131 .filter(|byte| (**byte & 0xC0) != 0x80)
132 .map(|byte| if *byte >= 0xF0 { 2 } else { 1 })
133 .sum()
134 }
135
136 pub fn code_unit_at(&self, index: usize) -> Option<u16> {
138 let mut position = 0;
141 let mut at = 0;
142 while at < self.bytes.len() {
143 let (units, count, width) = self.sequence_at(at);
144 if position + count > index {
145 return Some(units[index - position]);
146 }
147 position += count;
148 at += width;
149 }
150 None
151 }
152
153 pub fn is_empty(&self) -> bool {
155 self.bytes.is_empty()
156 }
157
158 pub fn unit_at(&self, index: usize) -> Option<Wtf8> {
163 self.code_unit_at(index)
164 .map(|unit| Wtf8::from_units(&[unit]))
165 }
166
167 pub fn slice_units(&self, start: usize, end: usize) -> Wtf8 {
169 let units = self.to_units();
170 let start = start.min(units.len());
171 let end = end.clamp(start, units.len());
172 Wtf8::from_units(&units[start..end])
173 }
174
175 pub fn code_points(&self) -> Vec<Wtf8> {
180 let mut out = Vec::new();
181 let mut at = 0;
182 while at < self.bytes.len() {
183 let (_, _, width) = self.sequence_at(at);
184 let mut bytes = Vec::with_capacity(width);
185 bytes.extend_from_slice(&self.bytes[at..at + width]);
186 out.push(Wtf8 {
190 valid: std::str::from_utf8(&bytes).is_ok(),
191 bytes: bytes.into_boxed_slice(),
192 });
193 at += width;
194 }
195 out
196 }
197
198 pub fn concat(&self, other: &Wtf8) -> Wtf8 {
205 let bridges =
206 ends_with_high_surrogate(&self.bytes) && starts_with_low_surrogate(&other.bytes);
207 if !bridges {
208 let mut bytes = Vec::with_capacity(self.bytes.len() + other.bytes.len());
209 bytes.extend_from_slice(&self.bytes);
210 bytes.extend_from_slice(&other.bytes);
211 return Wtf8 {
212 bytes: bytes.into_boxed_slice(),
213 valid: self.valid && other.valid,
214 };
215 }
216 let mut units = self.to_units();
217 units.extend(other.to_units());
218 Wtf8::from_units(&units)
219 }
220
221 fn push_units(&self, out: &mut Vec<u16>) {
223 let mut at = 0;
224 while at < self.bytes.len() {
225 let (units, count, width) = self.sequence_at(at);
226 out.extend_from_slice(&units[..count]);
227 at += width;
228 }
229 }
230
231 pub fn code_point_values(&self) -> Vec<u32> {
238 self.code_points()
239 .into_iter()
240 .map(|point| match point.as_str() {
241 Some(text) => text.chars().next().map_or(0xFFFD, |c| c as u32),
242 None => point.to_units().first().copied().map_or(0xFFFD, u32::from),
244 })
245 .collect()
246 }
247
248 fn sequence_at(&self, at: usize) -> ([u16; 2], usize, usize) {
251 let byte = self.bytes[at];
252 let byte_at = |offset: usize| self.bytes.get(at + offset).copied().unwrap_or(0) as u32;
253 if byte < 0x80 {
254 ([byte as u16, 0], 1, 1)
255 } else if byte >> 5 == 0b110 {
256 (
257 [
258 (((byte as u32 & 0x1F) << 6) | (byte_at(1) & 0x3F)) as u16,
259 0,
260 ],
261 1,
262 2,
263 )
264 } else if byte >> 4 == 0b1110 {
265 (
268 [
269 ((byte as u32 & 0x0F) << 12 | ((byte_at(1) & 0x3F) << 6) | (byte_at(2) & 0x3F))
270 as u16,
271 0,
272 ],
273 1,
274 3,
275 )
276 } else {
277 let code = (byte as u32 & 0x07) << 18
278 | ((byte_at(1) & 0x3F) << 12)
279 | ((byte_at(2) & 0x3F) << 6)
280 | (byte_at(3) & 0x3F);
281 let code = code.wrapping_sub(0x10000);
282 (
283 [
284 0xD800u16.wrapping_add((code >> 10) as u16),
285 0xDC00u16.wrapping_add((code & 0x3FF) as u16),
286 ],
287 2,
288 4,
289 )
290 }
291 }
292}
293
294fn is_surrogate(unit: u16) -> bool {
295 (0xD800..0xE000).contains(&unit)
296}
297
298fn is_high(unit: u16) -> bool {
299 (0xD800..0xDC00).contains(&unit)
300}
301
302fn is_low(unit: u16) -> bool {
303 (0xDC00..0xE000).contains(&unit)
304}
305
306fn combine(high: u16, low: u16) -> u32 {
308 0x10000 + ((high as u32 - 0xD800) << 10) + (low as u32 - 0xDC00)
309}
310
311fn push_code_point(out: &mut Vec<u8>, code: u32) {
313 if code < 0x80 {
314 out.push(code as u8);
315 } else if code < 0x800 {
316 out.push(0xC0 | (code >> 6) as u8);
317 out.push(0x80 | (code & 0x3F) as u8);
318 } else if code < 0x10000 {
319 out.push(0xE0 | (code >> 12) as u8);
320 out.push(0x80 | ((code >> 6) & 0x3F) as u8);
321 out.push(0x80 | (code & 0x3F) as u8);
322 } else {
323 out.push(0xF0 | (code >> 18) as u8);
324 out.push(0x80 | ((code >> 12) & 0x3F) as u8);
325 out.push(0x80 | ((code >> 6) & 0x3F) as u8);
326 out.push(0x80 | (code & 0x3F) as u8);
327 }
328}
329
330fn push_surrogate(out: &mut Vec<u8>, unit: u16) {
332 out.push(0xE0 | (unit >> 12) as u8);
333 out.push(0x80 | ((unit >> 6) & 0x3F) as u8);
334 out.push(0x80 | (unit & 0x3F) as u8);
335}
336
337fn ends_with_high_surrogate(bytes: &[u8]) -> bool {
342 let len = bytes.len();
343 len >= 3 && bytes[len - 3] == 0xED && (0xA0..0xB0).contains(&bytes[len - 2])
344}
345
346fn starts_with_low_surrogate(bytes: &[u8]) -> bool {
348 bytes.len() >= 3 && bytes[0] == 0xED && (0xB0..0xC0).contains(&bytes[1])
349}
350
351impl PartialEq for Wtf8 {
352 fn eq(&self, other: &Self) -> bool {
354 self.bytes == other.bytes
355 }
356}
357
358impl Eq for Wtf8 {}
359
360impl fmt::Debug for Wtf8 {
361 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362 write!(f, "{:?}", self.to_string_lossy())
363 }
364}
365
366pub struct JsString {
371 text: Wtf8,
372 units: RefCell<Option<std::rc::Rc<Vec<u16>>>>,
379}
380
381impl JsString {
382 pub fn new(text: impl Into<String>) -> JsString {
384 JsString {
385 text: Wtf8::new(text),
386 units: RefCell::new(None),
387 }
388 }
389
390 pub fn from_wtf8(text: Wtf8) -> JsString {
392 JsString {
393 text,
394 units: RefCell::new(None),
395 }
396 }
397
398 pub fn units_cached(&self) -> std::rc::Rc<Vec<u16>> {
400 if let Some(units) = self.units.borrow().as_ref() {
401 return units.clone();
402 }
403 let units = std::rc::Rc::new(self.text.to_units());
404 *self.units.borrow_mut() = Some(units.clone());
405 units
406 }
407
408 pub fn code_unit_at(&self, index: usize) -> Option<u16> {
410 self.units_cached().get(index).copied()
411 }
412
413 pub fn wtf8(&self) -> &Wtf8 {
415 &self.text
416 }
417
418 pub fn as_str(&self) -> Option<&str> {
420 self.text.as_str()
421 }
422
423 pub fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
425 self.text.to_string_lossy()
426 }
427
428 pub fn to_units(&self) -> Vec<u16> {
430 self.units_cached().as_ref().clone()
431 }
432
433 pub fn utf16_len(&self) -> usize {
436 self.text.utf16_len()
438 }
439}
440
441impl Trace for JsString {
442 fn trace(&self, _tracer: &mut Tracer) {}
443}
444
445impl fmt::Debug for JsString {
446 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
447 write!(f, "{:?}", self.text)
448 }
449}
450
451pub struct JsSymbol {
459 description: Option<String>,
464 registry_key: Option<String>,
469}
470
471impl JsSymbol {
472 pub fn new(description: Option<String>) -> JsSymbol {
474 JsSymbol {
475 description,
476 registry_key: None,
477 }
478 }
479
480 pub fn registered(key: String) -> JsSymbol {
482 JsSymbol {
483 description: Some(key.clone()),
484 registry_key: Some(key),
485 }
486 }
487
488 pub fn description(&self) -> Option<&str> {
490 self.description.as_deref()
491 }
492
493 pub fn registry_key(&self) -> Option<&str> {
495 self.registry_key.as_deref()
496 }
497
498 pub fn to_display_string(&self) -> String {
503 match &self.description {
504 Some(text) => format!("Symbol({text})"),
505 None => "Symbol()".to_string(),
506 }
507 }
508}
509
510impl Trace for JsSymbol {
511 fn trace(&self, _tracer: &mut Tracer) {}
512}
513
514impl fmt::Debug for JsSymbol {
515 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
516 write!(f, "{}", self.to_display_string())
517 }
518}
519
520pub struct Cell {
528 value: RefCell<Value>,
529}
530
531impl Cell {
532 pub fn new(value: Value) -> Cell {
534 Cell {
535 value: RefCell::new(value),
536 }
537 }
538
539 pub fn get(&self) -> Value {
541 self.value.borrow().clone()
542 }
543
544 pub fn set(&self, value: Value) {
546 *self.value.borrow_mut() = value;
547 }
548}
549
550impl Trace for Cell {
551 fn trace(&self, tracer: &mut Tracer) {
552 self.value.borrow().trace(tracer);
553 }
554}
555
556#[derive(Clone)]
558pub enum Value {
559 Undefined,
561 Null,
563 Bool(bool),
565 Int(i32),
567 Float(f64),
569 String(Gc<JsString>),
571 Object(Gc<JsObject>),
573 Symbol(Gc<JsSymbol>),
575 BigInt(Gc<crate::bigint::BigInt>),
580 CatchOffset(u32),
588 ReturnAddress(u32),
595 Hole,
603 Uninitialized,
610}
611
612impl Value {
613 pub fn string(heap: &js_gc::Heap, text: impl Into<String>) -> Value {
615 Value::String(Gc::new(heap, JsString::new(text)))
616 }
617
618 pub fn string_wtf8(heap: &js_gc::Heap, text: Wtf8) -> Value {
621 Value::String(Gc::new(heap, JsString::from_wtf8(text)))
622 }
623
624 pub fn as_f64(&self) -> Option<f64> {
626 match self {
627 Value::Int(i) => Some(*i as f64),
628 Value::Float(f) => Some(*f),
629 _ => None,
630 }
631 }
632
633 pub fn as_str(&self) -> Option<&str> {
635 match self {
636 Value::String(s) => s.as_str(),
637 _ => None,
638 }
639 }
640
641 pub fn as_wtf8(&self) -> Option<&Wtf8> {
644 match self {
645 Value::String(s) => Some(s.wtf8()),
646 _ => None,
647 }
648 }
649
650 pub fn as_symbol(&self) -> Option<&Gc<JsSymbol>> {
652 match self {
653 Value::Symbol(symbol) => Some(symbol),
654 _ => None,
655 }
656 }
657
658 pub fn as_object(&self) -> Option<&Gc<JsObject>> {
660 match self {
661 Value::Object(o) => Some(o),
662 _ => None,
663 }
664 }
665
666 pub fn is_nullish(&self) -> bool {
668 matches!(self, Value::Undefined | Value::Null)
669 }
670
671 pub fn type_of(&self) -> &'static str {
673 match self {
674 Value::Undefined => "undefined",
675 Value::Null => "object",
676 Value::Bool(_) => "boolean",
677 Value::Int(_) | Value::Float(_) => "number",
678 Value::String(_) => "string",
679 Value::Symbol(_) => "symbol",
680 Value::BigInt(_) => "bigint",
681 Value::Object(object) => {
682 if object.is_callable() {
683 "function"
684 } else {
685 "object"
686 }
687 }
688 Value::Uninitialized
691 | Value::Hole
692 | Value::CatchOffset(_)
693 | Value::ReturnAddress(_) => "undefined",
694 }
695 }
696
697 pub fn to_boolean(&self) -> bool {
699 match self {
700 Value::Undefined | Value::Null => false,
701 Value::Bool(b) => *b,
702 Value::Int(i) => *i != 0,
703 Value::Float(f) => *f != 0.0 && !f.is_nan(),
705 Value::String(s) => !s.wtf8().is_empty(),
706 Value::Symbol(_) => true,
708 Value::BigInt(big) => !big.is_zero(),
712 Value::Object(_) => true,
714 Value::Uninitialized
715 | Value::Hole
716 | Value::CatchOffset(_)
717 | Value::ReturnAddress(_) => false,
718 }
719 }
720
721 pub fn to_number(&self) -> f64 {
723 match self {
724 Value::Undefined => f64::NAN,
725 Value::Null => 0.0,
726 Value::Bool(b) => {
727 if *b {
728 1.0
729 } else {
730 0.0
731 }
732 }
733 Value::Int(i) => *i as f64,
734 Value::Float(f) => *f,
735 Value::String(s) => string_to_number(&s.to_string_lossy()),
736 Value::Symbol(_) => f64::NAN,
739 Value::BigInt(_) => f64::NAN,
740 Value::Object(_) => f64::NAN,
744 Value::Uninitialized
745 | Value::Hole
746 | Value::CatchOffset(_)
747 | Value::ReturnAddress(_) => f64::NAN,
748 }
749 }
750
751 pub fn to_int32(&self) -> i32 {
753 to_int32(self.to_number())
754 }
755
756 pub fn to_uint32(&self) -> u32 {
758 self.to_int32() as u32
759 }
760
761 pub fn to_js_string(&self) -> String {
768 match self {
769 Value::Undefined => "undefined".to_string(),
770 Value::Null => "null".to_string(),
771 Value::Bool(true) => "true".to_string(),
772 Value::Bool(false) => "false".to_string(),
773 Value::Int(i) => i.to_string(),
774 Value::Float(f) => number_to_string(*f),
775 Value::String(s) => s.to_string_lossy().into_owned(),
778 Value::BigInt(big) => big.to_decimal_string(),
779 Value::Symbol(s) => s.to_display_string(),
783 Value::Object(_) => "[object Object]".to_string(),
784 Value::Uninitialized
785 | Value::Hole
786 | Value::CatchOffset(_)
787 | Value::ReturnAddress(_) => "undefined".to_string(),
788 }
789 }
790
791 pub fn strict_equals(&self, other: &Value) -> bool {
793 match (self, other) {
794 (Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => true,
795 (Value::Bool(a), Value::Bool(b)) => a == b,
796 (Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) => {
798 let (a, b) = (self.to_number(), other.to_number());
799 a == b
800 }
801 (Value::String(a), Value::String(b)) => a.as_str() == b.as_str(),
802 (Value::BigInt(a), Value::BigInt(b)) => **a == **b,
805 (Value::Symbol(a), Value::Symbol(b)) => a.ptr_eq(b),
807 (Value::Object(a), Value::Object(b)) => a.ptr_eq(b),
809 _ => false,
810 }
811 }
812
813 pub fn same_value(&self, other: &Value) -> bool {
818 if let (Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) = (self, other) {
819 let (a, b) = (self.to_number(), other.to_number());
820 if a.is_nan() && b.is_nan() {
821 return true;
822 }
823 if a == 0.0 && b == 0.0 {
824 return a.is_sign_negative() == b.is_sign_negative();
825 }
826 return a == b;
827 }
828 self.strict_equals(other)
829 }
830
831 pub fn same_value_zero(&self, other: &Value) -> bool {
837 if let (Value::Float(a), Value::Float(b)) = (self, other)
838 && a.is_nan()
839 && b.is_nan()
840 {
841 return true;
842 }
843 self.strict_equals(other)
844 }
845
846 pub fn loose_equals(&self, other: &Value) -> bool {
852 if matches!(self, Value::Object(_)) || matches!(other, Value::Object(_)) {
853 return match (self, other) {
854 (Value::Object(a), Value::Object(b)) => a.ptr_eq(b),
855 _ => primitive_loose_equals(&self.primitive(), &other.primitive()),
856 };
857 }
858 match (self, other) {
859 (Value::Undefined | Value::Null, Value::Undefined | Value::Null) => true,
860 (Value::Undefined | Value::Null, _) | (_, Value::Undefined | Value::Null) => false,
861 (Value::String(a), Value::String(b)) => a.as_str() == b.as_str(),
862 (Value::Symbol(a), Value::Symbol(b)) => a.ptr_eq(b),
863 (Value::Bool(a), Value::Bool(b)) => a == b,
864 (Value::BigInt(a), Value::BigInt(b)) => **a == **b,
868 (Value::BigInt(a), Value::String(b)) | (Value::String(b), Value::BigInt(a)) => {
869 crate::bigint::BigInt::from_string(&b.to_string_lossy()).as_ref() == Some(&**a)
870 }
871 (Value::BigInt(a), other) => match other {
872 Value::Int(_) | Value::Float(_) => bigint_equals_number(a, other.to_number()),
873 Value::Bool(flag) => bigint_equals_number(a, if *flag { 1.0 } else { 0.0 }),
875 _ => false,
876 },
877 (other, Value::BigInt(b)) => match other {
878 Value::Int(_) | Value::Float(_) => bigint_equals_number(b, other.to_number()),
879 Value::Bool(flag) => bigint_equals_number(b, if *flag { 1.0 } else { 0.0 }),
880 _ => false,
881 },
882 _ => self.to_number() == other.to_number(),
885 }
886 }
887
888 fn primitive(&self) -> Primitive {
893 match self {
894 Value::Undefined => Primitive::Undefined,
895 Value::Null => Primitive::Null,
896 Value::Bool(b) => Primitive::Bool(*b),
897 Value::Int(i) => Primitive::Number(*i as f64),
898 Value::Float(f) => Primitive::Number(*f),
899 Value::String(s) => Primitive::String(s.to_string_lossy().into_owned()),
900 Value::Symbol(s) => Primitive::Symbol(s.clone()),
903 Value::BigInt(big) => Primitive::String(big.to_decimal_string()),
906 Value::Object(_) => Primitive::String(self.to_js_string()),
907 Value::Uninitialized
908 | Value::Hole
909 | Value::CatchOffset(_)
910 | Value::ReturnAddress(_) => Primitive::Undefined,
911 }
912 }
913}
914
915enum Primitive {
917 Undefined,
918 Null,
919 Bool(bool),
920 Number(f64),
921 String(String),
922 Symbol(Gc<JsSymbol>),
924}
925
926fn primitive_loose_equals(left: &Primitive, right: &Primitive) -> bool {
928 use Primitive::*;
929 match (left, right) {
930 (Undefined | Null, Undefined | Null) => true,
931 (Undefined | Null, _) | (_, Undefined | Null) => false,
932 (Symbol(a), Symbol(b)) => a.ptr_eq(b),
936 (Symbol(_), _) | (_, Symbol(_)) => false,
937 (String(a), String(b)) => a == b,
938 (Bool(a), Bool(b)) => a == b,
939 (Number(a), Number(b)) => a == b,
940 (String(s), Number(n)) | (Number(n), String(s)) => string_to_number(s) == *n,
943 (Bool(b), Number(n)) | (Number(n), Bool(b)) => (if *b { 1.0 } else { 0.0 }) == *n,
944 (Bool(b), String(s)) | (String(s), Bool(b)) => {
945 string_to_number(s) == (if *b { 1.0 } else { 0.0 })
946 }
947 }
948}
949
950fn bigint_equals_number(big: &crate::bigint::BigInt, number: f64) -> bool {
956 number.is_finite()
957 && number.fract() == 0.0
958 && crate::bigint::BigInt::from_f64_truncated(number) == *big
959}
960
961pub fn to_int32(value: f64) -> i32 {
966 if !value.is_finite() || value == 0.0 {
967 return 0;
968 }
969 let truncated = value.trunc();
970 let modulo = truncated.rem_euclid(4294967296.0);
971 let wrapped = if modulo >= 2147483648.0 {
972 modulo - 4294967296.0
973 } else {
974 modulo
975 };
976 wrapped as i32
977}
978
979pub fn string_to_number(text: &str) -> f64 {
985 let trimmed = text.trim();
986 if trimmed.is_empty() {
987 return 0.0;
988 }
989 if let Some(rest) = strip_radix_prefix(trimmed, "0x", "0X") {
990 return radix_number(rest, 16);
991 }
992 if let Some(rest) = strip_radix_prefix(trimmed, "0o", "0O") {
993 return radix_number(rest, 8);
994 }
995 if let Some(rest) = strip_radix_prefix(trimmed, "0b", "0B") {
996 return radix_number(rest, 2);
997 }
998 let (sign, digits) = match trimmed.strip_prefix(['+', '-']) {
999 Some(rest) => (&trimmed[..1], rest),
1000 None => ("", trimmed),
1001 };
1002 if digits == "Infinity" {
1004 return if sign == "-" {
1005 f64::NEG_INFINITY
1006 } else {
1007 f64::INFINITY
1008 };
1009 }
1010 if !is_decimal_literal(digits) {
1014 return f64::NAN;
1015 }
1016 trimmed.parse::<f64>().unwrap_or(f64::NAN)
1017}
1018
1019fn strip_radix_prefix<'a>(text: &'a str, lower: &str, upper: &str) -> Option<&'a str> {
1020 text.strip_prefix(lower)
1021 .or_else(|| text.strip_prefix(upper))
1022}
1023
1024fn radix_number(digits: &str, radix: u32) -> f64 {
1025 if digits.is_empty() || !digits.chars().all(|c| c.is_digit(radix)) {
1026 return f64::NAN;
1027 }
1028 match u64::from_str_radix(digits, radix) {
1031 Ok(value) => value as f64,
1032 Err(_) => digits.chars().fold(0.0, |acc, c| {
1033 acc * radix as f64 + c.to_digit(radix).unwrap_or(0) as f64
1034 }),
1035 }
1036}
1037
1038fn is_decimal_literal(text: &str) -> bool {
1040 let bytes = text.as_bytes();
1041 let mut index = 0;
1042 let mut digits = 0;
1043 while index < bytes.len() && bytes[index].is_ascii_digit() {
1044 index += 1;
1045 digits += 1;
1046 }
1047 if index < bytes.len() && bytes[index] == b'.' {
1048 index += 1;
1049 while index < bytes.len() && bytes[index].is_ascii_digit() {
1050 index += 1;
1051 digits += 1;
1052 }
1053 }
1054 if digits == 0 {
1055 return false;
1056 }
1057 if index < bytes.len() && (bytes[index] == b'e' || bytes[index] == b'E') {
1058 index += 1;
1059 if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
1060 index += 1;
1061 }
1062 let start = index;
1063 while index < bytes.len() && bytes[index].is_ascii_digit() {
1064 index += 1;
1065 }
1066 if index == start {
1067 return false;
1068 }
1069 }
1070 index == bytes.len()
1071}
1072
1073pub fn number_to_string(value: f64) -> String {
1081 if value.is_nan() {
1082 return "NaN".to_string();
1083 }
1084 if value.is_infinite() {
1085 return if value > 0.0 {
1086 "Infinity".to_string()
1087 } else {
1088 "-Infinity".to_string()
1089 };
1090 }
1091 if value == 0.0 {
1092 return "0".to_string();
1095 }
1096 let magnitude = value.abs();
1097 if magnitude >= 1e21 || magnitude < 1e-6 {
1098 return normalise_exponent(format!("{value:e}"));
1099 }
1100 format!("{value}")
1101}
1102
1103pub fn number_to_string_for_print(value: f64) -> String {
1110 if value == 0.0 && value.is_sign_negative() {
1111 return "-0".to_string();
1112 }
1113 number_to_string(value)
1114}
1115
1116fn normalise_exponent(text: String) -> String {
1121 let Some((mantissa, exponent)) = text.split_once('e') else {
1122 return text;
1123 };
1124 if exponent.starts_with('-') {
1125 text
1126 } else {
1127 let digits = exponent.strip_prefix('+').unwrap_or(exponent);
1128 format!("{mantissa}e+{digits}")
1129 }
1130}
1131
1132impl Trace for Value {
1133 fn trace(&self, tracer: &mut Tracer) {
1134 match self {
1135 Value::String(s) => tracer.visit(s),
1136 Value::Object(o) => tracer.visit(o),
1137 Value::Symbol(s) => tracer.visit(s),
1138 _ => {}
1139 }
1140 }
1141}
1142
1143impl fmt::Debug for Value {
1144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1145 match self {
1146 Value::Undefined => f.write_str("undefined"),
1147 Value::Null => f.write_str("null"),
1148 Value::Bool(b) => write!(f, "{b}"),
1149 Value::Int(i) => write!(f, "{i}"),
1150 Value::Float(x) => write!(f, "{}", number_to_string(*x)),
1151 Value::String(s) => write!(f, "{:?}", s.as_str()),
1152 Value::Object(_) => f.write_str("[object]"),
1153 Value::Symbol(s) => f.write_str(&s.to_display_string()),
1154 Value::BigInt(big) => write!(f, "{}n", big.to_decimal_string()),
1155 Value::Uninitialized => f.write_str("<uninitialised>"),
1156 Value::Hole => f.write_str("<hole>"),
1157 Value::CatchOffset(offset) => write!(f, "<catch {offset}>"),
1158 Value::ReturnAddress(address) => write!(f, "<ret {address}>"),
1159 }
1160 }
1161}
1162
1163#[cfg(test)]
1164mod tests {
1165 use super::*;
1166
1167 #[test]
1168 fn int32_wraps_the_way_the_spec_says() {
1169 assert_eq!(to_int32(0.0), 0);
1170 assert_eq!(to_int32(f64::NAN), 0);
1171 assert_eq!(to_int32(f64::INFINITY), 0);
1172 assert_eq!(to_int32(1.9), 1);
1173 assert_eq!(to_int32(-1.9), -1);
1174 assert_eq!(to_int32(2147483648.0), -2147483648);
1175 assert_eq!(to_int32(4294967296.0), 0);
1176 assert_eq!(to_int32(-4294967297.0), -1);
1177 }
1178
1179 #[test]
1180 fn numbers_print_like_javascript() {
1181 assert_eq!(number_to_string(0.0), "0");
1182 assert_eq!(number_to_string(-0.0), "0");
1183 assert_eq!(number_to_string(1.0), "1");
1184 assert_eq!(number_to_string(-1.5), "-1.5");
1185 assert_eq!(number_to_string(1e21), "1e+21");
1186 assert_eq!(number_to_string(1e-7), "1e-7");
1187 assert_eq!(number_to_string(1e-6), "0.000001");
1188 assert_eq!(number_to_string(1e20), "100000000000000000000");
1189 assert_eq!(number_to_string(5e-324), "5e-324");
1190 assert_eq!(number_to_string_for_print(-0.0), "-0");
1192 assert_eq!(number_to_string(f64::NAN), "NaN");
1193 assert_eq!(number_to_string(f64::INFINITY), "Infinity");
1194 assert_eq!(number_to_string(f64::NEG_INFINITY), "-Infinity");
1195 }
1196
1197 #[test]
1198 fn strings_parse_to_numbers_without_prefix_matching() {
1199 assert_eq!(string_to_number(""), 0.0);
1200 assert_eq!(string_to_number(" "), 0.0);
1201 assert_eq!(string_to_number(" 42 "), 42.0);
1202 assert_eq!(string_to_number("0x10"), 16.0);
1203 assert_eq!(string_to_number("0b101"), 5.0);
1204 assert_eq!(string_to_number("0o17"), 15.0);
1205 assert_eq!(string_to_number("Infinity"), f64::INFINITY);
1206 assert_eq!(string_to_number("-Infinity"), f64::NEG_INFINITY);
1207 assert_eq!(string_to_number("1e3"), 1000.0);
1208 assert_eq!(string_to_number(".5"), 0.5);
1209 assert_eq!(string_to_number("5."), 5.0);
1210 assert!(string_to_number("12px").is_nan());
1212 assert!(string_to_number("inf").is_nan());
1213 assert!(string_to_number("nan").is_nan());
1214 assert!(string_to_number("1e").is_nan());
1215 assert!(string_to_number("0x").is_nan());
1216 }
1217
1218 #[test]
1219 fn strict_equality_ignores_the_int_float_split() {
1220 assert!(Value::Int(1).strict_equals(&Value::Float(1.0)));
1221 assert!(!Value::Int(1).strict_equals(&Value::Float(1.5)));
1222 assert!(!Value::Float(f64::NAN).strict_equals(&Value::Float(f64::NAN)));
1223 assert!(Value::Int(0).strict_equals(&Value::Float(-0.0)));
1224 assert!(!Value::Int(0).strict_equals(&Value::Null));
1225 assert!(!Value::Undefined.strict_equals(&Value::Null));
1226 }
1227
1228 #[test]
1229 fn falsy_values_are_the_spec_list() {
1230 assert!(!Value::Undefined.to_boolean());
1231 assert!(!Value::Null.to_boolean());
1232 assert!(!Value::Bool(false).to_boolean());
1233 assert!(!Value::Int(0).to_boolean());
1234 assert!(!Value::Float(f64::NAN).to_boolean());
1235 assert!(!Value::Float(-0.0).to_boolean());
1236 assert!(Value::Float(0.1).to_boolean());
1237 }
1238}