Phase 10.7 - JIT統計とイベント機能の完成

主要な実装:
- PHI(b1)統計追跡: phi_total_slots/phi_b1_slotsをJSON出力
- 関数単位統計API: JitStatsBox.perFunction()で詳細統計取得
- JITイベントシステム: compile/execute/fallback/trapをJSONL形式で記録
- Store/Load命令対応: ローカル変数を含む関数のJIT実行が可能に

新しいBox:
- JitStatsBox: JIT統計の取得
- JitConfigBox: JIT設定の管理(将来用)
- JitEventsBox: イベントのJSONL出力(将来用)
- JitPolicyBox: 実行ポリシー管理(将来用)

CLI拡張:
- --jit-exec, --jit-stats, --jit-dump等のフラグ追加
- --jit-directモードでの独立JIT実行
- NYASH_JIT_*環境変数によるきめ細かい制御

ドキュメント:
- Phase 10.7実装計画の詳細化
- Phase 10.9 (ビルトインBox JIT) の計画追加
- JIT統計JSONスキーマ v1の仕様化

ChatGPT5との共同開発により、JIT基盤が大幅に強化されました。
次はPhase 10.9でビルトインBoxのJIT対応を進め、
Python統合(Phase 10.1)への道を開きます。

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Moe Charm
2025-08-28 09:26:58 +09:00
parent 99e59e24e2
commit e54561e69f
64 changed files with 4311 additions and 189 deletions

View File

