1use std::cell::RefCell;
11use std::fmt;
12
13use js_gc::{Gc, Trace, Tracer};
14
15use crate::object::JsObject;
16
17pub struct JsString {
24 text: String,
25}
26
27impl JsString {
28 pub fn new(text: String) -> JsString {
30 JsString { text }
31 }
32
33 pub fn as_str(&self) -> &str {
35 &self.text
36 }
37
38 pub fn utf16_len(&self) -> usize {
41 self.text.encode_utf16().count()
42 }
43}
44
45impl Trace for JsString {
46 fn trace(&self, _tracer: &mut Tracer) {}
47}
48
49impl fmt::Debug for JsString {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 write!(f, "{:?}", self.text)
52 }
53}
54
55pub struct Cell {
63 value: RefCell<Value>,
64}
65
66impl Cell {
67 pub fn new(value: Value) -> Cell {
69 Cell {
70 value: RefCell::new(value),
71 }
72 }
73
74 pub fn get(&self) -> Value {
76 self.value.borrow().clone()
77 }
78
79 pub fn set(&self, value: Value) {
81 *self.value.borrow_mut() = value;
82 }
83}
84
85impl Trace for Cell {
86 fn trace(&self, tracer: &mut Tracer) {
87 self.value.borrow().trace(tracer);
88 }
89}
90
91#[derive(Clone)]
93pub enum Value {
94 Undefined,
96 Null,
98 Bool(bool),
100 Int(i32),
102 Float(f64),
104 String(Gc<JsString>),
106 Object(Gc<JsObject>),
108 CatchOffset(u32),
116 ReturnAddress(u32),
123 Hole,
131 Uninitialized,
138}
139
140impl Value {
141 pub fn string(heap: &js_gc::Heap, text: impl Into<String>) -> Value {
143 Value::String(Gc::new(heap, JsString::new(text.into())))
144 }
145
146 pub fn as_f64(&self) -> Option<f64> {
148 match self {
149 Value::Int(i) => Some(*i as f64),
150 Value::Float(f) => Some(*f),
151 _ => None,
152 }
153 }
154
155 pub fn as_str(&self) -> Option<&str> {
157 match self {
158 Value::String(s) => Some(s.as_str()),
159 _ => None,
160 }
161 }
162
163 pub fn as_object(&self) -> Option<&Gc<JsObject>> {
165 match self {
166 Value::Object(o) => Some(o),
167 _ => None,
168 }
169 }
170
171 pub fn is_nullish(&self) -> bool {
173 matches!(self, Value::Undefined | Value::Null)
174 }
175
176 pub fn type_of(&self) -> &'static str {
178 match self {
179 Value::Undefined => "undefined",
180 Value::Null => "object",
181 Value::Bool(_) => "boolean",
182 Value::Int(_) | Value::Float(_) => "number",
183 Value::String(_) => "string",
184 Value::Object(object) => {
185 if object.is_callable() {
186 "function"
187 } else {
188 "object"
189 }
190 }
191 Value::Uninitialized
194 | Value::Hole
195 | Value::CatchOffset(_)
196 | Value::ReturnAddress(_) => "undefined",
197 }
198 }
199
200 pub fn to_boolean(&self) -> bool {
202 match self {
203 Value::Undefined | Value::Null => false,
204 Value::Bool(b) => *b,
205 Value::Int(i) => *i != 0,
206 Value::Float(f) => *f != 0.0 && !f.is_nan(),
208 Value::String(s) => !s.as_str().is_empty(),
209 Value::Object(_) => true,
211 Value::Uninitialized
212 | Value::Hole
213 | Value::CatchOffset(_)
214 | Value::ReturnAddress(_) => false,
215 }
216 }
217
218 pub fn to_number(&self) -> f64 {
220 match self {
221 Value::Undefined => f64::NAN,
222 Value::Null => 0.0,
223 Value::Bool(b) => {
224 if *b {
225 1.0
226 } else {
227 0.0
228 }
229 }
230 Value::Int(i) => *i as f64,
231 Value::Float(f) => *f,
232 Value::String(s) => string_to_number(s.as_str()),
233 Value::Object(_) => f64::NAN,
237 Value::Uninitialized
238 | Value::Hole
239 | Value::CatchOffset(_)
240 | Value::ReturnAddress(_) => f64::NAN,
241 }
242 }
243
244 pub fn to_int32(&self) -> i32 {
246 to_int32(self.to_number())
247 }
248
249 pub fn to_uint32(&self) -> u32 {
251 self.to_int32() as u32
252 }
253
254 pub fn to_js_string(&self) -> String {
261 match self {
262 Value::Undefined => "undefined".to_string(),
263 Value::Null => "null".to_string(),
264 Value::Bool(true) => "true".to_string(),
265 Value::Bool(false) => "false".to_string(),
266 Value::Int(i) => i.to_string(),
267 Value::Float(f) => number_to_string(*f),
268 Value::String(s) => s.as_str().to_string(),
269 Value::Object(_) => "[object Object]".to_string(),
270 Value::Uninitialized
271 | Value::Hole
272 | Value::CatchOffset(_)
273 | Value::ReturnAddress(_) => "undefined".to_string(),
274 }
275 }
276
277 pub fn strict_equals(&self, other: &Value) -> bool {
279 match (self, other) {
280 (Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => true,
281 (Value::Bool(a), Value::Bool(b)) => a == b,
282 (Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) => {
284 let (a, b) = (self.to_number(), other.to_number());
285 a == b
286 }
287 (Value::String(a), Value::String(b)) => a.as_str() == b.as_str(),
288 (Value::Object(a), Value::Object(b)) => a.ptr_eq(b),
290 _ => false,
291 }
292 }
293
294 pub fn loose_equals(&self, other: &Value) -> bool {
300 if matches!(self, Value::Object(_)) || matches!(other, Value::Object(_)) {
301 return match (self, other) {
302 (Value::Object(a), Value::Object(b)) => a.ptr_eq(b),
303 _ => primitive_loose_equals(&self.primitive(), &other.primitive()),
304 };
305 }
306 match (self, other) {
307 (Value::Undefined | Value::Null, Value::Undefined | Value::Null) => true,
308 (Value::Undefined | Value::Null, _) | (_, Value::Undefined | Value::Null) => false,
309 (Value::String(a), Value::String(b)) => a.as_str() == b.as_str(),
310 (Value::Bool(a), Value::Bool(b)) => a == b,
311 _ => self.to_number() == other.to_number(),
314 }
315 }
316
317 fn primitive(&self) -> Primitive {
322 match self {
323 Value::Undefined => Primitive::Undefined,
324 Value::Null => Primitive::Null,
325 Value::Bool(b) => Primitive::Bool(*b),
326 Value::Int(i) => Primitive::Number(*i as f64),
327 Value::Float(f) => Primitive::Number(*f),
328 Value::String(s) => Primitive::String(s.as_str().to_string()),
329 Value::Object(_) => Primitive::String(self.to_js_string()),
330 Value::Uninitialized
331 | Value::Hole
332 | Value::CatchOffset(_)
333 | Value::ReturnAddress(_) => Primitive::Undefined,
334 }
335 }
336}
337
338enum Primitive {
340 Undefined,
341 Null,
342 Bool(bool),
343 Number(f64),
344 String(String),
345}
346
347fn primitive_loose_equals(left: &Primitive, right: &Primitive) -> bool {
349 use Primitive::*;
350 match (left, right) {
351 (Undefined | Null, Undefined | Null) => true,
352 (Undefined | Null, _) | (_, Undefined | Null) => false,
353 (String(a), String(b)) => a == b,
354 (Bool(a), Bool(b)) => a == b,
355 (Number(a), Number(b)) => a == b,
356 (String(s), Number(n)) | (Number(n), String(s)) => string_to_number(s) == *n,
359 (Bool(b), Number(n)) | (Number(n), Bool(b)) => (if *b { 1.0 } else { 0.0 }) == *n,
360 (Bool(b), String(s)) | (String(s), Bool(b)) => {
361 string_to_number(s) == (if *b { 1.0 } else { 0.0 })
362 }
363 }
364}
365
366pub fn to_int32(value: f64) -> i32 {
371 if !value.is_finite() || value == 0.0 {
372 return 0;
373 }
374 let truncated = value.trunc();
375 let modulo = truncated.rem_euclid(4294967296.0);
376 let wrapped = if modulo >= 2147483648.0 {
377 modulo - 4294967296.0
378 } else {
379 modulo
380 };
381 wrapped as i32
382}
383
384pub fn string_to_number(text: &str) -> f64 {
390 let trimmed = text.trim();
391 if trimmed.is_empty() {
392 return 0.0;
393 }
394 if let Some(rest) = strip_radix_prefix(trimmed, "0x", "0X") {
395 return radix_number(rest, 16);
396 }
397 if let Some(rest) = strip_radix_prefix(trimmed, "0o", "0O") {
398 return radix_number(rest, 8);
399 }
400 if let Some(rest) = strip_radix_prefix(trimmed, "0b", "0B") {
401 return radix_number(rest, 2);
402 }
403 let (sign, digits) = match trimmed.strip_prefix(['+', '-']) {
404 Some(rest) => (&trimmed[..1], rest),
405 None => ("", trimmed),
406 };
407 if digits == "Infinity" {
409 return if sign == "-" {
410 f64::NEG_INFINITY
411 } else {
412 f64::INFINITY
413 };
414 }
415 if !is_decimal_literal(digits) {
419 return f64::NAN;
420 }
421 trimmed.parse::<f64>().unwrap_or(f64::NAN)
422}
423
424fn strip_radix_prefix<'a>(text: &'a str, lower: &str, upper: &str) -> Option<&'a str> {
425 text.strip_prefix(lower)
426 .or_else(|| text.strip_prefix(upper))
427}
428
429fn radix_number(digits: &str, radix: u32) -> f64 {
430 if digits.is_empty() || !digits.chars().all(|c| c.is_digit(radix)) {
431 return f64::NAN;
432 }
433 match u64::from_str_radix(digits, radix) {
436 Ok(value) => value as f64,
437 Err(_) => digits.chars().fold(0.0, |acc, c| {
438 acc * radix as f64 + c.to_digit(radix).unwrap_or(0) as f64
439 }),
440 }
441}
442
443fn is_decimal_literal(text: &str) -> bool {
445 let bytes = text.as_bytes();
446 let mut index = 0;
447 let mut digits = 0;
448 while index < bytes.len() && bytes[index].is_ascii_digit() {
449 index += 1;
450 digits += 1;
451 }
452 if index < bytes.len() && bytes[index] == b'.' {
453 index += 1;
454 while index < bytes.len() && bytes[index].is_ascii_digit() {
455 index += 1;
456 digits += 1;
457 }
458 }
459 if digits == 0 {
460 return false;
461 }
462 if index < bytes.len() && (bytes[index] == b'e' || bytes[index] == b'E') {
463 index += 1;
464 if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
465 index += 1;
466 }
467 let start = index;
468 while index < bytes.len() && bytes[index].is_ascii_digit() {
469 index += 1;
470 }
471 if index == start {
472 return false;
473 }
474 }
475 index == bytes.len()
476}
477
478pub fn number_to_string(value: f64) -> String {
486 if value.is_nan() {
487 return "NaN".to_string();
488 }
489 if value.is_infinite() {
490 return if value > 0.0 {
491 "Infinity".to_string()
492 } else {
493 "-Infinity".to_string()
494 };
495 }
496 if value == 0.0 {
497 return "0".to_string();
500 }
501 let magnitude = value.abs();
502 if magnitude >= 1e21 || magnitude < 1e-6 {
503 return normalise_exponent(format!("{value:e}"));
504 }
505 format!("{value}")
506}
507
508pub fn number_to_string_for_print(value: f64) -> String {
515 if value == 0.0 && value.is_sign_negative() {
516 return "-0".to_string();
517 }
518 number_to_string(value)
519}
520
521fn normalise_exponent(text: String) -> String {
526 let Some((mantissa, exponent)) = text.split_once('e') else {
527 return text;
528 };
529 if exponent.starts_with('-') {
530 text
531 } else {
532 let digits = exponent.strip_prefix('+').unwrap_or(exponent);
533 format!("{mantissa}e+{digits}")
534 }
535}
536
537impl Trace for Value {
538 fn trace(&self, tracer: &mut Tracer) {
539 match self {
540 Value::String(s) => tracer.visit(s),
541 Value::Object(o) => tracer.visit(o),
542 _ => {}
543 }
544 }
545}
546
547impl fmt::Debug for Value {
548 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
549 match self {
550 Value::Undefined => f.write_str("undefined"),
551 Value::Null => f.write_str("null"),
552 Value::Bool(b) => write!(f, "{b}"),
553 Value::Int(i) => write!(f, "{i}"),
554 Value::Float(x) => write!(f, "{}", number_to_string(*x)),
555 Value::String(s) => write!(f, "{:?}", s.as_str()),
556 Value::Object(_) => f.write_str("[object]"),
557 Value::Uninitialized => f.write_str("<uninitialised>"),
558 Value::Hole => f.write_str("<hole>"),
559 Value::CatchOffset(offset) => write!(f, "<catch {offset}>"),
560 Value::ReturnAddress(address) => write!(f, "<ret {address}>"),
561 }
562 }
563}
564
565#[cfg(test)]
566mod tests {
567 use super::*;
568
569 #[test]
570 fn int32_wraps_the_way_the_spec_says() {
571 assert_eq!(to_int32(0.0), 0);
572 assert_eq!(to_int32(f64::NAN), 0);
573 assert_eq!(to_int32(f64::INFINITY), 0);
574 assert_eq!(to_int32(1.9), 1);
575 assert_eq!(to_int32(-1.9), -1);
576 assert_eq!(to_int32(2147483648.0), -2147483648);
577 assert_eq!(to_int32(4294967296.0), 0);
578 assert_eq!(to_int32(-4294967297.0), -1);
579 }
580
581 #[test]
582 fn numbers_print_like_javascript() {
583 assert_eq!(number_to_string(0.0), "0");
584 assert_eq!(number_to_string(-0.0), "0");
585 assert_eq!(number_to_string(1.0), "1");
586 assert_eq!(number_to_string(-1.5), "-1.5");
587 assert_eq!(number_to_string(1e21), "1e+21");
588 assert_eq!(number_to_string(1e-7), "1e-7");
589 assert_eq!(number_to_string(1e-6), "0.000001");
590 assert_eq!(number_to_string(1e20), "100000000000000000000");
591 assert_eq!(number_to_string(5e-324), "5e-324");
592 assert_eq!(number_to_string_for_print(-0.0), "-0");
594 assert_eq!(number_to_string(f64::NAN), "NaN");
595 assert_eq!(number_to_string(f64::INFINITY), "Infinity");
596 assert_eq!(number_to_string(f64::NEG_INFINITY), "-Infinity");
597 }
598
599 #[test]
600 fn strings_parse_to_numbers_without_prefix_matching() {
601 assert_eq!(string_to_number(""), 0.0);
602 assert_eq!(string_to_number(" "), 0.0);
603 assert_eq!(string_to_number(" 42 "), 42.0);
604 assert_eq!(string_to_number("0x10"), 16.0);
605 assert_eq!(string_to_number("0b101"), 5.0);
606 assert_eq!(string_to_number("0o17"), 15.0);
607 assert_eq!(string_to_number("Infinity"), f64::INFINITY);
608 assert_eq!(string_to_number("-Infinity"), f64::NEG_INFINITY);
609 assert_eq!(string_to_number("1e3"), 1000.0);
610 assert_eq!(string_to_number(".5"), 0.5);
611 assert_eq!(string_to_number("5."), 5.0);
612 assert!(string_to_number("12px").is_nan());
614 assert!(string_to_number("inf").is_nan());
615 assert!(string_to_number("nan").is_nan());
616 assert!(string_to_number("1e").is_nan());
617 assert!(string_to_number("0x").is_nan());
618 }
619
620 #[test]
621 fn strict_equality_ignores_the_int_float_split() {
622 assert!(Value::Int(1).strict_equals(&Value::Float(1.0)));
623 assert!(!Value::Int(1).strict_equals(&Value::Float(1.5)));
624 assert!(!Value::Float(f64::NAN).strict_equals(&Value::Float(f64::NAN)));
625 assert!(Value::Int(0).strict_equals(&Value::Float(-0.0)));
626 assert!(!Value::Int(0).strict_equals(&Value::Null));
627 assert!(!Value::Undefined.strict_equals(&Value::Null));
628 }
629
630 #[test]
631 fn falsy_values_are_the_spec_list() {
632 assert!(!Value::Undefined.to_boolean());
633 assert!(!Value::Null.to_boolean());
634 assert!(!Value::Bool(false).to_boolean());
635 assert!(!Value::Int(0).to_boolean());
636 assert!(!Value::Float(f64::NAN).to_boolean());
637 assert!(!Value::Float(-0.0).to_boolean());
638 assert!(Value::Float(0.1).to_boolean());
639 }
640}