Skip to main content

atmos/os_lib/ecma/
value.rs

1//! JS ランタイム値の表現。
2//!
3//! ヒープオブジェクトは `Rc<RefCell<Obj>>` で表現する(参照カウントGC)。
4//! 循環参照はリークするが、ページ遷移ごとに `JsRuntime` を破棄するため許容する。
5
6use 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/// プロパティのキー(16 バイト)。15 バイトまではインラインで持ち、16 バイト以上は `Rc<str>` で共有する。
20///
21/// 【2026-11-01】YouTube の視聴ページでは生存オブジェクトが 60 万個を超え、ヒープが尽きる。キーを
22/// `String` で持つと短い名前でもキーごとに 1 ブロックを確保していた。
23/// 【2026-11-03】24 バイトから 16 バイトへ縮小(`SmallPropMap` の 1 要素 `(PropKey, Value)` が 40B→32B に縮小)。
24/// - `data[0] & 1 == 1`(Inline): `len = data[0] >> 1`(0〜15)、`data[1..1+len]` に UTF-8 バイト列を保持。
25/// - `data[0] & 1 == 0`(Shared): `Rc<str>` のデータポインタ(`RcBox<str>` 内なので 8 バイト境界、`bit 0 == 0`)を
26///   `data[0..8]`(LE)、長さを `data[8..16]`(LE)に保持し、構文木の `Rc<str>` やオブジェクト複製間で共有する。
27#[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            // SAFETY: `inline_from_str` が有効な UTF-8 文字列(`len <= 15`)を `data[1..1+len]` に書き込んでいる。
98            unsafe { core::str::from_utf8_unchecked(self.data.get_unchecked(1..1 + len)) }
99        } else {
100            // SAFETY: `self` が `raw_rc_ptr()` の指す `Rc<str>` の強参照を保持している。
101            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            // SAFETY: `self` が有効な `Rc<str>` の強参照を保持している。
111            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            // SAFETY: `self` が有効な `Rc<str>` の強参照を保持している。
122            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
245/// `Obj::props`/`.accessors`/`.attrs` のプロパティ表。
246pub type PropMap<V> = SmallPropMap<V>;
247
248type BigPropMap<V> = IndexMap<PropKey, V, core::hash::BuildHasherDefault<FnvHasher>>;
249
250/// この個数までは配列 1 本で持ち、超えたらハッシュ表(`IndexMap`)に切り替える。
251const SMALL_PROPS_MAX: usize = 8;
252
253/// `Rc<str>` を鍵にした表を `&str` で引くときの問い合わせ(`key_eq` で比べる。`str` の `==` は `memcmp` を呼ぶ)。
254/// ハッシュは `str` と同じ。
255pub(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/// 短い名前の比較。長さが違えば即座に偽、16 バイトまでは先頭と末尾を語単位で比べる(`memcmp` を呼ばない)。
270/// 【2026-11-05】プロパティ・変数の検索の `==` が毎回 `memcmp` を呼んでいた(`[PCPROF]` の上位)。
271#[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    // 【2026-11-05】1 バイトずつ比べるループはコンパイラが `memcmp` の呼び出しに置き換え、短い名前では呼び出しの方が
278    // 重かった(YouTube で変数の検索〔`VarMap::position`〕の `memcmp` が JS のコアの上位)。先頭と末尾を重ねて読んで比べる。
279    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/// プロパティ表(挿入順を保つ)。少ないうちは `(キー, 値)` の配列 1 本で線形に探し、
292/// `SMALL_PROPS_MAX` 個を超えたら `IndexMap` に切り替える。
293///
294/// 【2026-10-29】従来は常に `IndexMap` で、空でも 56 バイト、要素を入れると要素の配列とハッシュの
295/// 添字表の 2 ブロックを確保していた。YouTube の視聴ページでは生存オブジェクトが約 50 万個あり、
296/// ほとんどはプロパティが数個しかない(TODO A7)。挿入順・`shift_remove` の意味は `IndexMap` と同じ。
297#[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    /// キーの位置(挿入順の添字)を返す。
321    #[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    /// 値を入れる(既にあれば値だけ替えて位置はそのまま、古い値を返す。`IndexMap::insert` と同じ)。
346    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    /// 取り除く(後ろの要素を詰めて順序を保つ)。
369    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    /// 取り除く(末尾の要素と入れ替える。`IndexMap::swap_remove` と同じ)。
376    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    /// `IndexMap::entry` 相当(`or_insert`・`or_insert_with`・`or_default` だけ)。
412    pub fn entry(&mut self, k: PropKey) -> PropEntry<'_, V> {
413        PropEntry { map: self, key: k }
414    }
415    /// 添字 `i` 番目(挿入順)の組。
416    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
424/// [`SmallPropMap::entry`] の戻り値。
425pub 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        // 無ければ入れる(新しいキーはどちらの形でも末尾に入る)。
438        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
461/// `SmallPropMap` の反復子(挿入順)。
462pub 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
503/// 所有権ごとの反復子(挿入順)。
504pub 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/// 変数の表(スコープ)。キーは `Rc<str>`(構文木や巻き上げの名前と共有し、宣言のたびに確保しない)。
540///
541/// 【2026-10-24】関数呼び出しのスコープは変数が数個しかないのに、ハッシュ表(要素の配列と
542/// 添字表の 2 ブロック)を毎回確保していた。宣言順の配列 1 本に持ち、`VAR_INDEX_MIN` 個を
543/// 超えたら(グローバル等)ハッシュの添字を足す。探索は名前の `Rc` の番地の一致を先に見る。
544/// 【2026-11-03】`Small(Vec)` と `Big(Box)` の enum にすることで `VarMap` を 32B→24B に縮小し、
545/// `Scope` を 48B→40B(`RcBox<RefCell<Scope>>` を 72B→64B の 2 のべき乗境界内)へ収める。
546#[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
558/// この個数を超えたらハッシュの添字を作る。
559const 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        // まず番地だけで探す(同じスクリプトの名前は `Rc` を共有する)。無いときだけ文字列を比べ、
598        // 先頭の 1 バイトで大半を落とす(圧縮された JS は 1 文字の名前ばかりで、長さでは落ちない)。
599        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    /// `i` 番目の名前と値。
612    #[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    /// 名前の位置。
618    pub fn position_of(&self, k: &str) -> Option<usize> {
619        self.position(k)
620    }
621
622    /// `i` 番目の名前の番地が `key` なら値を返す。
623    #[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    /// 値を入れる(既にあれば値だけ置き換え、前の値を返す。順序は保つ)。
637    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    /// 取り除く(後ろの順序は詰める)。
658    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    /// 確保済みの `entries` 容量を残したまま空にする(スコープ再利用プール用)。
704    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    /// 余分な確保容量を切り詰める(クロージャに捕捉されて長寿命化するスコープ用)。
716    pub fn shrink_to_fit(&mut self) {
717        self.entries_vec_mut().shrink_to_fit();
718    }
719
720    /// 少なくとも `n` 要素分の容量を確保する。
721    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    /// 空または重複のない `Small` 状態に、キー比較なしでエントリを末尾追加する。
736    /// `VAR_INDEX_MIN` を超えた場合は呼び出し完了後に `promote_if_big` を呼ぶこと。
737    #[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    /// 巻き上げ変数リストのうち先頭 `n_prefix` 件(一意な仮引数)に含まれないものだけを末尾追加する。
748    /// `hoisted` 自体が重複なしであるため、追加済みの巻き上げ変数同士の比較を省略できる。
749    #[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    /// `push_fresh_small` / `push_hoisted_missing` による一括追加後、閾値超なら `Big` へ昇格させる。
774    #[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
790/// 空のうちは確保しない `PropMap`(8 バイト)。
791///
792/// 【2026-10-19】`Obj` は `props`/`accessors`/`attrs` の 3 つの `IndexMap`(各 56 バイト)を
793/// 持ち 256 バイトあった。getter/setter と属性はほとんどのオブジェクトで空なので、
794/// 中身ができたときだけ確保する。YouTube の kevlar_base(10.8MB)の実行で
795/// 512MB のヒープを使い切っていた。
796pub 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    /// `IndexMap::remove` と同じ(末尾と入れ替えて取り除く)。
830    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
861/// `&LazyPropMap` の反復子(空なら何も返さない)。
862pub 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
886/// 循環ゴミ回収の台帳に未登録であることを表す番号。
887pub const NO_GC_SLOT: u32 = u32::MAX;
888
889/// 作った `Obj` を循環ゴミ回収の台帳に載せる(カーネルのみ。ホストの試験では何もしない)。
890fn 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
901/// ヒープ上のオブジェクトへの共有参照。
902pub type ObjRef = Rc<RefCell<Obj>>;
903
904/// ネイティブ関数のシグネチャ。`Err(Value)` は JS の throw を表す。
905pub type NativeFn = fn(&mut Interp, this: Value, args: &[Value]) -> Result<Value, Value>;
906
907/// JS の値。プリミティブ + オブジェクト参照。
908#[derive(Clone)]
909pub enum Value {
910    Undefined,
911    Null,
912    Bool(bool),
913    Number(f64),
914    Str(Rc<String>),
915    /// 任意精度整数 BigInt。
916    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;
923/// 仮引数がすべてデフォルト値なし・レストなし・重複なしの単純識別子であるか。
924pub const FN_FLAG_SIMPLE_PARAMS: u8 = 1 << 3;
925
926/// 関数の静的コード情報(同一関数定義から作られる全インスタンスで Rc 共有)。
927#[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/// ユーザー定義関数のデータ(静的情報 + クロージャ環境)。
955/// 【2026-11-02】静的メタデータ(名前・引数・本体・フラグ)を `SharedFnInfo` へ切り出し、
956/// 関数インスタンスのサイズを 56→24 バイトへ 57% 縮小(YouTube 視聴ページの生存関数約 23 万個で
957/// 約 7.36MB 削減、TODO A7a)。
958/// 【2026-11-03】24 バイトになったため `ObjKind::Function(FunctionData)` として `ObjKind`(32 バイト)内に
959/// インライン格納し、関数ごとの `Rc<FunctionData>` ヒープ確保(約 23 万ブロック・約 11〜14MB)を廃止。
960#[derive(Clone)]
961pub struct FunctionData {
962    pub shared: Rc<SharedFnInfo>,
963    /// クロージャが捕捉した定義時スコープ。
964    pub closure: Rc<RefCell<Scope>>,
965    /// アロー関数が捕捉した `this`。
966    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
1008/// IEEE 754 half-precision float (16-bit) ユーティリティ (ES2025 Float16Array/getFloat16/setFloat16)
1009pub 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/// オブジェクトの種別。Plain 以外は内部表現を持つ。
1091/// TypedArray の共有バイト記憶域(共有のバイト列のうちバイト位置 `off` から `len` 要素)。
1092#[derive(Clone)]
1093pub struct ByteStore {
1094    pub buf: Rc<RefCell<Vec<u8>>>,
1095    /// `buf` 内の開始バイト位置(`byteOffset`)。
1096    pub off: usize,
1097    /// 要素数(`length`)。バイト長は `len * elem_size()`。
1098    pub len: usize,
1099    /// 0=Uint8, 1=Int8, 2=Uint8Clamped, 3=Int16, 4=Uint16, 5=Int32, 6=Uint32, 7=Float16, 8=Float32, 9=Float64,
1100    /// 10=BigInt64, 11=BigUint64(要素は BigInt。`get_value`/`set_value` で出し入れする)。
1101    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    /// 同じ記憶域の要素範囲 `[start, start+len)` を指す(`subarray`)。
1157    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    /// 同じ記憶域のバイト位置 `byte_offset` から `kind` 型の要素 `elem_len` 個を指す(`new TypedArray(buffer, byteOffset, length)`)。
1165    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    /// BigInt64Array/BigUint64Array か。
1198    #[inline]
1199    pub const fn is_bigint_kind(kind: u8) -> bool {
1200        matches!(kind, 10 | 11)
1201    }
1202
1203    /// 要素を JS の値で読む(BigInt の配列は BigInt、それ以外は Number)。
1204    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    /// 要素を JS の値で書く(BigInt の配列は 2^64 で丸めた BigInt、それ以外は数値化して `set`)。
1224    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    /// この配列が見ている範囲のバイトを、`next` が返す値で埋める(`crypto.getRandomValues`)。
1246    /// 数値を経由しないので、要素の幅に関係なく全部のビットが埋まる。
1247    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    /// 要素型に合わせてリトルエンディアンで変換して書く。
1257    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                // 数値の経路(`fill` 等)。2^64 で丸める(BigInt の値は `set_value` で書く)。
1289                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            // 偶数への丸め(Uint8ClampedArray の仕様)。
1303            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/// Proxy(target とハンドラ)。
1322#[derive(Clone)]
1323pub struct ProxyData {
1324    pub target: ObjRef,
1325    pub handler: ObjRef,
1326    /// `Proxy.revocable` の `revoke()` 後は true(以降の内部操作は TypeError)。
1327    pub revoked: core::cell::Cell<bool>,
1328}
1329
1330/// `Function.prototype.bind()` が返す束縛済み関数データ。
1331#[derive(Clone)]
1332pub struct BoundData {
1333    pub target: Value,
1334    pub bound_this: Value,
1335    pub bound_args: Vec<Value>,
1336}
1337
1338/// ホストが持つ物の識別子(種類の番号と、その種類の中での番号)。
1339/// `class` の最上位ビット(`HOST_CLASS_BY_ID`)が立つ種類は、ホスト側の表の番号から毎回ハンドルを作り直す物(DOM 要素)で、
1340/// 同じ `id` のハンドルは `===` で等しい。立たない種類(`style`・`document` など)は、作った 1 つ 1 つが別の物(`Rc::ptr_eq`)。
1341#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1342pub struct HostRef {
1343    pub class: u8,
1344    pub id: usize,
1345}
1346
1347/// `HostRef::class` の最上位ビット: 同じ `id` のハンドルは `===` で等しい。
1348pub const HOST_CLASS_BY_ID: u8 = 0x80;
1349
1350impl HostRef {
1351    /// 同じ `id` のハンドルが `===` で等しい種類か。
1352    #[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    /// 1 バイト型の TypedArray(Uint8Array / Int8Array / Uint8ClampedArray)。実バイト列を
1368    /// 共有の記憶域に持つ(`subarray`・`.buffer`・DataView が同じ記憶域を指す)。
1369    /// 【2026-10-18】従来は `ObjKind::Array`(要素ごとに `Value`)を流用しており、1 バイトに
1370    /// 16 バイト以上使い、`subarray` も複写だったため、YouTube の動画データ(数百 KB〜MB)の
1371    /// 解析でヒープが尽きた。
1372    Bytes(Box<ByteStore>),
1373    /// ホストが持つ物への参照(DOM 要素など)。ECMAScript の核は中身を知らず、識別子(`HostRef`)だけを持つ。
1374    /// 【2026-11-19 手順 7】従来の `DomElement(usize)`。種類(`class`)は `web_apis` 側が決める
1375    /// (DOM 要素・style・classList・document・storage など。`dom_bridge::HOST_*`)。`Rc` を持たないので GC は辿らない。
1376    HostRef(HostRef),
1377    /// `entries`/`keys`/`values` が返す軽量イテレータ(`make_iterator()`)。内部の状態は `props` の `_items`/`_pos`。
1378    /// 【2026-11-19 手順 7】従来は `Host("iterator")`。ECMAScript の機能なので `HostRef` にはしない。
1379    Iter,
1380    /// ジェネレータの `return` を本体へ伝える合図(`Host("_gen_return")` だった。例外として投げて呼び出しを抜ける)。
1381    GenReturn,
1382    /// Map: 挿入順を保つ (key, value) リスト(キー等価は SameValueZero 近似)。
1383    MapObj(Vec<(Value, Value)>),
1384    /// Set: 挿入順を保つ値リスト。
1385    SetObj(Vec<Value>),
1386    /// Promise。状態は共有可変(then/await で参照される)。
1387    PromiseObj(Rc<RefCell<PromiseState>>),
1388    /// resolve/reject 関数(Promise 状態を束縛したクロージャ相当)。
1389    Resolver {
1390        state: Rc<RefCell<PromiseState>>,
1391        reject: bool,
1392    },
1393    /// Generator(遅延評価。resume のたびに本体を replay して次の yield まで進める)。
1394    Generator(Rc<RefCell<GenState>>),
1395    /// RegExp(コンパイル済みパターン + lastIndex)。
1396    RegExpObj(Rc<RefCell<super::regex::RegExpData>>),
1397    /// Proxy(target とハンドラ。トラップ未定義時は target にフォワード)。
1398    Proxy(Box<ProxyData>),
1399    /// `Function.prototype.bind()` が返す束縛済み関数。呼び出し時は
1400    /// `bound_args ++ 実引数` を `bound_this` を this として `target` に渡す。
1401    Bound(Box<BoundData>),
1402    /// `Date`。内部値は UTC エポックミリ秒(不正な日時は `f64::NAN`。仕様の Invalid Date 相当)。
1403    DateObj(f64),
1404    /// クラスのプライベート要素記述子(`class_scope` 内部専用。スクリプトへは露出しない)。
1405    PrivateDesc(Box<PrivateDescriptor>),
1406}
1407
1408/// クラスプライベート要素の種別(インスタンス/静的のフィールド・メソッド・アクセサ)。
1409#[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/// クラスプライベート要素の識別情報(クラス評価ごとに一意な `brand_id` を持つ)。
1420#[derive(Clone)]
1421pub struct PrivateDescriptor {
1422    pub brand_id: u64,
1423    pub name: Rc<str>,
1424    pub kind: PrivateKind,
1425}
1426
1427impl ObjKind {
1428    /// ホスト物なら、その識別子。
1429    #[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/// Generator の完了・再開種別。
1439#[derive(Clone)]
1440pub enum GenCompletion {
1441    Normal(Value),
1442    Throw(Value),
1443    Return(Value),
1444}
1445
1446/// Generator の状態。
1447///
1448/// 【2026-11-30】本体は原則として `interp::gen_vm` の VM で実行し、`yield` で実行状態(`vm`)を
1449/// 保存して本当に中断・再開する(副作用は 1 回だけ、`return()`/`throw()` は中断位置から finally・
1450/// IteratorClose を通る、長い generator も線形時間)。VM で扱えない構文(`with` の中の `yield` など)を
1451/// 含む本体だけ、従来どおり resume のたびに本体を先頭から再実行(replay)し、N 番目の yield で中断する
1452/// (`sent`・`done_stmts` などの欄はその方式用)。
1453pub struct GenState {
1454    /// generator 関数本体(params/body/closure を保持)。
1455    pub func: FunctionData,
1456    /// 呼び出し時の実引数。
1457    pub args: Vec<Value>,
1458    /// 呼び出し時の `this`。
1459    pub this: Value,
1460    /// 呼び出し時に束縛し終えた仮引数の値(再実行のたびに仮引数の分解・既定値を評価し直さないため)。
1461    pub param_vars: Vec<(Rc<str>, Value)>,
1462    /// 既に通過した各 yield に `.next(v)`/`.throw(e)`/`.return(v)` で渡された結果。
1463    pub sent: Vec<GenCompletion>,
1464    /// 最初の `.next()` を消費済みか(最初の next の引数は捨てられる)。
1465    pub started: bool,
1466    /// 完了済みか(以降の next は常に done:true)。
1467    pub done: bool,
1468    /// 完了時の return 値(done:true の value)。
1469    pub returned: Value,
1470    /// 初回起動時に作成した実行用スコープ(リプレイ間でローカル変数を維持し、先頭文・巻き上げの二重実行を防ぐ)。
1471    pub call_scope: Option<Rc<RefCell<Scope>>>,
1472    /// 完了した文の範囲情報 `(end_stmt_cursor, end_scope_cursor, end_ctx_cursor, end_yield_counter, val)`。
1473    pub done_stmts: Vec<Option<DoneStmtEntry>>,
1474    /// リプレイ間で維持される子ブロックスコープ列。
1475    pub saved_scopes: Vec<Rc<RefCell<Scope>>>,
1476    /// 実行方式(`GEN_MODE_*`。最初の resume で決める)。2026-11-30
1477    pub(crate) vm_mode: u8,
1478    /// VM 方式の中断中の実行状態(命令位置・値スタック・スコープ・try/反復子の表)。実行中は取り出して `None`。
1479    pub(crate) vm: Option<alloc::boxed::Box<super::interp::gen_vm::GenFrame>>,
1480    /// 本体を実行中か(同期 generator の再入は TypeError、非同期は待ち行列へ)。
1481    pub(crate) executing: bool,
1482}
1483
1484/// generator の実行方式: まだ決めていない。
1485pub const GEN_MODE_UNKNOWN: u8 = 0;
1486/// 本体を VM(`interp::gen_vm`)で中断・再開する。
1487pub const GEN_MODE_VM: u8 = 1;
1488/// VM で扱えない本体。従来の replay 方式で動かす。
1489pub const GEN_MODE_REPLAY: u8 = 2;
1490
1491/// 完了したジェネレータ文の範囲情報 `(end_stmt_cursor, end_scope_cursor, end_ctx_cursor, end_yield_counter, val)`。
1492pub 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/// Promise の状態。
1512#[derive(Clone, Copy, PartialEq)]
1513pub enum PromiseStatus {
1514    Pending,
1515    Fulfilled,
1516    Rejected,
1517}
1518
1519/// settle 時に消費する then 反応。
1520pub struct Reaction {
1521    pub on_fulfilled: Option<Value>,
1522    pub on_rejected: Option<Value>,
1523    /// この反応の結果を反映する派生 Promise。
1524    pub result: Rc<RefCell<PromiseState>>,
1525}
1526
1527pub struct PromiseState {
1528    pub status: PromiseStatus,
1529    /// fulfilled の値、または rejected の理由。
1530    pub value: Value,
1531    /// pending 中に登録された反応(settle 時にマイクロタスクへ)。
1532    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
1545/// マイクロタスク(then 反応の遅延実行単位)。
1546pub struct Job {
1547    /// 実行するハンドラ(None なら値をそのまま伝播)。
1548    pub handler: Option<Value>,
1549    pub arg: Value,
1550    pub is_fulfill: bool,
1551    pub result: Rc<RefCell<PromiseState>>,
1552}
1553
1554/// アクセサ記述子(get/set の一方または両方)。
1555#[derive(Clone, Default)]
1556pub struct Accessor {
1557    pub get: Option<Value>,
1558    pub set: Option<Value>,
1559}
1560
1561/// オブジェクトの稀な拡張データ(アクセサ記述子、属性フラグ表、配列の穴)。
1562/// 通常の素のオブジェクト・関数・配列の大多数(98%以上)はこれらを持たないため、
1563/// `Option<Box<RareData>>`(8バイト)として分離し、`Obj` 本体のサイズを 96B → 72B(25%縮小)に抑える。
1564#[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    /// 値の包みオブジェクト(`new Number(5)`・`new String("a")`・`new Boolean(false)`・`Object(1)`)の中身(仕様の [[NumberData]] 等)。
1570    /// 【2026-11-18】以前は包みが空のオブジェクトで、`new Number(5)+1` が NaN・`new String("ab").length` が undefined だった。
1571    pub primitive: Option<Value>,
1572    /// クラスプライベートメソッド/アクセサ用のブランド一覧(クラス評価ごとの一意 ID)。
1573    pub private_brands: Vec<u64>,
1574    /// クラスプライベートフィールドの実値(`(brand_id, 名前, 値)`)。`props` には入れないため列挙・`hasOwnProperty`・`in` に露出しない。
1575    pub private_fields: Vec<(u64, Rc<str>, Value)>,
1576    /// `Intl.Locale` の内部スロット `[[Locale]]`(`hasOwnProperty` / `ownKeys` に露出しない)。
1577    pub intl_locale: Option<Rc<str>>,
1578    /// `Error` インスタンスの `[[ErrorData]]` 内部スロット兼スタック文字列(`hasOwnProperty` に露出しない)。
1579    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;
1586/// 仕様の [[IsHTMLDDA]](`document.all`)。typeof は "undefined"・真偽値は偽・`== null` は真。
1587pub const OBJ_FLAG_HTMLDDA: u8 = 1 << 4;
1588/// 関数の仮想自前プロパティ `name` が削除または実体化済みであることを示すビット。
1589pub const OBJ_FLAG_NO_FN_NAME: u8 = 1 << 5;
1590/// 関数の仮想自前プロパティ `length` が削除または実体化済みであることを示すビット。
1591pub const OBJ_FLAG_NO_FN_LENGTH: u8 = 1 << 6;
1592
1593/// 型付き配列の実体に付けている内部・組み込みのプロパティ(列挙しない。2026-11-16)。
1594pub 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/// 配列・文字列の添字として読めるキー(`"0"`・`"12"`)。`"01"`・`"+1"`・`" 1"` は仕様上ふつうの名前なので `None`。
1600/// 【2026-11-18】`key.parse::<usize>()` は `"01"` を 1 と読み、`a["01"]=2` が a[1] に入っていた。
1601#[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
1610/// `"-1"`・`"1.5"` のように、数値を文字列にした形そのもののキー(型付き配列では添字として扱い、
1611/// 範囲外なら置かない。仕様の CanonicalNumericIndexString)。
1612pub fn is_canonical_numeric_key(k: &str) -> bool {
1613    if k == "-0" {
1614        return true;
1615    }
1616    // 数字・符号・`.`・`e`・`Infinity` だけの短い形に限る(ほとんどのキーはここで落ちる)。
1617    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
1670/// ヒープオブジェクト本体。名前付きプロパティ + プロトタイプ + 種別。
1671pub 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    /// 循環ゴミ回収(`cycle_gc`)の台帳の番号(未登録は `NO_GC_SLOT`)。
1677    pub gc_slot: u32,
1678    /// 状態フラグ(frozen, sealed, non_extensible, null_proto を 1 バイトに集約)。
1679    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    /// 関数の「種類の名前」(`Object.getPrototypeOf(fn).constructor.name`)。普通は `Function`。
1751    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    /// 値の包みオブジェクトの中身(包みでなければ `None`)。
1763    #[inline]
1764    pub fn primitive(&self) -> Option<&Value> {
1765        self.rare.as_ref().and_then(|r| r.primitive.as_ref())
1766    }
1767    /// `[[ErrorData]]` 内部スロットを持つ Error インスタンスか。
1768    #[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    /// `[[ErrorData]]` 内部スロットのスタック文字列。
1773    #[inline]
1774    pub fn error_stack(&self) -> Option<&str> {
1775        self.rare.as_ref().and_then(|r| r.error_stack.as_deref())
1776    }
1777    /// `[[ErrorData]]` 内部スロットのスタック文字列を設定する。
1778    #[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    /// この関数オブジェクトが未削除・未実体化の仮想自前プロパティ(`name` または `length`)を持つか。
1917    #[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    /// 関数の仮想自前プロパティ(`name` / `length`)を削除済み(または `props`/`accessors` 実体化済み)としてマークする。
1933    #[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    /// 関数の `prototype`(通常の `function` は初回参照時に作る)。
1976    ///
1977    /// 【2026-10-24】以前は関数を作るたびに `prototype` のオブジェクトを作っていた。ほとんどの
1978    /// 関数(コールバック・メソッド)はコンストラクタとして使われないのに、関数 1 つにつき
1979    /// オブジェクトが 2 つになり、しかも `f.prototype.constructor === f` の循環で参照カウントでは
1980    /// 解放されず循環回収待ちになった(YouTube の視聴ページでヒープが尽きた一因)。
1981    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    /// 配列を `new_len` 要素まで伸ばす。増えた要素は穴(値は undefined だが要素として存在しない)。
2002    /// 上限 [`MAX_DENSE_ARRAY_LEN`] を超えるなら何もせず false(配列は要素を詰めて持つので、疎な巨大配列は作れない)。
2003    ///
2004    /// 【2026-11-12】以前は `a[4294967294] = 1` や `a.length = 2**32 - 1` でそのまま確保しようとして
2005    /// (68GB)、確保の失敗でアプリごと落ちていた。また、伸びた分が穴にならず `a.length = 5` の後の
2006    /// `a.indexOf(undefined)` が -1 にならなかった。
2007    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    /// `i` 番目の穴の印を消す(そこへ値を書いたとき。undefined を書いても穴ではなくなる)。
2035    #[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    /// 自身のプロパティ `key` を列挙するか(属性の表が無いものの既定を含む)。
2046    ///
2047    /// 【2026-11-16】属性を持たない次の 2 つは、仕様どおり列挙しない(属性の表を作らずに判定する。
2048    /// 関数ごとに表を持たせると、YouTube の数万のコンストラクタで数 MB 増えるため):
2049    /// - 関数の `prototype`。
2050    /// - `F.prototype.constructor`(値が関数で、その関数の `prototype` がこのオブジェクト)。
2051    ///   以前は `for (k in new F)` に `constructor` が出ていた。
2052    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            // `arguments`(配列で持つ)の `callee` は列挙しない。
2066            "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    /// 自身のプロパティ `keys` のうち、あるものを「列挙しない」にする(書き込み・設定の変更はできるまま)。
2079    /// 例外オブジェクトの `message`・`stack` や、組み込みが付けるプロパティ用。
2080    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    /// 配列の `i` 番目が穴か。
2088    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    /// 配列の穴の一覧(`len` 要素。穴が無ければ空)。
2097    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    /// 軽量イテレータ(`ObjKind::Iter`)。
2121    pub fn iter_obj() -> ObjRef {
2122        gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::Iter))))
2123    }
2124    /// ジェネレータの `return` の合図(`ObjKind::GenReturn`)。
2125    pub fn gen_return() -> ObjRef {
2126        gc_track(Rc::new(RefCell::new(Obj::new(ObjKind::GenReturn))))
2127    }
2128    /// ホスト物のハンドルを作る(DOM 要素の `Obj::dom` は `dom_bridge.rs`)。
2129    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        // `lastIndex` は自前のデータプロパティ(書込み可・列挙不可・設定不可。`get_attr_or_default` が属性を与える)。
2152        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            // Proxy は target が callable なら callable(自己借用時は安全に false)。
2205            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    /// ECMAScript ToBoolean。
2223    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    /// ECMAScript ToNumber(簡易)。
2235    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                    // `StringNumericLiteral` は `0x`/`0o`/`0b` 整数リテラルも受理する(符号無し)。
2253                    // `Number("0x1F")`===31 のような変換が以前は常に `NaN` になっていた。
2254                    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            // `Date` は ToPrimitive(hint=number) で `valueOf()`(エポックミリ秒)相当になる
2265            // (仕様上は他の型も `valueOf`/`Symbol.toPrimitive` を経由し得るが、この処理系は
2266            // それらを汎用的にはサポートしないため `Date` だけ直接特殊扱いする)。
2267            // これにより `date2 - date1` や `date1 < date2` の算術/比較が素で動くようになる。
2268            // `Array` も ToPrimitive(hint=default/number) で `toString()`(`join(',')`)した
2269            // 文字列を数値変換する(`[5]*2`===10、`[]+1`===1 のような定番イディオムが
2270            // 以前は常に `NaN` になっていた)。単一要素なら中身がそのまま数値化され、空配列は
2271            // `0`、複数要素は通常カンマ区切り文字列がパース不能で `NaN` になる(仕様どおり)。
2272            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                    // `Array.isArray`/`Object.keys`/`structuredClone`/`to_js_string` 等、
2290                    // 他の多くの操作は既に target へ委譲する透過性修正済みだったのに、
2291                    // 数値変換だけ見落とされていた(`+new Proxy([5],{})`===`5`、
2292                    // `new Proxy([5],{})*2`===`10` のような ToPrimitive(hint=number)
2293                    // 経由の算術が常に `NaN` になっていたバグ)。
2294                    ObjKind::Proxy(p) => Value::Object(p.target.clone()).to_number(),
2295                    _ => f64::NAN,
2296                }
2297            }
2298        }
2299    }
2300
2301    /// 型を表す `typeof` 文字列。
2302    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            // シンボルは `Symbol(…)` の形の文字列で近似している。`typeof` は "symbol" を返す(2026-11-13。
2309            // 以前は "string" で、`typeof Symbol.iterator === "symbol"` を確かめるコード〔Babel の `_typeof`・
2310            // lodash の `isSymbol` など〕が別の道を通っていた)。同じ形の普通の文字列は区別できない。
2311            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    /// ECMAScript ToString(簡易・表示用)。
2330    pub fn to_js_string(&self) -> String {
2331        let mut seen = Vec::new();
2332        self.to_js_string_seen(&mut seen)
2333    }
2334
2335    /// `to_js_string` の内部実装。`Array` の要素文字列化は再帰的に自分自身の
2336    /// `to_js_string` を呼ぶため、`var a=[1]; a.push(a); a.join()`(あるいは
2337    /// `String(a)`/テンプレートリテラル補間等、内部的に同じ経路を通る操作)が
2338    /// 循環参照でスタックオーバーフロー(この no_std 環境ではクラッシュ/ハングに
2339    /// なり得る)していた。`structuredClone`/`JSON.stringify`/`console.log` で
2340    /// 既に修正済みの「祖先を追跡して打ち切る」パターンをここにも適用し、
2341    /// 既に祖先に現れた配列を再訪した時点で空文字列を返して打ち切る
2342    /// (実ブラウザは無条件のスタックオーバーフローで `RangeError` を投げるが、
2343    /// この処理系は例外化されない Rust ネイティブ再帰でのクラッシュを避ける
2344    /// ことを優先し、値としては空文字列で打ち切る簡略挙動とする。
2345    /// `a=[1]; a.push(a); a.join()` は `"1,1,"` になる——2番目の要素 `a` 自身の
2346    /// `to_js_string()` が、その内部で自分自身を再訪した時点(3階層目)で
2347    /// 空文字列に切り詰められるため)。
2348    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                // 多重可変借用中(Map.set での自己参照など)は panic させず既定表現に逃がす。
2367                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                    // 定義のソースを記録できた関数はそのソース(仕様の `Function.prototype.toString`)。
2396                    // 記録できていない関数(アロー・メソッド等)は仕様の NativeFunction 形式(`[native code]`)にする。
2397                    // 【2026-11-04】従来は全部 `function f() { [code] }` で、評価すると `[code]` が正しい JS になってしまった。
2398                    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                    // `fn.bind(...)` が返す束縛済み関数(`ObjKind::Bound`)を
2428                    // 文字列化すると、専用ケースが無く汎用の `[object Object]` に
2429                    // 落ちるバグだった(`.name`/`.length` の欠落と同種)。
2430                    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                    // `Proxy` を文字列化すると、`ObjKind::Proxy` 専用のケースが無く
2443                    // 汎用の `[object Object]` に落ちるバグだった(`String(new
2444                    // Proxy([1,2,3], {}))` が `"1,2,3"` になるべきところ壊れた結果に
2445                    // なっていた)。`Array.isArray`/`Object.keys`/`structuredClone`
2446                    // 等、他の多くの操作は既に target へ委譲する透過性修正済みだった
2447                    // のに、この経路だけ見落とされていた。
2448                    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                    // 文字列変換(テンプレートリテラル補間・`String(date)`・暗黙の
2461                    // 文字列連結等)でも ISO 形式を返す。この簡易実装ではロケール依存の
2462                    // `toDateString()` 的フォーマットは持たないため常に ISO 形式。
2463                    // 【2026-11-17】不正な日時は "Invalid Date"(`String(new Date(NaN))`。以前は 1970 年の ISO 形式)。
2464                    ObjKind::DateObj(ms) if ms.is_nan() => String::from("Invalid Date"),
2465                    ObjKind::DateObj(ms) => date_to_iso_string_repr(*ms),
2466                    _ => {
2467                        // `Symbol.toStringTag`(データのプロパティ)があれば `[object タグ]`(`String(Math)`・`${JSON}`)。
2468                        // 既に可変借用中のオブジェクトや循環プロトタイプでも panic しないよう try_borrow を使う。
2469                        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    /// `===` 厳密等価。
2486    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            // DOM 要素は `Obj::dom(idx)` がアクセスの都度フレッシュな `Rc` を作るため
2495            // (`document.getElementById`/`querySelector`/`.content` 等の戻り値がそう)、
2496            // `Rc::ptr_eq` だけでは同じノードを指す2つのハンドルが常に不等になる
2497            // バグだった(実ブラウザでは `getElementById('x') === getElementById('x')`
2498            // は当然 `true`)。`ObjKind::HostRef` のうち `by_id` の種類は識別子(種類と番号)で比較する。
2499            // 同一 Rc は借用前に即 true とし、借用中(Map.set(map, v) 等の自己参照キー)は
2500            // try_borrow で panic を回避する。
2501            (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    /// 同一オブジェクト参照か(関数リスナの照合用)。プリミティブは strict_eq に委譲。
2519    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
2527/// 要素を詰めて持つ配列の長さの上限(約 838 万要素・134MB)。これを超える添字・長さは扱わない。
2528pub const MAX_DENSE_ARRAY_LEN: usize = 1 << 23;
2529
2530/// JS の数値表示規則(整数は小数点を付けない、NaN/Infinity 対応)。
2531pub 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    // 整数値は小数点なしで表示。2^53 以上は「元に戻せる最短の桁 + 0 埋め」(仕様の Number::toString。Rust の
2542    // f64 の表示と同じ)。【2026-11-04】従来は全部 `n as i64` で、2^63 以上 1e21 未満が i64 の最大値に張り付いていた。
2543    if libm::trunc(n) == n && libm::fabs(n) < 9007199254740992.0 {
2544        // 桁をスタックの配列へ書いて 1 回で文字列にする(2026-11-05。`format!` の書式機能を通していた)。
2545        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    // それ以外(小数・2^53 以上・1e21 以上・1e-6 未満)は仕様の桁の並べ方(`numfmt::to_string10`。2026-11-12)。
2568    super::numfmt::to_string10(n)
2569}
2570
2571/// `Date` の文字列表現(ISO 8601、UTC)。`builtins.rs` の `format_iso`/`decompose_ms` と
2572/// 同じ Howard Hinnant 方式の変換ロジックだが、`value.rs` は `builtins.rs` に依存できない
2573/// (下位レイヤのため)ので、ごく小さい純粋関数として独立に複製する
2574/// (`kernel::timer` にもある3つ目の複製。詳細は spec/walkthrough.md 2026-07-07 参照)。
2575fn 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
2599/// 数値を整数の配列の要素へ書くときの丸め(ECMAScript の ToUint8/16/32・ToBigUint64 の共通部分)。
2600/// 小数を切り捨て、2^64 で割った余りを返す(負の数は 2 の補数)。NaN・無限大は 0。呼ぶ側が下位の幅だけ取る。
2601///
2602/// 【2026-11-12】以前は `trunc(v) as i64` を取っていた。Rust の `as` は範囲の外を端の値に**張り付ける**ので、
2603/// 2^63 以上の値は全部 `i64::MAX`(下位のビットが全部 1)になり、8 bit なら 255、16 bit なら 65535 になっていた。
2604/// 仕様は 2^n で割った余り。
2605pub 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    // 2^63 以上(または -2^63 未満)。f64 の余りは正確に求まる(どちらも 2^64 の倍数からの差が表せる)。
2615    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}