@ -2,7 +2,14 @@
フェーズ10はJIT実用化へCore-1 Lowerの雛形を固めつつ、呼出/フォールバック導線を整えるよ。
## ⏱️ 今日のサマリ10_c実行経路の堅牢化10_7分岐配線GC/スケジューラ導線
## 🆕 Quick Hot Update2025-08-27-2
- JitStatsBox: perFunction() 追加関数単位の統計をJSON配列で取得
- b1 PHI格子 強化Compare/Const/Cast(TypeOp)/Branch/Copy/PHI/Store/Loadの固定点伝播
- 独立JIT: `--jit-direct` に引数対応(`NYASH_JIT_ARGS` をMIR型にcoerce、結果の型名も表示
- b1 ABI切替の下地: `NYASH_JIT_ABI_B1_SUPPORT=1` でcapを強制ONできるように将来のtoolchain更新に備えたスイッチ
- リンク: JSONスキーマ(v1) → `docs/reference/jit/jit_stats_json_v1.md`
## ⏱️ 今日のサマリ10_c実行経路の堅牢化10_7分岐/PHI/独立ABIGC/スケジューラ導線)
- 目的: JIT実行を安全に通す足場を仕上げつつ、GC/スケジューラ導線を整備し回帰検出力を上げる。
- 10_c: panic→VMフォールバック`catch_unwind`/ JIT経路のroot区域化 / Core-1 i64 param minimal pass`emit_param_i64` + LowerCoreで供給✅ 完了
- 10_4a/10_4b: GC導線 + Write-Barrier挿入ArraySet/RefSet/BoxCall、root APIenter/pin/leave
@ -10,8 +17,81 @@
- 10_4d: STRICTバリア検証CountingGc前後比較で漏れ即検出✅ 完了(`NYASH_GC_BARRIER_STRICT=1`
- 10_6b: シングルスレ・スケジューラspawn/spawn_after/poll、Safepointで`poll()`連携、`NYASH_SCHED_POLL_BUDGET`対応 ✅ 完了
- 10_7: JIT分岐配線Cranelift— MIR Branch/Jump→CLIFブロック配線、条件b1保持、分岐b1/`i64!=0`両対応feature: `cranelift-jit`
- 10_7: 最小PHI単純ダイアモンド`NYASH_JIT_PHI_MIN=1` で有効、ブロック引数で合流値を受け渡し ✅ 初期対応
- 10_7: JIT独立ABI導入 — `JitValue`i64/f64/bool/handle + VMValue↔JitValueアダプタ、TLS分離legacy VMArgs / JIT Args✅ 完了
- ベンチ: CLIベンチへJIT比較追加ウォームアップあり`branch_return`ケース追加、スクリプト版`examples/ny_bench.nyash`追加TimerBoxでops/sec
### 🆕 追加アップデート10_7進捗
- ハンドルレジストリ + スコープ管理JIT呼び出し単位で自動クリーンアップ
- HostCallブリッジハンドル経由・read-only中心
- Array/Map/String: `length`/`isEmpty`、Map: `has`、String: `charCodeAt`
- Array/Map get/set/push/size: 既存PoCをハンドル経由に段階移行
- 多値PHIの配線then/else/jumpで順序つき引数渡し
- DOT可視化`NYASH_JIT_DOT=path.dot` でCFG出力✅ 初期対応
- 引数ネイティブ型10_7hの前段: MIRシグネチャから `Float→F64`, `Bool→I64(0/1)` を反映(`NYASH_JIT_NATIVE_F64/BOOL`)✅ 初期対応
- ダンプの簡潔化CFG/PHI要点表示、f64/boolネイティブ有効フラグ表示
- CFG/PHIダンプの詳細化`NYASH_JIT_DUMP=1`)✅ 初期強化
- 例: `phi: bb=3 slots=2 preds=1|2` に続けて `dst vX <- pred:val, ...` を列挙(合流値の源が一目で分かる)
- JIT設定の集約Rust側✅ 初期導入
- `src/jit/config.rs``JitConfig` を追加し、RunnerからCLIと環境変数を一元反映
- JitConfigBox 追加10_7f✅ 初期対応
- `new JitConfigBox()``exec/stats/dump/phi_min/hostcall/.../threshold` を操作し `apply()` でenv反映
- `toJson()/fromJson()` で再現性確保、`summary()` で状態確認
- f64ネイティブ最小経路`NYASH_JIT_NATIVE_F64=1`)✅
- f64定数、F64同士の四則、F64戻りシグネチャ・トランポリン
- トランポリンは`desired_ret_is_f64`を捕捉env依存のズレを排除
- Boolネイティブ最小経路`NYASH_JIT_NATIVE_BOOL=1`)↗ 準備済み
- 比較はb1で保持し分岐に直接供給既定戻りは当面i64(0/1)で正規化将来b1戻りに拡張
- 細かな修正: P2PBoxでtransportコールバック登録時の借用期間エラーを修正lock解放順を明示
- Bugfix: Cranelift `push_block_param_i64_at``switch_to_block` 未呼出によるpanicを修正CFG/PHI経路の安定化
- LowerCore小型足場追加 ✅
- ret_boolヒント: 返り値がBoolの関数で `builder.hint_ret_bool(true)` を呼ぶ切替点を用意現状no-op、将来1行で切替
- Castの最小下ろし: `I::Cast` を値供給+既知整数の継承で安全通過(副作用なし領域)
- 観測強化 ✅
- b1正規化カウンタ: `b1_norm_count`分岐条件・b1ブロック引数の正規化で加算
- JitStatsBox: `{abi_mode, abi_b1_enabled, abi_b1_supported, b1_norm_count}``toJson()` で取得可能BoxFactory登録済み
- 統合JIT統計テキスト/JSON`abi_mode/…/b1_norm_count` を追加
- 便利CLI ✅
- `--emit-cfg <DOT_FILE>` 追加(`NYASH_JIT_DOT` のCLI版。`NYASH_JIT_DUMP`も自動オン)
- 重要: Cranelift未有効時の挙動を是正 ✅
- 以前: `NYASH_JIT_EXEC=1` でJITスタブが0を返すことがあり、結果が変わり得た
- 変更: Cranelift未有効では「未コンパイル扱い」にしてVMへ完全フォールバックJIT有効でも結果は不変
- 独立JITモード ✅ 追加
- `--jit-direct`: VM実行ループを介さず、JITエンジンで `main` を直接コンパイル実行Cranelift有効時
- `--jit-only`: フォールバック禁止JIT未コンパイル/失敗は即エラー)— 独立性検証に最適
- b1 PHIの型/格子解析 強化 ✅
- Compare/Const Bool起点Copy/PHIに加え、Load/Storeヒューリスティックを導入固定点伝播
- PHI統計は常時計測`phi_total_slots`/`phi_b1_slots`)→ JSON/ダンプ一致
- 関数単位JIT統計 ✅
- LowerCore→JitEngine→JitManagerで `phi_total/phi_b1/ret_bool_hint/hits/compiled/handle` を集約
- `JitStatsBox.summary()``perFunction` 配列を追加(関数ごとの明細)
- f64 E2Eと簡易ベンチCranelift向け✅ 追加
- 例: `examples/jit_f64_e2e_add_compare.nyash` / ベンチ: `examples/ny_bench_f64.nyash`
- 注意: VM単体ではf64演算/比較は未対応。`--features cranelift-jit` + `NYASH_JIT_EXEC=1 NYASH_JIT_NATIVE_F64=1` で実行
- JSONスキーマの文書化 ✅
- 参照: `docs/reference/jit/jit_stats_json_v1.md`version=1
- 統一JSON/Box JSONともに `version` フィールドを付与
- f64 E2Eと簡易ベンチCranelift向け✅ 追加
- 例: `examples/jit_f64_e2e_add_compare.nyash`
- ベンチ: `examples/ny_bench_f64.nyash`
- 注意: VM単体ではf64演算/比較は未対応。`--features cranelift-jit` + `NYASH_JIT_EXEC=1 NYASH_JIT_NATIVE_F64=1` で実行
- JSONスキーマの文書化 ✅ 追加
- 参照: `docs/reference/jit/jit_stats_json_v1.md`version=1
- 統一JSON/Box JSONともに `version` フィールドを付与
- PHI統計常時計測
- `phi_total_slots`/`phi_b1_slots` をLowerCoreで常時計測し、JSONに出力
- Cranelift互換性修正 ✅
- b1シグネチャを使用せず、戻りはi64に正規化`select(b1,1,0)`)。`types::B1`/`bint` 非依存でビルド安定化
### 直近タスク(小さく早く)
1) 10_b: Lower/Core-1 最小化(進行中 → ほぼ完了)
- IRBuilder抽象 + `NoopBuilder`emit数カウント✅ 完了
@ -20,25 +100,96 @@
- Engine.compile: builder選択feature連動Lower実行JIT handle発行✅ 完了
- JIT関数テーブルstub: handle→ダミー関数✅ 完了
- 残: 最小emitconst/binop/retをCLIFで生成し、関数ポインタをテーブル登録feature有効時
→ 実装: CraneliftBuilderでi64用の`const/binop/ret`を生成し、JIT関数テーブルへクロージャとして登録完了args未対応・i64専用
→ 実装: CraneliftBuilderでi64用の`const/binop/ret`を生成し、JIT関数テーブルへクロージャとして登録完了i64引数0〜6個対応bool,f64はi64正規化✅ 更新
2) 10_c: 呼出/フォールバック(最小経路)✅ 完了
- VM側の疑似ディスパッチログcompiled時/実行時ログ)✅
- JIT実行→`VMValue`返却、panic時VMフォールバック ✅(`engine.execute_handle``catch_unwind`
- Core-1最小: i64 param/return、Const(i64/bool→0/1)、BinOp/Compare/Return ✅
- HostCall最小Array/Map: len/get/set/push/sizeゲート`NYASH_JIT_HOSTCALL=1`
- Branch/JumpはCranelift配線導入済みfeature `cranelift-jit`。副作用命令は未lowerのためVMへフォールバック
3) 10_7: 分岐配線Cranelift— 進捗中
3) 10_7: 分岐/PHI/独立ABICranelift— 進捗中
- LowerCore: BB整列・マッピング→builderの`prepare_blocks/switch/seal/br_if/jump`呼出 ✅
- CraneliftBuilder: ブロック配列管理、`brif/jump`実装、条件b1/`i64!=0`両対応 ✅
- 最小PHI単純ダイアモンド導入`NYASH_JIT_PHI_MIN=1`ガード)✅ 初期対応
- 残: 副作用命令の扱い方針当面VMへ、CFG可視化の拡張`NYASH_JIT_DUMP=1`
- JIT独立化: `JitValue` ABI + 変換アダプタ + TLS分離でVM内部へ非依存化 ✅ 完了
- 残: 副作用命令の扱い方針当面VMへ、CFG可視化の追加改善ブロック引数の整形など
- 検証: `--features cranelift-jit` 有効ビルドで `examples/jit_branch_demo.nyash` / `jit_phi_demo.nyash` がJIT経路で正常動作を確認`NYASH_JIT_EXEC=1 NYASH_JIT_THRESHOLD=1`)✅
### 🆕 追加2025-08-28
- JitStatsBox: `perFunction()` をVMディスパッチへ実装JSON配列で name/hits/phi_total/phi_b1/ret_bool_hint/compiled/handle を返却)✅
- PHI(b1)読出しの安定化(最小)✅
- `NYASH_JIT_PHI_MIN=1` 有効時、ブールと推定されたPHIは b1 としてブロック引数を読み出し(分岐に直結)
- 分岐条件をブール格子のシードに追加pre-scanで `condition` をbooleanとして扱う
- デモ更新: `examples/jit_stats_summary_demo.nyash``perFunction()` 出力を追加 ✅
- jit-direct独立JIT足場の強化 ✅
- read-onlyガードWriteHeap検出で明示エラー/ 統一エラーJSON`NYASH_JIT_ERROR_JSON=1`
- 最小E2E: `examples/jit_direct_local_store_load.nyash` / `jit_direct_bool_ret.nyash` / `jit_direct_f64_ret.nyash`
- 参考: Box-First運用キット `docs/engineering/box_first_enforcement.md`PR/CIはアドバイザリ導入
## 🔜 次Phase 10.9 Builtin-Box JITBox-Firstで最小から
目的: VMとJITでビルトインBoxの読み取り系を同等動作にし、後続生成/書き込み)へ進む足場を固める。
### 必要な箱(最小セット)
- JitPolicyBoxポリシー箱
- 役割: read-onlyゲート/書き込み検出/HostCall許可リストの一本化1箇所で切替
- 経路: runner/jit-direct/engine/lower が参照env直読みはしない
- JitEventsBox観測箱
- 役割: compile/execute/fallback/trapを JSONL へAppend{fn, abi_mode, reason, ms}
- 経路: 既存statsと共存。回帰の目視を容易に。
- HostcallRegistryBoxread-only
- 役割: 許可HostCallと引数/戻りの種別を宣言。型検査の単一点にする。
- 初期: String.length/isEmpty/charCodeAt, Array.length/isEmpty/get, Map.size/has
- FrameSlotsBoxスロット箱
- 役割: ptr→slot の管理と型注釈今はi64のみ。LowerCoreから委譲。
- CallBoundaryBox呼出し境界箱薄い
- 役割: JIT↔JIT/JIT↔VM呼出しの単一点将来の多関数対応の足場。今は型変換の箱だけ用意。
最小原則: まず箱を置くno-op/ログだけでもOK→ 切替点が1箇所になったら機能を足す。
### 実装計画(小さい積み木で順に)
1) Week 10.9-α(足場)
- JitPolicyBox v0: read-only/HostCall whitelist を箱へ移動runnerの散在チェックを統合
- JitEventsBox v0: compile/executeのJSONLイベントオプトイン
- CURRENT_TASK/CLAUDEへポリシーと使い方を簡潔追記
2) Week 10.9-β(読み取り系カバレッジ)
- HostcallRegistryBox v0: String/Array/Mapの読み取りAPIを登録・型検査
- LowerCore: BoxCallのread-only経路をRegistry参照に切替散在ロジックの削減
- E2E: length/isEmpty/charCodeAt/get/size/hasjit-direct + VMで一致
3) Week 10.9-γ(生成の足場)
- CallBoundaryBox v0: JIT→VMnew演算子などを一旦VMへ委譲する薄い箱
- new StringBox/IntegerBox/ArrayBox の最小経路jit-directは方針次第で拒否でも可
4) Week 10.9-δ(書き込みの導線のみ)
- JitPolicyBox: write許可のスイッチを箱に実装既定OFF
- LowerCore: 書き込み命令はPolicy参照で拒否/委譲/許可1箇所で判断
### 成功判定DoD
- 機能: 読み取り系ビルトインBoxがJIT経路でVMと一致上記API
- 箱: Policy/Events/Registryが1箇所で参照される散在ロジック解消
- 観測: JSONLイベントが最低1件以上出力明示opt-in
- 回帰: `jit-direct` read-only方針が維持され、拒否理由がイベント/JSONで判読可
### リスクと箱での緩和
- HostCallの型崩れ: HostcallRegistryBoxで型検査→不一致はPolicy経由で明示拒否
- 方針変更の揺れ: JitPolicyBoxのフラグだけで切替可能コード散在を回避
- 観測不足: JitEventsBoxのイベント粒度を先に用意必要最小限でOK
備考(制限と次の着手点)
- 返り値はi64VMValue::Integerに限定。f64はconst最小emit、boolはi64 0/1へ正規化分岐条件入力に対応
- 引数はi64のみ最小パス。複数引数はparamマッピングで通過、非i64は未対応 → 次対応
- 返り値はi64VMValue::Integerに限定。f64/boolは設計着手ダンプで有効フラグ観測のみ
- 引数はi64最小パス。複数引数はparamマッピングで通過、非i64はハンドル/正規化で暫定対応
- Branch/JumpのCLIF配線は導入済みfeature `cranelift-jit`。条件はb1で保持し、必要に応じて`i64!=0`で正規化
- 副作用命令print等はJIT未対応のためVMへ委譲安全性優先
- JIT/VM統合統計フォールバック率/時間の一括出力)未統合 → 次対応
- JIT/VM統合統計フォールバック率/時間の一括出力)✅ 実装済み(最小)
- `maybe_print_jit_unified_stats()` により、テキスト/JSON`NYASH_JIT_STATS_JSON=1`でsites/compiled/hits/exec_ok/trap/fallback_rate/handlesを出力
## 📦 箱作戦JIT独立化の方針
- ABIの箱: `JitValue`I64/F64/Bool/HandleでJIT入出力を統一、VM型に非依存
- 変換アダプタ: VMValue↔JitValueはアダプタに集約、境界は必ずアダプタ経由
- TLS分離: legacy VMArgs既存HostCall用とJIT Args新ABIを分離し段階移行
- HostCall独立化計画: Handle(u64) + ハンドルレジストリ導入でJIT→ホストを完全独立VM型非参照
- 設定の箱(進捗): Rust側で`JitConfig`を導入しenv/CLI設定を集約Nyash側Box化は後続
- 可視化: `NYASH_JIT_DUMP=1`でCFG/ブロック引数を可視化し回帰検出力を強化
### すぐ試せるコマンド
```bash
@ -67,6 +218,17 @@ NYASH_JIT_EXEC=1 NYASH_JIT_THRESHOLD=1 ./target/release/nyash --backend vm examp
./target/release/nyash --benchmark --iterations 200
```
#### HostCallハンドルPoC
```bash
./target/release/nyash --backend vm --jit-exec --jit-hostcall examples/jit_array_param_call.nyash
./target/release/nyash --backend vm --jit-exec --jit-hostcall examples/jit_map_param_call.nyash
./target/release/nyash --backend vm --jit-exec --jit-hostcall examples/jit_map_int_keys_param_call.nyash
./target/release/nyash --backend vm --jit-exec --jit-hostcall examples/jit_map_has_int_keys.nyash
./target/release/nyash --backend vm --jit-exec --jit-hostcall examples/jit_string_param_length.nyash
./target/release/nyash --backend vm --jit-exec --jit-hostcall examples/jit_string_is_empty.nyash
./target/release/nyash --backend vm --jit-exec --jit-hostcall examples/jit_string_charcode_at.nyash
```
## 現在の地図Done / Next
### ✅ 完了Phase 9.79b
@ -92,12 +254,13 @@ NYASH_JIT_EXEC=1 NYASH_JIT_THRESHOLD=1 ./target/release/nyash --backend vm examp
- Lower emitのテスト雛形
- CLIFダンプ/CFG表示`NYASH_JIT_DUMP=1`
- VM `--vm-stats` とJIT統計の統合
→ 実装済みVM終了時にJIT統合サマリ出力。JSON出力も可
### 残タスク(箇条書き)
- 10_c:
- CLIF: Branch/Jumpの実ブロック配線、Compare結果の適用確認
- 返り値/引数の型拡張bool/f64、複数引数の網羅
- JIT/VM統合統計フォールバック率/時間の一括出力)
- JIT/VM統合統計フォールバック率/時間の一括出力)✅ 済(最小)
- 10_4c:
- リーチャビリティ観測の深さ拡張depth=2→Nと軽量ダンプ
- 将来実Mark/TraverseのPoC解放はしない
@ -106,13 +269,32 @@ NYASH_JIT_EXEC=1 NYASH_JIT_THRESHOLD=1 ./target/release/nyash --backend vm examp
- 10_6b:
- スケジューラ: poll予算の設定ファイル化、将来のscript API検討継続
- 10_7:
- 最小PHI単純ダイアモンドの導入`NYASH_JIT_PHI_MIN=1`ガード
- IRBuilder APIの整理block param/分岐引数の正式化とCranelift実装の安定化
- Hostハンドルレジストリ導入JIT側はHandleのみを見る
- IRBuilder APIの整理block param/分岐引数の正式化とCranelift実装の安定化暫定APIの整形
- 副作用命令のJIT扱い方針: 当面VMへ、将来はHostCall化
- CFG検証と`NYASH_JIT_DUMP=1`でのCFG可視化
- CFG検証と`NYASH_JIT_DUMP=1`でのCFG可視化(ブロックと引数のダンプ)✅ 初期強化済み(更なる整形・網羅は継続)
- JitConfigBoxで設定の箱集約env/CLI整合、テスト容易化✅ Rust側の`JitConfig`導入済Box化は後続
- Bool戻り最小化: `hint_ret_bool`をCranelift側に配線し、b1→i64とb1ネイティブを切替可能に
- Compare/BinOpの副作用なし領域の拡大Copy/Const/Castは開始済み、And/Orは当面VMフォールバック
- PHI(b1)の扱い整理: ブロック引数のb1対応を正式化i64 0/1正規化とb1の両立
- 統計/ダンプの整備: `b1_norm_count`のJSON/テキスト両方での検証手順をドキュメント化
- b1 PHI格子の精度UP簡易エイリアス/型注釈の取り込み)
- ネイティブb1 ABI: ツールチェーンcap連動で返り/引数b1署名への切替切替点は一本化済
- VMのf64演算/比較パリティ10.8へ移送)
- JitStatsBox: `perFunction()` の箱API追加summaryを介さず単体取得
- b1 PHIタグの頑健化Load/Store越しの由来推定を型/格子解析で補強)
- VMのf64演算/比較パリティ10.8へ移送予定)
- JSONスキーマのversion管理とサンプル更新`v1`整理済み、今後の拡張計画をドキュメント化)
- ベンチ:
- `examples/ny_bench.nyash`のケース追加(関数呼出/Map set-getとループ回数のenv化
### 🛠️ メンテ・ビルドノート(環境依存)
- WSL配下`/mnt/c/...`)で `cargo build` 時に `Invalid cross-device link (os error 18)` が発生する場合あり
- 対策: リポジトリをLinux FS側例: `~/work/nyash`)に配置/`CARGO_TARGET_DIR``TMPDIR` を同一FS配下へ設定
- 備考: リンク動作とFS差分が原因のため、コード修正ではなく環境調整で解決
- Codex CLIの実行権限・サンドボックス設定忘れで「ビルドできない」誤検知になる場合あり
- 対策: `codex --ask-for-approval never --sandbox danger-full-access` を付与して起動する(この指定忘れが原因だったケースあり)
---
10_d まとめ(完了)

