Skip to main content

atmos/os_lib/ecma/interp/
bytecode.rs

1//! 関数本体のバイトコード(A1 の第 1 段階)。
2//!
3//! 構文木をたどる `eval`/`exec_stmt` の代わりに、平らな命令列をスタックで実行する。まだ対応していない
4//! 構文は [`Op::Eval`]・[`Op::Exec`] で構文木の評価へ戻すので、どの関数でも変換できる。意味は構文木の評価と
5//! 同じでなければならない(JS セルフテストが適合試験)。
6//!
7//! 命令が持つ構文木への生ポインタは [`Code::_ast`] が保持する本体の中を指す。`Code` が生きている間は
8//! 本体も生きていて、構文木は実行中に書き換わらない。
9
10use super::*;
11use crate::os_lib::ecma::host::HostKeys;
12use crate::os_lib::ecma::host::HostProbe;
13use crate::os_lib::ecma::ast::{BinaryOp, Pattern, UnaryOp};
14use core::cell::Cell;
15
16pub(crate) enum Op {
17    /// 定数を積む。
18    Const(u32),
19    This,
20    /// 変数を読む(`Expression::Identifier` と同じ)。2 つ目は `Code::slots` の番号。
21    Load(u32, u32),
22    Pop,
23    Binary(BinaryOp),
24    /// スタックの値が偽なら飛ぶ(値は取り除く)。
25    JumpIfFalse(u32),
26    Jump(u32),
27    /// `&&`: 偽なら値を残して飛ぶ。真なら取り除いて続ける。
28    AndKeep(u32),
29    /// `||`: 真なら値を残して飛ぶ。偽なら取り除いて続ける。
30    OrKeep(u32),
31    /// `??`: null/undefined でなければ値を残して飛ぶ。
32    NullishKeep(u32),
33    /// メンバー論理代入: `[obj, v]` で短絡なら `obj` を消して飛ぶ。短絡でないなら `v` を pop して `[obj]` で次へ。
34    AndKeepMember(u32),
35    OrKeepMember(u32),
36    NullishKeepMember(u32),
37    /// インデックス論理代入: `[obj, key, v]` で短絡なら `obj`, `key` を消して飛ぶ。短絡でないなら `v` を pop して `[obj, key]` で次へ。
38    AndKeepIndex(u32),
39    OrKeepIndex(u32),
40    NullishKeepIndex(u32),
41    /// `?.`: null/undefined なら undefined を積んでチェイン末尾へ飛ぶ。
42    JumpIfNullish(u32),
43    /// `?.(...)`(メソッド): func が null/undefined なら [func, this] を pop して undefined を積んで飛ぶ。
44    JumpIfNullishMethod(u32),
45    /// `obj.name`(1 つ目は名前の番号、2 つ目は構文木、3 つ目は `Code::prop_slots` の番号)。
46    Member(u32, *const Expression, u32),
47    /// `obj[key]`
48    Index,
49    /// `obj.name(...)` の呼び先: `obj` を取り、関数と `this` を積む。3 つ目は `Code::prop_slots` の番号。
50    Method(u32, *const Expression, u32),
51    /// `obj[key](...)` の呼び先。
52    MethodIndex,
53    /// 関数・`this`・引数をスタックから取って呼ぶ(式はエラーの文言用)。
54    Call(u32, *const Expression),
55    /// 関数・`this`・引数配列をスタックから取って呼ぶ(引数スプレッド対応)。
56    CallWithArgs(*const Expression),
57    /// `!x`
58    Not,
59    /// `-x`
60    Neg,
61    /// `+x`
62    Pos,
63    /// `~x`
64    BitNot,
65    /// `typeof expr`(識別子以外)
66    TypeOf,
67    /// `typeof ident`(未宣言でも例外にならない。1 つ目は名前の番号、2 つ目は `Code::slots` の番号)。
68    TypeofIdent(u32, u32),
69    /// `var name = value`(スタックの値を関数スコープへ束縛する)。
70    DeclVar(*const Pattern, u32),
71    /// `let/const name = value`(スタックの値を現在のスコープへ束縛する)。
72    DeclLexical(u32),
73    /// ブロックスコープに入る。
74    EnterBlock,
75    /// ブロックスコープから `n` 段出る。
76    LeaveBlocks(u32),
77    /// `for (let/const ...)` の反復の終わりに、クロージャに捕捉されていれば新しいスコープへ値を引き継ぐ。
78    RefreshForLet,
79    /// `name = value`(値は残す)。
80    StoreIdent(*const Expression, u32),
81    /// `name += value`(スタックの今の値と右辺を取り、結果を残す)。変数の文字列がほかから参照されていなければ末尾に足す。
82    AddAssignIdent(*const Expression, u32),
83    /// `obj.name = value`(スタックの `obj`, `value` を取り、`value` を残す)。
84    StoreMember(u32),
85    /// `obj[key] = value`(スタックの `obj`, `key`, `value` を取り、`value` を残す)。
86    StoreIndex,
87    /// スタックの先頭を複製する(`[..., a] -> [..., a, a]`)。
88    Dup,
89    /// スタックの先頭 2 個を複製する(`[..., a, b] -> [..., a, b, a, b]`)。
90    Dup2,
91    /// `name++` など。
92    UpdateIdent { name: u32, target: *const Expression, delta: f64, prefix: bool, slot: u32 },
93    /// `obj.name++` など。
94    UpdateMember { name: u32, object: *const Expression, delta: f64, prefix: bool, slot: u32 },
95    /// `obj[key]++` など。
96    UpdateIndex { delta: f64, prefix: bool },
97    /// `delete obj.name`
98    DeleteMember(u32),
99    /// `delete obj[key]`
100    DeleteIndex,
101    /// `[e1, e2, ...]`(要素数)。
102    Array(u32),
103    /// 空配列 `[]` の生成。
104    NewArray,
105    /// 配列末尾追加: `[arr, val] -> [arr]`
106    ArrayPush,
107    /// 配列スプレッド: `[arr, iter] -> [arr]`(iter の全要素を arr の末尾へ追加)
108    ArraySpread,
109    /// `{}` の生成。
110    NewObject,
111    /// オブジェクトリテラルの通常プロパティ設定(`[obj, val] -> [obj]`)。
112    InitProp(u32),
113    /// オブジェクトリテラルの算出プロパティ設定(`[obj, key, val] -> [obj]`)。
114    InitPropComputed,
115    /// オブジェクトスプレッド `{ ...src }`: `[obj, src] -> [obj]`
116    SpreadObject,
117    /// `new Callee(a1, a2, ...)`(引数個数)。
118    New(u32),
119    /// テンプレートリテラル `` `...${e1}...` ``(quasis へのポインタ、式の数)。
120    Template(*const Vec<String>, u32),
121    /// `switch` の `case`: スタックの `tv` を取り、先頭の `d` と `strict_eq` なら `d` も取って飛ぶ。
122    CaseEq(u32),
123    /// `for-in` / `for-of` の列挙配列と添字 `0` を積む(`true` なら `for-of`)。
124    IterInit(bool),
125    /// `IterInit` に、利用者定義の反復子(遅延反復と IteratorClose が要る)なら評価済みの値を木走査の for-of へ渡して
126    /// 飛び先 `exec` へ飛ぶ分岐を足したもの(Wave F)。
127    IterInitOrExec(bool, u32),
128    /// `for-in` / `for-of` の次の要素を取り出して変数に束縛する。終端なら `exit` へ飛ぶ。
129    IterNext { exit: u32, name: u32, slot: u32, is_lexical: bool },
130    /// `for-in` / `for-of` の次の要素を取り出してスタックへ積む(分割代入用)。終端なら `exit` へ飛ぶ。
131    IterNextPush { exit: u32, is_lexical: bool },
132    /// 分割代入パターン(`{ a, b }`, `[x, y]`)をスタックトップの値から束縛する(`true` なら関数スコープ)。
133    BindPattern(*const Pattern, bool),
134    /// `try` ブロック開始(例外発生時の `catch` 飛び先)。
135    EnterTry(u32),
136    /// `try` ブロック正常脱出(`n` 段のハンドラを外す)。
137    LeaveTry(u32),
138    /// `catch (e)` の例外値を現在のスコープへ束縛する。
139    CatchParam(u32),
140    /// `new.target` をスタックへ積む。
141    NewTarget,
142    /// 関数式・アロー関数式(クロージャ)を生成してスタックへ積む。
143    Closure(*const Expression),
144    /// 正規表現リテラルを生成してスタックへ積む。
145    Regex(*const (String, String)),
146    Return,
147    ReturnUndefined,
148    /// `throw expr`
149    Throw,
150    /// 式を構文木のまま評価して積む。
151    Eval(*const Expression),
152    /// 文を構文木のまま実行する。`break`・`continue` は囲むループの飛び先へ。
153    Exec {
154        stmt: *const Statement,
155        brk: u32,
156        cont: u32,
157        brk_depth: u16,
158        cont_depth: u16,
159        brk_try: u16,
160        cont_try: u16,
161        brk_iters: u16,
162        cont_iters: u16,
163        /// `Code::exec_labels` の番号(ラベル付き `break`/`continue` の飛び先の表。無ければ `NO_LOOP`)。
164        lbls: u32,
165    },
166}
167
168/// `Op::Exec` の文の中から出るラベル付き `break label` / `continue label` の飛び先(外側のラベル付きループ/ブロック)。
169struct ExecLabel {
170    label: Rc<str>,
171    loop_idx: usize,
172    is_loop: bool,
173    brk: u32,
174    cont: u32,
175    brk_depth: u16,
176    cont_depth: u16,
177    brk_try: u16,
178    cont_try: u16,
179    iters: u16,
180}
181
182/// ループの外を表す飛び先。
183const NO_LOOP: u32 = u32::MAX;
184
185/// 変数の場所の覚え(A1 の段階 1)。何段外のスコープの何番目か。
186///
187/// スコープの連なりは字句の構造で決まるので、同じ命令なら場所は変わらない。名前の検索を省くのが
188/// 目的で、圧縮された JS の深い閉包では外側の変数の検索が実行時間の約 1 割を占めていた。`key` は
189/// 束縛の名前の番地で、その場所に同じ束縛があることの確認に使う。
190/// 外れるのは、読んだ後で内側に同名の `let` が宣言される場合だけで、これは本来 TDZ のエラーになる。
191pub(crate) struct Slot {
192    hops: Cell<u32>,
193    index: Cell<u32>,
194    key: Cell<*const u8>,
195}
196
197impl Slot {
198    /// 覚えた場所の値を読み書きする。
199    #[inline(always)]
200    fn with<R>(&self, scope: &Rc<RefCell<Scope>>, f: impl FnOnce(&mut Value) -> R) -> Option<R> {
201        let key = self.key.get();
202        if key.is_null() {
203            return None;
204        }
205        let mut cur = scope.as_ptr();
206        // SAFETY: `scope` が親の連なりを保持している。ここではスコープを書き換えず、値の参照は `f` の
207        // 間だけ使う。`f` は値を読むか置き換えるだけで JS を実行しない(前の値の解放を除く)。
208        unsafe {
209            for _ in 0..self.hops.get() {
210                cur = (*cur).parent.as_ref()?.as_ptr();
211            }
212            let v = (*cur).vars.entry_at_mut(self.index.get() as usize, key)?;
213            Some(f(v))
214        }
215    }
216
217    /// 覚えた場所の値を読み書きし、そのスコープがグローバルルート(`parent.is_none()`)かも返す。
218    #[inline(always)]
219    fn with_is_global<R>(&self, scope: &Rc<RefCell<Scope>>, f: impl FnOnce(&mut Value) -> R) -> Option<(R, bool)> {
220        let key = self.key.get();
221        if key.is_null() {
222            return None;
223        }
224        let mut cur = scope.as_ptr();
225        // SAFETY: `with` と同じ。
226        unsafe {
227            for _ in 0..self.hops.get() {
228                cur = (*cur).parent.as_ref()?.as_ptr();
229            }
230            let is_global = (*cur).parent.is_none();
231            let v = (*cur).vars.entry_at_mut(self.index.get() as usize, key)?;
232            Some((f(v), is_global))
233        }
234    }
235
236    /// 場所を探して覚える。
237    #[inline(never)]
238    fn learn(&self, name: &str, scope: &Rc<RefCell<Scope>>) {
239        let mut cur = scope.clone();
240        let mut hops = 0;
241        loop {
242            let next = {
243                let b = cur.borrow();
244                if b.with_obj.is_some() {
245                    return;
246                }
247                if let Some(i) = b.vars.position_of(name) {
248                    self.hops.set(hops);
249                    self.index.set(i as u32);
250                    self.key.set(b.vars.entry_at(i).map_or(core::ptr::null(), |(k, _)| k.as_ptr()));
251                    return;
252                }
253                b.parent.clone()
254            };
255            match next {
256                Some(p) => cur = p,
257                None => return,
258            }
259            hops += 1;
260        }
261    }
262}
263
264/// プロパティ参照の場所の覚え(A1 の段階 2: インラインキャッシュ)。
265///
266/// `obj.name` において、直前に見つかったオブジェクト(自身 `hops == 0` またはプロトタイプ連鎖先 `hops >= 1`)の
267/// `props` 内の添字(挿入順の位置)を記憶する。
268/// 同じ形状のオブジェクトや同じクラスのインスタンスを繰り返し走査するループでは、ハッシュ計算や線形探索・
269/// プロトタイプ連鎖走査をスキップして O(1) で即座に値やメソッドを取り出す。
270/// インラインキャッシュ(IC)の1スロットエントリ。
271#[derive(Clone, Copy)]
272struct PropSlotEntry {
273    index: u32,
274    hops: u8,
275    holder: *const RefCell<Obj>,
276}
277
278impl PropSlotEntry {
279    const UNSET: Self = Self {
280        index: u32::MAX,
281        hops: 0,
282        holder: core::ptr::null(),
283    };
284
285    #[inline(always)]
286    fn is_set(&self) -> bool {
287        self.index != u32::MAX
288    }
289}
290
291/// プロパティ参照の場所の覚え(A1 の段階 2: 2態インラインキャッシュ Bimorphic IC)。
292///
293/// `obj.name` において、直前に見つかったオブジェクト(自身 `hops == 0` またはプロトタイプ連鎖先 `hops >= 1`)の
294/// `props` 内の添字(挿入順の位置)を記憶する。
295/// 2つのスロット(`slot0`, `slot1`)を持ち、ループ内で2種類の異なるオブジェクト構造が交互に現れても
296/// キャッシュスラッシングを起こさず O(1) で即座に値やメソッドを取り出す。
297pub(crate) struct PropSlot {
298    slot0: Cell<PropSlotEntry>,
299    slot1: Cell<PropSlotEntry>,
300}
301
302impl PropSlot {
303    pub const UNSET: u32 = u32::MAX;
304
305    #[inline(always)]
306    fn new() -> Self {
307        Self {
308            slot0: Cell::new(PropSlotEntry::UNSET),
309            slot1: Cell::new(PropSlotEntry::UNSET),
310        }
311    }
312
313    #[inline(always)]
314    fn set_own(&self, idx: usize) {
315        let cur0 = self.slot0.get();
316        let new_entry = PropSlotEntry {
317            index: idx as u32,
318            hops: 0,
319            holder: core::ptr::null(),
320        };
321        if cur0.index == new_entry.index && cur0.hops == 0 && cur0.holder.is_null() {
322            return;
323        }
324        self.slot1.set(cur0);
325        self.slot0.set(new_entry);
326    }
327
328    #[inline(always)]
329    fn set_proto(&self, hops: u8, holder: *const RefCell<Obj>, idx: usize) {
330        let cur0 = self.slot0.get();
331        let new_entry = PropSlotEntry {
332            index: idx as u32,
333            hops,
334            holder,
335        };
336        if cur0.index == new_entry.index && cur0.hops == hops && cur0.holder == holder {
337            return;
338        }
339        self.slot1.set(cur0);
340        self.slot0.set(new_entry);
341    }
342}
343
344/// 複合代入の演算子。論理代入(`&&=` など)は `None`。
345fn compound_op(op: &str) -> Option<BinaryOp> {
346    Some(match op {
347        "+=" => BinaryOp::Add,
348        "-=" => BinaryOp::Sub,
349        "*=" => BinaryOp::Mul,
350        "/=" => BinaryOp::Div,
351        "%=" => BinaryOp::Mod,
352        "**=" => BinaryOp::Pow,
353        "&=" => BinaryOp::BitAnd,
354        "|=" => BinaryOp::BitOr,
355        "^=" => BinaryOp::BitXor,
356        "<<=" => BinaryOp::Shl,
357        ">>=" => BinaryOp::Shr,
358        ">>>=" => BinaryOp::UShr,
359        _ => return None,
360    })
361}
362
363/// 両辺が数値の演算の近道。
364#[inline(always)]
365fn number_binary(op: &BinaryOp, a: f64, b: f64) -> Option<Value> {
366    Some(match op {
367        BinaryOp::Add => Value::Number(a + b),
368        BinaryOp::Sub => Value::Number(a - b),
369        BinaryOp::Mul => Value::Number(a * b),
370        BinaryOp::Div => Value::Number(a / b),
371        BinaryOp::Mod => Value::Number(if b == 0.0 { f64::NAN } else { a % b }),
372        BinaryOp::Lt => Value::Bool(a < b),
373        BinaryOp::Gt => Value::Bool(a > b),
374        BinaryOp::LtEq => Value::Bool(a <= b),
375        BinaryOp::GtEq => Value::Bool(a >= b),
376        BinaryOp::Eq | BinaryOp::StrictEq => Value::Bool(a == b),
377        BinaryOp::NotEq | BinaryOp::StrictNotEq => Value::Bool(a != b),
378        BinaryOp::BitAnd => Value::Number((to_i32(a) & to_i32(b)) as f64),
379        BinaryOp::BitOr => Value::Number((to_i32(a) | to_i32(b)) as f64),
380        BinaryOp::BitXor => Value::Number((to_i32(a) ^ to_i32(b)) as f64),
381        BinaryOp::Shl => Value::Number((to_i32(a).wrapping_shl(to_u32(b) & 31)) as f64),
382        BinaryOp::Shr => Value::Number((to_i32(a).wrapping_shr(to_u32(b) & 31)) as f64),
383        BinaryOp::UShr => Value::Number((to_u32(a).wrapping_shr(to_u32(b) & 31)) as f64),
384        _ => return None,
385    })
386}
387
388pub struct Code {
389    ops: Vec<Op>,
390    consts: Vec<Value>,
391    names: Vec<Rc<str>>,
392    slots: Vec<Slot>,
393    prop_slots: Vec<PropSlot>,
394    exec_labels: Vec<Vec<ExecLabel>>,
395    /// 命令のポインタが指す構文木。
396    _ast: Rc<Vec<Statement>>,
397}
398
399/// ループ(または `switch`・ラベル付きブロック)の `break`・`continue` の飛び先(確定までは後で書き換える命令の番号を集める)。
400#[derive(Default)]
401struct LoopCtx {
402    breaks: Vec<usize>,
403    continues: Vec<usize>,
404    /// このループ/ブロックに付与されたラベル一覧。
405    labels: Vec<Rc<str>>,
406    /// ループ本体に入った時点の `block_depth`(`for (let ...)` のスコープを含む)。
407    block_depth: u32,
408    /// ループ本体に入った時点の `try_depth`。
409    try_depth: u32,
410    /// ループ本体に入った時点の `iter_depth`(`for-in` / `for-of` の反復スタック段数)。
411    iter_depth: u32,
412    /// `switch` 文か(`break` はここへ飛ぶが、`continue` は外側のループへ飛ぶ)。
413    is_switch: bool,
414    /// ラベル付き非ループ文か(ラベルなし `break` / `continue` はここを素通りし、ラベル指定 `break label` のみここへ飛ぶ)。
415    is_labeled_block: bool,
416}
417
418struct PendingExec {
419    at: usize,
420    brk_loop: Option<usize>,
421    cont_loop: Option<usize>,
422}
423
424struct TryCtx {
425    catch_pc: u32,
426    block_depth: u32,
427    stack_len: usize,
428}
429
430struct Compiler {
431    ops: Vec<Op>,
432    consts: Vec<Value>,
433    names: Vec<Rc<str>>,
434    slots: Vec<Slot>,
435    prop_slots: Vec<PropSlot>,
436    loops: Vec<LoopCtx>,
437    /// 直後のループまたはブロックに引き継ぐラベル一覧。
438    pending_labels: Vec<Rc<str>>,
439    /// 現在の字句ブロックスコープの入れ子段数。
440    block_depth: u32,
441    /// 現在の `try` ブロックの入れ子段数。
442    try_depth: u32,
443    /// 現在の `for-in` / `for-of` イテレータ(1段につき `vm_stack` 2要素)の入れ子段数。
444    iter_depth: u32,
445    /// 実行時に囲むループの飛び先を持つ `Exec`。
446    pending_exec: Vec<PendingExec>,
447    /// `Exec` ごとの、外側のラベル付きループ/ブロックへの飛び先の表。
448    exec_labels: Vec<Vec<ExecLabel>>,
449}
450
451/// `a.b.c` の形(`?.` を含まない)か。含むと途中で打ち切る `eval_chain_object` の経路が要る。
452fn plain_object(e: &Expression) -> bool {
453    match e {
454        Expression::Super => false,
455        Expression::Member { object, property, optional } => {
456            !*optional && !property.starts_with('#') && plain_object(object)
457        }
458        Expression::Index { object, optional, .. } => !*optional && plain_object(object),
459        Expression::Call { callee, optional, .. } => !*optional && plain_object(callee),
460        _ => true,
461    }
462}
463
464enum ChainOp<'a> {
465    Member {
466        property: &'a Rc<str>,
467        optional: bool,
468        orig_expr: *const Expression,
469    },
470    Index {
471        index: &'a Expression,
472        optional: bool,
473    },
474    Call {
475        arguments: &'a [Expression],
476        optional: bool,
477        orig_callee: *const Expression,
478    },
479}
480
481fn unroll_chain<'a>(mut e: &'a Expression, ops: &mut Vec<ChainOp<'a>>) -> Option<&'a Expression> {
482    loop {
483        match e {
484            Expression::Member { object, property, optional } => {
485                if matches!(**object, Expression::Super) || property.starts_with('#') {
486                    return None;
487                }
488                ops.push(ChainOp::Member {
489                    property,
490                    optional: *optional,
491                    orig_expr: &**object as *const Expression,
492                });
493                e = object;
494            }
495            Expression::Index { object, index, optional } => {
496                if matches!(**object, Expression::Super) {
497                    return None;
498                }
499                ops.push(ChainOp::Index {
500                    index,
501                    optional: *optional,
502                });
503                e = object;
504            }
505            Expression::Call { callee, arguments, optional } => {
506                if matches!(**callee, Expression::Super) {
507                    return None;
508                }
509                if let Expression::Identifier(n) = &**callee {
510                    if &**n == "eval" {
511                        return None;
512                    }
513                }
514                ops.push(ChainOp::Call {
515                    arguments,
516                    optional: *optional,
517                    orig_callee: &**callee as *const Expression,
518                });
519                e = callee;
520            }
521            _ => break,
522        }
523    }
524    if matches!(e, Expression::Super) {
525        return None;
526    }
527    ops.reverse();
528    Some(e)
529}
530
531impl Compiler {
532    fn name(&mut self, n: &Rc<str>) -> u32 {
533        self.names.push(n.clone());
534        (self.names.len() - 1) as u32
535    }
536
537    fn slot(&mut self) -> u32 {
538        self.slots.push(Slot { hops: Cell::new(0), index: Cell::new(0), key: Cell::new(core::ptr::null()) });
539        (self.slots.len() - 1) as u32
540    }
541
542    fn prop_slot(&mut self) -> u32 {
543        self.prop_slots.push(PropSlot::new());
544        (self.prop_slots.len() - 1) as u32
545    }
546
547    fn load(&mut self, n: &Rc<str>) {
548        let i = self.name(n);
549        let slot = self.slot();
550        self.ops.push(Op::Load(i, slot));
551    }
552
553    fn constant(&mut self, v: Value) {
554        self.consts.push(v);
555        self.ops.push(Op::Const((self.consts.len() - 1) as u32));
556    }
557
558    /// 飛び先が未定の命令を置く。
559    fn emit_jump(&mut self, op: Op) -> usize {
560        self.ops.push(op);
561        self.ops.len() - 1
562    }
563
564    fn patch(&mut self, at: usize) {
565        let to = self.ops.len() as u32;
566        self.patch_to(at, to);
567    }
568
569    fn patch_to(&mut self, at: usize, to: u32) {
570        if let Some(
571            Op::JumpIfFalse(t)
572            | Op::Jump(t)
573            | Op::AndKeep(t)
574            | Op::OrKeep(t)
575            | Op::NullishKeep(t)
576            | Op::AndKeepMember(t)
577            | Op::OrKeepMember(t)
578            | Op::NullishKeepMember(t)
579            | Op::AndKeepIndex(t)
580            | Op::OrKeepIndex(t)
581            | Op::NullishKeepIndex(t)
582            | Op::JumpIfNullish(t)
583            | Op::JumpIfNullishMethod(t)
584            | Op::CaseEq(t)
585            | Op::IterNext { exit: t, .. }
586            | Op::IterNextPush { exit: t, .. }
587            | Op::IterInitOrExec(_, t)
588            | Op::EnterTry(t),
589        ) = self.ops.get_mut(at)
590        {
591            *t = to;
592        }
593    }
594
595    fn emit_call_args(&mut self, arguments: &[Expression], orig_callee: *const Expression) {
596        if !arguments.iter().any(|a| matches!(a, Expression::Spread(_))) {
597            for a in arguments {
598                self.expr(a);
599            }
600            self.ops.push(Op::Call(arguments.len() as u32, orig_callee));
601        } else {
602            self.ops.push(Op::NewArray);
603            for a in arguments {
604                if let Expression::Spread(inner) = a {
605                    self.expr(inner);
606                    self.ops.push(Op::ArraySpread);
607                } else {
608                    self.expr(a);
609                    self.ops.push(Op::ArrayPush);
610                }
611            }
612            self.ops.push(Op::CallWithArgs(orig_callee));
613        }
614    }
615
616    fn compile_chain(&mut self, e: &Expression) -> bool {
617        let mut chain = Vec::new();
618        let Some(base) = unroll_chain(e, &mut chain) else {
619            return false;
620        };
621        if chain.is_empty() {
622            return false;
623        }
624
625        self.expr(base);
626
627        let mut jumps: Vec<usize> = Vec::new();
628
629        let mut i = 0;
630        while i < chain.len() {
631            match &chain[i] {
632                ChainOp::Member { property, optional, orig_expr } => {
633                    if *optional {
634                        jumps.push(self.emit_jump(Op::JumpIfNullish(0)));
635                    }
636                    if i + 1 < chain.len() {
637                        if let ChainOp::Call { arguments, optional: call_opt, orig_callee } = &chain[i + 1] {
638                            let prop_idx = self.name(property);
639                            let slot = self.prop_slot();
640                            self.ops.push(Op::Method(prop_idx, *orig_expr, slot));
641                            if *call_opt {
642                                jumps.push(self.emit_jump(Op::JumpIfNullishMethod(0)));
643                            }
644                            self.emit_call_args(arguments, *orig_callee);
645                            i += 2;
646                            continue;
647                        }
648                    }
649                    let prop_idx = self.name(property);
650                    let slot = self.prop_slot();
651                    self.ops.push(Op::Member(prop_idx, *orig_expr, slot));
652                    i += 1;
653                }
654                ChainOp::Index { index, optional } => {
655                    if *optional {
656                        jumps.push(self.emit_jump(Op::JumpIfNullish(0)));
657                    }
658                    if i + 1 < chain.len() {
659                        if let ChainOp::Call { arguments, optional: call_opt, orig_callee } = &chain[i + 1] {
660                            self.expr(index);
661                            self.ops.push(Op::MethodIndex);
662                            if *call_opt {
663                                jumps.push(self.emit_jump(Op::JumpIfNullishMethod(0)));
664                            }
665                            self.emit_call_args(arguments, *orig_callee);
666                            i += 2;
667                            continue;
668                        }
669                    }
670                    self.expr(index);
671                    self.ops.push(Op::Index);
672                    i += 1;
673                }
674                ChainOp::Call { arguments, optional, orig_callee } => {
675                    if *optional {
676                        jumps.push(self.emit_jump(Op::JumpIfNullish(0)));
677                    }
678                    self.constant(Value::Undefined);
679                    self.emit_call_args(arguments, *orig_callee);
680                    i += 1;
681                }
682            }
683        }
684
685        for j in jumps {
686            self.patch(j);
687        }
688
689        true
690    }
691
692    fn expr(&mut self, e: &Expression) {
693        match e {
694            Expression::Number(n) => self.constant(Value::Number(*n)),
695            Expression::BigIntLit(s) => match super::super::bigint::BigInt::parse_str(s) {
696                Some(b) => self.constant(Value::bigint(b)),
697                None => self.ops.push(Op::Eval(e)),
698            },
699            Expression::Str(s) => self.constant(Value::str(s.clone())),
700            Expression::Bool(b) => self.constant(Value::Bool(*b)),
701            Expression::Null => self.constant(Value::Null),
702            Expression::Undefined => self.constant(Value::Undefined),
703            Expression::Elision => self.constant(Value::Undefined),
704            Expression::This => self.ops.push(Op::This),
705            Expression::NewTarget => self.ops.push(Op::NewTarget),
706            Expression::Function { .. } => self.ops.push(Op::Closure(e as *const Expression)),
707            Expression::Regex(lit) => self.ops.push(Op::Regex(&**lit as *const (String, String))),
708            Expression::Identifier(n) => {
709                self.load(n);
710            }
711            Expression::TemplateLiteral { quasis, exprs } => {
712                for ex in exprs.iter() {
713                    self.expr(ex);
714                }
715                self.ops.push(Op::Template(&**quasis as *const Vec<String>, exprs.len() as u32));
716            }
717            // 穴のある配列リテラルは構文木の評価に任せる(穴の印を付けるのはそちら)。
718            Expression::Array(items) if items.iter().any(|it| matches!(it, Expression::Elision)) => {
719                self.ops.push(Op::Eval(e));
720            }
721            Expression::Array(items) => {
722                if !items.iter().any(|it| matches!(it, Expression::Spread(_))) {
723                    for it in items {
724                        self.expr(it);
725                    }
726                    self.ops.push(Op::Array(items.len() as u32));
727                } else {
728                    self.ops.push(Op::NewArray);
729                    for it in items {
730                        if let Expression::Spread(inner) = it {
731                            self.expr(inner);
732                            self.ops.push(Op::ArraySpread);
733                        } else {
734                            self.expr(it);
735                            self.ops.push(Op::ArrayPush);
736                        }
737                    }
738                }
739            }
740            Expression::Object(props)
741                if props.iter().all(|p| {
742                    p.accessor.is_none() && !(p.computed.is_none() && &*p.key == "__proto__")
743                }) =>
744            {
745                self.ops.push(Op::NewObject);
746                for p in props {
747                    if &*p.key == OBJECT_SPREAD_KEY {
748                        self.expr(&p.value);
749                        self.ops.push(Op::SpreadObject);
750                    } else if let Some(ce) = &p.computed {
751                        self.expr(ce);
752                        self.expr(&p.value);
753                        self.ops.push(Op::InitPropComputed);
754                    } else {
755                        self.expr(&p.value);
756                        let i = self.name(&p.key);
757                        self.ops.push(Op::InitProp(i));
758                    }
759                }
760            }
761            Expression::New { callee, arguments }
762                if !arguments.iter().any(|a| matches!(a, Expression::Spread(_))) =>
763            {
764                self.expr(callee);
765                for a in arguments {
766                    self.expr(a);
767                }
768                self.ops.push(Op::New(arguments.len() as u32));
769            }
770            Expression::Binary { op, left, right } => {
771                // `#x in obj` は左辺を評価しない。
772                let private = matches!(&**left, Expression::Identifier(n) if n.starts_with('#'));
773                if matches!(op, BinaryOp::In) && private {
774                    self.ops.push(Op::Eval(e));
775                    return;
776                }
777                self.expr(left);
778                self.expr(right);
779                self.ops.push(Op::Binary(op.clone()));
780            }
781            Expression::Logical { op, left, right } => {
782                self.expr(left);
783                let j = self.emit_jump(match op {
784                    LogicalOp::And => Op::AndKeep(0),
785                    LogicalOp::Or => Op::OrKeep(0),
786                    LogicalOp::Nullish => Op::NullishKeep(0),
787                });
788                self.expr(right);
789                self.patch(j);
790            }
791            Expression::Unary { op: UnaryOp::Not, expr } => {
792                self.expr(expr);
793                self.ops.push(Op::Not);
794            }
795            Expression::Unary { op: UnaryOp::Neg, expr } => {
796                self.expr(expr);
797                self.ops.push(Op::Neg);
798            }
799            Expression::Unary { op: UnaryOp::Pos, expr } => {
800                self.expr(expr);
801                self.ops.push(Op::Pos);
802            }
803            Expression::Unary { op: UnaryOp::BitNot, expr } => {
804                self.expr(expr);
805                self.ops.push(Op::BitNot);
806            }
807            Expression::Unary { op: UnaryOp::Void, expr } => {
808                if !matches!(
809                    **expr,
810                    Expression::Number(_)
811                        | Expression::Str(_)
812                        | Expression::Bool(_)
813                        | Expression::Null
814                        | Expression::Undefined
815                        | Expression::Elision
816                ) {
817                    self.expr(expr);
818                    self.ops.push(Op::Pop);
819                }
820                self.constant(Value::Undefined);
821            }
822            Expression::Unary { op: UnaryOp::TypeOf, expr } => {
823                if let Expression::Identifier(n) = &**expr {
824                    let i = self.name(n);
825                    let slot = self.slot();
826                    self.ops.push(Op::TypeofIdent(i, slot));
827                } else {
828                    self.expr(expr);
829                    self.ops.push(Op::TypeOf);
830                }
831            }
832            Expression::Unary { op: UnaryOp::Delete, expr }
833                if matches!(
834                    &**expr,
835                    Expression::Member { object, optional: false, .. } if plain_object(object)
836                ) =>
837            {
838                if let Expression::Member { object, property, .. } = &**expr {
839                    self.expr(object);
840                    let i = self.name(property);
841                    self.ops.push(Op::DeleteMember(i));
842                }
843            }
844            Expression::Unary { op: UnaryOp::Delete, expr }
845                if matches!(
846                    &**expr,
847                    Expression::Index { object, optional: false, .. } if plain_object(object)
848                ) =>
849            {
850                if let Expression::Index { object, index, .. } = &**expr {
851                    self.expr(object);
852                    self.expr(index);
853                    self.ops.push(Op::DeleteIndex);
854                }
855            }
856            Expression::Call { .. } | Expression::Member { .. } | Expression::Index { .. } => {
857                if !self.compile_chain(e) {
858                    self.ops.push(Op::Eval(e));
859                }
860            }
861            Expression::Conditional { test, consequent, alternate } => {
862                self.expr(test);
863                let else_at = self.emit_jump(Op::JumpIfFalse(0));
864                self.expr(consequent);
865                let end = self.emit_jump(Op::Jump(0));
866                self.patch(else_at);
867                self.expr(alternate);
868                self.patch(end);
869            }
870            Expression::Sequence(items) if !items.is_empty() => {
871                for (i, item) in items.iter().enumerate() {
872                    self.expr(item);
873                    if i + 1 < items.len() {
874                        self.ops.push(Op::Pop);
875                    }
876                }
877            }
878            Expression::Assign { op, target, value }
879                if *op == "=" && matches!(**target, Expression::Identifier(_)) =>
880            {
881                self.expr(value);
882                let slot = self.slot();
883                self.ops.push(Op::StoreIdent(&**target, slot));
884            }
885            Expression::Assign { op, target, value } if matches!(**target, Expression::Identifier(_)) => {
886                match (compound_op(op), *op, &**target) {
887                    // 現在の値は右辺より先に読む。
888                    (Some(BinaryOp::Add), _, Expression::Identifier(n)) => {
889                        self.load(n);
890                        self.expr(value);
891                        let slot = self.slot();
892                        self.ops.push(Op::AddAssignIdent(&**target, slot));
893                    }
894                    (Some(bop), _, Expression::Identifier(n)) => {
895                        self.load(n);
896                        self.expr(value);
897                        self.ops.push(Op::Binary(bop));
898                        let slot = self.slot();
899                        self.ops.push(Op::StoreIdent(&**target, slot));
900                    }
901                    (None, "&&=" | "||=" | "??=", Expression::Identifier(n)) => {
902                        self.load(n);
903                        let j = self.emit_jump(match *op {
904                            "&&=" => Op::AndKeep(0),
905                            "||=" => Op::OrKeep(0),
906                            _ => Op::NullishKeep(0),
907                        });
908                        self.expr(value);
909                        let slot = self.slot();
910                        self.ops.push(Op::StoreIdent(&**target, slot));
911                        self.patch(j);
912                    }
913                    _ => self.ops.push(Op::Eval(e)),
914                }
915            }
916            Expression::Assign { op, target, value }
917                if *op == "="
918                    && matches!(
919                        &**target,
920                        Expression::Member { object, property, optional: false }
921                            if !property.starts_with('#') && plain_object(object)
922                    ) =>
923            {
924                if let Expression::Member { object, property, .. } = &**target {
925                    self.expr(object);
926                    self.expr(value);
927                    let i = self.name(property);
928                    self.ops.push(Op::StoreMember(i));
929                }
930            }
931            Expression::Assign { op, target, value }
932                if compound_op(op).is_some()
933                    && matches!(
934                        &**target,
935                        Expression::Member { object, property, optional: false }
936                            if !property.starts_with('#') && plain_object(object)
937                    ) =>
938            {
939                if let (Some(bop), Expression::Member { object, property, .. }) = (compound_op(op), &**target) {
940                    self.expr(object);
941                    self.ops.push(Op::Dup);
942                    let i = self.name(property);
943                    let slot = self.prop_slot();
944                    self.ops.push(Op::Member(i, &**object, slot));
945                    self.expr(value);
946                    self.ops.push(Op::Binary(bop));
947                    let store_name = self.name(property);
948                    self.ops.push(Op::StoreMember(store_name));
949                }
950            }
951            Expression::Assign { op, target, value }
952                if matches!(*op, "&&=" | "||=" | "??=")
953                    && matches!(
954                        &**target,
955                        Expression::Member { object, property, optional: false }
956                            if !property.starts_with('#') && plain_object(object)
957                    ) =>
958            {
959                if let Expression::Member { object, property, .. } = &**target {
960                    self.expr(object);
961                    self.ops.push(Op::Dup);
962                    let i = self.name(property);
963                    let slot = self.prop_slot();
964                    self.ops.push(Op::Member(i, &**object, slot));
965                    let j = self.emit_jump(match *op {
966                        "&&=" => Op::AndKeepMember(0),
967                        "||=" => Op::OrKeepMember(0),
968                        _ => Op::NullishKeepMember(0),
969                    });
970                    self.expr(value);
971                    let store_name = self.name(property);
972                    self.ops.push(Op::StoreMember(store_name));
973                    self.patch(j);
974                }
975            }
976            Expression::Assign { op, target, value }
977                if *op == "="
978                    && matches!(
979                        &**target,
980                        Expression::Index { object, optional: false, .. } if plain_object(object)
981                    ) =>
982            {
983                if let Expression::Index { object, index, .. } = &**target {
984                    self.expr(object);
985                    self.expr(index);
986                    self.expr(value);
987                    self.ops.push(Op::StoreIndex);
988                }
989            }
990            Expression::Assign { op, target, value }
991                if compound_op(op).is_some()
992                    && matches!(
993                        &**target,
994                        Expression::Index { object, optional: false, .. } if plain_object(object)
995                    ) =>
996            {
997                if let (Some(bop), Expression::Index { object, index, .. }) = (compound_op(op), &**target) {
998                    self.expr(object);
999                    self.expr(index);
1000                    self.ops.push(Op::Dup2);
1001                    self.ops.push(Op::Index);
1002                    self.expr(value);
1003                    self.ops.push(Op::Binary(bop));
1004                    self.ops.push(Op::StoreIndex);
1005                }
1006            }
1007            Expression::Assign { op, target, value }
1008                if matches!(*op, "&&=" | "||=" | "??=")
1009                    && matches!(
1010                        &**target,
1011                        Expression::Index { object, optional: false, .. } if plain_object(object)
1012                    ) =>
1013            {
1014                if let Expression::Index { object, index, .. } = &**target {
1015                    self.expr(object);
1016                    self.expr(index);
1017                    self.ops.push(Op::Dup2);
1018                    self.ops.push(Op::Index);
1019                    let j = self.emit_jump(match *op {
1020                        "&&=" => Op::AndKeepIndex(0),
1021                        "||=" => Op::OrKeepIndex(0),
1022                        _ => Op::NullishKeepIndex(0),
1023                    });
1024                    self.expr(value);
1025                    self.ops.push(Op::StoreIndex);
1026                    self.patch(j);
1027                }
1028            }
1029            Expression::Update { op, prefix, target } if matches!(**target, Expression::Identifier(_)) => {
1030                if let Expression::Identifier(n) = &**target {
1031                    let name = self.name(n);
1032                    let delta = if *op == "++" { 1.0 } else { -1.0 };
1033                    let slot = self.slot();
1034                    self.ops.push(Op::UpdateIdent { name, target: &**target, delta, prefix: *prefix, slot });
1035                }
1036            }
1037            Expression::Update { op, prefix, target }
1038                if matches!(
1039                    &**target,
1040                    Expression::Member { object, property, optional: false }
1041                        if !property.starts_with('#') && plain_object(object)
1042                ) =>
1043            {
1044                if let Expression::Member { object, property, .. } = &**target {
1045                    self.expr(object);
1046                    let name = self.name(property);
1047                    let delta = if *op == "++" { 1.0 } else { -1.0 };
1048                    let slot = self.prop_slot();
1049                    self.ops.push(Op::UpdateMember {
1050                        name,
1051                        object: &**object,
1052                        delta,
1053                        prefix: *prefix,
1054                        slot,
1055                    });
1056                }
1057            }
1058            Expression::Update { op, prefix, target }
1059                if matches!(
1060                    &**target,
1061                    Expression::Index { object, optional: false, .. } if plain_object(object)
1062                ) =>
1063            {
1064                if let Expression::Index { object, index, .. } = &**target {
1065                    self.expr(object);
1066                    self.expr(index);
1067                    let delta = if *op == "++" { 1.0 } else { -1.0 };
1068                    self.ops.push(Op::UpdateIndex { delta, prefix: *prefix });
1069                }
1070            }
1071            _ => self.ops.push(Op::Eval(e)),
1072        }
1073    }
1074
1075    fn exec_fallback(&mut self, s: &Statement) {
1076        self.pending_labels.clear();
1077        let brk_loop = self.loops.iter().rposition(|l| !l.is_labeled_block);
1078        let cont_loop = self.loops.iter().rposition(|l| !l.is_switch && !l.is_labeled_block);
1079        let brk_depth = brk_loop.map_or(0, |i| self.loops[i].block_depth as u16);
1080        let brk_try = brk_loop.map_or(0, |i| self.loops[i].try_depth as u16);
1081        let brk_iters = brk_loop.map_or(0, |i| self.iter_depth.saturating_sub(self.loops[i].iter_depth) as u16);
1082        let cont_depth = cont_loop.map_or(0, |i| self.loops[i].block_depth as u16);
1083        let cont_try = cont_loop.map_or(0, |i| self.loops[i].try_depth as u16);
1084        let cont_iters = cont_loop.map_or(0, |i| self.iter_depth.saturating_sub(self.loops[i].iter_depth) as u16);
1085        // 外側のラベル付きループ/ブロックへの `break label`・`continue label`。
1086        let mut targets: Vec<ExecLabel> = Vec::new();
1087        for (i, l) in self.loops.iter().enumerate() {
1088            for lab in &l.labels {
1089                targets.push(ExecLabel {
1090                    label: lab.clone(),
1091                    loop_idx: i,
1092                    is_loop: !l.is_switch && !l.is_labeled_block,
1093                    brk: NO_LOOP,
1094                    cont: NO_LOOP,
1095                    brk_depth: l.block_depth as u16,
1096                    cont_depth: l.block_depth as u16,
1097                    brk_try: l.try_depth as u16,
1098                    cont_try: l.try_depth as u16,
1099                    iters: self.iter_depth.saturating_sub(l.iter_depth) as u16,
1100                });
1101            }
1102        }
1103        let lbls = if targets.is_empty() {
1104            NO_LOOP
1105        } else {
1106            self.exec_labels.push(targets);
1107            (self.exec_labels.len() - 1) as u32
1108        };
1109        let at = self.emit_jump(Op::Exec {
1110            stmt: s,
1111            brk: NO_LOOP,
1112            cont: NO_LOOP,
1113            brk_depth,
1114            cont_depth,
1115            brk_try,
1116            cont_try,
1117            brk_iters,
1118            cont_iters,
1119            lbls,
1120        });
1121        if brk_loop.is_some() || cont_loop.is_some() {
1122            self.pending_exec.push(PendingExec { at, brk_loop, cont_loop });
1123        }
1124    }
1125
1126    fn emit_unwind_to_loop(&mut self, target_idx: usize) {
1127        let leave_blocks = self.block_depth.saturating_sub(self.loops[target_idx].block_depth);
1128        let leave_try = self.try_depth.saturating_sub(self.loops[target_idx].try_depth);
1129        let leave_iters = self.iter_depth.saturating_sub(self.loops[target_idx].iter_depth);
1130        if leave_blocks > 0 {
1131            self.ops.push(Op::LeaveBlocks(leave_blocks));
1132        }
1133        if leave_try > 0 {
1134            self.ops.push(Op::LeaveTry(leave_try));
1135        }
1136        for _ in 0..(leave_iters * 2) {
1137            self.ops.push(Op::Pop);
1138        }
1139    }
1140
1141    fn stmt(&mut self, s: &Statement) {
1142        match s {
1143            Statement::Empty | Statement::FunctionDeclaration { .. } => {}
1144            Statement::Expression(e) => {
1145                self.expr(e);
1146                self.ops.push(Op::Pop);
1147            }
1148            Statement::VarDeclaration { kind: VarKind::Var, decls } => {
1149                for (pat, init) in decls {
1150                    match pat {
1151                        Pattern::Identifier(_) => {
1152                            // 初期化子の無い `var` は巻き上げ済み(本体の直下のスコープなので何もしない)。
1153                            if let Some(init) = init {
1154                                self.expr(init);
1155                                let slot = self.slot();
1156                                self.ops.push(Op::DeclVar(pat, slot));
1157                            }
1158                        }
1159                        _ => {
1160                            match init {
1161                                Some(init) => self.expr(init),
1162                                None => self.constant(Value::Undefined),
1163                            }
1164                            self.ops.push(Op::BindPattern(pat as *const Pattern, true));
1165                        }
1166                    }
1167                }
1168            }
1169            Statement::VarDeclaration { kind: VarKind::Let | VarKind::Const, decls } => {
1170                for (pat, init) in decls {
1171                    match init {
1172                        Some(init) => self.expr(init),
1173                        None => self.constant(Value::Undefined),
1174                    }
1175                    if let Pattern::Identifier(name) = pat {
1176                        let i = self.name(name);
1177                        self.ops.push(Op::DeclLexical(i));
1178                    } else {
1179                        self.ops.push(Op::BindPattern(pat as *const Pattern, false));
1180                    }
1181                }
1182            }
1183            // 関数宣言や `using` を含むブロックは入るとき・出るときの処理が要るので構文木のまま。
1184            Statement::Block(body) if !has_function(body) && !has_using(body) => {
1185                let lexical = block_has_lexical(body);
1186                if lexical {
1187                    self.ops.push(Op::EnterBlock);
1188                    self.block_depth += 1;
1189                }
1190                for s in body {
1191                    self.stmt(s);
1192                }
1193                if lexical {
1194                    self.block_depth -= 1;
1195                    self.ops.push(Op::LeaveBlocks(1));
1196                }
1197            }
1198            Statement::If { test, consequent, alternate } => {
1199                self.expr(test);
1200                let else_at = self.emit_jump(Op::JumpIfFalse(0));
1201                self.stmt(consequent);
1202                match alternate {
1203                    Some(alt) => {
1204                        let end = self.emit_jump(Op::Jump(0));
1205                        self.patch(else_at);
1206                        self.stmt(alt);
1207                        self.patch(end);
1208                    }
1209                    None => self.patch(else_at),
1210                }
1211            }
1212            Statement::Labeled(label, inner) if !has_uncompilable_labeled_jump(inner) && !labeled_for_of_needs_exec(inner) => {
1213                if matches!(**inner, Statement::Labeled(_, _)) || is_compilable_loop_or_switch(inner) {
1214                    self.pending_labels.push(label.clone());
1215                    self.stmt(inner);
1216                } else {
1217                    let mut labels = core::mem::take(&mut self.pending_labels);
1218                    labels.push(label.clone());
1219                    self.loops.push(LoopCtx {
1220                        labels,
1221                        block_depth: self.block_depth,
1222                        try_depth: self.try_depth,
1223                        iter_depth: self.iter_depth,
1224                        is_labeled_block: true,
1225                        ..LoopCtx::default()
1226                    });
1227                    self.stmt(inner);
1228                    self.close_loop(NO_LOOP);
1229                }
1230            }
1231            Statement::While { test, body } => {
1232                let labels = core::mem::take(&mut self.pending_labels);
1233                let head = self.ops.len() as u32;
1234                self.expr(test);
1235                let exit = self.emit_jump(Op::JumpIfFalse(0));
1236                self.loops.push(LoopCtx {
1237                    labels,
1238                    block_depth: self.block_depth,
1239                    try_depth: self.try_depth,
1240                    iter_depth: self.iter_depth,
1241                    ..LoopCtx::default()
1242                });
1243                self.stmt(body);
1244                self.ops.push(Op::Jump(head));
1245                self.patch(exit);
1246                self.close_loop(head);
1247            }
1248            Statement::DoWhile { body, test } => {
1249                let labels = core::mem::take(&mut self.pending_labels);
1250                let head = self.ops.len() as u32;
1251                self.loops.push(LoopCtx {
1252                    labels,
1253                    block_depth: self.block_depth,
1254                    try_depth: self.try_depth,
1255                    iter_depth: self.iter_depth,
1256                    ..LoopCtx::default()
1257                });
1258                self.stmt(body);
1259                let cont = self.ops.len() as u32;
1260                self.expr(test);
1261                let exit = self.emit_jump(Op::JumpIfFalse(0));
1262                self.ops.push(Op::Jump(head));
1263                self.patch(exit);
1264                self.close_loop(cont);
1265            }
1266            Statement::For { init, test, update, body }
1267                if init.as_deref().is_none_or(|i| {
1268                    matches!(
1269                        i,
1270                        Statement::Expression(_)
1271                            | Statement::VarDeclaration {
1272                                kind: VarKind::Var | VarKind::Let | VarKind::Const,
1273                                ..
1274                            }
1275                    )
1276                }) =>
1277            {
1278                let labels = core::mem::take(&mut self.pending_labels);
1279                let is_lexical = matches!(
1280                    init.as_deref(),
1281                    Some(Statement::VarDeclaration {
1282                        kind: VarKind::Let | VarKind::Const,
1283                        ..
1284                    })
1285                );
1286                if is_lexical {
1287                    self.ops.push(Op::EnterBlock);
1288                    self.block_depth += 1;
1289                }
1290                if let Some(i) = init {
1291                    self.stmt(i);
1292                }
1293                let head = self.ops.len() as u32;
1294                let exit = test.as_ref().map(|t| {
1295                    self.expr(t);
1296                    self.emit_jump(Op::JumpIfFalse(0))
1297                });
1298                self.loops.push(LoopCtx {
1299                    labels,
1300                    block_depth: self.block_depth,
1301                    try_depth: self.try_depth,
1302                    iter_depth: self.iter_depth,
1303                    ..LoopCtx::default()
1304                });
1305                self.stmt(body);
1306                let cont = self.ops.len() as u32;
1307                if is_lexical {
1308                    self.ops.push(Op::RefreshForLet);
1309                }
1310                if let Some(u) = update {
1311                    self.expr(u);
1312                    self.ops.push(Op::Pop);
1313                }
1314                self.ops.push(Op::Jump(head));
1315                if let Some(x) = exit {
1316                    self.patch(x);
1317                }
1318                self.close_loop(cont);
1319                if is_lexical {
1320                    self.block_depth -= 1;
1321                    self.ops.push(Op::LeaveBlocks(1));
1322                }
1323            }
1324            Statement::ForIn {
1325                decl_kind,
1326                pattern,
1327                object,
1328                body,
1329                of,
1330                is_await: false,
1331            } if decl_kind.as_ref().is_none_or(|k| matches!(k, VarKind::Var | VarKind::Let | VarKind::Const))
1332                && (decl_kind.is_some() || matches!(pattern, Pattern::Identifier(_))) =>
1333            {
1334                let labels = core::mem::take(&mut self.pending_labels);
1335                let is_lexical = matches!(decl_kind, Some(VarKind::Let | VarKind::Const));
1336                self.expr(object);
1337                // ラベルの無い for-of は、実行時に反復対象が利用者定義の反復子だと分かったら、同じ文を木走査で実行する
1338                // (1 要素ずつ引き、`break`・`return`・例外で IteratorClose を呼ぶため)。
1339                let or_exec = if *of && (labels.is_empty() || !contains_labeled_jump(body)) {
1340                    Some(self.emit_jump(Op::IterInitOrExec(true, 0)))
1341                } else {
1342                    self.ops.push(Op::IterInit(*of));
1343                    None
1344                };
1345                self.iter_depth += 1;
1346                if is_lexical {
1347                    self.ops.push(Op::EnterBlock);
1348                    self.block_depth += 1;
1349                }
1350                let head = self.ops.len() as u32;
1351                let exit = match pattern {
1352                    Pattern::Identifier(name) => {
1353                        let name_idx = self.name(name);
1354                        let slot = self.slot();
1355                        self.emit_jump(Op::IterNext {
1356                            exit: 0,
1357                            name: name_idx,
1358                            slot,
1359                            is_lexical,
1360                        })
1361                    }
1362                    _ => {
1363                        let e = self.emit_jump(Op::IterNextPush { exit: 0, is_lexical });
1364                        let to_call_scope = matches!(decl_kind, Some(VarKind::Var));
1365                        self.ops.push(Op::BindPattern(pattern as *const Pattern, to_call_scope));
1366                        e
1367                    }
1368                };
1369                self.loops.push(LoopCtx {
1370                    labels,
1371                    block_depth: self.block_depth,
1372                    try_depth: self.try_depth,
1373                    iter_depth: self.iter_depth,
1374                    ..LoopCtx::default()
1375                });
1376                self.stmt(body);
1377                self.ops.push(Op::Jump(head));
1378                self.patch(exit);
1379                self.close_loop(head);
1380                if is_lexical {
1381                    self.block_depth -= 1;
1382                    self.ops.push(Op::LeaveBlocks(1));
1383                }
1384                self.iter_depth -= 1;
1385                self.ops.push(Op::Pop);
1386                self.ops.push(Op::Pop);
1387                if let Some(at) = or_exec {
1388                    let end = self.emit_jump(Op::Jump(0));
1389                    self.patch(at);
1390                    self.exec_fallback(s);
1391                    self.patch(end);
1392                }
1393            }
1394            Statement::Switch { discriminant, cases }
1395                if cases.iter().all(|c| !has_function(&c.body) && !has_using(&c.body) && !super::block_has_lexical(&c.body)) =>
1396            {
1397                let labels = core::mem::take(&mut self.pending_labels);
1398                self.expr(discriminant);
1399                let mut case_jumps: Vec<(usize, usize)> = Vec::with_capacity(cases.len());
1400                let mut default_idx: Option<usize> = None;
1401                for (i, c) in cases.iter().enumerate() {
1402                    if let Some(test) = &c.test {
1403                        self.expr(test);
1404                        let j = self.emit_jump(Op::CaseEq(0));
1405                        case_jumps.push((i, j));
1406                    } else if default_idx.is_none() {
1407                        default_idx = Some(i);
1408                    }
1409                }
1410                self.ops.push(Op::Pop);
1411                let default_jump = self.emit_jump(Op::Jump(0));
1412                self.loops.push(LoopCtx {
1413                    labels,
1414                    block_depth: self.block_depth,
1415                    try_depth: self.try_depth,
1416                    iter_depth: self.iter_depth,
1417                    is_switch: true,
1418                    ..LoopCtx::default()
1419                });
1420                for (i, c) in cases.iter().enumerate() {
1421                    let body_pc = self.ops.len() as u32;
1422                    for &(ci, j) in &case_jumps {
1423                        if ci == i {
1424                            self.patch_to(j, body_pc);
1425                        }
1426                    }
1427                    if default_idx == Some(i) {
1428                        self.patch_to(default_jump, body_pc);
1429                    }
1430                    for st in &c.body {
1431                        self.stmt(st);
1432                    }
1433                }
1434                if default_idx.is_none() {
1435                    self.patch(default_jump);
1436                }
1437                self.close_loop(NO_LOOP);
1438            }
1439            Statement::Try(t)
1440                if t.finally_block.is_none()
1441                    && t.catch_block.as_ref().is_some_and(|cb| !has_function(cb) && !has_using(cb))
1442                    && !has_function(&t.block)
1443                    && !has_using(&t.block) =>
1444            {
1445                let enter_try = self.emit_jump(Op::EnterTry(0));
1446                self.try_depth += 1;
1447                let try_lexical = block_has_lexical(&t.block);
1448                if try_lexical {
1449                    self.ops.push(Op::EnterBlock);
1450                    self.block_depth += 1;
1451                }
1452                for st in &t.block {
1453                    self.stmt(st);
1454                }
1455                if try_lexical {
1456                    self.block_depth -= 1;
1457                    self.ops.push(Op::LeaveBlocks(1));
1458                }
1459                self.try_depth -= 1;
1460                self.ops.push(Op::LeaveTry(1));
1461                let end_jump = self.emit_jump(Op::Jump(0));
1462                self.patch(enter_try);
1463                if let Some(cb) = &t.catch_block {
1464                    let catch_lexical = t.catch_param.is_some() || block_has_lexical(cb);
1465                    if catch_lexical {
1466                        self.ops.push(Op::EnterBlock);
1467                        self.block_depth += 1;
1468                    }
1469                    match t.catch_param.as_deref() {
1470                        Some(Pattern::Identifier(name)) => {
1471                            let name_idx = self.name(name);
1472                            self.ops.push(Op::CatchParam(name_idx));
1473                        }
1474                        Some(pat) => {
1475                            self.ops.push(Op::BindPattern(pat as *const Pattern, false));
1476                        }
1477                        None => self.ops.push(Op::Pop),
1478                    }
1479                    for st in cb {
1480                        self.stmt(st);
1481                    }
1482                    if catch_lexical {
1483                        self.block_depth -= 1;
1484                        self.ops.push(Op::LeaveBlocks(1));
1485                    }
1486                }
1487                self.patch(end_jump);
1488            }
1489            Statement::Return(e) => match e {
1490                Some(e) => {
1491                    self.expr(e);
1492                    self.ops.push(Op::Return);
1493                }
1494                None => self.ops.push(Op::ReturnUndefined),
1495            },
1496            Statement::Throw(e) => {
1497                self.expr(e);
1498                self.ops.push(Op::Throw);
1499            }
1500            Statement::Break(None) if self.loops.iter().any(|l| !l.is_labeled_block) => {
1501                let Some(target_idx) = self.loops.iter().rposition(|l| !l.is_labeled_block) else {
1502                    return self.exec_fallback(s);
1503                };
1504                self.emit_unwind_to_loop(target_idx);
1505                let j = self.emit_jump(Op::Jump(0));
1506                self.loops[target_idx].breaks.push(j);
1507            }
1508            Statement::Break(Some(lbl))
1509                if self.loops.iter().any(|l| l.labels.iter().any(|x| x == lbl)) =>
1510            {
1511                let Some(target_idx) = self
1512                    .loops
1513                    .iter()
1514                    .rposition(|l| l.labels.iter().any(|x| x == lbl))
1515                else {
1516                    return self.exec_fallback(s);
1517                };
1518                self.emit_unwind_to_loop(target_idx);
1519                let j = self.emit_jump(Op::Jump(0));
1520                self.loops[target_idx].breaks.push(j);
1521            }
1522            Statement::Continue(None)
1523                if self.loops.iter().any(|l| !l.is_switch && !l.is_labeled_block) =>
1524            {
1525                let Some(target_idx) = self
1526                    .loops
1527                    .iter()
1528                    .rposition(|l| !l.is_switch && !l.is_labeled_block)
1529                else {
1530                    return self.exec_fallback(s);
1531                };
1532                self.emit_unwind_to_loop(target_idx);
1533                let j = self.emit_jump(Op::Jump(0));
1534                self.loops[target_idx].continues.push(j);
1535            }
1536            Statement::Continue(Some(lbl))
1537                if self
1538                    .loops
1539                    .iter()
1540                    .any(|l| !l.is_switch && !l.is_labeled_block && l.labels.iter().any(|x| x == lbl)) =>
1541            {
1542                let Some(target_idx) = self.loops.iter().rposition(|l| {
1543                    !l.is_switch && !l.is_labeled_block && l.labels.iter().any(|x| x == lbl)
1544                }) else {
1545                    return self.exec_fallback(s);
1546                };
1547                self.emit_unwind_to_loop(target_idx);
1548                let j = self.emit_jump(Op::Jump(0));
1549                self.loops[target_idx].continues.push(j);
1550            }
1551            _ => self.exec_fallback(s),
1552        }
1553    }
1554
1555    /// ループ(または `switch`)の出口はここ。`continue` は `cont` へ。
1556    fn close_loop(&mut self, cont: u32) {
1557        let depth = self.loops.len() - 1;
1558        let Some(l) = self.loops.pop() else { return };
1559        let end = self.ops.len() as u32;
1560        for j in l.breaks {
1561            self.patch_to(j, end);
1562        }
1563        for j in l.continues {
1564            self.patch_to(j, cont);
1565        }
1566        for table in self.exec_labels.iter_mut() {
1567            for t in table.iter_mut() {
1568                if t.loop_idx == depth && t.brk == NO_LOOP {
1569                    t.brk = end;
1570                    if t.is_loop {
1571                        t.cont = cont;
1572                    }
1573                }
1574            }
1575        }
1576        let mut rest = Vec::new();
1577        for mut pe in core::mem::take(&mut self.pending_exec) {
1578            if pe.brk_loop == Some(depth) {
1579                if let Some(Op::Exec { brk, .. }) = self.ops.get_mut(pe.at) {
1580                    *brk = end;
1581                }
1582                pe.brk_loop = None;
1583            }
1584            if !l.is_switch && !l.is_labeled_block && pe.cont_loop == Some(depth) {
1585                if let Some(Op::Exec { cont: c, .. }) = self.ops.get_mut(pe.at) {
1586                    *c = cont;
1587                }
1588                pe.cont_loop = None;
1589            }
1590            if pe.brk_loop.is_some() || pe.cont_loop.is_some() {
1591                rest.push(pe);
1592            }
1593        }
1594        self.pending_exec = rest;
1595    }
1596}
1597
1598fn is_compilable_loop_or_switch(s: &Statement) -> bool {
1599    match s {
1600        Statement::While { .. } | Statement::DoWhile { .. } => true,
1601        Statement::For { init, .. } => init.as_deref().is_none_or(|i| {
1602            matches!(
1603                i,
1604                Statement::Expression(_)
1605                    | Statement::VarDeclaration {
1606                        kind: VarKind::Var | VarKind::Let | VarKind::Const,
1607                        ..
1608                    }
1609            )
1610        }),
1611        Statement::ForIn {
1612            decl_kind,
1613            pattern,
1614            is_await: false,
1615            ..
1616        } => {
1617            decl_kind
1618                .as_ref()
1619                .is_none_or(|k| matches!(k, VarKind::Var | VarKind::Let | VarKind::Const))
1620                && (decl_kind.is_some() || matches!(pattern, Pattern::Identifier(_)))
1621        }
1622        Statement::Switch { cases, .. }
1623            if cases.iter().all(|c| !has_function(&c.body) && !has_using(&c.body) && !super::block_has_lexical(&c.body)) =>
1624        {
1625            cases.iter().any(|c| c.body.iter().any(contains_labeled_jump))
1626        }
1627        _ => false,
1628    }
1629}
1630
1631fn contains_labeled_jump(s: &Statement) -> bool {
1632    match s {
1633        Statement::Break(Some(_)) | Statement::Continue(Some(_)) => true,
1634        Statement::Block(body) => body.iter().any(contains_labeled_jump),
1635        Statement::If { consequent, alternate, .. } => {
1636            contains_labeled_jump(consequent)
1637                || alternate.as_deref().is_some_and(contains_labeled_jump)
1638        }
1639        Statement::While { body, .. }
1640        | Statement::DoWhile { body, .. }
1641        | Statement::For { body, .. }
1642        | Statement::ForIn { body, .. }
1643        | Statement::Labeled(_, body) => contains_labeled_jump(body),
1644        Statement::Switch { cases, .. } => {
1645            cases.iter().any(|c| c.body.iter().any(contains_labeled_jump))
1646        }
1647        Statement::Try(t) => {
1648            t.block.iter().any(contains_labeled_jump)
1649                || t.catch_block
1650                    .as_ref()
1651                    .is_some_and(|cb| cb.iter().any(contains_labeled_jump))
1652                || t.finally_block
1653                    .as_ref()
1654                    .is_some_and(|fb| fb.iter().any(contains_labeled_jump))
1655        }
1656        _ => false,
1657    }
1658}
1659
1660/// ラベル付きの for-of で、本体にラベル付きの `break`/`continue` があるもの。実行時に木走査へ回す(`IterInitOrExec`)と
1661/// 自身のラベルへの飛び先を持てないので、ラベル文ごと木走査で実行する。
1662fn labeled_for_of_needs_exec(s: &Statement) -> bool {
1663    let mut cur = s;
1664    while let Statement::Labeled(_, inner) = cur {
1665        cur = inner;
1666    }
1667    matches!(cur, Statement::ForIn { of: true, is_await: false, body, .. } if contains_labeled_jump(body))
1668}
1669
1670/// `Op::Exec` へフォールバックするコンテナの内部にラベル付き `break` / `continue` が含まれるか。
1671fn has_uncompilable_labeled_jump(s: &Statement) -> bool {
1672    match s {
1673        Statement::Empty
1674        | Statement::InitPrivateBrand(_)
1675        | Statement::InitPrivateField { .. }
1676        | Statement::InitPublicField { .. }
1677        | Statement::FunctionDeclaration { .. }
1678        | Statement::Expression(_)
1679        | Statement::VarDeclaration { .. }
1680        | Statement::Return(_)
1681        | Statement::Throw(_)
1682        | Statement::Break(_)
1683        | Statement::Continue(_) => false,
1684        Statement::Block(body) => {
1685            if !has_function(body) && !has_using(body) {
1686                body.iter().any(has_uncompilable_labeled_jump)
1687            } else {
1688                body.iter().any(contains_labeled_jump)
1689            }
1690        }
1691        Statement::If { consequent, alternate, .. } => {
1692            has_uncompilable_labeled_jump(consequent)
1693                || alternate.as_deref().is_some_and(has_uncompilable_labeled_jump)
1694        }
1695        Statement::While { body, .. } | Statement::DoWhile { body, .. } => {
1696            has_uncompilable_labeled_jump(body)
1697        }
1698        Statement::For { init, body, .. } => {
1699            if init.as_deref().is_none_or(|i| {
1700                matches!(
1701                    i,
1702                    Statement::Expression(_)
1703                        | Statement::VarDeclaration {
1704                            kind: VarKind::Var | VarKind::Let | VarKind::Const,
1705                            ..
1706                        }
1707                )
1708            }) {
1709                has_uncompilable_labeled_jump(body)
1710            } else {
1711                contains_labeled_jump(body)
1712            }
1713        }
1714        Statement::ForIn {
1715            decl_kind,
1716            pattern,
1717            body,
1718            is_await,
1719            ..
1720        } => {
1721            if !is_await
1722                && (decl_kind.is_some() || matches!(pattern, Pattern::Identifier(_)))
1723                && decl_kind
1724                    .as_ref()
1725                    .is_none_or(|k| matches!(k, VarKind::Var | VarKind::Let | VarKind::Const))
1726            {
1727                has_uncompilable_labeled_jump(body)
1728            } else {
1729                contains_labeled_jump(body)
1730            }
1731        }
1732        Statement::Switch { cases, .. } => {
1733            if cases.iter().all(|c| !has_function(&c.body) && !has_using(&c.body) && !super::block_has_lexical(&c.body)) {
1734                cases
1735                    .iter()
1736                    .any(|c| c.body.iter().any(has_uncompilable_labeled_jump))
1737            } else {
1738                cases.iter().any(|c| c.body.iter().any(contains_labeled_jump))
1739            }
1740        }
1741        Statement::Try(t) => {
1742            if t.finally_block.is_none()
1743                && t.catch_block
1744                    .as_ref()
1745                    .is_some_and(|cb| !has_function(cb) && !has_using(cb))
1746                && !has_function(&t.block)
1747                && !has_using(&t.block)
1748            {
1749                t.block.iter().any(has_uncompilable_labeled_jump)
1750                    || t.catch_block
1751                        .as_ref()
1752                        .is_some_and(|cb| cb.iter().any(has_uncompilable_labeled_jump))
1753            } else {
1754                contains_labeled_jump(s)
1755            }
1756        }
1757        Statement::Labeled(_, inner) => has_uncompilable_labeled_jump(inner),
1758        _ => contains_labeled_jump(s),
1759    }
1760}
1761
1762fn has_function(stmts: &[Statement]) -> bool {
1763    stmts.iter().any(|s| matches!(s, Statement::FunctionDeclaration { .. }))
1764}
1765
1766fn stmt_needs_tree_walk(s: &Statement) -> bool {
1767    match s {
1768        Statement::VarDeclaration { kind: VarKind::Using | VarKind::AwaitUsing, .. }
1769        | Statement::InitPrivateBrand(_)
1770        | Statement::InitPrivateField { .. }
1771        | Statement::InitPublicField { .. }
1772        | Statement::ClassFieldInit { .. }
1773        | Statement::With { .. } => true,
1774        Statement::Block(b) => has_using(b),
1775        Statement::If { consequent, alternate, .. } => {
1776            stmt_needs_tree_walk(consequent) || alternate.as_deref().is_some_and(stmt_needs_tree_walk)
1777        }
1778        Statement::While { body, .. }
1779        | Statement::DoWhile { body, .. }
1780        | Statement::For { body, .. }
1781        | Statement::ForIn { body, .. }
1782        | Statement::Labeled(_, body) => stmt_needs_tree_walk(body),
1783        Statement::Switch { cases, .. } => cases.iter().any(|c| has_using(&c.body)),
1784        Statement::Try(t) => {
1785            has_using(&t.block)
1786                || t.catch_block.as_ref().is_some_and(|b| has_using(b))
1787                || t.finally_block.as_ref().is_some_and(|b| has_using(b))
1788        }
1789        _ => false,
1790    }
1791}
1792
1793fn has_using(stmts: &[Statement]) -> bool {
1794    stmts.iter().any(stmt_needs_tree_walk)
1795}
1796
1797/// 関数本体を変換する。`using` は文の並びの終わりで片付ける処理が要るので対象外。
1798pub(crate) fn compile(stmts: &Rc<Vec<Statement>>) -> Option<Code> {
1799    if has_using(stmts) {
1800        return None;
1801    }
1802    let mut c = Compiler {
1803        ops: Vec::new(),
1804        consts: Vec::new(),
1805        names: Vec::new(),
1806        slots: Vec::new(),
1807        prop_slots: Vec::new(),
1808        loops: Vec::new(),
1809        pending_labels: Vec::new(),
1810        block_depth: 0,
1811        try_depth: 0,
1812        iter_depth: 0,
1813        pending_exec: Vec::new(),
1814        exec_labels: Vec::new(),
1815    };
1816    for s in stmts.iter() {
1817        c.stmt(s);
1818    }
1819    c.ops.push(Op::ReturnUndefined);
1820    Some(Code {
1821        ops: c.ops,
1822        consts: c.consts,
1823        names: c.names,
1824        slots: c.slots,
1825        prop_slots: c.prop_slots,
1826        exec_labels: c.exec_labels,
1827        _ast: stmts.clone(),
1828    })
1829}
1830
1831impl Interp {
1832    /// 変数を読む。覚えた場所があれば名前の検索なしで読む。
1833    #[inline(always)]
1834    fn load_slot(&mut self, name: &Rc<str>, slot: &Slot, scope: &Rc<RefCell<Scope>>) -> EvalResult {
1835        if let Some(v) = slot.with(scope, |v| v.clone()) {
1836            return Ok(v);
1837        }
1838        self.load_slot_miss(name, slot, scope)
1839    }
1840
1841    #[inline(never)]
1842    fn load_slot_miss(&mut self, name: &Rc<str>, slot: &Slot, scope: &Rc<RefCell<Scope>>) -> EvalResult {
1843        slot.learn(name, scope);
1844        self.load_identifier(name, scope)
1845    }
1846
1847    /// `name = v`。覚えた場所があれば名前の検索なしで書く。
1848    #[inline]
1849    fn store_slot(
1850        &mut self,
1851        target: &Expression,
1852        v: Value,
1853        slot: &Slot,
1854        scope: &Rc<RefCell<Scope>>,
1855        this: &Value,
1856    ) -> Result<(), Value> {
1857        let mut v = Some(v);
1858        let done = slot.with_is_global(scope, |cell| {
1859            if let Some(val) = v.take() {
1860                *cell = val;
1861            }
1862            cell.clone()
1863        });
1864        if let Some((written, is_global)) = done {
1865            if is_global {
1866                if let Expression::Identifier(name) = target {
1867                    if let Some(orig) = self.sync_global_prop_if_present(name, &written) {
1868                        slot.with(scope, |cell| *cell = orig);
1869                    }
1870                }
1871            }
1872            return Ok(());
1873        }
1874        if let Expression::Identifier(name) = target {
1875            slot.learn(name, scope);
1876        }
1877        self.assign_to(target, v.take().unwrap_or(Value::Undefined), scope, this)
1878    }
1879
1880    /// `code` を実行して関数の戻り値を返す。
1881    pub(crate) fn run_code(&mut self, code: &Code, scope: &Rc<RefCell<Scope>>, this: &Value) -> EvalResult {
1882        let base = self.vm_stack.len();
1883        let mut block_scopes: Vec<Rc<RefCell<Scope>>> = Vec::new();
1884        let r = self.run_code_inner(code, scope, &mut block_scopes, this);
1885        while let Some(sc) = block_scopes.pop() {
1886            self.recycle_block_scope(sc);
1887        }
1888        self.vm_stack.truncate(base);
1889        r
1890    }
1891
1892    fn run_code_inner(
1893        &mut self,
1894        code: &Code,
1895        call_scope: &Rc<RefCell<Scope>>,
1896        block_scopes: &mut Vec<Rc<RefCell<Scope>>>,
1897        this: &Value,
1898    ) -> EvalResult {
1899        let mut pc = 0usize;
1900        let mut try_stack: Vec<TryCtx> = Vec::new();
1901        loop {
1902            if self.tick() {
1903                return Err(Value::Undefined);
1904            }
1905            let Some(op) = code.ops.get(pc) else { return Ok(Value::Undefined) };
1906            pc += 1;
1907            let step: Result<Option<Value>, Value> = (|| {
1908                match op {
1909                    Op::Const(i) => {
1910                        let v = code.consts.get(*i as usize).cloned().unwrap_or(Value::Undefined);
1911                        self.vm_stack.push(v);
1912                    }
1913                    Op::This => {
1914                        let scope = block_scopes.last().unwrap_or(call_scope);
1915                        let v = self.resolve_this(scope, this)?;
1916                        self.vm_stack.push(v);
1917                    }
1918                    Op::Load(i, slot) => {
1919                        let scope = block_scopes.last().unwrap_or(call_scope);
1920                        let v = match (code.names.get(*i as usize), code.slots.get(*slot as usize)) {
1921                            (Some(n), Some(s)) => self.load_slot(n, s, scope)?,
1922                            _ => Value::Undefined,
1923                        };
1924                        self.vm_stack.push(v);
1925                    }
1926                    Op::Pop => {
1927                        self.vm_stack.pop();
1928                    }
1929                    Op::Dup => {
1930                        let v = self.vm_stack.last().cloned().unwrap_or(Value::Undefined);
1931                        self.vm_stack.push(v);
1932                    }
1933                    Op::Dup2 => {
1934                        let len = self.vm_stack.len();
1935                        let a = self.vm_stack.get(len.wrapping_sub(2)).cloned().unwrap_or(Value::Undefined);
1936                        let b = self.vm_stack.get(len.wrapping_sub(1)).cloned().unwrap_or(Value::Undefined);
1937                        self.vm_stack.push(a);
1938                        self.vm_stack.push(b);
1939                    }
1940                    Op::Binary(bop) => {
1941                        let r = self.vm_stack.pop().unwrap_or(Value::Undefined);
1942                        let l = self.vm_stack.pop().unwrap_or(Value::Undefined);
1943                        let fast = match (&l, &r) {
1944                            (Value::Number(a), Value::Number(b)) => number_binary(bop, *a, *b),
1945                            (Value::Str(a), Value::Str(b)) if matches!(bop, BinaryOp::Add) => {
1946                                let mut out = String::with_capacity(a.len() + b.len());
1947                                out.push_str(a);
1948                                out.push_str(b);
1949                                Some(Value::str(out))
1950                            }
1951                            (Value::Str(a), Value::Number(b)) if matches!(bop, BinaryOp::Add) => {
1952                                let bs = super::super::value::fmt_number(*b);
1953                                let mut out = String::with_capacity(a.len() + bs.len());
1954                                out.push_str(a);
1955                                out.push_str(&bs);
1956                                Some(Value::str(out))
1957                            }
1958                            (Value::Number(a), Value::Str(b)) if matches!(bop, BinaryOp::Add) => {
1959                                let as_str = super::super::value::fmt_number(*a);
1960                                let mut out = String::with_capacity(as_str.len() + b.len());
1961                                out.push_str(&as_str);
1962                                out.push_str(b);
1963                                Some(Value::str(out))
1964                            }
1965                            (Value::Str(a), Value::Bool(b)) if matches!(bop, BinaryOp::Add) => {
1966                                let bs = if *b { "true" } else { "false" };
1967                                let mut out = String::with_capacity(a.len() + bs.len());
1968                                out.push_str(a);
1969                                out.push_str(bs);
1970                                Some(Value::str(out))
1971                            }
1972                            (Value::Bool(a), Value::Str(b)) if matches!(bop, BinaryOp::Add) => {
1973                                let as_str = if *a { "true" } else { "false" };
1974                                let mut out = String::with_capacity(as_str.len() + b.len());
1975                                out.push_str(as_str);
1976                                out.push_str(b);
1977                                Some(Value::str(out))
1978                            }
1979                            (Value::Str(a), Value::Str(b)) if matches!(bop, BinaryOp::Eq | BinaryOp::StrictEq) => {
1980                                Some(Value::Bool(a == b))
1981                            }
1982                            (Value::Str(a), Value::Str(b)) if matches!(bop, BinaryOp::NotEq | BinaryOp::StrictNotEq) => {
1983                                Some(Value::Bool(a != b))
1984                            }
1985                            (Value::Bool(a), Value::Bool(b)) if matches!(bop, BinaryOp::Eq | BinaryOp::StrictEq) => {
1986                                Some(Value::Bool(a == b))
1987                            }
1988                            (Value::Bool(a), Value::Bool(b)) if matches!(bop, BinaryOp::NotEq | BinaryOp::StrictNotEq) => {
1989                                Some(Value::Bool(a != b))
1990                            }
1991                            (Value::Null, Value::Null) | (Value::Undefined, Value::Undefined)
1992                                if matches!(bop, BinaryOp::Eq | BinaryOp::StrictEq) =>
1993                            {
1994                                Some(Value::Bool(true))
1995                            }
1996                            (Value::Null, Value::Null) | (Value::Undefined, Value::Undefined)
1997                                if matches!(bop, BinaryOp::NotEq | BinaryOp::StrictNotEq) =>
1998                            {
1999                                Some(Value::Bool(false))
2000                            }
2001                            (Value::Null, Value::Undefined) | (Value::Undefined, Value::Null) => match bop {
2002                                BinaryOp::Eq => Some(Value::Bool(true)),
2003                                BinaryOp::NotEq => Some(Value::Bool(false)),
2004                                BinaryOp::StrictEq => Some(Value::Bool(false)),
2005                                BinaryOp::StrictNotEq => Some(Value::Bool(true)),
2006                                _ => None,
2007                            },
2008                            _ => None,
2009                        };
2010                        let v = match fast {
2011                            Some(v) => v,
2012                            None => self.op_binary_slow(bop, l, r)?,
2013                        };
2014                        self.vm_stack.push(v);
2015                    }
2016                    Op::JumpIfFalse(t) => {
2017                        if !self.vm_stack.pop().unwrap_or(Value::Undefined).truthy() {
2018                            pc = *t as usize;
2019                        }
2020                    }
2021                    Op::Jump(t) => pc = *t as usize,
2022                    Op::AndKeep(t) => {
2023                        if self.vm_stack.last().is_some_and(|v| v.truthy()) {
2024                            self.vm_stack.pop();
2025                        } else {
2026                            pc = *t as usize;
2027                        }
2028                    }
2029                    Op::OrKeep(t) => {
2030                        if self.vm_stack.last().is_some_and(|v| v.truthy()) {
2031                            pc = *t as usize;
2032                        } else {
2033                            self.vm_stack.pop();
2034                        }
2035                    }
2036                    Op::NullishKeep(t) => {
2037                        if self.vm_stack.last().is_some_and(|v| matches!(v, Value::Undefined | Value::Null)) {
2038                            self.vm_stack.pop();
2039                        } else {
2040                            pc = *t as usize;
2041                        }
2042                    }
2043                    Op::AndKeepMember(t) => {
2044                        let len = self.vm_stack.len();
2045                        if len >= 2 {
2046                            if !self.vm_stack[len - 1].truthy() {
2047                                let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
2048                                self.vm_stack.pop();
2049                                self.vm_stack.push(v);
2050                                pc = *t as usize;
2051                            } else {
2052                                self.vm_stack.pop();
2053                            }
2054                        }
2055                    }
2056                    Op::OrKeepMember(t) => {
2057                        let len = self.vm_stack.len();
2058                        if len >= 2 {
2059                            if self.vm_stack[len - 1].truthy() {
2060                                let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
2061                                self.vm_stack.pop();
2062                                self.vm_stack.push(v);
2063                                pc = *t as usize;
2064                            } else {
2065                                self.vm_stack.pop();
2066                            }
2067                        }
2068                    }
2069                    Op::NullishKeepMember(t) => {
2070                        let len = self.vm_stack.len();
2071                        if len >= 2 {
2072                            let is_nullish = matches!(self.vm_stack[len - 1], Value::Undefined | Value::Null);
2073                            if !is_nullish {
2074                                let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
2075                                self.vm_stack.pop();
2076                                self.vm_stack.push(v);
2077                                pc = *t as usize;
2078                            } else {
2079                                self.vm_stack.pop();
2080                            }
2081                        }
2082                    }
2083                    Op::AndKeepIndex(t) => {
2084                        let len = self.vm_stack.len();
2085                        if len >= 3 {
2086                            if !self.vm_stack[len - 1].truthy() {
2087                                let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
2088                                self.vm_stack.pop();
2089                                self.vm_stack.pop();
2090                                self.vm_stack.push(v);
2091                                pc = *t as usize;
2092                            } else {
2093                                self.vm_stack.pop();
2094                            }
2095                        }
2096                    }
2097                    Op::OrKeepIndex(t) => {
2098                        let len = self.vm_stack.len();
2099                        if len >= 3 {
2100                            if self.vm_stack[len - 1].truthy() {
2101                                let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
2102                                self.vm_stack.pop();
2103                                self.vm_stack.pop();
2104                                self.vm_stack.push(v);
2105                                pc = *t as usize;
2106                            } else {
2107                                self.vm_stack.pop();
2108                            }
2109                        }
2110                    }
2111                    Op::NullishKeepIndex(t) => {
2112                        let len = self.vm_stack.len();
2113                        if len >= 3 {
2114                            let is_nullish = matches!(self.vm_stack[len - 1], Value::Undefined | Value::Null);
2115                            if !is_nullish {
2116                                let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
2117                                self.vm_stack.pop();
2118                                self.vm_stack.pop();
2119                                self.vm_stack.push(v);
2120                                pc = *t as usize;
2121                            } else {
2122                                self.vm_stack.pop();
2123                            }
2124                        }
2125                    }
2126                    Op::JumpIfNullish(t) => {
2127                        if self.vm_stack.last().is_some_and(|v| matches!(v, Value::Undefined | Value::Null)) {
2128                            self.vm_stack.pop();
2129                            self.vm_stack.push(Value::Undefined);
2130                            pc = *t as usize;
2131                        }
2132                    }
2133                    Op::JumpIfNullishMethod(t) => {
2134                        let len = self.vm_stack.len();
2135                        if len >= 2 {
2136                            let is_nullish = matches!(self.vm_stack[len - 2], Value::Undefined | Value::Null);
2137                            if is_nullish {
2138                                self.vm_stack.pop();
2139                                self.vm_stack.pop();
2140                                self.vm_stack.push(Value::Undefined);
2141                                pc = *t as usize;
2142                            }
2143                        }
2144                    }
2145                    Op::Member(i, object, slot) => self.op_member(code, *i, *object, *slot)?,
2146                    Op::Index => self.op_index()?,
2147                    Op::Method(i, object, slot) => self.op_method(code, *i, *object, *slot)?,
2148                    Op::MethodIndex => self.op_method_index()?,
2149                    Op::Call(argc, callee) => self.op_call(*argc, *callee)?,
2150                    Op::CallWithArgs(callee) => self.op_call_with_args(*callee)?,
2151                    Op::Not => {
2152                        let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
2153                        self.vm_stack.push(Value::Bool(!v.truthy()));
2154                    }
2155                    Op::Neg => {
2156                        let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
2157                        let v = self.prim_num(v)?;
2158                        let r = match &v {
2159                            Value::Number(n) => Value::Number(-*n),
2160                            Value::BigInt(b) => Value::bigint(b.neg()),
2161                            _ => Value::Number(-v.to_number()),
2162                        };
2163                        self.vm_stack.push(r);
2164                    }
2165                    Op::Pos => {
2166                        let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
2167                        let v = self.prim_num(v)?;
2168                        let n = match &v {
2169                            Value::Number(n) => *n,
2170                            Value::BigInt(_) => return Err(self.type_error("Cannot convert a BigInt to a number")),
2171                            _ => v.to_number(),
2172                        };
2173                        self.vm_stack.push(Value::Number(n));
2174                    }
2175                    Op::BitNot => {
2176                        let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
2177                        let v = self.prim_num(v)?;
2178                        let r = match &v {
2179                            Value::Number(n) => Value::Number(!(to_i32(*n)) as f64),
2180                            Value::BigInt(b) => Value::bigint(b.bitnot()),
2181                            _ => Value::Number(!(to_i32(v.to_number())) as f64),
2182                        };
2183                        self.vm_stack.push(r);
2184                    }
2185                    Op::TypeOf => {
2186                        let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
2187                        self.vm_stack.push(Value::str(v.type_of()));
2188                    }
2189                    Op::TypeofIdent(i, slot) => {
2190                        let scope = block_scopes.last().unwrap_or(call_scope);
2191                        let v = self.op_typeof_ident(code, *i, *slot, scope)?;
2192                        self.vm_stack.push(v);
2193                    }
2194                    Op::DeleteMember(name) => self.op_delete_member(code, *name)?,
2195                    Op::DeleteIndex => self.op_delete_index()?,
2196                    Op::Array(len) => self.op_array(*len),
2197                    Op::NewArray => self.vm_stack.push(Value::Object(Obj::array(Vec::new()))),
2198                    Op::ArrayPush => {
2199                        let val = self.vm_stack.pop().unwrap_or(Value::Undefined);
2200                        if let Some(Value::Object(rc)) = self.vm_stack.last() {
2201                            rc.borrow_mut().array_push(val);
2202                        }
2203                    }
2204                    Op::ArraySpread => self.op_array_spread()?,
2205                    Op::NewObject => self.vm_stack.push(Value::Object(Obj::plain())),
2206                    Op::InitProp(name) => self.op_init_prop(code, *name),
2207                    Op::InitPropComputed => self.op_init_prop_computed()?,
2208                    Op::SpreadObject => self.op_spread_object()?,
2209                    Op::New(argc) => self.op_new(*argc)?,
2210                    Op::Template(quasis, len) => self.op_template(*quasis, *len)?,
2211                    Op::CaseEq(t) => {
2212                        let tv = self.vm_stack.pop().unwrap_or(Value::Undefined);
2213                        if self.vm_stack.last().is_some_and(|d| d.strict_eq(&tv)) {
2214                            self.vm_stack.pop();
2215                            pc = *t as usize;
2216                        }
2217                    }
2218                    Op::IterInit(of) => self.op_iter_init(*of)?,
2219                    Op::IterInitOrExec(of, exec_pc) => {
2220                        let lazy = self.vm_stack.last().is_some_and(|v| self.is_lazy_iter_candidate(v));
2221                        if lazy {
2222                            self.forof_preset = self.vm_stack.pop();
2223                            pc = *exec_pc as usize;
2224                        } else {
2225                            self.op_iter_init(*of)?;
2226                        }
2227                    }
2228                    Op::IterNext { exit, name, slot, is_lexical } => {
2229                        if !self.op_iter_next(code, *name, *slot, *is_lexical, call_scope, block_scopes) {
2230                            self.throw_deferred_iter_err()?;
2231                            pc = *exit as usize;
2232                        }
2233                    }
2234                    Op::IterNextPush { exit, is_lexical } => {
2235                        match self.pop_next_iter_item(*is_lexical, call_scope, block_scopes) {
2236                            Some(item) => self.vm_stack.push(item),
2237                            None => {
2238                                self.throw_deferred_iter_err()?;
2239                                pc = *exit as usize;
2240                            }
2241                        }
2242                    }
2243                    Op::BindPattern(pat, to_call_scope) => {
2244                        let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
2245                        let scope = if *to_call_scope {
2246                            call_scope
2247                        } else {
2248                            block_scopes.last().unwrap_or(call_scope)
2249                        };
2250                        // SAFETY: `Code::_ast` が構文木を保持している。
2251                        self.bind_pattern(unsafe { &**pat }, v, scope, this)?;
2252                    }
2253                    Op::EnterTry(catch_pc) => {
2254                        try_stack.push(TryCtx {
2255                            catch_pc: *catch_pc,
2256                            block_depth: block_scopes.len() as u32,
2257                            stack_len: self.vm_stack.len(),
2258                        });
2259                    }
2260                    Op::LeaveTry(n) => {
2261                        let new_len = try_stack.len().saturating_sub(*n as usize);
2262                        try_stack.truncate(new_len);
2263                    }
2264                    Op::CatchParam(name_idx) => {
2265                        let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
2266                        if let Some(name) = code.names.get(*name_idx as usize) {
2267                            let scope = block_scopes.last().unwrap_or(call_scope);
2268                            scope.borrow_mut().vars.insert(name.clone(), v);
2269                        }
2270                    }
2271                    Op::NewTarget => {
2272                        let v = self.new_target_stack.last().cloned().unwrap_or(Value::Undefined);
2273                        self.vm_stack.push(v);
2274                    }
2275                    Op::Closure(e) => {
2276                        let scope = block_scopes.last().unwrap_or(call_scope);
2277                        // SAFETY: `Code::_ast` が構文木を保持している。
2278                        if let Expression::Function {
2279                            name,
2280                            params,
2281                            body,
2282                            is_arrow,
2283                            is_async,
2284                            is_generator,
2285                        } = unsafe { &**e }
2286                        {
2287                            let v = self.eval_function_expr(
2288                                name,
2289                                params,
2290                                body,
2291                                *is_arrow,
2292                                *is_async,
2293                                *is_generator,
2294                                scope,
2295                                this,
2296                            )?;
2297                            self.vm_stack.push(v);
2298                        } else {
2299                            self.vm_stack.push(Value::Undefined);
2300                        }
2301                    }
2302                    Op::Regex(lit) => {
2303                        // SAFETY: `Code::_ast` が構文木を保持している。
2304                        let v = self.eval_regex_lit(unsafe { &**lit })?;
2305                        self.vm_stack.push(v);
2306                    }
2307                    Op::DeclVar(pat, slot) => self.op_decl_var(code, *pat, *slot, call_scope)?,
2308                    Op::DeclLexical(name_idx) => {
2309                        let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
2310                        if let Some(name) = code.names.get(*name_idx as usize) {
2311                            infer_function_name(&v, name);
2312                            let scope = block_scopes.last().unwrap_or(call_scope);
2313                            scope.borrow_mut().vars.insert(name.clone(), v);
2314                        }
2315                    }
2316                    Op::EnterBlock => {
2317                        let parent = block_scopes.last().unwrap_or(call_scope).clone();
2318                        block_scopes.push(self.alloc_block_scope(parent));
2319                    }
2320                    Op::LeaveBlocks(n) => {
2321                        for _ in 0..*n {
2322                            if let Some(sc) = block_scopes.pop() {
2323                                self.recycle_block_scope(sc);
2324                            }
2325                        }
2326                    }
2327                    Op::RefreshForLet => {
2328                        if let Some(cur) = block_scopes.last() {
2329                            if Rc::strong_count(cur) > 1 {
2330                                let parent = cur.borrow().parent.clone().unwrap_or_else(|| call_scope.clone());
2331                                let next = self.alloc_block_scope(parent);
2332                                {
2333                                    let cb = cur.borrow();
2334                                    let mut nb = next.borrow_mut();
2335                                    for (k, v) in cb.vars.iter() {
2336                                        nb.vars.insert(k.clone(), v.clone());
2337                                    }
2338                                }
2339                                if let Some(prev) = block_scopes.pop() {
2340                                    self.recycle_block_scope(prev);
2341                                }
2342                                block_scopes.push(next);
2343                            }
2344                        }
2345                    }
2346                    Op::StoreIdent(target, slot) => {
2347                        let scope = block_scopes.last().unwrap_or(call_scope);
2348                        self.op_store(code, *target, *slot, scope, this)?;
2349                    }
2350                    Op::AddAssignIdent(target, slot) => {
2351                        let scope = block_scopes.last().unwrap_or(call_scope);
2352                        self.op_add_assign_ident(code, *target, *slot, scope, this)?;
2353                    }
2354                    Op::StoreMember(name) => self.op_store_member(code, *name)?,
2355                    Op::StoreIndex => self.op_store_index()?,
2356                    Op::UpdateIdent { name, target, delta, prefix, slot } => {
2357                        let scope = block_scopes.last().unwrap_or(call_scope);
2358                        self.op_update(code, *name, *target, *delta, *prefix, *slot, scope, this)?;
2359                    }
2360                    Op::UpdateMember { name, object, delta, prefix, slot } => {
2361                        self.op_update_member(code, *name, *object, *delta, *prefix, *slot)?;
2362                    }
2363                    Op::UpdateIndex { delta, prefix } => {
2364                        self.op_update_index(*delta, *prefix)?;
2365                    }
2366                    Op::Return => return Ok(Some(self.vm_stack.pop().unwrap_or(Value::Undefined))),
2367                    Op::ReturnUndefined => return Ok(Some(Value::Undefined)),
2368                    Op::Throw => {
2369                        let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
2370                        self.note_thrown_value(&v);
2371                        return Err(v);
2372                    }
2373                    Op::Eval(e) => {
2374                        let scope = block_scopes.last().unwrap_or(call_scope);
2375                        // SAFETY: `Code::_ast` が構文木を保持している。
2376                        let v = self.eval(unsafe { &**e }, scope, this)?;
2377                        self.vm_stack.push(v);
2378                    }
2379                    Op::Exec {
2380                        stmt,
2381                        brk,
2382                        cont,
2383                        brk_depth,
2384                        cont_depth,
2385                        brk_try,
2386                        cont_try,
2387                        brk_iters,
2388                        cont_iters,
2389                        lbls,
2390                    } => {
2391                        let scope = block_scopes.last().unwrap_or(call_scope).clone();
2392                        // SAFETY: `Code::_ast` が構文木を保持している。
2393                        match self.exec_stmt(unsafe { &**stmt }, &scope, this)? {
2394                            Completion::Normal(_) => {}
2395                            Completion::Return(v) => return Ok(Some(v)),
2396                            Completion::Break(None) if *brk != NO_LOOP => {
2397                                while block_scopes.len() > *brk_depth as usize {
2398                                    if let Some(sc) = block_scopes.pop() {
2399                                        self.recycle_block_scope(sc);
2400                                    }
2401                                }
2402                                try_stack.truncate(*brk_try as usize);
2403                                for _ in 0..(*brk_iters as usize * 2) {
2404                                    self.vm_stack.pop();
2405                                }
2406                                pc = *brk as usize;
2407                            }
2408                            Completion::Continue(None) if *cont != NO_LOOP => {
2409                                while block_scopes.len() > *cont_depth as usize {
2410                                    if let Some(sc) = block_scopes.pop() {
2411                                        self.recycle_block_scope(sc);
2412                                    }
2413                                }
2414                                try_stack.truncate(*cont_try as usize);
2415                                for _ in 0..(*cont_iters as usize * 2) {
2416                                    self.vm_stack.pop();
2417                                }
2418                                pc = *cont as usize;
2419                            }
2420                            // 外側のラベル付きループ/ブロックへの `break label` / `continue label`。
2421                            Completion::Break(Some(l)) => {
2422                                let tgt = code
2423                                    .exec_labels
2424                                    .get(*lbls as usize)
2425                                    .and_then(|t| t.iter().find(|e| e.label == l && e.brk != NO_LOOP));
2426                                let Some(e) = tgt else { return Ok(Some(Value::Undefined)) };
2427                                while block_scopes.len() > e.brk_depth as usize {
2428                                    if let Some(sc) = block_scopes.pop() {
2429                                        self.recycle_block_scope(sc);
2430                                    }
2431                                }
2432                                try_stack.truncate(e.brk_try as usize);
2433                                for _ in 0..(e.iters as usize * 2) {
2434                                    self.vm_stack.pop();
2435                                }
2436                                pc = e.brk as usize;
2437                            }
2438                            Completion::Continue(Some(l)) => {
2439                                let tgt = code
2440                                    .exec_labels
2441                                    .get(*lbls as usize)
2442                                    .and_then(|t| t.iter().find(|e| e.label == l && e.is_loop && e.cont != NO_LOOP));
2443                                let Some(e) = tgt else { return Ok(Some(Value::Undefined)) };
2444                                while block_scopes.len() > e.cont_depth as usize {
2445                                    if let Some(sc) = block_scopes.pop() {
2446                                        self.recycle_block_scope(sc);
2447                                    }
2448                                }
2449                                try_stack.truncate(e.cont_try as usize);
2450                                for _ in 0..(e.iters as usize * 2) {
2451                                    self.vm_stack.pop();
2452                                }
2453                                pc = e.cont as usize;
2454                            }
2455                            // ループの外の `break` は、構文木の評価と同じく本体の終わりへ。
2456                            Completion::Break(_) | Completion::Continue(_) => return Ok(Some(Value::Undefined)),
2457                        }
2458                    }
2459                }
2460                Ok(None)
2461            })();
2462            match step {
2463                Ok(None) => {}
2464                Ok(Some(ret)) => return Ok(ret),
2465                Err(thrown) => {
2466                    if !self.aborted && !self.is_suspending() && !self.is_gen_returning() {
2467                        if let Some(t) = try_stack.pop() {
2468                            while block_scopes.len() > t.block_depth as usize {
2469                                if let Some(sc) = block_scopes.pop() {
2470                                    self.recycle_block_scope(sc);
2471                                }
2472                            }
2473                            self.vm_stack.truncate(t.stack_len);
2474                            self.vm_stack.push(thrown);
2475                            pc = t.catch_pc as usize;
2476                            continue;
2477                        }
2478                    }
2479                    return Err(thrown);
2480                }
2481            }
2482        }
2483    }
2484
2485    // 実行ループを小さく保つため、重い命令は関数へ分ける(ループへ展開すると全命令が遅くなった)。
2486
2487    #[inline(always)]
2488    fn try_prop_entry(
2489        &self,
2490        b: &Obj,
2491        name: &str,
2492        entry: &PropSlotEntry,
2493        cur_proto: Option<ObjRef>,
2494    ) -> Option<Value> {
2495        if !entry.is_set() {
2496            return None;
2497        }
2498        let idx = entry.index as usize;
2499        let hops = entry.hops;
2500        if hops == 0 {
2501            if let Some((k, v)) = b.props.get_index(idx) {
2502                if k.as_str() == name {
2503                    return Some(v.clone());
2504                }
2505            }
2506        } else if !b.props.contains_key(name) {
2507            let mut cur_opt = cur_proto;
2508            let mut rem = hops;
2509            while let Some(cur) = cur_opt {
2510                rem -= 1;
2511                let cb = cur.borrow();
2512                if cb.has_accessor(name) {
2513                    return None;
2514                }
2515                if rem == 0 {
2516                    if Rc::as_ptr(&cur) == entry.holder {
2517                        if let Some((k, v)) = cb.props.get_index(idx) {
2518                            if k.as_str() == name {
2519                                return Some(v.clone());
2520                            }
2521                        }
2522                    }
2523                    return None;
2524                }
2525                if cb.props.contains_key(name) {
2526                    return None;
2527                }
2528                cur_opt = cb.proto.clone();
2529            }
2530        }
2531        None
2532    }
2533
2534    #[inline(always)]
2535    fn get_prop_fast(&self, obj: &Value, name: &str, slot: &PropSlot) -> Option<Value> {
2536        match obj {
2537            Value::Object(o) => {
2538                let b = o.borrow();
2539                match &b.kind {
2540                    ObjKind::Array(items) => {
2541                        if name == "length" {
2542                            return Some(Value::Number(items.len() as f64));
2543                        }
2544                        if let Some(v) = b.props.get(name) {
2545                            return Some(v.clone());
2546                        }
2547                        if b.has_accessor(name) {
2548                            return None;
2549                        }
2550                        // `Array.prototype` に並べた(差し替えられたかもしれない)メソッドを先に見る。
2551                        // 無い名前・アクセサは遅い経路(原型連鎖 → 組込みの名前表)へ。【2026-11-20】
2552                        return self.builtin_proto_data("Array", name);
2553                    }
2554                    ObjKind::Bytes(_) => {
2555                        if name == "length" {
2556                            return Some(Value::Number(
2557                                crate::os_lib::ecma::value::ta_effective_len(&b).unwrap_or(0) as f64,
2558                            ));
2559                        }
2560                        if let Some(v) = b.props.get(name) {
2561                            return Some(v.clone());
2562                        }
2563                        return None;
2564                    }
2565                    ObjKind::HostRef(h) => {
2566                        let proto_opt = match (self.host.probe)(self, *h, name, false) {
2567                            HostProbe::Skip => return None,
2568                            HostProbe::Own(v) => return Some(v),
2569                            HostProbe::Proto(p) => p,
2570                        };
2571                        let e0 = slot.slot0.get();
2572                        if let Some(v) = self.try_prop_entry(&b, name, &e0, proto_opt.clone()) {
2573                            return Some(v);
2574                        }
2575                        let e1 = slot.slot1.get();
2576                        if let Some(v) = self.try_prop_entry(&b, name, &e1, proto_opt) {
2577                            slot.slot0.set(e1);
2578                            slot.slot1.set(e0);
2579                            return Some(v);
2580                        }
2581                        return None;
2582                    }
2583                    ObjKind::Plain => {
2584                        if b.has_accessor(name) {
2585                            return None;
2586                        }
2587                        let proto_opt = b.proto.clone();
2588                        let is_null_p = b.is_null_proto();
2589                        let e0 = slot.slot0.get();
2590                        if let Some(v) = self.try_prop_entry(&b, name, &e0, proto_opt.clone()) {
2591                            return Some(v);
2592                        }
2593                        let e1 = slot.slot1.get();
2594                        if let Some(v) = self.try_prop_entry(&b, name, &e1, proto_opt.clone()) {
2595                            slot.slot0.set(e1);
2596                            slot.slot1.set(e0);
2597                            return Some(v);
2598                        }
2599                        if !b.props.contains_key(name) && proto_opt.is_none() && !is_null_p {
2600                            return self.builtin_proto_data("Object", name);
2601                        }
2602                    }
2603                    _ => {}
2604                }
2605                None
2606            }
2607            Value::Str(_) => {
2608                if name == "length" {
2609                    return Some(Value::Number(super::super::builtins::cached_units(self, obj).len() as f64));
2610                }
2611                self.builtin_proto_data("String", name)
2612            }
2613            _ => None,
2614        }
2615    }
2616
2617    /// 組込みの原型(`Array.prototype` 等)の自前のデータプロパティ。アクセサや無い名前は `None`(遅い経路へ)。
2618    #[inline]
2619    fn builtin_proto_data(&self, ctor: &str, name: &str) -> Option<Value> {
2620        let p = super::super::builtins::global_ctor_proto(self, ctor)?;
2621        let pb = p.borrow();
2622        if pb.has_accessor(name) {
2623            return None;
2624        }
2625        pb.props.get(name).cloned()
2626    }
2627
2628    #[inline(always)]
2629    fn learn_prop_slot(&self, obj: &Value, name: &str, slot: &PropSlot) {
2630        if let Value::Object(o) = obj {
2631            let b = o.borrow();
2632            let mut cur_opt = match &b.kind {
2633                ObjKind::Plain => {
2634                    if b.has_accessor(name) {
2635                        return;
2636                    }
2637                    if let Some(i) = b.props.get_index_of(name) {
2638                        slot.set_own(i);
2639                        return;
2640                    }
2641                    if name == "__proto__" || name == "selectedIndex" || name == "size" || self.is_window_obj(o) {
2642                        return;
2643                    }
2644                    b.proto.clone()
2645                }
2646                ObjKind::HostRef(h) => match (self.host.probe)(self, *h, name, true) {
2647                    HostProbe::Proto(p) => p,
2648                    _ => return,
2649                },
2650                _ => return,
2651            };
2652            drop(b);
2653            let mut hops = 1u8;
2654            while let Some(cur) = cur_opt {
2655                let cb = cur.borrow();
2656                if cb.has_accessor(name) {
2657                    return;
2658                }
2659                if let Some(i) = cb.props.get_index_of(name) {
2660                    slot.set_proto(hops, Rc::as_ptr(&cur), i);
2661                    return;
2662                }
2663                if hops >= 16 {
2664                    return;
2665                }
2666                hops += 1;
2667                cur_opt = cb.proto.clone();
2668            }
2669        }
2670    }
2671
2672    #[inline(never)]
2673    fn op_typeof_ident(
2674        &mut self,
2675        code: &Code,
2676        name_idx: u32,
2677        slot_idx: u32,
2678        scope: &Rc<RefCell<Scope>>,
2679    ) -> EvalResult {
2680        let (Some(name), Some(slot)) = (code.names.get(name_idx as usize), code.slots.get(slot_idx as usize)) else {
2681            return Ok(Value::str("undefined"));
2682        };
2683        if let Some(t) = slot.with(scope, |v| v.type_of()) {
2684            return Ok(Value::str(t));
2685        }
2686        slot.learn(name, scope);
2687        if let Some(t) = slot.with(scope, |v| v.type_of()) {
2688            return Ok(Value::str(t));
2689        }
2690        if let Value::Object(w) = self.global_window() {
2691            if w.borrow().props.contains_key(name) || w.borrow().has_accessor(name) {
2692                let v = self.get_property(&Value::Object(w), name)?;
2693                return Ok(Value::str(v.type_of()));
2694            }
2695        }
2696        Ok(Value::str("undefined"))
2697    }
2698
2699    #[inline(never)]
2700    fn op_binary_slow(&mut self, op: &BinaryOp, l: Value, r: Value) -> EvalResult {
2701        self.eval_binary(op, l, r)
2702    }
2703
2704    #[inline(never)]
2705    fn op_member(
2706        &mut self,
2707        code: &Code,
2708        name: u32,
2709        object: *const Expression,
2710        slot: u32,
2711    ) -> Result<(), Value> {
2712        let obj = self.vm_stack.pop().unwrap_or(Value::Undefined);
2713        let name_str = code.names.get(name as usize).map_or("", |n| &**n);
2714        let prop_slot = code.prop_slots.get(slot as usize);
2715        if let Some(slot) = prop_slot {
2716            if let Some(v) = self.get_prop_fast(&obj, name_str, slot) {
2717                self.vm_stack.push(v);
2718                return Ok(());
2719            }
2720        }
2721        // SAFETY: `Code::_ast` が構文木を保持している。
2722        let v = self.get_property_of_expr(&obj, name_str, unsafe { &*object })?;
2723        if let Some(slot) = prop_slot {
2724            self.learn_prop_slot(&obj, name_str, slot);
2725        }
2726        self.vm_stack.push(v);
2727        Ok(())
2728    }
2729
2730    #[inline(never)]
2731    fn op_index(&mut self) -> Result<(), Value> {
2732        let key = self.vm_stack.pop().unwrap_or(Value::Undefined);
2733        let obj = self.vm_stack.pop().unwrap_or(Value::Undefined);
2734        let key = self.prim_key_for(&obj, key)?;
2735        let v = match self.get_index_fast(&obj, &key) {
2736            Some(v) => v,
2737            None => {
2738                let fast = if let (Value::Object(o), Value::Str(s)) = (&obj, &key) {
2739                    let b = o.borrow();
2740                    if matches!(b.kind, ObjKind::Plain) && !b.has_accessor(s) {
2741                        b.props.get(s).cloned()
2742                    } else {
2743                        None
2744                    }
2745                } else {
2746                    None
2747                };
2748                match fast {
2749                    Some(v) => v,
2750                    None => self.get_property(&obj, &to_property_key(&key))?,
2751                }
2752            }
2753        };
2754        self.vm_stack.push(v);
2755        Ok(())
2756    }
2757
2758    #[inline(never)]
2759    fn op_method(
2760        &mut self,
2761        code: &Code,
2762        name: u32,
2763        object: *const Expression,
2764        slot: u32,
2765    ) -> Result<(), Value> {
2766        let obj = self.vm_stack.pop().unwrap_or(Value::Undefined);
2767        let name_str = code.names.get(name as usize).map_or("", |n| &**n);
2768        let prop_slot = code.prop_slots.get(slot as usize);
2769        if let Some(slot) = prop_slot {
2770            if let Some(f) = self.get_prop_fast(&obj, name_str, slot) {
2771                self.vm_stack.push(f);
2772                self.vm_stack.push(obj);
2773                return Ok(());
2774            }
2775        }
2776        // SAFETY: `Code::_ast` が構文木を保持している。
2777        let f = self.get_property_of_expr(&obj, name_str, unsafe { &*object })?;
2778        if let Some(slot) = prop_slot {
2779            self.learn_prop_slot(&obj, name_str, slot);
2780        }
2781        self.vm_stack.push(f);
2782        self.vm_stack.push(obj);
2783        Ok(())
2784    }
2785
2786    #[inline(never)]
2787    fn op_method_index(&mut self) -> Result<(), Value> {
2788        let key = self.vm_stack.pop().unwrap_or(Value::Undefined);
2789        let obj = self.vm_stack.pop().unwrap_or(Value::Undefined);
2790        let key = self.prim_key_for(&obj, key)?;
2791        let f = match self.get_index_fast(&obj, &key) {
2792            Some(v) => v,
2793            None => {
2794                let fast = if let (Value::Object(o), Value::Str(s)) = (&obj, &key) {
2795                    let b = o.borrow();
2796                    if matches!(b.kind, ObjKind::Plain) && !b.has_accessor(s) {
2797                        b.props.get(s).cloned()
2798                    } else {
2799                        None
2800                    }
2801                } else {
2802                    None
2803                };
2804                match fast {
2805                    Some(f) => f,
2806                    None => self.get_property(&obj, &to_property_key(&key))?,
2807                }
2808            }
2809        };
2810        self.vm_stack.push(f);
2811        self.vm_stack.push(obj);
2812        Ok(())
2813    }
2814
2815    /// ホットビルトインを `vm_stack` 上で直接実行する(成功時 true、フォールバック時 false)。
2816    #[inline]
2817    fn try_inline_native(&mut self, fn_ptr: NativeFn, at: usize, argc: usize) -> bool {
2818        let fp = fn_ptr as usize;
2819        if fp == super::super::builtins::arr_push as *const () as usize {
2820            if let Value::Object(to) = &self.vm_stack[at - 1] {
2821                let to = to.clone();
2822                let mut b = to.borrow_mut();
2823                if !b.is_frozen() && !b.is_sealed() && !b.has_rare_props() {
2824                    if let ObjKind::Array(items) = &mut b.kind {
2825                        items.extend(self.vm_stack.drain(at..));
2826                        let new_len = items.len() as f64;
2827                        drop(b);
2828                        self.vm_stack.truncate(at - 2);
2829                        self.vm_stack.push(Value::Number(new_len));
2830                        return true;
2831                    }
2832                }
2833            }
2834            return false;
2835        }
2836        if fp == super::super::builtins::arr_pop as *const () as usize && argc == 0 {
2837            if let Value::Object(to) = &self.vm_stack[at - 1] {
2838                let mut b = to.borrow_mut();
2839                // 穴のある配列は穴の印も動かす本来の実装へ(2026-11-16)。
2840                if !b.is_frozen() && !b.is_sealed() && !b.has_rare_props() && b.holes().is_none() {
2841                    if let ObjKind::Array(items) = &mut b.kind {
2842                        let val = items.pop().unwrap_or(Value::Undefined);
2843                        drop(b);
2844                        self.vm_stack.truncate(at - 2);
2845                        self.vm_stack.push(val);
2846                        return true;
2847                    }
2848                }
2849            }
2850            return false;
2851        }
2852        if fp == super::super::builtins::arr_shift as *const () as usize && argc == 0 {
2853            if let Value::Object(to) = &self.vm_stack[at - 1] {
2854                let mut b = to.borrow_mut();
2855                if !b.is_frozen() && !b.is_sealed() && !b.has_rare_props() && b.holes().is_none() {
2856                    if let ObjKind::Array(items) = &mut b.kind {
2857                        let val = if items.is_empty() {
2858                            Value::Undefined
2859                        } else {
2860                            items.remove(0)
2861                        };
2862                        drop(b);
2863                        self.vm_stack.truncate(at - 2);
2864                        self.vm_stack.push(val);
2865                        return true;
2866                    }
2867                }
2868            }
2869            return false;
2870        }
2871        let is_char_code = fp == super::super::builtins::str_char_code_at as *const () as usize;
2872        let is_char_at = !is_char_code && fp == super::super::builtins::str_char_at as *const () as usize;
2873        if (is_char_code || is_char_at)
2874            && argc <= 1
2875            && matches!(self.vm_stack[at - 1], Value::Str(_))
2876        {
2877            let idx = if argc == 0 {
2878                0usize
2879            } else if !matches!(self.vm_stack[at], Value::Object(_)) {
2880                self.vm_stack[at].to_number() as usize
2881            } else {
2882                return false;
2883            };
2884            self.vm_stack.truncate(at);
2885            let recv = self.vm_stack.pop().unwrap_or(Value::Undefined);
2886            self.vm_stack.pop(); // f
2887            let u = super::super::builtins::cached_units(self, &recv).at(idx);
2888            let val = if is_char_code {
2889                match u {
2890                    Some(c) => Value::Number(c as f64),
2891                    None => Value::Number(f64::NAN),
2892                }
2893            } else {
2894                self.char_unit_val(u)
2895            };
2896            self.vm_stack.push(val);
2897            return true;
2898        }
2899        if fp == super::super::builtins::string_from_char_code as *const () as usize && argc == 1 {
2900            if !matches!(self.vm_stack[at], Value::Object(_)) {
2901                let unit = (to_u32(self.vm_stack[at].to_number()) & 0xFFFF) as u16;
2902                let val = self.char_unit_val(Some(unit));
2903                self.vm_stack.truncate(at - 2);
2904                self.vm_stack.push(val);
2905                return true;
2906            }
2907            return false;
2908        }
2909        if argc == 1 && !matches!(self.vm_stack[at], Value::Object(_)) {
2910            let n = self.vm_stack[at].to_number();
2911            let res = if fp == super::super::builtins::math_floor as *const () as usize {
2912                Some(libm::floor(n))
2913            } else if fp == super::super::builtins::math_ceil as *const () as usize {
2914                Some(libm::ceil(n))
2915            } else if fp == super::super::builtins::math_round as *const () as usize {
2916                Some(libm::floor(n + 0.5))
2917            } else if fp == super::super::builtins::math_trunc as *const () as usize {
2918                Some(libm::trunc(n))
2919            } else if fp == super::super::builtins::math_abs as *const () as usize {
2920                Some(libm::fabs(n))
2921            } else {
2922                None
2923            };
2924            if let Some(v) = res {
2925                self.vm_stack.truncate(at - 2);
2926                self.vm_stack.push(Value::Number(v));
2927                return true;
2928            }
2929        }
2930        if fp == super::super::builtins::math_imul as *const () as usize
2931            && argc == 2
2932            && !matches!(self.vm_stack[at], Value::Object(_))
2933            && !matches!(self.vm_stack[at + 1], Value::Object(_))
2934        {
2935            let x = to_i32(self.vm_stack[at].to_number());
2936            let y = to_i32(self.vm_stack[at + 1].to_number());
2937            self.vm_stack.truncate(at - 2);
2938            self.vm_stack.push(Value::Number(x.wrapping_mul(y) as f64));
2939            return true;
2940        }
2941        if fp == super::super::builtins::array_is_array as *const () as usize && argc == 1 {
2942            let is_arr = match &self.vm_stack[at] {
2943                Value::Object(o) => {
2944                    let b = o.borrow();
2945                    match &b.kind {
2946                        ObjKind::Array(_) => !b.props.contains_key("_ta_kind"),
2947                        ObjKind::Proxy(_) => return false,
2948                        _ => false,
2949                    }
2950                }
2951                _ => false,
2952            };
2953            self.vm_stack.truncate(at - 2);
2954            self.vm_stack.push(Value::Bool(is_arr));
2955            return true;
2956        }
2957        false
2958    }
2959
2960    #[inline(never)]
2961    fn op_call(&mut self, argc: u32, callee: *const Expression) -> Result<(), Value> {
2962        let stack_len = self.vm_stack.len();
2963        let argc = argc as usize;
2964        let at = stack_len.saturating_sub(argc);
2965        if at >= 2 {
2966            let target = match &self.vm_stack[at - 2] {
2967                Value::Object(fo) => extract_call_target(fo, self.host),
2968                _ => CallKind::NotCallable(""),
2969            };
2970            if let CallKind::NotCallable(_) = target {
2971                self.vm_stack.truncate(at);
2972                let call_this = self.vm_stack.pop().unwrap_or(Value::Undefined);
2973                let fv = self.vm_stack.pop().unwrap_or(Value::Undefined);
2974                let err = self
2975                    .not_callable(&fv, unsafe { &*callee }, &call_this)
2976                    .unwrap_or(Value::Undefined);
2977                return Err(err);
2978            }
2979            if let CallKind::Native(fn_ptr) = target {
2980                if self.try_inline_native(fn_ptr, at, argc) {
2981                    return Ok(());
2982                }
2983            }
2984            if argc <= 4 {
2985                let mut inline_args = [const { Value::Undefined }; 4];
2986                for slot in inline_args[..argc].iter_mut().rev() {
2987                    *slot = self.vm_stack.pop().unwrap_or(Value::Undefined);
2988                }
2989                let call_this = self.vm_stack.pop().unwrap_or(Value::Undefined);
2990                let f = self.vm_stack.pop().unwrap_or(Value::Undefined);
2991                self.call_enter(&f)?;
2992                let r = self.dispatch_call_kind(target, &f, call_this, &inline_args[..argc]);
2993                self.call_leave();
2994                self.vm_stack.push(r?);
2995                return Ok(());
2996            }
2997            let mut args = self.arg_pool.pop().unwrap_or_default();
2998            args.extend(self.vm_stack.drain(at..));
2999            let call_this = self.vm_stack.pop().unwrap_or(Value::Undefined);
3000            let f = self.vm_stack.pop().unwrap_or(Value::Undefined);
3001            self.call_enter(&f)?;
3002            let r = self.dispatch_call_kind(target, &f, call_this, &args);
3003            self.call_leave();
3004            self.recycle_args(args);
3005            self.vm_stack.push(r?);
3006            return Ok(());
3007        }
3008        let mut args = self.arg_pool.pop().unwrap_or_default();
3009        args.extend(self.vm_stack.drain(at..));
3010        let call_this = self.vm_stack.pop().unwrap_or(Value::Undefined);
3011        let f = self.vm_stack.pop().unwrap_or(Value::Undefined);
3012        if let Some(e) = self.not_callable(&f, unsafe { &*callee }, &call_this) {
3013            return Err(e);
3014        }
3015        let r = self.call_value(&f, call_this, &args);
3016        self.recycle_args(args);
3017        self.vm_stack.push(r?);
3018        Ok(())
3019    }
3020
3021    #[inline(never)]
3022    fn op_call_with_args(&mut self, callee: *const Expression) -> Result<(), Value> {
3023        let args_val = self.vm_stack.pop().unwrap_or(Value::Undefined);
3024        let call_this = self.vm_stack.pop().unwrap_or(Value::Undefined);
3025        let f = self.vm_stack.pop().unwrap_or(Value::Undefined);
3026        if let (Value::Object(fo), Value::Object(to)) = (&f, &call_this) {
3027            let fn_ptr = if let ObjKind::Native { func, .. } = fo.borrow().kind {
3028                func as usize
3029            } else {
3030                0
3031            };
3032            if fn_ptr == super::super::builtins::arr_push as *const () as usize {
3033                if let Value::Object(ao) = &args_val {
3034                    let mut b = to.borrow_mut();
3035                    if !b.is_frozen() && !b.is_sealed() && !b.has_rare_props() {
3036                        if let ObjKind::Array(items) = &mut b.kind {
3037                            let ab = ao.borrow();
3038                            if let ObjKind::Array(src_items) = &ab.kind {
3039                                items.extend_from_slice(src_items);
3040                                let new_len = items.len() as f64;
3041                                drop(b);
3042                                drop(ab);
3043                                self.vm_stack.push(Value::Number(new_len));
3044                                return Ok(());
3045                            }
3046                        }
3047                    }
3048                }
3049            }
3050        }
3051        if let Some(e) = self.not_callable(&f, unsafe { &*callee }, &call_this) {
3052            return Err(e);
3053        }
3054        let mut args = self.arg_pool.pop().unwrap_or_default();
3055        if let Value::Object(o) = &args_val {
3056            if let ObjKind::Array(items) = &o.borrow().kind {
3057                args.extend(items.iter().cloned());
3058            }
3059        }
3060        let r = self.call_value(&f, call_this, &args);
3061        self.recycle_args(args);
3062        self.vm_stack.push(r?);
3063        Ok(())
3064    }
3065
3066    /// 変換の対象は単純な名前だけで、巻き上げ済みなので関数のスコープに必ずある。
3067    #[inline(never)]
3068    fn op_decl_var(
3069        &mut self,
3070        code: &Code,
3071        pat: *const Pattern,
3072        slot: u32,
3073        scope: &Rc<RefCell<Scope>>,
3074    ) -> Result<(), Value> {
3075        let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
3076        // SAFETY: `Code::_ast` が構文木を保持している。
3077        let (Pattern::Identifier(name), Some(slot)) = (unsafe { &*pat }, code.slots.get(slot as usize)) else {
3078            return Ok(());
3079        };
3080        infer_function_name(&v, name);
3081        let mut v = Some(v);
3082        let done = slot.with(scope, |cell| {
3083            if let Some(v) = v.take() {
3084                *cell = v;
3085            }
3086        });
3087        if done.is_none() {
3088            scope.borrow_mut().vars.insert(name.clone(), v.take().unwrap_or(Value::Undefined));
3089            slot.learn(name, scope);
3090        }
3091        Ok(())
3092    }
3093
3094    #[inline(never)]
3095    fn op_store(
3096        &mut self,
3097        code: &Code,
3098        target: *const Expression,
3099        slot: u32,
3100        scope: &Rc<RefCell<Scope>>,
3101        this: &Value,
3102    ) -> Result<(), Value> {
3103        let Some(slot) = code.slots.get(slot as usize) else { return Ok(()) };
3104        let v = self.vm_stack.last().cloned().unwrap_or(Value::Undefined);
3105        // SAFETY: `Code::_ast` が構文木を保持している。
3106        let target = unsafe { &*target };
3107        if let Expression::Identifier(name) = target {
3108            infer_function_name(&v, name);
3109        }
3110        self.store_slot(target, v, slot, scope, this)
3111    }
3112
3113    /// `name += value`。スタックの `[今の値, 右辺]` を取り、結果を残す。
3114    ///
3115    /// 【2026-11-05】文字列を伸ばすループ(`s += x`)が毎回 `s` 全体を写して新しい文字列を作り、長さの 2 乗の
3116    /// 写しになっていた(QEMU の YouTube で `memcpy` の最大の呼び出し元が二項演算)。右辺を評価した後で、変数が持つ文字列を
3117    /// 参照しているのが変数と読み出した値の 2 つだけなら、読み出した方を手放して変数の文字列の末尾に足す。
3118    fn op_add_assign_ident(
3119        &mut self,
3120        code: &Code,
3121        target: *const Expression,
3122        slot: u32,
3123        scope: &Rc<RefCell<Scope>>,
3124        this: &Value,
3125    ) -> Result<(), Value> {
3126        let rhs = self.vm_stack.pop().unwrap_or(Value::Undefined);
3127        let mut cur = self.vm_stack.pop().unwrap_or(Value::Undefined);
3128        if let (Value::Str(_), Value::Str(_) | Value::Number(_), Some(slot_ref)) =
3129            (&cur, &rhs, code.slots.get(slot as usize))
3130        {
3131            let add: alloc::borrow::Cow<'_, str> = match &rhs {
3132                Value::Str(s) => alloc::borrow::Cow::Borrowed(s.as_str()),
3133                _ => alloc::borrow::Cow::Owned(rhs.to_js_string()),
3134            };
3135            let mut held = Some(cur);
3136            let done = slot_ref
3137                .with_is_global(scope, |cell| {
3138                    let sole = match (&held, &*cell) {
3139                        (Some(Value::Str(a)), Value::Str(b)) => {
3140                            Rc::ptr_eq(a, b) && Rc::strong_count(b) == 2 && Rc::weak_count(b) == 0
3141                        }
3142                        _ => false,
3143                    };
3144                    if !sole {
3145                        return None;
3146                    }
3147                    held = None;
3148                    if let Value::Str(b) = cell {
3149                        if let Some(m) = Rc::get_mut(b) {
3150                            m.push_str(&add);
3151                            return Some(cell.clone());
3152                        }
3153                    }
3154                    None
3155                });
3156            if let Some((Some(v), is_global)) = done {
3157                if is_global {
3158                    // SAFETY: `Code::_ast` が構文木を保持している。
3159                    if let Expression::Identifier(name) = unsafe { &*target } {
3160                        let _ = self.sync_global_prop_if_present(name, &v);
3161                    }
3162                }
3163                self.vm_stack.push(v);
3164                return Ok(());
3165            }
3166            // 足せなかった(ほかからも参照されている等)。手放していたら変数の値(同じ文字列)を読み直す。
3167            cur = match held {
3168                Some(c) => c,
3169                None => slot_ref.with(scope, |c| c.clone()).unwrap_or(Value::Undefined),
3170            };
3171        }
3172        let v = self.eval_binary(&BinaryOp::Add, cur, rhs)?;
3173        self.vm_stack.push(v);
3174        self.op_store(code, target, slot, scope, this)
3175    }
3176
3177    #[inline(never)]
3178    fn op_store_member(&mut self, code: &Code, name: u32) -> Result<(), Value> {
3179        let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
3180        let obj = self.vm_stack.pop().unwrap_or(Value::Undefined);
3181        let Some(name_rc) = code.names.get(name as usize) else {
3182            self.vm_stack.push(v);
3183            return Ok(());
3184        };
3185        if matches!(obj, Value::Undefined | Value::Null) {
3186            return Err(self.set_on_nullish_error(&obj, name_rc));
3187        }
3188        if let Value::Object(o) = &v {
3189            let anon = matches!(&o.borrow().kind, ObjKind::Function(fd) if fd.name().is_empty());
3190            if anon {
3191                o.borrow_mut().props.insert("_diag_name".into(), Value::str(&**name_rc));
3192            }
3193        }
3194        self.put_value_rc(&obj, name_rc, v.clone())?;
3195        self.vm_stack.push(v);
3196        Ok(())
3197    }
3198
3199    #[inline(never)]
3200    fn op_store_index(&mut self) -> Result<(), Value> {
3201        let v = self.vm_stack.pop().unwrap_or(Value::Undefined);
3202        let key = self.vm_stack.pop().unwrap_or(Value::Undefined);
3203        let obj = self.vm_stack.pop().unwrap_or(Value::Undefined);
3204        let key = self.prim_key_for(&obj, key)?;
3205        if matches!(obj, Value::Undefined | Value::Null) {
3206            return Err(self.set_on_nullish_error(&obj, &to_property_key(&key)));
3207        }
3208        if matches!(key, Value::Number(_)) {
3209            if let Some(rem) = self.set_index_fast(&obj, &key, v.clone()) {
3210                self.put_value(&obj, &to_property_key(&key), rem)?;
3211            }
3212        } else {
3213            let fast_stored = if let (Value::Object(o), Value::Str(s)) = (&obj, &key) {
3214                let mut b = o.borrow_mut();
3215                if matches!(b.kind, ObjKind::Plain)
3216                    && !b.is_frozen()
3217                    && !b.is_sealed()
3218                    && !b.has_rare_props()
3219                    && !b.has_accessor(s)
3220                    && (b.props.contains_key(s) || !b.is_non_extensible())
3221                    && b.proto.is_none()
3222                {
3223                    b.props.insert(PropKey::from(&**s), v.clone());
3224                    true
3225                } else {
3226                    false
3227                }
3228            } else {
3229                false
3230            };
3231            if !fast_stored {
3232                self.put_value(&obj, &to_property_key(&key), v.clone())?;
3233            }
3234        }
3235        self.vm_stack.push(v);
3236        Ok(())
3237    }
3238
3239    #[inline(never)]
3240    #[allow(clippy::too_many_arguments)]
3241    fn op_update(
3242        &mut self,
3243        code: &Code,
3244        name: u32,
3245        target: *const Expression,
3246        delta: f64,
3247        prefix: bool,
3248        slot: u32,
3249        scope: &Rc<RefCell<Scope>>,
3250        this: &Value,
3251    ) -> Result<(), Value> {
3252        let (Some(n), Some(slot)) = (code.names.get(name as usize), code.slots.get(slot as usize)) else {
3253            return Ok(());
3254        };
3255        let old = self.load_slot(n, slot, scope)?;
3256        if let Value::Number(o) = old {
3257            let new = o + delta;
3258            // SAFETY: `Code::_ast` が構文木を保持している。
3259            self.store_slot(unsafe { &*target }, Value::Number(new), slot, scope, this)?;
3260            self.vm_stack.push(Value::Number(if prefix { new } else { o }));
3261            return Ok(());
3262        }
3263        let (old, new) = self.numeric_step(&old, delta)?;
3264        // SAFETY: `Code::_ast` が構文木を保持している。
3265        self.store_slot(unsafe { &*target }, new.clone(), slot, scope, this)?;
3266        self.vm_stack.push(if prefix { new } else { old });
3267        Ok(())
3268    }
3269
3270    #[inline(never)]
3271    fn op_update_member(
3272        &mut self,
3273        code: &Code,
3274        name: u32,
3275        object: *const Expression,
3276        delta: f64,
3277        prefix: bool,
3278        slot: u32,
3279    ) -> Result<(), Value> {
3280        let obj = self.vm_stack.pop().unwrap_or(Value::Undefined);
3281        let Some(name_rc) = code.names.get(name as usize) else {
3282            self.vm_stack.push(Value::Number(f64::NAN));
3283            return Ok(());
3284        };
3285        let prop_slot = code.prop_slots.get(slot as usize);
3286        let cur = if let Some(s) = prop_slot {
3287            match self.get_prop_fast(&obj, name_rc, s) {
3288                Some(v) => v,
3289                None => {
3290                    // SAFETY: `Code::_ast` が構文木を保持している。
3291                    let v = self.get_property_of_expr(&obj, name_rc, unsafe { &*object })?;
3292                    self.learn_prop_slot(&obj, name_rc, s);
3293                    v
3294                }
3295            }
3296        } else {
3297            // SAFETY: `Code::_ast` が構文木を保持している。
3298            self.get_property_of_expr(&obj, name_rc, unsafe { &*object })?
3299        };
3300        let (old, new) = self.numeric_step(&cur, delta)?;
3301        self.put_value_rc(&obj, name_rc, new.clone())?;
3302        self.vm_stack.push(if prefix { new } else { old });
3303        Ok(())
3304    }
3305
3306    #[inline(never)]
3307    fn op_update_index(&mut self, delta: f64, prefix: bool) -> Result<(), Value> {
3308        let key = self.vm_stack.pop().unwrap_or(Value::Undefined);
3309        let obj = self.vm_stack.pop().unwrap_or(Value::Undefined);
3310        let key = self.prim_key_for(&obj, key)?;
3311        if matches!(key, Value::Number(_)) {
3312            if let Some(old_val) = self.get_index_fast(&obj, &key).filter(|v| !matches!(v, Value::BigInt(_))) {
3313                let old = old_val.to_number();
3314                let new = old + delta;
3315                if let Some(rem) = self.set_index_fast(&obj, &key, Value::Number(new)) {
3316                    self.put_value(&obj, &to_property_key(&key), rem)?;
3317                }
3318                self.vm_stack.push(Value::Number(if prefix { new } else { old }));
3319                return Ok(());
3320            }
3321        }
3322        let k = to_property_key(&key);
3323        let cur = self.get_property(&obj, &k)?;
3324        let (old, new) = self.numeric_step(&cur, delta)?;
3325        self.put_value(&obj, &k, new.clone())?;
3326        self.vm_stack.push(if prefix { new } else { old });
3327        Ok(())
3328    }
3329
3330    #[inline(never)]
3331    fn op_delete_member(&mut self, code: &Code, name: u32) -> Result<(), Value> {
3332        let obj = self.vm_stack.pop().unwrap_or(Value::Undefined);
3333        let name_str = code.names.get(name as usize).map_or("", |n| &**n);
3334        let v = self.delete_property(&obj, name_str)?;
3335        let v = self.delete_checked(v, name_str)?;
3336        self.vm_stack.push(v);
3337        Ok(())
3338    }
3339
3340    #[inline(never)]
3341    fn op_delete_index(&mut self) -> Result<(), Value> {
3342        let key = self.vm_stack.pop().unwrap_or(Value::Undefined);
3343        let obj = self.vm_stack.pop().unwrap_or(Value::Undefined);
3344        let key = self.prim_key_for(&obj, key)?;
3345        let k = to_property_key(&key);
3346        let v = self.delete_property(&obj, &k)?;
3347        let v = self.delete_checked(v, &k)?;
3348        self.vm_stack.push(v);
3349        Ok(())
3350    }
3351
3352    #[inline(never)]
3353    fn op_array(&mut self, len: u32) {
3354        let at = self.vm_stack.len().saturating_sub(len as usize);
3355        let vals: Vec<Value> = self.vm_stack.drain(at..).collect();
3356        self.vm_stack.push(Value::Object(Obj::array(vals)));
3357    }
3358
3359    #[inline(never)]
3360    fn op_init_prop(&mut self, code: &Code, name: u32) {
3361        let val = self.vm_stack.pop().unwrap_or(Value::Undefined);
3362        let Some(name_rc) = code.names.get(name as usize) else { return };
3363        infer_function_name(&val, name_rc);
3364        if let Some(Value::Object(o)) = self.vm_stack.last() {
3365            o.borrow_mut().props.insert(PropKey::from(name_rc), val);
3366        }
3367    }
3368
3369    #[inline(never)]
3370    fn op_init_prop_computed(&mut self) -> Result<(), Value> {
3371        let val = self.vm_stack.pop().unwrap_or(Value::Undefined);
3372        let key_val = self.vm_stack.pop().unwrap_or(Value::Undefined);
3373        let key_val = self.prim_key(key_val)?;
3374        let key: PropKey = to_property_key(&key_val).as_ref().into();
3375        infer_function_name(&val, key.as_str());
3376        if let Some(Value::Object(o)) = self.vm_stack.last() {
3377            o.borrow_mut().props.insert(key, val);
3378        }
3379        Ok(())
3380    }
3381
3382    #[inline(never)]
3383    fn op_spread_object(&mut self) -> Result<(), Value> {
3384        let src = self.vm_stack.pop().unwrap_or(Value::Undefined);
3385        let Some(target) = self.vm_stack.last().cloned() else { return Ok(()) };
3386        if let Value::Object(to) = target {
3387            // 【2026-11-17】`{..."ab"}` は文字列の添字を写す(以前は無視)。
3388            if let Value::Str(st) = &src {
3389                for (i, c) in st.chars().enumerate() {
3390                    to.borrow_mut().props.insert(i.to_string().into(), Value::str(c.to_string()));
3391                }
3392                return Ok(());
3393            }
3394            if let Value::Object(so) = &src {
3395                let (kind_is_array, items, prop_entries, getters) = {
3396                    let b = so.borrow();
3397                    match &b.kind {
3398                        ObjKind::Array(items) => (true, items.clone(), Vec::new(), Vec::new()),
3399                        ObjKind::Iter | ObjKind::GenReturn => (false, Vec::new(), Vec::new(), Vec::new()),
3400                        ObjKind::HostRef(h) if !matches!((self.host.keys)(self, *h), HostKeys::Generic) => {
3401                            (false, Vec::new(), Vec::new(), Vec::new())
3402                        }
3403                        _ => {
3404                            let plain_entries: Vec<(String, Value)> = b
3405                                .props
3406                                .iter()
3407                                .filter(|(k, _)| {
3408                                    if super::super::builtins::is_symbol_like_key(k) {
3409                                        return false;
3410                                    }
3411                                    b.is_enumerable(k)
3412                                })
3413                                .map(|(k, v)| (k.to_string(), v.clone()))
3414                                .collect();
3415                            let mut prop_entries: Vec<(String, Value)> =
3416                                super::super::builtins::spec_key_order(plain_entries);
3417                            prop_entries.extend(
3418                                b.props
3419                                    .iter()
3420                                    .filter(|(k, _)| {
3421                                        super::super::builtins::is_symbol_like_key(k)
3422                                            && b.is_enumerable(k)
3423                                    })
3424                                    .map(|(k, v)| (k.to_string(), v.clone())),
3425                            );
3426                            let getters: Vec<(String, Value)> =
3427                                super::super::builtins::accessor_only_keys(&b)
3428                                    .into_iter()
3429                                    .filter(|k| b.is_enumerable(k))
3430                                    .filter_map(|k| b.get_getter(&k).map(|g| (k, g)))
3431                                    .collect();
3432                            (false, Vec::new(), prop_entries, getters)
3433                        }
3434                    }
3435                };
3436                if kind_is_array {
3437                    for (i, v) in items.iter().enumerate() {
3438                        to.borrow_mut().props.insert(alloc::format!("{}", i).into(), v.clone());
3439                    }
3440                } else {
3441                    for (k, v) in prop_entries {
3442                        to.borrow_mut().props.insert(k.into(), v);
3443                    }
3444                    for (k, g) in getters {
3445                        let v = self.call_value(&g, src.clone(), &[])?;
3446                        to.borrow_mut().props.insert(k.into(), v);
3447                    }
3448                }
3449            } else if let Value::Str(s) = &src {
3450                for (i, ch) in s.chars().enumerate() {
3451                    to.borrow_mut()
3452                        .props
3453                        .insert(alloc::format!("{}", i).into(), Value::str(alloc::string::String::from(ch)));
3454                }
3455            }
3456        }
3457        Ok(())
3458    }
3459
3460    #[inline(never)]
3461    fn op_array_spread(&mut self) -> Result<(), Value> {
3462        let src = self.vm_stack.pop().unwrap_or(Value::Undefined);
3463        let items = self.spread_values(&src)?;
3464        if let Some(Value::Object(target_rc)) = self.vm_stack.last() {
3465            let mut b = target_rc.borrow_mut();
3466            for it in items {
3467                b.array_push(it);
3468            }
3469        }
3470        Ok(())
3471    }
3472
3473    #[inline(never)]
3474    fn op_new(&mut self, argc: u32) -> Result<(), Value> {
3475        let at = self.vm_stack.len().saturating_sub(argc as usize);
3476        let mut args = self.arg_pool.pop().unwrap_or_default();
3477        args.extend(self.vm_stack.drain(at..));
3478        let func = self.vm_stack.pop().unwrap_or(Value::Undefined);
3479        let proxy = match &func {
3480            Value::Object(o) => match &o.borrow().kind {
3481                ObjKind::Proxy(p) => Some((p.target.clone(), p.handler.clone())),
3482                _ => None,
3483            },
3484            _ => None,
3485        };
3486        let res = if let Some((target, handler)) = proxy {
3487            let trap = handler.borrow().props.get("construct").cloned();
3488            if let Some(trap) =
3489                trap.filter(|t| matches!(t, Value::Object(f) if f.borrow().is_callable()))
3490            {
3491                let arg_arr = Value::Object(Obj::array(args.clone()));
3492                let targs = [
3493                    Value::Object(target),
3494                    arg_arr,
3495                    Value::Object(handler.clone()),
3496                ];
3497                self.call_value(&trap, Value::Object(handler), &targs)
3498            } else {
3499                self.construct_object(&Value::Object(target), &args)
3500            }
3501        } else {
3502            self.construct_object(&func, &args)
3503        };
3504        self.recycle_args(args);
3505        self.vm_stack.push(res?);
3506        Ok(())
3507    }
3508
3509    #[inline(never)]
3510    fn op_template(&mut self, quasis: *const Vec<String>, len: u32) -> Result<(), Value> {
3511        let at = self.vm_stack.len().saturating_sub(len as usize);
3512        let mut vals = self.arg_pool.pop().unwrap_or_default();
3513        vals.extend(self.vm_stack.drain(at..));
3514        // SAFETY: `Code::_ast` が構文木を保持している。
3515        let quasis = unsafe { &*quasis };
3516        let mut s = String::new();
3517        for (i, q) in quasis.iter().enumerate() {
3518            s.push_str(q);
3519            if let Some(v) = vals.get(i).cloned() {
3520                match self.to_string_value(v) {
3521                    Ok(sv) => s.push_str(&sv),
3522                    Err(e) => {
3523                        self.recycle_args(vals);
3524                        return Err(e);
3525                    }
3526                }
3527            }
3528        }
3529        self.recycle_args(vals);
3530        self.vm_stack.push(Value::str(s));
3531        Ok(())
3532    }
3533
3534    #[inline(never)]
3535    fn op_iter_init(&mut self, of: bool) -> Result<(), Value> {
3536        let obj = self.vm_stack.pop().unwrap_or(Value::Undefined);
3537        // 反復の途中の例外は、要素を回し終えた後(`IterNext` が尽きたとき)に投げる(`deferred_iter_err`)。
3538        let mut deferred = None;
3539        let items = self.iterate_values_deferred(&obj, of, &mut deferred)?;
3540        let arr = Obj::array(items);
3541        if let Some(e) = deferred {
3542            arr.borrow_mut().props.insert("_iterr".into(), e);
3543        }
3544        self.vm_stack.push(Value::Object(arr));
3545        self.vm_stack.push(Value::Number(0.0));
3546        Ok(())
3547    }
3548
3549    #[inline]
3550    fn pop_next_iter_item(
3551        &mut self,
3552        is_lexical: bool,
3553        call_scope: &Rc<RefCell<Scope>>,
3554        block_scopes: &mut Vec<Rc<RefCell<Scope>>>,
3555    ) -> Option<Value> {
3556        let len = self.vm_stack.len();
3557        if len < 2 {
3558            return None;
3559        }
3560        let idx = match &self.vm_stack[len - 1] {
3561            Value::Number(n) => *n as usize,
3562            _ => return None,
3563        };
3564        let item_opt = match &self.vm_stack[len - 2] {
3565            Value::Object(o) => match &o.borrow().kind {
3566                ObjKind::Array(items) => items.get(idx).cloned(),
3567                _ => None,
3568            },
3569            _ => None,
3570        };
3571        let item = item_opt?;
3572        self.vm_stack[len - 1] = Value::Number((idx + 1) as f64);
3573        if is_lexical {
3574            if let Some(cur) = block_scopes.last() {
3575                if Rc::strong_count(cur) > 1 {
3576                    let parent = cur.borrow().parent.clone().unwrap_or_else(|| call_scope.clone());
3577                    let next = self.alloc_block_scope(parent);
3578                    if let Some(prev) = block_scopes.pop() {
3579                        self.recycle_block_scope(prev);
3580                    }
3581                    block_scopes.push(next);
3582                }
3583            }
3584        }
3585        Some(item)
3586    }
3587
3588    /// 要素が尽きた反復の配列に、途中の例外(`_iterr`)が残っていれば投げる(for-of が最後まで回ったときだけ呼ぶ)。
3589    #[cold]
3590    fn throw_deferred_iter_err(&mut self) -> Result<(), Value> {
3591        let len = self.vm_stack.len();
3592        if len < 2 {
3593            return Ok(());
3594        }
3595        let err = match &self.vm_stack[len - 2] {
3596            Value::Object(o) => o.borrow().props.get("_iterr").cloned(),
3597            _ => None,
3598        };
3599        match err {
3600            Some(e) => Err(e),
3601            None => Ok(()),
3602        }
3603    }
3604
3605    #[inline(never)]
3606    fn op_iter_next(
3607        &mut self,
3608        code: &Code,
3609        name_idx: u32,
3610        slot_idx: u32,
3611        is_lexical: bool,
3612        call_scope: &Rc<RefCell<Scope>>,
3613        block_scopes: &mut Vec<Rc<RefCell<Scope>>>,
3614    ) -> bool {
3615        let Some(item) = self.pop_next_iter_item(is_lexical, call_scope, block_scopes) else {
3616            return false;
3617        };
3618        let (Some(name), Some(slot)) = (code.names.get(name_idx as usize), code.slots.get(slot_idx as usize)) else {
3619            return true;
3620        };
3621        let scope = block_scopes.last().unwrap_or(call_scope);
3622        let mut v = Some(item);
3623        let done = slot.with(scope, |cell| {
3624            if let Some(val) = v.take() {
3625                *cell = val;
3626            }
3627        });
3628        if done.is_none() {
3629            scope.borrow_mut().vars.insert(name.clone(), v.take().unwrap_or(Value::Undefined));
3630            slot.learn(name, scope);
3631        }
3632        true
3633    }
3634}