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 fn sequence_at(&self, at: usize) -> ([u16; 2], usize, usize) {
234 let byte = self.bytes[at];
235 let byte_at = |offset: usize| self.bytes.get(at + offset).copied().unwrap_or(0) as u32;
236 if byte < 0x80 {
237 ([byte as u16, 0], 1, 1)
238 } else if byte >> 5 == 0b110 {
239 (
240 [
241 (((byte as u32 & 0x1F) << 6) | (byte_at(1) & 0x3F)) as u16,
242 0,
243 ],
244 1,
245 2,
246 )
247 } else if byte >> 4 == 0b1110 {
248 (
251 [
252 ((byte as u32 & 0x0F) << 12 | ((byte_at(1) & 0x3F) << 6) | (byte_at(2) & 0x3F))
253 as u16,
254 0,
255 ],
256 1,
257 3,
258 )
259 } else {
260 let code = (byte as u32 & 0x07) << 18
261 | ((byte_at(1) & 0x3F) << 12)
262 | ((byte_at(2) & 0x3F) << 6)
263 | (byte_at(3) & 0x3F);
264 let code = code.wrapping_sub(0x10000);
265 (
266 [
267 0xD800u16.wrapping_add((code >> 10) as u16),
268 0xDC00u16.wrapping_add((code & 0x3FF) as u16),
269 ],
270 2,
271 4,
272 )
273 }
274 }
275}
276
277fn is_surrogate(unit: u16) -> bool {
278 (0xD800..0xE000).contains(&unit)
279}
280
281fn is_high(unit: u16) -> bool {
282 (0xD800..0xDC00).contains(&unit)
283}
284
285fn is_low(unit: u16) -> bool {
286 (0xDC00..0xE000).contains(&unit)
287}
288
289fn combine(high: u16, low: u16) -> u32 {
291 0x10000 + ((high as u32 - 0xD800) << 10) + (low as u32 - 0xDC00)
292}
293
294fn push_code_point(out: &mut Vec<u8>, code: u32) {
296 if code < 0x80 {
297 out.push(code as u8);
298 } else if code < 0x800 {
299 out.push(0xC0 | (code >> 6) as u8);
300 out.push(0x80 | (code & 0x3F) as u8);
301 } else if code < 0x10000 {
302 out.push(0xE0 | (code >> 12) as u8);
303 out.push(0x80 | ((code >> 6) & 0x3F) as u8);
304 out.push(0x80 | (code & 0x3F) as u8);
305 } else {
306 out.push(0xF0 | (code >> 18) as u8);
307 out.push(0x80 | ((code >> 12) & 0x3F) as u8);
308 out.push(0x80 | ((code >> 6) & 0x3F) as u8);
309 out.push(0x80 | (code & 0x3F) as u8);
310 }
311}
312
313fn push_surrogate(out: &mut Vec<u8>, unit: u16) {
315 out.push(0xE0 | (unit >> 12) as u8);
316 out.push(0x80 | ((unit >> 6) & 0x3F) as u8);
317 out.push(0x80 | (unit & 0x3F) as u8);
318}
319
320fn ends_with_high_surrogate(bytes: &[u8]) -> bool {
325 let len = bytes.len();
326 len >= 3 && bytes[len - 3] == 0xED && (0xA0..0xB0).contains(&bytes[len - 2])
327}
328
329fn starts_with_low_surrogate(bytes: &[u8]) -> bool {
331 bytes.len() >= 3 && bytes[0] == 0xED && (0xB0..0xC0).contains(&bytes[1])
332}
333
334impl PartialEq for Wtf8 {
335 fn eq(&self, other: &Self) -> bool {
337 self.bytes == other.bytes
338 }
339}
340
341impl Eq for Wtf8 {}
342
343impl fmt::Debug for Wtf8 {
344 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
345 write!(f, "{:?}", self.to_string_lossy())
346 }
347}
348
349pub struct JsString {
354 text: Wtf8,
355 units: RefCell<Option<std::rc::Rc<Vec<u16>>>>,
362}
363
364impl JsString {
365 pub fn new(text: impl Into<String>) -> JsString {
367 JsString {
368 text: Wtf8::new(text),
369 units: RefCell::new(None),
370 }
371 }
372
373 pub fn from_wtf8(text: Wtf8) -> JsString {
375 JsString {
376 text,
377 units: RefCell::new(None),
378 }
379 }
380
381 pub fn units_cached(&self) -> std::rc::Rc<Vec<u16>> {
383 if let Some(units) = self.units.borrow().as_ref() {
384 return units.clone();
385 }
386 let units = std::rc::Rc::new(self.text.to_units());
387 *self.units.borrow_mut() = Some(units.clone());
388 units
389 }
390
391 pub fn code_unit_at(&self, index: usize) -> Option<u16> {
393 self.units_cached().get(index).copied()
394 }
395
396 pub fn wtf8(&self) -> &Wtf8 {
398 &self.text
399 }
400
401 pub fn as_str(&self) -> Option<&str> {
403 self.text.as_str()
404 }
405
406 pub fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
408 self.text.to_string_lossy()
409 }
410
411 pub fn to_units(&self) -> Vec<u16> {
413 self.units_cached().as_ref().clone()
414 }
415
416 pub fn utf16_len(&self) -> usize {
419 self.text.utf16_len()
421 }
422}
423
424impl Trace for JsString {
425 fn trace(&self, _tracer: &mut Tracer) {}
426}
427
428impl fmt::Debug for JsString {
429 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
430 write!(f, "{:?}", self.text)
431 }
432}
433
434pub struct JsSymbol {
442 description: Option<String>,
447 registry_key: Option<String>,
452}
453
454impl JsSymbol {
455 pub fn new(description: Option<String>) -> JsSymbol {
457 JsSymbol {
458 description,
459 registry_key: None,
460 }
461 }
462
463 pub fn registered(key: String) -> JsSymbol {
465 JsSymbol {
466 description: Some(key.clone()),
467 registry_key: Some(key),
468 }
469 }
470
471 pub fn description(&self) -> Option<&str> {
473 self.description.as_deref()
474 }
475
476 pub fn registry_key(&self) -> Option<&str> {
478 self.registry_key.as_deref()
479 }
480
481 pub fn to_display_string(&self) -> String {
486 match &self.description {
487 Some(text) => format!("Symbol({text})"),
488 None => "Symbol()".to_string(),
489 }
490 }
491}
492
493impl Trace for JsSymbol {
494 fn trace(&self, _tracer: &mut Tracer) {}
495}
496
497impl fmt::Debug for JsSymbol {
498 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
499 write!(f, "{}", self.to_display_string())
500 }
501}
502
503pub struct Cell {
511 value: RefCell<Value>,
512}
513
514impl Cell {
515 pub fn new(value: Value) -> Cell {
517 Cell {
518 value: RefCell::new(value),
519 }
520 }
521
522 pub fn get(&self) -> Value {
524 self.value.borrow().clone()
525 }
526
527 pub fn set(&self, value: Value) {
529 *self.value.borrow_mut() = value;
530 }
531}
532
533impl Trace for Cell {
534 fn trace(&self, tracer: &mut Tracer) {
535 self.value.borrow().trace(tracer);
536 }
537}
538
539#[derive(Clone)]
541pub enum Value {
542 Undefined,
544 Null,
546 Bool(bool),
548 Int(i32),
550 Float(f64),
552 String(Gc<JsString>),
554 Object(Gc<JsObject>),
556 Symbol(Gc<JsSymbol>),
558 BigInt(Gc<crate::bigint::BigInt>),
563 CatchOffset(u32),
571 ReturnAddress(u32),
578 Hole,
586 Uninitialized,
593}
594
595impl Value {
596 pub fn string(heap: &js_gc::Heap, text: impl Into<String>) -> Value {
598 Value::String(Gc::new(heap, JsString::new(text)))
599 }
600
601 pub fn string_wtf8(heap: &js_gc::Heap, text: Wtf8) -> Value {
604 Value::String(Gc::new(heap, JsString::from_wtf8(text)))
605 }
606
607 pub fn as_f64(&self) -> Option<f64> {
609 match self {
610 Value::Int(i) => Some(*i as f64),
611 Value::Float(f) => Some(*f),
612 _ => None,
613 }
614 }
615
616 pub fn as_str(&self) -> Option<&str> {
618 match self {
619 Value::String(s) => s.as_str(),
620 _ => None,
621 }
622 }
623
624 pub fn as_wtf8(&self) -> Option<&Wtf8> {
627 match self {
628 Value::String(s) => Some(s.wtf8()),
629 _ => None,
630 }
631 }
632
633 pub fn as_symbol(&self) -> Option<&Gc<JsSymbol>> {
635 match self {
636 Value::Symbol(symbol) => Some(symbol),
637 _ => None,
638 }
639 }
640
641 pub fn as_object(&self) -> Option<&Gc<JsObject>> {
643 match self {
644 Value::Object(o) => Some(o),
645 _ => None,
646 }
647 }
648
649 pub fn is_nullish(&self) -> bool {
651 matches!(self, Value::Undefined | Value::Null)
652 }
653
654 pub fn type_of(&self) -> &'static str {
656 match self {
657 Value::Undefined => "undefined",
658 Value::Null => "object",
659 Value::Bool(_) => "boolean",
660 Value::Int(_) | Value::Float(_) => "number",
661 Value::String(_) => "string",
662 Value::Symbol(_) => "symbol",
663 Value::BigInt(_) => "bigint",
664 Value::Object(object) => {
665 if object.is_callable() {
666 "function"
667 } else {
668 "object"
669 }
670 }
671 Value::Uninitialized
674 | Value::Hole
675 | Value::CatchOffset(_)
676 | Value::ReturnAddress(_) => "undefined",
677 }
678 }
679
680 pub fn to_boolean(&self) -> bool {
682 match self {
683 Value::Undefined | Value::Null => false,
684 Value::Bool(b) => *b,
685 Value::Int(i) => *i != 0,
686 Value::Float(f) => *f != 0.0 && !f.is_nan(),
688 Value::String(s) => !s.wtf8().is_empty(),
689 Value::Symbol(_) => true,
691 Value::BigInt(big) => !big.is_zero(),
695 Value::Object(_) => true,
697 Value::Uninitialized
698 | Value::Hole
699 | Value::CatchOffset(_)
700 | Value::ReturnAddress(_) => false,
701 }
702 }
703
704 pub fn to_number(&self) -> f64 {
706 match self {
707 Value::Undefined => f64::NAN,
708 Value::Null => 0.0,
709 Value::Bool(b) => {
710 if *b {
711 1.0
712 } else {
713 0.0
714 }
715 }
716 Value::Int(i) => *i as f64,
717 Value::Float(f) => *f,
718 Value::String(s) => string_to_number(&s.to_string_lossy()),
719 Value::Symbol(_) => f64::NAN,
722 Value::BigInt(_) => f64::NAN,
723 Value::Object(_) => f64::NAN,
727 Value::Uninitialized
728 | Value::Hole
729 | Value::CatchOffset(_)
730 | Value::ReturnAddress(_) => f64::NAN,
731 }
732 }
733
734 pub fn to_int32(&self) -> i32 {
736 to_int32(self.to_number())
737 }
738
739 pub fn to_uint32(&self) -> u32 {
741 self.to_int32() as u32
742 }
743
744 pub fn to_js_string(&self) -> String {
751 match self {
752 Value::Undefined => "undefined".to_string(),
753 Value::Null => "null".to_string(),
754 Value::Bool(true) => "true".to_string(),
755 Value::Bool(false) => "false".to_string(),
756 Value::Int(i) => i.to_string(),
757 Value::Float(f) => number_to_string(*f),
758 Value::String(s) => s.to_string_lossy().into_owned(),
761 Value::BigInt(big) => big.to_decimal_string(),
762 Value::Symbol(s) => s.to_display_string(),
766 Value::Object(_) => "[object Object]".to_string(),
767 Value::Uninitialized
768 | Value::Hole
769 | Value::CatchOffset(_)
770 | Value::ReturnAddress(_) => "undefined".to_string(),
771 }
772 }
773
774 pub fn strict_equals(&self, other: &Value) -> bool {
776 match (self, other) {
777 (Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => true,
778 (Value::Bool(a), Value::Bool(b)) => a == b,
779 (Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) => {
781 let (a, b) = (self.to_number(), other.to_number());
782 a == b
783 }
784 (Value::String(a), Value::String(b)) => a.as_str() == b.as_str(),
785 (Value::BigInt(a), Value::BigInt(b)) => **a == **b,
788 (Value::Symbol(a), Value::Symbol(b)) => a.ptr_eq(b),
790 (Value::Object(a), Value::Object(b)) => a.ptr_eq(b),
792 _ => false,
793 }
794 }
795
796 pub fn same_value(&self, other: &Value) -> bool {
801 if let (Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) = (self, other) {
802 let (a, b) = (self.to_number(), other.to_number());
803 if a.is_nan() && b.is_nan() {
804 return true;
805 }
806 if a == 0.0 && b == 0.0 {
807 return a.is_sign_negative() == b.is_sign_negative();
808 }
809 return a == b;
810 }
811 self.strict_equals(other)
812 }
813
814 pub fn same_value_zero(&self, other: &Value) -> bool {
820 if let (Value::Float(a), Value::Float(b)) = (self, other)
821 && a.is_nan()
822 && b.is_nan()
823 {
824 return true;
825 }
826 self.strict_equals(other)
827 }
828
829 pub fn loose_equals(&self, other: &Value) -> bool {
835 if matches!(self, Value::Object(_)) || matches!(other, Value::Object(_)) {
836 return match (self, other) {
837 (Value::Object(a), Value::Object(b)) => a.ptr_eq(b),
838 _ => primitive_loose_equals(&self.primitive(), &other.primitive()),
839 };
840 }
841 match (self, other) {
842 (Value::Undefined | Value::Null, Value::Undefined | Value::Null) => true,
843 (Value::Undefined | Value::Null, _) | (_, Value::Undefined | Value::Null) => false,
844 (Value::String(a), Value::String(b)) => a.as_str() == b.as_str(),
845 (Value::Symbol(a), Value::Symbol(b)) => a.ptr_eq(b),
846 (Value::Bool(a), Value::Bool(b)) => a == b,
847 (Value::BigInt(a), Value::BigInt(b)) => **a == **b,
851 (Value::BigInt(a), Value::String(b)) | (Value::String(b), Value::BigInt(a)) => {
852 crate::bigint::BigInt::from_string(&b.to_string_lossy()).as_ref() == Some(&**a)
853 }
854 (Value::BigInt(a), other) => match other {
855 Value::Int(_) | Value::Float(_) => bigint_equals_number(a, other.to_number()),
856 Value::Bool(flag) => bigint_equals_number(a, if *flag { 1.0 } else { 0.0 }),
858 _ => false,
859 },
860 (other, Value::BigInt(b)) => match other {
861 Value::Int(_) | Value::Float(_) => bigint_equals_number(b, other.to_number()),
862 Value::Bool(flag) => bigint_equals_number(b, if *flag { 1.0 } else { 0.0 }),
863 _ => false,
864 },
865 _ => self.to_number() == other.to_number(),
868 }
869 }
870
871 fn primitive(&self) -> Primitive {
876 match self {
877 Value::Undefined => Primitive::Undefined,
878 Value::Null => Primitive::Null,
879 Value::Bool(b) => Primitive::Bool(*b),
880 Value::Int(i) => Primitive::Number(*i as f64),
881 Value::Float(f) => Primitive::Number(*f),
882 Value::String(s) => Primitive::String(s.to_string_lossy().into_owned()),
883 Value::Symbol(s) => Primitive::Symbol(s.clone()),
886 Value::BigInt(big) => Primitive::String(big.to_decimal_string()),
889 Value::Object(_) => Primitive::String(self.to_js_string()),
890 Value::Uninitialized
891 | Value::Hole
892 | Value::CatchOffset(_)
893 | Value::ReturnAddress(_) => Primitive::Undefined,
894 }
895 }
896}
897
898enum Primitive {
900 Undefined,
901 Null,
902 Bool(bool),
903 Number(f64),
904 String(String),
905 Symbol(Gc<JsSymbol>),
907}
908
909fn primitive_loose_equals(left: &Primitive, right: &Primitive) -> bool {
911 use Primitive::*;
912 match (left, right) {
913 (Undefined | Null, Undefined | Null) => true,
914 (Undefined | Null, _) | (_, Undefined | Null) => false,
915 (Symbol(a), Symbol(b)) => a.ptr_eq(b),
919 (Symbol(_), _) | (_, Symbol(_)) => false,
920 (String(a), String(b)) => a == b,
921 (Bool(a), Bool(b)) => a == b,
922 (Number(a), Number(b)) => a == b,
923 (String(s), Number(n)) | (Number(n), String(s)) => string_to_number(s) == *n,
926 (Bool(b), Number(n)) | (Number(n), Bool(b)) => (if *b { 1.0 } else { 0.0 }) == *n,
927 (Bool(b), String(s)) | (String(s), Bool(b)) => {
928 string_to_number(s) == (if *b { 1.0 } else { 0.0 })
929 }
930 }
931}
932
933fn bigint_equals_number(big: &crate::bigint::BigInt, number: f64) -> bool {
939 number.is_finite()
940 && number.fract() == 0.0
941 && crate::bigint::BigInt::from_f64_truncated(number) == *big
942}
943
944pub fn to_int32(value: f64) -> i32 {
949 if !value.is_finite() || value == 0.0 {
950 return 0;
951 }
952 let truncated = value.trunc();
953 let modulo = truncated.rem_euclid(4294967296.0);
954 let wrapped = if modulo >= 2147483648.0 {
955 modulo - 4294967296.0
956 } else {
957 modulo
958 };
959 wrapped as i32
960}
961
962pub fn string_to_number(text: &str) -> f64 {
968 let trimmed = text.trim();
969 if trimmed.is_empty() {
970 return 0.0;
971 }
972 if let Some(rest) = strip_radix_prefix(trimmed, "0x", "0X") {
973 return radix_number(rest, 16);
974 }
975 if let Some(rest) = strip_radix_prefix(trimmed, "0o", "0O") {
976 return radix_number(rest, 8);
977 }
978 if let Some(rest) = strip_radix_prefix(trimmed, "0b", "0B") {
979 return radix_number(rest, 2);
980 }
981 let (sign, digits) = match trimmed.strip_prefix(['+', '-']) {
982 Some(rest) => (&trimmed[..1], rest),
983 None => ("", trimmed),
984 };
985 if digits == "Infinity" {
987 return if sign == "-" {
988 f64::NEG_INFINITY
989 } else {
990 f64::INFINITY
991 };
992 }
993 if !is_decimal_literal(digits) {
997 return f64::NAN;
998 }
999 trimmed.parse::<f64>().unwrap_or(f64::NAN)
1000}
1001
1002fn strip_radix_prefix<'a>(text: &'a str, lower: &str, upper: &str) -> Option<&'a str> {
1003 text.strip_prefix(lower)
1004 .or_else(|| text.strip_prefix(upper))
1005}
1006
1007fn radix_number(digits: &str, radix: u32) -> f64 {
1008 if digits.is_empty() || !digits.chars().all(|c| c.is_digit(radix)) {
1009 return f64::NAN;
1010 }
1011 match u64::from_str_radix(digits, radix) {
1014 Ok(value) => value as f64,
1015 Err(_) => digits.chars().fold(0.0, |acc, c| {
1016 acc * radix as f64 + c.to_digit(radix).unwrap_or(0) as f64
1017 }),
1018 }
1019}
1020
1021fn is_decimal_literal(text: &str) -> bool {
1023 let bytes = text.as_bytes();
1024 let mut index = 0;
1025 let mut digits = 0;
1026 while index < bytes.len() && bytes[index].is_ascii_digit() {
1027 index += 1;
1028 digits += 1;
1029 }
1030 if index < bytes.len() && bytes[index] == b'.' {
1031 index += 1;
1032 while index < bytes.len() && bytes[index].is_ascii_digit() {
1033 index += 1;
1034 digits += 1;
1035 }
1036 }
1037 if digits == 0 {
1038 return false;
1039 }
1040 if index < bytes.len() && (bytes[index] == b'e' || bytes[index] == b'E') {
1041 index += 1;
1042 if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
1043 index += 1;
1044 }
1045 let start = index;
1046 while index < bytes.len() && bytes[index].is_ascii_digit() {
1047 index += 1;
1048 }
1049 if index == start {
1050 return false;
1051 }
1052 }
1053 index == bytes.len()
1054}
1055
1056pub fn number_to_string(value: f64) -> String {
1064 if value.is_nan() {
1065 return "NaN".to_string();
1066 }
1067 if value.is_infinite() {
1068 return if value > 0.0 {
1069 "Infinity".to_string()
1070 } else {
1071 "-Infinity".to_string()
1072 };
1073 }
1074 if value == 0.0 {
1075 return "0".to_string();
1078 }
1079 let magnitude = value.abs();
1080 if magnitude >= 1e21 || magnitude < 1e-6 {
1081 return normalise_exponent(format!("{value:e}"));
1082 }
1083 format!("{value}")
1084}
1085
1086pub fn number_to_string_for_print(value: f64) -> String {
1093 if value == 0.0 && value.is_sign_negative() {
1094 return "-0".to_string();
1095 }
1096 number_to_string(value)
1097}
1098
1099fn normalise_exponent(text: String) -> String {
1104 let Some((mantissa, exponent)) = text.split_once('e') else {
1105 return text;
1106 };
1107 if exponent.starts_with('-') {
1108 text
1109 } else {
1110 let digits = exponent.strip_prefix('+').unwrap_or(exponent);
1111 format!("{mantissa}e+{digits}")
1112 }
1113}
1114
1115impl Trace for Value {
1116 fn trace(&self, tracer: &mut Tracer) {
1117 match self {
1118 Value::String(s) => tracer.visit(s),
1119 Value::Object(o) => tracer.visit(o),
1120 Value::Symbol(s) => tracer.visit(s),
1121 _ => {}
1122 }
1123 }
1124}
1125
1126impl fmt::Debug for Value {
1127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1128 match self {
1129 Value::Undefined => f.write_str("undefined"),
1130 Value::Null => f.write_str("null"),
1131 Value::Bool(b) => write!(f, "{b}"),
1132 Value::Int(i) => write!(f, "{i}"),
1133 Value::Float(x) => write!(f, "{}", number_to_string(*x)),
1134 Value::String(s) => write!(f, "{:?}", s.as_str()),
1135 Value::Object(_) => f.write_str("[object]"),
1136 Value::Symbol(s) => f.write_str(&s.to_display_string()),
1137 Value::BigInt(big) => write!(f, "{}n", big.to_decimal_string()),
1138 Value::Uninitialized => f.write_str("<uninitialised>"),
1139 Value::Hole => f.write_str("<hole>"),
1140 Value::CatchOffset(offset) => write!(f, "<catch {offset}>"),
1141 Value::ReturnAddress(address) => write!(f, "<ret {address}>"),
1142 }
1143 }
1144}
1145
1146#[cfg(test)]
1147mod tests {
1148 use super::*;
1149
1150 #[test]
1151 fn int32_wraps_the_way_the_spec_says() {
1152 assert_eq!(to_int32(0.0), 0);
1153 assert_eq!(to_int32(f64::NAN), 0);
1154 assert_eq!(to_int32(f64::INFINITY), 0);
1155 assert_eq!(to_int32(1.9), 1);
1156 assert_eq!(to_int32(-1.9), -1);
1157 assert_eq!(to_int32(2147483648.0), -2147483648);
1158 assert_eq!(to_int32(4294967296.0), 0);
1159 assert_eq!(to_int32(-4294967297.0), -1);
1160 }
1161
1162 #[test]
1163 fn numbers_print_like_javascript() {
1164 assert_eq!(number_to_string(0.0), "0");
1165 assert_eq!(number_to_string(-0.0), "0");
1166 assert_eq!(number_to_string(1.0), "1");
1167 assert_eq!(number_to_string(-1.5), "-1.5");
1168 assert_eq!(number_to_string(1e21), "1e+21");
1169 assert_eq!(number_to_string(1e-7), "1e-7");
1170 assert_eq!(number_to_string(1e-6), "0.000001");
1171 assert_eq!(number_to_string(1e20), "100000000000000000000");
1172 assert_eq!(number_to_string(5e-324), "5e-324");
1173 assert_eq!(number_to_string_for_print(-0.0), "-0");
1175 assert_eq!(number_to_string(f64::NAN), "NaN");
1176 assert_eq!(number_to_string(f64::INFINITY), "Infinity");
1177 assert_eq!(number_to_string(f64::NEG_INFINITY), "-Infinity");
1178 }
1179
1180 #[test]
1181 fn strings_parse_to_numbers_without_prefix_matching() {
1182 assert_eq!(string_to_number(""), 0.0);
1183 assert_eq!(string_to_number(" "), 0.0);
1184 assert_eq!(string_to_number(" 42 "), 42.0);
1185 assert_eq!(string_to_number("0x10"), 16.0);
1186 assert_eq!(string_to_number("0b101"), 5.0);
1187 assert_eq!(string_to_number("0o17"), 15.0);
1188 assert_eq!(string_to_number("Infinity"), f64::INFINITY);
1189 assert_eq!(string_to_number("-Infinity"), f64::NEG_INFINITY);
1190 assert_eq!(string_to_number("1e3"), 1000.0);
1191 assert_eq!(string_to_number(".5"), 0.5);
1192 assert_eq!(string_to_number("5."), 5.0);
1193 assert!(string_to_number("12px").is_nan());
1195 assert!(string_to_number("inf").is_nan());
1196 assert!(string_to_number("nan").is_nan());
1197 assert!(string_to_number("1e").is_nan());
1198 assert!(string_to_number("0x").is_nan());
1199 }
1200
1201 #[test]
1202 fn strict_equality_ignores_the_int_float_split() {
1203 assert!(Value::Int(1).strict_equals(&Value::Float(1.0)));
1204 assert!(!Value::Int(1).strict_equals(&Value::Float(1.5)));
1205 assert!(!Value::Float(f64::NAN).strict_equals(&Value::Float(f64::NAN)));
1206 assert!(Value::Int(0).strict_equals(&Value::Float(-0.0)));
1207 assert!(!Value::Int(0).strict_equals(&Value::Null));
1208 assert!(!Value::Undefined.strict_equals(&Value::Null));
1209 }
1210
1211 #[test]
1212 fn falsy_values_are_the_spec_list() {
1213 assert!(!Value::Undefined.to_boolean());
1214 assert!(!Value::Null.to_boolean());
1215 assert!(!Value::Bool(false).to_boolean());
1216 assert!(!Value::Int(0).to_boolean());
1217 assert!(!Value::Float(f64::NAN).to_boolean());
1218 assert!(!Value::Float(-0.0).to_boolean());
1219 assert!(Value::Float(0.1).to_boolean());
1220 }
1221}