feat(loop-phi): Add body-local variable PHI generation for Rust AST loops

Phase 25.1c/k: Fix ValueId undefined errors in loops with body-local variables

**Problem:**
- FuncScannerBox.scan_all_boxes/1 and BreakFinderBox._find_loops/2 had ValueId
  undefined errors for variables declared inside loop bodies
- LoopFormBuilder only generated PHIs for preheader variables, missing body-locals
- Example: `local ch = s.substring(i, i+1)` inside loop → undefined on next iteration

**Solution:**
1. **Rust AST path** (src/mir/loop_builder.rs):
   - Detect body-local variables by comparing body_end_vars vs current_vars
   - Generate empty PHI nodes at loop header for body-local variables
   - Seal PHIs with latch + continue snapshot inputs after seal_phis()
   - Added HAKO_LOOP_PHI_TRACE=1 logging for debugging

2. **JSON v0 path** (already fixed in previous session):
   - src/runner/json_v0_bridge/lowering/loop_.rs handles body-locals
   - Uses same strategy but for JSON v0 bridge lowering

**Results:**
-  FuncScannerBox.scan_all_boxes: 41 body-local PHIs generated
-  Main.main (demo harness): 23 body-local PHIs generated
- ⚠️ Still some ValueId undefined errors remaining (exit PHI issue)

**Files changed:**
- src/mir/loop_builder.rs: body-local PHI generation logic
- lang/src/compiler/entry/func_scanner.hako: debug logging
- /tmp/stageb_funcscan_demo.hako: test harness

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
nyash-codex
2025-11-19 23:12:01 +09:00
parent fb256670a1
commit 525e59bc8d
35 changed files with 1795 additions and 607 deletions

View File

@ -63,6 +63,28 @@ Status: in progress.hako 側 LoopSSA v2 本体実装Rust 側は既存 SSA/
- ゴール:
- LoopSSA 本来そのループに属さない block body に含めないようにするValueId(50) のような飛び火を防ぐ)。
### KB2: BreakFinderBox._find_loops/2 ループ構造の整理region box 化の一歩)
- 背景:
- `BreakFinderBox._find_loops/2` のループ内で `header_pos` / `header_id` / `exit_pos` / `exit_id` を扱う際
`header_id == null` `exit_pos` 異常系で `continue` を多用していたため
LoopForm v2 / LoopSSA 側から見るとループ本体が細かい early-continue に分割された形になっていた
- StageB Test2 ではこの経路で `header_pos` `i` まわりの ValueId が観測しづらくなり
SSA バグ調査の足場としても扱いづらかった
- 対応:
- `lang/src/compiler/builder/ssa/exit_phi/break_finder.hako::_find_loops` をリファクタし
`next_i` ローカルを導入して1 イテレーション中のすべての分岐が最後に `i = next_i` に合流する形に整理した
- `header_id == null` / `exit_pos < 0` / 範囲外 / `exit_id == null` の各ケースは
`next_i` の更新だけで表現し`continue` を使わない構造に変更
- 正常系`header_id` / `exit_pos` / `exit_id` が全て有効の場合のみ
`body_blocks` / `ControlFormBox` / `loop_info` の構築と `loops.push(loop_info)` を行い
そのうえで `next_i = exit_pos + 12` を設定
- これにより:
- LoopForm v2 から見るとループ本体が単一の region`next_i` による合流)」として観測できるようになり
break/continue 経路の SSA 構造が単純化された
- ループの意味論自体は従来どおりヘッダ/出口検出ロジックや body_blocks の定義は不変
既存の JSON v0 / LoopSSA の挙動には影響しない
### KC: PhiInjectorBox の v2 への一歩Carrier/Pinned の入口だけ作る)
- 目的: