1use alloc::boxed::Box;
7use indexmap::IndexMap;
8use alloc::format;
9use alloc::rc::Rc;
10use alloc::string::String;
11use alloc::vec::Vec;
12use core::cell::RefCell;
13
14use super::ast::Param;
15use super::bigint::BigInt;
16use super::interp::{Interp, Scope};
17
18pub use crate::os_lib::util::fnv::FnvHasher;
19#[repr(C, align(8))]
28pub struct PropKey {
29 data: [u8; 16],
30}
31
32pub const PROP_KEY_INLINE: usize = 15;
33
34impl PropKey {
35 #[inline(always)]
36 pub fn is_inline(&self) -> bool {
37 (self.data[0] & 1) != 0
38 }
39
40 #[inline(always)]
41 pub fn is_shared(&self) -> bool {
42 (self.data[0] & 1) == 0
43 }
44
45 #[inline]
46 fn inline_from_str(s: &str) -> Self {
47 let mut data = [0u8; 16];
48 let len = s.len();
49 data[0] = ((len as u8) << 1) | 1;
50 if let Some(d) = data.get_mut(1..1 + len) {
51 d.copy_from_slice(s.as_bytes());
52 }
53 PropKey { data }
54 }
55
56 #[inline]
57 fn shared_from_rc(rc: Rc<str>) -> Self {
58 let len = rc.len();
59 let raw: *const str = Rc::into_raw(rc);
60 let ptr = raw as *const u8 as usize;
61 debug_assert_eq!(ptr & 1, 0, "Rc<str> data pointer must be aligned");
62 let mut data = [0u8; 16];
63 data[0..8].copy_from_slice(&ptr.to_le_bytes());
64 data[8..16].copy_from_slice(&len.to_le_bytes());
65 PropKey { data }
66 }
67
68 #[inline(always)]
69 fn raw_rc_ptr(&self) -> *const str {
70 let ptr = usize::from_le_bytes([
71 self.data[0],
72 self.data[1],
73 self.data[2],
74 self.data[3],
75 self.data[4],
76 self.data[5],
77 self.data[6],
78 self.data[7],
79 ]) as *const u8;
80 let len = usize::from_le_bytes([
81 self.data[8],
82 self.data[9],
83 self.data[10],
84 self.data[11],
85 self.data[12],
86 self.data[13],
87 self.data[14],
88 self.data[15],
89 ]);
90 core::ptr::slice_from_raw_parts(ptr, len) as *const str
91 }
92
93 #[inline]
94 pub fn as_str(&self) -> &str {
95 if self.is_inline() {
96 let len = (self.data[0] >> 1) as usize;
97 unsafe { core::str::from_utf8_unchecked(self.data.get_unchecked(1..1 + len)) }
99 } else {
100 unsafe { &*self.raw_rc_ptr() }
102 }
103 }
104}
105
106impl Clone for PropKey {
107 #[inline]
108 fn clone(&self) -> Self {
109 if !self.is_inline() {
110 unsafe { Rc::increment_strong_count(self.raw_rc_ptr()) };
112 }
113 PropKey { data: self.data }
114 }
115}
116
117impl Drop for PropKey {
118 #[inline]
119 fn drop(&mut self) {
120 if !self.is_inline() {
121 unsafe { drop(Rc::from_raw(self.raw_rc_ptr())) };
123 }
124 }
125}
126
127impl From<&str> for PropKey {
128 #[inline]
129 fn from(s: &str) -> Self {
130 if s.len() <= PROP_KEY_INLINE {
131 Self::inline_from_str(s)
132 } else {
133 Self::shared_from_rc(Rc::from(s))
134 }
135 }
136}
137impl From<String> for PropKey {
138 #[inline]
139 fn from(s: String) -> Self {
140 if s.len() <= PROP_KEY_INLINE {
141 Self::inline_from_str(&s)
142 } else {
143 Self::shared_from_rc(Rc::from(s))
144 }
145 }
146}
147impl From<&String> for PropKey {
148 #[inline]
149 fn from(s: &String) -> Self {
150 s.as_str().into()
151 }
152}
153impl From<Rc<str>> for PropKey {
154 #[inline]
155 fn from(rc: Rc<str>) -> Self {
156 if rc.len() <= PROP_KEY_INLINE {
157 Self::inline_from_str(&rc)
158 } else {
159 Self::shared_from_rc(rc)
160 }
161 }
162}
163impl From<&Rc<str>> for PropKey {
164 #[inline]
165 fn from(rc: &Rc<str>) -> Self {
166 if rc.len() <= PROP_KEY_INLINE {
167 Self::inline_from_str(rc)
168 } else {
169 Self::shared_from_rc(rc.clone())
170 }
171 }
172}
173impl From<&PropKey> for PropKey {
174 #[inline]
175 fn from(s: &PropKey) -> Self {
176 s.clone()
177 }
178}
179impl From<PropKey> for String {
180 fn from(k: PropKey) -> String {
181 String::from(k.as_str())
182 }
183}
184impl core::ops::Deref for PropKey {
185 type Target = str;
186 #[inline]
187 fn deref(&self) -> &str {
188 self.as_str()
189 }
190}
191impl core::borrow::Borrow<str> for PropKey {
192 #[inline]
193 fn borrow(&self) -> &str {
194 self.as_str()
195 }
196}
197impl PartialEq for PropKey {
198 #[inline]
199 fn eq(&self, o: &Self) -> bool {
200 if self.data == o.data {
201 return true;
202 }
203 if self.is_inline() || o.is_inline() {
204 return false;
205 }
206 self.as_str() == o.as_str()
207 }
208}
209impl Eq for PropKey {}
210impl PartialEq<str> for PropKey {
211 #[inline]
212 fn eq(&self, o: &str) -> bool {
213 self.as_str() == o
214 }
215}
216impl PartialEq<&str> for PropKey {
217 #[inline]
218 fn eq(&self, o: &&str) -> bool {
219 self.as_str() == *o
220 }
221}
222impl PartialEq<String> for PropKey {
223 #[inline]
224 fn eq(&self, o: &String) -> bool {
225 self.as_str() == o.as_str()
226 }
227}
228impl core::hash::Hash for PropKey {
229 #[inline]
230 fn hash<H: core::hash::Hasher>(&self, h: &mut H) {
231 self.as_str().hash(h)
232 }
233}
234impl core::fmt::Debug for PropKey {
235 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
236 core::fmt::Debug::fmt(self.as_str(), f)
237 }
238}
239impl core::fmt::Display for PropKey {
240 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
241 f.write_str(self.as_str())
242 }
243}
244
245pub type PropMap<V> = SmallPropMap<V>;
247
248type BigPropMap<V> = IndexMap<PropKey, V, core::hash::BuildHasherDefault<FnvHasher>>;
249
250const SMALL_PROPS_MAX: usize = 8;
252
253pub(crate) struct NameQ<'a>(pub &'a str);
256
257impl core::hash::Hash for NameQ<'_> {
258 fn hash<H: core::hash::Hasher>(&self, h: &mut H) {
259 self.0.hash(h)
260 }
261}
262
263impl indexmap::Equivalent<Rc<str>> for NameQ<'_> {
264 fn equivalent(&self, key: &Rc<str>) -> bool {
265 key_eq(self.0, key)
266 }
267}
268
269#[inline(always)]
272pub(crate) fn key_eq(a: &str, b: &str) -> bool {
273 let (a, b) = (a.as_bytes(), b.as_bytes());
274 if a.len() != b.len() {
275 return false;
276 }
277 let n = a.len();
280 let w8 = |s: &[u8], at: usize| s.get(at..at + 8).and_then(|x| <[u8; 8]>::try_from(x).ok()).map(u64::from_ne_bytes);
281 let w4 = |s: &[u8], at: usize| s.get(at..at + 4).and_then(|x| <[u8; 4]>::try_from(x).ok()).map(u32::from_ne_bytes);
282 match n {
283 0 => true,
284 1..=3 => a.first() == b.first() && a.get(n / 2) == b.get(n / 2) && a.last() == b.last(),
285 4..=7 => w4(a, 0) == w4(b, 0) && w4(a, n - 4) == w4(b, n - 4),
286 8..=16 => w8(a, 0) == w8(b, 0) && w8(a, n - 8) == w8(b, n - 8),
287 _ => a == b,
288 }
289}
290
291#[derive(Clone)]
298pub enum SmallPropMap<V> {
299 Small(Vec<(PropKey, V)>),
300 Big(Box<BigPropMap<V>>),
301}
302
303impl<V> Default for SmallPropMap<V> {
304 fn default() -> Self {
305 SmallPropMap::Small(Vec::new())
306 }
307}
308
309impl<V: core::fmt::Debug> core::fmt::Debug for SmallPropMap<V> {
310 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
311 f.debug_map().entries(self.iter()).finish()
312 }
313}
314
315impl<V> SmallPropMap<V> {
316 #[inline]
317 fn small_pos(v: &[(PropKey, V)], k: &str) -> Option<usize> {
318 v.iter().position(|(key, _)| key_eq(key.as_str(), k))
319 }
320 #[inline]
322 pub fn get_index_of(&self, k: &str) -> Option<usize> {
323 match self {
324 SmallPropMap::Small(v) => Self::small_pos(v, k),
325 SmallPropMap::Big(m) => m.get_index_of(k),
326 }
327 }
328 #[inline]
329 pub fn get(&self, k: &str) -> Option<&V> {
330 match self {
331 SmallPropMap::Small(v) => v.iter().find(|(key, _)| key_eq(key.as_str(), k)).map(|(_, x)| x),
332 SmallPropMap::Big(m) => m.get(k),
333 }
334 }
335 pub fn get_mut(&mut self, k: &str) -> Option<&mut V> {
336 match self {
337 SmallPropMap::Small(v) => v.iter_mut().find(|(key, _)| key_eq(key.as_str(), k)).map(|(_, x)| x),
338 SmallPropMap::Big(m) => m.get_mut(k),
339 }
340 }
341 #[inline]
342 pub fn contains_key(&self, k: &str) -> bool {
343 self.get(k).is_some()
344 }
345 pub fn insert(&mut self, k: PropKey, val: V) -> Option<V> {
347 match self {
348 SmallPropMap::Small(v) => {
349 if let Some(i) = Self::small_pos(v, &k) {
350 return Some(core::mem::replace(&mut v[i].1, val));
351 }
352 if v.len() < SMALL_PROPS_MAX {
353 v.push((k, val));
354 return None;
355 }
356 let mut m: BigPropMap<V> = BigPropMap::default();
357 m.reserve(v.len() + 1);
358 for (key, x) in v.drain(..) {
359 m.insert(key, x);
360 }
361 m.insert(k, val);
362 *self = SmallPropMap::Big(Box::new(m));
363 None
364 }
365 SmallPropMap::Big(m) => m.insert(k, val),
366 }
367 }
368 pub fn shift_remove(&mut self, k: &str) -> Option<V> {
370 match self {
371 SmallPropMap::Small(v) => Self::small_pos(v, k).map(|i| v.remove(i).1),
372 SmallPropMap::Big(m) => m.shift_remove(k),
373 }
374 }
375 pub fn swap_remove(&mut self, k: &str) -> Option<V> {
377 match self {
378 SmallPropMap::Small(v) => Self::small_pos(v, k).map(|i| v.swap_remove(i).1),
379 SmallPropMap::Big(m) => m.swap_remove(k),
380 }
381 }
382 pub fn clear(&mut self) {
383 *self = SmallPropMap::Small(Vec::new());
384 }
385 #[inline]
386 pub fn len(&self) -> usize {
387 match self {
388 SmallPropMap::Small(v) => v.len(),
389 SmallPropMap::Big(m) => m.len(),
390 }
391 }
392 #[inline]
393 pub fn is_empty(&self) -> bool {
394 self.len() == 0
395 }
396 pub fn iter(&self) -> PropIter<'_, V> {
397 match self {
398 SmallPropMap::Small(v) => PropIter::Small(v.iter()),
399 SmallPropMap::Big(m) => PropIter::Big(m.iter()),
400 }
401 }
402 pub fn keys(&self) -> impl DoubleEndedIterator<Item = &PropKey> {
403 self.iter().map(|(k, _)| k)
404 }
405 pub fn values(&self) -> impl DoubleEndedIterator<Item = &V> {
406 self.iter().map(|(_, v)| v)
407 }
408 pub fn into_values(self) -> impl Iterator<Item = V> {
409 self.into_iter().map(|(_, v)| v)
410 }
411 pub fn entry(&mut self, k: PropKey) -> PropEntry<'_, V> {
413 PropEntry { map: self, key: k }
414 }
415 pub fn get_index(&self, i: usize) -> Option<(&PropKey, &V)> {
417 match self {
418 SmallPropMap::Small(v) => v.get(i).map(|(k, x)| (k, x)),
419 SmallPropMap::Big(m) => m.get_index(i),
420 }
421 }
422}
423
424pub struct PropEntry<'a, V> {
426 map: &'a mut SmallPropMap<V>,
427 key: PropKey,
428}
429
430impl<'a, V> PropEntry<'a, V> {
431 pub fn or_insert_with<F: FnOnce() -> V>(self, f: F) -> &'a mut V {
432 let PropEntry { map, key } = self;
433 let i = match map {
434 SmallPropMap::Small(v) => SmallPropMap::small_pos(v, &key),
435 SmallPropMap::Big(m) => m.get_index_of(key.as_str()),
436 };
437 let i = match i {
439 Some(i) => i,
440 None => {
441 map.insert(key, f());
442 map.len() - 1
443 }
444 };
445 match map {
446 SmallPropMap::Small(v) => &mut v[i].1,
447 SmallPropMap::Big(m) => &mut m[i],
448 }
449 }
450 pub fn or_insert(self, v: V) -> &'a mut V {
451 self.or_insert_with(|| v)
452 }
453 pub fn or_default(self) -> &'a mut V
454 where
455 V: Default,
456 {
457 self.or_insert_with(V::default)
458 }
459}
460
461pub enum PropIter<'a, V> {
463 Small(core::slice::Iter<'a, (PropKey, V)>),
464 Big(indexmap::map::Iter<'a, PropKey, V>),
465}
466
467impl<'a, V> Iterator for PropIter<'a, V> {
468 type Item = (&'a PropKey, &'a V);
469 #[inline]
470 fn next(&mut self) -> Option<Self::Item> {
471 match self {
472 PropIter::Small(it) => it.next().map(|(k, v)| (k, v)),
473 PropIter::Big(it) => it.next(),
474 }
475 }
476 fn size_hint(&self) -> (usize, Option<usize>) {
477 match self {
478 PropIter::Small(it) => it.size_hint(),
479 PropIter::Big(it) => it.size_hint(),
480 }
481 }
482}
483
484impl<'a, V> DoubleEndedIterator for PropIter<'a, V> {
485 fn next_back(&mut self) -> Option<Self::Item> {
486 match self {
487 PropIter::Small(it) => it.next_back().map(|(k, v)| (k, v)),
488 PropIter::Big(it) => it.next_back(),
489 }
490 }
491}
492
493impl<'a, V> ExactSizeIterator for PropIter<'a, V> {}
494
495impl<'a, V> IntoIterator for &'a SmallPropMap<V> {
496 type Item = (&'a PropKey, &'a V);
497 type IntoIter = PropIter<'a, V>;
498 fn into_iter(self) -> Self::IntoIter {
499 self.iter()
500 }
501}
502
503pub enum PropIntoIter<V> {
505 Small(alloc::vec::IntoIter<(PropKey, V)>),
506 Big(indexmap::map::IntoIter<PropKey, V>),
507}
508
509impl<V> Iterator for PropIntoIter<V> {
510 type Item = (PropKey, V);
511 fn next(&mut self) -> Option<Self::Item> {
512 match self {
513 PropIntoIter::Small(it) => it.next(),
514 PropIntoIter::Big(it) => it.next(),
515 }
516 }
517}
518
519impl<V> IntoIterator for SmallPropMap<V> {
520 type Item = (PropKey, V);
521 type IntoIter = PropIntoIter<V>;
522 fn into_iter(self) -> Self::IntoIter {
523 match self {
524 SmallPropMap::Small(v) => PropIntoIter::Small(v.into_iter()),
525 SmallPropMap::Big(m) => PropIntoIter::Big((*m).into_iter()),
526 }
527 }
528}
529
530impl<V, K: Into<PropKey>> FromIterator<(K, V)> for SmallPropMap<V> {
531 fn from_iter<I: IntoIterator<Item = (K, V)>>(it: I) -> Self {
532 let mut m = SmallPropMap::default();
533 for (k, v) in it {
534 m.insert(k.into(), v);
535 }
536 m
537 }
538}
539#[derive(Clone)]
547pub struct BigVarMap<V> {
548 entries: Vec<(Rc<str>, V)>,
549 index: IndexMap<Rc<str>, usize, core::hash::BuildHasherDefault<FnvHasher>>,
550}
551
552#[derive(Clone)]
553pub enum VarMap<V> {
554 Small(Vec<(Rc<str>, V)>),
555 Big(Box<BigVarMap<V>>),
556}
557
558const VAR_INDEX_MIN: usize = 8;
560
561impl<V> Default for VarMap<V> {
562 fn default() -> Self {
563 VarMap::Small(Vec::new())
564 }
565}
566
567impl<V> VarMap<V> {
568 pub fn with_capacity(n: usize) -> Self {
569 if n == 0 {
570 VarMap::Small(Vec::new())
571 } else {
572 VarMap::Small(Vec::with_capacity(n))
573 }
574 }
575
576 #[inline(always)]
577 fn entries(&self) -> &[(Rc<str>, V)] {
578 match self {
579 VarMap::Small(v) => v,
580 VarMap::Big(b) => &b.entries,
581 }
582 }
583
584 #[inline(always)]
585 fn entries_vec_mut(&mut self) -> &mut Vec<(Rc<str>, V)> {
586 match self {
587 VarMap::Small(v) => v,
588 VarMap::Big(b) => &mut b.entries,
589 }
590 }
591
592 fn position(&self, k: &str) -> Option<usize> {
593 let entries = match self {
594 VarMap::Small(v) => v.as_slice(),
595 VarMap::Big(b) => return b.index.get(&NameQ(k)).copied(),
596 };
597 let kp = k.as_ptr();
600 if let Some(i) = entries.iter().position(|(n, _)| n.as_ptr() == kp && n.len() == k.len()) {
601 return Some(i);
602 }
603 let first = k.as_bytes().first();
604 entries.iter().position(|(n, _)| n.as_bytes().first() == first && key_eq(n, k))
605 }
606
607 pub fn get(&self, k: &str) -> Option<&V> {
608 self.position(k).and_then(|i| self.entries().get(i)).map(|(_, v)| v)
609 }
610
611 #[inline]
613 pub fn entry_at(&self, i: usize) -> Option<(&Rc<str>, &V)> {
614 self.entries().get(i).map(|(k, v)| (k, v))
615 }
616
617 pub fn position_of(&self, k: &str) -> Option<usize> {
619 self.position(k)
620 }
621
622 #[inline(always)]
624 pub fn entry_at_mut(&mut self, i: usize, key: *const u8) -> Option<&mut V> {
625 self.entries_vec_mut().get_mut(i).filter(|(n, _)| n.as_ptr() == key).map(|(_, v)| v)
626 }
627
628 pub fn get_mut(&mut self, k: &str) -> Option<&mut V> {
629 self.position(k).and_then(move |i| self.entries_vec_mut().get_mut(i)).map(|(_, v)| v)
630 }
631
632 pub fn contains_key(&self, k: &str) -> bool {
633 self.position(k).is_some()
634 }
635
636 pub fn insert(&mut self, k: Rc<str>, v: V) -> Option<V> {
638 if let Some(i) = self.position(&k) {
639 if let Some(slot) = self.entries_vec_mut().get_mut(i) {
640 return Some(core::mem::replace(&mut slot.1, v));
641 }
642 }
643 match self {
644 VarMap::Small(entries) => {
645 entries.push((k, v));
646 self.promote_if_big();
647 }
648 VarMap::Big(b) => {
649 let i = b.entries.len();
650 b.index.insert(k.clone(), i);
651 b.entries.push((k, v));
652 }
653 }
654 None
655 }
656
657 pub fn shift_remove(&mut self, k: &str) -> Option<V> {
659 let i = self.position(k)?;
660 let (_, v) = self.entries_vec_mut().remove(i);
661 if let VarMap::Big(b) = self {
662 if b.entries.len() <= VAR_INDEX_MIN {
663 let entries = core::mem::take(&mut b.entries);
664 *self = VarMap::Small(entries);
665 } else {
666 b.index.clear();
667 for (idx, (key, _)) in b.entries.iter().enumerate() {
668 b.index.insert(key.clone(), idx);
669 }
670 }
671 }
672 Some(v)
673 }
674
675 pub fn len(&self) -> usize {
676 self.entries().len()
677 }
678
679 pub fn is_empty(&self) -> bool {
680 self.entries().is_empty()
681 }
682
683 pub fn iter(&self) -> impl Iterator<Item = (&Rc<str>, &V)> {
684 self.entries().iter().map(|(k, v)| (k, v))
685 }
686
687 pub fn keys(&self) -> impl Iterator<Item = &Rc<str>> {
688 self.entries().iter().map(|(k, _)| k)
689 }
690
691 pub fn values(&self) -> impl Iterator<Item = &V> {
692 self.entries().iter().map(|(_, v)| v)
693 }
694
695 pub fn into_values(self) -> impl Iterator<Item = V> {
696 let entries = match self {
697 VarMap::Small(v) => v,
698 VarMap::Big(b) => b.entries,
699 };
700 entries.into_iter().map(|(_, v)| v)
701 }
702
703 pub fn clear_keep_capacity(&mut self) {
705 match self {
706 VarMap::Small(v) => v.clear(),
707 VarMap::Big(b) => {
708 let mut v = core::mem::take(&mut b.entries);
709 v.clear();
710 *self = VarMap::Small(v);
711 }
712 }
713 }
714
715 pub fn shrink_to_fit(&mut self) {
717 self.entries_vec_mut().shrink_to_fit();
718 }
719
720 pub fn ensure_capacity(&mut self, n: usize) {
722 let v = self.entries_vec_mut();
723 if v.capacity() < n {
724 v.reserve(n - v.len());
725 }
726 }
727
728 pub fn capacity(&self) -> usize {
729 self.entries().len().max(match self {
730 VarMap::Small(v) => v.capacity(),
731 VarMap::Big(b) => b.entries.capacity(),
732 })
733 }
734
735 #[inline(always)]
738 pub fn push_fresh_small(&mut self, k: Rc<str>, v: V) {
739 match self {
740 VarMap::Small(entries) => entries.push((k, v)),
741 VarMap::Big(_) => {
742 self.insert(k, v);
743 }
744 }
745 }
746
747 #[inline]
750 pub fn push_hoisted_missing(&mut self, k: &Rc<str>, n_prefix: usize, default_val: V) {
751 match self {
752 VarMap::Small(entries) => {
753 let kp = k.as_ptr();
754 let kl = k.len();
755 let first = k.as_bytes().first();
756 let prefix = &entries[..n_prefix.min(entries.len())];
757 let exists = prefix.iter().any(|(n, _)| {
758 (n.as_ptr() == kp && n.len() == kl)
759 || (n.as_bytes().first() == first && key_eq(n, k))
760 });
761 if !exists {
762 entries.push((k.clone(), default_val));
763 }
764 }
765 VarMap::Big(_) => {
766 if !self.contains_key(k) {
767 self.insert(k.clone(), default_val);
768 }
769 }
770 }
771 }
772
773 #[inline]
775 pub fn promote_if_big(&mut self) {
776 if let VarMap::Small(entries) = self {
777 if entries.len() > VAR_INDEX_MIN {
778 let entries = core::mem::take(entries);
779 let mut ix: IndexMap<Rc<str>, usize, core::hash::BuildHasherDefault<FnvHasher>> =
780 IndexMap::with_capacity_and_hasher(entries.len(), Default::default());
781 for (i, (key, _)) in entries.iter().enumerate() {
782 ix.insert(key.clone(), i);
783 }
784 *self = VarMap::Big(Box::new(BigVarMap { entries, index: ix }));
785 }
786 }
787 }
788}
789
790pub struct LazyPropMap<V>(Option<Box<PropMap<V>>>);
797
798impl<V> Default for LazyPropMap<V> {
799 fn default() -> Self {
800 LazyPropMap(None)
801 }
802}
803
804impl<V: Clone> Clone for LazyPropMap<V> {
805 fn clone(&self) -> Self {
806 LazyPropMap(self.0.clone())
807 }
808}
809
810impl<V> LazyPropMap<V> {
811 fn map_mut(&mut self) -> &mut PropMap<V> {
812 self.0.get_or_insert_with(|| Box::new(PropMap::default()))
813 }
814 pub fn get(&self, k: &str) -> Option<&V> {
815 self.0.as_ref()?.get(k)
816 }
817 pub fn get_mut(&mut self, k: &str) -> Option<&mut V> {
818 self.0.as_mut()?.get_mut(k)
819 }
820 pub fn contains_key(&self, k: &str) -> bool {
821 self.0.as_ref().is_some_and(|m| m.contains_key(k))
822 }
823 pub fn insert(&mut self, k: String, v: V) -> Option<V> {
824 self.map_mut().insert(k.into(), v)
825 }
826 pub fn entry(&mut self, k: String) -> PropEntry<'_, V> {
827 self.map_mut().entry(k.into())
828 }
829 pub fn remove(&mut self, k: &str) -> Option<V> {
831 self.0.as_mut()?.swap_remove(k)
832 }
833 pub fn shift_remove(&mut self, k: &str) -> Option<V> {
834 self.0.as_mut()?.shift_remove(k)
835 }
836 pub fn clear(&mut self) {
837 self.0 = None;
838 }
839 pub fn len(&self) -> usize {
840 self.0.as_ref().map_or(0, |m| m.len())
841 }
842 pub fn is_empty(&self) -> bool {
843 self.len() == 0
844 }
845 pub fn keys(&self) -> impl Iterator<Item = &PropKey> {
846 self.0.iter().flat_map(|m| m.keys())
847 }
848 pub fn iter(&self) -> impl Iterator<Item = (&PropKey, &V)> {
849 self.0.iter().flat_map(|m| m.iter())
850 }
851}
852
853impl<V> IntoIterator for LazyPropMap<V> {
854 type Item = (PropKey, V);
855 type IntoIter = core::iter::Flatten<core::option::IntoIter<PropMap<V>>>;
856 fn into_iter(self) -> Self::IntoIter {
857 self.0.map(|b| *b).into_iter().flatten()
858 }
859}
860
861pub struct LazyPropIter<'a, V>(Option<PropIter<'a, V>>);
863
864impl<'a, V> Iterator for LazyPropIter<'a, V> {
865 type Item = (&'a PropKey, &'a V);
866 fn next(&mut self) -> Option<Self::Item> {
867 self.0.as_mut()?.next()
868 }
869}
870
871impl<'a, V> IntoIterator for &'a LazyPropMap<V> {
872 type Item = (&'a PropKey, &'a V);
873 type IntoIter = LazyPropIter<'a, V>;
874 fn into_iter(self) -> Self::IntoIter {
875 LazyPropIter(self.0.as_ref().map(|m| m.iter()))
876 }
877}
878
879impl Drop for Obj {
880 fn drop(&mut self) {
881 #[cfg(target_os = "none")]
882 super::cycle_gc::untrack_obj(self.gc_slot);
883 }
884}
885
886pub const NO_GC_SLOT: u32 = u32::MAX;
888
889fn gc_track(rc: ObjRef) -> ObjRef {
891 #[cfg(target_os = "none")]
892 {
893 super::cycle_gc::track_obj(rc)
894 }
895 #[cfg(not(target_os = "none"))]
896 {
897 rc
898 }
899}
900
901pub type ObjRef = Rc<RefCell<Obj>>;
903
904pub type NativeFn = fn(&mut Interp, this: Value, args: &[Value]) -> Result<Value, Value>;
906
907#[derive(Clone)]
909pub enum Value {
910 Undefined,
911 Null,
912 Bool(bool),
913 Number(f64),
914 Str(Rc<String>),
915 BigInt(Rc<BigInt>),
917 Object(ObjRef),
918}
919
920pub const FN_FLAG_ARROW: u8 = 1 << 0;
921pub const FN_FLAG_ASYNC: u8 = 1 << 1;
922pub const FN_FLAG_GENERATOR: u8 = 1 << 2;
923pub const FN_FLAG_SIMPLE_PARAMS: u8 = 1 << 3;
925
926#[derive(Clone)]
928pub struct SharedFnInfo {
929 pub name: Rc<str>,
930 pub params: Rc<Vec<Param>>,
931 pub body: Rc<super::ast::FnBody>,
932 pub flags: u8,
933}
934
935impl SharedFnInfo {
936 #[inline]
937 pub fn is_arrow(&self) -> bool {
938 self.flags & FN_FLAG_ARROW != 0
939 }
940 #[inline]
941 pub fn is_async(&self) -> bool {
942 self.flags & FN_FLAG_ASYNC != 0
943 }
944 #[inline]
945 pub fn is_generator(&self) -> bool {
946 self.flags & FN_FLAG_GENERATOR != 0
947 }
948 #[inline]
949 pub fn has_simple_unique_params(&self) -> bool {
950 self.flags & FN_FLAG_SIMPLE_PARAMS != 0
951 }
952}
953
954#[derive(Clone)]
961pub struct FunctionData {
962 pub shared: Rc<SharedFnInfo>,
963 pub closure: Rc<RefCell<Scope>>,
965 pub bound_this: Option<Rc<Value>>,
967}
968
969impl FunctionData {
970 #[inline]
971 pub fn name(&self) -> &str {
972 &self.shared.name
973 }
974 #[inline]
975 pub fn name_rc(&self) -> Rc<str> {
976 self.shared.name.clone()
977 }
978 #[inline]
979 pub fn params(&self) -> &Rc<Vec<Param>> {
980 &self.shared.params
981 }
982 #[inline]
983 pub fn body(&self) -> &Rc<super::ast::FnBody> {
984 &self.shared.body
985 }
986 #[inline]
987 pub fn is_arrow(&self) -> bool {
988 self.shared.is_arrow()
989 }
990 #[inline]
991 pub fn is_async(&self) -> bool {
992 self.shared.is_async()
993 }
994 #[inline]
995 pub fn is_generator(&self) -> bool {
996 self.shared.is_generator()
997 }
998 #[inline]
999 pub fn has_simple_unique_params(&self) -> bool {
1000 self.shared.has_simple_unique_params()
1001 }
1002 #[inline]
1003 pub fn set_name(&mut self, name: &str) {
1004 Rc::make_mut(&mut self.shared).name = name.into();
1005 }
1006}
1007
1008pub fn f16_bits_to_f64(bits: u16) -> f64 {
1010 let sign = ((bits >> 15) & 1) as u64;
1011 let exp = ((bits >> 10) & 0x1F) as u32;
1012 let mant = (bits & 0x3FF) as u64;
1013 if exp == 0x1F {
1014 if mant != 0 {
1015 f64::NAN
1016 } else if sign != 0 {
1017 -f64::INFINITY
1018 } else {
1019 f64::INFINITY
1020 }
1021 } else if exp == 0 {
1022 if mant == 0 {
1023 if sign != 0 { -0.0 } else { 0.0 }
1024 } else {
1025 let val = (mant as f64) * 0.000_000_059_604_644_775_390_63;
1026 if sign != 0 { -val } else { val }
1027 }
1028 } else {
1029 let unbiased_exp = (exp as i32) - 15;
1030 let f64_exp = ((unbiased_exp + 1023) as u64) << 52;
1031 let f64_mant = mant << 42;
1032 f64::from_bits((sign << 63) | f64_exp | f64_mant)
1033 }
1034}
1035
1036pub fn f64_to_f16_bits(val: f64) -> u16 {
1037 let bits = val.to_bits();
1038 let sign = ((bits >> 63) & 1) as u16;
1039 let exp = ((bits >> 52) & 0x7FF) as i32;
1040 let mant = bits & 0x000F_FFFF_FFFF_FFFF;
1041
1042 if exp == 0x7FF {
1043 if mant != 0 {
1044 (sign << 15) | 0x7E00 | (((mant >> 42) as u16) | 1)
1045 } else {
1046 (sign << 15) | 0x7C00
1047 }
1048 } else {
1049 let unbiased_exp = exp - 1023;
1050 if unbiased_exp > 15 {
1051 (sign << 15) | 0x7C00
1052 } else if unbiased_exp >= -14 {
1053 let sig53 = 0x0010_0000_0000_0000u64 | mant;
1054 let half = 1u64 << 41;
1055 let rem = sig53 & ((1u64 << 42) - 1);
1056 let mut f16_sig = (sig53 >> 42) as u16;
1057 if rem > half || (rem == half && (f16_sig & 1) != 0) {
1058 f16_sig += 1;
1059 }
1060 let mut f16_exp = (unbiased_exp + 15) as u16;
1061 if f16_sig >= 0x800 {
1062 f16_sig >>= 1;
1063 f16_exp += 1;
1064 }
1065 if f16_exp >= 31 {
1066 (sign << 15) | 0x7C00
1067 } else {
1068 (sign << 15) | (f16_exp << 10) | (f16_sig & 0x3FF)
1069 }
1070 } else if unbiased_exp >= -25 && exp > 0 {
1071 let sig53 = 0x0010_0000_0000_0000u64 | mant;
1072 let shift = (42 + (-14 - unbiased_exp)) as u32;
1073 let half = 1u64 << (shift - 1);
1074 let rem = sig53 & ((1u64 << shift) - 1);
1075 let mut f16_mant = (sig53 >> shift) as u16;
1076 if rem > half || (rem == half && (f16_mant & 1) != 0) {
1077 f16_mant += 1;
1078 }
1079 if f16_mant >= 0x400 {
1080 (sign << 15) | 0x0400
1081 } else {
1082 (sign << 15) | f16_mant
1083 }
1084 } else {
1085 sign << 15
1086 }
1087 }
1088}
1089
1090#[derive(Clone)]
1093pub struct ByteStore {
1094 pub buf: Rc<RefCell<Vec<u8>>>,
1095 pub off: usize,
1097 pub len: usize,
1099 pub kind: u8,
1102}
1103
1104impl ByteStore {
1105 #[inline]
1106 pub const fn elem_size_of(kind: u8) -> usize {
1107 match kind {
1108 3 | 4 | 7 => 2,
1109 5 | 6 | 8 => 4,
1110 9..=11 => 8,
1111 _ => 1,
1112 }
1113 }
1114 #[inline]
1115 pub const fn raw_kind(&self) -> u8 {
1116 self.kind & 0x7f
1117 }
1118 #[inline]
1119 pub const fn is_auto(&self) -> bool {
1120 (self.kind & 0x80) != 0
1121 }
1122 #[inline]
1123 pub const fn elem_size(&self) -> usize {
1124 Self::elem_size_of(self.raw_kind())
1125 }
1126 #[inline]
1127 pub fn is_out_of_bounds(&self) -> bool {
1128 let total = self.buf.borrow().len();
1129 if self.is_auto() {
1130 total < self.off
1131 } else {
1132 total < self.off.saturating_add(self.len.saturating_mul(self.elem_size()))
1133 }
1134 }
1135 #[inline]
1136 pub fn effective_len(&self) -> usize {
1137 let total = self.buf.borrow().len();
1138 if self.is_auto() {
1139 if total < self.off {
1140 0
1141 } else {
1142 (total - self.off) / self.elem_size()
1143 }
1144 } else if total < self.off.saturating_add(self.len.saturating_mul(self.elem_size())) {
1145 0
1146 } else {
1147 self.len
1148 }
1149 }
1150 pub fn new(bytes: Vec<u8>, kind: u8) -> Self {
1151 let kind = kind & 0x7f;
1152 let es = Self::elem_size_of(kind);
1153 let len = bytes.len() / es;
1154 ByteStore { buf: Rc::new(RefCell::new(bytes)), off: 0, len, kind }
1155 }
1156 pub fn view(&self, start: usize, len: usize, kind: u8) -> Self {
1158 let cur_len = self.effective_len();
1159 let start = start.min(cur_len);
1160 let len = len.min(cur_len - start);
1161 let es = self.elem_size();
1162 ByteStore { buf: self.buf.clone(), off: self.off + start * es, len, kind }
1163 }
1164 pub fn view_bytes(&self, byte_offset: usize, elem_len: usize, kind: u8) -> Self {
1166 let es = Self::elem_size_of(kind & 0x7f);
1167 let total = self.buf.borrow().len();
1168 let off = (self.off + byte_offset).min(total);
1169 let max_elems = (total - off) / es;
1170 let len = if (kind & 0x80) != 0 { max_elems } else { elem_len.min(max_elems) };
1171 ByteStore { buf: self.buf.clone(), off, len, kind }
1172 }
1173 pub fn get(&self, i: usize) -> Option<f64> {
1174 if i >= self.effective_len() {
1175 return None;
1176 }
1177 let es = self.elem_size();
1178 let at = self.off + i * es;
1179 let b = self.buf.borrow();
1180 let s = b.get(at..at + es)?;
1181 Some(match self.raw_kind() {
1182 0 | 2 => s[0] as f64,
1183 1 => s[0] as i8 as f64,
1184 3 => i16::from_le_bytes([s[0], s[1]]) as f64,
1185 4 => u16::from_le_bytes([s[0], s[1]]) as f64,
1186 5 => i32::from_le_bytes([s[0], s[1], s[2], s[3]]) as f64,
1187 6 => u32::from_le_bytes([s[0], s[1], s[2], s[3]]) as f64,
1188 7 => f16_bits_to_f64(u16::from_le_bytes([s[0], s[1]])),
1189 8 => f32::from_le_bytes([s[0], s[1], s[2], s[3]]) as f64,
1190 9 => f64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]),
1191 10 => i64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]) as f64,
1192 11 => u64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]) as f64,
1193 _ => s[0] as f64,
1194 })
1195 }
1196
1197 #[inline]
1199 pub const fn is_bigint_kind(kind: u8) -> bool {
1200 matches!(kind, 10 | 11)
1201 }
1202
1203 pub fn get_value(&self, i: usize) -> Option<Value> {
1205 let rk = self.raw_kind();
1206 if !Self::is_bigint_kind(rk) {
1207 return self.get(i).map(Value::Number);
1208 }
1209 if i >= self.effective_len() {
1210 return None;
1211 }
1212 let at = self.off + i * 8;
1213 let b = self.buf.borrow();
1214 let s = b.get(at..at + 8)?;
1215 let bytes = [s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]];
1216 Some(if rk == 10 {
1217 Value::bigint(super::bigint::BigInt::from_i64(i64::from_le_bytes(bytes)))
1218 } else {
1219 Value::bigint(super::bigint::BigInt::from_u64(u64::from_le_bytes(bytes)))
1220 })
1221 }
1222
1223 pub fn set_value(&self, i: usize, v: &Value) {
1225 let rk = self.raw_kind();
1226 if !Self::is_bigint_kind(rk) {
1227 self.set(i, v.to_number());
1228 return;
1229 }
1230 if i >= self.effective_len() {
1231 return;
1232 }
1233 let n: u64 = match v {
1234 Value::BigInt(b) => b.to_u64_truncated(),
1235 other => super::bigint::BigInt::from_f64(libm::trunc(other.to_number()))
1236 .map(|b| b.to_u64_truncated())
1237 .unwrap_or(0),
1238 };
1239 let at = self.off + i * 8;
1240 let mut b = self.buf.borrow_mut();
1241 if let Some(s) = b.get_mut(at..at + 8) {
1242 s.copy_from_slice(&n.to_le_bytes());
1243 }
1244 }
1245 pub fn fill_bytes_with(&self, mut next: impl FnMut() -> u8) {
1248 let (at, n) = (self.off, self.effective_len() * self.elem_size());
1249 let mut b = self.buf.borrow_mut();
1250 if let Some(s) = b.get_mut(at..at + n) {
1251 for x in s.iter_mut() {
1252 *x = next();
1253 }
1254 }
1255 }
1256 pub fn set(&self, i: usize, v: f64) {
1258 if i >= self.effective_len() {
1259 return;
1260 }
1261 let rk = self.raw_kind();
1262 let es = self.elem_size();
1263 let at = self.off + i * es;
1264 let mut b = self.buf.borrow_mut();
1265 let Some(s) = b.get_mut(at..at + es) else { return };
1266 match rk {
1267 0..=2 => {
1268 s[0] = Self::coerce(v, rk);
1269 }
1270 3 | 4 => {
1271 let n = wrap_f64_to_u64(v) as u16;
1272 s.copy_from_slice(&n.to_le_bytes());
1273 }
1274 5 | 6 => {
1275 let n = wrap_f64_to_u64(v) as u32;
1276 s.copy_from_slice(&n.to_le_bytes());
1277 }
1278 7 => {
1279 s.copy_from_slice(&f64_to_f16_bits(v).to_le_bytes());
1280 }
1281 8 => {
1282 s.copy_from_slice(&(v as f32).to_le_bytes());
1283 }
1284 9 => {
1285 s.copy_from_slice(&v.to_le_bytes());
1286 }
1287 10 | 11 => {
1288 let n = wrap_f64_to_u64(v);
1290 s.copy_from_slice(&n.to_le_bytes());
1291 }
1292 _ => {
1293 s[0] = Self::coerce(v, 0);
1294 }
1295 }
1296 }
1297 pub fn coerce(v: f64, kind: u8) -> u8 {
1298 if kind == 2 {
1299 if v.is_nan() {
1300 return 0;
1301 }
1302 let c = v.clamp(0.0, 255.0);
1304 let f = libm::floor(c);
1305 let r = if c - f > 0.5 || (c - f == 0.5 && (f as u32) % 2 == 1) { f + 1.0 } else { f };
1306 return r as u8;
1307 }
1308 wrap_f64_to_u64(v) as u8
1309 }
1310 pub fn to_vec(&self) -> Vec<u8> {
1311 let b = self.buf.borrow();
1312 let byte_len = self.effective_len() * self.elem_size();
1313 b.get(self.off..self.off + byte_len).map(|s| s.to_vec()).unwrap_or_default()
1314 }
1315 pub fn values(&self) -> Vec<Value> {
1316 let n = self.effective_len();
1317 (0..n).map(|i| self.get_value(i).unwrap_or(Value::Number(0.0))).collect()
1318 }
1319}
1320
1321#[derive(Clone)]
1323pub struct ProxyData {
1324 pub target: ObjRef,
1325 pub handler: ObjRef,
1326 pub revoked: core::cell::Cell<bool>,
1328}
1329
1330#[derive(Clone)]
1332pub struct BoundData {
1333 pub target: Value,
1334 pub bound_this: Value,
1335 pub bound_args: Vec<Value>,
1336}
1337
1338#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1342pub struct HostRef {
1343 pub class: u8,
1344 pub id: usize,
1345}
1346
1347pub const HOST_CLASS_BY_ID: u8 = 0x80;
1349
1350impl HostRef {
1351 #[inline]
1353 pub fn by_id(&self) -> bool {
1354 self.class & HOST_CLASS_BY_ID != 0
1355 }
1356}
1357
1358#[derive(Clone)]
1359pub enum ObjKind {
1360 Plain,
1361 Array(Vec<Value>),
1362 Function(FunctionData),
1363 Native {
1364 name: Rc<str>,
1365 func: NativeFn,
1366 },
1367 Bytes(Box<ByteStore>),
1373 HostRef(HostRef),
1377 Iter,
1380 GenReturn,
1382 MapObj(Vec<(Value, Value)>),
1384 SetObj(Vec<Value>),
1386 PromiseObj(Rc<RefCell<PromiseState>>),
1388 Resolver {
1390 state: Rc<RefCell<PromiseState>>,
1391 reject: bool,
1392 },
1393 Generator(Rc<RefCell<GenState>>),
1395 RegExpObj(Rc<RefCell<super::regex::RegExpData>>),
1397 Proxy(Box<ProxyData>),
1399 Bound(Box<BoundData>),
1402 DateObj(f64),
1404 PrivateDesc(Box<PrivateDescriptor>),
1406}
1407
1408#[derive(Clone)]
1410pub enum PrivateKind {
1411 Field,
1412 StaticField,
1413 Method(Value),
1414 StaticMethod(Value),
1415 Accessor { get: Option<Value>, set: Option<Value> },
1416 StaticAccessor { get: Option<Value>, set: Option<Value> },
1417}
1418
1419#[derive(Clone)]
1421pub struct PrivateDescriptor {
1422 pub brand_id: u64,
1423 pub name: Rc<str>,
1424 pub kind: PrivateKind,
1425}
1426
1427impl ObjKind {
1428 #[inline]
1430 pub fn host_ref(&self) -> Option<HostRef> {
1431 match self {
1432 ObjKind::HostRef(h) => Some(*h),
1433 _ => None,
1434 }
1435 }
1436}
1437
1438#[derive(Clone)]
1440pub enum GenCompletion {
1441 Normal(Value),
1442 Throw(Value),
1443 Return(Value),
1444}
1445
1446pub struct GenState {
1454 pub func: FunctionData,
1456 pub args: Vec<Value>,
1458 pub this: Value,
1460 pub param_vars: Vec<(Rc<str>, Value)>,
1462 pub sent: Vec<GenCompletion>,
1464 pub started: bool,
1466 pub done: bool,
1468 pub returned: Value,
1470 pub call_scope: Option<Rc<RefCell<Scope>>>,
1472 pub done_stmts: Vec<Option<DoneStmtEntry>>,
1474 pub saved_scopes: Vec<Rc<RefCell<Scope>>>,
1476 pub(crate) vm_mode: u8,
1478 pub(crate) vm: Option<alloc::boxed::Box<super::interp::gen_vm::GenFrame>>,
1480 pub(crate) executing: bool,
1482}
1483
1484pub const GEN_MODE_UNKNOWN: u8 = 0;
1486pub const GEN_MODE_VM: u8 = 1;
1488pub const GEN_MODE_REPLAY: u8 = 2;
1490
1491pub type DoneStmtEntry = (usize, usize, usize, usize, Value);
1493
1494#[derive(Debug, Clone, Copy, PartialEq)]
1495pub struct PropertyAttributes {
1496 pub writable: bool,
1497 pub configurable: bool,
1498 pub enumerable: bool,
1499}
1500
1501impl Default for PropertyAttributes {
1502 fn default() -> Self {
1503 PropertyAttributes {
1504 writable: true,
1505 configurable: true,
1506 enumerable: true,
1507 }
1508 }
1509}
1510
1511#[derive(Clone, Copy, PartialEq)]
1513pub enum PromiseStatus {
1514 Pending,
1515 Fulfilled,
1516 Rejected,
1517}
1518
1519pub struct Reaction {
1521 pub on_fulfilled: Option<Value>,
1522 pub on_rejected: Option<Value>,
1523 pub result: Rc<RefCell<PromiseState>>,
1525}
1526
1527pub struct PromiseState {
1528 pub status: PromiseStatus,
1529 pub value: Value,
1531 pub reactions: Vec<Reaction>,
1533}
1534
1535impl PromiseState {
1536 pub fn pending() -> Self {
1537 PromiseState {
1538 status: PromiseStatus::Pending,
1539 value: Value::Undefined,
1540 reactions: Vec::new(),
1541 }
1542 }
1543}
1544
1545pub struct Job {
1547 pub handler: Option<Value>,
1549 pub arg: Value,
1550 pub is_fulfill: bool,
1551 pub result: Rc<RefCell<PromiseState>>,
1552}
1553
1554#[derive(Clone, Default)]
1556pub struct Accessor {
1557 pub get: Option<Value>,
1558 pub set: Option<Value>,
1559}
1560
1561#[derive(Default, Clone)]
1565pub struct RareData {
1566 pub accessors: PropMap<Accessor>,
1567 pub attrs: PropMap<PropertyAttributes>,
1568 pub holes: Option<alloc::boxed::Box<Vec<bool>>>,
1569 pub primitive: Option<Value>,
1572 pub private_brands: Vec<u64>,
1574 pub private_fields: Vec<(u64, Rc<str>, Value)>,
1576 pub intl_locale: Option<Rc<str>>,
1578 pub error_stack: Option<String>,
1580}
1581
1582pub const OBJ_FLAG_FROZEN: u8 = 1 << 0;
1583pub const OBJ_FLAG_SEALED: u8 = 1 << 1;
1584pub const OBJ_FLAG_NON_EXTENSIBLE: u8 = 1 << 2;
1585pub const OBJ_FLAG_NULL_PROTO: u8 = 1 << 3;
1586pub const OBJ_FLAG_HTMLDDA: u8 = 1 << 4;
1588pub const OBJ_FLAG_NO_FN_NAME: u8 = 1 << 5;
1590pub const OBJ_FLAG_NO_FN_LENGTH: u8 = 1 << 6;
1592
1593pub const TYPED_ARRAY_INTERNAL_PROPS: &[&str] = &[
1595 "_ta_kind", "_ta_off", "_ta_buf", "BYTES_PER_ELEMENT", "byteLength", "byteOffset", "buffer", "set", "slice", "subarray", "fill",
1596 "toBase64", "toHex", "setFromBase64", "setFromHex",
1597];
1598
1599#[inline]
1602pub fn parse_index(key: &str) -> Option<usize> {
1603 let b = key.as_bytes();
1604 if b.is_empty() || b.len() > 10 || (b[0] == b'0' && b.len() > 1) || !b.iter().all(u8::is_ascii_digit) {
1605 return None;
1606 }
1607 key.parse::<usize>().ok()
1608}
1609
1610pub fn is_canonical_numeric_key(k: &str) -> bool {
1613 if k == "-0" {
1614 return true;
1615 }
1616 let first = k.as_bytes().first().copied().unwrap_or(b'x');
1618 if !(first.is_ascii_digit() || first == b'-' || first == b'I') {
1619 return k == "NaN";
1620 }
1621 let n = Value::Str(Rc::new(String::from(k))).to_number();
1622 if n.is_nan() {
1623 return k == "NaN";
1624 }
1625 fmt_number(n) == k
1626}
1627
1628#[inline]
1629pub fn ta_is_immutable(o: &Obj) -> bool {
1630 matches!(
1631 o.props.get("_ta_buf"),
1632 Some(Value::Object(buf)) if matches!(buf.borrow().props.get("_immutable"), Some(Value::Bool(true)))
1633 )
1634}
1635
1636#[inline]
1637pub fn ta_is_detached_or_oob(o: &Obj) -> bool {
1638 if let Some(Value::Object(buf)) = o.props.get("_ta_buf") {
1639 if matches!(buf.borrow().props.get("detached"), Some(Value::Bool(true))) {
1640 return true;
1641 }
1642 }
1643 if let ObjKind::Bytes(st) = &o.kind {
1644 return st.is_out_of_bounds();
1645 }
1646 false
1647}
1648
1649#[inline]
1650pub fn ta_effective_len(o: &Obj) -> Option<usize> {
1651 if ta_is_detached_or_oob(o) {
1652 return None;
1653 }
1654 if let ObjKind::Bytes(st) = &o.kind {
1655 return Some(st.effective_len());
1656 }
1657 None
1658}
1659
1660#[inline]
1661pub fn ta_valid_index(o: &Obj, key: &str) -> Option<usize> {
1662 if key == "-0" {
1663 return None;
1664 }
1665 let idx = parse_index(key)?;
1666 let len = ta_effective_len(o)?;
1667 if idx < len { Some(idx) } else { None }
1668}
1669
1670pub struct Obj {
1672 pub props: PropMap<Value>,
1673 pub kind: ObjKind,
1674 pub proto: Option<ObjRef>,
1675 pub rare: Option<alloc::boxed::Box<RareData>>,
1676 pub gc_slot: u32,
1678 pub flags: u8,
1680}
1681
1682impl Obj {
1683 pub fn new(kind: ObjKind) -> Self {
1684 Self {
1685 props: PropMap::default(),
1686 kind,
1687 proto: None,
1688 rare: None,
1689 gc_slot: crate::os_lib::ecma::value::NO_GC_SLOT,
1690 flags: 0,
1691 }
1692 }
1693
1694 #[inline]
1695 pub fn is_frozen(&self) -> bool {
1696 (self.flags & OBJ_FLAG_FROZEN) != 0
1697 }
1698 #[inline]
1699 pub fn set_frozen(&mut self, v: bool) {
1700 if v {
1701 self.flags |= OBJ_FLAG_FROZEN;
1702 } else {
1703 self.flags &= !OBJ_FLAG_FROZEN;
1704 }
1705 }
1706
1707 #[inline]
1708 pub fn is_sealed(&self) -> bool {
1709 (self.flags & OBJ_FLAG_SEALED) != 0
1710 }
1711 #[inline]
1712 pub fn set_sealed(&mut self, v: bool) {
1713 if v {
1714 self.flags |= OBJ_FLAG_SEALED;
1715 } else {
1716 self.flags &= !OBJ_FLAG_SEALED;
1717 }
1718 }
1719
1720 #[inline]
1721 pub fn is_non_extensible(&self) -> bool {
1722 (self.flags & OBJ_FLAG_NON_EXTENSIBLE) != 0
1723 }
1724 #[inline]
1725 pub fn set_non_extensible(&mut self, v: bool) {
1726 if v {
1727 self.flags |= OBJ_FLAG_NON_EXTENSIBLE;
1728 } else {
1729 self.flags &= !OBJ_FLAG_NON_EXTENSIBLE;
1730 }
1731 }
1732
1733 #[inline]
1734 pub fn is_null_proto(&self) -> bool {
1735 (self.flags & OBJ_FLAG_NULL_PROTO) != 0
1736 }
1737 #[inline]
1738 pub fn set_null_proto(&mut self, v: bool) {
1739 if v {
1740 self.flags |= OBJ_FLAG_NULL_PROTO;
1741 } else {
1742 self.flags &= !OBJ_FLAG_NULL_PROTO;
1743 }
1744 }
1745
1746 #[inline]
1747 pub fn rare_data(&self) -> Option<&RareData> {
1748 self.rare.as_deref()
1749 }
1750 pub fn function_class_name(&self) -> &'static str {
1752 match &self.kind {
1753 ObjKind::Function(f) => match (f.is_async(), f.is_generator()) {
1754 (true, true) => "%AsyncGeneratorFunction",
1755 (true, false) => "%AsyncFunction",
1756 (false, true) => "%GeneratorFunction",
1757 _ => "Function",
1758 },
1759 _ => "Function",
1760 }
1761 }
1762 #[inline]
1764 pub fn primitive(&self) -> Option<&Value> {
1765 self.rare.as_ref().and_then(|r| r.primitive.as_ref())
1766 }
1767 #[inline]
1769 pub fn is_error_obj(&self) -> bool {
1770 self.rare.as_ref().is_some_and(|r| r.error_stack.is_some())
1771 }
1772 #[inline]
1774 pub fn error_stack(&self) -> Option<&str> {
1775 self.rare.as_ref().and_then(|r| r.error_stack.as_deref())
1776 }
1777 #[inline]
1779 pub fn set_error_stack(&mut self, s: String) {
1780 self.rare_data_mut().error_stack = Some(s);
1781 }
1782 #[inline]
1783 pub fn has_private_brand(&self, brand: u64) -> bool {
1784 self.rare.as_ref().is_some_and(|r| r.private_brands.contains(&brand))
1785 }
1786 #[inline]
1787 pub fn add_private_brand(&mut self, brand: u64) {
1788 let brands = &mut self.rare_data_mut().private_brands;
1789 if !brands.contains(&brand) {
1790 brands.push(brand);
1791 }
1792 }
1793 #[inline]
1794 pub fn has_private_field(&self, brand: u64, name: &str) -> bool {
1795 self.rare.as_ref().is_some_and(|r| {
1796 r.private_fields
1797 .iter()
1798 .any(|(b, n, _)| *b == brand && &**n == name)
1799 })
1800 }
1801 #[inline]
1802 pub fn get_private_field(&self, brand: u64, name: &str) -> Option<&Value> {
1803 self.rare.as_ref().and_then(|r| {
1804 r.private_fields
1805 .iter()
1806 .find(|(b, n, _)| *b == brand && &**n == name)
1807 .map(|(_, _, v)| v)
1808 })
1809 }
1810 #[inline]
1811 pub fn set_private_field(&mut self, brand: u64, name: &str, val: Value) -> bool {
1812 let Some(r) = self.rare.as_mut() else {
1813 return false;
1814 };
1815 if let Some((_, _, slot)) = r
1816 .private_fields
1817 .iter_mut()
1818 .find(|(b, n, _)| *b == brand && &**n == name)
1819 {
1820 *slot = val;
1821 true
1822 } else {
1823 false
1824 }
1825 }
1826 #[inline]
1827 pub fn define_private_field(&mut self, brand: u64, name: Rc<str>, val: Value) -> bool {
1828 let fields = &mut self.rare_data_mut().private_fields;
1829 if fields.iter().any(|(b, n, _)| *b == brand && **n == *name) {
1830 return false;
1831 }
1832 fields.push((brand, name, val));
1833 true
1834 }
1835 #[inline]
1836 pub fn rare_data_mut(&mut self) -> &mut RareData {
1837 self.rare.get_or_insert_with(alloc::boxed::Box::default)
1838 }
1839
1840 #[inline]
1841 pub fn has_rare_props(&self) -> bool {
1842 self.rare.as_ref().is_some_and(|r| !r.accessors.is_empty() || !r.attrs.is_empty())
1843 }
1844
1845 #[inline]
1846 pub fn accessors(&self) -> Option<&PropMap<Accessor>> {
1847 self.rare.as_ref().map(|r| &r.accessors)
1848 }
1849 #[inline]
1850 pub fn accessors_mut(&mut self) -> &mut PropMap<Accessor> {
1851 &mut self.rare_data_mut().accessors
1852 }
1853 #[inline]
1854 pub fn get_accessor(&self, key: &str) -> Option<&Accessor> {
1855 self.rare.as_ref().and_then(|r| r.accessors.get(key))
1856 }
1857 #[inline]
1858 pub fn has_any_accessor(&self) -> bool {
1859 self.rare.as_ref().is_some_and(|r| !r.accessors.is_empty())
1860 }
1861 #[inline]
1862 pub fn has_accessor(&self, key: &str) -> bool {
1863 self.rare.as_ref().is_some_and(|r| r.accessors.contains_key(key))
1864 }
1865 #[inline]
1866 pub fn get_getter(&self, key: &str) -> Option<Value> {
1867 self.get_accessor(key).and_then(|a| a.get.clone())
1868 }
1869 #[inline]
1870 pub fn get_setter(&self, key: &str) -> Option<Value> {
1871 self.get_accessor(key).and_then(|a| a.set.clone())
1872 }
1873 #[inline]
1874 pub fn insert_accessor(&mut self, key: impl Into<PropKey>, acc: Accessor) {
1875 self.accessors_mut().insert(key.into(), acc);
1876 }
1877 #[inline]
1878 pub fn remove_accessor(&mut self, key: &str) -> Option<Accessor> {
1879 if let Some(r) = self.rare.as_mut() {
1880 r.accessors.shift_remove(key)
1881 } else {
1882 None
1883 }
1884 }
1885
1886 #[inline]
1887 pub fn attrs(&self) -> Option<&PropMap<PropertyAttributes>> {
1888 self.rare.as_ref().map(|r| &r.attrs)
1889 }
1890 #[inline]
1891 pub fn attrs_mut(&mut self) -> &mut PropMap<PropertyAttributes> {
1892 &mut self.rare_data_mut().attrs
1893 }
1894 #[inline]
1895 pub fn get_attr(&self, key: &str) -> Option<PropertyAttributes> {
1896 self.rare.as_ref().and_then(|r| r.attrs.get(key).copied())
1897 }
1898 #[inline]
1899 pub fn get_attr_or_default(&self, key: &str) -> PropertyAttributes {
1900 if let Some(a) = self.get_attr(key) {
1901 return a;
1902 }
1903 if key == "lastIndex" && matches!(self.kind, ObjKind::RegExpObj(_)) {
1904 return PropertyAttributes { writable: true, configurable: false, enumerable: false };
1905 }
1906 if !self.props.contains_key(key) && !self.has_accessor(key) && self.has_virtual_fn_prop(key) {
1907 return PropertyAttributes {
1908 writable: false,
1909 configurable: true,
1910 enumerable: false,
1911 };
1912 }
1913 PropertyAttributes::default()
1914 }
1915
1916 #[inline]
1918 pub fn has_virtual_fn_prop(&self, key: &str) -> bool {
1919 if !matches!(
1920 self.kind,
1921 ObjKind::Function(_) | ObjKind::Native { .. } | ObjKind::Bound(_) | ObjKind::Resolver { .. }
1922 ) {
1923 return false;
1924 }
1925 match key {
1926 "name" => (self.flags & OBJ_FLAG_NO_FN_NAME) == 0,
1927 "length" => (self.flags & OBJ_FLAG_NO_FN_LENGTH) == 0,
1928 _ => false,
1929 }
1930 }
1931
1932 #[inline]
1934 pub fn delete_virtual_fn_prop(&mut self, key: &str) {
1935 if matches!(
1936 self.kind,
1937 ObjKind::Function(_) | ObjKind::Native { .. } | ObjKind::Bound(_) | ObjKind::Resolver { .. }
1938 ) {
1939 match key {
1940 "name" => self.flags |= OBJ_FLAG_NO_FN_NAME,
1941 "length" => self.flags |= OBJ_FLAG_NO_FN_LENGTH,
1942 _ => {}
1943 }
1944 }
1945 }
1946 #[inline]
1947 pub fn insert_attr(&mut self, key: impl Into<PropKey>, attr: PropertyAttributes) {
1948 self.attrs_mut().insert(key.into(), attr);
1949 }
1950 #[inline]
1951 pub fn remove_attr(&mut self, key: &str) -> Option<PropertyAttributes> {
1952 if let Some(r) = self.rare.as_mut() {
1953 r.attrs.shift_remove(key)
1954 } else {
1955 None
1956 }
1957 }
1958
1959 #[inline]
1960 pub fn holes(&self) -> Option<&[bool]> {
1961 self.rare.as_ref().and_then(|r| r.holes.as_deref().map(|v| v.as_slice()))
1962 }
1963 #[inline]
1964 pub fn set_holes(&mut self, holes: Option<alloc::boxed::Box<Vec<bool>>>) {
1965 if holes.is_some() || self.rare.is_some() {
1966 self.rare_data_mut().holes = holes;
1967 }
1968 }
1969 #[inline]
1970 pub fn clear_holes(&mut self) {
1971 if let Some(r) = self.rare.as_mut() {
1972 r.holes = None;
1973 }
1974 }
1975 pub fn fn_prototype(o: &ObjRef) -> Option<Value> {
1982 if let Some(v) = o.borrow().props.get("prototype") {
1983 return Some(v.clone());
1984 }
1985 let lazy = matches!(&o.borrow().kind, ObjKind::Function(fd) if !fd.is_arrow());
1986 if !lazy {
1987 return None;
1988 }
1989 let proto = Obj::plain();
1990 proto.borrow_mut().props.insert(String::from("constructor").into(), Value::Object(o.clone()));
1991 o.borrow_mut().props.insert(String::from("prototype").into(), Value::Object(proto.clone()));
1992 Some(Value::Object(proto))
1993 }
1994
1995 pub fn plain() -> ObjRef {
1996 gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::Plain))))
1997 }
1998 pub fn bytes(store: ByteStore) -> ObjRef {
1999 gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::Bytes(Box::new(store))))))
2000 }
2001 pub fn grow_array(&mut self, new_len: usize) -> bool {
2008 if new_len > MAX_DENSE_ARRAY_LEN {
2009 return false;
2010 }
2011 let old_len = match &mut self.kind {
2012 ObjKind::Array(items) => {
2013 let old = items.len();
2014 if new_len <= old {
2015 return true;
2016 }
2017 if items.try_reserve_exact(new_len - old).is_err() {
2018 return false;
2019 }
2020 items.resize(new_len, Value::Undefined);
2021 old
2022 }
2023 _ => return false,
2024 };
2025 let mut mask = self.holes().map(<[bool]>::to_vec).unwrap_or_default();
2026 if mask.len() < new_len && mask.try_reserve_exact(new_len - mask.len()).is_err() {
2027 return false;
2028 }
2029 mask.resize(old_len, false);
2030 mask.resize(new_len, true);
2031 self.set_holes(Some(alloc::boxed::Box::new(mask)));
2032 true
2033 }
2034 #[inline]
2036 pub fn clear_hole(&mut self, i: usize) {
2037 if let Some(r) = self.rare.as_mut() {
2038 if let Some(h) = r.holes.as_mut() {
2039 if let Some(m) = h.get_mut(i) {
2040 *m = false;
2041 }
2042 }
2043 }
2044 }
2045 pub fn is_enumerable(&self, key: &str) -> bool {
2053 if let Some(a) = self.get_attr(key) {
2054 return a.enumerable;
2055 }
2056 if !self.props.contains_key(key) && !self.has_accessor(key) && self.has_virtual_fn_prop(key) {
2057 return false;
2058 }
2059 if matches!(self.kind, ObjKind::Bytes(_)) && TYPED_ARRAY_INTERNAL_PROPS.contains(&key) {
2060 return false;
2061 }
2062 match key {
2063 "lastIndex" if matches!(self.kind, ObjKind::RegExpObj(_)) => false,
2064 "prototype" => !matches!(self.kind, ObjKind::Function(_) | ObjKind::Native { .. }),
2065 "callee" => !matches!(self.kind, ObjKind::Array(_)),
2067 "constructor" => {
2068 let Some(Value::Object(f)) = self.props.get("constructor") else { return true };
2069 let Ok(fb) = f.try_borrow() else { return true };
2070 if !matches!(fb.kind, ObjKind::Function(_) | ObjKind::Native { .. }) {
2071 return true;
2072 }
2073 !matches!(fb.props.get("prototype"), Some(Value::Object(p)) if core::ptr::eq(p.as_ptr() as *const Obj, self as *const Obj))
2074 }
2075 _ => true,
2076 }
2077 }
2078 pub fn hide_props(&mut self, keys: &[&str]) {
2081 for k in keys {
2082 if self.props.contains_key(k) {
2083 self.insert_attr(*k, PropertyAttributes { writable: true, configurable: true, enumerable: false });
2084 }
2085 }
2086 }
2087 pub fn is_hole(&self, i: usize) -> bool {
2089 match (self.holes(), &self.kind) {
2090 (Some(h), ObjKind::Array(items)) => {
2091 h.get(i).copied().unwrap_or(false) && matches!(items.get(i), Some(Value::Undefined))
2092 }
2093 _ => false,
2094 }
2095 }
2096 pub fn hole_mask(&self) -> Vec<bool> {
2098 match (self.holes(), &self.kind) {
2099 (Some(_), ObjKind::Array(items)) => (0..items.len()).map(|i| self.is_hole(i)).collect(),
2100 _ => Vec::new(),
2101 }
2102 }
2103 pub fn array(items: Vec<Value>) -> ObjRef {
2104 gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::Array(items)))))
2105 }
2106 pub fn array_push(&mut self, v: Value) {
2107 if let ObjKind::Array(items) = &mut self.kind {
2108 items.push(v);
2109 }
2110 }
2111 pub fn function(data: FunctionData) -> ObjRef {
2112 gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::Function(data)))))
2113 }
2114 pub fn function_rc(data: Rc<FunctionData>) -> ObjRef {
2115 Self::function((*data).clone())
2116 }
2117 pub fn native(name: &str, func: NativeFn) -> ObjRef {
2118 gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::Native { name: Rc::from(name), func }))))
2119 }
2120 pub fn iter_obj() -> ObjRef {
2122 gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::Iter))))
2123 }
2124 pub fn gen_return() -> ObjRef {
2126 gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::GenReturn))))
2127 }
2128 pub fn host_ref(h: HostRef) -> ObjRef {
2130 gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::HostRef(h)))))
2131 }
2132 pub fn private_desc(pd: PrivateDescriptor) -> ObjRef {
2133 gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::PrivateDesc(alloc::boxed::Box::new(pd))))))
2134 }
2135 pub fn map_obj(entries: Vec<(Value, Value)>) -> ObjRef {
2136 gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::MapObj(entries)))))
2137 }
2138 pub fn set_obj(items: Vec<Value>) -> ObjRef {
2139 gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::SetObj(items)))))
2140 }
2141 pub fn promise(state: Rc<RefCell<PromiseState>>) -> ObjRef {
2142 gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::PromiseObj(state)))))
2143 }
2144 pub fn resolver(state: Rc<RefCell<PromiseState>>, reject: bool) -> ObjRef {
2145 gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::Resolver { state, reject }))))
2146 }
2147 pub fn generator(state: GenState) -> ObjRef {
2148 gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::Generator(Rc::new(RefCell::new(state)))))))
2149 }
2150 pub fn regexp(data: super::regex::RegExpData) -> ObjRef {
2151 let li = data.last_index as f64;
2153 let o = Obj::new(ObjKind::RegExpObj(Rc::new(RefCell::new(data))));
2154 let o = gc_track(Rc::new(RefCell::new(o)));
2155 o.borrow_mut().props.insert("lastIndex".into(), Value::Number(li));
2156 o
2157 }
2158 pub fn proxy(target: ObjRef, handler: ObjRef) -> ObjRef {
2159 gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::Proxy(Box::new(ProxyData { target, handler, revoked: core::cell::Cell::new(false) }))))))
2160 }
2161 pub fn date_obj(epoch_ms: f64) -> ObjRef {
2162 gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::DateObj(epoch_ms)))))
2163 }
2164 pub fn bound(target: Value, bound_this: Value, bound_args: Vec<Value>) -> ObjRef {
2165 gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::Bound(Box::new(BoundData { target, bound_this, bound_args }))))))
2166 }
2167 pub fn clear_references(&mut self) {
2168 self.props.clear();
2169 self.rare = None;
2170 self.proto = None;
2171 match &mut self.kind {
2172 ObjKind::Array(items) => items.clear(),
2173 ObjKind::Function(f) => {
2174 f.bound_this = None;
2175 f.closure = Scope::new_root();
2176 }
2177 ObjKind::MapObj(entries) => entries.clear(),
2178 ObjKind::SetObj(items) => items.clear(),
2179 ObjKind::PromiseObj(p) => {
2180 if let Ok(mut p) = p.try_borrow_mut() {
2181 p.reactions.clear();
2182 p.value = Value::Undefined;
2183 }
2184 }
2185 ObjKind::Resolver { state, .. } => {
2186 if let Ok(mut s) = state.try_borrow_mut() {
2187 s.reactions.clear();
2188 s.value = Value::Undefined;
2189 }
2190 }
2191 ObjKind::Bound(b) => {
2192 b.target = Value::Undefined;
2193 b.bound_this = Value::Undefined;
2194 b.bound_args.clear();
2195 }
2196 _ => {}
2197 }
2198 }
2199
2200 pub fn is_callable(&self) -> bool {
2201 match &self.kind {
2202 ObjKind::Function(_) | ObjKind::Native { .. } | ObjKind::Resolver { .. } => true,
2203 ObjKind::Bound(_) => true,
2204 ObjKind::Proxy(p) => p.target.try_borrow().is_ok_and(|b| b.is_callable()),
2206 _ => false,
2207 }
2208 }
2209}
2210
2211impl Value {
2212 pub fn str(s: impl Into<String>) -> Value {
2213 Value::Str(Rc::new(s.into()))
2214 }
2215 pub fn bigint(b: BigInt) -> Value {
2216 Value::BigInt(Rc::new(b))
2217 }
2218 pub fn object(o: ObjRef) -> Value {
2219 Value::Object(o)
2220 }
2221
2222 pub fn truthy(&self) -> bool {
2224 match self {
2225 Value::Undefined | Value::Null => false,
2226 Value::Bool(b) => *b,
2227 Value::Number(n) => *n != 0.0 && !n.is_nan(),
2228 Value::Str(s) => !s.is_empty(),
2229 Value::BigInt(b) => !b.is_zero(),
2230 Value::Object(o) => o.try_borrow().map_or(true, |b| b.flags & OBJ_FLAG_HTMLDDA == 0),
2231 }
2232 }
2233
2234 pub fn to_number(&self) -> f64 {
2236 match self {
2237 Value::Undefined => f64::NAN,
2238 Value::Null => 0.0,
2239 Value::Bool(b) => {
2240 if *b {
2241 1.0
2242 } else {
2243 0.0
2244 }
2245 }
2246 Value::Number(n) => *n,
2247 Value::Str(s) => {
2248 let t = s.trim();
2249 if t.is_empty() {
2250 0.0
2251 } else if let Some(rest) = t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) {
2252 u64::from_str_radix(rest, 16).map(|n| n as f64).unwrap_or(f64::NAN)
2255 } else if let Some(rest) = t.strip_prefix("0o").or_else(|| t.strip_prefix("0O")) {
2256 u64::from_str_radix(rest, 8).map(|n| n as f64).unwrap_or(f64::NAN)
2257 } else if let Some(rest) = t.strip_prefix("0b").or_else(|| t.strip_prefix("0B")) {
2258 u64::from_str_radix(rest, 2).map(|n| n as f64).unwrap_or(f64::NAN)
2259 } else {
2260 t.parse::<f64>().unwrap_or(f64::NAN)
2261 }
2262 }
2263 Value::BigInt(b) => b.to_f64(),
2264 Value::Object(o) => {
2273 let Ok(b) = o.try_borrow() else {
2274 return f64::NAN;
2275 };
2276 match &b.kind {
2277 ObjKind::Plain if b.primitive().is_some() => b.primitive().map_or(f64::NAN, Value::to_number),
2278 ObjKind::DateObj(ms) => *ms,
2279 ObjKind::Array(_) | ObjKind::Bytes(_) => {
2280 drop(b);
2281 let s = self.to_js_string();
2282 let t = s.trim();
2283 if t.is_empty() {
2284 0.0
2285 } else {
2286 t.parse::<f64>().unwrap_or(f64::NAN)
2287 }
2288 }
2289 ObjKind::Proxy(p) => Value::Object(p.target.clone()).to_number(),
2295 _ => f64::NAN,
2296 }
2297 }
2298 }
2299 }
2300
2301 pub fn type_of(&self) -> &'static str {
2303 match self {
2304 Value::Undefined => "undefined",
2305 Value::Null => "object",
2306 Value::Bool(_) => "boolean",
2307 Value::Number(_) => "number",
2308 Value::Str(s) if s.len() > 8 && s.starts_with("Symbol(") && s.ends_with(')') => "symbol",
2312 Value::Str(_) => "string",
2313 Value::BigInt(_) => "bigint",
2314 Value::Object(o) => {
2315 let Ok(b) = o.try_borrow() else {
2316 return "object";
2317 };
2318 if b.flags & OBJ_FLAG_HTMLDDA != 0 {
2319 "undefined"
2320 } else if b.is_callable() {
2321 "function"
2322 } else {
2323 "object"
2324 }
2325 }
2326 }
2327 }
2328
2329 pub fn to_js_string(&self) -> String {
2331 let mut seen = Vec::new();
2332 self.to_js_string_seen(&mut seen)
2333 }
2334
2335 fn to_js_string_seen(&self, seen: &mut Vec<ObjRef>) -> String {
2349 if seen.len() > 30 {
2350 return String::new();
2351 }
2352 match self {
2353 Value::Undefined => String::from("undefined"),
2354 Value::Null => String::from("null"),
2355 Value::Bool(b) => {
2356 if *b {
2357 String::from("true")
2358 } else {
2359 String::from("false")
2360 }
2361 }
2362 Value::Number(n) => fmt_number(*n),
2363 Value::Str(s) => (**s).clone(),
2364 Value::BigInt(b) => b.to_decimal_string(),
2365 Value::Object(o) => {
2366 let Ok(b) = o.try_borrow() else {
2368 return String::from("[object Object]");
2369 };
2370 if let (ObjKind::Plain, Some(p)) = (&b.kind, b.primitive()) {
2371 return p.to_js_string();
2372 }
2373 match &b.kind {
2374 ObjKind::Array(items) => {
2375 if seen.iter().any(|s| Rc::ptr_eq(s, o)) {
2376 return String::new();
2377 }
2378 seen.push(o.clone());
2379 let parts: Vec<String> = items
2380 .iter()
2381 .map(|v| match v {
2382 Value::Undefined | Value::Null => String::new(),
2383 _ => v.to_js_string_seen(seen),
2384 })
2385 .collect();
2386 seen.pop();
2387 parts.join(",")
2388 }
2389 ObjKind::Bytes(st) => {
2390 let parts: Vec<String> = (0..st.len)
2391 .map(|i| fmt_number(st.get(i).unwrap_or(0.0)))
2392 .collect();
2393 parts.join(",")
2394 }
2395 ObjKind::Function(f) => f
2399 .body()
2400 .source_text()
2401 .unwrap_or_else(|| format!("function {}() {{ [native code] }}", f.name())),
2402 ObjKind::Native { name, .. } => {
2403 let (prefix, rest) = if let Some(s) = name.strip_prefix("get ") {
2404 ("get ", s)
2405 } else if let Some(s) = name.strip_prefix("set ") {
2406 ("set ", s)
2407 } else {
2408 ("", name.as_ref())
2409 };
2410 let tail = if let Some(idx) = rest.find('[') {
2411 rest.get(idx..).unwrap_or(rest)
2412 } else if let Some(idx) = rest.rfind('.') {
2413 rest.get(idx + 1..).unwrap_or(rest)
2414 } else {
2415 rest
2416 };
2417 let norm = if let Some(inner) = tail
2418 .strip_prefix("Symbol(")
2419 .and_then(|s| s.strip_suffix(')'))
2420 {
2421 format!("[{}]", inner)
2422 } else {
2423 String::from(tail)
2424 };
2425 format!("function {}{}() {{ [native code] }}", prefix, norm)
2426 }
2427 ObjKind::Bound(_) => String::from("function () { [native code] }"),
2431 ObjKind::MapObj(_) => String::from("[object Map]"),
2432 ObjKind::SetObj(_) => String::from("[object Set]"),
2433 ObjKind::PromiseObj(_) => String::from("[object Promise]"),
2434 ObjKind::Resolver { .. } => String::from("function () { [native code] }"),
2435 ObjKind::Generator(_) => String::from("[object Generator]"),
2436 ObjKind::RegExpObj(r) => {
2437 let Ok(d) = r.try_borrow() else {
2438 return String::from("/(?:)/");
2439 };
2440 format!("/{}/{}", d.re.source, d.re.flags)
2441 }
2442 ObjKind::Proxy(p) => {
2449 if b.is_callable() {
2450 return String::from("function () { [native code] }");
2451 }
2452 if seen.iter().any(|s| Rc::ptr_eq(s, o)) {
2453 return String::new();
2454 }
2455 seen.push(o.clone());
2456 let s = Value::Object(p.target.clone()).to_js_string_seen(seen);
2457 seen.pop();
2458 s
2459 }
2460 ObjKind::DateObj(ms) if ms.is_nan() => String::from("Invalid Date"),
2465 ObjKind::DateObj(ms) => date_to_iso_string_repr(*ms),
2466 _ => {
2467 let mut cur = Some(o.clone());
2470 for _ in 0..8 {
2471 let Some(c) = cur else { break };
2472 let Ok(cb) = c.try_borrow() else { break };
2473 if let Some(Value::Str(t)) = cb.props.get("Symbol(Symbol.toStringTag)") {
2474 return format!("[object {}]", t);
2475 }
2476 cur = cb.proto.clone();
2477 }
2478 String::from("[object Object]")
2479 }
2480 }
2481 }
2482 }
2483 }
2484
2485 pub fn strict_eq(&self, other: &Value) -> bool {
2487 match (self, other) {
2488 (Value::Undefined, Value::Undefined) => true,
2489 (Value::Null, Value::Null) => true,
2490 (Value::Bool(a), Value::Bool(b)) => a == b,
2491 (Value::Number(a), Value::Number(b)) => a == b,
2492 (Value::Str(a), Value::Str(b)) => a == b,
2493 (Value::BigInt(a), Value::BigInt(b)) => a.cmp(b) == core::cmp::Ordering::Equal,
2494 (Value::Object(a), Value::Object(b)) => {
2502 if Rc::ptr_eq(a, b) {
2503 return true;
2504 }
2505 if let (Ok(ba), Ok(bb)) = (a.try_borrow(), b.try_borrow()) {
2506 if let (ObjKind::HostRef(ha), ObjKind::HostRef(hb)) = (&ba.kind, &bb.kind) {
2507 if ha.by_id() {
2508 return ha == hb;
2509 }
2510 }
2511 }
2512 false
2513 }
2514 _ => false,
2515 }
2516 }
2517
2518 pub fn same_ref(&self, other: &Value) -> bool {
2520 match (self, other) {
2521 (Value::Object(a), Value::Object(b)) => Rc::ptr_eq(a, b),
2522 _ => self.strict_eq(other),
2523 }
2524 }
2525}
2526
2527pub const MAX_DENSE_ARRAY_LEN: usize = 1 << 23;
2529
2530pub fn fmt_number(n: f64) -> String {
2532 if n.is_nan() {
2533 return String::from("NaN");
2534 }
2535 if n.is_infinite() {
2536 return String::from(if n > 0.0 { "Infinity" } else { "-Infinity" });
2537 }
2538 if n == 0.0 {
2539 return String::from("0");
2540 }
2541 if libm::trunc(n) == n && libm::fabs(n) < 9007199254740992.0 {
2544 let neg = n < 0.0;
2546 let mut v = libm::fabs(n) as u64;
2547 let mut buf = [0u8; 20];
2548 let mut i = buf.len();
2549 loop {
2550 i -= 1;
2551 if let Some(b) = buf.get_mut(i) {
2552 *b = b'0' + (v % 10) as u8;
2553 }
2554 v /= 10;
2555 if v == 0 || i == 1 {
2556 break;
2557 }
2558 }
2559 if neg {
2560 i -= 1;
2561 if let Some(b) = buf.get_mut(i) {
2562 *b = b'-';
2563 }
2564 }
2565 return String::from(core::str::from_utf8(buf.get(i..).unwrap_or(&[])).unwrap_or("0"));
2566 }
2567 super::numfmt::to_string10(n)
2569}
2570
2571fn date_to_iso_string_repr(ms: f64) -> String {
2576 let total_ms = libm::floor(ms) as i64;
2577 let days = total_ms.div_euclid(86_400_000);
2578 let ms_of_day = total_ms.rem_euclid(86_400_000);
2579 let z = days + 719468;
2580 let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
2581 let doe = z - era * 146097;
2582 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
2583 let y = yoe + era * 400;
2584 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2585 let mp = (5 * doy + 2) / 153;
2586 let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
2587 let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
2588 let y = if m <= 2 { y + 1 } else { y };
2589 let hh = (ms_of_day / 3_600_000) as u32;
2590 let mm = ((ms_of_day / 60_000) % 60) as u32;
2591 let ss = ((ms_of_day / 1000) % 60) as u32;
2592 let mms = (ms_of_day % 1000) as u32;
2593 format!(
2594 "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z",
2595 y, m, d, hh, mm, ss, mms
2596 )
2597}
2598
2599pub fn wrap_f64_to_u64(v: f64) -> u64 {
2606 if !v.is_finite() {
2607 return 0;
2608 }
2609 let t = libm::trunc(v);
2610 const TWO63: f64 = 9223372036854775808.0;
2611 if (-TWO63..TWO63).contains(&t) {
2612 return (t as i64) as u64;
2613 }
2614 let m = libm::fmod(t, 18446744073709551616.0);
2616 if m < 0.0 {
2617 (m + 18446744073709551616.0) as u64
2618 } else {
2619 m as u64
2620 }
2621}