Skip to main content

atmos/os_lib/ecma/builtins/
props_methods.rs

1// 分割: builtins.rs より機械的に移動(2026-07-16 リファクタ フェーズ2)。
2// ロジック不変。可視性のみ pub(crate) へ昇格し、親が pub(crate) use で再エクスポート。
3use super::*;
4use crate::os_lib::ecma::host::HostOwn;
5
6// ============ グローバル関数 ============
7
8/// `parseInt(string, radix)`。以前は `radix` 省略時に常に10進として扱い、また
9/// `radix` を明示していても `"0x"`/`"0X"` 接頭辞を読み飛ばさなかった。仕様上は
10/// `radix` 省略(または `0`)かつ文字列が(符号の後)`0x`/`0X` で始まる場合は自動的に
11/// 16進として解釈し、明示的に `radix=16` の場合も同接頭辞を読み飛ばす必要がある。
12/// 例: `parseInt("0xFF")` は仕様どおりなら `255` だが、以前は `0`("0" の直後の "x" が
13/// 数字でないため即座に打ち切られていた)になっていた。
14pub(crate) fn global_parse_int(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
15    let s = it.to_string_value(arg(a, 0))?;
16    let radix = crate::os_lib::ecma::interp::to_i32(it.num_of(&arg(a, 1))?);
17    Ok(Value::Number(crate::os_lib::ecma::numfmt::parse_int(&s, radix)))
18}
19pub(crate) fn global_parse_float(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
20    let s = it.to_string_value(arg(a, 0))?;
21    Ok(Value::Number(crate::os_lib::ecma::numfmt::parse_float(&s)))
22}
23pub(crate) fn global_is_nan(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
24    Ok(Value::Bool(it.num_of(&arg(a, 0))?.is_nan()))
25}
26pub(crate) fn global_is_finite(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
27    Ok(Value::Bool(it.num_of(&arg(a, 0))?.is_finite()))
28}
29
30/// `eval(source)`(ES1)。文字列以外の引数は仕様どおり無変換でそのまま返す。
31pub(crate) fn global_eval(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
32    let first = arg(a, 0);
33    match &first {
34        Value::Str(s) => it.eval_source(s),
35        _ => Ok(first),
36    }
37}
38
39/// `new Function(arg1, ..., argN, body)`(ES1)。動的にソースからコードを生成する定番
40/// イディオム。`(function anonymous(arg1,...,argN){ body })` という即時式へ組み立て直し、
41/// 既存の `eval_source`(常にグローバルスコープで実行する簡略実装)へ委譲する。
42pub(crate) fn function_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
43    dynamic_function(it, a, "function")
44}
45/// `new AsyncFunction(...)`・`new GeneratorFunction(...)`・`new AsyncGeneratorFunction(...)`(グローバルには無く、
46/// `Object.getPrototypeOf(async function(){}).constructor` から得る)。
47pub(crate) fn async_function_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
48    dynamic_function(it, a, "async function")
49}
50pub(crate) fn generator_function_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
51    dynamic_function(it, a, "function*")
52}
53pub(crate) fn async_generator_function_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
54    dynamic_function(it, a, "async function*")
55}
56fn dynamic_function(it: &mut Interp, a: &[Value], head: &str) -> Result<Value, Value> {
57    let (params, body): (String, String) = match a.len() {
58        0 => (String::new(), String::new()),
59        1 => (String::new(), a[0].to_js_string()),
60        n => {
61            let params = a[..n - 1]
62                .iter()
63                .map(|v| v.to_js_string())
64                .collect::<Vec<_>>()
65                .join(",");
66            (params, a[n - 1].to_js_string())
67        }
68    };
69    let source = format!("({} anonymous({}\n) {{\n{}\n}})", head, params, body);
70    it.eval_source(&source)
71}
72
73// ============ プロパティ取得(プリミティブ/組込みメソッド) ============
74
75/// 文字列の組込みネイティブ関数定義(関数名, 実体ポインタ)。
76pub fn string_builtin_fn(key: &str) -> Option<(&'static str, NativeFn)> {
77    let pair = match key {
78        "charAt" => ("charAt", str_char_at as NativeFn),
79        "charCodeAt" => ("charCodeAt", str_char_code_at as NativeFn),
80        "codePointAt" => ("codePointAt", str_code_point_at as NativeFn),
81        "localeCompare" => ("localeCompare", str_locale_compare as NativeFn),
82        "indexOf" => ("indexOf", str_index_of as NativeFn),
83        "lastIndexOf" => ("lastIndexOf", str_last_index_of as NativeFn),
84        "includes" => ("includes", str_includes as NativeFn),
85        "startsWith" => ("startsWith", str_starts_with as NativeFn),
86        "endsWith" => ("endsWith", str_ends_with as NativeFn),
87        "slice" => ("slice", str_slice as NativeFn),
88        "substring" => ("substring", str_substring as NativeFn),
89        "substr" => ("substr", str_substr as NativeFn),
90        "toUpperCase" => ("toUpperCase", str_to_upper as NativeFn),
91        // ロケールつきの版(ロケールごとの特別な対応は持たない。既定のロケールでは同じ結果)。
92        "toLocaleUpperCase" => ("toLocaleUpperCase", str_to_upper as NativeFn),
93        "toLocaleLowerCase" => ("toLocaleLowerCase", str_to_lower as NativeFn),
94        "toLowerCase" => ("toLowerCase", str_to_lower as NativeFn),
95        "trim" => ("trim", str_trim as NativeFn),
96        "split" => ("split", str_split as NativeFn),
97        "replace" => ("replace", str_replace as NativeFn),
98        "replaceAll" => ("replaceAll", str_replace_all as NativeFn),
99        "match" => ("match", str_match as NativeFn),
100        "matchAll" => ("matchAll", str_match_all as NativeFn),
101        "search" => ("search", str_search as NativeFn),
102        "repeat" => ("repeat", str_repeat as NativeFn),
103        "concat" => ("concat", str_concat as NativeFn),
104        "padStart" => ("padStart", str_pad_start as NativeFn),
105        "padEnd" => ("padEnd", str_pad_end as NativeFn),
106        "at" => ("at", str_at as NativeFn),
107        "toString" => ("toString", str_identity as NativeFn),
108        "valueOf" => ("valueOf", str_identity as NativeFn),
109        "trimStart" => ("trimStart", str_trim_start as NativeFn),
110        "trimEnd" => ("trimEnd", str_trim_end as NativeFn),
111        "trimLeft" => ("trimStart", str_trim_start as NativeFn),
112        "trimRight" => ("trimEnd", str_trim_end as NativeFn),
113        "Symbol(Symbol.iterator)" => ("[Symbol.iterator]", str_iterator as NativeFn),
114        "isWellFormed" => ("isWellFormed", str_is_well_formed as NativeFn),
115        "toWellFormed" => ("toWellFormed", str_to_well_formed as NativeFn),
116        "normalize" => ("normalize", str_normalize as NativeFn),
117        "anchor" => ("anchor", str_anchor as NativeFn),
118        "big" => ("big", str_big as NativeFn),
119        "blink" => ("blink", str_blink as NativeFn),
120        "bold" => ("bold", str_bold as NativeFn),
121        "fixed" => ("fixed", str_fixed as NativeFn),
122        "fontcolor" => ("fontcolor", str_fontcolor as NativeFn),
123        "fontsize" => ("fontsize", str_fontsize as NativeFn),
124        "italics" => ("italics", str_italics as NativeFn),
125        "link" => ("link", str_link as NativeFn),
126        "small" => ("small", str_small as NativeFn),
127        "strike" => ("strike", str_strike as NativeFn),
128        "sub" => ("sub", str_sub as NativeFn),
129        "sup" => ("sup", str_sup as NativeFn),
130        _ => return None,
131    };
132    Some(pair)
133}
134
135/// 文字列レシーバのプロパティ/メソッド。
136pub fn string_get(s: &str, key: &str) -> Value {
137    if key == "length" {
138        return Value::Number(s.chars().count() as f64);
139    }
140    if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
141        return match s.chars().nth(idx) {
142            Some(c) => Value::str(c.to_string()),
143            None => Value::Undefined,
144        };
145    }
146    string_builtin_fn(key).map(|(name, f)| nv(name, f)).unwrap_or(Value::Undefined)
147}
148
149/// Annex B.2.3 `CreateHTML` の属性なし版(`<tag>this</tag>`)。
150pub(crate) fn html_wrap_tag(s: &str, tag: &str) -> String {
151    alloc::format!("<{0}>{1}</{0}>", tag, s)
152}
153/// Annex B.2.3 `CreateHTML`。属性値の `"` は `&quot;` へエスケープする(仕様どおり)。
154pub(crate) fn html_wrap_attr(s: &str, tag: &str, attr: &str, value: &str) -> String {
155    let escaped = value.replace('"', "&quot;");
156    alloc::format!("<{0} {1}=\"{2}\">{3}</{0}>", tag, attr, escaped, s)
157}
158pub(crate) fn str_anchor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
159    Ok(Value::str(html_wrap_attr(&this_str_c(it, &t)?, "a", "name", &it.to_string_value(arg(a, 0))?)))
160}
161pub(crate) fn str_big(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
162    Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "big")))
163}
164pub(crate) fn str_blink(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
165    Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "blink")))
166}
167pub(crate) fn str_bold(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
168    Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "b")))
169}
170pub(crate) fn str_fixed(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
171    Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "tt")))
172}
173pub(crate) fn str_fontcolor(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
174    Ok(Value::str(html_wrap_attr(&this_str_c(it, &t)?, "font", "color", &it.to_string_value(arg(a, 0))?)))
175}
176pub(crate) fn str_fontsize(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
177    Ok(Value::str(html_wrap_attr(&this_str_c(it, &t)?, "font", "size", &it.to_string_value(arg(a, 0))?)))
178}
179pub(crate) fn str_italics(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
180    Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "i")))
181}
182pub(crate) fn str_link(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
183    Ok(Value::str(html_wrap_attr(&this_str_c(it, &t)?, "a", "href", &it.to_string_value(arg(a, 0))?)))
184}
185pub(crate) fn str_small(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
186    Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "small")))
187}
188pub(crate) fn str_strike(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
189    Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "strike")))
190}
191pub(crate) fn str_sub(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
192    Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "sub")))
193}
194pub(crate) fn str_sup(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
195    Ok(Value::str(html_wrap_tag(&this_str_c(it, &t)?, "sup")))
196}
197
198/// RequireObjectCoercible(this) + ToString(this)(String.prototype の各メソッドの先頭。文字列はそのまま借りる)。
199pub(crate) fn this_str_c<'a>(it: &mut Interp, this: &'a Value) -> Result<alloc::borrow::Cow<'a, str>, Value> {
200    match this {
201        Value::Str(s) => {
202            if is_symbol_like_key(s) {
203                return Err(it.type_error("Cannot convert a Symbol value to a string"));
204            }
205            Ok(alloc::borrow::Cow::Borrowed(s.as_str()))
206        }
207        Value::Undefined | Value::Null => Err(it.type_error("String.prototype method called on null or undefined")),
208        Value::Object(_) => Ok(alloc::borrow::Cow::Owned(it.to_string_value(this.clone())?)),
209        _ => Ok(alloc::borrow::Cow::Owned(this.to_js_string())),
210    }
211}
212
213/// 仕様の ToString(Symbol は常に TypeError)。
214pub(crate) fn to_str_strict(it: &mut Interp, v: Value) -> Result<String, Value> {
215    let prim = if matches!(v, Value::Object(_)) {
216        it.to_primitive(v, "string")?
217    } else {
218        v
219    };
220    if let Value::Str(s) = &prim {
221        if is_symbol_like_key(s) {
222            return Err(it.type_error("Cannot convert a Symbol value to a string"));
223        }
224        return Ok(s.to_string());
225    }
226    Ok(prim.to_js_string())
227}
228
229/// `this_str_c` の値版(`cached_units` 用。文字列値にして返す)。
230pub(crate) fn this_val(it: &mut Interp, this: &Value) -> Result<Value, Value> {
231    match this {
232        Value::Str(s) if !is_symbol_like_key(s) => Ok(this.clone()),
233        _ => Ok(Value::str(this_str_c(it, this)?.into_owned())),
234    }
235}
236
237#[allow(dead_code)]
238pub(crate) fn this_str(this: &Value) -> alloc::borrow::Cow<'_, str> {
239    // 【2026-11-02】毎回 `to_js_string` で全文を複製していた(`s.charCodeAt(i)` の 1 回ごとに全文のコピー)。
240    match this {
241        Value::Str(s) => alloc::borrow::Cow::Borrowed(s.as_str()),
242        _ => alloc::borrow::Cow::Owned(this.to_js_string()),
243    }
244}
245
246/// 文字列を UTF-16 の単位で見る(JS の添字・`length` の単位。2026-11-02)。ASCII はバイトがそのまま単位に
247/// なるので配列を作らない。文字列は UTF-8 で持つので、サロゲートの片割れは表せず U+FFFD になる。
248pub(crate) enum Units<'a> {
249    Ascii(&'a str),
250    Wide(Vec<u16>),
251}
252
253impl<'a> Units<'a> {
254    pub(crate) fn of(s: &'a str) -> Self {
255        if s.is_ascii() {
256            Units::Ascii(s)
257        } else {
258            Units::Wide(s.encode_utf16().collect())
259        }
260    }
261
262    pub(crate) fn len(&self) -> usize {
263        match self {
264            Units::Ascii(s) => s.len(),
265            Units::Wide(v) => v.len(),
266        }
267    }
268
269    pub(crate) fn at(&self, i: usize) -> Option<u16> {
270        match self {
271            Units::Ascii(s) => s.as_bytes().get(i).map(|b| *b as u16),
272            Units::Wide(v) => v.get(i).copied(),
273        }
274    }
275
276    /// `[s, e)` の部分文字列。
277    pub(crate) fn slice(&self, s: usize, e: usize) -> String {
278        match self {
279            Units::Ascii(t) => t.get(s..e).map(String::from).unwrap_or_default(),
280            Units::Wide(v) => v.get(s..e).map(String::from_utf16_lossy).unwrap_or_default(),
281        }
282    }
283}
284
285/// 長い文字列の UTF-16 の単位の写しの表(最近使った 4 件)。`Rc` を持つので同じ番地が別の文字列に使い回されず、
286/// 中身が書き換わることもない(持っている間は参照が 2 以上)。【2026-11-04】`s.charCodeAt(i)`・`s.length` の 1 回ごとに
287/// 全文を調べ(`is_ascii`)、ASCII 以外なら全文を UTF-16 の配列に作り直していた(長い文字列の繰り返しが O(n²)。
288/// YouTube の日本語のページで JS の zlib などが重かった。TODO B0)。
289type UnitsCacheEntry = (Rc<String>, Option<Rc<[u16]>>);
290
291#[derive(Default)]
292pub struct UnitsCache {
293    entries: Vec<UnitsCacheEntry>,
294}
295
296/// これより短い文字列は表に入れない(その場で調べても安い)。
297const UNITS_CACHE_MIN: usize = 256;
298
299/// 文字列の UTF-16 の単位(表を使う版)。
300pub(crate) enum CUnits<'a> {
301    Plain(Units<'a>),
302    Ascii(Rc<String>),
303    Wide(Rc<[u16]>),
304}
305
306impl CUnits<'_> {
307    pub(crate) fn len(&self) -> usize {
308        match self {
309            CUnits::Plain(u) => u.len(),
310            CUnits::Ascii(s) => s.len(),
311            CUnits::Wide(v) => v.len(),
312        }
313    }
314    pub(crate) fn at(&self, i: usize) -> Option<u16> {
315        match self {
316            CUnits::Plain(u) => u.at(i),
317            CUnits::Ascii(s) => s.as_bytes().get(i).map(|b| *b as u16),
318            CUnits::Wide(v) => v.get(i).copied(),
319        }
320    }
321    pub(crate) fn slice(&self, s: usize, e: usize) -> String {
322        match self {
323            CUnits::Plain(u) => u.slice(s, e),
324            CUnits::Ascii(t) => t.get(s..e).map(String::from).unwrap_or_default(),
325            CUnits::Wide(v) => v.get(s..e).map(String::from_utf16_lossy).unwrap_or_default(),
326        }
327    }
328}
329
330/// `Value::Str` の UTF-16 の単位。長い文字列は表から引く(無ければ作って入れる)。
331pub(crate) fn cached_units<'a>(it: &Interp, v: &'a Value) -> CUnits<'a> {
332    let Value::Str(rc) = v else {
333        return CUnits::Plain(Units::Wide(v.to_js_string().encode_utf16().collect()));
334    };
335    if rc.len() < UNITS_CACHE_MIN {
336        return CUnits::Plain(Units::of(rc.as_str()));
337    }
338    let Ok(mut cache) = it.units_cache.try_borrow_mut() else {
339        return CUnits::Plain(Units::of(rc.as_str()));
340    };
341    if let Some(pos) = cache.entries.iter().position(|(s, _)| Rc::ptr_eq(s, rc)) {
342        let e = cache.entries.remove(pos);
343        let out = match &e.1 {
344            Some(w) => CUnits::Wide(w.clone()),
345            None => CUnits::Ascii(e.0.clone()),
346        };
347        cache.entries.push(e);
348        return out;
349    }
350    let wide: Option<Rc<[u16]>> = if rc.is_ascii() { None } else { Some(rc.encode_utf16().collect::<Vec<u16>>().into()) };
351    if cache.entries.len() >= 4 {
352        cache.entries.remove(0);
353    }
354    cache.entries.push((rc.clone(), wide.clone()));
355    match wide {
356        Some(w) => CUnits::Wide(w),
357        None => CUnits::Ascii(rc.clone()),
358    }
359}
360
361/// UTF-16 の長さ(JS の `.length` に相当するコード単位数)。
362/// ASCII 文字列ならバイト長と等価。
363/// 非 ASCII の場合、UTF-8 の先頭バイト(継続バイト以外)をカウントし、
364/// 4 バイト文字(U+10000 以上、先頭バイト 0xF0..=0xF4)は UTF-16 で
365/// サロゲートペア(2 単位)となるため +1 加算する。
366/// `s.encode_utf16().count()` のデコードイテレータを排除し、高速なバイト走査で計算。
367pub(crate) fn unit_len(s: &str) -> usize {
368    if s.is_ascii() {
369        s.len()
370    } else {
371        let mut units = 0;
372        for &b in s.as_bytes() {
373            if (b & 0xC0) != 0x80 {
374                units += 1;
375                if b >= 0xF0 {
376                    units += 1;
377                }
378            }
379        }
380        units
381    }
382}
383pub(crate) fn str_char_at(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
384    let t = this_val(it, &t)?;
385    let pos = to_integer_or_infinity(it.num_of(&arg(a, 0))?);
386    let u = cached_units(it, &t);
387    if pos < 0.0 || pos >= (u.len() as f64) {
388        return Ok(Value::str(String::new()));
389    }
390    Ok(it.char_unit_val(u.at(pos as usize)))
391}
392pub(crate) fn str_char_code_at(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
393    let t = this_val(it, &t)?;
394    let pos = to_integer_or_infinity(it.num_of(&arg(a, 0))?);
395    let u = cached_units(it, &t);
396    if pos < 0.0 || pos >= (u.len() as f64) {
397        return Ok(Value::Number(f64::NAN));
398    }
399    match u.at(pos as usize) {
400        Some(c) => Ok(Value::Number(c as f64)),
401        None => Ok(Value::Number(f64::NAN)),
402    }
403}
404/// `String.prototype.codePointAt()`(ES2015)。サロゲートの対は 1 つのコードポイントにする。
405pub(crate) fn str_code_point_at(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
406    let t = this_val(it, &t)?;
407    let pos = to_integer_or_infinity(it.num_of(&arg(a, 0))?);
408    let u = cached_units(it, &t);
409    if pos < 0.0 || pos >= (u.len() as f64) {
410        return Ok(Value::Undefined);
411    }
412    let i = pos as usize;
413    let Some(hi) = u.at(i) else { return Ok(Value::Undefined) };
414    if (0xD800..0xDC00).contains(&hi) {
415        if let Some(lo) = u.at(i + 1).filter(|l| (0xDC00..0xE000).contains(l)) {
416            let cp = 0x10000 + (((hi as u32) - 0xD800) << 10) + ((lo as u32) - 0xDC00);
417            return Ok(Value::Number(cp as f64));
418        }
419    }
420    Ok(Value::Number(hi as f64))
421}/// `String.prototype.localeCompare()`(ES3)も未実装だった。この環境には Intl/ロケール
422/// データが無いため、ロケール依存の照合順序ではなく通常の(コードポイント順)比較で近似する。
423pub(crate) fn str_locale_compare(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
424    let s = this_str_c(it, &t)?;
425    let other = it.to_string_value(arg(a, 0))?;
426    let locale = super::intl::ctor_locale(it, &arg(a, 1))?;
427    let _options = super::intl::get_options_object(it, &arg(a, 2), false)?;
428    let phonebook = locale.contains("-u-co-phonebk");
429    use core::cmp::Ordering;
430    Ok(Value::Number(match crate::os_lib::ecma::collate::locale_compare_with_options(&s, other.as_str(), phonebook) {
431        Ordering::Less => -1.0,
432        Ordering::Equal => 0.0,
433        Ordering::Greater => 1.0,
434    }))
435}
436/// UTF-16 の位置 `n` に対応するバイト位置(範囲外は末尾)。
437fn unit_to_byte(s: &str, n: usize) -> usize {
438    if s.is_ascii() {
439        return n.min(s.len());
440    }
441    let mut u = 0;
442    for (b, c) in s.char_indices() {
443        if u >= n {
444            return b;
445        }
446        u += c.len_utf16();
447    }
448    s.len()
449}
450
451/// 位置の引数(UTF-16 単位。`ToNumber` の例外を伝播し、NaN は `default`、負は 0、範囲外は末尾)。
452fn pos_arg_checked(it: &mut Interp, v: &Value, default: usize, len: usize) -> Result<usize, Value> {
453    if matches!(v, Value::Undefined) {
454        return Ok(default);
455    }
456    let p = it.num_of(v)?;
457    Ok(if p.is_nan() {
458        default
459    } else if p <= 0.0 {
460        0
461    } else if p.is_finite() {
462        (p as usize).min(len)
463    } else {
464        len
465    })
466}
467
468/// 位置の引数(UTF-16 単位。NaN は `default`、負は 0、範囲外は末尾)。
469#[allow(dead_code)]
470fn pos_arg(v: &Value, default: usize, len: usize) -> usize {
471    if matches!(v, Value::Undefined) {
472        return default;
473    }
474    let p = v.to_number();
475    if p.is_nan() {
476        default
477    } else if p <= 0.0 {
478        0
479    } else if p.is_finite() {
480        (p as usize).min(len)
481    } else {
482        len
483    }
484}
485
486/// `str.indexOf(search, position)`(位置は文字単位)。
487/// 【2026-10-17】従来は第 2 引数(開始位置)を無視していた。探索は `str::find`(バイト列)。
488pub(crate) fn str_index_of(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
489    let s = this_str_c(it, &t)?.into_owned();
490    let needle = to_str_strict(it, arg(a, 0))?;
491    let start_unit = pos_arg_checked(it, &arg(a, 1), 0, unit_len(&s))?;
492    let start = unit_to_byte(&s, start_unit);
493    match s.get(start..).and_then(|rest| rest.find(&needle)) {
494        Some(off) => Ok(Value::Number(unit_len(s.get(..start + off).unwrap_or("")) as f64)),
495        None => Ok(Value::Number(-1.0)),
496    }
497}
498/// `str.lastIndexOf(search, position)`(位置は文字単位。省略・NaN は末尾から)。
499/// 【2026-10-17】丸ごと未実装で、YouTube の cookie 読み出し(`f.lastIndexOf(c, 0) == 0`)が
500/// 例外を投げ、そのエラー記録がまたエラーになる無限再帰を起こしていた。
501pub(crate) fn str_last_index_of(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
502    let s = this_str_c(it, &t)?.into_owned();
503    let needle = to_str_strict(it, arg(a, 0))?;
504    let len = unit_len(&s);
505    let nlen = unit_len(&needle);
506    let pos_num = if matches!(arg(a, 1), Value::Undefined) {
507        f64::NAN
508    } else {
509        it.num_of(&arg(a, 1))?
510    };
511    if nlen > len {
512        return Ok(Value::Number(-1.0));
513    }
514    let start_unit = if pos_num.is_nan() {
515        len - nlen
516    } else {
517        let pos = to_integer_or_infinity(pos_num);
518        if pos <= 0.0 {
519            0
520        } else if pos.is_finite() {
521            (pos as usize).min(len - nlen)
522        } else {
523            len - nlen
524        }
525    };
526    let end = unit_to_byte(&s, start_unit + nlen);
527    match s.get(..end).and_then(|head| head.rfind(&needle)) {
528        Some(b) => Ok(Value::Number(unit_len(s.get(..b).unwrap_or("")) as f64)),
529        None => Ok(Value::Number(-1.0)),
530    }
531}
532/// `includes`/`startsWith`/`endsWith` は仕様上、第1引数に RegExp(または `Symbol.match` が truthy な値)を渡すと
533/// `TypeError` を投げる必要がある。
534pub(crate) fn reject_regexp_arg(it: &mut Interp, v: &Value, method: &str) -> Result<(), Value> {
535    if super::regexp_proto::is_regexp(it, v)? {
536        return Err(it.type_error(alloc::format!(
537            "First argument to String.prototype.{} must not be a regular expression",
538            method
539        )));
540    }
541    Ok(())
542}
543fn clamp_unit_pos(num: f64, len: usize) -> usize {
544    let pos = to_integer_or_infinity(num);
545    if pos <= 0.0 {
546        0
547    } else if pos.is_finite() {
548        (pos as usize).min(len)
549    } else {
550        len
551    }
552}
553pub(crate) fn str_includes(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
554    let s = this_str_c(it, &t)?.into_owned();
555    let search = arg(a, 0);
556    reject_regexp_arg(it, &search, "includes")?;
557    let needle = to_str_strict(it, search)?;
558    let len = unit_len(&s);
559    let start = if matches!(arg(a, 1), Value::Undefined) {
560        0
561    } else {
562        clamp_unit_pos(it.num_of(&arg(a, 1))?, len)
563    };
564    let start_byte = unit_to_byte(&s, start);
565    Ok(Value::Bool(s.get(start_byte..).is_some_and(|rest| rest.contains(&needle))))
566}
567pub(crate) fn str_starts_with(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
568    let s = this_str_c(it, &t)?.into_owned();
569    let search = arg(a, 0);
570    reject_regexp_arg(it, &search, "startsWith")?;
571    let needle = to_str_strict(it, search)?;
572    let len = unit_len(&s);
573    let start = if matches!(arg(a, 1), Value::Undefined) {
574        0
575    } else {
576        clamp_unit_pos(it.num_of(&arg(a, 1))?, len)
577    };
578    let start_byte = unit_to_byte(&s, start);
579    Ok(Value::Bool(s.get(start_byte..).is_some_and(|rest| rest.starts_with(&needle))))
580}
581pub(crate) fn str_ends_with(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
582    let s = this_str_c(it, &t)?.into_owned();
583    let search = arg(a, 0);
584    reject_regexp_arg(it, &search, "endsWith")?;
585    let needle = to_str_strict(it, search)?;
586    let len = unit_len(&s);
587    let end = if matches!(arg(a, 1), Value::Undefined) {
588        len
589    } else {
590        clamp_unit_pos(it.num_of(&arg(a, 1))?, len)
591    };
592    let end_byte = unit_to_byte(&s, end);
593    Ok(Value::Bool(s.get(..end_byte).is_some_and(|head| head.ends_with(&needle))))
594}
595pub(crate) fn str_slice(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
596    let t = this_val(it, &t)?;
597    let u = cached_units(it, &t);
598    let len = u.len() as i64;
599    let start = norm_index(it.num_of(&arg(a, 0))?, len, 0);
600    let end = if matches!(arg(a, 1), Value::Undefined) {
601        len
602    } else {
603        norm_index(it.num_of(&arg(a, 1))?, len, len)
604    };
605    let (s, e) = (start.max(0) as usize, end.max(0) as usize);
606    Ok(Value::str(if s < e { u.slice(s, e.min(u.len())) } else { String::new() }))
607}pub(crate) fn str_substring(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
608    let t = this_val(it, &t)?;
609    let u = cached_units(it, &t);
610    let len = u.len();
611    let mut s = clamp_idx(it.num_of(&arg(a, 0))?, len);
612    let mut e = if matches!(arg(a, 1), Value::Undefined) {
613        len
614    } else {
615        clamp_idx(it.num_of(&arg(a, 1))?, len)
616    };
617    if s > e {
618        core::mem::swap(&mut s, &mut e);
619    }
620    Ok(Value::str(u.slice(s, e)))
621}/// `String.prototype.substr(start, length)`。ES3 由来の非推奨(Annex B)メソッドだが、
622/// 古いコードで依然として広く使われるため実装する。`slice`/`substring` はあったが
623/// `substr` だけが欠落していた。
624pub(crate) fn str_substr(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
625    let t = this_val(it, &t)?;
626    let u = cached_units(it, &t);
627    let len = u.len() as i64;
628    let raw_start = it.num_of(&arg(a, 0))?;
629    let start = if raw_start < 0.0 {
630        (len + raw_start as i64).max(0)
631    } else {
632        (raw_start as i64).min(len)
633    };
634    let length = if matches!(arg(a, 1), Value::Undefined) {
635        len - start
636    } else {
637        (it.num_of(&arg(a, 1))? as i64).max(0)
638    };
639    let end = (start + length).min(len);
640    let s = start as usize;
641    let e = (end.max(start)) as usize;
642    Ok(Value::str(if s < e { u.slice(s, e) } else { String::new() }))
643}pub(crate) fn str_to_upper(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
644    Ok(Value::str(this_str_c(it, &t)?.to_uppercase()))
645}
646pub(crate) fn str_to_lower(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
647    Ok(Value::str(this_str_c(it, &t)?.to_lowercase()))
648}
649#[inline]
650fn is_ecma_ws(c: char) -> bool {
651    matches!(
652        c,
653        '\u{0009}'
654            | '\u{000A}'
655            | '\u{000B}'
656            | '\u{000C}'
657            | '\u{000D}'
658            | ' '
659            | '\u{00A0}'
660            | '\u{2028}'
661            | '\u{2029}'
662            | '\u{FEFF}'
663    ) || (c != '\u{180E}' && c.is_whitespace())
664}
665pub(crate) fn str_trim(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
666    Ok(Value::str(this_str_c(it, &t)?.trim_matches(is_ecma_ws).to_string()))
667}
668pub(crate) fn str_trim_start(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
669    Ok(Value::str(this_str_c(it, &t)?.trim_start_matches(is_ecma_ws).to_string()))
670}
671pub(crate) fn str_trim_end(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
672    Ok(Value::str(this_str_c(it, &t)?.trim_end_matches(is_ecma_ws).to_string()))
673}
674pub(crate) fn str_identity(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
675    // thisStringValue: 文字列かその包みだけ(Symbol を除く)。
676    match &t {
677        Value::Str(s) if !is_symbol_like_key(s) => return Ok(t),
678        Value::Object(o) => {
679            if let Some(p @ Value::Str(_)) = o.borrow().primitive() {
680                return Ok(p.clone());
681            }
682        }
683        _ => {}
684    }
685    Err(it.type_error("String.prototype.toString requires that 'this' be a String"))
686}
687/// thisNumberValue。
688pub(crate) fn this_number(it: &mut Interp, t: &Value, what: &str) -> Result<f64, Value> {
689    match t {
690        Value::Number(n) => Ok(*n),
691        Value::Object(o) => {
692            if let Some(Value::Number(n)) = o.borrow().primitive() {
693                return Ok(*n);
694            }
695            Err(it.type_error(alloc::format!("Number.prototype.{} requires that 'this' be a Number", what)))
696        }
697        _ => Err(it.type_error(alloc::format!("Number.prototype.{} requires that 'this' be a Number", what))),
698    }
699}
700/// thisBooleanValue。
701fn this_boolean(it: &mut Interp, t: &Value, what: &str) -> Result<bool, Value> {
702    match t {
703        Value::Bool(b) => Ok(*b),
704        Value::Object(o) => {
705            if let Some(Value::Bool(b)) = o.borrow().primitive() {
706                return Ok(*b);
707            }
708            Err(it.type_error(alloc::format!("Boolean.prototype.{} requires that 'this' be a Boolean", what)))
709        }
710        _ => Err(it.type_error(alloc::format!("Boolean.prototype.{} requires that 'this' be a Boolean", what))),
711    }
712}
713/// `String.prototype[Symbol.iterator]()`(ES2015)が丸ごと欠落していた。呼び出すと
714/// 「メソッドが存在しない」`TypeError` になっていた(`for...of` 自体は文字列を直接
715/// 走査する内部高速経路で動くため気づかれなかった)。コードポイント単位(サロゲート
716/// ペアを1文字として扱う。Rust の `char` が既にスカラー値単位のため自然に対応できる)で
717/// 走査する Iterator オブジェクトを、`Array.prototype[Symbol.iterator]` 等と同じ
718/// `make_iterator()` を再利用して返す。
719pub(crate) fn str_iterator(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
720    let s = this_str_c(it, &t)?;
721    let items: Vec<Value> = s.chars().map(|c| Value::str(c.to_string())).collect();
722    Ok(Value::Object(make_iterator(items)))
723}
724/// `String.prototype.isWellFormed()`(ES2024)。内部表現が Rust の `String`(常に有効な UTF-8)
725/// であるため、単独サロゲート(lone surrogate)は構造上存在し得ず常に true を返す簡略実装。
726pub(crate) fn str_is_well_formed(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
727    this_str_c(it, &t)?;
728    Ok(Value::Bool(true))
729}
730/// `String.prototype.toWellFormed()`(ES2024)。上記と同じ理由により常に元の文字列をそのまま返す。
731pub(crate) fn str_to_well_formed(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
732    Ok(Value::str(this_str_c(it, &t)?))
733}
734/// `String.prototype.normalize(form)`(ES2015)。丸ごと欠落しており、呼び出すと
735/// 「メソッドが存在しない」`TypeError` になっていた。本来は Unicode 正規化(NFC/NFD/NFKC/NFKD)
736/// を行うが、この no_std 環境には正規化用の Unicode 分解/合成テーブルが無いため、`form` 引数の
737/// 妥当性検証(無効な値は仕様どおり `RangeError`)だけ行い、内容は元の文字列をそのまま返す
738/// 簡略実装(合成済み文字のみで構成された通常の文字列であれば実質的に無害)。
739/// 西欧言語の合成済みラテン文字 ⇔ (基底文字, 結合分音符) の対応表。
740/// フル Unicode Character Database(分解表・結合クラス・正規順序付け・合成除外
741/// リスト)を持たない no_std 環境では完全な NFC/NFD/NFKC/NFKD 実装は非現実的な
742/// ため、実用頻度の高いラテン語圏の分音符付き文字(フランス語・スペイン語・
743/// ドイツ語・ポルトガル語等)に限定した部分実装とする。
744pub(crate) const NFD_TABLE: &[(char, char, char)] = &[
745    ('À', 'A', '\u{0300}'), ('Á', 'A', '\u{0301}'), ('Â', 'A', '\u{0302}'),
746    ('Ã', 'A', '\u{0303}'), ('Ä', 'A', '\u{0308}'), ('Å', 'A', '\u{030A}'),
747    ('Ç', 'C', '\u{0327}'),
748    ('È', 'E', '\u{0300}'), ('É', 'E', '\u{0301}'), ('Ê', 'E', '\u{0302}'), ('Ë', 'E', '\u{0308}'),
749    ('Ì', 'I', '\u{0300}'), ('Í', 'I', '\u{0301}'), ('Î', 'I', '\u{0302}'), ('Ï', 'I', '\u{0308}'),
750    ('Ñ', 'N', '\u{0303}'),
751    ('Ò', 'O', '\u{0300}'), ('Ó', 'O', '\u{0301}'), ('Ô', 'O', '\u{0302}'),
752    ('Õ', 'O', '\u{0303}'), ('Ö', 'O', '\u{0308}'),
753    ('Ù', 'U', '\u{0300}'), ('Ú', 'U', '\u{0301}'), ('Û', 'U', '\u{0302}'), ('Ü', 'U', '\u{0308}'),
754    ('Ý', 'Y', '\u{0301}'),
755    ('à', 'a', '\u{0300}'), ('á', 'a', '\u{0301}'), ('â', 'a', '\u{0302}'),
756    ('ã', 'a', '\u{0303}'), ('ä', 'a', '\u{0308}'), ('å', 'a', '\u{030A}'),
757    ('ç', 'c', '\u{0327}'),
758    ('è', 'e', '\u{0300}'), ('é', 'e', '\u{0301}'), ('ê', 'e', '\u{0302}'), ('ë', 'e', '\u{0308}'),
759    ('ì', 'i', '\u{0300}'), ('í', 'i', '\u{0301}'), ('î', 'i', '\u{0302}'), ('ï', 'i', '\u{0308}'),
760    ('ñ', 'n', '\u{0303}'),
761    ('ò', 'o', '\u{0300}'), ('ó', 'o', '\u{0301}'), ('ô', 'o', '\u{0302}'),
762    ('õ', 'o', '\u{0303}'), ('ö', 'o', '\u{0308}'),
763    ('ù', 'u', '\u{0300}'), ('ú', 'u', '\u{0301}'), ('û', 'u', '\u{0302}'), ('ü', 'u', '\u{0308}'),
764    ('ý', 'y', '\u{0301}'), ('ÿ', 'y', '\u{0308}'),
765];
766pub(crate) fn japanese_voiced_sound_decompose(c: char) -> Option<(char, char)> {
767    let cp = c as u32;
768    match cp {
769        0x304C | 0x304E | 0x3050 | 0x3052 | 0x3054 |
770        0x3056 | 0x3058 | 0x305A | 0x305C | 0x305E |
771        0x3060 | 0x3062 | 0x3065 | 0x3067 | 0x3069 |
772        0x3070 | 0x3073 | 0x3076 | 0x3079 | 0x307C |
773        0x30AC | 0x30AE | 0x30B0 | 0x30B2 | 0x30B4 |
774        0x30B6 | 0x30B8 | 0x30BA | 0x30BC | 0x30BE |
775        0x30C0 | 0x30C2 | 0x30C5 | 0x30C7 | 0x30C9 |
776        0x30D0 | 0x30D3 | 0x30D6 | 0x30D9 | 0x30DC => {
777            char::from_u32(cp - 1).map(|b| (b, '\u{3099}'))
778        }
779        0x3071 | 0x3074 | 0x3077 | 0x307A | 0x307D |
780        0x30D1 | 0x30D4 | 0x30D7 | 0x30DA | 0x30DD => {
781            char::from_u32(cp - 2).map(|b| (b, '\u{309A}'))
782        }
783        0x30F4 => Some(('ウ', '\u{3099}')),
784        _ => None,
785    }
786}
787
788pub(crate) fn japanese_voiced_sound_compose(base: char, mark: char) -> Option<char> {
789    if mark != '\u{3099}' && mark != '\u{309A}' && mark != '\u{309B}' && mark != '\u{309C}' {
790        return None;
791    }
792    let b = base as u32;
793    let is_dakuten = mark == '\u{3099}' || mark == '\u{309B}';
794    let is_handakuten = mark == '\u{309A}' || mark == '\u{309C}';
795
796    match b {
797        0x304B | 0x304D | 0x304F | 0x3051 | 0x3053 |
798        0x3055 | 0x3057 | 0x3059 | 0x305B | 0x305D |
799        0x305F | 0x3061 | 0x3064 | 0x3066 | 0x3068 |
800        0x306F | 0x3072 | 0x3075 | 0x3078 | 0x307B |
801        0x30AB | 0x30AD | 0x30AF | 0x30B1 | 0x30B3 |
802        0x30B5 | 0x30B7 | 0x30B9 | 0x30BB | 0x30BD |
803        0x30BF | 0x30C1 | 0x30C4 | 0x30C6 | 0x30C8 |
804        0x30CF | 0x30D2 | 0x30D5 | 0x30D8 | 0x30DB if is_dakuten => {
805            char::from_u32(b + 1)
806        }
807        0x306F | 0x3072 | 0x3075 | 0x3078 | 0x307B |
808        0x30CF | 0x30D2 | 0x30D5 | 0x30D8 | 0x30DB if is_handakuten => {
809            char::from_u32(b + 2)
810        }
811        0x30A6 if is_dakuten => Some('ヴ'),
812        _ => None,
813    }
814}
815
816pub(crate) fn nfd_decompose(s: &str) -> String {
817    const HANGUL_S_BASE: u32 = 0xAC00;
818    const HANGUL_L_BASE: u32 = 0x1100;
819    const HANGUL_V_BASE: u32 = 0x1161;
820    const HANGUL_T_BASE: u32 = 0x11A7;
821    const HANGUL_N_COUNT: u32 = 588;
822    const HANGUL_T_COUNT: u32 = 28;
823    const HANGUL_S_COUNT: u32 = 11172;
824
825    let mut out = String::with_capacity(s.len());
826    for c in s.chars() {
827        let cp = c as u32;
828        if (HANGUL_S_BASE..HANGUL_S_BASE + HANGUL_S_COUNT).contains(&cp) {
829            let s_index = cp - HANGUL_S_BASE;
830            let l_index = s_index / HANGUL_N_COUNT;
831            let v_index = (s_index % HANGUL_N_COUNT) / HANGUL_T_COUNT;
832            let t_index = s_index % HANGUL_T_COUNT;
833            if let Some(l) = char::from_u32(HANGUL_L_BASE + l_index) {
834                out.push(l);
835            }
836            if let Some(v) = char::from_u32(HANGUL_V_BASE + v_index) {
837                out.push(v);
838            }
839            if t_index > 0 {
840                if let Some(t) = char::from_u32(HANGUL_T_BASE + t_index) {
841                    out.push(t);
842                }
843            }
844            continue;
845        }
846        if let Some((base, mark)) = japanese_voiced_sound_decompose(c) {
847            out.push(base);
848            out.push(mark);
849            continue;
850        }
851        match NFD_TABLE.iter().find(|(pre, _, _)| *pre == c) {
852            Some((_, base, mark)) => {
853                out.push(*base);
854                out.push(*mark);
855            }
856            None => out.push(c),
857        }
858    }
859    out
860}
861pub(crate) fn nfc_compose(s: &str) -> String {
862    const HANGUL_S_BASE: u32 = 0xAC00;
863    const HANGUL_L_BASE: u32 = 0x1100;
864    const HANGUL_V_BASE: u32 = 0x1161;
865    const HANGUL_T_BASE: u32 = 0x11A7;
866    const HANGUL_L_COUNT: u32 = 19;
867    const HANGUL_V_COUNT: u32 = 21;
868    const HANGUL_T_COUNT: u32 = 28;
869    const HANGUL_N_COUNT: u32 = 588;
870
871    let decomposed = nfd_decompose(s);
872    let mut out = String::with_capacity(decomposed.len());
873    let mut chars = decomposed.chars().peekable();
874    while let Some(c) = chars.next() {
875        let cp = c as u32;
876        if (HANGUL_L_BASE..HANGUL_L_BASE + HANGUL_L_COUNT).contains(&cp) {
877            if let Some(&next) = chars.peek() {
878                let np = next as u32;
879                if (HANGUL_V_BASE..HANGUL_V_BASE + HANGUL_V_COUNT).contains(&np) {
880                    chars.next();
881                    let l_index = cp - HANGUL_L_BASE;
882                    let v_index = np - HANGUL_V_BASE;
883                    let mut s_index = l_index * HANGUL_N_COUNT + v_index * HANGUL_T_COUNT;
884                    if let Some(&t_next) = chars.peek() {
885                        let tp = t_next as u32;
886                        if tp > HANGUL_T_BASE && tp < HANGUL_T_BASE + HANGUL_T_COUNT {
887                            chars.next();
888                            let t_index = tp - HANGUL_T_BASE;
889                            s_index += t_index;
890                        }
891                    }
892                    if let Some(hangul) = char::from_u32(HANGUL_S_BASE + s_index) {
893                        out.push(hangul);
894                        continue;
895                    }
896                }
897            }
898        }
899        if let Some(&next) = chars.peek() {
900            if let Some(composed) = japanese_voiced_sound_compose(c, next) {
901                out.push(composed);
902                chars.next();
903                continue;
904            }
905            if let Some((pre, _, _)) = NFD_TABLE.iter().find(|(_, base, mark)| *base == c && *mark == next) {
906                out.push(*pre);
907                chars.next();
908                continue;
909            }
910        }
911        out.push(c);
912    }
913    out
914}
915pub(crate) fn str_normalize(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
916    let s = this_str_c(it, &t)?;
917    let form = if matches!(arg(a, 0), Value::Undefined) {
918        String::from("NFC")
919    } else {
920        it.to_string_value(arg(a, 0))?
921    };
922    match form.as_str() {
923        "NFC" | "NFKC" => Ok(Value::str(nfc_compose(&s))),
924        "NFD" | "NFKD" => Ok(Value::str(nfd_decompose(&s))),
925        _ => Err(it.range_error("The normalization form should be one of NFC, NFD, NFKC, NFKD.")),
926    }
927}
928/// `String.prototype.split(separator, limit)`。以前は `limit`(第2引数。結果配列の
929/// 最大要素数)を完全に無視しており、`"a,b,c".split(",", 2)` が仕様の `["a","b"]` ではなく
930/// 全要素 `["a","b","c"]` を返していた。
931pub(crate) fn str_split(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
932    let rx = arg(a, 0);
933    if matches!(t, Value::Undefined | Value::Null) {
934        return Err(it.type_error("String.prototype.split called on null or undefined"));
935    }
936    if let Some(v) = dispatch_symbol(it, &t, &rx, symbol_split_key(), arg(a, 1))? {
937        return Ok(v);
938    }
939    let s = this_str_c(it, &t)?.into_owned();
940    // 仕様の順序: ToUint32(limit) → ToString(separator) → limit が 0 なら空配列 → separator が undefined なら [S]。
941    let lim = match arg(a, 1) {
942        Value::Undefined => 4294967295.0,
943        v => to_uint32(it.num_of(&v)?),
944    };
945    let limit = lim as usize;
946    let sep = if matches!(rx, Value::Undefined) { None } else { Some(it.to_string_value(rx)?) };
947    if limit == 0 {
948        return Ok(Value::Object(Obj::array(Vec::new())));
949    }
950    let mut items: Vec<Value> = match sep {
951        None => vec![Value::str(s)],
952        Some(sep) => {
953            if sep.is_empty() {
954                let u = Units::of(&s);
955                (0..u.len().min(limit)).map(|i| Value::str(u.slice(i, i + 1))).collect()
956            } else if s.is_empty() {
957                vec![Value::str(s)]
958            } else {
959                s.split(&sep as &str).take(limit).map(|p| Value::str(p.to_string())).collect()
960            }
961        }
962    };
963    items.truncate(limit);
964    Ok(Value::Object(Obj::array(items)))
965}
966pub(crate) fn str_replace(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
967    let rx = arg(a, 0);
968    if matches!(t, Value::Undefined | Value::Null) {
969        return Err(it.type_error("String.prototype.replace called on null or undefined"));
970    }
971    if let Some(v) = dispatch_symbol(it, &t, &rx, symbol_replace_key(), arg(a, 1))? {
972        return Ok(v);
973    }
974    let s = this_str_c(it, &t)?.into_owned();
975    let from = to_str_strict(it, rx)?;
976    let repl = arg(a, 1);
977    Ok(Value::str(replace_string_pattern(it, &s, &from, repl, false)?))
978}
979/// `String.prototype.replaceAll(pattern, replacement)`。
980pub(crate) fn str_replace_all(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
981    // 仕様の順序: this の検査 → `g` のない RegExp 風の引数の TypeError → `[Symbol.replace]` への委譲。
982    let rx = arg(a, 0);
983    if matches!(t, Value::Undefined | Value::Null) {
984        return Err(it.type_error("String.prototype.replaceAll called on null or undefined"));
985    }
986    replace_all_precheck(it, &rx)?;
987    if let Some(v) = dispatch_symbol(it, &t, &rx, symbol_replace_key(), arg(a, 1))? {
988        return Ok(v);
989    }
990    let s = this_str_c(it, &t)?.into_owned();
991    let from = to_str_strict(it, rx)?;
992    let repl = arg(a, 1);
993    Ok(Value::str(replace_string_pattern(it, &s, &from, repl, true)?))
994}
995/// `String.prototype.repeat(count)`(ES2015)。仕様上 `count` が負値または `+Infinity` の
996/// 場合は `RangeError` を投げる必要があるが、以前は範囲外を空文字列へ黙って丸めていた
997/// (`"x".repeat(-1)` が例外にならず `""` を返す、呼び出し側が引数ミスに気づけないバグ。
998/// `Array.prototype.with` の範囲外 `index` と同種の「RangeError 相当箇所で `it.error()` の
999/// 汎用 Error を投げる」という既存の簡略方針に合わせる)。
1000pub(crate) fn str_repeat(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1001    let t = this_val(it, &t)?;
1002    let n = it.num_of(&arg(a, 0))?;
1003    if n.is_nan() {
1004        return Ok(Value::str(String::new()));
1005    }
1006    if n < 0.0 || n == f64::INFINITY {
1007        return Err(it.range_error("Invalid count value"));
1008    }
1009    Ok(Value::str(this_str_c(it, &t)?.repeat(n as usize)))
1010}
1011pub(crate) fn str_concat(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1012    let mut s = this_str_c(it, &t)?.into_owned();
1013    for v in a {
1014        s.push_str(&to_str_strict(it, v.clone())?);
1015    }
1016    Ok(Value::str(s))
1017}
1018pub(crate) fn str_pad_start(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1019    let s = this_str_c(it, &t)?.into_owned();
1020    let target = to_length_u64_checked(it, &arg(a, 0))? as usize;
1021    let pad = if matches!(arg(a, 1), Value::Undefined) {
1022        String::from(" ")
1023    } else {
1024        to_str_strict(it, arg(a, 1))?
1025    };
1026    Ok(Value::str(pad_str(&s, target, &pad, true)))
1027}
1028pub(crate) fn str_pad_end(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1029    let s = this_str_c(it, &t)?.into_owned();
1030    let target = to_length_u64_checked(it, &arg(a, 0))? as usize;
1031    let pad = if matches!(arg(a, 1), Value::Undefined) {
1032        String::from(" ")
1033    } else {
1034        to_str_strict(it, arg(a, 1))?
1035    };
1036    Ok(Value::str(pad_str(&s, target, &pad, false)))
1037}
1038
1039/// 数値の組込みネイティブ関数定義。
1040pub fn number_builtin_fn(key: &str) -> Option<(&'static str, NativeFn)> {
1041    let pair = match key {
1042        "toFixed" => ("toFixed", num_to_fixed as NativeFn),
1043        "toString" => ("Number.toString", num_to_string as NativeFn),
1044        "toExponential" => ("toExponential", num_to_exponential as NativeFn),
1045        "toPrecision" => ("toPrecision", num_to_precision as NativeFn),
1046        "valueOf" => ("valueOf", num_value_of as NativeFn),
1047        "toLocaleString" => ("toLocaleString", num_to_locale_string as NativeFn),
1048        _ => return None,
1049    };
1050    Some(pair)
1051}
1052
1053/// 数値レシーバのメソッド。
1054pub fn number_get(n: f64, key: &str) -> Value {
1055    let _ = n;
1056    number_builtin_fn(key).map(|(name, f)| nv(name, f)).unwrap_or(Value::Undefined)
1057}
1058pub(crate) fn num_value_of(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
1059    Ok(Value::Number(this_number(it, &t, "valueOf")?))
1060}
1061/// `Boolean.prototype.toString`/`valueOf`。以前は `Value::Bool` へのプロパティアクセスが
1062/// `get_property()` で一律 `Value::Undefined` を返しており、`true.toString()`/
1063/// `false.valueOf()` のような基本的な呼出しが「関数ではない」`TypeError` になっていた
1064/// (プリミティブ中 `Boolean` だけがメソッドを一切持たない状態だった)。`NativeFn` は環境を
1065/// 捕獲できない生の関数ポインタのため、値は(他のプリミティブ同様)呼出時の `this` から
1066/// 読み取る。
1067/// 真偽値の組込みネイティブ関数定義。
1068pub fn boolean_builtin_fn(key: &str) -> Option<(&'static str, NativeFn)> {
1069    let pair = match key {
1070        "toString" => ("toString", bool_to_string as NativeFn),
1071        "valueOf" => ("valueOf", bool_value_of as NativeFn),
1072        _ => return None,
1073    };
1074    Some(pair)
1075}
1076
1077pub fn boolean_get(_b: bool, key: &str) -> Value {
1078    boolean_builtin_fn(key).map(|(name, f)| nv(name, f)).unwrap_or(Value::Undefined)
1079}
1080pub(crate) fn bool_to_string(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
1081    Ok(Value::str(if this_boolean(it, &t, "toString")? { "true" } else { "false" }))
1082}
1083pub(crate) fn bool_value_of(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
1084    Ok(Value::Bool(this_boolean(it, &t, "valueOf")?))
1085}
1086/// 仮数部を `[1,10)` の範囲に正規化した `(仮数, 指数)` を返す(`0` は `(0, 0)`)。
1087/// 浮動小数点誤差で `log10`/`pow` の往復が範囲をわずかに外れることがあるので補正する。
1088pub(crate) fn normalize_mantissa(abs_n: f64) -> (f64, i32) {
1089    if abs_n == 0.0 {
1090        return (0.0, 0);
1091    }
1092    let mut exp = libm::floor(libm::log10(abs_n)) as i32;
1093    let mut mantissa = abs_n / libm::pow(10.0, exp as f64);
1094    if mantissa >= 10.0 {
1095        mantissa /= 10.0;
1096        exp += 1;
1097    } else if mantissa < 1.0 {
1098        mantissa *= 10.0;
1099        exp -= 1;
1100    }
1101    (mantissa, exp)
1102}
1103/// `Number.prototype.toExponential(fractionDigits)`(ES3)。丸ごと欠落しており、
1104/// `n.toExponential(2)`(`"1.50e+2"` 等)を呼ぶと「メソッドが存在しない」`TypeError` に
1105/// なっていた。
1106pub(crate) fn num_to_exponential(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1107    let n = this_number(it, &t, "toExponential")?;
1108    let digits = match arg(a, 0) {
1109        Value::Undefined => None,
1110        v => {
1111            let d = it.num_of(&v)?;
1112            Some(if d.is_nan() { 0.0 } else { libm::trunc(d) })
1113        }
1114    };
1115    if !n.is_finite() {
1116        return Ok(Value::str(crate::os_lib::ecma::numfmt::to_string10(n)));
1117    }
1118    let digits = match digits {
1119        None => None,
1120        Some(d) if (0.0..=100.0).contains(&d) => Some(d as usize),
1121        Some(_) => return Err(it.range_error("toExponential() argument must be between 0 and 100")),
1122    };
1123    Ok(Value::str(crate::os_lib::ecma::numfmt::to_exponential(n, digits)))
1124}
1125/// `Number.prototype.toPrecision(precision)`(ES3)。丸ごと欠落していた。`precision`
1126/// 省略時は `toString()` と同じ、指定時は有効桁数がその値になるよう固定小数/指数表記を
1127/// 自動選択する(仕様どおり、指数が `-6` 未満または `precision` 以上なら指数表記)。
1128pub(crate) fn num_to_precision(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1129    let n = this_number(it, &t, "toPrecision")?;
1130    if matches!(arg(a, 0), Value::Undefined) {
1131        return Ok(Value::str(crate::os_lib::ecma::numfmt::to_string10(n)));
1132    }
1133    let p = libm::trunc(it.num_of(&arg(a, 0))?);
1134    if !n.is_finite() {
1135        return Ok(Value::str(crate::os_lib::ecma::numfmt::to_string10(n)));
1136    }
1137    if !(1.0..=100.0).contains(&p) {
1138        return Err(it.range_error("toPrecision() argument must be between 1 and 100"));
1139    }
1140    Ok(Value::str(crate::os_lib::ecma::numfmt::to_precision(n, p as usize)))
1141}
1142/// `Number.prototype.toFixed(fractionDigits)`。仕様上 `fractionDigits` が `0`〜`100`
1143/// の範囲外(負値や `101` 以上)なら `RangeError` を投げる必要があるが、以前は範囲外/
1144/// 非有限値を黙って `0` にクランプするだけで上限チェックが無く、`(1).toFixed(500)` の
1145/// ような呼び出しが `10^500`(`Infinity`)を経由して壊れた出力になり得た
1146/// (`toPrecision` には同種のチェックが既にあったが `toFixed` だけ欠けていた)。
1147pub(crate) fn num_to_fixed(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1148    let n = this_number(it, &t, "toFixed")?;
1149    let digits = match arg(a, 0) {
1150        Value::Undefined => 0.0,
1151        v => {
1152            let d = it.num_of(&v)?;
1153            if d.is_nan() { 0.0 } else { libm::trunc(d) }
1154        }
1155    };
1156    if !(0.0..=100.0).contains(&digits) {
1157        return Err(it.range_error("toFixed() digits argument must be between 0 and 100"));
1158    }
1159    Ok(Value::str(crate::os_lib::ecma::numfmt::to_fixed(n, digits as usize)))
1160}
1161/// `Number.prototype.toString(radix)`。以前は `radix`(第1引数。2進/16進表示等の定番
1162/// イディオム `n.toString(16)`)を完全に無視し常に10進表示だった。
1163pub(crate) fn num_to_string(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1164    let n = this_number(it, &t, "toString")?;
1165    let radix = match arg(a, 0) {
1166        Value::Undefined => 10.0,
1167        v => {
1168            let r = it.num_of(&v)?;
1169            if r.is_nan() { 0.0 } else { libm::trunc(r) }
1170        }
1171    };
1172    if !(2.0..=36.0).contains(&radix) {
1173        return Err(it.range_error("toString() radix must be between 2 and 36"));
1174    }
1175    if radix == 10.0 {
1176        return Ok(Value::str(crate::os_lib::ecma::numfmt::to_string10(n)));
1177    }
1178    Ok(Value::str(crate::os_lib::ecma::numfmt::to_radix(n, radix as u32)))
1179}
1180/// `Number.prototype.toLocaleString()` が `toString()` の別名に過ぎず、実際のブラウザなら
1181/// `Intl` 非搭載でも必ず入る3桁区切りのカンマ(`(1234567).toLocaleString()` → `"1,234,567"`)
1182/// が丸ごと欠落していた(常に `"1234567"` になっていた)バグ。`Intl`/ロケール引数自体は
1183/// 非対応(`Array.prototype.toLocaleString`/`normalize`/`localeCompare` と同種の割り切り)
1184/// だが、既定のグループ区切り(整数部のみ、小数部・NaN・Infinity・負号は対象外)だけは行う。
1185pub(crate) fn num_to_locale_string(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1186    // 【2026-11-18】ロケールとオプション(`style`・`currency`・`maximumFractionDigits`・`notation` など)に対応(`numloc.rs`)。
1187    // 以前は引数を無視した 3 桁区切りだけで、`NaN`・`Infinity` は文字のままだった(V8 は `∞`)。
1188    let n = if matches!(t, Value::BigInt(_)) { t.to_number() } else { this_number(it, &t, "toLocaleString")? };
1189    let opts = super::intl::build_nf_options(it, &arg(a, 0), &arg(a, 1))?;
1190    Ok(Value::str(crate::os_lib::ecma::numloc::format(n, &opts)))
1191}
1192pub(crate) const RADIX_DIGITS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
1193pub(crate) fn format_radix(num: f64, radix: u32) -> String {
1194    if num.is_nan() {
1195        return String::from("NaN");
1196    }
1197    if num.is_infinite() {
1198        return String::from(if num > 0.0 { "Infinity" } else { "-Infinity" });
1199    }
1200    let neg = num < 0.0;
1201    let n = libm::fabs(num);
1202    let int_n = libm::floor(n);
1203    let mut frac = n - int_n;
1204    let mut int_digits = Vec::new();
1205    let mut i = int_n;
1206    if i == 0.0 {
1207        int_digits.push(b'0');
1208    }
1209    while i >= 1.0 {
1210        let rem = libm::fmod(i, radix as f64) as usize;
1211        int_digits.push(RADIX_DIGITS[rem.min(35)]);
1212        i = libm::floor(i / radix as f64);
1213    }
1214    int_digits.reverse();
1215    let mut s = String::from_utf8(int_digits).unwrap_or_default();
1216    if frac > 0.0 {
1217        s.push('.');
1218        let mut count = 0;
1219        while frac > 0.0 && count < 20 {
1220            frac *= radix as f64;
1221            let d = libm::floor(frac) as usize;
1222            s.push(RADIX_DIGITS[d.min(35)] as char);
1223            frac -= libm::floor(frac);
1224            count += 1;
1225        }
1226    }
1227    if neg {
1228        format!("-{}", s)
1229    } else {
1230        s
1231    }
1232}
1233
1234/// BigInt の組込みネイティブ関数定義。
1235pub fn bigint_builtin_fn(key: &str) -> Option<(&'static str, NativeFn)> {
1236    let pair = match key {
1237        "toString" => ("toString", bigint_to_string as NativeFn),
1238        "valueOf" => ("valueOf", bigint_value_of as NativeFn),
1239        "toLocaleString" => ("toLocaleString", bigint_to_locale_string as NativeFn),
1240        _ => return None,
1241    };
1242    Some(pair)
1243}
1244
1245pub(crate) fn bigint_to_locale_string(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1246    let bi_str = match &t {
1247        Value::BigInt(b) => b.to_radix_string(10),
1248        Value::Object(o) => match o.borrow().primitive() {
1249            Some(Value::BigInt(b)) => b.to_radix_string(10),
1250            _ => return Err(it.type_error("BigInt.prototype.toLocaleString requires that 'this' be a BigInt")),
1251        },
1252        _ => return Err(it.type_error("BigInt.prototype.toLocaleString requires that 'this' be a BigInt")),
1253    };
1254    let opts = super::intl::build_nf_options(it, &arg(a, 0), &arg(a, 1))?;
1255    let nv = crate::os_lib::ecma::numloc::NumValue::from_int_str(&bi_str);
1256    Ok(Value::str(crate::os_lib::ecma::numloc::format_value(&nv, &opts)))
1257}
1258
1259/// BigInt レシーバのメソッド(toString / valueOf)。
1260pub fn bigint_get(b: &alloc::rc::Rc<super::super::bigint::BigInt>, key: &str) -> Value {
1261    let _ = b;
1262    bigint_builtin_fn(key).map(|(name, f)| nv(name, f)).unwrap_or(Value::Undefined)
1263}
1264pub(crate) fn bigint_to_string(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
1265    let bi_val = match &t {
1266        Value::BigInt(_) => t.clone(),
1267        Value::Object(o) => match o.borrow().primitive() {
1268            Some(p @ Value::BigInt(_)) => p.clone(),
1269            _ => return Err(it.type_error("BigInt.prototype.toString requires that 'this' be a BigInt")),
1270        },
1271        _ => return Err(it.type_error("BigInt.prototype.toString requires that 'this' be a BigInt")),
1272    };
1273    // 【2026-11-17】基数の引数(`(255n).toString(16)` は "ff")。以前は無視して 10 進で返していた。
1274    if let (Value::BigInt(b), Some(r)) = (&bi_val, a.first().filter(|v| !matches!(v, Value::Undefined))) {
1275        let n = it.num_of(r)?;
1276        let radix = to_integer_or_infinity(n);
1277        if !(2.0..=36.0).contains(&radix) {
1278            return Err(it.range_error("toString() radix must be between 2 and 36"));
1279        }
1280        return Ok(Value::str(b.to_radix_string(radix as u32)));
1281    }
1282    Ok(Value::str(bi_val.to_js_string()))
1283}
1284pub(crate) fn bigint_value_of(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
1285    match &t {
1286        Value::BigInt(_) => Ok(t),
1287        Value::Object(o) => match o.borrow().primitive() {
1288            Some(p @ Value::BigInt(_)) => Ok(p.clone()),
1289            _ => Err(it.type_error("BigInt.prototype.valueOf requires that 'this' be a BigInt")),
1290        },
1291        _ => Err(it.type_error("BigInt.prototype.valueOf requires that 'this' be a BigInt")),
1292    }
1293}
1294
1295/// BigInt(value): Number / String / Boolean / BigInt から BigInt を生成する。
1296/// `new BigInt()` は不可だが、ここでは関数呼び出しのみ対応。
1297pub(crate) fn bigint_ctor(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1298    use super::super::bigint::BigInt;
1299    let raw = a.first().cloned().unwrap_or(Value::Undefined);
1300    let arg = if matches!(raw, Value::Object(_)) {
1301        it.to_primitive(raw, "number")?
1302    } else {
1303        raw
1304    };
1305    let bi = match &arg {
1306        Value::BigInt(b) => (**b).clone(),
1307        Value::Number(n) => match BigInt::from_f64(*n) {
1308            Some(v) => v,
1309            None => {
1310                return Err(it.range_error("The number cannot be converted to a BigInt because it is not an integer"));
1311            }
1312        },
1313        Value::Bool(b) => BigInt::from_i64(if *b { 1 } else { 0 }),
1314        Value::Str(s) => match BigInt::parse_js_string(s) {
1315            Some(v) => v,
1316            None => return Err(it.syntax_error("Cannot convert string to a BigInt")),
1317        },
1318        _ => return Err(it.type_error("Cannot convert value to a BigInt")),
1319    };
1320    Ok(Value::bigint(bi))
1321}
1322
1323/// 引数から「ビット幅」を取り出す(ECMA-262 ToIndex 準拠)。
1324pub(crate) fn bits_arg(it: &mut Interp, a: &[Value]) -> Result<u64, Value> {
1325    let raw = arg(a, 0);
1326    if matches!(raw, Value::Undefined) {
1327        return Ok(0);
1328    }
1329    let n = it.num_of(&raw)?;
1330    let int = to_integer_or_infinity(n);
1331    if !(0.0..=MAX_SAFE_INT_F64).contains(&int) {
1332        return Err(it.range_error("Invalid bits value for BigInt.asIntN/asUintN"));
1333    }
1334    Ok(int as u64)
1335}
1336
1337/// 引数2を ToBigInt で変換して取り出す。
1338pub(crate) fn bigint_arg(it: &mut Interp, a: &[Value]) -> Result<super::super::bigint::BigInt, Value> {
1339    use super::super::bigint::BigInt;
1340    let raw = arg(a, 1);
1341    let prim = if matches!(raw, Value::Object(_)) {
1342        it.to_primitive(raw, "number")?
1343    } else {
1344        raw
1345    };
1346    match &prim {
1347        Value::BigInt(b) => Ok((**b).clone()),
1348        Value::Bool(b) => Ok(BigInt::from_i64(if *b { 1 } else { 0 })),
1349        Value::Str(s) if !is_symbol_like_key(s) => match BigInt::parse_js_string(s) {
1350            Some(v) => Ok(v),
1351            None => Err(it.syntax_error("Cannot convert string to a BigInt")),
1352        },
1353        _ => Err(it.type_error("Cannot convert value to a BigInt")),
1354    }
1355}
1356
1357/// BigInt.asIntN(bits, bigint)
1358pub(crate) fn bigint_as_int_n(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1359    let bits = bits_arg(it, a)?;
1360    let v = bigint_arg(it, a)?;
1361    Ok(Value::bigint(v.as_int_n(bits)))
1362}
1363
1364/// BigInt.asUintN(bits, bigint)
1365pub(crate) fn bigint_as_uint_n(it: &mut Interp, _t: Value, a: &[Value]) -> Result<Value, Value> {
1366    let bits = bits_arg(it, a)?;
1367    let v = bigint_arg(it, a)?;
1368    Ok(Value::bigint(v.as_uint_n(bits)))
1369}
1370
1371// ============ オブジェクト/配列メソッド ============
1372
1373/// オブジェクトレシーバのメソッド(配列メソッド含む)。
1374/// 配列の組込みネイティブ関数定義。
1375pub fn array_builtin_fn(key: &str) -> Option<(&'static str, NativeFn)> {
1376    let pair = match key {
1377        "push" => ("push", arr_push as NativeFn),
1378        "pop" => ("pop", arr_pop as NativeFn),
1379        "shift" => ("shift", arr_shift as NativeFn),
1380        "unshift" => ("unshift", arr_unshift as NativeFn),
1381        "slice" => ("slice", arr_slice as NativeFn),
1382        "indexOf" => ("indexOf", arr_index_of as NativeFn),
1383        "includes" => ("includes", arr_includes as NativeFn),
1384        "join" => ("join", arr_join as NativeFn),
1385        "concat" => ("concat", arr_concat as NativeFn),
1386        "reverse" => ("reverse", arr_reverse as NativeFn),
1387        "map" => ("map", arr_map_g as NativeFn),
1388        "filter" => ("filter", arr_filter_g as NativeFn),
1389        "forEach" => ("forEach", arr_for_each_g as NativeFn),
1390        "reduce" => ("reduce", arr_reduce_g as NativeFn),
1391        "find" => ("find", arr_find as NativeFn),
1392        "findIndex" => ("findIndex", arr_find_index as NativeFn),
1393        "some" => ("some", arr_some_g as NativeFn),
1394        "every" => ("every", arr_every_g as NativeFn),
1395        "sort" => ("sort", arr_sort as NativeFn),
1396        "fill" => ("fill", arr_fill as NativeFn),
1397        "flat" => ("flat", arr_flat as NativeFn),
1398        "flatMap" => ("flatMap", arr_flat_map as NativeFn),
1399        "at" => ("at", arr_at as NativeFn),
1400        "findLast" => ("findLast", arr_find_last_safe as NativeFn),
1401        "findLastIndex" => ("findLastIndex", arr_find_last_index_safe as NativeFn),
1402        "entries" => ("entries", arr_entries as NativeFn),
1403        "keys" => ("keys", arr_keys as NativeFn),
1404        "values" => ("values", arr_values as NativeFn),
1405        "Symbol(Symbol.iterator)" => ("[Symbol.iterator]", arr_values as NativeFn),
1406        "reduceRight" => ("reduceRight", arr_reduce_right_safe as NativeFn),
1407        "toString" => ("toString", arr_to_string as NativeFn),
1408        "toLocaleString" => ("toLocaleString", arr_to_locale_string as NativeFn),
1409        "splice" => ("splice", arr_splice as NativeFn),
1410        "lastIndexOf" => ("lastIndexOf", arr_last_index_of as NativeFn),
1411        "copyWithin" => ("copyWithin", arr_copy_within as NativeFn),
1412        "toSorted" => ("toSorted", arr_to_sorted as NativeFn),
1413        "toReversed" => ("toReversed", arr_to_reversed as NativeFn),
1414        "toSpliced" => ("toSpliced", arr_to_spliced as NativeFn),
1415        "with" => ("with", arr_with as NativeFn),
1416        _ => return None,
1417    };
1418    Some(pair)
1419}
1420
1421/// 共通オブジェクトの組込みネイティブ関数定義。
1422pub fn object_builtin_fn(key: &str) -> Option<(&'static str, NativeFn)> {
1423    let pair = match key {
1424        "hasOwnProperty" => ("hasOwnProperty", obj_has_own as NativeFn),
1425        "toString" => ("toString", obj_to_string as NativeFn),
1426        "toLocaleString" => ("toLocaleString", obj_to_locale_string as NativeFn),
1427        "valueOf" => ("valueOf", obj_value_of as NativeFn),
1428        "isPrototypeOf" => ("isPrototypeOf", obj_is_prototype_of as NativeFn),
1429        "propertyIsEnumerable" => ("propertyIsEnumerable", obj_property_is_enumerable as NativeFn),
1430        "__defineGetter__" => ("__defineGetter__", obj_define_getter as NativeFn),
1431        "__defineSetter__" => ("__defineSetter__", obj_define_setter as NativeFn),
1432        "__lookupGetter__" => ("__lookupGetter__", obj_lookup_getter as NativeFn),
1433        "__lookupSetter__" => ("__lookupSetter__", obj_lookup_setter as NativeFn),
1434        _ => return None,
1435    };
1436    Some(pair)
1437}
1438
1439pub(crate) fn obj_value_of(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
1440    if matches!(t, Value::Undefined | Value::Null) {
1441        return Err(it.type_error("Cannot convert undefined or null to object"));
1442    }
1443    // ToObject(this)(プリミティブはラッパーオブジェクトにする)。
1444    to_object_required(it, &t, "valueOf")
1445}
1446
1447/// オブジェクトレシーバのメソッド(配列メソッド含む)。
1448pub fn object_get(o: &ObjRef, key: &str) -> Value {
1449    let is_array = matches!(o.borrow().kind, ObjKind::Array(_));
1450    if is_array {
1451        if let Some((name, f)) = array_builtin_fn(key) {
1452            return nv(name, f);
1453        }
1454    }
1455    if let Some((name, f)) = object_builtin_fn(key) {
1456        return nv(name, f);
1457    }
1458    Value::Undefined
1459}
1460fn to_object_required(it: &mut Interp, v: &Value, method: &str) -> Result<Value, Value> {
1461    if matches!(v, Value::Undefined | Value::Null) {
1462        return Err(it.type_error(alloc::format!(
1463            "Object.prototype.{} called on null or undefined",
1464            method
1465        )));
1466    }
1467    if matches!(v, Value::Object(_)) {
1468        Ok(v.clone())
1469    } else {
1470        super::object_array::object_ctor(it, Value::Undefined, core::slice::from_ref(v))
1471    }
1472}
1473
1474fn define_accessor_legacy(
1475    it: &mut Interp,
1476    this: Value,
1477    a: &[Value],
1478    is_getter: bool,
1479    method: &str,
1480) -> Result<Value, Value> {
1481    let obj = to_object_required(it, &this, method)?;
1482    let f = arg(a, 1);
1483    if !matches!(&f, Value::Object(fo) if fo.borrow().is_callable()) {
1484        return Err(it.type_error("Accessor must be a function"));
1485    }
1486    let pk = it.prim_key(arg(a, 0))?;
1487    let key = super::super::interp::to_property_key(&pk).into_owned();
1488    let desc = Obj::plain();
1489    {
1490        let mut db = desc.borrow_mut();
1491        db.props.insert(if is_getter { "get" } else { "set" }.into(), f);
1492        db.props.insert("enumerable".into(), Value::Bool(true));
1493        db.props.insert("configurable".into(), Value::Bool(true));
1494    }
1495    super::extra_static::object_define_property(
1496        it,
1497        Value::Undefined,
1498        &[obj, Value::str(key), Value::Object(desc)],
1499    )?;
1500    Ok(Value::Undefined)
1501}
1502
1503fn lookup_accessor_legacy(
1504    it: &mut Interp,
1505    this: Value,
1506    a: &[Value],
1507    is_getter: bool,
1508    method: &str,
1509) -> Result<Value, Value> {
1510    let mut cur = to_object_required(it, &this, method)?;
1511    let pk = it.prim_key(arg(a, 0))?;
1512    let key = Value::str(super::super::interp::to_property_key(&pk).into_owned());
1513    for _ in 0..1000 {
1514        let desc = super::extra_static::object_get_own_property_descriptor(
1515            it,
1516            Value::Undefined,
1517            &[cur.clone(), key.clone()],
1518        )?;
1519        if !matches!(desc, Value::Undefined) {
1520            let has_data = if let Value::Object(d) = &desc {
1521                let db = d.borrow();
1522                db.props.contains_key("value") || db.props.contains_key("writable")
1523            } else {
1524                false
1525            };
1526            if has_data {
1527                return Ok(Value::Undefined);
1528            }
1529            return it.get_property(&desc, if is_getter { "get" } else { "set" });
1530        }
1531        cur = super::extra_static::object_get_prototype_of(it, Value::Undefined, &[cur])?;
1532        if !matches!(cur, Value::Object(_)) {
1533            break;
1534        }
1535    }
1536    Ok(Value::Undefined)
1537}
1538
1539pub(crate) fn obj_define_getter(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1540    define_accessor_legacy(it, this, a, true, "__defineGetter__")
1541}
1542pub(crate) fn obj_define_setter(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1543    define_accessor_legacy(it, this, a, false, "__defineSetter__")
1544}
1545pub(crate) fn obj_lookup_getter(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1546    lookup_accessor_legacy(it, this, a, true, "__lookupGetter__")
1547}
1548pub(crate) fn obj_lookup_setter(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1549    lookup_accessor_legacy(it, this, a, false, "__lookupSetter__")
1550}
1551
1552/// 配列プロトタイプメソッドのほぼ全てがこのヘルパ経由で `this` の要素を読む。以前は
1553/// `Proxy` を素通しできず(`ObjKind::Array` に一致しない)、`Array.prototype.map.call(
1554/// new Proxy([1,2,3],{}), f)` のように Proxy をラップした配列へ直接メソッド呼出しすると
1555/// 常に空配列扱いになるバグだった(`for...of`/スプレッドは別経路で既に対応済みだったが、
1556/// メソッド呼出し経由はこのヘルパ止まりで漏れていた)。
1557pub(crate) fn this_items(this: &Value) -> Vec<Value> {
1558    if let Value::Object(o) = this {
1559        let o = unwrap_proxy_target(o);
1560        let b = o.borrow();
1561        if let ObjKind::Array(items) = &b.kind {
1562            return items.clone();
1563        }
1564        if let ObjKind::Bytes(st) = &b.kind {
1565            return st.values();
1566        }
1567    }
1568    Vec::new()
1569}
1570/// `this_items` と同じ Proxy 透過性が必要(配列を直接変更するメソッド
1571/// push/pop/sort/splice 等が内部で使う実オブジェクト参照)。
1572pub(crate) fn this_objref(this: &Value) -> Option<ObjRef> {
1573    if let Value::Object(o) = this {
1574        Some(unwrap_proxy_target(o))
1575    } else {
1576        None
1577    }
1578}
1579
1580/// ECMA-262 の最大安全整数 `2^53 - 1`。
1581const MAX_SAFE_INT_U64: u64 = 9_007_199_254_740_991;
1582const MAX_SAFE_INT_F64: f64 = 9_007_199_254_740_991.0;
1583
1584fn to_integer_or_infinity(n: f64) -> f64 {
1585    if n.is_nan() || n == 0.0 {
1586        0.0
1587    } else if n.is_infinite() {
1588        n
1589    } else {
1590        libm::trunc(n)
1591    }
1592}
1593
1594pub(crate) fn to_length_u64(v: &Value) -> u64 {
1595    let n = to_integer_or_infinity(v.to_number());
1596    if n <= 0.0 {
1597        0
1598    } else if n >= MAX_SAFE_INT_F64 {
1599        MAX_SAFE_INT_U64
1600    } else {
1601        n as u64
1602    }
1603}
1604
1605pub(crate) fn to_length_u64_checked(it: &mut Interp, v: &Value) -> Result<u64, Value> {
1606    let n = to_integer_or_infinity(it.num_of(v)?);
1607    Ok(if n <= 0.0 {
1608        0
1609    } else if n >= MAX_SAFE_INT_F64 {
1610        MAX_SAFE_INT_U64
1611    } else {
1612        n as u64
1613    })
1614}
1615
1616fn norm_index_u64(v: f64, len: u64) -> u64 {
1617    let int = to_integer_or_infinity(v);
1618    if int == f64::NEG_INFINITY {
1619        0
1620    } else if int == f64::INFINITY || int >= (len as f64) {
1621        len
1622    } else if int < 0.0 {
1623        let abs = -int;
1624        if abs >= (len as f64) {
1625            0
1626        } else {
1627            len - (abs as u64)
1628        }
1629    } else {
1630        (int as u64).min(len)
1631    }
1632}
1633
1634fn from_index_u64(a: &[Value], len: u64) -> Option<u64> {
1635    if len == 0 {
1636        return None;
1637    }
1638    if a.len() < 2 || matches!(arg(a, 1), Value::Undefined) {
1639        return Some(0);
1640    }
1641    let n = to_integer_or_infinity(arg(a, 1).to_number());
1642    if n == f64::INFINITY || n >= (len as f64) {
1643        return None;
1644    }
1645    if n == f64::NEG_INFINITY {
1646        return Some(0);
1647    }
1648    if n >= 0.0 {
1649        Some((n as u64).min(len))
1650    } else {
1651        let abs = -n;
1652        if abs >= (len as f64) {
1653            Some(0)
1654        } else {
1655            Some(len - (abs as u64))
1656        }
1657    }
1658}
1659
1660fn is_direct_array(t: &Value) -> bool {
1661    matches!(t, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Array(_)))
1662}
1663
1664fn is_dense_plain_array(t: &Value) -> bool {
1665    matches!(t, Value::Object(o) if {
1666        let b = o.borrow();
1667        matches!(b.kind, ObjKind::Array(_)) && b.holes().is_none() && b.accessors().is_none()
1668    })
1669}
1670
1671fn is_js_array(t: &Value) -> bool {
1672    matches!(t, Value::Object(o) if matches!(unwrap_proxy_target(o).borrow().kind, ObjKind::Array(_)))
1673}
1674
1675fn try_vec_with_capacity<T>(it: &mut Interp, cap: usize) -> Result<Vec<T>, Value> {
1676    if cap > crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN {
1677        return Err(it.range_error("Invalid array length"));
1678    }
1679    let mut v = Vec::new();
1680    if cap > 0 && v.try_reserve_exact(cap).is_err() {
1681        return Err(it.range_error("Invalid array length"));
1682    }
1683    Ok(v)
1684}
1685
1686fn next_proto_for_elem(it: &Interp, cur: &ObjRef) -> Option<ObjRef> {
1687    let b = cur.borrow();
1688    if let Some(p) = &b.proto {
1689        return Some(p.clone());
1690    }
1691    if b.is_null_proto() {
1692        return None;
1693    }
1694    if let (ObjKind::Plain, Some(prim)) = (&b.kind, b.primitive()) {
1695        let cname = match prim {
1696            Value::Str(_) => Some("String"),
1697            Value::Number(_) => Some("Number"),
1698            Value::Bool(_) => Some("Boolean"),
1699            _ => None,
1700        };
1701        if let Some(p) = cname.and_then(|n| global_ctor_proto(it, n)) {
1702            if !Rc::ptr_eq(&p, cur) {
1703                return Some(p);
1704            }
1705        }
1706    }
1707    drop(b);
1708    implicit_proto(it, cur)
1709}
1710
1711fn has_array_elem(it: &mut Interp, t: &Value, key: &str) -> Result<bool, Value> {
1712    match t {
1713        Value::Object(o) => {
1714            // Proxy: has トラップがあれば呼び、無ければ target へ委譲する。
1715            let proxy = match &o.borrow().kind {
1716                ObjKind::Proxy(p) => Some((p.target.clone(), p.handler.clone())),
1717                _ => None,
1718            };
1719            if let Some((target, handler)) = proxy {
1720                let trap = handler.borrow().props.get("has").cloned();
1721                if let Some(trap) = trap.filter(|f| matches!(f, Value::Object(fn_o) if fn_o.borrow().is_callable())) {
1722                    let args = [Value::Object(target), Value::str(key)];
1723                    let res = it.call_value(&trap, Value::Object(handler), &args)?;
1724                    return Ok(res.truthy());
1725                }
1726                return has_array_elem(it, &Value::Object(target), key);
1727            }
1728            let mut cur_opt = Some(o.clone());
1729            let mut guard = 0u32;
1730            while let Some(cur) = cur_opt {
1731                let host_ref = cur.borrow().kind.host_ref();
1732                if let Some(h) = host_ref {
1733                    if !matches!(
1734                        (it.host.own)(it, h, key),
1735                        crate::os_lib::ecma::host::HostOwn::Generic
1736                            | crate::os_lib::ecma::host::HostOwn::Absent
1737                    ) {
1738                        return Ok(true);
1739                    }
1740                    if (it.host.resolves_on_read)(h) && (it.host.get)(it, &cur, h, key).is_some() {
1741                        return Ok(true);
1742                    }
1743                }
1744                {
1745                    let b = cur.borrow();
1746                    let is_arr = matches!(&b.kind, ObjKind::Array(_));
1747                    match &b.kind {
1748                        ObjKind::Array(items) => {
1749                            if key == "length" {
1750                                return Ok(true);
1751                            }
1752                            if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
1753                                if idx < items.len() && !b.is_hole(idx) {
1754                                    return Ok(true);
1755                                }
1756                            }
1757                        }
1758                        ObjKind::Bytes(st)
1759                            if key == "length"
1760                                || crate::os_lib::ecma::value::parse_index(key).is_some_and(|idx| idx < st.len) =>
1761                        {
1762                            return Ok(true);
1763                        }
1764                        ObjKind::Plain => {
1765                            if let Some(Value::Str(s)) = b.primitive() {
1766                                if key == "length"
1767                                    || crate::os_lib::ecma::value::parse_index(key)
1768                                        .is_some_and(|idx| idx < Units::of(s).len())
1769                                {
1770                                    return Ok(true);
1771                                }
1772                            }
1773                        }
1774                        _ => {}
1775                    }
1776                    let array_hole_index = is_arr && crate::os_lib::ecma::value::parse_index(key).is_some();
1777                    if (!array_hole_index && b.props.contains_key(key)) || b.has_accessor(key) {
1778                        return Ok(true);
1779                    }
1780                }
1781                guard += 1;
1782                if guard > 1000 {
1783                    break;
1784                }
1785                cur_opt = next_proto_for_elem(it, &cur);
1786            }
1787            Ok(false)
1788        }
1789        Value::Str(s) => {
1790            if key == "length"
1791                || crate::os_lib::ecma::value::parse_index(key).is_some_and(|idx| idx < Units::of(s).len())
1792            {
1793                return Ok(true);
1794            }
1795            match global_ctor_proto(it, "String") {
1796                Some(p) => has_array_elem(it, &Value::Object(p), key),
1797                None => Ok(false),
1798            }
1799        }
1800        Value::Bool(_) => match global_ctor_proto(it, "Boolean") {
1801            Some(p) => has_array_elem(it, &Value::Object(p), key),
1802            None => Ok(false),
1803        },
1804        Value::Number(_) => match global_ctor_proto(it, "Number") {
1805            Some(p) => has_array_elem(it, &Value::Object(p), key),
1806            None => Ok(false),
1807        },
1808        Value::BigInt(_) => match global_ctor_proto(it, "BigInt") {
1809            Some(p) => has_array_elem(it, &Value::Object(p), key),
1810            None => Ok(false),
1811        },
1812        _ => Ok(false),
1813    }
1814}
1815
1816fn get_array_elem(it: &mut Interp, t: &Value, key: &str) -> Result<Value, Value> {
1817    if let Value::Object(o) = t {
1818        let arr_direct = matches!(&o.borrow().kind, ObjKind::Array(_));
1819        if arr_direct {
1820            enum Hit {
1821                Getter(Option<Value>),
1822                Prop(Value),
1823                Elem(Value),
1824                Proto,
1825            }
1826            let hit = {
1827                let b = o.borrow();
1828                if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
1829                    let is_hole = matches!(&b.kind, ObjKind::Array(items) if idx < items.len() && b.is_hole(idx));
1830                    if is_hole {
1831                        Hit::Proto
1832                    } else if let Some(acc) = b.get_accessor(key) {
1833                        Hit::Getter(acc.get.clone())
1834                    } else if let ObjKind::Array(items) = &b.kind {
1835                        if idx < items.len() {
1836                            Hit::Elem(items[idx].clone())
1837                        } else {
1838                            Hit::Proto
1839                        }
1840                    } else {
1841                        Hit::Proto
1842                    }
1843                } else if let Some(acc) = b.get_accessor(key) {
1844                    Hit::Getter(acc.get.clone())
1845                } else if let Some(v) = b.props.get(key) {
1846                    Hit::Prop(v.clone())
1847                } else {
1848                    Hit::Proto
1849                }
1850            };
1851            return match hit {
1852                Hit::Getter(Some(g)) => it.call_value(&g, t.clone(), &[]),
1853                Hit::Getter(None) => Ok(Value::Undefined),
1854                Hit::Prop(v) | Hit::Elem(v) => Ok(v),
1855                Hit::Proto => {
1856                    let start = implicit_proto(it, o);
1857                    it.get_property_proto_chain(t, o, key, start)
1858                }
1859            };
1860        }
1861    }
1862    it.get_property(t, key)
1863}
1864
1865/// `this` の `length` を読む(array-like 汎用経路用。ECMA-262 ToLength 準拠)。
1866pub(crate) fn array_like_length(it: &mut Interp, t: &Value) -> usize {
1867    it.get_property(t, "length")
1868        .map(|l| to_length_u64(&l) as usize)
1869        .unwrap_or(0)
1870}
1871
1872/// 配列の「書き換えを拒む状態」の検査。【2026-11-19】
1873/// `Array.prototype` の書き込み系メソッド(push・pop・shift・unshift・splice・fill・copyWithin・reverse・sort)は、
1874/// 仕様上 `Set(O, P, V, true)` / `DeletePropertyOrThrow` を使うので、`Object.freeze` 済み・`length` が
1875/// 書き換え不可・拡張不可の配列では strict / sloppy を問わず TypeError になる
1876/// (ECMA-262 §23.1.3.* の各アルゴリズム、§7.3.4 Set の Throw=true、§7.3.10 DeletePropertyOrThrow、
1877/// §10.1.9.2 OrdinarySetWithOwnDescriptor、§10.4.2.4 ArraySetLength)。
1878/// 以前はフラグを見ずに中身を直接書き換えており、凍結した配列に `push` できていた。
1879/// 実装は「先に全部検査してから書く」形(仕様は途中まで書いてから投げる。途中経過の差は
1880/// 例外を捕まえた後の配列の中身にだけ出る)。何も掛かっていない配列は一度の借用で素通りする。
1881pub(crate) enum ArrOp {
1882    Push(usize),
1883    Pop,
1884    Shift,
1885    Unshift(usize),
1886    /// 先頭の位置・取り除く数・差し込む数
1887    Splice(usize, usize, usize),
1888    Fill(usize, usize),
1889    /// 書き込み先の先頭・個数
1890    CopyWithin(usize, usize),
1891    Reverse,
1892    Sort,
1893}
1894
1895struct ArrLock {
1896    frozen: bool,
1897    sealed: bool,
1898    non_ext: bool,
1899    len_ro: bool,
1900}
1901
1902fn arr_lock(o: &ObjRef) -> Option<ArrLock> {
1903    let b = o.borrow();
1904    if !matches!(b.kind, ObjKind::Array(_)) || b.props.contains_key("_ta_kind") {
1905        return None;
1906    }
1907    let frozen = b.is_frozen();
1908    let sealed = frozen || b.is_sealed();
1909    let non_ext = sealed || b.is_non_extensible();
1910    let len_ro = frozen || b.get_attr("length").is_some_and(|a| !a.writable);
1911    let elem_attrs = b.attrs().is_some_and(|m| m.keys().any(|k| crate::os_lib::ecma::value::parse_index(k).is_some()));
1912    if !(non_ext || len_ro || elem_attrs) {
1913        return None;
1914    }
1915    Some(ArrLock { frozen, sealed, non_ext, len_ro })
1916}
1917
1918/// 配列の添字 `idx` が書き換え不可か(凍結、または `defineProperty` で `writable:false` / setter無しアクセサ)。
1919fn arr_elem_ro(o: &ObjRef, lk: &ArrLock, idx: usize) -> bool {
1920    if lk.frozen {
1921        return true;
1922    }
1923    let b = o.borrow();
1924    let ks = idx.to_string();
1925    if let Some(acc) = b.get_accessor(&ks) {
1926        return acc.set.is_none();
1927    }
1928    b.get_attr(&ks).is_some_and(|a| !a.writable)
1929}
1930/// 配列の添字 `idx` が削除できないか(凍結・封印、または `configurable:false`)。
1931fn arr_elem_nc(o: &ObjRef, lk: &ArrLock, idx: usize) -> bool {
1932    lk.sealed || o.borrow().get_attr(&idx.to_string()).is_some_and(|a| !a.configurable)
1933}
1934
1935pub(crate) fn arr_check(it: &mut Interp, o: &ObjRef, op: ArrOp) -> Result<(), Value> {
1936    let Some(lk) = arr_lock(o) else { return Ok(()) };
1937    let len = match &o.borrow().kind {
1938        ObjKind::Array(items) => items.len(),
1939        _ => 0,
1940    };
1941    // 添字 idx への Set(既存なら書き換え可否、無ければ追加の可否)。
1942    let write = |it: &mut Interp, idx: usize| -> Result<(), Value> {
1943        if idx < len {
1944            if arr_elem_ro(o, &lk, idx) {
1945                return Err(it.type_error(alloc::format!(
1946                    "Cannot assign to read only property '{}' of object '[object Array]'",
1947                    idx
1948                )));
1949            }
1950        } else if lk.non_ext || lk.len_ro {
1951            return Err(it.type_error(alloc::format!("Cannot add property {}, object is not extensible", idx)));
1952        }
1953        Ok(())
1954    };
1955    let del = |it: &mut Interp, idx: usize| -> Result<(), Value> {
1956        if arr_elem_nc(o, &lk, idx) {
1957            return Err(it.type_error(alloc::format!("Cannot delete property '{}' of [object Array]", idx)));
1958        }
1959        Ok(())
1960    };
1961    let set_len = |it: &mut Interp| -> Result<(), Value> {
1962        if lk.len_ro {
1963            return Err(it.type_error("Cannot assign to read only property 'length' of object '[object Array]'"));
1964        }
1965        Ok(())
1966    };
1967    match op {
1968        ArrOp::Push(n) => {
1969            for i in 0..n {
1970                write(it, len + i)?;
1971            }
1972            set_len(it)
1973        }
1974        ArrOp::Pop => {
1975            if len > 0 {
1976                del(it, len - 1)?;
1977            }
1978            set_len(it)
1979        }
1980        ArrOp::Shift => {
1981            for i in 0..len.saturating_sub(1) {
1982                write(it, i)?;
1983            }
1984            if len > 0 {
1985                del(it, len - 1)?;
1986            }
1987            set_len(it)
1988        }
1989        ArrOp::Unshift(n) => {
1990            if n > 0 {
1991                for i in 0..len + n {
1992                    write(it, i)?;
1993                }
1994            }
1995            set_len(it)
1996        }
1997        ArrOp::Splice(start, dc, ic) => {
1998            if ic < dc {
1999                for i in start + ic..len - dc + ic {
2000                    write(it, i)?;
2001                }
2002                for i in len - dc + ic..len {
2003                    del(it, i)?;
2004                }
2005            } else if ic > dc {
2006                for i in start + ic..len - dc + ic {
2007                    write(it, i)?;
2008                }
2009            }
2010            for i in start..start + ic {
2011                write(it, i)?;
2012            }
2013            set_len(it)
2014        }
2015        ArrOp::Fill(start, end) => {
2016            for i in start..end {
2017                write(it, i)?;
2018            }
2019            Ok(())
2020        }
2021        ArrOp::CopyWithin(to, count) => {
2022            for i in to..to + count {
2023                write(it, i)?;
2024            }
2025            Ok(())
2026        }
2027        ArrOp::Reverse => {
2028            if len >= 2 {
2029                for i in 0..len {
2030                    write(it, i)?;
2031                }
2032            }
2033            Ok(())
2034        }
2035        ArrOp::Sort => {
2036            for i in 0..len {
2037                write(it, i)?;
2038            }
2039            Ok(())
2040        }
2041    }
2042}
2043
2044/// `push`/`pop`/`shift`/`unshift` は仕様上ジェネリックメソッドで、`length` +
2045/// 添字プロパティを持つだけの非配列 array-like オブジェクトへの `.call()` でも
2046/// 機能すべきだが、以前は `this_objref` で得た `ObjRef` が `ObjKind::Array` で
2047/// なければ何もせず `0`/`undefined` を返す静かな破壊バグだった(`slice`/`join`
2048/// 等の読み取り専用メソッドで修正済みの同型バグの、書き込み系での見落とし)。
2049/// 実配列は高速パス(`Vec` 直接操作)、それ以外は `length`+添字プロパティの
2050/// 読み書きにフォールバックする。
2051pub(crate) fn arr_push(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2052    let t = to_object_required(it, &t, "push")?;
2053    if let Some(o) = this_objref(&t) {
2054        if matches!(o.borrow().kind, ObjKind::Array(_)) && !o.borrow().props.contains_key("_ta_kind") {
2055            arr_check(it, &o, ArrOp::Push(a.len()))?;
2056            if let ObjKind::Array(items) = &mut o.borrow_mut().kind {
2057                for v in a {
2058                    items.push(v.clone());
2059                }
2060                return Ok(Value::Number(items.len() as f64));
2061            }
2062        }
2063    }
2064    let lv = it.get_property(&t, "length")?;
2065    let mut len = to_length_u64_checked(it, &lv)?;
2066    if len + (a.len() as u64) > MAX_SAFE_INT_U64 {
2067        return Err(it.type_error("Invalid array length"));
2068    }
2069    for v in a {
2070        put_prop_strict(it, &t, &len.to_string(), v.clone())?;
2071        len += 1;
2072    }
2073    put_prop_strict(it, &t, "length", Value::Number(len as f64))?;
2074    Ok(Value::Number(len as f64))
2075}
2076pub(crate) fn arr_pop(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
2077    let t = to_object_required(it, &t, "pop")?;
2078    if let Some(o) = this_objref(&t) {
2079        if matches!(o.borrow().kind, ObjKind::Array(_)) && !o.borrow().props.contains_key("_ta_kind") {
2080            arr_check(it, &o, ArrOp::Pop)?;
2081            let popped = if let ObjKind::Array(items) = &mut o.borrow_mut().kind {
2082                Some((items.pop().unwrap_or(Value::Undefined), items.len()))
2083            } else {
2084                None
2085            };
2086            if let Some((v, n)) = popped {
2087                move_holes(&o, |m| m.truncate(n));
2088                return Ok(v);
2089            }
2090        }
2091    }
2092    let lv = it.get_property(&t, "length")?;
2093    let len = to_length_u64_checked(it, &lv)?;
2094    if len == 0 {
2095        put_prop_strict(it, &t, "length", Value::Number(0.0))?;
2096        return Ok(Value::Undefined);
2097    }
2098    let new_len = len - 1;
2099    let index_str = new_len.to_string();
2100    let val = if has_array_elem(it, &t, &index_str)? {
2101        get_array_elem(it, &t, &index_str)?
2102    } else {
2103        Value::Undefined
2104    };
2105    del_prop_strict(it, &t, &index_str)?;
2106    put_prop_strict(it, &t, "length", Value::Number(new_len as f64))?;
2107    Ok(val)
2108}
2109pub(crate) fn arr_shift(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
2110    let t = to_object_required(it, &t, "shift")?;
2111    if let Some(o) = this_objref(&t) {
2112        if matches!(o.borrow().kind, ObjKind::Array(_)) && !o.borrow().props.contains_key("_ta_kind") {
2113            arr_check(it, &o, ArrOp::Shift)?;
2114            let shifted = if let ObjKind::Array(items) = &mut o.borrow_mut().kind {
2115                Some(if items.is_empty() { None } else { Some(items.remove(0)) })
2116            } else {
2117                None
2118            };
2119            match shifted {
2120                Some(None) => return Ok(Value::Undefined),
2121                Some(Some(v)) => {
2122                    move_holes(&o, |m| {
2123                        if !m.is_empty() {
2124                            m.remove(0);
2125                        }
2126                    });
2127                    return Ok(v);
2128                }
2129                None => {}
2130            }
2131        }
2132    }
2133    let lv = it.get_property(&t, "length")?;
2134    let len = to_length_u64_checked(it, &lv)?;
2135    if len == 0 {
2136        put_prop_strict(it, &t, "length", Value::Number(0.0))?;
2137        return Ok(Value::Undefined);
2138    }
2139    let first = if has_array_elem(it, &t, "0")? {
2140        get_array_elem(it, &t, "0")?
2141    } else {
2142        Value::Undefined
2143    };
2144    for k in 1..len {
2145        if it.tick() {
2146            return Err(Value::Undefined);
2147        }
2148        let from_key = k.to_string();
2149        let to_key = (k - 1).to_string();
2150        if has_array_elem(it, &t, &from_key)? {
2151            let v = get_array_elem(it, &t, &from_key)?;
2152            put_prop_strict(it, &t, &to_key, v)?;
2153        } else {
2154            del_prop_strict(it, &t, &to_key)?;
2155        }
2156    }
2157    del_prop_strict(it, &t, &(len - 1).to_string())?;
2158    put_prop_strict(it, &t, "length", Value::Number((len - 1) as f64))?;
2159    Ok(first)
2160}
2161pub(crate) fn arr_unshift(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2162    let t = to_object_required(it, &t, "unshift")?;
2163    if let Some(o) = this_objref(&t) {
2164        if matches!(o.borrow().kind, ObjKind::Array(_)) && !o.borrow().props.contains_key("_ta_kind") {
2165            arr_check(it, &o, ArrOp::Unshift(a.len()))?;
2166            let n = if let ObjKind::Array(items) = &mut o.borrow_mut().kind {
2167                for (i, v) in a.iter().enumerate() {
2168                    items.insert(i, v.clone());
2169                }
2170                Some(items.len())
2171            } else {
2172                None
2173            };
2174            if let Some(n) = n {
2175                move_holes(&o, |m| {
2176                    m.splice(0..0, core::iter::repeat_n(false, a.len()));
2177                });
2178                return Ok(Value::Number(n as f64));
2179            }
2180        }
2181    }
2182    let len_val = it.get_property(&t, "length")?;
2183    let len = to_length_u64_checked(it, &len_val)?;
2184    let shift = a.len() as u64;
2185    if shift > 0 {
2186        if len + shift > MAX_SAFE_INT_U64 {
2187            return Err(it.type_error("Invalid array length"));
2188        }
2189        // 仕様どおり末尾から先頭へ移動し、元の穴は削除する(HasProperty + Get/Set/DeletePropertyOrThrow)。
2190        for k in (1..=len).rev() {
2191            if it.tick() {
2192                return Err(Value::Undefined);
2193            }
2194            let from_key = (k - 1).to_string();
2195            let to_key = (k + shift - 1).to_string();
2196            if has_array_elem(it, &t, &from_key)? {
2197                let v = get_array_elem(it, &t, &from_key)?;
2198                put_prop_strict(it, &t, &to_key, v)?;
2199            } else {
2200                del_prop_strict(it, &t, &to_key)?;
2201            }
2202        }
2203        for (i, v) in a.iter().enumerate() {
2204            put_prop_strict(it, &t, &i.to_string(), v.clone())?;
2205        }
2206    }
2207    let new_len = len + shift;
2208    put_prop_strict(it, &t, "length", Value::Number(new_len as f64))?;
2209    Ok(Value::Number(new_len as f64))
2210}
2211/// `Array.prototype.slice` は仕様上ジェネリックメソッドだが、以前は `this_items`
2212/// (`ObjKind::Array` 以外は無条件で空 `Vec`)を直接使っていたため、
2213/// `[].slice.call(arrayLikeObj, ...)` のような array-like への適用が常に `[]` を
2214/// 返す静かな破壊バグだった(`join`/`concat` で修正済みの同型バグ)。
2215pub(crate) fn arr_slice(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2216    let t = to_object_required(it, &t, "slice")?;
2217    if is_dense_plain_array(&t) {
2218        let len = this_items(&t).len() as u64;
2219        let start = norm_index_u64(it.num_of(&arg(a, 0))?, len) as usize;
2220        let end = if matches!(arg(a, 1), Value::Undefined) {
2221            len as usize
2222        } else {
2223            norm_index_u64(it.num_of(&arg(a, 1))?, len) as usize
2224        };
2225        // 引数の強制変換中に配列の長さが変化している可能性があるため、ここで再取得する。
2226        let items = this_items(&t);
2227        let out = if start < end && start < items.len() {
2228            items[start..end.min(items.len())].to_vec()
2229        } else {
2230            Vec::new()
2231        };
2232        if is_typed_array(&t) {
2233            return Ok(same_kind_as(it, &t, out));
2234        }
2235        let a_obj = array_species_create(it, &t, out.len())?;
2236        return populate_array_species(it, &a_obj, out);
2237    }
2238
2239    // 汎用経路(array-like・Proxy・スパース配列): 巨大 length でも全展開せず対象範囲 [k..final] のみ読む。
2240    let len_val = it.get_property(&t, "length")?;
2241    let len = to_length_u64_checked(it, &len_val)?;
2242    let k = norm_index_u64(it.num_of(&arg(a, 0))?, len);
2243    let final_idx = if matches!(arg(a, 1), Value::Undefined) {
2244        len
2245    } else {
2246        norm_index_u64(it.num_of(&arg(a, 1))?, len)
2247    };
2248    let count = final_idx.saturating_sub(k);
2249    if count > crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN as u64 {
2250        return Err(it.range_error("Invalid array length"));
2251    }
2252    let count_usize = count as usize;
2253    let a_obj = array_species_create(it, &t, count_usize)?;
2254    let mut out = try_vec_with_capacity::<Value>(it, count_usize)?;
2255    let mut mask = try_vec_with_capacity::<bool>(it, count_usize)?;
2256    for idx in k..final_idx {
2257        let ks = idx.to_string();
2258        if has_array_elem(it, &t, &ks)? {
2259            out.push(get_array_elem(it, &t, &ks)?);
2260            mask.push(false);
2261        } else {
2262            out.push(Value::Undefined);
2263            mask.push(true);
2264        }
2265    }
2266    if is_typed_array(&t) {
2267        return Ok(same_kind_as(it, &t, out));
2268    }
2269    let r = populate_array_species(it, &a_obj, out)?;
2270    if mask.iter().any(|&h| h) {
2271        set_holes(&r, mask);
2272    }
2273    Ok(r)
2274}
2275/// `fromIndex`(第2引数)を正規化する。負の値は末尾からのオフセット、範囲外は
2276/// `len`(=以降の探索が即座に空になる)に丸める(`indexOf`/`includes` 共通)。
2277pub(crate) fn arr_from_index(a: &[Value], len: usize) -> usize {
2278    from_index_u64(a, len as u64).unwrap_or(len as u64) as usize
2279}
2280/// `Array.prototype.indexOf(searchElement, fromIndex)`。以前は `fromIndex`
2281/// (第2引数)を完全に無視し、常に先頭から探索していた。
2282/// `indexOf`/`includes`/`forEach`/`map`/`filter` 等は仕様上ジェネリックメソッドだが、
2283/// 以前は `this_items` を直接使っていたため array-like への `.call()` が常に
2284/// 「何も見つからない/反復しない」結果になる同型のバグが複数箇所にあった
2285/// (`join`/`slice`/`concat`/`forEach` で修正済みの続き)。
2286/// 第 2 引数(fromIndex)が Object のときだけ ToNumber して差し替える(例外を伝える。Object 以外は何もしない)。
2287/// 仕様の順序: `this` が undefined/null なら先に TypeError、`length` が 0 なら fromIndex は変換しない。
2288/// 整数の型付き配列(`ObjKind::Bytes`)は従来どおり変換しない(デタッチ検査が未対応のため)。
2289fn num_arg1<'a>(it: &mut Interp, t: &Value, a: &'a [Value], buf: &'a mut Vec<Value>) -> Result<&'a [Value], Value> {
2290    if let Some(v @ Value::Object(_)) = a.get(1) {
2291        match t {
2292            Value::Undefined | Value::Null => return Err(it.type_error("Array.prototype method called on null or undefined")),
2293            Value::Object(o) if matches!(o.borrow().kind, ObjKind::Bytes(_)) => return Ok(a),
2294            _ => {}
2295        }
2296        let len = if is_dense_plain_array(t) {
2297            with_array_items(t, |items| items.len() as u64).unwrap_or(0)
2298        } else {
2299            let lv = it.get_property(t, "length")?;
2300            to_length_u64_checked(it, &lv)?
2301        };
2302        if len == 0 {
2303            return Ok(a);
2304        }
2305        let n = it.num_of(v)?;
2306        *buf = a.to_vec();
2307        buf[1] = Value::Number(n);
2308        return Ok(&buf[..]);
2309    }
2310    Ok(a)
2311}
2312pub(crate) fn arr_index_of(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2313    if matches!(t, Value::Undefined | Value::Null) {
2314        return Err(it.type_error("Array.prototype method called on null or undefined"));
2315    }
2316    let mut a_buf = Vec::new();
2317    let a = num_arg1(it, &t, a, &mut a_buf)?;
2318    if let Some(r) = bytes_index_of(&t, a) {
2319        return Ok(Value::Number(r.map_or(-1.0, |i| i as f64)));
2320    }
2321    let target = arg(a, 0);
2322    if is_dense_plain_array(&t) {
2323        let found = with_array_items(&t, |items| {
2324            let from = arr_from_index(a, items.len());
2325            items
2326                .iter()
2327                .enumerate()
2328                .skip(from)
2329                .find(|(_, v)| v.strict_eq(&target))
2330                .map(|(i, _)| i)
2331        })
2332        .flatten();
2333        return Ok(Value::Number(found.map_or(-1.0, |i| i as f64)));
2334    }
2335    // 汎用経路(array-like・Proxy・スパース配列): Vec へ全展開せず直接添字アクセスで探索する。
2336    let len_val = it.get_property(&t, "length")?;
2337    let len = to_length_u64_checked(it, &len_val)?;
2338    let Some(start) = from_index_u64(a, len) else {
2339        return Ok(Value::Number(-1.0));
2340    };
2341    for k in start..len {
2342        let ks = k.to_string();
2343        if has_array_elem(it, &t, &ks)? {
2344            let v = get_array_elem(it, &t, &ks)?;
2345            if v.strict_eq(&target) {
2346                return Ok(Value::Number(k as f64));
2347            }
2348        }
2349    }
2350    Ok(Value::Number(-1.0))
2351}
2352/// `Array.prototype.includes` は仕様上 SameValueZero で比較する必要がある
2353/// (`===` と違って `NaN` 同士は等しいと判定される)。以前は `strict_eq`(`===`)を
2354/// 使っており、`[NaN].includes(NaN)` が `false` になるバグだった(`indexOf` が `===` を
2355/// 使うのは仕様どおり正しいので、そちらは変更していない)。
2356pub(crate) fn arr_includes(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2357    if matches!(t, Value::Undefined | Value::Null) {
2358        return Err(it.type_error("Array.prototype method called on null or undefined"));
2359    }
2360    let mut a_buf = Vec::new();
2361    let a = num_arg1(it, &t, a, &mut a_buf)?;
2362    // 整数の型付き配列に NaN は無いので `indexOf` と同じ結果になる(浮動小数は下の経路)。
2363    if !matches!(arg(a, 0), Value::Number(n) if n.is_nan()) {
2364        if let Some(r) = bytes_index_of(&t, a) {
2365            return Ok(Value::Bool(r.is_some()));
2366        }
2367    }
2368    let target = arg(a, 0);
2369    if is_dense_plain_array(&t) {
2370        let found = with_array_items(&t, |items| {
2371            let from = arr_from_index(a, items.len());
2372            items.iter().skip(from).any(|v| same_value_zero(v, &target))
2373        })
2374        .unwrap_or(false);
2375        return Ok(Value::Bool(found));
2376    }
2377    // 汎用経路(array-like・Proxy・スパース配列): Vec へ全展開せず直接添字アクセスで探索する。
2378    let len_val = it.get_property(&t, "length")?;
2379    let len = to_length_u64_checked(it, &len_val)?;
2380    let Some(start) = from_index_u64(a, len) else {
2381        return Ok(Value::Bool(false));
2382    };
2383    for k in start..len {
2384        let v = get_array_elem(it, &t, &k.to_string())?;
2385        if same_value_zero(&v, &target) {
2386            return Ok(Value::Bool(true));
2387        }
2388    }
2389    Ok(Value::Bool(false))
2390}
2391/// `Array.prototype.join` は仕様上ジェネリックメソッド(`this` の内部 `[[Class]]` を
2392/// 見ず `length` + 添字プロパティだけを見る)だが、以前は `this_items`(`ObjKind::Array`
2393/// 以外は無条件で空 `Vec`)を直接使っていたため、
2394/// `Array.prototype.join.call({0:'a',1:'b',length:2}, '-')` のような array-like への
2395/// 適用が常に `""` を返す静かな破壊バグだった。
2396pub(crate) fn arr_join(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2397    if matches!(t, Value::Undefined | Value::Null) {
2398        return Err(it.type_error("Array.prototype method called on null or undefined"));
2399    }
2400    let is_array = matches!(&t, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Array(_) | ObjKind::Bytes(_)));
2401    let items = if is_array {
2402        this_items(&t)
2403    } else {
2404        array_like_items(it, &t)
2405    };
2406    let sep = if matches!(arg(a, 0), Value::Undefined) {
2407        String::from(",")
2408    } else {
2409        it.to_string_value(arg(a, 0))?
2410    };
2411    // 【2026-11-17】要素の普通のオブジェクト・関数は利用者定義の toString を呼ぶ(仕様の ToString)。
2412    // 以前は組み込みの変換だけで、`[{toString(){return "T"}}].join()` が "[object Object]" だった。
2413    // 入れ子の配列は組み込みの変換のまま(循環する配列で無限に再帰しないため)。
2414    // 入れ子の配列も同じ規則でつなぐ。循環する配列は V8 と同じく "" にする(`join_stack`)。
2415    let self_id = match &t {
2416        Value::Object(o) => Rc::as_ptr(o) as *const () as usize,
2417        _ => 0,
2418    };
2419    if self_id != 0 && it.join_stack.contains(&self_id) {
2420        return Ok(Value::str(""));
2421    }
2422    let needs_calls = items.iter().any(|v| {
2423        matches!(v, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Plain | ObjKind::Function(_) | ObjKind::Array(_)))
2424    });
2425    if !needs_calls {
2426        let parts: Vec<String> = items
2427            .iter()
2428            .map(|v| match v {
2429                Value::Undefined | Value::Null => String::new(),
2430                _ => v.to_js_string(),
2431            })
2432            .collect();
2433        return Ok(Value::str(parts.join(&sep)));
2434    }
2435    it.join_stack.push(self_id);
2436    let mut parts: Vec<String> = Vec::with_capacity(items.len());
2437    let mut res = Ok(());
2438    for v in items.iter() {
2439        let part = match v {
2440            Value::Undefined | Value::Null => Ok(String::new()),
2441            Value::Object(o)
2442                if matches!(o.borrow().kind, ObjKind::Plain | ObjKind::Function(_) | ObjKind::HostRef(_)) =>
2443            {
2444                it.to_string_value(v.clone())
2445            }
2446            Value::Object(o) if matches!(o.borrow().kind, ObjKind::Array(_)) && o.borrow().proto.is_none() => {
2447                arr_join(it, v.clone(), &[]).map(|r| r.to_js_string())
2448            }
2449            _ => Ok(v.to_js_string()),
2450        };
2451        match part {
2452            Ok(p) => parts.push(p),
2453            Err(e) => {
2454                res = Err(e);
2455                break;
2456            }
2457        }
2458    }
2459    it.join_stack.pop();
2460    res?;
2461    Ok(Value::str(parts.join(&sep)))
2462}
2463/// `this` が実配列(`ObjKind::Array`)かどうか。`join`/`slice`/`concat` に続き、
2464/// `forEach`/`map`/`filter`/`indexOf`/`includes` 等の仕様上ジェネリックなメソッドで
2465/// `this_items`(非配列は無条件で空 `Vec`)から `array_like_items`
2466/// (`length`+添字プロパティを読む汎用フォールバック)への切り替え判定に使う共通ヘルパ。
2467/// 本物の配列(`ObjKind::Array`、Proxy は外す)の要素を写さずに見る。JS を呼ばない処理(比較・添字)だけに使う。
2468/// 【2026-11-04】`at`・`indexOf`・`includes`・`lastIndexOf` が呼ぶたびに配列全体を写していた(`a.at(i)` の繰り返しが O(n²))。
2469pub(crate) fn with_array_items<R>(t: &Value, f: impl FnOnce(&[Value]) -> R) -> Option<R> {
2470    let Value::Object(o) = t else { return None };
2471    let o = unwrap_proxy_target(o);
2472    let b = o.borrow();
2473    match &b.kind {
2474        ObjKind::Array(items) => Some(f(items.as_slice())),
2475        _ => None,
2476    }
2477}
2478/// 反復する配列の見え方。本物の配列は写さず、長さだけ最初に決めて要素は訪れたときに読む(仕様どおり。
2479/// 途中で縮んで無くなった要素は飛ばす)。それ以外(array-like・型付き配列)は従来どおり写す。
2480/// 【2026-11-04】`forEach`/`map`/`filter` が呼ぶたびに配列全体を写しており、確保と `memcpy` の呼び出し元の上位だった。
2481pub(crate) enum ArrView {
2482    Live(ObjRef, usize),
2483    Owned(Vec<Value>),
2484}
2485
2486impl ArrView {
2487    pub(crate) fn len(&self) -> usize {
2488        match self {
2489            ArrView::Live(_, n) => *n,
2490            ArrView::Owned(v) => v.len(),
2491        }
2492    }
2493    pub(crate) fn get(&self, i: usize) -> Option<Value> {
2494        match self {
2495            ArrView::Live(o, _) => match &o.borrow().kind {
2496                ObjKind::Array(items) => items.get(i).cloned(),
2497                _ => None,
2498            },
2499            ArrView::Owned(v) => v.get(i).cloned(),
2500        }
2501    }
2502}
2503
2504pub(crate) fn array_view(it: &mut Interp, t: &Value) -> ArrView {
2505    if let Value::Object(o) = t {
2506        let o = unwrap_proxy_target(o);
2507        let n = match &o.borrow().kind {
2508            ObjKind::Array(items) => Some(items.len()),
2509            _ => None,
2510        };
2511        if let Some(n) = n {
2512            return ArrView::Live(o, n);
2513        }
2514    }
2515    ArrView::Owned(generic_array_items(it, t))
2516}
2517pub(crate) fn is_real_array(t: &Value) -> bool {
2518    matches!(t, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Array(_) | ObjKind::Bytes(_)))
2519}
2520/// `this_items` と `array_like_items` を上記の判定で使い分ける便宜関数。
2521/// `t` が配列なら穴の一覧(穴が無ければ空)。反復系のメソッドは穴を飛ばす。
2522pub(crate) fn holes_of(t: &Value) -> Vec<bool> {
2523    match t {
2524        Value::Object(o) => o.borrow().hole_mask(),
2525        _ => Vec::new(),
2526    }
2527}
2528fn is_hole_at(holes: &[bool], i: usize) -> bool {
2529    holes.get(i).copied().unwrap_or(false)
2530}
2531/// 配列 `v` に穴の印を付ける(穴が 1 つも無ければ付けない)。
2532pub(crate) fn set_holes(v: &Value, mask: Vec<bool>) {
2533    if let Value::Object(o) = v {
2534        let mut b = o.borrow_mut();
2535        if matches!(b.kind, ObjKind::Array(_)) {
2536            b.set_holes(if mask.iter().any(|&h| h) { Some(alloc::boxed::Box::new(mask)) } else { None });
2537        }
2538    }
2539}
2540/// 配列 `t` の要素 `items` から穴を除く(`flat`・`flatMap` は穴を飛ばす。2026-11-16)。
2541pub(crate) fn without_holes(t: &Value, items: Vec<Value>) -> Vec<Value> {
2542    let h = holes_of(t);
2543    if h.is_empty() {
2544        return items;
2545    }
2546    items.into_iter().enumerate().filter(|(i, _)| !is_hole_at(&h, *i)).map(|(_, v)| v).collect()
2547}
2548/// 添字がずれる操作の前に穴の印を捨てる。
2549fn drop_holes(o: &ObjRef) {
2550    o.borrow_mut().clear_holes();
2551}
2552/// 配列の穴の印を `f` で書き換える(穴が無い配列では何もしない)。添字がずれる操作で、要素と同じように
2553/// 印も動かすのに使う(2026-11-16。以前は `drop_holes` で捨てていて、穴が undefined の要素に変わっていた)。
2554fn move_holes(o: &ObjRef, f: impl FnOnce(&mut Vec<bool>)) {
2555    // 要素を動かした後で呼ぶので、要素の値と照らす `hole_mask` ではなく印そのものを使う。
2556    let Some(mut mask) = o.borrow().holes().map(<[bool]>::to_vec) else { return };
2557    f(&mut mask);
2558    set_holes(&Value::Object(o.clone()), mask);
2559}
2560/// 型付き配列の `indexOf`。`this` が型付き配列でなければ `None`。
2561///
2562/// 【2026-11-02】型付き配列を array-like として 1 要素ずつ「添字の文字列化 → プロパティ参照」で読み、
2563/// 全要素を `Vec<Value>` へ展開していた。YouTube の 2 本目の動画の処理が動画データに対する
2564/// `indexOf` で何分も止まり、次の動画へ進めなかった。
2565fn bytes_index_of(t: &Value, a: &[Value]) -> Option<Option<usize>> {
2566    let Value::Object(o) = t else { return None };
2567    let b = o.borrow();
2568    let ObjKind::Bytes(st) = &b.kind else { return None };
2569    let from = arr_from_index(a, st.effective_len());
2570    let Value::Number(n) = arg(a, 0) else { return Some(None) };
2571    let rk = st.raw_kind();
2572    if rk <= 2 {
2573        // 1 バイトの要素はバイト列を直接探す。
2574        let v = n as i64;
2575        let want = match rk {
2576            1 if (-128..=127).contains(&v) && v as f64 == n => (v as i8) as u8,
2577            0 | 2 if (0..=255).contains(&v) && v as f64 == n => v as u8,
2578            _ => return Some(None),
2579        };
2580        let buf = st.buf.borrow();
2581        let len = st.effective_len();
2582        let s = buf.get(st.off + from.min(len)..st.off + len)?;
2583        return Some(s.iter().position(|x| *x == want).map(|p| p + from));
2584    }
2585    Some((from..st.effective_len()).find(|i| st.get(*i) == Some(n)))
2586}
2587
2588pub(crate) fn generic_array_items(it: &mut Interp, t: &Value) -> Vec<Value> {
2589    if is_real_array(t) || matches!(t, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Bytes(_))) {
2590        this_items(t)
2591    } else {
2592        array_like_items(it, t)
2593    }
2594}
2595/// 配列でない array-like オブジェクト(`length` + 添字プロパティ)を `Vec<Value>` に
2596/// 展開する。巨大長での OOM を防ぐため `MAX_DENSE_ARRAY_LEN` を上限とする。
2597pub(crate) fn array_like_items(it: &mut Interp, v: &Value) -> Vec<Value> {
2598    let len = it
2599        .get_property(v, "length")
2600        .map(|l| to_length_u64(&l))
2601        .unwrap_or(0);
2602    let len = (len as usize).min(crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN);
2603    let mut out = Vec::with_capacity(len.min(4096));
2604    for i in 0..len {
2605        out.push(
2606            it.get_property(v, &i.to_string())
2607                .unwrap_or(Value::Undefined),
2608        );
2609    }
2610    out
2611}
2612
2613/// `Array.prototype.concat` は仕様上 `Symbol.isConcatSpreadable` を尊重すべきだが、
2614/// 以前は単に `ObjKind::Array` かどうかだけで展開の有無を決めており、
2615/// `arr[Symbol.isConcatSpreadable] = false` な配列も無条件に展開され、逆に
2616/// `Symbol.isConcatSpreadable = true` を明示した非配列 array-like オブジェクトは
2617/// 展開されず単一要素として push されてしまっていた。
2618/// 結果長が `2^53 - 1` を超える場合は仕様どおり `TypeError` を投げる。
2619pub(crate) fn concat_push(
2620    it: &mut Interp,
2621    v: &Value,
2622    items: &mut Vec<Value>,
2623    mask: &mut Vec<bool>,
2624) -> Result<(), Value> {
2625    match v {
2626        Value::Object(_) => {
2627            let flag = it.get_property(v, "Symbol(Symbol.isConcatSpreadable)")?;
2628            let is_array = is_js_array(v);
2629            let spreadable = if matches!(flag, Value::Undefined) {
2630                is_array
2631            } else {
2632                flag.truthy()
2633            };
2634            if !spreadable {
2635                if (items.len() as u64) >= MAX_SAFE_INT_U64 {
2636                    return Err(it.type_error("Invalid array length"));
2637                }
2638                items.push(v.clone());
2639                mask.push(false);
2640            } else if is_dense_plain_array(v) {
2641                let other = this_items(v);
2642                let len = other.len() as u64;
2643                if len > MAX_SAFE_INT_U64 - (items.len() as u64) {
2644                    return Err(it.type_error("Invalid array length"));
2645                }
2646                if items.len() + other.len() > crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN
2647                    || items.try_reserve(other.len()).is_err()
2648                {
2649                    return Err(it.range_error("Invalid array length"));
2650                }
2651                let added = other.len();
2652                items.extend(other);
2653                mask.extend(core::iter::repeat_n(false, added));
2654            } else {
2655                let len_val = it.get_property(v, "length")?;
2656                let len = to_length_u64_checked(it, &len_val)?;
2657                if len > MAX_SAFE_INT_U64 - (items.len() as u64) {
2658                    return Err(it.type_error("Invalid array length"));
2659                }
2660                for k in 0..len {
2661                    if items.len() >= crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN {
2662                        return Err(it.range_error("Invalid array length"));
2663                    }
2664                    let ks = k.to_string();
2665                    if has_array_elem(it, v, &ks)? {
2666                        let sub = get_array_elem(it, v, &ks)?;
2667                        items.push(sub);
2668                        mask.push(false);
2669                    } else {
2670                        items.push(Value::Undefined);
2671                        mask.push(true);
2672                    }
2673                }
2674            }
2675        }
2676        other => {
2677            if (items.len() as u64) >= MAX_SAFE_INT_U64 {
2678                return Err(it.type_error("Invalid array length"));
2679            }
2680            items.push(other.clone());
2681            mask.push(false);
2682        }
2683    }
2684    Ok(())
2685}
2686pub(crate) fn arr_concat(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2687    let obj = to_object_required(it, &t, "concat")?;
2688    let mut items = Vec::new();
2689    let mut mask: Vec<bool> = Vec::new();
2690    for v in core::iter::once(&obj).chain(a.iter()) {
2691        concat_push(it, v, &mut items, &mut mask)?;
2692    }
2693    let a_obj = array_species_create(it, &obj, 0)?;
2694    let r = populate_array_species(it, &a_obj, items)?;
2695    set_holes(&r, mask);
2696    Ok(r)
2697}
2698pub(crate) fn arr_reverse(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
2699    let t = to_object_required(it, &t, "reverse")?;
2700    if let Some(o) = this_objref(&t) {
2701        let is_plain_arr = {
2702            let b = o.borrow();
2703            matches!(b.kind, ObjKind::Array(_)) && !b.props.contains_key("_ta_kind") && !b.has_any_accessor()
2704        };
2705        if is_plain_arr {
2706            arr_check(it, &o, ArrOp::Reverse)?;
2707            let n = match &o.borrow().kind {
2708                ObjKind::Array(items) => items.len(),
2709                _ => 0,
2710            };
2711            move_holes(&o, |m| {
2712                m.resize(n, false);
2713                m.reverse();
2714            });
2715            if let ObjKind::Array(items) = &mut o.borrow_mut().kind {
2716                items.reverse();
2717            }
2718            return Ok(t);
2719        }
2720        if matches!(o.borrow().kind, ObjKind::Bytes(_)) {
2721            let mut b = o.borrow_mut();
2722            if let ObjKind::Bytes(st) = &mut b.kind {
2723                let mut vals = st.values();
2724                vals.reverse();
2725                for (i, v) in vals.into_iter().enumerate() {
2726                    st.set(i, v.to_number());
2727                }
2728            }
2729            return Ok(t);
2730        }
2731    }
2732    let lv = it.get_property(&t, "length")?;
2733    let len = to_length_u64_checked(it, &lv)?;
2734    let middle = len / 2;
2735    for lower in 0..middle {
2736        if it.tick() {
2737            return Err(Value::Undefined);
2738        }
2739        let upper = len - lower - 1;
2740        let lower_p = lower.to_string();
2741        let upper_p = upper.to_string();
2742        let lower_exists = has_array_elem(it, &t, &lower_p)?;
2743        let lower_val = if lower_exists {
2744            Some(get_array_elem(it, &t, &lower_p)?)
2745        } else {
2746            None
2747        };
2748        let upper_exists = has_array_elem(it, &t, &upper_p)?;
2749        let upper_val = if upper_exists {
2750            Some(get_array_elem(it, &t, &upper_p)?)
2751        } else {
2752            None
2753        };
2754        match (lower_val, upper_val) {
2755            (Some(lv_val), Some(uv_val)) => {
2756                put_prop_strict(it, &t, &lower_p, uv_val)?;
2757                put_prop_strict(it, &t, &upper_p, lv_val)?;
2758            }
2759            (None, Some(uv_val)) => {
2760                put_prop_strict(it, &t, &lower_p, uv_val)?;
2761                del_prop_strict(it, &t, &upper_p)?;
2762            }
2763            (Some(lv_val), None) => {
2764                del_prop_strict(it, &t, &lower_p)?;
2765                put_prop_strict(it, &t, &upper_p, lv_val)?;
2766            }
2767            (None, None) => {}
2768        }
2769    }
2770    Ok(t)
2771}
2772pub(crate) fn arr_to_string(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
2773    if matches!(t, Value::Undefined | Value::Null) {
2774        return Err(it.type_error("Array.prototype method called on null or undefined"));
2775    }
2776    Ok(Value::str(t.to_js_string()))
2777}
2778/// `Array.prototype.toLocaleString()`(ES3)が丸ごと欠落していた。各要素の
2779/// `toLocaleString()` を呼び出し `,` で連結する(`Intl` 非搭載のためロケール依存の書式化は
2780/// 行わず、要素が `toLocaleString` を持たなければ通常の文字列化にフォールバックする簡略実装。
2781/// `Date.prototype.toLocaleString` 等、要素側の実装があればそちらが優先される)。
2782pub(crate) fn obj_to_locale_string(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
2783    let to_str = it.get_property(&t, "toString")?;
2784    if !matches!(&to_str, Value::Object(f) if f.borrow().is_callable()) {
2785        return Err(it.type_error("toString is not a function"));
2786    }
2787    it.call_value(&to_str, t, &[])
2788}
2789
2790pub(crate) fn arr_to_locale_string(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2791    let t = to_object_required(it, &t, "toLocaleString")?;
2792    let lv = it.get_property(&t, "length")?;
2793    let len = to_length_u64_checked(it, &lv)?;
2794    if len > crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN as u64 {
2795        return Err(it.range_error("Invalid array length"));
2796    }
2797    let mut parts = Vec::with_capacity(len as usize);
2798    for k in 0..len {
2799        let v = get_array_elem(it, &t, &k.to_string())?;
2800        if matches!(v, Value::Undefined | Value::Null) {
2801            parts.push(String::new());
2802            continue;
2803        }
2804        let method = it.get_property(&v, "toLocaleString")?;
2805        if !matches!(&method, Value::Object(f) if f.borrow().is_callable()) {
2806            return Err(it.type_error("toLocaleString is not a function"));
2807        }
2808        let res = it.call_value(&method, v, a)?;
2809        parts.push(it.to_string_value(res)?);
2810    }
2811    Ok(Value::str(parts.join(",")))
2812}
2813/// 高階配列メソッドのコールバックは第2引数 `thisArg` を受け付ける(`map`/`filter`/
2814/// `forEach`/`find` 系すべてに共通の仕様だが、以前はどれも `Value::Undefined` を
2815/// 決め打ちしており `thisArg` が完全に無視されていた)。
2816pub(crate) fn arr_map_legacy(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2817    if matches!(t, Value::Undefined | Value::Null) {
2818        return Err(it.type_error("Array.prototype method called on null or undefined"));
2819    }
2820    let items = array_view(it, &t);
2821    let f = arg(a, 0);
2822    let this_arg = arg(a, 1);
2823    let holes = holes_of(&t);
2824    let mut out = Vec::with_capacity(items.len());
2825    for i in 0..items.len() {
2826        let v = match items.get(i) {
2827            Some(v) if !is_hole_at(&holes, i) => v,
2828            _ => {
2829                out.push(Value::Undefined);
2830                continue;
2831            }
2832        };
2833        let r = it.call_value(
2834            &f,
2835            this_arg.clone(),
2836            &[v.clone(), Value::Number(i as f64), t.clone()],
2837        )?;
2838        out.push(r);
2839    }
2840    if is_typed_array(&t) {
2841        return Ok(same_kind_as(it, &t, out));
2842    }
2843    let a_obj = array_species_create(it, &t, items.len())?;
2844    let r = populate_array_species(it, &a_obj, out)?;
2845    set_holes(&r, holes);
2846    Ok(r)
2847}
2848pub(crate) fn arr_filter_legacy(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2849    if matches!(t, Value::Undefined | Value::Null) {
2850        return Err(it.type_error("Array.prototype method called on null or undefined"));
2851    }
2852    let items = array_view(it, &t);
2853    let f = arg(a, 0);
2854    let this_arg = arg(a, 1);
2855    let mut out = Vec::new();
2856    let holes = holes_of(&t);
2857    for i in 0..items.len() {
2858        let v = match items.get(i) {
2859            Some(v) if !is_hole_at(&holes, i) => v,
2860            _ => continue,
2861        };
2862        if it
2863            .call_value(
2864                &f,
2865                this_arg.clone(),
2866                &[v.clone(), Value::Number(i as f64), t.clone()],
2867            )?
2868            .truthy()
2869        {
2870            out.push(v.clone());
2871        }
2872    }
2873    if is_typed_array(&t) {
2874        return Ok(same_kind_as(it, &t, out));
2875    }
2876    let a_obj = array_species_create(it, &t, 0)?;
2877    populate_array_species(it, &a_obj, out)
2878}
2879/// `Array.prototype.forEach` は仕様上ジェネリックメソッドだが、以前は `this_items`
2880/// (`ObjKind::Array` 以外は無条件で空 `Vec`)を直接使っていたため、`.call(arrayLikeObj,
2881/// fn)`(`arguments`/`NodeList` 等への定番イディオム)が何も反復しない静かな破壊
2882/// バグだった(`join`/`slice`/`concat` で修正済みの同型バグ)。
2883pub(crate) fn arr_for_each_legacy(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2884    if matches!(t, Value::Undefined | Value::Null) {
2885        return Err(it.type_error("Array.prototype method called on null or undefined"));
2886    }
2887    let items = array_view(it, &t);
2888    let f = arg(a, 0);
2889    let this_arg = arg(a, 1);
2890    let holes = holes_of(&t);
2891    for i in 0..items.len() {
2892        let v = match items.get(i) {
2893            Some(v) if !is_hole_at(&holes, i) => v,
2894            _ => continue,
2895        };
2896        it.call_value(
2897            &f,
2898            this_arg.clone(),
2899            &[v.clone(), Value::Number(i as f64), t.clone()],
2900        )?;
2901    }
2902    Ok(Value::Undefined)
2903}
2904/// `reduce`/`find`/`findIndex`/`some`/`every` にも `forEach`/`map`/`filter`/`indexOf`/
2905/// `includes` と同型のジェネリックメソッド未対応バグがあった(`this_items` を直接
2906/// 使っており array-like への `.call()` が常に「何もしない/見つからない」になっていた)。
2907pub(crate) fn arr_reduce_legacy(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2908    if matches!(t, Value::Undefined | Value::Null) {
2909        return Err(it.type_error("Array.prototype method called on null or undefined"));
2910    }
2911    let items = generic_array_items(it, &t);
2912    let f = arg(a, 0);
2913    let holes = holes_of(&t);
2914    let mut idx = 0;
2915    let mut acc = if a.len() >= 2 {
2916        arg(a, 1)
2917    } else {
2918        while is_hole_at(&holes, idx) {
2919            idx += 1;
2920        }
2921        if idx >= items.len() {
2922            return Err(it.type_error("Reduce of empty array with no initial value"));
2923        }
2924        idx += 1;
2925        items[idx - 1].clone()
2926    };
2927    while idx < items.len() {
2928        if is_hole_at(&holes, idx) {
2929            idx += 1;
2930            continue;
2931        }
2932        acc = it.call_value(
2933            &f,
2934            Value::Undefined,
2935            &[
2936                acc,
2937                items[idx].clone(),
2938                Value::Number(idx as f64),
2939                t.clone(),
2940            ],
2941        )?;
2942        idx += 1;
2943    }
2944    Ok(acc)
2945}
2946/// 添字 `k` の要素の読み出し(仕様の `Get(O, k)`)。素の密な配列は文字列化せず直接読む。
2947fn elem_at(it: &mut Interp, t: &Value, k: u64) -> Result<Value, Value> {
2948    if let Value::Object(o) = t {
2949        let b = o.borrow();
2950        if let ObjKind::Array(items) = &b.kind {
2951            let i = k as usize;
2952            if i < items.len() && !b.is_hole(i) && !b.has_any_accessor() {
2953                return Ok(items[i].clone());
2954            }
2955        }
2956    }
2957    get_array_elem(it, t, &k.to_string())
2958}
2959
2960/// `find` / `findIndex` / `findLast` / `findLastIndex` の共通実装(ECMA-262 §23.1.3.9 ほか)。
2961/// 長さは最初に 1 度だけ読み、要素は毎回 `Get` する(走査中の変更・getter・穴を仕様どおり見る)。
2962fn find_core(it: &mut Interp, t: Value, a: &[Value], rev: bool, want_index: bool) -> Result<Value, Value> {
2963    if matches!(t, Value::Undefined | Value::Null) {
2964        return Err(it.type_error("Array.prototype method called on null or undefined"));
2965    }
2966    let len_val = it.get_property(&t, "length")?;
2967    let len = to_length_u64_checked(it, &len_val)?;
2968    let f = arg(a, 0);
2969    if !matches!(&f, Value::Object(fo) if fo.borrow().is_callable()) {
2970        return Err(it.type_error(alloc::format!("{} is not a function", describe_for_error(&f))));
2971    }
2972    let this_arg = arg(a, 1);
2973    let mut n = 0u64;
2974    while n < len {
2975        let k = if rev { len - 1 - n } else { n };
2976        n += 1;
2977        let v = elem_at(it, &t, k)?;
2978        if it.call_value(&f, this_arg.clone(), &[v.clone(), Value::Number(k as f64), t.clone()])?.truthy() {
2979            return Ok(if want_index { Value::Number(k as f64) } else { v });
2980        }
2981    }
2982    Ok(if want_index { Value::Number(-1.0) } else { Value::Undefined })
2983}
2984pub(crate) fn arr_find(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2985    find_core(it, t, a, false, false)
2986}
2987pub(crate) fn arr_find_index(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2988    find_core(it, t, a, false, true)
2989}
2990pub(crate) fn arr_some_legacy(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
2991    if matches!(t, Value::Undefined | Value::Null) {
2992        return Err(it.type_error("Array.prototype method called on null or undefined"));
2993    }
2994    let items = generic_array_items(it, &t);
2995    let f = arg(a, 0);
2996    let this_arg = arg(a, 1);
2997    let holes = holes_of(&t);
2998    for (i, v) in items.iter().enumerate() {
2999        if is_hole_at(&holes, i) {
3000            continue;
3001        }
3002        if it
3003            .call_value(
3004                &f,
3005                this_arg.clone(),
3006                &[v.clone(), Value::Number(i as f64), t.clone()],
3007            )?
3008            .truthy()
3009        {
3010            return Ok(Value::Bool(true));
3011        }
3012    }
3013    Ok(Value::Bool(false))
3014}
3015pub(crate) fn arr_every_legacy(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3016    if matches!(t, Value::Undefined | Value::Null) {
3017        return Err(it.type_error("Array.prototype method called on null or undefined"));
3018    }
3019    let items = generic_array_items(it, &t);
3020    let f = arg(a, 0);
3021    let this_arg = arg(a, 1);
3022    let holes = holes_of(&t);
3023    for (i, v) in items.iter().enumerate() {
3024        if is_hole_at(&holes, i) {
3025            continue;
3026        }
3027        if !it
3028            .call_value(
3029                &f,
3030                this_arg.clone(),
3031                &[v.clone(), Value::Number(i as f64), t.clone()],
3032            )?
3033            .truthy()
3034        {
3035            return Ok(Value::Bool(false));
3036        }
3037    }
3038    Ok(Value::Bool(true))
3039}
3040// ===== 仕様どおりの高階メソッド(forEach・map・filter・some・every・reduce)=====
3041// 【2026-11-20】以前は要素を先に写して(穴・アクセサ・原型の添字・途中の変更を無視)反復し、コールバックが
3042// 関数かの検査もなかった。仕様(ToObject → LengthOfArrayLike → IsCallable → HasProperty/Get を 1 つずつ)どおりにする。
3043// 型付き配列(`ObjKind::Bytes`)は従来の実装のまま。
3044
3045fn hof_is_bytes(t: &Value) -> bool {
3046    matches!(t, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Bytes(_)))
3047}
3048
3049/// 共通の前段: ToObject(this)・長さ・コールバックの検査(長さは 2^53-1 までそのまま)。
3050fn hof_begin_obj_raw(it: &mut Interp, t: &Value, cb: &Value, name: &str) -> Result<(Value, u64), Value> {
3051    let obj = to_object_required(it, t, name)?;
3052    let lv = it.get_property(&obj, "length")?;
3053    let n = it.num_of(&lv)?;
3054    let len = to_length_u64(&Value::Number(n));
3055    if !matches!(cb, Value::Object(f) if f.borrow().is_callable()) {
3056        return Err(it.type_error(alloc::format!("{} is not a function", describe_for_error(cb))));
3057    }
3058    Ok((obj, len))
3059}
3060
3061/// 共通の前段: ToObject(this)・長さ・コールバックの検査。
3062fn hof_begin_obj(it: &mut Interp, t: &Value, cb: &Value, name: &str) -> Result<(Value, u64), Value> {
3063    let (obj, len) = hof_begin_obj_raw(it, t, cb, name)?;
3064    Ok((obj, len.min(crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN as u64)))
3065}
3066
3067fn describe_for_error(v: &Value) -> String {
3068    match v {
3069        Value::Object(_) => String::from("#<Object>"),
3070        Value::Str(s) => alloc::format!("\"{}\"", s),
3071        other => other.to_js_string(),
3072    }
3073}
3074
3075/// 添字 `k` の要素(HasProperty が偽なら `None`)。穴もアクセサも無い実配列は直接読む。
3076#[inline]
3077fn hof_elem(it: &mut Interp, o: &Value, k: u64) -> Result<Option<Value>, Value> {
3078    if let Value::Object(ob) = o {
3079        let b = ob.borrow();
3080        if let ObjKind::Array(items) = &b.kind {
3081            let i = k as usize;
3082            if i < items.len() && !b.is_hole(i) && !b.has_rare_props() {
3083                return Ok(Some(items[i].clone()));
3084            }
3085        }
3086    }
3087    let key = k.to_string();
3088    if has_array_elem(it, o, &key)? {
3089        Ok(Some(get_array_elem(it, o, &key)?))
3090    } else {
3091        Ok(None)
3092    }
3093}
3094
3095pub(crate) fn arr_for_each_g(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3096    if hof_is_bytes(&t) {
3097        return arr_for_each_legacy(it, t, a);
3098    }
3099    let f = arg(a, 0);
3100    let (t, len) = hof_begin_obj(it, &t, &f, "forEach")?;
3101    let this_arg = arg(a, 1);
3102    for k in 0..len {
3103        if let Some(v) = hof_elem(it, &t, k)? {
3104            it.call_value(&f, this_arg.clone(), &[v, Value::Number(k as f64), t.clone()])?;
3105        }
3106    }
3107    Ok(Value::Undefined)
3108}
3109
3110pub(crate) fn arr_some_g(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3111    if hof_is_bytes(&t) {
3112        return arr_some_legacy(it, t, a);
3113    }
3114    let f = arg(a, 0);
3115    let (t, len) = hof_begin_obj(it, &t, &f, "some")?;
3116    let this_arg = arg(a, 1);
3117    for k in 0..len {
3118        if let Some(v) = hof_elem(it, &t, k)? {
3119            if it.call_value(&f, this_arg.clone(), &[v, Value::Number(k as f64), t.clone()])?.truthy() {
3120                return Ok(Value::Bool(true));
3121            }
3122        }
3123    }
3124    Ok(Value::Bool(false))
3125}
3126
3127pub(crate) fn arr_every_g(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3128    if hof_is_bytes(&t) {
3129        return arr_every_legacy(it, t, a);
3130    }
3131    let f = arg(a, 0);
3132    let (t, len) = hof_begin_obj(it, &t, &f, "every")?;
3133    let this_arg = arg(a, 1);
3134    for k in 0..len {
3135        if let Some(v) = hof_elem(it, &t, k)? {
3136            if !it.call_value(&f, this_arg.clone(), &[v, Value::Number(k as f64), t.clone()])?.truthy() {
3137                return Ok(Value::Bool(false));
3138            }
3139        }
3140    }
3141    Ok(Value::Bool(true))
3142}
3143
3144/// 結果の配列へ添字 `idx` の値を置く(実配列なら詰めて持つ。そうでなければ CreateDataPropertyOrThrow)。
3145fn hof_put(it: &mut Interp, target: &Value, idx: u64, v: Value) -> Result<(), Value> {
3146    if let Value::Object(o) = target {
3147        let mut b = o.borrow_mut();
3148        let i = idx as usize;
3149        let plain = !b.has_rare_props() && !b.is_frozen() && !b.is_sealed() && !b.is_non_extensible();
3150        if plain {
3151            let mut grown = false;
3152            if let ObjKind::Array(items) = &mut b.kind {
3153                if i == items.len() {
3154                    items.push(v.clone());
3155                    grown = true;
3156                } else if i < items.len() {
3157                    items[i] = v.clone();
3158                    grown = true;
3159                }
3160            }
3161            if grown {
3162                return Ok(());
3163            }
3164        }
3165    }
3166    super::object_array::create_data_property_or_throw(it, target, &idx.to_string(), v)
3167}
3168
3169pub(crate) fn arr_map_g(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3170    if hof_is_bytes(&t) {
3171        return arr_map_legacy(it, t, a);
3172    }
3173    let f = arg(a, 0);
3174    let (t, raw_len) = hof_begin_obj_raw(it, &t, &f, "map")?;
3175    let this_arg = arg(a, 1);
3176    let out = if raw_len > u32::MAX as u64 {
3177        let is_arr = super::object_array::is_array_value(it, &t)?;
3178        let custom_species = if is_arr {
3179            let ctor = it.get_property(&t, "constructor")?;
3180            if let Value::Object(co) = &ctor {
3181                let sp = it.get_property(&Value::Object(co.clone()), "Symbol(Symbol.species)")?;
3182                match &sp {
3183                    Value::Undefined | Value::Null => None,
3184                    Value::Object(so) if so.borrow().is_callable() => Some(sp),
3185                    _ => return Err(it.type_error("Symbol.species is not a constructor")),
3186                }
3187            } else if matches!(ctor, Value::Undefined) {
3188                None
3189            } else {
3190                return Err(it.type_error("Array constructor is not an object"));
3191            }
3192        } else {
3193            None
3194        };
3195        match custom_species {
3196            Some(sp) => it.construct_value(&sp, &[Value::Number(raw_len as f64)])?,
3197            None => return Err(it.range_error("Invalid array length")),
3198        }
3199    } else {
3200        array_species_create(it, &t, raw_len as usize)?
3201    };
3202    let len = raw_len.min(crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN as u64);
3203    // 結果が素の実配列なら、長さ len・全部が穴で始め、訪れた添字だけ埋める(仕様の ArraySpeciesCreate(O, len))。
3204    let fast = match &out {
3205        Value::Object(o) => {
3206            let mut b = o.borrow_mut();
3207            let ok = matches!(b.kind, ObjKind::Array(_))
3208                && !b.has_rare_props()
3209                && !b.is_frozen()
3210                && !b.is_sealed()
3211                && !b.is_non_extensible();
3212            if ok {
3213                let old = b.hole_mask();
3214                let n = match &mut b.kind {
3215                    ObjKind::Array(items) => {
3216                        let n = items.len();
3217                        if (n as u64) < len {
3218                            items.resize(len as usize, Value::Undefined);
3219                        }
3220                        n
3221                    }
3222                    _ => 0,
3223                };
3224                if (n as u64) < len {
3225                    let mut m = old;
3226                    m.resize(len as usize, false);
3227                    for h in m.iter_mut().skip(n) {
3228                        *h = true;
3229                    }
3230                    b.set_holes(Some(alloc::boxed::Box::new(m)));
3231                }
3232            }
3233            ok
3234        }
3235        _ => false,
3236    };
3237    for k in 0..len {
3238        if let Some(v) = hof_elem(it, &t, k)? {
3239            let r = it.call_value(&f, this_arg.clone(), &[v, Value::Number(k as f64), t.clone()])?;
3240            let mut done = false;
3241            if fast {
3242                if let Value::Object(o) = &out {
3243                    let mut b = o.borrow_mut();
3244                    let i = k as usize;
3245                    if let ObjKind::Array(items) = &mut b.kind {
3246                        if i < items.len() {
3247                            items[i] = r.clone();
3248                            done = true;
3249                        }
3250                    }
3251                    if done {
3252                        b.clear_hole(i);
3253                    }
3254                }
3255            }
3256            if !done {
3257                hof_put(it, &out, k, r)?;
3258            }
3259        }
3260    }
3261    if !fast {
3262        it.put_value(&out, "length", Value::Number(len as f64))?;
3263    }
3264    Ok(out)
3265}
3266
3267pub(crate) fn arr_filter_g(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3268    if hof_is_bytes(&t) {
3269        return arr_filter_legacy(it, t, a);
3270    }
3271    let f = arg(a, 0);
3272    let (t, len) = hof_begin_obj(it, &t, &f, "filter")?;
3273    let this_arg = arg(a, 1);
3274    let out = array_species_create(it, &t, 0)?;
3275    let mut to = 0u64;
3276    for k in 0..len {
3277        if let Some(v) = hof_elem(it, &t, k)? {
3278            if it.call_value(&f, this_arg.clone(), &[v.clone(), Value::Number(k as f64), t.clone()])?.truthy() {
3279                hof_put(it, &out, to, v)?;
3280                to += 1;
3281            }
3282        }
3283    }
3284    Ok(out)
3285}
3286
3287pub(crate) fn arr_reduce_g(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3288    if hof_is_bytes(&t) {
3289        return arr_reduce_legacy(it, t, a);
3290    }
3291    let f = arg(a, 0);
3292    let (t, len) = hof_begin_obj(it, &t, &f, "reduce")?;
3293    let mut k = 0u64;
3294    let mut acc = if a.len() >= 2 {
3295        arg(a, 1)
3296    } else {
3297        let mut init = None;
3298        while k < len {
3299            let e = hof_elem(it, &t, k)?;
3300            k += 1;
3301            if let Some(v) = e {
3302                init = Some(v);
3303                break;
3304            }
3305        }
3306        match init {
3307            Some(v) => v,
3308            None => return Err(it.type_error("Reduce of empty array with no initial value")),
3309        }
3310    };
3311    while k < len {
3312        if let Some(v) = hof_elem(it, &t, k)? {
3313            acc = it.call_value(&f, Value::Undefined, &[acc, v, Value::Number(k as f64), t.clone()])?;
3314        }
3315        k += 1;
3316    }
3317    Ok(acc)
3318}
3319/// 仕様上 `sort`/`toSorted` は `undefined` 要素を比較関数に一切渡さず、常に配列末尾に
3320/// 送る特別扱いが必要(ECMA-262 `SortCompare`)。以前はこの特別扱いが無く `undefined` も
3321/// 通常の要素として文字列比較/比較関数に渡していたため、例えば
3322/// `[undefined, 5].sort((a,b)=>a-b)` は `a-b` が `NaN` になり順序が保証されない
3323/// (常に末尾に来るはずが来ない)バグがあった。
3324pub(crate) fn sort_excluding_undefined(
3325    it: &mut Interp,
3326    mut items: alloc::vec::Vec<Value>,
3327    cmp: &Value,
3328) -> Result<alloc::vec::Vec<Value>, Value> {
3329    // 【2026-10-19】挿入ソート(O(n²))から安定なマージソート(O(n log n))へ。
3330    // YouTube の kevlar_base が HTML 実体参照名(約 2200 個)を比較関数付きで sort し、
3331    // 比較関数を約 250 万回呼んでいた(同じ呼び出しが約 1500 回で済む)。
3332    let undefined_count = items.iter().filter(|v| matches!(v, Value::Undefined)).count();
3333    items.retain(|v| !matches!(v, Value::Undefined));
3334    let n = items.len();
3335    let keys: Option<alloc::vec::Vec<String>> = if matches!(cmp, Value::Undefined) {
3336        let mut ks = alloc::vec::Vec::with_capacity(items.len());
3337        for v in &items {
3338            ks.push(it.to_string_value(v.clone())?);
3339        }
3340        Some(ks)
3341    } else {
3342        None
3343    };
3344    // a が b より後ろへ行くべきか(等しければ偽 = 元の順を保つ)。
3345    let greater = |it: &mut Interp, a: usize, b: usize| -> Result<bool, Value> {
3346        match &keys {
3347            Some(k) => Ok(k[a] > k[b]),
3348            None => {
3349                let v = it.call_value(cmp, Value::Undefined, &[items[a].clone(), items[b].clone()])?;
3350                let n = it.num_of(&v)?;
3351                Ok(n > 0.0)
3352            }
3353        }
3354    };
3355    let mut idx: alloc::vec::Vec<usize> = (0..n).collect();
3356    let mut buf: alloc::vec::Vec<usize> = alloc::vec![0; n];
3357    let mut width = 1;
3358    while width < n {
3359        let mut lo = 0;
3360        while lo < n {
3361            let mid = (lo + width).min(n);
3362            let hi = (lo + 2 * width).min(n);
3363            let (mut l, mut r, mut k) = (lo, mid, lo);
3364            while l < mid && r < hi {
3365                if greater(it, idx[l], idx[r])? {
3366                    buf[k] = idx[r];
3367                    r += 1;
3368                } else {
3369                    buf[k] = idx[l];
3370                    l += 1;
3371                }
3372                k += 1;
3373            }
3374            buf[k..k + (mid - l)].copy_from_slice(&idx[l..mid]);
3375            k += mid - l;
3376            buf[k..k + (hi - r)].copy_from_slice(&idx[r..hi]);
3377            lo += 2 * width;
3378        }
3379        core::mem::swap(&mut idx, &mut buf);
3380        width *= 2;
3381    }
3382    let mut out: alloc::vec::Vec<Value> = idx.into_iter().map(|i| items[i].clone()).collect();
3383    for _ in 0..undefined_count {
3384        out.push(Value::Undefined);
3385    }
3386    Ok(out)
3387}
3388pub(crate) fn put_prop_strict(it: &mut Interp, obj: &Value, key: &str, val: Value) -> Result<(), Value> {
3389    if !it.set_property_inner(obj, key, None, val)? {
3390        return Err(it.type_error(alloc::format!("Cannot assign to read only property '{}'", key)));
3391    }
3392    Ok(())
3393}
3394
3395fn del_prop_strict(it: &mut Interp, obj: &Value, key: &str) -> Result<(), Value> {
3396    if !it.delete_property(obj, key)?.truthy() {
3397        return Err(it.type_error(alloc::format!("Cannot delete property '{}'", key)));
3398    }
3399    Ok(())
3400}
3401
3402pub(crate) fn arr_sort(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3403    if matches!(t, Value::Undefined | Value::Null) {
3404        return Err(it.type_error("Array.prototype method called on null or undefined"));
3405    }
3406    let cmp = arg(a, 0);
3407    if !matches!(cmp, Value::Undefined) && !matches!(&cmp, Value::Object(f) if f.borrow().is_callable()) {
3408        return Err(it.type_error("The comparison function must be either a function or undefined"));
3409    }
3410    let obj = if matches!(&t, Value::Object(_)) {
3411        t.clone()
3412    } else {
3413        super::object_array::object_ctor(it, Value::Undefined, core::slice::from_ref(&t))?
3414    };
3415    if is_dense_plain_array(&obj) && matches!(&obj, Value::Object(o) if o.borrow().proto.is_none()) {
3416        let items = this_items(&obj);
3417        let items = sort_excluding_undefined(it, items, &cmp)?;
3418        if let Some(o) = this_objref(&obj) {
3419            arr_check(it, &o, ArrOp::Sort)?;
3420            if let ObjKind::Array(slot) = &mut o.borrow_mut().kind {
3421                *slot = items;
3422            }
3423        }
3424        return Ok(obj);
3425    }
3426    if let Some(o) = this_objref(&obj) {
3427        if matches!(&o.borrow().kind, ObjKind::Bytes(_)) {
3428            let items = this_items(&obj);
3429            let sorted = sort_excluding_undefined(it, items, &cmp)?;
3430            arr_check(it, &o, ArrOp::Sort)?;
3431            if let ObjKind::Bytes(st) = &mut o.borrow_mut().kind {
3432                for (i, v) in sorted.into_iter().enumerate() {
3433                    st.set_value(i, &v);
3434                }
3435            }
3436            return Ok(obj);
3437        }
3438    }
3439    let len_val = it.get_property(&obj, "length")?;
3440    let len = to_length_u64_checked(it, &len_val)?;
3441    let max_len = (crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN as u64).min(len);
3442    let mut items = Vec::new();
3443    for k in 0..max_len {
3444        let ks = k.to_string();
3445        if has_array_elem(it, &obj, &ks)? {
3446            items.push(get_array_elem(it, &obj, &ks)?);
3447        }
3448    }
3449    let item_count = items.len();
3450    let sorted = sort_excluding_undefined(it, items, &cmp)?;
3451    if let Some(o) = this_objref(&obj) {
3452        let is_plain_arr = {
3453            let b = o.borrow();
3454            matches!(&b.kind, ObjKind::Array(_))
3455                && !b.props.contains_key("_ta_kind")
3456                && !b.has_rare_props()
3457                && b.proto.is_none()
3458        };
3459        let is_bytes = matches!(&o.borrow().kind, ObjKind::Bytes(_));
3460        if is_plain_arr {
3461            arr_check(it, &o, ArrOp::Sort)?;
3462            let n_holes = (max_len as usize).saturating_sub(item_count);
3463            let mut full = sorted;
3464            full.extend(core::iter::repeat_n(Value::Undefined, n_holes));
3465            drop_holes(&o);
3466            if n_holes > 0 {
3467                let mut mask = alloc::vec![false; item_count];
3468                mask.extend(core::iter::repeat_n(true, n_holes));
3469                set_holes(&obj, mask);
3470            }
3471            if let ObjKind::Array(slot) = &mut o.borrow_mut().kind {
3472                *slot = full;
3473            }
3474            return Ok(obj);
3475        }
3476        if is_bytes {
3477            arr_check(it, &o, ArrOp::Sort)?;
3478            if let ObjKind::Bytes(st) = &mut o.borrow_mut().kind {
3479                for (i, v) in sorted.into_iter().enumerate() {
3480                    st.set(i, v.to_number());
3481                }
3482            }
3483            return Ok(obj);
3484        }
3485    }
3486    for (i, v) in sorted.into_iter().enumerate() {
3487        put_prop_strict(it, &obj, &i.to_string(), v)?;
3488    }
3489    for k in (item_count as u64)..max_len {
3490        del_prop_strict(it, &obj, &k.to_string())?;
3491    }
3492    Ok(obj)
3493}
3494/// `Array.prototype.fill(value, start, end)`。以前は `start`/`end`(第2/第3引数)を
3495/// 完全に無視して常に配列全体を上書きしており、`[1,2,3,4,5].fill(0,1,3)` のような
3496/// 部分埋めの定番パターンが機能していなかった。
3497pub(crate) fn arr_fill(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3498    if matches!(t, Value::Undefined | Value::Null) {
3499        return Err(it.type_error("Array.prototype method called on null or undefined"));
3500    }
3501    if let Some(o) = this_objref(&t) {
3502        let cur_len = match &o.borrow().kind {
3503            ObjKind::Array(items) => items.len(),
3504            _ => 0,
3505        };
3506        {
3507            let len = cur_len as i64;
3508            let start = norm_index(it.num_of(&arg(a, 1))?, len, 0).max(0) as usize;
3509            let end = if matches!(arg(a, 2), Value::Undefined) {
3510                len
3511            } else {
3512                norm_index(it.num_of(&arg(a, 2))?, len, len)
3513            }
3514            .max(0) as usize;
3515            arr_check(it, &o, ArrOp::Fill(start, end.min(cur_len)))?;
3516        }
3517        if let ObjKind::Array(items) = &mut o.borrow_mut().kind {
3518            let v = arg(a, 0);
3519            let len = items.len() as i64;
3520            let start = norm_index(it.num_of(&arg(a, 1))?, len, 0).max(0) as usize;
3521            let end = if matches!(arg(a, 2), Value::Undefined) {
3522                len
3523            } else {
3524                norm_index(it.num_of(&arg(a, 2))?, len, len)
3525            }
3526            .max(0) as usize;
3527            let end = end.min(items.len());
3528            for slot in items.iter_mut().take(end).skip(start) {
3529                *slot = v.clone();
3530            }
3531        }
3532    }
3533    Ok(t)
3534}
3535pub(crate) fn arr_splice(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3536    if matches!(t, Value::Undefined | Value::Null) {
3537        return Err(it.type_error("Array.prototype method called on null or undefined"));
3538    }
3539    let obj = if matches!(&t, Value::Object(_)) {
3540        t.clone()
3541    } else {
3542        super::object_array::object_ctor(it, Value::Undefined, core::slice::from_ref(&t))?
3543    };
3544    if is_direct_array(&obj) {
3545        let o = match this_objref(&obj) {
3546            Some(o) => o,
3547            None => return Ok(Value::Object(Obj::array(alloc::vec![]))),
3548        };
3549        let mut items = if let ObjKind::Array(v) = &o.borrow().kind {
3550            v.clone()
3551        } else {
3552            return Ok(Value::Object(Obj::array(alloc::vec![])));
3553        };
3554        let len_u64 = items.len() as u64;
3555        let start = norm_index_u64(it.num_of(&arg(a, 0))?, len_u64) as usize;
3556        let delete_count = if a.is_empty() {
3557            0
3558        } else if a.len() < 2 {
3559            items.len() - start
3560        } else {
3561            let dc = to_integer_or_infinity(it.num_of(&arg(a, 1))?);
3562            if dc <= 0.0 {
3563                0
3564            } else if dc == f64::INFINITY || dc >= ((items.len() - start) as f64) {
3565                items.len() - start
3566            } else {
3567                dc as usize
3568            }
3569        };
3570        let insert: alloc::vec::Vec<Value> = a.iter().skip(2).cloned().collect();
3571        let n_insert = insert.len();
3572        arr_check(it, &o, ArrOp::Splice(start, delete_count, n_insert))?;
3573        let h = holes_of(&obj);
3574        let mut removed = Vec::with_capacity(delete_count);
3575        let mut removed_mask = Vec::new();
3576        for (idx, item) in items.iter().enumerate().skip(start).take(delete_count) {
3577            if is_hole_at(&h, idx) {
3578                let ks = idx.to_string();
3579                if has_array_elem(it, &obj, &ks)? {
3580                    removed.push(get_array_elem(it, &obj, &ks)?);
3581                    removed_mask.push(false);
3582                } else {
3583                    removed.push(Value::Undefined);
3584                    removed_mask.push(true);
3585                }
3586            } else {
3587                removed.push(item.clone());
3588                removed_mask.push(false);
3589            }
3590        }
3591        items.drain(start..start + delete_count);
3592        for (i, v) in insert.into_iter().enumerate() {
3593            items.insert(start + i, v);
3594        }
3595        let new_mask: Vec<bool> = if h.is_empty() {
3596            Vec::new()
3597        } else {
3598            let old_len = items.len() + delete_count - n_insert;
3599            let mut m: Vec<bool> = (0..start).map(|i| is_hole_at(&h, i)).collect();
3600            m.extend(core::iter::repeat_n(false, n_insert));
3601            m.extend((start + delete_count..old_len).map(|i| is_hole_at(&h, i)));
3602            m
3603        };
3604        drop_holes(&o);
3605        if let ObjKind::Array(slot) = &mut o.borrow_mut().kind {
3606            *slot = items;
3607        }
3608        if !new_mask.is_empty() {
3609            set_holes(&obj, new_mask);
3610        }
3611        let a_obj = array_species_create(it, &obj, removed.len())?;
3612        let r = populate_array_species(it, &a_obj, removed)?;
3613        if removed_mask.iter().any(|&x| x) {
3614            set_holes(&r, removed_mask);
3615        }
3616        return Ok(r);
3617    }
3618
3619    // 汎用 array-like / Proxy 経路 (ECMA-262 §23.1.3.29)
3620    let len_val = it.get_property(&obj, "length")?;
3621    let len = to_length_u64_checked(it, &len_val)?;
3622    let actual_start = norm_index_u64(it.num_of(&arg(a, 0))?, len);
3623    let insert_count = a.len().saturating_sub(2) as u64;
3624    let actual_delete_count = if a.is_empty() {
3625        0
3626    } else if a.len() < 2 {
3627        len - actual_start
3628    } else {
3629        let dc = to_integer_or_infinity(it.num_of(&arg(a, 1))?);
3630        if dc <= 0.0 {
3631            0
3632        } else if dc == f64::INFINITY || dc >= ((len - actual_start) as f64) {
3633            len - actual_start
3634        } else {
3635            dc as u64
3636        }
3637    };
3638    if len + insert_count - actual_delete_count > MAX_SAFE_INT_U64 {
3639        return Err(it.type_error("Invalid array length"));
3640    }
3641    if actual_delete_count > crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN as u64 {
3642        return Err(it.range_error("Invalid array length"));
3643    }
3644    let del_usize = actual_delete_count as usize;
3645    let a_obj = array_species_create(it, &obj, del_usize)?;
3646    let mut removed = try_vec_with_capacity::<Value>(it, del_usize)?;
3647    let mut removed_mask = try_vec_with_capacity::<bool>(it, del_usize)?;
3648    for k in 0..actual_delete_count {
3649        let ks = (actual_start + k).to_string();
3650        if has_array_elem(it, &obj, &ks)? {
3651            removed.push(get_array_elem(it, &obj, &ks)?);
3652            removed_mask.push(false);
3653        } else {
3654            removed.push(Value::Undefined);
3655            removed_mask.push(true);
3656        }
3657    }
3658    if insert_count < actual_delete_count {
3659        for k in actual_start..(len - actual_delete_count) {
3660            let from = (k + actual_delete_count).to_string();
3661            let to = (k + insert_count).to_string();
3662            if has_array_elem(it, &obj, &from)? {
3663                let fv = get_array_elem(it, &obj, &from)?;
3664                put_prop_strict(it, &obj, &to, fv)?;
3665            } else {
3666                del_prop_strict(it, &obj, &to)?;
3667            }
3668        }
3669        let mut k = len;
3670        let target_len = len - actual_delete_count + insert_count;
3671        while k > target_len {
3672            k -= 1;
3673            del_prop_strict(it, &obj, &k.to_string())?;
3674        }
3675    } else if insert_count > actual_delete_count {
3676        let mut k = len - actual_delete_count;
3677        while k > actual_start {
3678            k -= 1;
3679            let from = (k + actual_delete_count).to_string();
3680            let to = (k + insert_count).to_string();
3681            if has_array_elem(it, &obj, &from)? {
3682                let fv = get_array_elem(it, &obj, &from)?;
3683                put_prop_strict(it, &obj, &to, fv)?;
3684            } else {
3685                del_prop_strict(it, &obj, &to)?;
3686            }
3687        }
3688    }
3689    for (i, item) in a.iter().skip(2).enumerate() {
3690        put_prop_strict(it, &obj, &(actual_start + (i as u64)).to_string(), item.clone())?;
3691    }
3692    let new_len = len - actual_delete_count + insert_count;
3693    put_prop_strict(it, &obj, "length", Value::Number(new_len as f64))?;
3694    let r = populate_array_species(it, &a_obj, removed)?;
3695    if removed_mask.iter().any(|&x| x) {
3696        set_holes(&r, removed_mask);
3697    }
3698    Ok(r)
3699}
3700
3701/// `Array.prototype.lastIndexOf(searchElement, fromIndex)`。同じ `fromIndex` 無視バグが
3702/// こちらにもあった(`indexOf`/`includes` と同じ調査で発見)。既定は末尾(`length-1`)から、
3703/// 負の値は末尾からのオフセットとして解釈し、その位置から先頭へ向かって探索する。
3704/// `Array.prototype.lastIndexOf(target, fromIndex)`。仕様の `ToIntegerOrInfinity` は
3705/// `NaN` を `0` として扱うため、`fromIndex` に `NaN` を渡した場合は「index 0 のみを見る」
3706/// (`fromIndex=0` と同じ)挙動になるはずだが、以前は `NaN` を検知すると無条件に `-1` を
3707/// 返しており、`[5,1,2].lastIndexOf(5, NaN)` が本来の `0` ではなく `-1` になっていた。
3708pub(crate) fn arr_last_index_of(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3709    if matches!(t, Value::Undefined | Value::Null) {
3710        return Err(it.type_error("Array.prototype method called on null or undefined"));
3711    }
3712    let mut a_buf = Vec::new();
3713    let a = num_arg1(it, &t, a, &mut a_buf)?;
3714    let target = arg(a, 0);
3715    if is_dense_plain_array(&t) {
3716        let found = with_array_items(&t, |items| {
3717            let len = items.len() as i128;
3718            if len == 0 {
3719                return None;
3720            }
3721            let start = if a.len() < 2 {
3722                len - 1
3723            } else {
3724                let n = to_integer_or_infinity(arg(a, 1).to_number());
3725                if n == f64::NEG_INFINITY {
3726                    return None;
3727                } else if n == f64::INFINITY {
3728                    len - 1
3729                } else if n < 0.0 {
3730                    let s = len + (n as i128);
3731                    if s < 0 {
3732                        return None;
3733                    }
3734                    s
3735                } else {
3736                    (n as i128).min(len - 1)
3737                }
3738            };
3739            (0..=start as usize).rev().find(|&i| items.get(i).is_some_and(|v| v.strict_eq(&target)))
3740        })
3741        .flatten();
3742        return Ok(Value::Number(found.map_or(-1.0, |i| i as f64)));
3743    }
3744
3745    let len_val = it.get_property(&t, "length")?;
3746    let len = to_length_u64_checked(it, &len_val)?;
3747    if len == 0 {
3748        return Ok(Value::Number(-1.0));
3749    }
3750    let len_i128 = len as i128;
3751    let mut k = if a.len() < 2 {
3752        len_i128 - 1
3753    } else {
3754        // 整数の型付き配列は変換しない(デタッチ検査が未対応のため従来どおり)。
3755        let raw = arg(a, 1);
3756        let n = if matches!(&t, Value::Object(o) if matches!(o.borrow().kind, ObjKind::Bytes(_))) {
3757            to_integer_or_infinity(raw.to_number())
3758        } else {
3759            to_integer_or_infinity(it.num_of(&raw)?)
3760        };
3761        if n == f64::NEG_INFINITY {
3762            return Ok(Value::Number(-1.0));
3763        } else if n == f64::INFINITY {
3764            len_i128 - 1
3765        } else if n < 0.0 {
3766            len_i128 + (n as i128)
3767        } else {
3768            (n as i128).min(len_i128 - 1)
3769        }
3770    };
3771    while k >= 0 {
3772        let ks = (k as u64).to_string();
3773        if has_array_elem(it, &t, &ks)? {
3774            let v = get_array_elem(it, &t, &ks)?;
3775            if v.strict_eq(&target) {
3776                return Ok(Value::Number(k as f64));
3777            }
3778        }
3779        k -= 1;
3780    }
3781    Ok(Value::Number(-1.0))
3782}
3783
3784pub(crate) fn arr_copy_within(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3785    if matches!(t, Value::Undefined | Value::Null) {
3786        return Err(it.type_error("Array.prototype method called on null or undefined"));
3787    }
3788    let obj = if matches!(t, Value::Object(_)) {
3789        t.clone()
3790    } else {
3791        super::object_array::object_ctor(it, Value::Undefined, core::slice::from_ref(&t))?
3792    };
3793    let len_val = it.get_property(&obj, "length")?;
3794    let len = to_length_u64_checked(it, &len_val)?;
3795    let to_n = it.num_of(&arg(a, 0))?;
3796    let to = norm_index_u64(to_n, len);
3797    let from_n = if matches!(arg(a, 1), Value::Undefined) {
3798        0.0
3799    } else {
3800        it.num_of(&arg(a, 1))?
3801    };
3802    let from = norm_index_u64(from_n, len);
3803    let end_n = if matches!(arg(a, 2), Value::Undefined) {
3804        len as f64
3805    } else {
3806        it.num_of(&arg(a, 2))?
3807    };
3808    let fin = norm_index_u64(end_n, len);
3809    let mut count = if fin > from {
3810        (fin - from).min(len - to)
3811    } else {
3812        0
3813    };
3814    if count == 0 {
3815        return Ok(obj);
3816    }
3817    let is_fast_bytes = matches!(&obj, Value::Object(o) if matches!(&o.borrow().kind, ObjKind::Bytes(_)));
3818    if is_fast_bytes {
3819        if let Value::Object(o) = &obj {
3820            let mut b = o.borrow_mut();
3821            if let ObjKind::Bytes(st) = &mut b.kind {
3822                let c = count as usize;
3823                let f = from as usize;
3824                let dst = to as usize;
3825                let cur_len = st.effective_len();
3826                let vals: Vec<Option<Value>> = (f..f + c).map(|i| st.get_value(i)).collect();
3827                for (i, v) in vals.into_iter().enumerate() {
3828                    if dst + i < cur_len {
3829                        if let Some(val) = v {
3830                            st.set_value(dst + i, &val);
3831                        }
3832                    }
3833                }
3834            }
3835        }
3836        return Ok(obj);
3837    }
3838    // 仕様 §23.1.3.4 準拠: 重なりに応じてコピー方向を決め、HasProperty / Get / Set(Throw=true) / DeletePropertyOrThrow を使う。
3839    let forward = !(from < to && to < from + count);
3840    let mut from_idx = if forward { from } else { from + count - 1 };
3841    let mut to_idx = if forward { to } else { to + count - 1 };
3842    while count > 0 {
3843        if it.tick() {
3844            return Err(Value::Undefined);
3845        }
3846        let from_key = from_idx.to_string();
3847        let to_key = to_idx.to_string();
3848        if has_array_elem(it, &obj, &from_key)? {
3849            let from_val = get_array_elem(it, &obj, &from_key)?;
3850            put_prop_strict(it, &obj, &to_key, from_val)?;
3851        } else {
3852            del_prop_strict(it, &obj, &to_key)?;
3853        }
3854        if forward {
3855            from_idx += 1;
3856            to_idx += 1;
3857        } else if count > 1 {
3858            from_idx -= 1;
3859            to_idx -= 1;
3860        }
3861        count -= 1;
3862    }
3863    Ok(obj)
3864}
3865
3866/// `Array.prototype.toSorted/toReversed/toSpliced/with`(ES2023)は %TypedArray%
3867/// にも同名メソッドが仕様化されているが、この処理系ではどれも `this` が TypedArray
3868/// (`ObjKind::Array` を流用し `_ta_kind` タグで区別)かどうかを見ずに常に素の
3869/// `Obj::array(items)` を返しており、`new Int8Array([3,1,2]).toSorted()` が
3870/// `Int8Array` ではなく普通の配列に化けるバグだった(`structuredClone(TypedArray)`
3871/// と同種)。`this` の `_ta_kind` を引き継いで返す共通ヘルパーで対応する。
3872pub(crate) fn is_typed_array(t: &Value) -> bool {
3873    if let Value::Object(o) = t {
3874        o.borrow().props.contains_key("_ta_kind")
3875    } else {
3876        false
3877    }
3878}
3879
3880/// `ArraySpeciesCreate(originalArray, length)` (ECMAScript 9.4.2.3)。
3881///
3882/// `map`/`filter`/`slice`/`splice`/`concat`/`flatMap` 等の派生配列生成で、
3883/// `this.constructor[Symbol.species]` を参照して結果オブジェクトを槃築する。
3884pub(crate) fn array_species_create(
3885    it: &mut Interp,
3886    original: &Value,
3887    length: usize,
3888) -> Result<Value, Value> {
3889    let init_cap = length.min(4096);
3890    let is_array = super::object_array::is_array_value(it, original)?;
3891    if !is_array {
3892        return Ok(Value::Object(Obj::array(alloc::vec::Vec::with_capacity(init_cap))));
3893    }
3894
3895    let ctor = it.get_property(original, "constructor")?;
3896    if matches!(ctor, Value::Undefined) {
3897        return Ok(Value::Object(Obj::array(alloc::vec::Vec::with_capacity(init_cap))));
3898    }
3899    if !matches!(ctor, Value::Object(_)) {
3900        return Err(it.type_error("Array constructor is not an object"));
3901    }
3902
3903    // @@species を取得
3904    let species_val = it.get_property(&ctor, "Symbol(Symbol.species)")?;
3905    if matches!(species_val, Value::Null | Value::Undefined) {
3906        return Ok(Value::Object(Obj::array(alloc::vec::Vec::with_capacity(init_cap))));
3907    }
3908
3909    // もし標準の Array コンストラクタなら高速路
3910    if let Value::Object(ref so) = species_val {
3911        if let Some(Value::Object(ref ao)) = it.global.borrow().vars.get("Array") {
3912            if core::ptr::eq(so.as_ref(), ao.as_ref()) {
3913                return Ok(Value::Object(Obj::array(alloc::vec::Vec::with_capacity(init_cap))));
3914            }
3915        }
3916    }
3917    if super::super::interp::calls::is_constructor(&species_val) {
3918        return it.construct_value(&species_val, &[Value::Number(length as f64)]);
3919    }
3920
3921    Err(it.type_error("Symbol.species is not a constructor"))
3922}
3923
3924pub(crate) fn populate_array_species(
3925    it: &mut Interp,
3926    target: &Value,
3927    items: alloc::vec::Vec<Value>,
3928) -> Result<Value, Value> {
3929    if let Value::Object(o) = target {
3930        let can_fast = {
3931            let b = o.borrow();
3932            matches!(b.kind, ObjKind::Array(_))
3933                && !b.has_rare_props()
3934                && !b.is_frozen()
3935                && !b.is_sealed()
3936                && !b.is_non_extensible()
3937        };
3938        if can_fast {
3939            let len = items.len();
3940            o.borrow_mut().kind = ObjKind::Array(items);
3941            o.borrow_mut().props.insert("length".into(), Value::Number(len as f64));
3942            return Ok(target.clone());
3943        }
3944    }
3945    let len = items.len();
3946    for (i, v) in items.into_iter().enumerate() {
3947        super::object_array::create_data_property_or_throw(it, target, &i.to_string(), v)?;
3948    }
3949    let _ = len;
3950    Ok(target.clone())
3951}
3952
3953pub(crate) fn same_kind_as(it: &mut Interp, t: &Value, items: alloc::vec::Vec<Value>) -> Value {
3954    let ta_kind_tag = if let Value::Object(o) = t {
3955        o.borrow().props.get("_ta_kind").map(|v| v.to_js_string())
3956    } else {
3957        None
3958    };
3959    match ta_kind_tag {
3960        Some(tag) => {
3961            // `with()` の第2引数のような、まだ型変換(ラップ/クランプ)を経ていない
3962            // 生の値が混ざっている場合があるため、コンストラクタ/`set`/索引代入と
3963            // 同じ `TaKind::convert()` を通す(既に有効域内の値には無害)。
3964            let kind = TaKind::from_name(&tag);
3965            let values: alloc::vec::Vec<f64> = items.iter().map(|v| kind.convert(v)).collect();
3966            make_typed_array(it, values, kind)
3967        }
3968        None => Value::Object(Obj::array(items)),
3969    }
3970}
3971pub(crate) fn arr_to_sorted(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3972    if matches!(t, Value::Undefined | Value::Null) {
3973        return Err(it.type_error("Array.prototype method called on null or undefined"));
3974    }
3975    let items = generic_array_items(it, &t);
3976    let cmp = arg(a, 0);
3977    let items = sort_excluding_undefined(it, items, &cmp)?;
3978    Ok(same_kind_as(it, &t, items))
3979}
3980
3981pub(crate) fn arr_to_reversed(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
3982    if matches!(t, Value::Undefined | Value::Null) {
3983        return Err(it.type_error("Array.prototype method called on null or undefined"));
3984    }
3985    let mut items = generic_array_items(it, &t);
3986    items.reverse();
3987    Ok(same_kind_as(it, &t, items))
3988}
3989
3990pub(crate) fn arr_to_spliced(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
3991    if matches!(t, Value::Undefined | Value::Null) {
3992        return Err(it.type_error("Array.prototype method called on null or undefined"));
3993    }
3994    let len_val = it.get_property(&t, "length")?;
3995    let len = to_length_u64_checked(it, &len_val)?;
3996    let actual_start = norm_index_u64(it.num_of(&arg(a, 0))?, len);
3997    let insert_count = a.len().saturating_sub(2) as u64;
3998    let actual_delete_count = if a.is_empty() {
3999        // 引数なしは何も取り除かない(2026-11-16)。
4000        0
4001    } else if a.len() < 2 {
4002        len - actual_start
4003    } else {
4004        let dc = to_integer_or_infinity(it.num_of(&arg(a, 1))?);
4005        if dc <= 0.0 {
4006            0
4007        } else if dc == f64::INFINITY || dc >= ((len - actual_start) as f64) {
4008            len - actual_start
4009        } else {
4010            dc as u64
4011        }
4012    };
4013    let new_len = len - actual_delete_count + insert_count;
4014    if new_len > MAX_SAFE_INT_U64 {
4015        return Err(it.type_error("Invalid array length"));
4016    }
4017    if new_len > crate::os_lib::ecma::value::MAX_DENSE_ARRAY_LEN as u64 {
4018        return Err(it.range_error("Invalid array length"));
4019    }
4020    let mut out = try_vec_with_capacity::<Value>(it, new_len as usize)?;
4021    if is_dense_plain_array(&t) {
4022        let items = this_items(&t);
4023        for k in 0..actual_start as usize {
4024            out.push(items.get(k).cloned().unwrap_or(Value::Undefined));
4025        }
4026        for v in a.iter().skip(2) {
4027            out.push(v.clone());
4028        }
4029        out.extend(
4030            items
4031                .iter()
4032                .skip((actual_start + actual_delete_count) as usize)
4033                .cloned(),
4034        );
4035    } else {
4036        for k in 0..actual_start {
4037            out.push(get_array_elem(it, &t, &k.to_string())?);
4038        }
4039        for v in a.iter().skip(2) {
4040            out.push(v.clone());
4041        }
4042        for k in (actual_start + actual_delete_count)..len {
4043            out.push(get_array_elem(it, &t, &k.to_string())?);
4044        }
4045    }
4046    Ok(same_kind_as(it, &t, out))
4047}
4048
4049fn arr_find_last_safe(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4050    find_core(it, t, a, true, false)
4051}
4052
4053fn arr_find_last_index_safe(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4054    find_core(it, t, a, true, true)
4055}
4056
4057/// 巨大 length でも全展開せず末尾から存在要素のみ辿る `reduceRight` 実装。
4058fn arr_reduce_right_safe(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4059    let t = to_object_required(it, &t, "reduceRight")?;
4060    let len_val = it.get_property(&t, "length")?;
4061    let len = to_length_u64(&Value::Number(if matches!(len_val, Value::Object(_)) { it.num_of(&len_val)? } else { len_val.to_number() }));
4062    let f = arg(a, 0);
4063    if !matches!(&f, Value::Object(fo) if fo.borrow().is_callable()) {
4064        return Err(it.type_error(alloc::format!("{} is not a function", describe_for_error(&f))));
4065    }
4066    let mut k: i128 = (len as i128) - 1;
4067    let mut acc = if a.len() > 1 {
4068        arg(a, 1)
4069    } else {
4070        let mut init: Option<Value> = None;
4071        while k >= 0 {
4072            let ks = (k as u64).to_string();
4073            if has_array_elem(it, &t, &ks)? {
4074                init = Some(get_array_elem(it, &t, &ks)?);
4075                k -= 1;
4076                break;
4077            }
4078            k -= 1;
4079        }
4080        match init {
4081            Some(v) => v,
4082            None => return Err(it.type_error("Reduce of empty array with no initial value")),
4083        }
4084    };
4085    while k >= 0 {
4086        let ku = k as u64;
4087        let ks = ku.to_string();
4088        if has_array_elem(it, &t, &ks)? {
4089            let v = get_array_elem(it, &t, &ks)?;
4090            acc = it.call_value(&f, Value::Undefined, &[acc, v, Value::Number(ku as f64), t.clone()])?;
4091        }
4092        k -= 1;
4093    }
4094    Ok(acc)
4095}
4096
4097/// `Array.prototype.with(index, value)`(ES2023)。範囲外 `index` は仕様上 `RangeError` だが、
4098/// 以前は黙って無視して元と同じ配列を返していた(呼び出し側が範囲外に気づけないバグ)。
4099pub(crate) fn arr_with(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4100    if matches!(t, Value::Undefined | Value::Null) {
4101        return Err(it.type_error("Array.prototype method called on null or undefined"));
4102    }
4103    let mut items = generic_array_items(it, &t);
4104    let len = items.len() as i64;
4105    let idx_raw = it.num_of(&arg(a, 0))? as i64;
4106    let idx = if idx_raw < 0 { len + idx_raw } else { idx_raw };
4107    if idx < 0 || idx >= len {
4108        return Err(it.range_error("Invalid index"));
4109    }
4110    items[idx as usize] = arg(a, 1);
4111    Ok(same_kind_as(it, &t, items))
4112}
4113
4114/// 再帰的に `depth` 段だけネスト配列を展開する(`arr_flat` のヘルパ)。
4115/// `depth=Infinity`(`arr.flat(Infinity)`)は定番イディオムだが、`depth - 1.0`
4116/// は `Infinity` のままなので、循環参照する配列(`a.push(a)`)に対しては
4117/// 祖先追跡ガードが無いと無限再帰になり、この no_std 環境ではスタック
4118/// オーバーフロー(クラッシュ/ハング)に直結し得る(`Value::to_js_string`
4119/// で修正済みの「循環参照でスタックオーバーフロー」系と同種のバグ。
4120/// 2026-07-13 の横断監査で発見)。既に祖先に現れた配列を再訪した時点で、
4121/// それ以上展開せずそのまま(配列のまま)結果へ積んで打ち切る。
4122pub(crate) fn flatten_depth(items: Vec<Value>, depth: f64, out: &mut Vec<Value>, seen: &mut Vec<ObjRef>) {
4123    for v in items {
4124        match v {
4125            Value::Object(o) if depth > 0.0 && matches!(o.borrow().kind, ObjKind::Array(_)) => {
4126                if seen.iter().any(|s| Rc::ptr_eq(s, &o)) {
4127                    out.push(Value::Object(o));
4128                    continue;
4129                }
4130                seen.push(o.clone());
4131                // 入れ子の配列の穴は飛ばす(2026-11-16)。
4132                let inner = {
4133                    let b = o.borrow();
4134                    match &b.kind {
4135                        ObjKind::Array(inner) if b.holes().is_some() => inner
4136                            .iter()
4137                            .enumerate()
4138                            .filter(|(i, _)| !b.is_hole(*i))
4139                            .map(|(_, v)| v.clone())
4140                            .collect(),
4141                        ObjKind::Array(inner) => inner.clone(),
4142                        _ => Vec::new(),
4143                    }
4144                };
4145                flatten_depth(inner, depth - 1.0, out, seen);
4146                seen.pop();
4147            }
4148            other => out.push(other),
4149        }
4150    }
4151}
4152/// `Array.prototype.flat(depth = 1)`。以前は `depth` 引数を完全に無視して常に1段だけ
4153/// 展開する実装になっており、`arr.flat(2)` や、深いネスト解除の定番イディオムである
4154/// `arr.flat(Infinity)` が仕様どおりに動かない(1段しか展開されない)バグだった。
4155pub(crate) fn arr_flat(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4156    if matches!(t, Value::Undefined | Value::Null) {
4157        return Err(it.type_error("Array.prototype method called on null or undefined"));
4158    }
4159    let items = without_holes(&t, generic_array_items(it, &t));
4160    let depth = if matches!(arg(a, 0), Value::Undefined) {
4161        1.0
4162    } else {
4163        it.num_of(&arg(a, 0))?
4164    };
4165    let mut out = Vec::new();
4166    flatten_depth(items, depth, &mut out, &mut Vec::new());
4167    Ok(Value::Object(Obj::array(out)))
4168}
4169/// `hasOwnProperty`/`Object.hasOwn` の実体。以前は `props.contains_key` だけを見ており、
4170/// (1) `accessors`(getter/setter 限定プロパティ)専用マップに存在するプロパティ
4171/// (`{get x(){}}.hasOwnProperty('x')`)と (2) 配列の数値インデックス/`length`
4172/// (`ObjKind::Array` 側にあり `props` には無い。`[1,2].hasOwnProperty(0)`)の
4173/// 2種類を「自身にあるのに無い」と誤判定するバグだった(`in`/`for...in` 等と同種)。
4174pub(crate) fn has_own_property(o: &super::super::value::ObjRef, key: &str) -> bool {
4175    let o = unwrap_proxy_target(o);
4176    if key == "prototype" {
4177        let _ = Obj::fn_prototype(&o);
4178    }
4179    let b = o.borrow();
4180    if let ObjKind::Array(items) = &b.kind {
4181        if key == "length" {
4182            return true;
4183        }
4184        if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
4185            return idx < items.len() && !b.is_hole(idx);
4186        }
4187    }
4188    if let ObjKind::Bytes(st) = &b.kind {
4189        if key == "length" {
4190            return true;
4191        }
4192        if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
4193            return idx < st.len;
4194        }
4195    }
4196    if let ObjKind::Plain = &b.kind {
4197        if let Some(Value::Str(s)) = b.primitive() {
4198            if !(s.starts_with("Symbol(") && s.ends_with(')')) {
4199                if key == "length" {
4200                    return true;
4201                }
4202                if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
4203                    if idx < Units::of(s).len() {
4204                        return true;
4205                    }
4206                }
4207            }
4208        }
4209    }
4210    b.props.contains_key(key) || b.has_accessor(key) || b.has_virtual_fn_prop(key)
4211}
4212pub(crate) fn obj_has_own(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4213    let pk = it.prim_key(arg(a, 0))?;
4214    let key = super::super::interp::to_property_key(&pk).into_owned();
4215    if matches!(t, Value::Undefined | Value::Null) {
4216        return Err(it.type_error("Cannot convert undefined or null to object"));
4217    }
4218    if let Value::Object(o) = &t {
4219        // ホスト物(DOM 要素のハンドルなど): 自前のプロパティはホスト側の expando(組込みは原型のアクセサ扱い)。
4220        let host_ref = o.borrow().kind.host_ref();
4221        if let Some(h) = host_ref {
4222            match (it.host.own)(it, h, &key) {
4223                HostOwn::Generic => {}
4224                HostOwn::Absent => return Ok(Value::Bool(false)),
4225                HostOwn::Accessor(..) | HostOwn::Data(_) => return Ok(Value::Bool(true)),
4226            }
4227        }
4228        if key == "prototype" {
4229            let _ = Obj::fn_prototype(o);
4230        }
4231        return Ok(Value::Bool(has_own_property(o, &key)));
4232    }
4233    // 文字列は `length` と各添字を自身のプロパティとして持つ(Symbol は持たない)。
4234    if let Value::Str(s) = &t {
4235        if !is_symbol_like_key(s) {
4236            let n = Units::of(s).len();
4237            return Ok(Value::Bool(
4238                key == "length" || crate::os_lib::ecma::value::parse_index(&key).is_some_and(|i| i < n),
4239            ));
4240        }
4241    }
4242    Ok(Value::Bool(false))
4243}
4244/// `Object.prototype.toString.call(x)`(`{}.toString()` 含む)。以前は `this` の
4245/// 実際の種別を一切見ず常に `"[object Object]"` を返しており、`lodash` 等の
4246/// ライブラリで広く使われる型判定イディオム(`Object.prototype.toString.call(x)
4247/// === '[object Array]'` 等)が配列/Map/Set/Date/RegExp/関数のいずれに対しても
4248/// 常に `"[object Object]"` になってしまう、実用上かなり影響の大きいバグだった。
4249pub(crate) fn obj_proto_get(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
4250    if matches!(t, Value::Undefined | Value::Null) {
4251        return Err(it.type_error("Cannot convert undefined or null to object"));
4252    }
4253    let obj = match &t {
4254        Value::Object(_) => t,
4255        _ => super::object_array::object_ctor(it, Value::Undefined, &[t])?,
4256    };
4257    super::extra_static::object_get_prototype_of(it, Value::Undefined, &[obj])
4258}
4259
4260pub(crate) fn obj_proto_set(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4261    if matches!(t, Value::Undefined | Value::Null) {
4262        return Err(it.type_error("Cannot convert undefined or null to object"));
4263    }
4264    let proto = arg(a, 0);
4265    if !matches!(proto, Value::Object(_) | Value::Null) {
4266        return Ok(Value::Undefined);
4267    }
4268    if !matches!(t, Value::Object(_)) {
4269        return Ok(Value::Undefined);
4270    }
4271    super::extra_static::object_set_prototype_of(it, Value::Undefined, &[t, proto])?;
4272    Ok(Value::Undefined)
4273}
4274
4275pub(crate) fn obj_to_string(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
4276    // ECMA-262 §20.1.3.6: まず builtinTag(および Proxy の IsArray/[[Call]] 判定)を決め、
4277    // その後 Get(O, @@toStringTag) を行う。Map/Set/Promise/Generator/関数サブタイプのタグは
4278    // 各 prototype の [Symbol.toStringTag] から得る。
4279    let builtin_tag = match &t {
4280        Value::Undefined => "Undefined",
4281        Value::Null => "Null",
4282        Value::Object(o) => {
4283            let target = unwrap_proxy_target(o);
4284            let b = target.borrow();
4285            if b.is_callable() {
4286                "Function"
4287            } else {
4288                match &b.kind {
4289                    ObjKind::Array(_) if b.props.contains_key("callee") || b.has_accessor("callee") => "Arguments",
4290                    ObjKind::Array(_) => "Array",
4291                    ObjKind::DateObj(_) => "Date",
4292                    ObjKind::RegExpObj(_) => "RegExp",
4293                    ObjKind::Bytes(_) => {
4294                        if let Some(k) = b.props.get("_ta_kind") {
4295                            return Ok(Value::str(format!("[object {}]", k.to_js_string())));
4296                        }
4297                        "Object"
4298                    }
4299                    ObjKind::Plain if b.primitive().is_some() => match b.primitive() {
4300                        Some(Value::Number(_)) => "Number",
4301                        Some(Value::Str(s)) if super::is_symbol_like_key(s) => "Object",
4302                        Some(Value::Str(_)) => "String",
4303                        Some(Value::BigInt(_)) => "BigInt",
4304                        _ => "Boolean",
4305                    },
4306                    ObjKind::Plain if b.is_error_obj() => "Error",
4307                    _ => "Object",
4308                }
4309            }
4310        }
4311        Value::Str(s) if super::is_symbol_like_key(s) => "Object",
4312        Value::Str(_) => "String",
4313        Value::Number(_) => "Number",
4314        Value::Bool(_) => "Boolean",
4315        Value::BigInt(_) => "BigInt",
4316    };
4317    if !matches!(&t, Value::Undefined | Value::Null) {
4318        let tag_val = it.get_property(&t, "Symbol(Symbol.toStringTag)")?;
4319        if let Value::Str(s) = tag_val {
4320            if !super::is_symbol_like_key(&s) {
4321                return Ok(Value::str(format!("[object {}]", s)));
4322            }
4323        }
4324    }
4325    Ok(Value::str(format!("[object {}]", builtin_tag)))
4326}
4327/// `Object.prototype.isPrototypeOf(obj)`: `this` が `obj` のプロトタイプ連鎖上に
4328/// 存在するか(`instanceof` の `r.prototype` 版に相当。こちらは呼び出し元自身と比較する)。
4329pub(crate) fn obj_is_prototype_of(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4330    let Value::Object(candidate) = arg(a, 0) else {
4331        return Ok(Value::Bool(false));
4332    };
4333    if matches!(t, Value::Undefined | Value::Null) {
4334        return Err(it.type_error("Cannot convert undefined or null to object"));
4335    }
4336    let target_val = super::object_array::object_ctor(it, Value::Undefined, &[t])?;
4337    let Value::Object(target) = target_val else {
4338        return Ok(Value::Bool(false));
4339    };
4340    let mut cur = super::extra_static::implicit_proto(it, &candidate);
4341    let mut guard = 0;
4342    while let Some(p) = cur {
4343        if Rc::ptr_eq(&p, &target) {
4344            return Ok(Value::Bool(true));
4345        }
4346        cur = super::extra_static::implicit_proto(it, &p);
4347        guard += 1;
4348        if guard > 1000 {
4349            break;
4350        }
4351    }
4352    Ok(Value::Bool(false))
4353}
4354/// `Object.prototype.propertyIsEnumerable(key)`: この処理系は独自プロパティに enumerable
4355/// フラグを持たないため、「自身の直接プロパティかどうか」で近似する(`hasOwnProperty` と
4356/// 同じ判定だが、プロトタイプ継承プロパティに対しては仕様通り false になる点は共通)。
4357pub(crate) fn obj_property_is_enumerable(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4358    let own = obj_has_own(it, t.clone(), a)?;
4359    if !own.truthy() {
4360        return Ok(own);
4361    }
4362    // 自身のプロパティのうち、列挙しないもの(配列・文字列の `length`、属性で隠したもの)は false
4363    // (2026-11-16。以前は自身のプロパティなら常に true だった)。
4364    let key = it.to_string_value(arg(a, 0))?;
4365    Ok(Value::Bool(match &t {
4366        Value::Str(_) => key != "length",
4367        Value::Object(o) => {
4368            let b = o.borrow();
4369            if matches!(b.kind, ObjKind::Array(_) | ObjKind::Bytes(_)) && key == "length" {
4370                false
4371            } else {
4372                b.is_enumerable(&key)
4373            }
4374        }
4375        _ => true,
4376    }))
4377}
4378
4379// ===== Function.prototype.call/apply/bind =====
4380// `Reflect.apply`/`Reflect.construct` は既にあったが、実用上はるかに一般的なこちらの
4381// インスタンスメソッド(`fn.call(this, ...)` 等)が長期間丸ごと欠落していた。
4382pub fn function_method_fn(key: &str) -> Option<(&'static str, NativeFn)> {
4383    match key {
4384        "call" => Some(("call", fn_call)),
4385        "apply" => Some(("apply", fn_apply)),
4386        "bind" => Some(("bind", fn_bind)),
4387        // 【2026-11-04】`toString` が無く、`fn.toString()` が Object.prototype.toString の `[object Function]` になっていた。
4388        "toString" => Some(("toString", fn_to_string)),
4389        _ => None,
4390    }
4391}
4392
4393pub fn function_method(key: &str) -> Value {
4394    match function_method_fn(key) {
4395        Some((n, f)) => nv(n, f),
4396        None => Value::Undefined,
4397    }
4398}
4399/// `Function.prototype.toString`: `this`(関数)のソース表現/`[native code]` を返す。
4400/// 関数でなければ TypeError(仕様どおり)。
4401pub(crate) fn fn_to_string(it: &mut Interp, t: Value, _a: &[Value]) -> Result<Value, Value> {
4402    match &t {
4403        Value::Object(o) if o.borrow().is_callable() => {
4404            let b = o.borrow();
4405            match &b.kind {
4406                ObjKind::Native { name, .. } => Ok(Value::str(alloc::format!(
4407                    "function {}() {{ [native code] }}",
4408                    crate::os_lib::ecma::fn_meta::native_name_string(name)
4409                ))),
4410                ObjKind::Bound(_) | ObjKind::Resolver { .. } | ObjKind::Proxy(_) => {
4411                    Ok(Value::str("function () { [native code] }"))
4412                }
4413                _ => {
4414                    drop(b);
4415                    Ok(Value::str(t.to_js_string()))
4416                }
4417            }
4418        }
4419        // ホストの物(DOM のコンストラクタなど。ブラウザでは関数)は、組み込みと同じ見た目の文字列を返す。
4420        // 投げると `Function.prototype.toString.call(HTMLElement)` を使う実サイトが落ちる(YouTube)。
4421        Value::Object(o) if o.borrow().kind.host_ref().is_some() => {
4422            Ok(Value::str("function () { [native code] }"))
4423        }
4424        _ => Err(it.type_error("Function.prototype.toString requires that 'this' be a Function")),
4425    }
4426}
4427pub(crate) fn fn_call(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4428    let this_arg = arg(a, 0);
4429    let rest: Vec<Value> = a.get(1..).map(|s| s.to_vec()).unwrap_or_default();
4430    it.call_value(&t, this_arg, &rest)
4431}
4432// `Function.prototype.apply` の第2引数も `Reflect.apply` と同じく
4433// `CreateListFromArrayLike`(array-like 全般)を経由すべきだが、`&mut Interp` を
4434// 持たない `iterable_values` を使っており素の array-like(実配列ではない)を渡すと
4435// 引数が丸ごと消える同型のバグだった。
4436pub(crate) fn fn_apply(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4437    let this_arg = arg(a, 0);
4438    let args_vec = match arg(a, 1) {
4439        Value::Undefined | Value::Null => Vec::new(),
4440        v => array_like_items(it, &v),
4441    };
4442    it.call_value(&t, this_arg, &args_vec)
4443}
4444pub(crate) fn fn_bind(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
4445    let Value::Object(target_obj) = &t else {
4446        return Err(it.type_error("Function.prototype.bind called on non-callable"));
4447    };
4448    if !target_obj.borrow().is_callable() {
4449        return Err(it.type_error("Function.prototype.bind called on non-callable"));
4450    }
4451    let bound_this = arg(a, 0);
4452    let bound_args: Vec<Value> = a.get(1..).map(|s| s.to_vec()).unwrap_or_default();
4453    let needs_dynamic = {
4454        let b = target_obj.borrow();
4455        matches!(b.kind, ObjKind::Proxy(_))
4456            || b.props.contains_key("length")
4457            || b.props.contains_key("name")
4458            || b.has_accessor("length")
4459            || b.has_accessor("name")
4460            || !b.has_virtual_fn_prop("length")
4461            || !b.has_virtual_fn_prop("name")
4462    };
4463    let bound_obj = Obj::bound(t.clone(), bound_this, bound_args.clone());
4464    if needs_dynamic {
4465        // ECMA-262 §20.2.3.2 Function.prototype.bind: カスタム属性やアクセサ・Proxy を持つターゲットでは
4466        // ? HasOwnProperty(Target, "length") / ? Get(Target, "length") / ? Get(Target, "name") を評価する。
4467        let has_len = has_own_property(target_obj, "length");
4468        let len_num = if has_len {
4469            match it.get_property(&t, "length")? {
4470                Value::Number(n) => {
4471                    if n.is_nan() || n <= 0.0 || n == f64::NEG_INFINITY {
4472                        0.0
4473                    } else if n == f64::INFINITY {
4474                        f64::INFINITY
4475                    } else {
4476                        (libm::trunc(n) - (bound_args.len() as f64)).max(0.0)
4477                    }
4478                }
4479                _ => 0.0,
4480            }
4481        } else {
4482            0.0
4483        };
4484        let target_name = match it.get_property(&t, "name")? {
4485            Value::Str(s) => (*s).clone(),
4486            _ => String::new(),
4487        };
4488        let bound_name = format!("bound {}", target_name);
4489        let default_attr = super::super::value::PropertyAttributes {
4490            writable: false,
4491            enumerable: false,
4492            configurable: true,
4493        };
4494        let mut bb = bound_obj.borrow_mut();
4495        let same_len = matches!(super::virtual_fn_prop_value(&bb, "length"), Some(Value::Number(n)) if n == len_num);
4496        if !same_len {
4497            bb.props.insert("length".into(), Value::Number(len_num));
4498            bb.delete_virtual_fn_prop("length");
4499            bb.insert_attr("length", default_attr);
4500        }
4501        if super::virtual_fn_prop_value(&bb, "name").as_ref().map(Value::to_js_string).as_deref() != Some(bound_name.as_str()) {
4502            bb.props.insert("name".into(), Value::str(bound_name));
4503            bb.delete_virtual_fn_prop("name");
4504            bb.insert_attr("name", default_attr);
4505        }
4506    }
4507    Ok(Value::Object(bound_obj))
4508}
4509
4510// ============ 小ヘルパ ============
4511
4512pub(crate) fn norm_index(v: f64, len: i64, default: i64) -> i64 {
4513    if v.is_nan() {
4514        return default;
4515    }
4516    let i = libm::trunc(v) as i64;
4517    if i < 0 {
4518        (len + i).max(0)
4519    } else {
4520        i.min(len)
4521    }
4522}
4523pub(crate) fn clamp_idx(v: f64, len: usize) -> usize {
4524    if v.is_nan() || v < 0.0 {
4525        0
4526    } else {
4527        (v as usize).min(len)
4528    }
4529}
4530pub(crate) fn pad_str(s: &str, target: usize, pad: &str, start: bool) -> String {
4531    let cur = unit_len(s);
4532    if cur >= target || pad.is_empty() {
4533        return String::from(s);
4534    }
4535    let mut padding = String::new();
4536    let pad_chars: Vec<char> = pad.chars().collect();
4537    let mut i = 0;
4538    while padding.chars().count() < target - cur {
4539        padding.push(pad_chars[i % pad_chars.len()]);
4540        i += 1;
4541    }
4542    if start {
4543        format!("{}{}", padding, s)
4544    } else {
4545        format!("{}{}", s, padding)
4546    }
4547}
4548pub(crate) fn format_fixed(n: f64, digits: usize) -> String {
4549    let neg = n < 0.0;
4550    let n = libm::fabs(n);
4551    let int_part = libm::trunc(n) as i64;
4552    let scale = libm::pow(10.0, digits as f64);
4553    let frac = libm::trunc((n - libm::trunc(n)) * scale + 0.5) as i64;
4554    let frac_str = format!("{:0width$}", frac, width = digits);
4555    format!("{}{}.{}", if neg { "-" } else { "" }, int_part, frac_str)
4556}
4557