View File

@ -0,0 +1,52 @@
JIT Phase 10_7 — Known Issues and Future Refinements (2025-08-27)
Scope: LowerCore(Core-1), Branch/PHI wiring, ABI(min), Stats/CFG dump
1) b1 PHI tagging heuristics
- Symptom: (b1) tag may not appear for some PHI nodes when inputs are routed via variables (Load/Store) or multi-step copies.
- Current mitigation:
- Pre-scan: mark Compare/Const Bool as boolean producers.
- Propagate through Copy; close over PHI if all inputs are boolean-like.
- CFG dump heuristic: mark (b1) if pre-analysis true OR all inputs look boolean OR the PHI output is used as branch condition.
- Residual risk: Complex IR (loads/stores, deep copies, optimizer rewrites) can hide provenance; tag may still be missed.
- Future: Track boolean type via MIR type system or a dedicated lattice in analysis pass; extend provenance across Load/Store when safe.
2) f64 arithmetic/compare on VM backend
- Symptom: VM path errors on f64 BinOp/Compare (e.g., Add/>, mixed types).
- Cause: VM does not yet implement floating-point arithmetic/compare ops.
- Current mitigation: Examples using f64 are marked for Cranelift-enabled JIT environments; VM returns type errors as expected.
- Future: Implement f64 BinOp/Compare in VM or add auto-promotion layer consistent with JIT behavior.
3) JIT execution stub semantics
- Symptom: Previously, enabling NYASH_JIT_EXEC could alter results via stub returns when Cranelift was not enabled.
- Fix: Stub disabled; compilation skipped without Cranelift, full VM fallback retains semantics.
- Future: None (resolved). Keep behavior documented.
4) ret_bool_hint_count visibility
- Symptom: Counter can remain 0 when MIR signatures dont mark Bool return even if code returns boolean values via VM-level boxes.
- Cause: Counter increments on MIR signature Bool return detection; not on dynamic boolean returns.
- Future: Consider counting dynamic sites or adding per-function attributes post-inference.
5) PHI dump dependency on phi_min
- Symptom: Detailed PHI dump (with (b1) tags) only shows when NYASH_JIT_PHI_MIN=1.
- Current stance: Intended; PHI path is opt-in while stabilizing.
- Future: Always-on summary rows possible; keep detail behind flag to reduce noise.
6) Stats scope and sources
- Symptom: JitStatsBox and unified stats currently reflect process-local counters; function-level detail via top5 only.
- Future: Add per-function structured stats via Box API; expose compilation state/timings when available.
7) Toolchain capability gating (b1 ABI)
- Symptom: Native boolean (b1) return in signatures remains disabled (cap false).
- Current stance: Switch point centralized; flips on when toolchain supports b1 in signatures.
- Future: Periodically probe toolchain; add CI check to toggle automatically.
8) Warning noise (unexpected cfg: llvm)
- Symptom: Warnings about unknown `llvm` feature in conditional cfg.
- Cause: Feature not declared in Cargo.toml; code guards are placeholders.
- Future: Add feature or silence warnings for non-supported builds.
9) Documentation sync
- Symptom: Some flags visible via CLI and boxes; ensure README/CURRENT_TASK stay aligned.
- Future: Add short “JIT quick flags” section with examples in docs.

