Skip to main content

atmos/os_lib/ecma/interp/
properties.rs

1// 分割: interp.rs の `impl Interp` から機械的に移動(2026-07-16 リファクタ フェーズ5)。
2// ロジック不変。メソッド可視性のみ pub(crate) へ昇格(別モジュールの impl Interp
3// からの self 呼び出しのため)。impl ブロックは型 Interp に自動で結合する。
4use super::*;
5
6impl Interp {
7    pub(crate) fn string_get_prop(&self, sv: &Value, key: &str) -> Value {
8        if key == "length" {
9            return Value::Number(super::super::builtins::cached_units(self, sv).len() as f64);
10        }
11        if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
12            let u = super::super::builtins::cached_units(self, sv);
13            return if idx < u.len() { self.char_unit_val(u.at(idx)) } else { Value::Undefined };
14        }
15        super::super::builtins::string_builtin_fn(key)
16            .map(|(name, f)| self.builtin_fn_val(name, f))
17            .unwrap_or(Value::Undefined)
18    }
19
20    pub(crate) fn number_get_prop(&self, key: &str) -> Value {
21        super::super::builtins::number_builtin_fn(key)
22            .map(|(name, f)| self.builtin_fn_val(name, f))
23            .unwrap_or(Value::Undefined)
24    }
25
26    pub(crate) fn boolean_get_prop(&self, key: &str) -> Value {
27        super::super::builtins::boolean_builtin_fn(key)
28            .map(|(name, f)| self.builtin_fn_val(name, f))
29            .unwrap_or(Value::Undefined)
30    }
31
32    pub(crate) fn bigint_get_prop(&self, key: &str) -> Value {
33        super::super::builtins::bigint_builtin_fn(key)
34            .map(|(name, f)| self.builtin_fn_val(name, f))
35            .unwrap_or(Value::Undefined)
36    }
37
38    pub(crate) fn object_get_prop(&self, o: &ObjRef, key: &str) -> Value {
39        let is_array = matches!(o.borrow().kind, ObjKind::Array(_));
40        if is_array {
41            if let Some((name, f)) = super::super::builtins::array_builtin_fn(key) {
42                return self.builtin_fn_val(name, f);
43            }
44        }
45        if let Some((name, f)) = super::super::builtins::object_builtin_fn(key) {
46            return self.builtin_fn_val(name, f);
47        }
48        Value::Undefined
49    }
50
51    /// `key in obj` 用: 自身 props → プロトタイプ連鎖を辿って存在判定。
52    /// 配列の length / 数値インデックスも考慮する。
53    // 循環プロトタイプ連鎖で再帰が無限に深くならないよう、他の連鎖走査と同じ上限
54    // ガードを使った反復実装にしている(以前の素朴な再帰は無限再帰=スタック
55    // オーバーフローの危険があった)。
56    pub(crate) fn has_property_chain(&self, o: &ObjRef, key: &str) -> bool {
57        let mut cur = o.clone();
58        let mut guard = 0u32;
59        loop {
60            let b = cur.borrow();
61            if let ObjKind::Array(items) = &b.kind {
62                if key == "length" {
63                    return true;
64                }
65                if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
66                    if idx < items.len() && !b.is_hole(idx) {
67                        return true;
68                    }
69                }
70            }
71            if matches!(&b.kind, ObjKind::Bytes(_))
72                && crate::os_lib::ecma::value::is_canonical_numeric_key(key)
73            {
74                return crate::os_lib::ecma::value::ta_valid_index(&b, key).is_some();
75            }
76            // `accessors`(getter/setter 専用プロパティ)は `props` とは別マップで管理されて
77            // いるため、`props.contains_key` だけでは `{get x(){}}` のような accessor 限定の
78            // プロパティが `in` 演算子で「無い」ことになるバグがあった。
79            if b.props.contains_key(key) || b.has_accessor(key) {
80                return true;
81            }
82            if let Some(h) = b.kind.host_ref() {
83                if !matches!(
84                    (self.host.own)(self, h, key),
85                    crate::os_lib::ecma::host::HostOwn::Generic | crate::os_lib::ecma::host::HostOwn::Absent
86                ) {
87                    return true;
88                }
89            }
90            guard += 1;
91            if guard > 1000 {
92                return false;
93            }
94            let next = b.proto.clone();
95            let null_proto = b.is_null_proto();
96            let host_proto = if next.is_none() && !null_proto {
97                self.host_proto_of(&b.kind).flatten()
98            } else {
99                None
100            };
101            drop(b);
102            match next.or(host_proto) {
103                Some(p) => cur = p,
104                // 連鎖の終端(組込みの prototype は実体から動的に解決するので、ここで補う)。
105                // 【2026-10-20】`'constructor' in {}` が false になっていた。Polymer の
106                // `ybe`(`if(!(n in B5f))` で constructor のコピーを除外する)が prototype の
107                // constructor を上書きし、YouTube の ytd-app の起動が `finalize is not a function` で止まった。
108                None => {
109                    if null_proto {
110                        return false;
111                    }
112                    if matches!(key, "constructor" | "__proto__") {
113                        return true;
114                    }
115                    if o.borrow().is_callable() && matches!(key, "call" | "apply" | "bind" | "name" | "length") {
116                        return true;
117                    }
118                    return !matches!(super::super::builtins::object_get(o, key), Value::Undefined);
119                }
120            }
121        }
122    }
123
124    /// `o` がグローバルオブジェクト(`globalThis` / ブラウザ時は `window`)か。
125    pub(crate) fn is_global_obj(&self, o: &crate::os_lib::ecma::value::ObjRef) -> bool {
126        matches!(self.global.borrow().vars.get("globalThis"), Some(Value::Object(w)) if alloc::rc::Rc::ptr_eq(w, o))
127    }
128
129    /// `is_global_obj` の互換名。
130    pub(crate) fn is_window_obj(&self, o: &crate::os_lib::ecma::value::ObjRef) -> bool {
131        self.is_global_obj(o)
132    }
133
134    /// `recv.key` を読む。`recv` が undefined/null のときの例外に、その値を生んだ式
135    /// (`obj_expr`)を `stack` の先頭行の直後へ添える(2026-09-26。どの式が undefined
136    /// だったか分からず、ミニファイされたライブラリの不具合を追えなかった)。
137    pub fn get_property_of_expr(
138        &mut self,
139        recv: &Value,
140        key: &str,
141        obj_expr: &crate::os_lib::ecma::ast::Expression,
142    ) -> EvalResult {
143        let r = self.get_property(recv, key);
144        if let (Err(Value::Object(o)), Value::Undefined | Value::Null) = (&r, recv) {
145            let desc = describe_expr(obj_expr);
146            let stack = o.borrow().error_stack().unwrap_or("").to_string();
147            let mut lines = stack.splitn(2, '\n');
148            let first = lines.next().unwrap_or("");
149            let rest = lines.next();
150            let mut ns = alloc::format!("{first}\n    (undefined だった式: {desc})");
151            if let Some(rest) = rest {
152                ns.push('\n');
153                ns.push_str(rest);
154            }
155            o.borrow_mut().set_error_stack(ns);
156        }
157        r
158    }
159
160    /// 数値の添字 `obj[n]` の読み取りの近道(配列・型付き配列・文字列)。扱えなければ None
161    /// (呼び出し側は文字列キーの `get_property` へ回す)。
162    /// 【2026-10-24】従来は添字を毎回文字列に変換(確保と数値の書式化)して文字列キーで
163    /// 引き直していた。YouTube が JS 版 zlib(pako)で送信データを圧縮する内側のループ
164    /// (`S.window[p+2]` 等)が QEMU で 1 回 90µs かかり、再生開始が数分遅れていた。
165    /// 【2026-11-10】`Value::Str` に対するインデックスアクセスも直接高速処理し、UTF-16 単位キャッシュ
166    /// から O(1) ゼロアロケーションで文字を返却可能に拡張。
167    #[inline]
168    pub(crate) fn get_index_fast(&self, obj: &Value, key: &Value) -> Option<Value> {
169        let Value::Number(n) = key else { return None };
170        let n = *n;
171        if !(0.0..4_294_967_295.0).contains(&n) || (n as u32) as f64 != n {
172            return None;
173        }
174        let i = n as usize;
175        match obj {
176            Value::Object(o) => {
177                let b = o.borrow();
178                match &b.kind {
179                    ObjKind::Array(_) if b.has_any_accessor() => None,
180                    ObjKind::Array(items) => Some(items.get(i).cloned().unwrap_or(Value::Undefined)),
181                    ObjKind::Bytes(st) => {
182                        if crate::os_lib::ecma::value::ta_is_detached_or_oob(&b) {
183                            Some(Value::Undefined)
184                        } else if i < st.effective_len() {
185                            Some(st.get_value(i).unwrap_or(Value::Undefined))
186                        } else {
187                            Some(Value::Undefined)
188                        }
189                    }
190                    _ => None,
191                }
192            }
193            Value::Str(_) => {
194                let units = super::super::builtins::cached_units(self, obj);
195                if i < units.len() {
196                    Some(self.char_unit_val(units.at(i)))
197                } else {
198                    Some(Value::Undefined)
199                }
200            }
201            _ => None,
202        }
203    }
204
205    /// 数値の添字 `obj[n] = v` の書き込みの近道。扱えたら None、扱えなければ値を返す
206    /// (呼び出し側は文字列キーの `set_property` へ回す)。
207    /// 【2026-11-10】範囲内要素の上書きに加え、末尾要素の追加(`i == items.len()`)および
208    /// 近傍拡張(`i - items.len() <= 64`)を直接 `push`/`resize` でゼロアロケーション実行可能にし、
209    /// かつ `_ta_kind` の走査をゼロコピー借用に刷新。
210    #[inline]
211    pub(crate) fn set_index_fast(&mut self, obj: &Value, key: &Value, val: Value) -> Option<Value> {
212        let (Value::Object(o), Value::Number(n)) = (obj, key) else { return Some(val) };
213        let n = *n;
214        if !(0.0..4_294_967_295.0).contains(&n) || (n as u32) as f64 != n {
215            return Some(val);
216        }
217        let i = n as usize;
218        let mut b = o.borrow_mut();
219        if b.is_frozen() || b.is_sealed() || b.is_non_extensible() || b.has_rare_props() {
220            return Some(val);
221        }
222        if let ObjKind::Bytes(st) = &b.kind {
223            if super::super::value::ByteStore::is_bigint_kind(st.raw_kind())
224                || !matches!(val, Value::Number(_))
225                || crate::os_lib::ecma::value::ta_is_immutable(&b)
226            {
227                return Some(val);
228            }
229            if !crate::os_lib::ecma::value::ta_is_detached_or_oob(&b) && i < st.effective_len() {
230                st.set_value(i, &val);
231            }
232            return None;
233        }
234        let ta_kind = if !b.props.is_empty() {
235            if let Some(t) = b.props.get("_ta_kind") {
236                if b.props.contains_key("_view_root") {
237                    return Some(val);
238                }
239                match t {
240                    Value::Str(s) => Some(super::super::builtins::TaKind::from_name(s.as_str())),
241                    _ => None,
242                }
243            } else {
244                None
245            }
246        } else {
247            None
248        };
249        // 穴へ undefined を書いたときは穴の印を消す(値が undefined のままだと穴に見えるため)。
250        if matches!(val, Value::Undefined) && b.rare.is_some() {
251            b.clear_hole(i);
252        }
253        if let ObjKind::Array(items) = &mut b.kind {
254            if i < items.len() {
255                items[i] = match ta_kind {
256                    Some(ta) => Value::Number(ta.convert(&val)),
257                    None => val,
258                };
259                return None;
260            } else if i == items.len() && i < 1_000_000 {
261                let val_coerced = match ta_kind {
262                    Some(ta) => Value::Number(ta.convert(&val)),
263                    None => val,
264                };
265                items.push(val_coerced);
266                return None;
267            }
268        }
269        Some(val)
270    }
271
272    pub fn get_property(&mut self, recv: &Value, key: &str) -> EvalResult {
273        match recv {
274            Value::Undefined | Value::Null => Err(self.type_error(format!(
275                "Cannot read properties of {} (reading '{}')",
276                recv.to_js_string(),
277                key
278            ))),
279            Value::Str(_) | Value::Number(_) | Value::BigInt(_) | Value::Bool(_) => {
280                let is_sym = matches!(recv, Value::Str(s) if super::super::builtins::is_symbol_like_key(s));
281                let ctor = match recv {
282                    Value::Str(_) if is_sym => "Symbol",
283                    Value::Str(_) => "String",
284                    Value::Number(_) => "Number",
285                    Value::BigInt(_) => "BigInt",
286                    _ => "Boolean",
287                };
288                // 文字列の `length`・添字は実体から。それ以外は原型連鎖(`String.prototype` 等に足した・差し替えたメソッド、
289                // アクセサを含む。getter の this は元の値)を先に引き、無ければ組込みの名前表。【2026-11-20】
290                if !is_sym
291                    && matches!(recv, Value::Str(_))
292                    && (key == "length" || crate::os_lib::ecma::value::parse_index(key).is_some())
293                {
294                    let v = self.string_get_prop(recv, key);
295                    if !matches!(v, Value::Undefined) || key == "length" {
296                        return Ok(v);
297                    }
298                }
299                if let Some(p) = super::super::builtins::global_ctor_proto(self, ctor) {
300                    if let Some(r) = self.proto_chain_lookup(recv, &p, key, Some(p.clone())) {
301                        return r;
302                    }
303                }
304                let v = match recv {
305                    Value::Str(_) if is_sym => Value::Undefined,
306                    Value::Str(_) => self.string_get_prop(recv, key),
307                    Value::Number(_) => self.number_get_prop(key),
308                    Value::BigInt(_) => self.bigint_get_prop(key),
309                    _ => self.boolean_get_prop(key),
310                };
311                if !matches!(v, Value::Undefined) {
312                    return Ok(v);
313                }
314                // 組込みに無い名前は `String.prototype` 等(ポリフィルで足されたメソッドを含む)、
315                // その先の `Object.prototype`(`hasOwnProperty` 等)から引く。【2026-10-17】
316                // `false.hasOwnProperty(k)`(YouTube の `(!a).hasOwnProperty(c)`)が落ちていた。
317                // 原型連鎖(`Object.prototype` まで)は上の `proto_chain_lookup` で引き済み。
318                Ok(Value::Undefined)
319            }
320            Value::Object(o) => {
321                // 【高速化ホットパス】プレーンオブジェクト・配列・バイト列の直接プロパティ/要素
322                // 大半の一般JSアクセス(obj.x, arr.length, arr[i])において、後続の Proxy/Window/DOM/
323                // Storage/Iterator/Document (30+文字列比較)/Generator 等の重い判定を完全バイパスする。
324                let mut plain_proto_start = None;
325                {
326                    let b = o.borrow();
327                    match &b.kind {
328                        ObjKind::Plain if key != "__proto__" => {
329                            if let Some(a) = b.get_accessor(key) {
330                                let getter = a.get.clone();
331                                drop(b);
332                                return if let Some(g) = getter {
333                                    self.call_value(&g, recv.clone(), &[])
334                                } else {
335                                    Ok(Value::Undefined)
336                                };
337                            }
338                            if let Some(v) = b.props.get(key) {
339                                return Ok(v.clone());
340                            }
341                            // 値の包み(`new String("ab").length`・`new Number(5).toFixed(1)`)は中身の値の組み込みから引く。
342                            if let Some(p) = b.primitive() {
343                                let p = p.clone();
344                                drop(b);
345                                return self.get_property(&p, key);
346                            }
347                            if key != "selectedIndex" && key != "size" {
348                                plain_proto_start = Some(b.proto.clone());
349                            }
350                        }
351                        ObjKind::Array(items) => {
352                            if key == "length" {
353                                return Ok(Value::Number(items.len() as f64));
354                            }
355                            if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
356                                if let Some(a) = b.get_accessor(key) {
357                                    let getter = a.get.clone();
358                                    drop(b);
359                                    return match getter {
360                                        Some(g) => self.call_value(&g, recv.clone(), &[]),
361                                        None => Ok(Value::Undefined),
362                                    };
363                                }
364                                return Ok(items.get(idx).cloned().unwrap_or(Value::Undefined));
365                            }
366                        }
367                        ObjKind::Bytes(st)
368                            if crate::os_lib::ecma::value::is_canonical_numeric_key(key) =>
369                        {
370                            if let Some(idx) = crate::os_lib::ecma::value::ta_valid_index(&b, key) {
371                                return Ok(st.get_value(idx).unwrap_or(Value::Undefined));
372                            }
373                            return Ok(Value::Undefined);
374                        }
375                        ObjKind::HostRef(h) if key != "__proto__" && key != "selectedIndex" => {
376                            let h = *h;
377                            drop(b);
378                            if let Some(v) = self.host_get(o, h, key) {
379                                return Ok(v);
380                            }
381                        }
382                        _ => {}
383                    }
384                }
385                if let Some(first_proto) = plain_proto_start {
386                    if !self.is_window_obj(o) {
387                        let first = match first_proto {
388                            Some(p) => Some(p),
389                            None => super::super::builtins::implicit_proto(self, o),
390                        };
391                        return self.get_property_proto_chain(recv, o, key, first);
392                    }
393                }
394
395                // Proxy: [[Get]](get トラップ・不変条件・receiver)。
396                if matches!(o.borrow().kind, ObjKind::Proxy(_)) {
397                    return super::super::builtins::pm_get(self, o, key, recv);
398                }
399                // グローバルオブジェクト: `window.x` は同じ名前のグローバル変数(スクリプトの
400                // トップレベルの `var`・関数宣言・組み込み)でもある。
401                // 【2026-10-17】従来は `window` を普通のオブジェクトとして持ち、`var ytcfg = …;
402                // window.ytcfg.set(…)`(YouTube の視聴ページ)が undefined になっていた。
403                // 逆方向(素の `x` → `window.x`)は `eval_expr` の識別子解決が見る。
404                // ネイティブのコンストラクタ(組み込み関数)の `prototype` を初回参照時に用意する。
405                // 【2026-10-17】多くの組み込みが `prototype` を持たず、ポリフィルの
406                // `if (!X.prototype.entries)` 等が「undefined の 'entries'」で落ちていた(YouTube)。
407                if key == "prototype" && matches!(o.borrow().kind, ObjKind::Function(_)) {
408                    if let Some(v) = Obj::fn_prototype(o) {
409                        return Ok(v);
410                    }
411                }
412                if key == "prototype"
413                    && matches!(o.borrow().kind, ObjKind::Native { .. })
414                    && !o.borrow().props.contains_key("prototype")
415                    // `Proxy` コンストラクタは `prototype` を持たない(§28.2.2)。
416                    && !matches!(&o.borrow().kind, ObjKind::Native { name, .. } if &**name == "Proxy")
417                    // 組込みのメソッド(`exec`・`Symbol.match` など)は構築子でなく、`prototype` を持たない。
418                    && super::calls::is_constructor(&Value::Object(o.clone()))
419                {
420                    let proto = Obj::plain();
421                    proto.borrow_mut().props.insert("constructor".into(), Value::Object(o.clone()));
422                    o.borrow_mut().props.insert("prototype".into(), Value::Object(proto.clone()));
423                    return Ok(Value::Object(proto));
424                }
425                if self.is_window_obj(o) && !o.borrow().props.contains_key(key) {
426                    if !self.global_lexicals.borrow().contains(key) {
427                        if let Some(v) = self.global.borrow().vars.get(key).cloned() {
428                            return Ok(v);
429                        }
430                    }
431                    // 【2026-11-04 診断】window から大文字で始まる名前(コンストラクタ)を引いて見つからなかったもの。
432                    // BotGuard の VM が環境を調べる対象のうち、この処理系に無い API の目安(TODO B0)。
433                    if key.as_bytes().first().is_some_and(|c| c.is_ascii_uppercase()) && !o.borrow().has_accessor(key) {
434                        super::exec::note_engine_error(&alloc::format!("missing window.{}", key), || ());
435                    }
436                }
437                // RadioNodeList.prototype.value(HTML Standard §4.10.21.1 getter)・`select.selectedIndex`。
438                if key == "value" || key == "selectedIndex" {
439                    if let Some(v) = (self.host.special_get)(self, o, key) {
440                        return Ok(v);
441                    }
442                }
443                // ホスト物(DOM 要素のハンドル)の動的プロパティ。
444                let host_ref = o.borrow().kind.host_ref();
445                if let Some(h) = host_ref {
446                    if let Some(v) = self.host_get(o, h, key) {
447                        return Ok(v);
448                    }
449                }
450                // `entries`/`keys`/`values` が返す軽量イテレータ(`make_iterator()`。
451                // `ObjKind::Iter` + 内部 `_items`/`_pos` で近似)の `next`/
452                // `Symbol.iterator` メソッド。
453                let is_iterator = matches!(&o.borrow().kind, ObjKind::Iter);
454                if is_iterator {
455                    // 自前プロパティおよびプロトタイプ(%ArrayIteratorPrototype% → Iterator.prototype)を優先し、
456                    // 見つからない場合のみ従来の組み込みイテレータメソッドへフォールバックする。
457                    if o.borrow().props.contains_key(key) || o.borrow().has_accessor(key) {
458                        // 通常経路へ
459                    } else {
460                        let start = super::super::builtins::implicit_proto(self, o);
461                        if let Some(res) = self.proto_chain_lookup(recv, o, key, start) {
462                            return res;
463                        }
464                        if let Some(m) = match key {
465                            "next" => Some(self.builtin_fn_val("next", super::super::builtins::iterator_next)),
466                            "Symbol(Symbol.iterator)" => Some(self.builtin_fn_val(
467                                "[Symbol.iterator]",
468                                super::super::builtins::iterator_self,
469                            )),
470                            "map" => Some(self.builtin_fn_val("map", super::super::builtins::iterator_map)),
471                            "filter" => Some(self.builtin_fn_val("filter", super::super::builtins::iterator_filter)),
472                            "take" => Some(self.builtin_fn_val("take", super::super::builtins::iterator_take)),
473                            "drop" => Some(self.builtin_fn_val("drop", super::super::builtins::iterator_drop)),
474                            "toArray" => Some(self.builtin_fn_val("toArray", super::super::builtins::iterator_to_array)),
475                            "forEach" => Some(self.builtin_fn_val("forEach", super::super::builtins::iterator_for_each)),
476                            "reduce" => Some(self.builtin_fn_val("reduce", super::super::builtins::iterator_reduce)),
477                            "some" => Some(self.builtin_fn_val("some", super::super::builtins::iterator_some)),
478                            "every" => Some(self.builtin_fn_val("every", super::super::builtins::iterator_every)),
479                            "find" => Some(self.builtin_fn_val("find", super::super::builtins::iterator_find)),
480                            "flatMap" => Some(self.builtin_fn_val("flatMap", super::super::builtins::iterator_flat_map)),
481                            "includes" => Some(self.builtin_fn_val("includes", super::super::builtins::iterator_includes)),
482                            _ => None,
483                        } {
484                            return Ok(m);
485                        }
486                        return Ok(Value::Undefined);
487                    }
488                }
489                // Map / Set / Promise / Date のメソッドは、原型(`Map.prototype` 等)に足した・差し替えたものを先に引く。
490                if key != "size"
491                    && matches!(
492                        &o.borrow().kind,
493                        ObjKind::MapObj(_) | ObjKind::SetObj(_) | ObjKind::PromiseObj(_) | ObjKind::DateObj(_)
494                    )
495                {
496                    if let Some(r) = self.proto_chain_lookup(recv, o, key, Some(o.clone())) {
497                        return r;
498                    }
499                }
500                // Map / Set の size とメソッド。
501                let mapset = {
502                    match &o.borrow().kind {
503                        ObjKind::MapObj(e) => Some((true, e.len())),
504                        ObjKind::SetObj(s) => Some((false, s.len())),
505                        _ => None,
506                    }
507                };
508                if let Some((is_map, len)) = mapset {
509                    if key == "size" {
510                        return Ok(Value::Number(len as f64));
511                    }
512                    if let Some((n, f)) = super::super::builtins::mapset_method_fn(is_map, key) {
513                        return Ok(self.builtin_fn_val(n, f));
514                    }
515                }
516                // Promise のメソッド(then/catch/finally)。
517                let is_promise = matches!(&o.borrow().kind, ObjKind::PromiseObj(_));
518                if is_promise {
519                    if let Some((n, f)) = super::super::builtins::promise_method_fn(key) {
520                        return Ok(self.builtin_fn_val(n, f));
521                    }
522                }
523                // Generator のメソッド(next/return)。
524                let is_gen = matches!(&o.borrow().kind, ObjKind::Generator(_));
525                if is_gen {
526                    if key == "Symbol(Symbol.iterator)" {
527                        return Ok(self.builtin_fn_val("Generator[Symbol.iterator]", super::super::builtins::gen_self_iterator));
528                    }
529                    if key == "Symbol(Symbol.asyncIterator)" {
530                        let is_async = if let ObjKind::Generator(g) = &o.borrow().kind {
531                            g.borrow().func.is_async()
532                        } else {
533                            false
534                        };
535                        return Ok(if is_async {
536                            self.builtin_fn_val("Generator[Symbol.iterator]", super::super::builtins::gen_self_iterator)
537                        } else {
538                            Value::Undefined
539                        });
540                    }
541                    if let Some((n, f)) = super::super::builtins::generator_method_fn(key) {
542                        return Ok(self.builtin_fn_val(n, f));
543                    }
544                }
545                // Date のメソッド。
546                let is_date = matches!(&o.borrow().kind, ObjKind::DateObj(_));
547                if is_date {
548                    if let Some((n, f)) = super::super::builtins::date_method_fn(key) {
549                        return Ok(self.builtin_fn_val(n, f));
550                    }
551                }
552                // 配列の length / 数値インデックス。
553                {
554                    let b = o.borrow();
555                    if let ObjKind::Array(items) = &b.kind {
556                        if key == "length" {
557                            return Ok(Value::Number(items.len() as f64));
558                        }
559                        if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
560                            return Ok(items.get(idx).cloned().unwrap_or(Value::Undefined));
561                        }
562                    }
563                    if let ObjKind::Bytes(st) = &b.kind {
564                        if crate::os_lib::ecma::value::is_canonical_numeric_key(key) {
565                            if let Some(idx) = crate::os_lib::ecma::value::ta_valid_index(&b, key) {
566                                return Ok(st.get_value(idx).unwrap_or(Value::Undefined));
567                            }
568                            return Ok(Value::Undefined);
569                        }
570                    }
571                }
572                // 関数オブジェクトの call/apply/bind(Function.prototype 相当)。
573                if matches!(key, "call" | "apply" | "bind" | "toString")
574                    && o.borrow().is_callable()
575                    && !o.borrow().props.contains_key(key)
576                {
577                    if let Some(r) = self.proto_chain_lookup(recv, o, key, Some(o.clone())) {
578                        return r;
579                    }
580                    if let Some((n, f)) = super::super::builtins::function_method_fn(key) {
581                        return Ok(self.builtin_fn_val(n, f));
582                    }
583                }
584                // 非 strict な関数の `caller`/`arguments` は undefined(拡張を持たない扱い)。strict の関数・組込みは
585                // `Function.prototype` の投げるアクセサへ進む。【2026-11-20】
586                if key == "caller" || key == "arguments" {
587                    let b = o.borrow();
588                    if let ObjKind::Function(fd) = &b.kind {
589                        if !fd.shared.body.strict && !fd.is_arrow() && !b.props.contains_key(key) && !b.has_accessor(key) {
590                            return Ok(Value::Undefined);
591                        }
592                    }
593                }
594                // 関数の仮想自前プロパティ `name`/`length`(`props`/`accessors` に実体化されておらず、
595                // かつ `delete` されていないときのみ実体から求める。実体化・削除済みなら下の proto_chain へ流す)。
596                if key == "name" || key == "length" {
597                    if let Some(v) = super::super::builtins::virtual_fn_prop_value(&o.borrow(), key) {
598                        return Ok(v);
599                    }
600                }
601                self.get_property_proto_chain(recv, o, key, Some(o.clone()))
602            }
603        }
604    }
605
606    /// 自身のプロパティ / アクセサ / プロトタイプ連鎖を辿って解決する。
607    /// アクセサの getter は必ず元の recv(レシーバ)を this として呼ぶ。
608    /// 以前はプロトタイプ連鎖を get_property の再帰で辿っていたため、
609    /// 継承した getter(class の `get x(){}` 等)を呼ぶ際に this が
610    /// プロトタイプ自身に化けてしまい、インスタンス側のフィールドを
611    /// 正しく読めない(`this.r` 等が常に undefined になる)バグがあった。
612    /// ここでは recv を固定したまま cur だけをプロトタイプ連鎖に沿って
613    /// 進めるループに書き換えている。
614    pub(crate) fn get_property_proto_chain(
615        &mut self,
616        recv: &Value,
617        o: &ObjRef,
618        key: &str,
619        start: Option<ObjRef>,
620    ) -> EvalResult {
621        // `Object.setPrototypeOf` は循環(`setPrototypeOf(a,a)` 等)を検証
622        // しないため、プロトタイプ連鎖に循環があるとこのループが無限になり得る
623        // (`Proxy` チェーン解決ループで見つかったのと同型のバグ)。他の連鎖
624        // 走査と同じ上限ガードで打ち切る。2026-07-11 に一度試みて「新しい
625        // ハング」に見えたため撤回したが、2026-07-12 にそれが QEMU 起動側の
626        // host タイミング変動による誤検知だったと判明したため再度追加する。
627        if let Some(r) = self.proto_chain_lookup(recv, o, key, start) {
628            return r;
629        }
630        // `Object.create(null)`/`Object.groupBy()`等、明示的にnull
631        // プロトタイプ化されたオブジェクト(`null_proto`)は、
632        // `hasOwnProperty`/`toString`等の共通メソッドフォールバックも
633        // 一切持たないのが仕様(`proto: None`が「単に通常オブジェクト
634        // でチェーンが尽きた」のか「明示的にnull」なのかを区別する
635        // ためのフラグ。2026-07-18 発見・実装)。
636        if o.borrow().is_null_proto() {
637            return Ok(Value::Undefined);
638        }
639        // `x.constructor`(自前・原型に無い): 組込みの prototype の constructor。
640        // 【2026-10-20】`{}.constructor` が undefined だった。YouTube の Polymer(polySi)は
641        // 振る舞いオブジェクトの `.constructor` を `Reflect.construct`/`apply` に使う。
642        if key == "constructor" {
643            let name = {
644                let b = o.borrow();
645                match &b.kind {
646                    ObjKind::Array(_) => "Array",
647                    ObjKind::PromiseObj(_) => "Promise",
648                    ObjKind::MapObj(_) => "Map",
649                    ObjKind::SetObj(_) => "Set",
650                    ObjKind::RegExpObj(_) => "RegExp",
651                    ObjKind::DateObj(_) => "Date",
652                    _ if b.is_callable() => b.function_class_name(),
653                    _ => "Object",
654                }
655            };
656            if let Some(c) = super::scope_get(&self.global, name) {
657                return Ok(c);
658            }
659        }
660        // 関数オブジェクトの削除済み `name`/`length` は `Function.prototype` から継承する。
661        if (key == "name" || key == "length") && o.borrow().is_callable() && o.borrow().proto.is_none() {
662            if let Some(fp) = super::super::builtins::global_ctor_proto(self, o.borrow().function_class_name())
663                .or_else(|| super::super::builtins::global_ctor_proto(self, "Function"))
664            {
665                let b = fp.borrow();
666                if let Some(v) = b.props.get(key) {
667                    return Ok(v.clone());
668                }
669                if let Some(v) = super::super::builtins::virtual_fn_prop_value(&b, key) {
670                    return Ok(v);
671                }
672            }
673        }
674        // 組込みメソッド(Array/Object 共通)。
675        Ok(self.object_get_prop(o, key))
676    }
677
678    /// 原型連鎖(実体が原型を持たない組込みは、種類に応じた組込みの prototype と `Object.prototype` まで)を
679    /// 辿って、自前・アクセサ・継承のプロパティを探す。見つからなければ `None`(組込みの名前表へは進まない)。
680    /// 【2026-11-20】以前は `proto` が無い配列・素のオブジェクトで連鎖が途切れ、`Array.prototype.foo = …; [].foo()`・
681    /// `Object.prototype.bar = …; ({}).bar()` が「関数でない」になっていた(test262 の原型汚染の試験が大量に落ちる)。
682    pub(crate) fn proto_chain_lookup(
683        &mut self,
684        recv: &Value,
685        o: &ObjRef,
686        key: &str,
687        start: Option<ObjRef>,
688    ) -> Option<EvalResult> {
689        let mut cur_opt = start;
690        let mut guard = 0u32;
691        while let Some(cur) = cur_opt {
692            // 連鎖上の Proxy は [[Get]](トラップ)に任せる(receiver は元のまま)。
693            if !Rc::ptr_eq(&cur, o) && matches!(cur.borrow().kind, ObjKind::Proxy(_)) {
694                return Some(super::super::builtins::pm_get(self, &cur, key, recv));
695            }
696            // 連鎖上のホスト物(HTMLCollection 等)は host_get に問い合わせる。
697            if !Rc::ptr_eq(&cur, o) {
698                let hr = cur.borrow().kind.host_ref();
699                if let Some(h) = hr {
700                    if let Some(v) = self.host_get(&cur, h, key) {
701                        return Some(Ok(v));
702                    }
703                }
704            }
705            let (getter_opt, prop_opt, next) = {
706                let b = cur.borrow();
707                if let Some(a) = b.get_accessor(key) {
708                    (Some(a.get.clone()), None, None)
709                } else if let ObjKind::Array(items) = &b.kind {
710                    if key == "length" {
711                        (None, Some(Value::Number(items.len() as f64)), None)
712                    } else if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
713                        if idx < items.len() && !b.is_hole(idx) {
714                            (None, Some(items[idx].clone()), None)
715                        } else {
716                            let next = match b.proto.clone() {
717                                Some(p) => Some(p),
718                                None => super::super::builtins::implicit_proto(self, &cur),
719                            };
720                            (None, None, next)
721                        }
722                    } else if let Some(v) = b.props.get(key) {
723                        (None, Some(v.clone()), None)
724                    } else {
725                        let next = match b.proto.clone() {
726                            Some(p) => Some(p),
727                            None => super::super::builtins::implicit_proto(self, &cur),
728                        };
729                        (None, None, next)
730                    }
731                } else if let Some(v) = b.props.get(key) {
732                    (None, Some(v.clone()), None)
733                } else if (key == "name" || key == "length") && !Rc::ptr_eq(&cur, o) && b.has_virtual_fn_prop(key) {
734                    (None, super::super::builtins::virtual_fn_prop_value(&b, key), None)
735                } else {
736                    let next = match b.proto.clone() {
737                        Some(p) => Some(p),
738                        None => super::super::builtins::implicit_proto(self, &cur),
739                    };
740                    (None, None, next)
741                }
742            };
743            if let Some(getter) = getter_opt {
744                return Some(if let Some(g) = getter {
745                    self.call_value(&g, recv.clone(), &[])
746                } else {
747                    Ok(Value::Undefined)
748                });
749            }
750            if let Some(v) = prop_opt {
751                return Some(Ok(v));
752            }
753            guard += 1;
754            if guard > 1000 {
755                break;
756            }
757            cur_opt = next;
758        }
759        None
760    }
761
762    /// [[Set]] の結果を捨てる版(組み込み関数の内部用。従来どおり、失敗は黙殺し、setter・Proxy の例外は報告だけする)。
763    pub fn set_property(&mut self, recv: &Value, key: &str, val: Value) {
764        if let Err(e) = self.set_property_inner(recv, key, None, val) {
765            self.report_uncaught("setter", &e);
766        }
767    }
768
769    pub fn set_property_rc(&mut self, recv: &Value, key: &Rc<str>, val: Value) {
770        if let Err(e) = self.set_property_inner(recv, key, Some(key), val) {
771            self.report_uncaught("setter", &e);
772        }
773    }
774
775    /// 利用者のコードの代入(PutValue。ECMA-262 §6.2.5.6)。[[Set]] が false を返したとき、strict のコードなら TypeError、
776    /// setter・Proxy の set トラップが投げた例外は常に呼び出し元へ伝える。
777    #[inline]
778    pub fn put_value(&mut self, recv: &Value, key: &str, val: Value) -> Result<(), Value> {
779        match self.set_property_inner(recv, key, None, val) {
780            Ok(true) => Ok(()),
781            Ok(false) => self.put_failed(recv, key),
782            Err(e) => Err(e),
783        }
784    }
785
786    #[inline]
787    pub fn put_value_rc(&mut self, recv: &Value, key: &Rc<str>, val: Value) -> Result<(), Value> {
788        match self.set_property_inner(recv, key, Some(key), val) {
789            Ok(true) => Ok(()),
790            Ok(false) => self.put_failed(recv, key),
791            Err(e) => Err(e),
792        }
793    }
794
795    #[cold]
796    #[inline(never)]
797    fn put_failed(&mut self, recv: &Value, key: &str) -> Result<(), Value> {
798        if !self.strict {
799            return Ok(());
800        }
801        let what = match recv {
802            Value::Object(_) => "object",
803            _ => "primitive value",
804        };
805        Err(self.type_error(alloc::format!("Cannot assign to read only property '{}' of {}", key, what)))
806    }
807
808    /// [[Set]](OrdinarySet 相当)。成功なら `Ok(true)`、拒否(書込み不可・拡張不可・setter なし)は `Ok(false)`、
809    /// setter・Proxy トラップの例外は `Err`。
810    pub(crate) fn set_property_inner(&mut self, recv: &Value, key: &str, key_rc: Option<&Rc<str>>, val: Value) -> Result<bool, Value> {
811        if let Value::Object(o) = recv {
812            // 【高速化ホットパス】プレーンオブジェクト & 配列の直接プロパティ代入
813            // 一般的な代入(o.x = v, this.x = v, arr[i] = v)において、後続の数十個の特殊判定
814            // (Proxy, window, DOM, document, storage, radio, select, cookie, events,
815            // typed_array, location 等)をバイパスする。
816            {
817                let mut b = o.borrow_mut();
818                if !b.is_frozen()
819                    && !b.is_sealed()
820                    && !b.is_non_extensible()
821                    && !b.has_rare_props()
822                    && b.primitive().is_none()
823                    && key != "__proto__"
824                    && key != "returnValue"
825                    && key != "cancelBubble"
826                    && key != "selectedIndex"
827                {
828                    if let ObjKind::Plain = b.kind {
829                        if !b.props.contains_key("_is_location") && !proto_has_accessor(&b.proto, key) {
830                            drop(b);
831                            if !self.is_window_obj(o) {
832                                let mut b = o.borrow_mut();
833                                if let Some(slot) = b.props.get_mut(key) {
834                                    *slot = val;
835                                } else {
836                                    let pk = match key_rc {
837                                        Some(rc) => rc.into(),
838                                        None => key.into(),
839                                    };
840                                    b.props.insert(pk, val);
841                                }
842                                return Ok(true);
843                            }
844                        }
845                    } else if !b.props.contains_key("_ta_kind") && key != "length" {
846                        if let ObjKind::Array(ref mut items) = b.kind {
847                            if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
848                                if idx < items.len() {
849                                    items[idx] = val;
850                                    b.clear_hole(idx);
851                                    return Ok(true);
852                                }
853                            }
854                        }
855                    }
856                }
857            }
858
859            // Proxy: [[Set]](set トラップ・不変条件)。
860            if matches!(o.borrow().kind, ObjKind::Proxy(_)) {
861                return super::super::builtins::pm_set(self, o, key, val, recv);
862            }
863            // RadioNodeList.prototype.value = val(HTML Standard §4.10.21.1 setter)・`select.selectedIndex = n`。
864            if (key == "value" || key == "selectedIndex") && (self.host.special_set)(self, o, key, &val) {
865                return Ok(true);
866            }
867            // ホスト物(DOM 要素のハンドル)への代入。
868            let host_ref = o.borrow().kind.host_ref();
869            let val = match host_ref {
870                Some(h) => match (self.host.set)(self, o, h, key, val) {
871                    None => return Ok(true),
872                    Some(v) => v,
873                },
874                None => val,
875            };
876            // レガシー DOM Level 0 の `event.returnValue`/`event.cancelBubble` への
877            // 代入が丸ごと無視され、単なるプロパティ上書き(何の効果も持たない)に
878            // なっていたバグ。仕様上これらは `preventDefault()`/`stopPropagation()`
879            // と等価の副作用を持つべき。`preventDefault` プロパティ(callable)の
880            // 有無で Event オブジェクトかどうかを判定する(このエンジンの
881            // event_ctor/custom_event_ctor/DOM 要素側いずれも必ず持つ一意な目印)。
882            if key == "returnValue" || key == "cancelBubble" {
883                let is_event = matches!(
884                    o.borrow().props.get("preventDefault"),
885                    Some(Value::Object(f)) if f.borrow().is_callable()
886                );
887                if is_event {
888                    if key == "returnValue" && !val.truthy() {
889                        // `o.borrow()` の一時 Ref を `if let` の条件式に直接書くと
890                        // ブロック終端までライフタイムが延び、`call_value` が呼ぶ
891                        // `preventDefault` 内の `borrow_mut()` と衝突して
892                        // 「RefCell already borrowed」パニックになる(実機/QEMU
893                        // 起動時の自己テストで発覚)。先に所有値へ取り出してから
894                        // 呼び出すことで借用を確実に解放する。
895                        let pd = o.borrow().props.get("preventDefault").cloned();
896                        if let Some(f) = pd {
897                            self.call_listener(&f, recv.clone(), &[], "preventDefault()");
898                        }
899                        return Ok(true);
900                    }
901                    if key == "cancelBubble" && val.truthy() {
902                        let sp = o.borrow().props.get("stopPropagation").cloned();
903                        if let Some(f) = sp {
904                            self.call_listener(&f, recv.clone(), &[], "stopPropagation()");
905                        }
906                        return Ok(true);
907                    }
908                    // `returnValue = true` や `cancelBubble = false` は一度止めた
909                    // ものを元に戻す効果を持たない no-op だが、自身・プロトタイプ連鎖上に
910                    // アクセサ(getter/setter)がある場合は props を上書きせず setter 側へ流す。
911                    let mut has_acc = false;
912                    let mut cur_acc = Some(o.clone());
913                    let mut g = 0u32;
914                    while let Some(c) = cur_acc {
915                        let b = c.borrow();
916                        if b.has_accessor(key)
917                            || matches!(b.kind, ObjKind::Proxy(_))
918                            || (!alloc::rc::Rc::ptr_eq(&c, o)
919                                && matches!(&b.kind, ObjKind::Bytes(_))
920                                && b.props.contains_key("_ta_kind")
921                                && crate::os_lib::ecma::value::is_canonical_numeric_key(key))
922                        {
923                            has_acc = true;
924                            break;
925                        }
926                        g += 1;
927                        if g > 64 {
928                            break;
929                        }
930                        let p = b.proto.clone();
931                        cur_acc = if p.is_none() && !b.is_null_proto() {
932                            self.host_proto_of(&b.kind).flatten()
933                        } else {
934                            p
935                        };
936                    }
937                    if !has_acc {
938                        o.borrow_mut().props.insert(key.to_string().into(), val);
939                        return Ok(true);
940                    }
941                }
942            }
943            // TypedArray (ECMA-262 §10.4.5.5 [[Set]]):
944            // CanonicalNumericIndexString はプロトタイプ連鎖を辿らず処理する。
945            if matches!(o.borrow().kind, ObjKind::Bytes(_))
946                && crate::os_lib::ecma::value::is_canonical_numeric_key(key)
947            {
948                let same_recv = matches!(recv, Value::Object(ro) if alloc::rc::Rc::ptr_eq(o, ro));
949                if !same_recv {
950                    return super::super::builtins::set_on_receiver(self, key, val, recv);
951                }
952                if crate::os_lib::ecma::value::ta_is_immutable(&o.borrow()) {
953                    return Ok(false);
954                }
955                let (st, is_bigint) = {
956                    let b = o.borrow();
957                    if let ObjKind::Bytes(st) = &b.kind {
958                        (st.clone(), super::super::value::ByteStore::is_bigint_kind(st.raw_kind()))
959                    } else {
960                        unreachable!()
961                    }
962                };
963                let coerced = if matches!(val, Value::Object(_)) {
964                    self.to_primitive(val, "number")?
965                } else {
966                    val
967                };
968                if coerced.type_of() == "symbol" {
969                    return Err(self.type_error("Cannot convert a Symbol value to a number"));
970                }
971                let converted = if is_bigint {
972                    match &coerced {
973                        Value::BigInt(bi) => Value::BigInt(bi.clone()),
974                        Value::Bool(true) => Value::bigint(super::super::bigint::BigInt::from_i64(1)),
975                        Value::Bool(false) => Value::bigint(super::super::bigint::BigInt::zero()),
976                        Value::Str(s) => match super::super::bigint::BigInt::parse_js_string(s) {
977                            Some(bi) => Value::bigint(bi),
978                            None => return Err(self.syntax_error("Cannot convert string to a BigInt")),
979                        },
980                        _ => return Err(self.type_error("Cannot convert value to a BigInt")),
981                    }
982                } else {
983                    if matches!(coerced, Value::BigInt(_)) {
984                        return Err(self.type_error("Cannot convert a BigInt value to a number"));
985                    }
986                    coerced
987                };
988                // 変換中にバッファが resize / detach される可能性があるため変換後に再検証する。
989                let valid_idx = crate::os_lib::ecma::value::ta_valid_index(&o.borrow(), key);
990                if let Some(idx) = valid_idx {
991                    st.set_value(idx, &converted);
992                }
993                return Ok(true);
994            }
995            if matches!(o.borrow().kind, ObjKind::Bytes(_)) && key == "length" {
996                return Ok(false);
997            }
998            // アクセサ(setter)確認。`get_property` と同じ理由で、プロトタイプ連鎖
999            // (class の `set x(v){}` は prototype 上にある)を this を固定したまま
1000            // ループで辿る(インスタンス自身だけしか見ていなかった旧実装は、継承した
1001            // setter が一切呼ばれず通常のプロパティ書込みにフォールバックしてしまう
1002            // バグだった)。
1003            let mut cur = o.clone();
1004            // `get_property` と同じ理由(`Object.setPrototypeOf` が循環プロトタイプ
1005            // 連鎖を検証しない)で上限ガードが必要。
1006            let mut guard = 0u32;
1007            loop {
1008                if matches!(cur.borrow().kind, ObjKind::Proxy(_)) {
1009                    return super::super::builtins::pm_set(self, &cur, key, val, recv);
1010                }
1011                if !alloc::rc::Rc::ptr_eq(&cur, o)
1012                    && crate::os_lib::ecma::value::is_canonical_numeric_key(key)
1013                {
1014                    let is_ta_proto = {
1015                        let cb = cur.borrow();
1016                        matches!(&cb.kind, ObjKind::Bytes(_)) && cb.props.contains_key("_ta_kind")
1017                    };
1018                    if is_ta_proto {
1019                        // TypedArray Exotic [[Set]] (ECMA-262 §10.4.5.5): プロトタイプ上の TypedArray に
1020                        // CanonicalNumericIndexString キーの書き込みが到達したら Receiver へプロパティを作らず完了。
1021                        return Ok(true);
1022                    }
1023                }
1024                let (has_accessor_entry, has_own_data) = {
1025                    let cb = cur.borrow();
1026                    let is_arr_len = matches!(&cb.kind, ObjKind::Array(_)) && key == "length";
1027                    let is_arr_elem = matches!(&cb.kind, ObjKind::Array(items)
1028                        if !cb.props.contains_key("_ta_kind")
1029                            && crate::os_lib::ecma::value::parse_index(key)
1030                                .is_some_and(|i| i < items.len() && !cb.is_hole(i)));
1031                    (cb.has_accessor(key), cb.props.contains_key(key) || is_arr_len || is_arr_elem)
1032                };
1033                if has_accessor_entry {
1034                    let setter = cur.borrow().get_setter(key);
1035                    if let Some(s) = setter {
1036                        self.call_value(&s, recv.clone(), &[val])?;
1037                        return Ok(true);
1038                    }
1039                    // setter が無い(getter のみ)場合も、アクセサ定義がある以上は
1040                    // 通常のデータプロパティ書込みへフォールバックしない(仕様通り)。[[Set]] は false。
1041                    return Ok(false);
1042                }
1043                if has_own_data {
1044                    break;
1045                }
1046                guard += 1;
1047                if guard > 1000 {
1048                    break;
1049                }
1050                let next = {
1051                    let cb = cur.borrow();
1052                    match cb.proto.clone() {
1053                        Some(p) => Some(p),
1054                        None if !cb.is_null_proto() => super::super::builtins::implicit_proto(self, &cur),
1055                        None => None,
1056                    }
1057                };
1058                match next {
1059                    Some(p) if !alloc::rc::Rc::ptr_eq(&p, &cur) => cur = p,
1060                    _ => break,
1061                }
1062            }
1063            let mut b = o.borrow_mut();
1064            if b.is_frozen() {
1065                return Ok(false);
1066            }
1067            if let Some(Value::Str(sv)) = b.primitive() {
1068                if !super::super::builtins::is_symbol_like_key(sv)
1069                    && (key == "length"
1070                        || crate::os_lib::ecma::value::parse_index(key)
1071                            .is_some_and(|i| i < sv.encode_utf16().count()))
1072                {
1073                    return Ok(false);
1074                }
1075            }
1076            if b.props.contains_key(key) {
1077                if let Some(attr) = b.get_attr(key) {
1078                    if !attr.writable {
1079                        return Ok(false);
1080                    }
1081                }
1082            } else if !b.has_accessor(key) && b.has_virtual_fn_prop(key) {
1083                // 関数の仮想自前プロパティ `name` / `length` は既定で `writable: false` のため直接代入を無視する。
1084                return Ok(false);
1085            }
1086            // TypedArray(`_ta_kind` タグ付きの `ObjKind::Array` 流用実装)の索引代入
1087            // `ta[i] = v` は、コンストラクタ/`set`/`fill` 経由と違って型変換
1088            // (ToInt8/ToUint8Clamp/... 相当。範囲外の値のラップ/クランプ)が一切
1089            // 効かず生の数値がそのまま入るバグだった(例: `new Int8Array(1); a[0]=200;`
1090            // が `200` のまま、本来は `-56` にラップされるべき)。
1091            let ta_kind_tag = b.props.get("_ta_kind").map(|v| v.to_js_string());
1092            if matches!(b.kind, ObjKind::Array(_)) {
1093                // 【2026-11-19】`length` が書き換え不可、要素が書き換え不可、拡張不可の配列に新しい添字、は書き込みを拒む
1094                // (ECMA-262 §10.4.2.1 [[DefineOwnProperty]] / §10.1.9.2 OrdinarySet。strict では TypeError になるが、
1095                // この経路は結果を返せないので sloppy 相当で黙って捨てる)。
1096                if !b.props.contains_key("_ta_kind") {
1097                    if key == "length" {
1098                        if b.get_attr("length").is_some_and(|a| !a.writable) {
1099                            return Ok(false);
1100                        }
1101                    } else if let Some(idx) = crate::os_lib::ecma::value::parse_index(key) {
1102                        let cur = match &b.kind {
1103                            ObjKind::Array(items) => items.len(),
1104                            _ => 0,
1105                        };
1106                        if idx < cur {
1107                            if b.get_attr(key).is_some_and(|a| !a.writable) {
1108                                return Ok(false);
1109                            }
1110                        } else if b.is_sealed()
1111                            || b.is_non_extensible()
1112                            || b.get_attr("length").is_some_and(|a| !a.writable)
1113                        {
1114                            return Ok(false);
1115                        }
1116                    }
1117                }
1118                if key == "length" {
1119                    let n = val.to_number();
1120                    if n.is_finite() && n >= 0.0 {
1121                        let n = n as usize;
1122                        let cur = match &b.kind {
1123                            ObjKind::Array(items) => items.len(),
1124                            _ => 0,
1125                        };
1126                        if n > cur {
1127                            // 伸びた分は穴。上限を超える長さは扱えないので変えない(`grow_array`)。
1128                            b.grow_array(n);
1129                        } else if let ObjKind::Array(items) = &mut b.kind {
1130                            items.truncate(n);
1131                        }
1132                    }
1133                    return Ok(true);
1134                }
1135                // 添字("0"・"12"。"01"・"+1" は普通のプロパティ)。
1136                let index = crate::os_lib::ecma::value::parse_index(key);
1137                if let Some(idx) = index {
1138                    let cur = match &b.kind {
1139                        ObjKind::Array(items) => items.len(),
1140                        _ => 0,
1141                    };
1142                    if idx >= cur && !b.grow_array(idx + 1) {
1143                        // 上限を超える添字は、長さを変えずに普通のプロパティとして持つ(読み返せる。落とさない)。
1144                        b.props.insert(key.into(), val);
1145                        return Ok(true);
1146                    }
1147                    b.clear_hole(idx);
1148                }
1149            }
1150            if let ObjKind::Array(items) = &mut b.kind {
1151                if let Some(idx) = crate::os_lib::ecma::value::parse_index(key).filter(|&i| i < items.len()) {
1152                    let val = match &ta_kind_tag {
1153                        Some(tag) => Value::Number(super::super::builtins::ta_coerce_index_value(tag, &val)),
1154                        None => val,
1155                    };
1156                    items[idx] = val;
1157                    // TypedArray のビュー(`subarray` 等)なら元配列へ書き通す。
1158                    if ta_kind_tag.is_some() && b.props.contains_key("_view_root") {
1159                        drop(b);
1160                        super::super::builtins::ta_write_through(o, idx, idx + 1);
1161                    }
1162                    return Ok(true);
1163                }
1164            }
1165            // `Object.seal()`/`Object.preventExtensions()` 済みなら新規プロパティの追加を
1166            // 拒否する(既存キーの値変更は許可。配列の数値インデックス拡張は対象外の簡略化)。
1167            if (b.is_sealed() || b.is_non_extensible()) && !b.props.contains_key(key) {
1168                return Ok(false);
1169            }
1170            // location オブジェクトのナビゲーション系プロパティへの代入。
1171            // 例: location.href = "..." / location.hash = "#x" / location.pathname = "/p"。
1172            // ホストが take_pending_location() で回収し実ナビゲーションするよう要求を積む。
1173            // それ以外(origin 等の読取専用や href の文字列保持)は通常通り props に格納する。
1174            let is_location = b.props.contains_key("_is_location");
1175            if is_location {
1176                let new_val = val.to_js_string();
1177                // 【診断】JS によるページ遷移の要求(どの関数から何を代入したか)。
1178                if matches!(key, "href" | "hash" | "pathname" | "search" | "protocol" | "host" | "hostname" | "port") {
1179                    let top = self.call_stack_names(8);
1180                    crate::warn!("[JSNAV] location.{} = {:?} top={:?}", key, new_val.chars().take(120).collect::<String>(), top);
1181                }
1182                match key {
1183                    "href" => {
1184                        b.props
1185                            .insert(String::from("_pending_location").into(), Value::str(&new_val));
1186                        b.props
1187                            .insert(String::from("_pending_location_mode").into(), Value::str("assign"));
1188                    }
1189                    "hash" => {
1190                        // 現在の href からフラグメントだけ差し替えた完全URLを要求に積む。
1191                        let cur = b
1192                            .props
1193                            .get("href")
1194                            .map(|v| v.to_js_string())
1195                            .unwrap_or_default();
1196                        let base = match cur.split_once('#') {
1197                            Some((b, _)) => String::from(b),
1198                            None => cur,
1199                        };
1200                        let frag = new_val.trim_start_matches('#');
1201                        let full = alloc::format!("{}#{}", base, frag);
1202                        b.props
1203                            .insert(String::from("_pending_location").into(), Value::str(&full));
1204                        b.props
1205                            .insert(String::from("_pending_location_mode").into(), Value::str("hash"));
1206                    }
1207                    "pathname" | "search" => {
1208                        // protocol+host を保ったまま path / query を差し替える。
1209                        let proto = b
1210                            .props
1211                            .get("protocol")
1212                            .map(|v| v.to_js_string())
1213                            .unwrap_or_else(|| String::from("https:"));
1214                        let host = b
1215                            .props
1216                            .get("host")
1217                            .map(|v| v.to_js_string())
1218                            .unwrap_or_default();
1219                        let pathname = if key == "pathname" {
1220                            new_val.clone()
1221                        } else {
1222                            b.props
1223                                .get("pathname")
1224                                .map(|v| v.to_js_string())
1225                                .unwrap_or_else(|| String::from("/"))
1226                        };
1227                        let search = if key == "search" {
1228                            if new_val.is_empty() || new_val.starts_with('?') {
1229                                new_val.clone()
1230                            } else {
1231                                alloc::format!("?{}", new_val)
1232                            }
1233                        } else {
1234                            b.props
1235                                .get("search")
1236                                .map(|v| v.to_js_string())
1237                                .unwrap_or_default()
1238                        };
1239                        let full = alloc::format!("{}//{}{}{}", proto, host, pathname, search);
1240                        b.props
1241                            .insert(String::from("_pending_location").into(), Value::str(&full));
1242                        b.props
1243                            .insert(String::from("_pending_location_mode").into(), Value::str("assign"));
1244                    }
1245                    // `location.protocol`/`.host`/`.hostname`/`.port`への代入も実際に
1246                    // 実 URL では再ナビゲーションを発生させる仕様だが、`href`/`hash`/
1247                    // `pathname`/`search`だけがこの`match`で処理されており、この4つは
1248                    // 常に`_ => {}`(後段で見かけ上の`.props`値は更新されるが、
1249                    // `_pending_location`が積まれずナビゲーション要求にならない)に
1250                    // 落ちていた。`pathname`/`search`分岐と同じ「他のコンポーネントは
1251                    // 現在値を保ったまま、変更対象だけ差し替えてhrefを再構成する」
1252                    // パターンをそのまま適用する。
1253                    "protocol" | "host" | "hostname" | "port" => {
1254                        let proto = if key == "protocol" {
1255                            if new_val.ends_with(':') { new_val.clone() } else { alloc::format!("{}:", new_val) }
1256                        } else {
1257                            b.props.get("protocol").map(|v| v.to_js_string()).unwrap_or_else(|| String::from("https:"))
1258                        };
1259                        let host = if key == "host" {
1260                            // `host`は`hostname`+`:`+`port`の合成値のため、`hostname`/
1261                            // `port`個別プロパティもここで分割して同期しておく(しないと
1262                            // `location.host='a.com:1'`の直後に`location.hostname`/
1263                            // `.port`を読んだ時だけ古い値のままという食い違いが起きる)。
1264                            let (hn, pt) = match new_val.split_once(':') {
1265                                Some((h, p)) => (String::from(h), String::from(p)),
1266                                None => (new_val.clone(), String::new()),
1267                            };
1268                            b.props.insert(String::from("hostname").into(), Value::str(&hn));
1269                            b.props.insert(String::from("port").into(), Value::str(&pt));
1270                            new_val.clone()
1271                        } else if key == "hostname" || key == "port" {
1272                            let hostname = if key == "hostname" {
1273                                new_val.clone()
1274                            } else {
1275                                b.props.get("hostname").map(|v| v.to_js_string()).unwrap_or_default()
1276                            };
1277                            let port = if key == "port" {
1278                                new_val.clone()
1279                            } else {
1280                                b.props.get("port").map(|v| v.to_js_string()).unwrap_or_default()
1281                            };
1282                            if port.is_empty() { hostname } else { alloc::format!("{}:{}", hostname, port) }
1283                        } else {
1284                            b.props.get("host").map(|v| v.to_js_string()).unwrap_or_default()
1285                        };
1286                        let pathname = b
1287                            .props
1288                            .get("pathname")
1289                            .map(|v| v.to_js_string())
1290                            .unwrap_or_else(|| String::from("/"));
1291                        let search = b.props.get("search").map(|v| v.to_js_string()).unwrap_or_default();
1292                        let full = alloc::format!("{}//{}{}{}", proto, host, pathname, search);
1293                        b.props
1294                            .insert(String::from("_pending_location").into(), Value::str(&full));
1295                        b.props
1296                            .insert(String::from("_pending_location_mode").into(), Value::str("assign"));
1297                    }
1298                    _ => {}
1299                }
1300                // href 等の見かけ上の値も更新しておく(同期読取のため)。
1301                if let Some(slot) = b.props.get_mut(key) {
1302                    *slot = val;
1303                } else {
1304                    let pk = match key_rc {
1305                        Some(rc) => rc.into(),
1306                        None => key.into(),
1307                    };
1308                    b.props.insert(pk, val);
1309                }
1310                return Ok(true);
1311            }
1312            let is_win = self.is_window_obj(o);
1313            let win_val = if is_win { Some(val.clone()) } else { None };
1314            if let Some(slot) = b.props.get_mut(key) {
1315                *slot = val;
1316            } else {
1317                let pk = match key_rc {
1318                    Some(rc) => rc.into(),
1319                    None => key.into(),
1320                };
1321                b.props.insert(pk, val);
1322            }
1323            drop(b);
1324            // `globalThis.x = v` が実際に書き込まれた場合のみ同じ名前のグローバル変数も同期する
1325            // (writable:false や sealed/non_extensible、トップレベルの let/const/class は上書きしない)。
1326            if let Some(v) = win_val {
1327                if !self.global_lexicals.borrow().contains(key) {
1328                    if let Some(slot) = self.global.borrow_mut().vars.get_mut(key) {
1329                        *slot = v;
1330                    }
1331                }
1332            }
1333        } else {
1334            return self.set_on_primitive(recv, key, val);
1335        }
1336        Ok(true)
1337    }
1338
1339    /// プリミティブ値への代入(OrdinarySet で receiver がオブジェクトでない場合)。原型連鎖に setter があれば `this` に
1340    /// そのプリミティブを渡して呼ぶ。それ以外は常に拒否(`Ok(false)`。strict では TypeError)。
1341    #[cold]
1342    #[inline(never)]
1343    fn set_on_primitive(&mut self, recv: &Value, key: &str, val: Value) -> Result<bool, Value> {
1344        let ctor = match recv {
1345            Value::Str(_) => "String",
1346            Value::Number(_) => "Number",
1347            Value::Bool(_) => "Boolean",
1348            Value::BigInt(_) => "BigInt",
1349            _ => return Ok(false),
1350        };
1351        let mut cur = super::super::builtins::global_ctor_proto(self, ctor);
1352        let mut guard = 0u32;
1353        while let Some(p) = cur {
1354            let setter = {
1355                let b = p.borrow();
1356                if b.has_accessor(key) {
1357                    Some(b.get_setter(key))
1358                } else if b.props.contains_key(key) {
1359                    return Ok(false);
1360                } else {
1361                    None
1362                }
1363            };
1364            if let Some(s) = setter {
1365                return match s {
1366                    Some(f) => {
1367                        self.call_value(&f, recv.clone(), &[val])?;
1368                        Ok(true)
1369                    }
1370                    None => Ok(false),
1371                };
1372            }
1373            guard += 1;
1374            if guard > 100 {
1375                break;
1376            }
1377            cur = p.borrow().proto.clone();
1378        }
1379        Ok(false)
1380    }
1381
1382    // ============ DOM プロキシのプロパティ ============
1383
1384}
1385
1386#[inline]
1387fn proto_has_accessor(proto: &Option<ObjRef>, key: &str) -> bool {
1388    let mut cur = proto.clone();
1389    let mut guard = 0u32;
1390    while let Some(p) = cur {
1391        let Ok(b) = p.try_borrow() else {
1392            return true;
1393        };
1394        if b.has_accessor(key)
1395            || matches!(b.kind, ObjKind::Proxy(_))
1396            || (matches!(&b.kind, ObjKind::Bytes(_))
1397                && b.props.contains_key("_ta_kind")
1398                && crate::os_lib::ecma::value::is_canonical_numeric_key(key))
1399        {
1400            return true;
1401        }
1402        guard += 1;
1403        if guard > 64 {
1404            return true;
1405        }
1406        cur = b.proto.clone();
1407    }
1408    false
1409}
1410
1411/// 式を短い文字列にする(エラーの発生箇所の表示用。識別子・メンバー・添字・呼び出しのみ)。
1412pub(crate) fn describe_expr(e: &crate::os_lib::ecma::ast::Expression) -> String {
1413    use crate::os_lib::ecma::ast::Expression as E;
1414    let s = match e {
1415        E::Identifier(n) => n.to_string(),
1416        E::This => String::from("this"),
1417        E::Member { object, property, .. } => alloc::format!("{}.{}", describe_expr(object), property),
1418        E::Index { object, .. } => alloc::format!("{}[…]", describe_expr(object)),
1419        E::Call { callee, .. } => alloc::format!("{}()", describe_expr(callee)),
1420        // 複合式も中身が分かるように(ミニファイされたコードの `(a=b.c)==null?…` 等)。
1421        E::Assign { op, target, value } => alloc::format!("({}{}{})", describe_expr(target), op, describe_expr(value)),
1422        E::Logical { left, right, .. } => alloc::format!("({}||&&{})", describe_expr(left), describe_expr(right)),
1423        E::Conditional { consequent, alternate, .. } => alloc::format!("(…?{}:{})", describe_expr(consequent), describe_expr(alternate)),
1424        E::Sequence(v) => match v.last() {
1425            Some(l) => alloc::format!("(…,{})", describe_expr(l)),
1426            None => String::from("…"),
1427        },
1428        _ => String::from("…"),
1429    };
1430    if s.chars().count() > 80 {
1431        let t: String = s.chars().rev().take(80).collect::<Vec<_>>().into_iter().rev().collect();
1432        alloc::format!("…{t}")
1433    } else {
1434        s
1435    }
1436}