Skip to main content

atmos/os_lib/ecma/
ast.rs

1//! JavaScript の抽象構文木(実用コア相当)。
2//!
3//! Phase 1 のスコープ: 関数/クロージャ・制御構文・全演算子・オブジェクト/配列・
4//! メンバ/添字/呼出/new・三項・論理・代入・try/catch/throw。
5//! 分割代入・デフォルト引数・class などのモダン構文は Phase 4 で拡張する。
6
7use alloc::boxed::Box;
8use alloc::rc::Rc;
9use core::cell::{Cell, RefCell};
10use alloc::string::String;
11use alloc::vec::Vec;
12
13#[derive(Debug, Clone, PartialEq)]
14pub enum BinaryOp {
15    Add,
16    Sub,
17    Mul,
18    Div,
19    Mod,
20    Pow,
21    Eq,
22    NotEq,
23    StrictEq,
24    StrictNotEq,
25    Lt,
26    Gt,
27    LtEq,
28    GtEq,
29    BitAnd,
30    BitOr,
31    BitXor,
32    Shl,
33    Shr,
34    UShr,
35    InstanceOf,
36    In,
37}
38
39#[derive(Debug, Clone, PartialEq)]
40pub enum LogicalOp {
41    And,     // &&
42    Or,      // ||
43    Nullish, // ??
44}
45
46#[derive(Debug, Clone, PartialEq)]
47pub enum UnaryOp {
48    Neg,    // -x
49    Pos,    // +x
50    Not,    // !x
51    BitNot, // ~x
52    TypeOf, // typeof x
53    Void,   // void x
54    Delete, // delete x
55}
56
57/// オブジェクトリテラルのプロパティ。
58#[derive(Debug, Clone, PartialEq)]
59pub struct Property {
60    pub key: Rc<str>,
61    pub value: Expression,
62    /// 算出キー `{[expr]: v}` の場合のキー式。None なら `key` を使う。
63    pub computed: Option<Expression>,
64    /// `{get x(){...}}`/`{set x(v){...}}` アクセサの場合 `Some(true)`/`Some(false)`。
65    /// 通常のプロパティ(値/メソッド短縮/短縮プロパティ)は `None`。
66    pub accessor: Option<bool>,
67}
68
69/// オブジェクトスプレッド `{...o}` を表す Property.key の番兵(通常キーと衝突しない制御文字)。
70pub const OBJECT_SPREAD_KEY: &str = "\u{0}spread";
71
72#[derive(Debug, Clone, PartialEq)]
73pub enum Expression {
74    Number(f64),
75    /// BigInt リテラル(数値部分の文字列。0x/0o/0b 接頭辞を含み得る)。
76    BigIntLit(String),
77    Str(String),
78    Bool(bool),
79    Null,
80    Undefined,
81    Identifier(Rc<str>),
82    This,
83    TemplateLiteral {
84        // quasis.len() == exprs.len() + 1
85        // 【2026-10-27】Expression を 56→48 バイトにするため、2 つの Vec は箱に入れてポインタ 1 個ずつにした。
86        quasis: Box<Vec<String>>,
87        exprs: Box<Vec<Expression>>,
88    },
89    /// タグ付きテンプレート `` tag`...${e}...` ``(ES2015)。`quasis`/`raw` は
90    /// `TemplateLiteral` と同様 exprs より1つ多い。`tag(strings, ...values)` 呼出しで
91    /// `strings` は `quasis` の配列に `.raw`(`raw` の配列)を added property として持つ。
92    TaggedTemplate {
93        tag: Box<Expression>,
94        quasis: Box<Vec<String>>,
95        raw: Box<Vec<String>>,
96        exprs: Box<Vec<Expression>>,
97    },
98    /// 配列リテラルの穴(`[1,,3]` の 2 番目)。値は undefined だが、要素として存在しない(2026-11-12)。
99    Elision,
100    Array(Vec<Expression>),
101    Object(Vec<Property>),
102    /// 関数式・アロー関数。本体と引数は `Rc` で共有する(【2026-10-17】従来は評価のたびに
103    /// 本体の構文木を丸ごと複製しており、YouTube の base.js(全体が 1 つの即時関数)で
104    /// 約 100MB の複製が起きていた)。
105    Function {
106        /// 【2026-10-27】`Option<String>`(24 バイト)から `Option<Rc<str>>`(16 バイト)へ。
107        /// Expression を 48 バイトに収めるため。
108        name: Option<Rc<str>>,
109        params: Rc<Vec<Param>>,
110        body: Rc<FnBody>,
111        is_arrow: bool,
112        is_async: bool,
113        is_generator: bool,
114    },
115    /// `await expr`。
116    Await(Box<Expression>),
117    /// `yield expr` / `yield* expr`。
118    Yield {
119        argument: Option<Box<Expression>>,
120        delegate: bool,
121    },
122    Unary {
123        op: UnaryOp,
124        expr: Box<Expression>,
125    },
126    Update {
127        op: &'static str, // "++" / "--"
128        prefix: bool,
129        target: Box<Expression>,
130    },
131    Binary {
132        op: BinaryOp,
133        left: Box<Expression>,
134        right: Box<Expression>,
135    },
136    Logical {
137        op: LogicalOp,
138        left: Box<Expression>,
139        right: Box<Expression>,
140    },
141    Assign {
142        op: &'static str, // "=", "+=", "-=", ...
143        target: Box<Expression>,
144        value: Box<Expression>,
145    },
146    Conditional {
147        test: Box<Expression>,
148        consequent: Box<Expression>,
149        alternate: Box<Expression>,
150    },
151    Member {
152        object: Box<Expression>,
153        property: Rc<str>,
154        optional: bool, // a?.b
155    },
156    Index {
157        object: Box<Expression>,
158        index: Box<Expression>,
159        optional: bool, // a?.[b]
160    },
161    Call {
162        callee: Box<Expression>,
163        arguments: Vec<Expression>,
164        optional: bool, // a?.()
165    },
166    New {
167        callee: Box<Expression>,
168        arguments: Vec<Expression>,
169    },
170    /// スプレッド要素 `...expr`(配列リテラル/呼出引数/オブジェクト内で展開される)。
171    Spread(Box<Expression>),
172    /// `class` 式/宣言。
173    Class {
174        name: Option<String>,
175        superclass: Option<Box<Expression>>,
176        members: Box<Vec<ClassMember>>,
177    },
178    /// `super`(`super(...)` / `super.x`)。
179    Super,
180    /// カンマ演算子 `a, b, c`。全要素を順に評価し、最後の値を返す
181    /// (途中の要素の副作用も実行する。`for(i=0,j=10; ...)` 等で使われる)。
182    Sequence(Vec<Expression>),
183    /// `new.target`(MetaProperty。`new` 経由の呼び出しではコンストラクタ関数自身、
184    /// 通常呼び出しでは `undefined`)。
185    NewTarget,
186    /// 正規表現リテラル `/pattern/flags`。`(pattern, flags)`。稀なので箱に入れて Expression を小さく保つ。
187    Regex(Box<(String, String)>),
188}
189
190/// クラスメンバの種別。
191#[derive(Debug, Clone, PartialEq)]
192pub enum MethodKind {
193    Method,
194    Constructor,
195    /// フィールド宣言(`x = expr;` または `x;`、`#x = expr;` を含む)。
196    /// params/body は使わず、初期化式は ClassMember::field_init に持つ。
197    Field,
198    /// `get name() {...}`(アクセサ getter)。
199    Getter,
200    /// `set name(v) {...}`(アクセサ setter)。
201    Setter,
202    /// `static { ... }`(ES2022 静的初期化ブロック)。`body` に文の列を持つ
203    /// (`key`/`params`/`field_init` は使わない)。
204    StaticBlock,
205    /// クラス全体のソースを持つだけの仮のメンバ(`body` のソース範囲だけを使う。`Function.prototype.toString` 用)。
206    ClassSource,
207}
208
209/// クラスのメソッド/静的メソッド/フィールド宣言。
210#[derive(Debug, Clone, PartialEq)]
211pub struct ClassMember {
212    pub key: Rc<str>,
213    /// 算出メソッド名 `[expr](){}`(`[Symbol.iterator]` 等)。Some の場合、実際のキーは
214    /// クラス定義時にこれを評価して得る(`key` フィールドは無視される)。
215    pub computed_key: Option<Expression>,
216    pub kind: MethodKind,
217    pub params: Rc<Vec<Param>>,
218    pub body: Rc<FnBody>,
219    pub is_static: bool,
220    /// kind == Field のときのみ Some(初期化式。省略時は None → undefined 初期化)。
221    pub field_init: Option<Expression>,
222    /// `async method(){}`(kind == Method のときのみ意味を持つ)。
223    pub is_async: bool,
224    /// `*method(){}`/`async *method(){}`(kind == Method のときのみ意味を持つ)。
225    pub is_generator: bool,
226}
227
228#[derive(Debug, Clone, PartialEq)]
229pub enum VarKind {
230    Var,
231    Let,
232    Const,
233    /// `using x = expr;`(Explicit Resource Management)。囲むブロック実行終了時に
234    /// `x[Symbol.dispose]()` を宣言の逆順で呼ぶ。
235    Using,
236    /// `await using x = expr;`。`x[Symbol.asyncDispose]()` の戻り値を await する。
237    AwaitUsing,
238}
239
240/// 束縛パターン(分割代入・引数)。
241#[derive(Debug, Clone, PartialEq)]
242pub enum Pattern {
243    Identifier(Rc<str>),
244    /// `{ a, b: c, d = 1, ...rest }`
245    Object(Vec<ObjPatProp>),
246    /// `[ a, , b = 1, ...rest ]`
247    Array(Vec<ArrPatElem>),
248    /// メンバー/添字式への代入ターゲット(`for (obj.prop of arr)` / `for (obj[k] of arr)` 用)。
249    /// 分割代入の宣言では使わず、非宣言形式 for-of/for-in の代入先としてのみ生成される。
250    Expr(Box<Expression>),
251}
252
253/// オブジェクトパターンの 1 プロパティ。
254#[derive(Debug, Clone, PartialEq)]
255pub struct ObjPatProp {
256    /// 取り出すソースキー(`is_rest` の場合は未使用。`computed_key` が Some の場合も
257    /// 未使用で、実際のキーは束縛時に `computed_key` を評価して得る)。
258    pub key: Rc<str>,
259    /// 算出プロパティ名 `{[expr]: target}`。Some の場合、`key` フィールドは無視される。
260    pub computed_key: Option<Expression>,
261    /// 束縛先パターン(`{a}` なら Identifier("a")、`{a: {b}}` ならネスト)。
262    pub value: Pattern,
263    pub default: Option<Expression>,
264    pub is_rest: bool,
265}
266
267/// 配列パターンの 1 要素。
268#[derive(Debug, Clone, PartialEq)]
269pub struct ArrPatElem {
270    /// None は穴 `[a, , b]`。
271    pub pattern: Option<Pattern>,
272    pub default: Option<Expression>,
273    pub is_rest: bool,
274}
275
276/// 関数パラメータ(パターン+デフォルト+レスト)。
277#[derive(Debug, Clone, PartialEq)]
278pub struct Param {
279    pub pattern: Pattern,
280    pub default: Option<Box<Expression>>,
281    pub is_rest: bool,
282}
283
284#[derive(Debug, Clone, PartialEq)]
285pub enum Statement {
286    Expression(Expression),
287    VarDeclaration {
288        kind: VarKind,
289        // 1 文で複数宣言可能: `let a = 1, b = 2;`。分割代入のため左辺は Pattern。
290        decls: Vec<(Pattern, Option<Expression>)>,
291    },
292    Block(Vec<Statement>),
293    If {
294        test: Box<Expression>,
295        consequent: Box<Statement>,
296        alternate: Option<Box<Statement>>,
297    },
298    While {
299        test: Expression,
300        body: Box<Statement>,
301    },
302    DoWhile {
303        body: Box<Statement>,
304        test: Expression,
305    },
306    For {
307        init: Option<Box<Statement>>,
308        test: Option<Box<Expression>>,
309        update: Option<Box<Expression>>,
310        body: Box<Statement>,
311    },
312    ForIn {
313        decl_kind: Option<VarKind>,
314        pattern: Pattern,
315        object: Box<Expression>,
316        body: Box<Statement>,
317        of: bool, // true: for-of, false: for-in
318        /// `for await (x of iterable)`。`Symbol.asyncIterator` があればそれを駆動し、
319        /// 無ければ同期イテラブルの各要素を await するフォールバック(`of` の時のみ意味を持つ)。
320        is_await: bool,
321    },
322    FunctionDeclaration {
323        name: Rc<str>,
324        params: Rc<Vec<Param>>,
325        body: Rc<FnBody>,
326        is_async: bool,
327        is_generator: bool,
328    },
329    Return(Option<Expression>),
330    /// `break;` / `break label;`。
331    Break(Option<Rc<str>>),
332    /// `continue;` / `continue label;`。
333    Continue(Option<Rc<str>>),
334    /// `label: statement`(ラベル付き文。主にループの `break label`/`continue label` の
335    /// ターゲットとして使う)。
336    Labeled(Rc<str>, Box<Statement>),
337    Throw(Expression),
338    Switch {
339        discriminant: Box<Expression>,
340        cases: Vec<SwitchCase>,
341    },
342    /// `try`/`catch`/`finally`。【2026-10-27】4 つの本体で 80 バイトあり Statement 全体を太らせていたので
343    /// 箱に入れた(中身は `TryStmt`)。
344    Try(Box<TryStmt>),
345    /// `import ... from "spec"` 宣言。
346    /// 例: `import def, { a, b as c }, * as ns from "mod"`。
347    /// `import ...`(中身は `ImportDecl`。文の列挙を小さく保つため箱に入れる)。
348    Import(Box<ImportDecl>),
349    /// `export { a, b as c }` / `export { x } from "mod"`(再エクスポート)。
350    ExportNamed {
351        /// (ローカル名 or 元名, 公開する export 名)。
352        specifiers: Vec<(String, String)>,
353        /// 再エクスポート元の指定子(`export { x } from "mod"`)。None なら自モジュール。
354        source: Option<String>,
355    },
356    /// `export default <expr>`。
357    ExportDefault(Expression),
358    /// `export var/let/const/function/class ...`(宣言を実行しつつ名前を export)。
359    /// 内側の宣言文と、そこから公開する名前のリストを保持する。
360    ExportDecl {
361        declaration: Box<Statement>,
362        names: Vec<String>,
363    },
364    /// `export * from "mod"`(全名前の再エクスポート)。
365    ExportAll {
366        source: String,
367    },
368    /// クラスインスタンスへのプライベートブランド付与(内部専用)。
369    InitPrivateBrand(u64),
370    /// クラスインスタンスへのプライベートフィールド定義(内部専用)。
371    InitPrivateField {
372        brand: u64,
373        name: Rc<str>,
374        init: Option<Box<Expression>>,
375    },
376    /// クラスインスタンスのパブリックフィールド定義(内部専用。CreateDataPropertyOrThrow、無名関数の NamedEvaluation 付き)。
377    InitPublicField {
378        key: Rc<str>,
379        init: Option<Box<Expression>>,
380    },
381    /// クラスインスタンスフィールド初期化列(direct eval 静的文脈付与用)。
382    ClassFieldInit {
383        stmts: Vec<Statement>,
384        priv_names: Vec<Rc<str>>,
385    },
386    /// `with (object) body`。
387    With {
388        object: Box<Expression>,
389        body: Box<Statement>,
390    },
391    Empty,
392}
393
394/// switch の 1 ケース。`test` が None なら default。
395/// `try` 文の中身(`Statement::Try` が箱に入れて持つ)。
396#[derive(Debug, Clone, PartialEq)]
397pub struct TryStmt {
398    pub block: Vec<Statement>,
399    /// `catch (e)`/`catch ({message})` 等。分割代入パターンにも対応(ES2015)。
400    pub catch_param: Option<Box<Pattern>>,
401    pub catch_block: Option<Vec<Statement>>,
402    pub finally_block: Option<Vec<Statement>>,
403}
404
405#[derive(Debug, Clone, PartialEq)]
406pub struct ImportDecl {
407    /// モジュール指定子(指定子文字列)。
408    pub source: String,
409    /// default インポートの束縛名(`import def from ...`)。
410    pub default: Option<String>,
411    /// 名前空間インポートの束縛名(`import * as ns from ...`)。
412    pub namespace: Option<String>,
413    /// 名前付きインポート: (元の export 名, ローカル束縛名)。
414    pub named: Vec<(String, String)>,
415    /// 副作用のみ `import "mod"`(束縛なし)。
416    pub side_effect_only: bool,
417}
418
419#[derive(Debug, Clone, PartialEq)]
420pub struct SwitchCase {
421    pub test: Option<Expression>,
422    pub body: Vec<Statement>,
423}
424
425#[derive(Debug, Clone, PartialEq)]
426pub struct Program {
427    pub body: Vec<Statement>,
428}
429
430/// 関数本体。大きな本体は解析せずにソースだけ持ち、初めて実行するときに解析する(遅延解析)。
431///
432/// 本体をバイトコードへ変換するまでの呼び出しの回数。
433pub(crate) const CODE_AFTER_CALLS: u32 = 2;
434
435#[derive(Debug, Clone, Default, PartialEq, Eq)]
436pub struct EvalSyntaxCtx {
437    pub in_function: bool,
438    pub allow_super_call: bool,
439    pub allow_super_prop: bool,
440    pub in_field_init: bool,
441    pub in_static_block: bool,
442    pub private_names: Vec<Rc<str>>,
443}
444
445/// 【2026-10-17】YouTube のアプリ JS(10.9MB)・player(3MB)は関数の大半が呼ばれないのに、
446/// 全関数の構文木を作るとヒープ 512MB に収まらなかった。未解析の本体同士は入れ子に
447/// ならない(外側を解析した時点で内側が作られる)ので、保持する文字列の合計はソース以下。
448/// パーサは文脈(generator / async)に依存しないので、後から本体だけ解析しても結果は同じ。
449pub struct FnBody {
450    state: RefCell<FnBodyState>,
451    /// strict モードの本体か(`"use strict"` の指令・strict な外側・クラス)。
452    /// 非 strict の関数は this が undefined/null のときグローバル(window)になる。
453    pub strict: bool,
454    /// 本体(または内側のアロー関数)が `arguments` / `eval` を参照するか(0=未計算, 1=いいえ, 2=はい)。
455    uses_args: core::cell::Cell<u8>,
456    /// 本体のトップレベルに `FunctionDeclaration`(または `ExportDecl { FunctionDeclaration }`)があるか(0=未計算, 1=なし, 2=あり)。
457    has_func_decl: core::cell::Cell<u8>,
458    /// 本体の `var` 巻き上げの名前(構文木をキャッシュしている間だけ保持)。
459    /// 【2026-10-24】従来は呼び出しのたびに本体全体をたどって名前を集め直していた
460    /// (文字列の確保つき)。YouTube の pako の関数のように何十万回も呼ばれると効いていた。
461    var_names: RefCell<Option<Rc<Vec<Rc<str>>>>>,
462    /// バイトコード(構文木をキャッシュした本体だけ。`None` はまだ変換していない)。
463    /// generator の本体は通常の関数のバイトコードを使わないので、同じ欄に generator の VM の命令列を置く(2026-11-30)。
464    code: RefCell<Option<BodyCode>>,
465    /// 変換までに数える呼び出しの回数。
466    code_calls: Cell<u32>,
467    /// 関数の静的コード情報キャッシュ(同一関数定義から作られる全インスタンスで共有)。
468    shared_info: RefCell<Option<alloc::rc::Weak<super::value::SharedFnInfo>>>,
469    /// 定義全体(`function f(a) { ... }`)のソースと範囲(`Function.prototype.toString` 用。記録できた関数だけ)。
470    /// 【2026-11-04】従来の `toString()` は `function f() { [code] }` という仮の文字列で、BotGuard の VM が
471    /// それを評価して `code is not defined` になり、環境の改ざんと見なされた(TODO B0)。
472    source_text: RefCell<Option<(Rc<str>, u32, u32)>>,
473    eval_ctx: RefCell<Option<EvalSyntaxCtx>>,
474    /// メソッド・getter・setter の本体か(`new` できない。§15.4.4 のメソッド定義は [[Construct]] を持たない)。
475    is_method: Cell<bool>,
476}
477
478/// 本体の変換結果(通常の関数のバイトコードか、generator の VM の命令列)。
479enum BodyCode {
480    Func(Option<Rc<super::interp::bytecode::Code>>),
481    Gen(Option<Rc<super::interp::gen_vm::GenCode>>),
482}
483
484/// 【一時診断】遅延解析の種類ごとの文字数。
485pub static LAZY_KIND: [core::sync::atomic::AtomicU64; 3] = [const { core::sync::atomic::AtomicU64::new(0) }; 3];
486
487enum FnBodyState {
488    Parsed(Rc<Vec<Statement>>),
489    Source {
490        src: Rc<str>,
491        start: u32,
492        end: u32,
493        calls: u8,
494        /// この本体を切り出した解析のインターン表(後から解析するときに引き継ぐ)。
495        atoms: Option<super::lexer::SharedAtoms>,
496    },
497}
498
499impl FnBody {
500    pub fn parsed(stmts: Vec<Statement>) -> Rc<Self> {
501        Self::parsed_with(stmts, false)
502    }
503
504    pub fn parsed_with(stmts: Vec<Statement>, strict: bool) -> Rc<Self> {
505        Rc::new(Self {
506            state: RefCell::new(FnBodyState::Parsed(Rc::new(stmts))),
507            strict,
508            uses_args: core::cell::Cell::new(0),
509            has_func_decl: core::cell::Cell::new(0),
510            var_names: RefCell::new(None),
511            code: RefCell::new(None),
512            code_calls: Cell::new(0),
513            shared_info: RefCell::new(None),
514            source_text: RefCell::new(None),
515            eval_ctx: RefCell::new(None),
516            is_method: Cell::new(false),
517        })
518    }
519
520    pub fn from_rc(stmts: Rc<Vec<Statement>>) -> Rc<Self> {
521        Rc::new(Self {
522            state: RefCell::new(FnBodyState::Parsed(stmts)),
523            strict: false,
524            uses_args: core::cell::Cell::new(0),
525            has_func_decl: core::cell::Cell::new(0),
526            var_names: RefCell::new(None),
527            code: RefCell::new(None),
528            code_calls: Cell::new(0),
529            shared_info: RefCell::new(None),
530            source_text: RefCell::new(None),
531            eval_ctx: RefCell::new(None),
532            is_method: Cell::new(false),
533        })
534    }
535
536    pub fn lazy(source: String, strict: bool) -> Rc<Self> {
537        let len = source.len() as u32;
538        Self::lazy_range(Rc::from(source.into_boxed_str()), 0, len, strict, None)
539    }
540
541    pub fn lazy_range(src: Rc<str>, start: u32, end: u32, strict: bool, atoms: Option<super::lexer::SharedAtoms>) -> Rc<Self> {
542        Rc::new(Self {
543            state: RefCell::new(FnBodyState::Source {
544                src,
545                start,
546                end,
547                calls: 0,
548                atoms,
549            }),
550            strict,
551            uses_args: core::cell::Cell::new(0),
552            has_func_decl: core::cell::Cell::new(0),
553            var_names: RefCell::new(None),
554            code: RefCell::new(None),
555            code_calls: Cell::new(0),
556            shared_info: RefCell::new(None),
557            source_text: RefCell::new(None),
558            eval_ctx: RefCell::new(None),
559            is_method: Cell::new(false),
560        })
561    }
562    pub fn set_eval_ctx(&self, ctx: EvalSyntaxCtx) {
563        *self.eval_ctx.borrow_mut() = Some(ctx);
564    }
565    pub fn eval_ctx(&self) -> Option<EvalSyntaxCtx> {
566        self.eval_ctx.borrow().clone()
567    }
568    /// メソッド定義の本体として印を付ける(構文解析器から)。
569    pub fn mark_method(&self) {
570        self.is_method.set(true);
571    }
572    pub fn is_method(&self) -> bool {
573        self.is_method.get()
574    }
575    /// 定義全体のソースの範囲を記録する(構文解析器から)。
576    pub fn set_source_text(&self, src: Rc<str>, start: u32, end: u32) {
577        *self.source_text.borrow_mut() = Some((src, start, end));
578    }
579
580    /// 別の本体のソース範囲を写す(クラスの全体のソースを、コンストラクタの本体へ移す)。
581    pub fn copy_source_from(&self, other: &FnBody) {
582        let v = other.source_text.borrow().clone();
583        *self.source_text.borrow_mut() = v;
584    }
585
586    /// 定義全体のソース(記録できていなければ `None`)。
587    pub fn source_text(&self) -> Option<String> {
588        let b = self.source_text.borrow();
589        let (src, s, e) = b.as_ref()?;
590        src.get(*s as usize..*e as usize).map(String::from)
591    }
592
593    /// 定義のソースの先頭 `n` 文字だけ(診断の表示用)。
594    ///
595    /// 【2026-11-19】TODO A7: 全体を複製する `source_text()` を診断が数万ステップごとに呼ぶと、
596    /// スクリプト全体を包む関数(YouTube の kevlar は 10.4MB)のたびに 10MB の一括確保が起きていた。
597    pub fn source_head(&self, n: usize) -> Option<String> {
598        let b = self.source_text.borrow();
599        let (src, s, e) = b.as_ref()?;
600        src.get(*s as usize..*e as usize).map(|t| t.chars().take(n).collect())
601    }
602
603    /// 関数の静的メタデータ(`SharedFnInfo`)を取得または生成してキャッシュする。
604    pub fn get_or_create_shared_info(
605        self: &Rc<Self>,
606        name: &str,
607        params: &Rc<Vec<Param>>,
608        flags: u8,
609    ) -> Rc<super::value::SharedFnInfo> {
610        if let Some(existing) = self.shared_info.borrow().as_ref().and_then(|w| w.upgrade()) {
611            return existing;
612        }
613        let mut full_flags = flags & !super::value::FN_FLAG_SIMPLE_PARAMS;
614        if compute_simple_unique_params(params) {
615            full_flags |= super::value::FN_FLAG_SIMPLE_PARAMS;
616        }
617        let shared = Rc::new(super::value::SharedFnInfo {
618            name: name.into(),
619            params: params.clone(),
620            body: self.clone(),
621            flags: full_flags,
622        });
623        *self.shared_info.borrow_mut() = Some(Rc::downgrade(&shared));
624        shared
625    }
626
627
628    /// 保存済みの `var` 名(構文木をキャッシュ済みで、名前を計算済みのときだけ)。
629    pub fn cached_var_names(&self) -> Option<Rc<Vec<Rc<str>>>> {
630        self.var_names.borrow().clone()
631    }
632
633    /// `var` 名を保存する(構文木をキャッシュ済みで、`stmts` がその構文木のときだけ。
634    /// 1 回だけ解析して捨てる本体では保存しない)。
635    pub fn store_var_names(&self, stmts: &Rc<Vec<Statement>>, names: Rc<Vec<Rc<str>>>) {
636        let cached = matches!(&*self.state.borrow(), FnBodyState::Parsed(s) if Rc::ptr_eq(s, stmts));
637        if cached {
638            *self.var_names.borrow_mut() = Some(names);
639        }
640    }
641
642    /// バイトコード。何度も呼ばれる本体だけ変換する。構文木をキャッシュ済みで `stmts` がその構文木の
643    /// ときに限る(解析して捨てる本体は変換しない)。ループを含む関数は初回からバイトコードへ変換する。
644    pub(crate) fn code(&self, stmts: &Rc<Vec<Statement>>) -> Option<Rc<super::interp::bytecode::Code>> {
645        if let Some(BodyCode::Func(c)) = &*self.code.borrow() {
646            return c.clone();
647        }
648        if !matches!(&*self.state.borrow(), FnBodyState::Parsed(s) if Rc::ptr_eq(s, stmts)) {
649            return None;
650        }
651        let calls = self.code_calls.get() + 1;
652        self.code_calls.set(calls);
653        if calls < CODE_AFTER_CALLS && !stmts_has_loop(stmts) {
654            return None;
655        }
656        let c = super::interp::bytecode::compile(stmts).map(Rc::new);
657        *self.code.borrow_mut() = Some(BodyCode::Func(c.clone()));
658        c
659    }
660
661    /// generator 本体の VM 命令列(`interp::gen_vm`)。構文木をキャッシュ済みで `stmts` がその構文木なら
662    /// 本体に覚えて使い回す(そうでなければ毎回変換する)。`None` は VM で扱えない本体(従来の replay で動かす)。
663    pub(crate) fn gen_code(&self, stmts: &Rc<Vec<Statement>>) -> Option<Rc<super::interp::gen_vm::GenCode>> {
664        if let Some(BodyCode::Gen(c)) = &*self.code.borrow() {
665            return c.clone();
666        }
667        let c = super::interp::gen_vm::compile_gen(stmts).map(Rc::new);
668        if matches!(&*self.state.borrow(), FnBodyState::Parsed(s) if Rc::ptr_eq(s, stmts)) {
669            *self.code.borrow_mut() = Some(BodyCode::Gen(c.clone()));
670        }
671        c
672    }
673
674    /// まだ解析していないか。
675    pub fn is_lazy(&self) -> bool {
676        matches!(&*self.state.borrow(), FnBodyState::Source { .. })
677    }
678
679    /// 本体の文(初回は構文木を保持せず返し、2 回目以降だけ構文木に置き換える)。
680    ///
681    /// 【2026-10-19】従来は 1 回呼ばれただけの関数でも構文木(ソース文字列の約 5〜8 倍の
682    /// 大きさ)を `self.state` に永続保持していた。特に YouTube の `kevlar_base`(10.88MB)や
683    /// `base.js`(2.97MB)の最外の即時関数は 1 回しか実行されないのに、約 40MB の構文木が
684    /// クロージャ経由で最後まで残り続けていた。
685    /// - 64KB 以上の巨大な本体(バンドル全体の即時関数など)は、1 回目は構文木を捨ててソースのまま残す
686    ///   (2026-11-18 から。2 回目に呼ばれたら下と同じく構文木を残す)。
687    /// - それ以外は 1 回目の呼び出しではソースのまま残して構文木は呼び出し終了時に解放し、
688    ///   2 回目に呼ばれた関数だけ構文木をキャッシュする。
689    pub fn stmts(&self) -> Rc<Vec<Statement>> {
690        enum Action {
691            Cached(Rc<Vec<Statement>>),
692            ParseOnce(Rc<str>, u32, u32),
693            ParseAndDrop(Rc<str>, u32, u32),
694            ParseAndCache(Rc<str>, u32, u32),
695        }
696        let mut atoms_for_parse: Option<super::lexer::SharedAtoms> = None;
697        let action = {
698            let mut b = self.state.borrow_mut();
699            if let FnBodyState::Source { atoms, .. } = &*b {
700                atoms_for_parse = atoms.clone();
701            }
702            match &mut *b {
703                FnBodyState::Parsed(s) => Action::Cached(s.clone()),
704                FnBodyState::Source {
705                    src,
706                    start,
707                    end,
708                    calls,
709                    ..
710                } => {
711                    let s = src.clone();
712                    let st = *start;
713                    let en = *end;
714                    if en.saturating_sub(st) >= 65_536 && *calls == 0 {
715                        // 【2026-11-18】従来はここで状態を「空の構文木」に置き換えていたため、2 回目の呼び出しが
716                        // 空の本体を実行して `undefined` を返していた(YouTube の `ZiD`〔98KB・複数回呼ぶ〕が
717                        // 2 回目から undefined を返し、`ZiD().objectRepresentation` が例外になっていた)。
718                        // ソースは読み込んだファイル全体の共有文字列を指すだけなので残しても費用は増えない。
719                        // 1 回目は構文木を捨て、2 回目に呼ばれたときだけ構文木を残す。
720                        *calls = 1;
721                        Action::ParseAndDrop(s, st, en)
722                    } else if *calls == 0 {
723                        *calls = 1;
724                        Action::ParseOnce(s, st, en)
725                    } else {
726                        *b = FnBodyState::Parsed(Rc::new(Vec::new()));
727                        Action::ParseAndCache(s, st, en)
728                    }
729                }
730            }
731        };
732        // 【一時診断】遅延解析の種類ごとの文字数([0]=1 回目で捨てる・[1]=2 回目で残す・[2]=大きくて捨てる)。
733        match &action {
734            Action::ParseOnce(_, a, b) => LAZY_KIND.first().map(|x| x.fetch_add((*b - *a) as u64, core::sync::atomic::Ordering::Relaxed)),
735            Action::ParseAndCache(_, a, b) => LAZY_KIND.get(1).map(|x| x.fetch_add((*b - *a) as u64, core::sync::atomic::Ordering::Relaxed)),
736            Action::ParseAndDrop(_, a, b) => LAZY_KIND.get(2).map(|x| x.fetch_add((*b - *a) as u64, core::sync::atomic::Ordering::Relaxed)),
737            Action::Cached(_) => None,
738        };
739        match action {
740            Action::Cached(s) => s,
741            Action::ParseOnce(src, start, end) => {
742                let parsed = Rc::new(super::parser::parse_function_body_range(
743                    src,
744                    start as usize,
745                    end as usize,
746                    self.strict,
747                    atoms_for_parse.clone(),
748                ));
749                if end.saturating_sub(start) < 16_384 && stmts_has_loop(&parsed) {
750                    *self.state.borrow_mut() = FnBodyState::Parsed(parsed.clone());
751                }
752                parsed
753            }
754            Action::ParseAndDrop(src, start, end) => {
755                Rc::new(super::parser::parse_function_body_range(
756                    src,
757                    start as usize,
758                    end as usize,
759                    self.strict,
760                    atoms_for_parse.clone(),
761                ))
762            }
763            Action::ParseAndCache(src, start, end) => {
764                let parsed = Rc::new(super::parser::parse_function_body_range(
765                    src,
766                    start as usize,
767                    end as usize,
768                    self.strict,
769                    atoms_for_parse.clone(),
770                ));
771                *self.state.borrow_mut() = FnBodyState::Parsed(parsed.clone());
772                parsed
773            }
774        }
775    }
776
777    /// この関数本体(および内側のアロー関数)が `arguments` または `eval` を参照するか。
778    pub fn uses_arguments(&self, stmts: &[Statement]) -> bool {
779        match self.uses_args.get() {
780            1 => false,
781            2 => true,
782            _ => {
783                let u = stmts_use_arguments(stmts);
784                self.uses_args.set(if u { 2 } else { 1 });
785                u
786            }
787        }
788    }
789
790    /// 本体のトップレベルに `FunctionDeclaration`(または `ExportDecl { FunctionDeclaration }`)が含まれるか。
791    #[inline]
792    pub fn has_function_decls(&self, stmts: &[Statement]) -> bool {
793        match self.has_func_decl.get() {
794            1 => false,
795            2 => true,
796            _ => {
797                let has = stmts.iter().any(|s| match s {
798                    Statement::FunctionDeclaration { .. } => true,
799                    Statement::ExportDecl { declaration, .. } => {
800                        matches!(**declaration, Statement::FunctionDeclaration { .. })
801                    }
802                    _ => false,
803                });
804                self.has_func_decl.set(if has { 2 } else { 1 });
805                has
806            }
807        }
808    }
809
810    fn raw_might_use_arguments(&self) -> bool {
811        match self.uses_args.get() {
812            1 => false,
813            2 => true,
814            _ => match &*self.state.borrow() {
815                FnBodyState::Source {
816                    src, start, end, ..
817                } => {
818                    let slice = src.get(*start as usize..*end as usize).unwrap_or("");
819                    slice.contains("arguments") || slice.contains("eval")
820                }
821                FnBodyState::Parsed(s) => {
822                    let u = stmts_use_arguments(s);
823                    self.uses_args.set(if u { 2 } else { 1 });
824                    u
825                }
826            },
827        }
828    }
829}
830
831fn compute_simple_unique_params(params: &[Param]) -> bool {
832    if params.len() > 16 {
833        return false;
834    }
835    for (i, p) in params.iter().enumerate() {
836        if p.is_rest || p.default.is_some() {
837            return false;
838        }
839        let Pattern::Identifier(name) = &p.pattern else {
840            return false;
841        };
842        for prev in &params[..i] {
843            if let Pattern::Identifier(pn) = &prev.pattern {
844                if Rc::ptr_eq(name, pn) || **name == **pn {
845                    return false;
846                }
847            }
848        }
849    }
850    true
851}
852
853fn stmts_use_arguments(stmts: &[Statement]) -> bool {
854    stmts.iter().any(stmt_uses_arguments)
855}
856
857fn stmt_uses_arguments(stmt: &Statement) -> bool {
858    match stmt {
859        Statement::Expression(e)
860        | Statement::Return(Some(e))
861        | Statement::Throw(e)
862        | Statement::ExportDefault(e) => expr_uses_arguments(e),
863        Statement::VarDeclaration { decls, .. } => decls
864            .iter()
865            .any(|(p, init)| pat_uses_arguments(p) || init.as_ref().is_some_and(expr_uses_arguments)),
866        Statement::Block(b) => stmts_use_arguments(b),
867        Statement::If {
868            test,
869            consequent,
870            alternate,
871        } => {
872            expr_uses_arguments(test)
873                || stmt_uses_arguments(consequent)
874                || alternate.as_deref().is_some_and(stmt_uses_arguments)
875        }
876        Statement::While { test, body } | Statement::DoWhile { body, test } => {
877            expr_uses_arguments(test) || stmt_uses_arguments(body)
878        }
879        Statement::For {
880            init,
881            test,
882            update,
883            body,
884        } => {
885            init.as_deref().is_some_and(stmt_uses_arguments)
886                || test.as_deref().is_some_and(expr_uses_arguments)
887                || update.as_deref().is_some_and(expr_uses_arguments)
888                || stmt_uses_arguments(body)
889        }
890        Statement::ForIn {
891            pattern,
892            object,
893            body,
894            ..
895        } => {
896            pat_uses_arguments(pattern)
897                || expr_uses_arguments(object)
898                || stmt_uses_arguments(body)
899        }
900        Statement::Labeled(_, s) | Statement::ExportDecl { declaration: s, .. } => {
901            stmt_uses_arguments(s)
902        }
903        Statement::ClassFieldInit { stmts, .. } => stmts_use_arguments(stmts),
904        Statement::With { object, body } => {
905            expr_uses_arguments(object) || stmt_uses_arguments(body)
906        }
907        Statement::Switch {
908            discriminant,
909            cases,
910        } => {
911            expr_uses_arguments(discriminant)
912                || cases.iter().any(|c| {
913                    c.test.as_ref().is_some_and(expr_uses_arguments)
914                        || stmts_use_arguments(&c.body)
915                })
916        }
917        Statement::Try(t) => {
918            let TryStmt {
919                block,
920                catch_param,
921                catch_block,
922                finally_block,
923            } = &**t;
924            stmts_use_arguments(block)
925                || catch_param.as_deref().is_some_and(pat_uses_arguments)
926                || catch_block.as_deref().is_some_and(stmts_use_arguments)
927                || finally_block.as_deref().is_some_and(stmts_use_arguments)
928        }
929        // 非アローの関数宣言は独自の `arguments` を持つため外側の `arguments` は参照しない。
930        Statement::InitPrivateField { init: Some(e), .. } | Statement::InitPublicField { init: Some(e), .. } => {
931            expr_uses_arguments(e)
932        }
933        Statement::InitPrivateBrand(_)
934        | Statement::InitPrivateField { init: None, .. }
935        | Statement::InitPublicField { init: None, .. }
936        | Statement::FunctionDeclaration { .. }
937        | Statement::Return(None)
938        | Statement::Break(_)
939        | Statement::Continue(_)
940        | Statement::Import(_)
941        | Statement::ExportNamed { .. }
942        | Statement::ExportAll { .. }
943        | Statement::Empty => false,
944    }
945}
946
947fn pat_uses_arguments(pat: &Pattern) -> bool {
948    match pat {
949        Pattern::Identifier(n) => &**n == "arguments" || &**n == "eval",
950        Pattern::Object(props) => props.iter().any(|p| {
951            p.computed_key.as_ref().is_some_and(expr_uses_arguments)
952                || pat_uses_arguments(&p.value)
953                || p.default.as_ref().is_some_and(expr_uses_arguments)
954        }),
955        Pattern::Array(elems) => elems.iter().any(|e| {
956            e.pattern.as_ref().is_some_and(pat_uses_arguments)
957                || e.default.as_ref().is_some_and(expr_uses_arguments)
958        }),
959        Pattern::Expr(e) => expr_uses_arguments(e),
960    }
961}
962
963fn expr_uses_arguments(expr: &Expression) -> bool {
964    match expr {
965        Expression::Identifier(n) => &**n == "arguments" || &**n == "eval",
966        Expression::TemplateLiteral { exprs, .. } => exprs.iter().any(expr_uses_arguments),
967        Expression::Array(exprs) | Expression::Sequence(exprs) => {
968            exprs.iter().any(expr_uses_arguments)
969        }
970        Expression::TaggedTemplate { tag, exprs, .. } => {
971            expr_uses_arguments(tag) || exprs.iter().any(expr_uses_arguments)
972        }
973        Expression::Object(props) => props.iter().any(|p| {
974            p.computed.as_ref().is_some_and(expr_uses_arguments) || expr_uses_arguments(&p.value)
975        }),
976        Expression::Function {
977            params,
978            body,
979            is_arrow,
980            ..
981        } => {
982            if !*is_arrow {
983                false
984            } else {
985                params.iter().any(|p| {
986                    pat_uses_arguments(&p.pattern)
987                        || p.default.as_deref().is_some_and(expr_uses_arguments)
988                }) || body.raw_might_use_arguments()
989            }
990        }
991        Expression::Await(e)
992        | Expression::Unary { expr: e, .. }
993        | Expression::Update { target: e, .. }
994        | Expression::Spread(e)
995        | Expression::Member { object: e, .. } => expr_uses_arguments(e),
996        Expression::Yield { argument, .. } => argument.as_deref().is_some_and(expr_uses_arguments),
997        Expression::Binary { left, right, .. }
998        | Expression::Logical { left, right, .. }
999        | Expression::Assign {
1000            target: left,
1001            value: right,
1002            ..
1003        }
1004        | Expression::Index {
1005            object: left,
1006            index: right,
1007            ..
1008        } => expr_uses_arguments(left) || expr_uses_arguments(right),
1009        Expression::Conditional {
1010            test,
1011            consequent,
1012            alternate,
1013        } => {
1014            expr_uses_arguments(test)
1015                || expr_uses_arguments(consequent)
1016                || expr_uses_arguments(alternate)
1017        }
1018        Expression::Call {
1019            callee, arguments, ..
1020        }
1021        | Expression::New { callee, arguments } => {
1022            expr_uses_arguments(callee) || arguments.iter().any(expr_uses_arguments)
1023        }
1024        Expression::Class {
1025            superclass,
1026            members,
1027            ..
1028        } => {
1029            superclass.as_deref().is_some_and(expr_uses_arguments)
1030                || members.iter().any(|m| {
1031                    m.computed_key.as_ref().is_some_and(expr_uses_arguments)
1032                        || m.field_init.as_ref().is_some_and(expr_uses_arguments)
1033                })
1034        }
1035        Expression::Number(_)
1036        | Expression::BigIntLit(_)
1037        | Expression::Str(_)
1038        | Expression::Bool(_)
1039        | Expression::Null
1040        | Expression::Undefined
1041        | Expression::Elision
1042        | Expression::This
1043        | Expression::Super
1044        | Expression::NewTarget
1045        | Expression::Regex(_) => false,
1046    }
1047}
1048
1049impl core::fmt::Debug for FnBody {
1050    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1051        match &*self.state.borrow() {
1052            FnBodyState::Parsed(s) => write!(f, "FnBody({} stmts)", s.len()),
1053            FnBodyState::Source { start, end, .. } => {
1054                write!(f, "FnBody(lazy {} chars)", end.saturating_sub(*start))
1055            }
1056        }
1057    }
1058}
1059
1060/// 同じ本体(同じ定義)かどうかで比べる。
1061impl PartialEq for FnBody {
1062    fn eq(&self, other: &Self) -> bool {
1063        core::ptr::eq(self, other)
1064    }
1065}
1066
1067fn stmt_has_loop(s: &Statement) -> bool {
1068    match s {
1069        Statement::While { .. }
1070        | Statement::DoWhile { .. }
1071        | Statement::For { .. }
1072        | Statement::ForIn { .. } => true,
1073        Statement::Block(body) => stmts_has_loop(body),
1074        Statement::If { consequent, alternate, .. } => {
1075            stmt_has_loop(consequent) || alternate.as_deref().is_some_and(stmt_has_loop)
1076        }
1077        Statement::Labeled(_, inner) | Statement::With { body: inner, .. } => stmt_has_loop(inner),
1078        Statement::ClassFieldInit { stmts, .. } => stmts_has_loop(stmts),
1079        Statement::Try(t) => {
1080            stmts_has_loop(&t.block)
1081                || t.catch_block.as_ref().is_some_and(|cb| stmts_has_loop(cb))
1082                || t.finally_block.as_ref().is_some_and(|fb| stmts_has_loop(fb))
1083        }
1084        Statement::Switch { cases, .. } => cases.iter().any(|c| stmts_has_loop(&c.body)),
1085        _ => false,
1086    }
1087}
1088
1089pub(crate) fn stmts_has_loop(stmts: &[Statement]) -> bool {
1090    stmts.iter().any(stmt_has_loop)
1091}