View File

@ -0,0 +1,68 @@
# JIT機能拡張 - 2025年8月27日
## ChatGPT5による最新実装
### 1. PHI可視化強化
- CFGダンプに「PHIがboolean(b1)かどうか」を明示表示
- 例: `dst v12 (b1) <- 1:8, 2:9`
- PHI命令の型情報が一目で分かるように改善
### 2. JIT統計の上位表示
- 統合JIT統計(JSON)に `top5` を追加
- 関数名
- ヒット数
- compiled状態
- handle番号
- 例実行で `top5``main` が入ることを確認
### 3. 返り値ヒントの観測
- `ret_bool_hint_count` をJIT統計に追加
- JitStatsBox/統合JIT統計の両方で確認可能
- ブール返り値の最適化機会を可視化
### 4. 新しい例の追加
#### `examples/jit_stats_bool_ret.nyash`
- 統計JSONをプリントする最小デモ
- 最後にブールを返す
- JIT統計の動作確認用
#### `examples/jit_mixed_f64_compare.nyash`
- f64比較のデモ
- **注意**: VMのf64演算/比較未対応のため、Cranelift有効環境向けサンプル
## 使い方(観測)
### 統計JSON出力
```bash
NYASH_JIT_STATS=1 NYASH_JIT_STATS_JSON=1 NYASH_JIT_THRESHOLD=1 \
./target/release/nyash --backend vm examples/jit_stats_bool_ret.nyash
```
JSONに以下が出力される
- `abi_mode`
- `b1_norm_count`
- `ret_bool_hint_count`
- `top5`
### CFG/PHIダンプ
```bash
NYASH_JIT_DUMP=1 ./target/release/nyash --backend vm examples/phi_bool_merge.nyash
```
- b1 PHIには `(b1)` タグが付与される
## 注意事項
- VMのf64演算/比較は未対応
- `jit_mixed_f64_compare.nyash` はCranelift有効環境JIT実行での確認用
- VMでの実行はエラーになる
## 実装の意義
これらの機能拡張により:
1. **可視性の向上**: PHI命令の型情報が明確に
2. **統計の充実**: top5による頻繁に呼ばれる関数の把握
3. **最適化ヒント**: ブール返り値のカウントによる最適化機会の発見
4. **デバッグ支援**: より詳細な情報による問題解析の容易化
Box-First方法論の「観測箱」の具現化として、これらの機能は論文の実証例となる。

View File

@ -0,0 +1,239 @@
# Phase 10.1 - Python統合計画ChatGPT5高速開発版
最終更新: 2025-08-27
## 🚀 概要2週間での爆速実装
ChatGPT5の最小Box設計により、元の1ヶ月計画を**2週間**に圧縮。Nyash既存アーキテクチャMirBuilder 100%実装済み、HandleRegistry 80%実装済み)を最大活用。
## 📦 ChatGPT5の6つの必須Box最小実装
### 1. **PythonParserBox** - CPython AST取得3日
```rust
// 既存: pyo3統合済み
// 追加: JSON出力とバージョン固定
pub struct PythonParserBox {
base: BoxBase,
py_helper: Arc<Mutex<PyHelper>>,
version: String, // "3.11"固定
}
// メソッド(最小限)
- parse_to_json(src: String) -> String // ast.parse() → JSON
- get_version() -> String // "3.11"
```
### 2. **Py2NyASTBox** - AST変換3日
```rust
// 新規実装
pub struct Py2NyASTBox {
base: BoxBase,
normalizer: AstNormalizer,
}
// メソッド(制御フロー正規化)
- convert(json: String) -> NyashAst
- normalize_for_else(ast: &mut PyAst) // for/else → if分岐
- normalize_comprehensions(ast: &mut PyAst)
```
### 3. **MirBuilderBox** - MIR生成0日 - 既存活用)
```rust
// 既存実装100%活用
// 追加: Python由来フラグのみ
pub struct MirBuilderBox {
// 既存フィールド
is_python_origin: bool, // 追加
}
```
### 4. **BoundaryBox** - 型変換2日
```rust
// Python版のHandleRegistry相当
pub struct BoundaryBox {
base: BoxBase,
handle_registry: Arc<Mutex<HandleRegistry>>, // 既存80%活用
}
// メソッド
- py_to_jit(py_val: PyValBox) -> JitValue
- jit_to_py(jit_val: JitValue) -> PyValBox
- register_handle(obj: Arc<dyn NyashBox>) -> u64
```
### 5. **PyRuntimeBox** - 実行制御2日
```rust
pub struct PyRuntimeBox {
base: BoxBase,
fallback_stats: FallbackStats,
}
// メソッド(関数単位フォールバック)
- execute_function(name: &str, args: Vec<JitValue>) -> JitValue
- should_fallback(func_ast: &PyAst) -> bool // Phase1機能判定
- fallback_to_cpython(code: &str) -> PyObject
```
### 6. **ObservabilityBox** - 統計収集1日
```rust
// 既存のJIT統計システム70%実装済み)を拡張
pub struct ObservabilityBox {
base: BoxBase,
stats_collector: StatsCollector,
}
// JSONLフォーマット出力
- log_attempt(module: &str, func: &str, compiled: bool, reason: Option<&str>)
- output_jsonl() -> String
```
## 🗓️ 実装タイムライン2週間
### Week 1: 基盤実装7日
- **Day 1-3**: PythonParserBox実装
- pyo3統合既存活用
- Python 3.11固定
- JSON出力実装
- **Day 4-6**: Py2NyASTBox実装
- 制御フロー正規化
- for/else, while/else変換
- Phase1機能のみサポート
- **Day 7**: ObservabilityBox実装
- 既存JIT統計拡張
- JSONLフォーマット
### Week 2: 統合と検証7日
- **Day 8-9**: BoundaryBox実装
- HandleRegistry活用
- 型変換ルール確立
- **Day 10-11**: PyRuntimeBox実装
- 関数単位フォールバック
- CPython連携
- **Day 12-13**: 統合テスト
- Differential Testing
- ベンチマーク実行
- **Day 14**: ドキュメント・リリース
- 使用例作成
- パフォーマンス測定
## 📊 既存アーキテクチャとの整合性
### 活用率
- **MirBuilderBox**: 100%(変更なし)
- **HandleRegistry**: 80%BoundaryBoxで再利用
- **JIT統計**: 70%ObservabilityBoxで拡張
- **VM/JIT実行**: 100%(そのまま使用)
### 新規実装
- **PythonParserBox**: 30%pyo3部分は既存
- **Py2NyASTBox**: 100%新規
- **PyRuntimeBox**: 100%新規
## 🎯 Phase 1でサポートする機能Codex先生推奨
### 必須実装
1. **LEGB + locals/freevars** - スコーピング規則
2. **デフォルト引数の評価タイミング** - 定義時評価
3. **イテレータベースのfor文**
4. **for/else + while/else**
5. **Python真偽値判定**
6. **短絡評価**
### サポートする文
- def関数定義
- if/elif/else
- forelse節対応
- whileelse節対応
- break/continue
- return
### サポートする式
- 算術演算子(+,-,*,/,//,%
- 比較演算子(==,!=,<,>,<=,>=
- 論理演算子and,or,not
- 関数呼び出し
- リテラル(数値/文字列/bool
## 📈 成功指標2週間後
### 定量的
- **関数コンパイル率**: 70%以上Phase 1機能
- **実行速度**: 純Pythonループで2倍以上
- **メモリ効率**: CPython比50%削減
### 定性的
- **統計可視化**: JSONL形式で全実行を記録
- **デバッグ容易性**: 関数単位でフォールバック理由明示
- **将来拡張性**: Phase 2-4への明確な道筋
## 🔧 実装例(最終形)
```nyash
// Nyashから使用
local py = new PythonParserBox()
local converter = new Py2NyASTBox()
local builder = new MirBuilderBox()
local runtime = new PyRuntimeBox()
local stats = new ObservabilityBox()
// Pythonコードをコンパイル・実行
local code = "def fib(n): return n if n <= 1 else fib(n-1) + fib(n-2)"
local json_ast = py.parse_to_json(code)
local ny_ast = converter.convert(json_ast)
local mir = builder.build(ny_ast)
// 実行自動的にJIT/VMで高速化
local result = runtime.execute_function("fib", [10])
print(result) // 55
// 統計出力
print(stats.output_jsonl())
// {"mod":"test","func":"fib","attempt":1,"jitted":true,"native":true}
```
## 🚨 重要な設計判断
### 1. 関数単位の境界
- ファイル単位ではなく**関数単位**でコンパイル/フォールバック
- 未対応機能を含む関数のみCPython実行
### 2. Python 3.11固定
- AST安定性の確保
- 将来のバージョンアップは別Phase
### 3. 箱境界の明確化
- 各Boxは単一責任
- 相互依存を最小化
- テスト可能な粒度
### 4. 既存資産の最大活用
- MirBuilder/VM/JITはそのまま使用
- 新規実装は変換層のみ
## 🎉 期待される成果
### 即時的効果2週間後
- Pythonコードの70%がNyashで高速実行
- バグ検出力の飛躍的向上Differential Testing
- 統計による最適化ポイントの可視化
### 長期的効果
- Python→Nyash→Native の世界初パイプライン確立
- Nyash言語の成熟度向上
- エコシステムの爆発的拡大
## 📝 次のステップ
1. **Phase 10.7完了確認** - JIT統計JSONの安定化
2. **PythonParserBox実装開始** - pyo3統合から着手
3. **テストコーパス準備** - Python標準ライブラリから抜粋
---
**作成者**: ClaudeClaude Code
**承認者**: ChatGPT5予定
**開始予定**: Phase 10.7完了直後

View File

@ -0,0 +1,135 @@
Phase 10.7 — JIT CFG/PHI/ABI Hardening (Master Plan)
Intent
- Deliver a practical, observable JIT path for control flow and minimal data flow while keeping VM as the safe fallback.
- Decompose into small, shippable sub-phases with flags and examples, minimizing blast radius.
Related docs
- 10.7a details: phase_10_7a_jit_phi_cfg_and_abi_min.txt
- Current work log: docs/development/current/CURRENT_TASK.md
- Cranelift JIT backend notes: phase_10_cranelift_jit_backend.md
Flags and CLI (common across 10.7)
- Env: NYASH_JIT_EXEC, NYASH_JIT_STATS, NYASH_JIT_STATS_JSON, NYASH_JIT_DUMP, NYASH_JIT_THRESHOLD, NYASH_JIT_PHI_MIN, NYASH_JIT_HOSTCALL
- CLI: --jit-exec --jit-stats --jit-stats-json --jit-dump --jit-threshold N --jit-phi-min --jit-hostcall
Examples to validate
- examples/jit_branch_demo.nyash
- examples/jit_loop_early_return.nyash
- examples/jit_phi_demo.nyash
- examples/jit_array_param_call.nyash, jit_map_param_call.nyash (when hostcall is enabled)
Sub-phases (10.7a → 10.7h)
10.7a — Minimal branch/PHI/ABI (Done or in-flight)
- Branch wiring with b1 and i64!=0 normalization
- Minimal PHI: single-value diamond via block param
- Independent ABI (JitValue) with integer-first calling
- Panic-safe dispatch (catch_unwind) and VM fallback
- Minimal hostcall bridge (Array/Map) behind NYASH_JIT_HOSTCALL
- Observability: unified JIT summary/JSON, lower summary (argc/phi_min), CFG edge dump (phi_min)
Acceptance: see 10.7a doc
10.7b — PHI generalization and block-parameterization
- Support multiple PHIs in a merge block; pass N values via block params
- LowerCore: gather PHI inputs per successor, produce explicit arg lists; handle straight merges and simple loops
- IRBuilder API formalization:
- ensure_block_params_i64(index, count)
- br_if_with_args(then_idx, else_idx, then_n, else_n)
- jump_with_args(target_idx, n)
- CraneliftBuilder: append N I64 params per block, materialize current block params onto stack when requested
- Validation: multi-PHI diamonds, if-else chains, early returns; keep loops as simple as possible in 10.7b
10.7c — Independent host-handle registry (JIT↔Host decoupling)
- Introduce JitHandleRegistry: u64 ↔ Arc<dyn NyashBox>
- JIT hostcalls accept/return only handles and PODs; VMValue↔JitValue boundary converts BoxRef <-> Handle via registry
- Rooting policy: enter/pin roots for handles crossing the boundary; leave on return
- Flags: NYASH_JIT_HOSTCALL=1 (still gated); add NYASH_JIT_HANDLE_DEBUG for dumps
- Deliverables: array/map operations via handles, no direct VMValue access on JIT side
10.7d — Side-effect boundary and hostcall coverage expansion
- Keep side-effecting ops (print/IO) on VM for now; document deopt path
- Expand safe hostcalls (read-only or confined):
- String.len / slice basics (POD returns)
- Map.size; Map.get with integer and string keys (key boxing handled at boundary)
- Record effect categories on lowered calls for future optimizer (metadata only)
10.7e — CFG diagnostics and visualization
- Add DOT export for CLIF CFG with block params and PHI bindings
- Env: NYASH_JIT_DOT=path.dot (produces per-function graph)
- Optional: ASCII CFG summary for CI logs
- Cross-check with VM-side MIR printer for block and PHI consistency
10.7f — JitConfigBox (configuration as a Box)
- Encapsulate all JIT toggles into a runtime-managed box (JitConfigBox)
- Harmonize env/CLI with programmatic overrides for tests
- Feed config into JIT engine and lowerers (no direct env reads inside hot paths)
- Serialization: dump/load config JSON for reproducible runs
10.7g — Stability, tests, and benchmarks
- Golden tests: ensure JIT/VM outputs match on curated programs
- Fallback ratio regression guard: alert when fallback_rate spikes beyond threshold
- JSON schema stability for stats; include version field
- Microbenchmarks: branch-heavy, phi-heavy, and hostcall-heavy cases; gated perf checks
10.7h — Type widening for native ABI
- Add native F64 and Bool parameter/return paths in CLIF
- Condition handling: keep b1 where possible; map Bool to b1 cleanly
- Conversions: explicit i64<->f64 ops in lowerer where needed (no silent truncation)
- Update adapter and closure trampoline to select proper function signatures (arity×type shapes)
Out of scope for 10.7 (shift to 10.8/10.9)
- Global register allocation strategies or codegen-level optimizations
- Deoptimization machinery beyond simple VM fallback
- Advanced exception propagation across JIT/VM boundary
Risks and mitigation
- PHI N-arity correctness: introduce targeted unit tests over synthetic MIR
- Handle registry leaks: counting diagnostics, strict mode; tie roots to scope regions
- CLIF block-param misuse: deterministic block order + seal discipline + assertions in builder
Verification checklist (roll-up)
- cargo check (± --features cranelift-jit)
- Run examples with JIT flags; diff with pure VM runs
- Inspect: unified JIT summary/JSON, lower logs, CFG dumps/DOT
- Leak/roots checks when NYASH_GC_TRACE=1/2/3 and strict barrier mode is on
Suggested timeline (tentative)
- 10.7a: Minimal branch/PHI/ABI (done / in-flight)
- 10.7b: PHI generalization + builder API formalization (12 days)
- 10.7c: Host-handle registry PoC (12 days)
- 10.7d/e: Hostcall coverage + CFG DOT (23 days)
- 10.7f: JitConfigBox + integration (1 day)
- 10.7g/h: QA + type widening for f64/bool (24 days)
10.7z — Follow-ups and Open Items (post-10.7)
- b1 PHI tagging robustness
- Problem: Provenance can be obscured by Load/Store and multi-step copies; (b1) tag may be missed in dumps.
- Action:
- Add a lightweight boolean-lattice analysis over MIR to classify boolean-producing values independent of path shape.
- Extend dump to include phi_summary JSON or structured rows when NYASH_JIT_STATS_JSON is on.
- Placement: 10.7g (stability/tests) — does not block 10.7 close.
- VM f64 arithmetic/compare parity
- Problem: VM backend currently errors on f64 BinOp/Compare; JIT (Cranelift) supports f64 when enabled.
- Action: Implement f64 ops in VM or add consistent auto-promotion; add golden tests.
- Placement: 10.8 (VM parity/perf) — out-of-scope for 10.7.
- Native b1 ABI in function signatures
- Problem: Toolchain capability for b1 return/params is currently disabled.
- Action: Keep centralized switch; add CI probe to flip automatically when supported; wire return path fully.
- Placement: 10.7h or later (gated by toolchain).
- Stats/diagnostics polish
- Action: Version the unified JIT JSON schema; expose phi(b1) slot counts in JSON; enrich JitStatsBox with summary/topN (partially done).
- Placement: 10.7g.
- Build warnings (unexpected cfg: llvm)
- Problem: Warning noise from unused/unknown cfg.
- Action: Declare feature flags in Cargo.toml or gate code behind existing features; optionally silence for non-supported builds.
- Placement: 10.7g (cleanup) — non-blocking.
- Documentation sync
- Action: Add a "JIT quick flags" section with common env/CLI combos; ensure CURRENT_TASK and examples remain aligned.
- Placement: 10.7e (docs) — non-blocking.

View File

@ -0,0 +1,92 @@
Phase 10.7a — JIT Branch/PHI/Independent ABI: Minimal Path Hardening (Plan)
Purpose
- Solidify the first functional slice of the JIT control-flow path:
- Branch wiring (b1 and i64!=0 normalization)
- Minimal PHI via block parameters (single-value diamond)
- Independent ABI (JitValue) and safe dispatch + fallback
- Observable, toggleable, and easy to verify via flags + examples
Scope (10.7a only)
1) Minimal PHI handoff
- LowerCore: detect single-PHI merge; pass i64 value via block param
- CraneliftBuilder: ensure block param (I64), push/pop on branch/jump with args
- Flag gate: NYASH_JIT_PHI_MIN=1
2) Branch wiring and condition normalization
- Keep compare result on stack as b1 when possible
- If top-of-stack is I64, normalize by icmp_imm != 0
- Implement br_if/jump to pre-created blocks (deterministic order)
3) Independent ABI (minimum viable)
- JitValue(I64/F64/Bool/Handle) in/out; normalize non-i64 args to i64 for now
- TLS split: legacy VM args (for hostcalls) and JIT args
- Engine.execute_handle uses catch_unwind; panic → VM fallback with stats
4) Minimal hostcall bridge (safe; off by default)
- Symbols: nyash.array.{len,get,set,push}, nyash.map.{size}
- Gate: NYASH_JIT_HOSTCALL=1
- Only integer indices/values (PoC); other types map to handles later
5) Observability and ergonomics
- Flags: NYASH_JIT_EXEC, NYASH_JIT_STATS, NYASH_JIT_STATS_JSON, NYASH_JIT_DUMP, NYASH_JIT_THRESHOLD, NYASH_JIT_PHI_MIN, NYASH_JIT_HOSTCALL
- CLI: --jit-exec --jit-stats --jit-stats-json --jit-dump --jit-threshold N --jit-phi-min --jit-hostcall
- Unified JIT summary on VM exit (sites/compiled/hits/exec_ok/trap/fallback_rate)
- Lower log includes argc/phi_min + CFG light dump (phi edges) when NYASH_JIT_DUMP=1
Non-Goals (later 10.7b+)
- Full PHI generalization (multiple values, loops, complex CFG forms)
- Non-i64 native path (true F64/Bool return/params in CLIF)
- Side-effect instruction lowering (print, IO) — keep in VM path
- Host handle registry for real object bridging (u64↔Arc<dyn NyashBox>)
Deliverables
- Working minimal PHI + branch JIT execution on curated examples:
- examples/jit_branch_demo.nyash
- examples/jit_loop_early_return.nyash
- examples/jit_phi_demo.nyash (single-PHI diamond)
- Fallback correctness: traps/panic → VM path; results match VM
- Configurable via CLI flags; metrics visible via JIT summary/JSON
Acceptance Criteria
- With: --backend vm --jit-exec --jit-stats --jit-threshold 1
- For branch/phi examples, JIT executes without panic
- VM fallback occurs only for unsupported ops (logged)
- JIT summary shows exec_ok > 0 and reasonable fallback_rate
- With: --jit-phi-min
- CFG dump lists phi_min edges and blocks count
- Results match the same program without JIT enabled
Risk & Mitigation
- Mismatch between VMValue and JitValue adapters
- Mitigation: normalize non-i64 to i64 defensively; expand tests on adapters
- Cranelift block parameter misuse
- Mitigation: deterministic block order and explicit ensure_block_param_i64()
- Panic in hostcall stubs (unexpected Box types)
- Mitigation: gated by NYASH_JIT_HOSTCALL=1; default off; fallback to VM on panic
Verification Checklist
- cargo check (w/ and w/o --features cranelift-jit)
- Run examples with JIT flags; compare outputs with pure VM
- Inspect logs: lower summary + CFG dump + unified summary/JSON
Timeline (10.7a)
Day 1:
- Finalize ABI normalization and branch wiring; add unified stats (done)
- Wire CLI flags and JSON stats (done)
Day 2:
- Harden minimal PHI path and CFG dump (done)
- Curate examples and sanity-run on flags
Day 3:
- Stabilize logging format, trim rough edges, doc polish
→ Then roll into 10.7b (multi-PHI, multi-arg block params, real handle registry)
Follow-ups (10.7b/10.7c seeds)
- Host handle registry (u64↔Arc) and type-safe bridging
- True F64/Bool native ABI, multi-arg params/returns
- CFG visualization improvements (dot export) and JitConfigBox
Refs
- docs/development/current/CURRENT_TASK.md (10_7 items)
- src/jit/{lower,engine,manager,abi,rt}/
- examples: jit_* demos

View File

@ -0,0 +1,45 @@
# Phase 10.7h — Native ABI Types (F64/Bool)
Goal
- Extend the minimal i64-only JIT ABI to support f64 and bool as native parameter/return types in CLIF.
Principles
- Keep JIT independent from VM internals (use JitValue + adapters at boundary)
- Avoid silent truncation; perform explicit conversions in the lowerer
- Maintain safety-first fallback to VM for unsupported ops
Plan
1) JitValue widening
- JitValue already has I64/F64/Bool/Handle — keep this as the ABI surface
- Adapter: refine to/from VMValue mappings (no lossy coercion by default)
2) CLIF signature selection
- Augment CraneliftBuilder to build signatures based on (arity × type shape)
- Start with small shapes: (I64|F64|Bool)* → I64|F64|Bool
- Closure trampoline: transmute to matching extern "C" fn type; dispatch by shape id
3) Condition handling
- Bool: prefer b1 in IR; allow i64!=0 normalization when comparing integers
- Comparisons yield b1; lower branch consumes b1 directly
4) Conversions in lowerer (explicit only)
- add_const_f64, add_convert_{i64_to_f64, f64_to_i64}
- prohibit implicit int<->float coercion in arithmetic; gate conversions via explicit MIR ops or intrinsics
5) Observability and flags
- NYASH_JIT_NATIVE_F64=1 / NYASH_JIT_NATIVE_BOOL=1 to enable paths
- Dump: show chosen signature shape and conversions when NYASH_JIT_DUMP=1
6) Rollout
- Phase A: const/binop/ret for f64; comparisons yield b1
- Phase B: mixed-type ops via explicit converts
- Phase C: HostCall bridging for f64/bool PODs (read-only first)
Risks / Mitigation
- Signature explosion: start with a few common shapes; fallback to i64 path
- Platform ABI mismatches: rely on Cranelift default call conv; e2e-perf and correctness first
Acceptance
- Examples with pure f64 pipelines run under JIT with matching results vs VM
- No silent lossy conversions; conversions visible in MIR/Lower logs

View File

@ -0,0 +1,175 @@
# Phase 10.9 - ビルトインBox JITサポート
## 🎯 目的
ビルトインBoxをJITで使えるようにし、Python統合Phase 10.1)への道を開く。
## 📦 対象Box優先順位順
### 第1段階読み取り専用メソッド
```nyash
// StringBox
str.length() // → i64
str.isEmpty() // → bool
str.charAt(idx) // → String新Box生成
// ArrayBox
arr.length() // → i64
arr.isEmpty() // → bool
arr.get(idx) // → Box既存参照
// IntegerBox/FloatBox
int.toFloat() // → f64
float.toInt() // → i64
```
### 第2段階Box生成
```nyash
// new演算子のJIT化
new StringBox("hello") // → Handle
new IntegerBox(42) // → Handleまたは直接i64
new ArrayBox() // → Handle
```
### 第3段階書き込みメソッド
```nyash
// 状態変更を伴う操作
arr.push(item) // Mutex操作必要
arr.set(idx, value) // 境界チェック必要
map.set(key, value) // ハッシュ操作
```
## 🔧 実装戦略
### 1. HandleRegistry活用
```rust
// 既存のHandleRegistry80%実装済み)を拡張
pub fn jit_get_box_method(handle: u64, method: &str) -> Option<MethodPtr> {
// ハンドル → Box → メソッドポインタ
}
```
### 2. HostCall拡張
```rust
// 現在の限定的なHostCallを段階的に拡張
enum HostCallKind {
// 既存
ArrayIsEmpty,
StringLength,
// Phase 10.9で追加
StringIsEmpty,
StringCharAt,
ArrayGet,
IntToFloat,
FloatToInt,
// new演算子サポート
NewStringBox,
NewIntegerBox,
NewArrayBox,
}
```
### 3. 型安全性の確保
```rust
// JIT時の型チェック
match method {
"length" => {
// StringBox/ArrayBoxのみ許可
verify_box_type(handle, &[BoxType::String, BoxType::Array])?
}
"isEmpty" => {
// より多くのBoxで使用可能
verify_box_type(handle, &[BoxType::String, BoxType::Array, BoxType::Map])?
}
}
```
## 📊 成功指標
### 機能面
- [ ] StringBox.length() がJITで実行可能
- [ ] ArrayBox.isEmpty() がJITで実行可能
- [ ] new StringBox() がJITで生成可能
- [ ] 型チェックが正しく動作
### 性能面
- [ ] HostCall経由でも10倍以上高速化
- [ ] Handle解決のオーバーヘッド最小化
- [ ] Mutex競合の回避読み取り専用
### Python統合への貢献
- [ ] PythonParserBoxの基本メソッドが使用可能
- [ ] MirBuilderBoxへのデータ受け渡し可能
- [ ] 最小限のPython→Nyash変換が動作
## 🚧 技術的課題
### 1. Arc<Mutex>パターンとの整合性
```rust
// 読み取り専用でもMutexロックが必要
// → 読み取り専用APIを別途用意
```
### 2. Box生成時のメモリ管理
```rust
// JIT内でのArc生成
// → HandleRegistryで一元管理
```
### 3. エラーハンドリング
```rust
// パニックしない設計
// → Result型での丁寧なエラー伝播
```
## 📈 実装ロードマップ
### Week 1基盤整備
- HandleRegistry拡張
- HostCallインターフェース設計
- 型チェック機構
### Week 2読み取りメソッド実装
- StringBoxlength, isEmpty, charAt
- ArrayBoxlength, isEmpty, get
- 数値変換toInt, toFloat
### Week 3Box生成サポート
- new演算子のMIR→JIT変換
- コンストラクタ呼び出し
- HandleRegistry登録
### Week 4テストと最適化
- E2Eテストスイート
- パフォーマンス測定
- Python統合の動作確認
## 🎉 期待される成果
```nyash
// これが高速に動く!
static box FastPython {
main() {
local py = new PythonParserBox() // JITで生成
local code = "def add(a, b): return a + b"
local ast = py.parse(code) // JITで実行
local builder = new MirBuilderBox() // JITで生成
local mir = builder.build(ast) // JITで実行
// Python関数がネイティブ速度で動く
return "Python is now Native!"
}
}
```
## 🚀 次のステップ
→ Phase 10.10プラグインBox JITサポート
→ Phase 10.1Python統合いよいよ実現
---
作成者ClaudeNyashくんの要望により
目的「うるさい、Nyashつかえ」を真に実現するため