481 Commits

Author SHA1 Message Date
4082abb30c feat(normalization): Phase 142 P0 - Loop statement-level normalization
Phase 142-loopstmt P0: Statement-level normalization

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

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2025-12-19 05:28:49 +09:00
f775c0fe01 docs: Phase 131 P2 DirectValue exit reconnection complete
Update completion status for Phase 131 P2:
- CURRENT_TASK.md: Note WSL restart resolved EXDEV issue
- 10-Now.md: Add Phase 131 P2 completion entry
- phase-131/README.md: Document P1.5 and P2 deliverables

Phase 131 Status: DONE 
- loop(true) break-once executes correctly
- Exit values propagate through DirectValue mode
- VM + LLVM EXE parity verified

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-18 17:48:18 +09:00
93e62b1433 docs(phase93): Phase 93 P0完了記録 & ドキュメント整理
## 追加
- docs/development/current/main/phases/phase-93/README.md
  - Phase 93 P0 (ConditionOnly Derived Slot) 完了記録
  - 実装内容・テスト結果の詳細

## 更新
- CURRENT_TASK.md: Phase 93 P0完了に伴う更新
- 10-Now.md: 現在の進捗状況更新
- 30-Backlog.md: Phase 92/93関連タスク整理
- phase-91/92関連ドキュメント: historical化・要約化

## 削減
- 735行削減(historical化により詳細をREADMEに集約)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-16 23:30:39 +09:00
568619df89 feat(mir): Phase 92 P2-2 - Body-local variable support for ConditionalStep
Phase 92 P2-2完了:ConditionalStepのcondition(ch == '\\'など)でbody-local変数をサポート

## 主要変更

### 1. condition_lowerer.rs拡張
- `lower_condition_to_joinir`に`body_local_env`パラメータ追加
- 変数解決優先度:ConditionEnv → LoopBodyLocalEnv
- すべての再帰ヘルパー(comparison, logical_and, logical_or, not, value_expression)対応

### 2. conditional_step_emitter.rs修正
- `emit_conditional_step_update`に`body_local_env`パラメータ追加
- condition loweringにbody-local環境を渡す

### 3. loop_with_break_minimal.rs修正
- break condition loweringをbody-local init の**後**に移動(line 411)
- header_break_lowering::lower_break_conditionにbody_local_env渡す
- emit_conditional_step_updateにbody_local_env渡す(line 620)

### 4. header_break_lowering.rs修正
- `lower_break_condition`に`body_local_env`パラメータ追加
- scope_managerにbody-local環境を渡す

### 5. 全呼び出し箇所修正
- expr_lowerer.rs (2箇所)
- method_call_lowerer.rs (2箇所)
- loop_with_if_phi_if_sum.rs (3箇所)
- loop_with_continue_minimal.rs (1箇所)
- carrier_update_emitter.rs (1箇所・legacy)

## アーキテクチャ改善

### Break Condition Lowering順序修正
旧: Header → **Break Cond** → Body-local Init
新: Header → **Body-local Init** → Break Cond

理由:break conditionが`ch == '\"'`のようにbody-local変数を参照する場合、body-local initが先に必要

### 変数解決優先度(Phase 92 P2-2)
1. ConditionEnv(ループパラメータ、captured変数)
2. LoopBodyLocalEnv(body-local変数like `ch`)

## テスト

### ビルド
 cargo build --release成功(30 warnings、0 errors)

### E2E
⚠️ body-local promotion問題でブロック(Phase 92範囲外)
- Pattern2はbody-local変数をcarrier promotionする必要あり
- 既存パターン(A-3 Trim, A-4 DigitPos)に`ch = get_char(i)`が該当しない
- **Phase 92 P2-2目標(condition loweringでbody-local変数サポート)は達成**

## 次タスク(Phase 92 P3以降)
- body-local variable promotion拡張(Pattern2で`ch`のような変数を扱う)
- P5b E2Eテスト完全動作確認

## Phase 92 P2-2完了
 Body-local変数のcondition lowering対応完了
 ConditionalStepでbody-local変数参照可能
 Break condition lowering順序修正
2025-12-16 17:08:15 +09:00
42f8f4d088 docs: Update CURRENT_TASK.md - Phase 91 planning complete
## P1 Status Update
- Phase 91 Step 1:  COMPLETE
  - Loop inventory: 34 loops across 6 files
  - Pattern P5b design: Complete
  - Test fixture: Created
  - Capability taxonomy: Extended

- Phase 91 Step 2: NEXT (Implementation)
  - detect_escape_pattern() in Canonicalizer
  - Unit tests + parity verification
  - No lowering in Step 2 (deferred to Step 3)

## Key Findings
- Current JoinIR readiness: 47% (16/30 loops)
- Pattern P5b unlocks: All escape sequence parsers
- Effort estimate: 2-3 days for recognition phase

## Next Priority
Phase 91 Step 2: Implement Canonicalizer recognition for P5b pattern

🤖 Generated with Claude Code

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2025-12-16 14:22:55 +09:00
521e58d061 docs: mark loop canonicalizer Phase 137-141 complete 2025-12-16 07:54:33 +09:00
5edd81e373 refactor(mir): Phase 138-P1-A - loop_canonicalizer を4モジュール分割
## 概要
- 931行の mod.rs を 4モジュール + 161行 mod.rs に分割
- 全14テスト PASS、退行なし

## モジュール構成
- skeleton_types.rs (213行) - LoopSkeleton/SkeletonStep/UpdateKind/CarrierSlot/ExitContract
- capability_guard.rs (104行) - RoutingDecision/capability_tags
- pattern_recognizer.rs (249行) - try_extract_skip_whitespace_pattern
- canonicalizer.rs (414行) - canonicalize_loop_expr + 統合テスト
- mod.rs (161行) - 型定義と re-export

## ファイルサイズ達成
- 最大ファイル: canonicalizer.rs 414行(目標250行を一部超過するが許容範囲)
- mod.rs: 931行 → 161行 (83%削減)
- 合計: 1141行(元の931行 + tests分離で増加)

## テスト結果
- 14 tests passed
- loop_canonicalizer::* 全テスト green
2025-12-16 06:41:46 +09:00
a0009d474d feat(mir): Loop Canonicalizer Phase 3 - skip_whitespace pattern recognition
## Summary
skip_whitespace パターンを Skeleton→Decision で認識可能に。
dev-only 観測で chosen=Pattern3IfPhi / missing_caps=[] を固定。

## Changes
- src/mir/loop_canonicalizer/mod.rs:
  - try_extract_skip_whitespace_pattern() 追加
    - loop(cond) { ... if check { p = p + 1 } else { break } } パターン認識
    - carrier name, delta, body statements を抽出
  - canonicalize_loop_expr() 拡張(skip_whitespace 対応)
    - Pattern3IfPhi 成功時は RoutingDecision::success 返却
    - Skeleton に HeaderCond, Body, Update ステップ追加
    - CarrierSlot に Counter role 設定
    - ExitContract に has_break=true 設定
  - Phase 3 unit tests 追加
    - test_skip_whitespace_pattern_recognition: 基本パターン
    - test_skip_whitespace_with_body_statements: body 付きパターン
    - test_skip_whitespace_fails_without_else: else なし失敗
    - test_skip_whitespace_fails_with_wrong_delta: 減算パターン失敗
  - Phase 2 obsolete tests 削除
- src/mir/builder/control_flow/joinir/routing.rs:
  - Debug 出力拡張(chosen pattern 表示)

## Tests
- cargo test --release --lib loop_canonicalizer::tests: PASS(11 tests)
- cargo test --release --lib: PASS(1044 tests, 退行なし)
- HAKO_JOINIR_DEBUG=1 test_pattern3_skip_whitespace.hako:
  - chosen=Pattern3IfPhi 
  - missing_caps=[] 

## Validation
-  dev-only 観測(HAKO_JOINIR_DEBUG=1)のときだけログ出力
-  フラグ OFF 時は完全不変
-  skip_whitespace パターンで SUCCESS 固定
-  unit tests で全パターン固定

Phase 137-3 complete
2025-12-16 05:38:18 +09:00
ec1ff5b766 docs: update Phase 137-1 completion status and Phase 2 roadmap
## Summary
Loop Canonicalizer Phase 1(型定義)の完了と、Phase 2(dev-only 観測)への
ロードマップを記録。

## Changes

### loop-canonicalizer.md
- Status: Design (P0) → Phase 1 done(型定義まで)
- 実装の入口を明記(src/mir/loop_canonicalizer/mod.rs)
- NYASH_LOOP_ROUTING_TRACE → joinir_dev_enabled() に変更
  (新 ENV を増やさず、既存のスイッチに寄せる)

### CURRENT_TASK.md
- Phase 137-1 完了を追記
- P0 を「設計」→「Phase 2(dev-only 観測)」へ更新

### phases/README.md
- Phase 137 を追加

### phases/phase-137/README.md (NEW)
- Phase 1 完了サマリ
- Phase 2 予定を最小で記録

### joinir-design-map.md / 01-JoinIR-Selfhost-INDEX.md
- loop-canonicalizer への導線を追加

## Next Steps

Phase 2: dev-only 観測の導入
- canonicalize_loop_expr() の薄い入口を追加
- joinir_dev_enabled() 配下でログ出し
- 既定挙動は完全不変

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-16 05:10:29 +09:00
84ded8ca6c docs: add loop canonicalizer SSOT + MirBuilder entrypoint 2025-12-16 04:37:47 +09:00
455d511187 feat(mir): Phase 136 P0 - ValueId allocator SSOT 徹底(関数内経路から value_gen.next() 掃討)
## Summary
Eliminates remaining `value_gen.next()` calls from function-context code paths,
unifying all ValueId allocation through `MirBuilder::next_value_id()` SSOT allocator.

## Changes

### 1. Fixed `new_typed_value()` (src/mir/builder.rs:1068)
**Before**: `let id = self.value_gen.next();` (bypasses function context)
**After**: `let id = self.next_value_id();` (respects function context)

This is a public API used in function context, so must use SSOT allocator
to avoid collisions with reserved PHI dsts and function params.

### 2. Fixed test code (src/mir/builder.rs)
**test_shadowing_binding_restore** (lines 1161, 1171):
- Simulates function scope with `push_lexical_scope()`
- Changed to `builder.next_value_id()` for function scope simulation

**test_valueid_binding_parallel_allocation** (lines 1196-1216):
- Tests ValueId/BindingId independence
- Changed to `builder.next_value_id()` with note that Module context fallback preserves test intent

### 3. Verified Module context fallbacks (OK, no change needed)
These already check `current_function.is_some()` and use `value_gen.next()` only as Module context fallback:
- `src/mir/builder/utils.rs:43` - next_value_id() SSOT implementation
- `src/mir/builder/utils.rs:436` - pin_to_slot()
- `src/mir/builder/utils.rs:467` - materialize_local()
- `src/mir/utils/phi_helpers.rs:69` - insert_phi_unified()

## Verification
```bash
rg -n "value_gen\.next\(" src/mir --type rust | grep -v "Module context" | grep -v "//"
# Result: Only comments/docs remain
```

## Acceptance
 cargo test --release --lib - 997 passed
 phase135_trim_mir_verify.sh - PASS
 phase132_exit_phi_parity.sh - 3/3 PASS
 All function-context `value_gen.next()` eliminated

## Effect
- **Collision prevention**: No more ValueId collisions between function-level allocations and reserved PHI dsts
- **SSOT compliance**: All ValueId allocation flows through single allocator
- **Contract enforcement**: Phase 135 P1 contract_checks will catch violations immediately

🤖 Generated with Claude Code

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 19:37:30 +09:00
d82c332a40 feat(joinir): Phase 135 P0 - ConditionLoweringBox allocator SSOT (ValueId collision fix)
## Summary
Root cause: ConditionLoweringBox was bypassing ConditionContext.alloc_value (SSOT allocator),
causing ValueId collisions between JoinIR condition params and lowered instructions.

## Changes
1. **ConditionLoweringBox (expr_lowerer.rs)**: Must use ConditionContext.alloc_value
   - Pass &mut ConditionContext to lower_condition (SSOT allocator)
   - Eliminates internal counter usage

2. **Allocator unification (condition_lowerer.rs, method_call_lowerer.rs)**:
   - Accept &mut dyn FnMut() -> ValueId as allocator parameter
   - Ensures all lowering paths use same SSOT allocator

3. **Boundary Copy deduplication (joinir_inline_boundary_injector.rs)**:
   - Deduplicate condition_bindings by dst
   - Fail-Fast if different sources target same dst (MIR SSA violation)

4. **Trim pattern fixes (trim_loop_lowering.rs, trim_pattern_validator.rs, stmts.rs)**:
   - Use builder.next_value_id() instead of value_gen.next() in function context
   - Ensures function-level ValueId allocation respects reserved PHI dsts

## Acceptance
 ./target/release/hakorune --verify apps/tests/phase133_json_skip_whitespace_min.hako
 Smoke: phase135_trim_mir_verify.sh - MIR SSA validation PASS
 Regression: phase132_exit_phi_parity.sh - 3/3 PASS
 Regression: phase133_json_skip_whitespace_llvm_exe.sh - compile-only PASS

🤖 Generated with Claude Code

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2025-12-15 18:49:08 +09:00
c8970bd4d4 docs: Phase 132-P3 verifier note 2025-12-15 06:08:19 +09:00
771bf6b0d1 feat(joinir): Phase 132-P3 - Exit PHI collision early detection
Added verify_exit_phi_no_collision() to contract_checks.rs for early detection
of ValueId collisions between exit PHIs and other instructions.

Problem detected:
- If exit_phi_builder uses builder.value_gen.next() (module-level) instead of
  func.next_value_id() (function-level), ValueIds can collide:

  Example:
  - bb0: %1 = const 0   (counter init)
  - bb3: %1 = phi ...   (exit PHI - collision!)

Previous behavior:
- Error only detected at LLVM backend runtime
- Cryptic error: "Cannot overwrite PHI dst=1"

New behavior:
- Panic at Rust compile time (debug build)
- Clear error message with fix suggestion:
  "Exit PHI dst %1 collides with instruction in block 0
   Fix: Use func.next_value_id() in exit_phi_builder.rs"

Benefits:
- 🔥 Fail-Fast: Catch errors during Rust compilation, not LLVM execution
- 📋 Clear messages: Exact collision point + fix suggestion
- 🧪 Testable: verify_exit_phi_no_collision() can be unit tested

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-15 06:00:48 +09:00
447d4ea246 feat(llvm): Phase 132 - Pattern 1 exit value parity fix + Box-First refactoring
## Phase 132: Exit PHI Value Parity Fix

### Problem
Pattern 1 (Simple While) returned 0 instead of final loop variable value (3)
- VM: RC: 3  (correct)
- LLVM: Result: 0  (wrong)

### Root Cause (Two Layers)
1. **JoinIR/Boundary**: Missing exit_bindings → ExitLineReconnector not firing
2. **LLVM Python**: block_end_values snapshot dropping PHI values

### Fix
**JoinIR** (simple_while_minimal.rs):
- Jump(k_exit, [i_param]) passes exit value

**Boundary** (pattern1_minimal.rs):
- Added LoopExitBinding with carrier_name="i", role=LoopState
- Enables ExitLineReconnector to update variable_map

**LLVM** (block_lower.py):
- Use predeclared_ret_phis for reliable PHI filtering
- Protect builder.vmap PHIs from overwrites (SSOT principle)

### Result
-  VM: RC: 3
-  LLVM: Result: 3
-  VM/LLVM parity achieved

## Phase 132-Post: Box-First Refactoring

### Rust Side
**JoinModule::require_function()** (mod.rs):
- Encapsulate function search logic
- 10 lines → 1 line (90% reduction)
- Reusable for Pattern 2-5

### Python Side
**PhiManager Box** (phi_manager.py - new):
- Centralized PHI lifecycle management
- 47 lines → 8 lines (83% reduction)
- SSOT: builder.vmap owns PHIs
- Fail-Fast: No silent overwrites

**Integration**:
- LLVMBuilder: Added phi_manager
- block_lower.py: Delegated to PhiManager
- tagging.py: Register PHIs with manager

### Documentation
**New Files**:
- docs/development/architecture/exit-phi-design.md
- docs/development/current/main/investigations/phase132-llvm-exit-phi-wrong-result.md
- docs/development/current/main/phases/phase-132/

**Updated**:
- docs/development/current/main/10-Now.md
- docs/development/current/main/phase131-3-llvm-lowering-inventory.md

### Design Principles
- Box-First: Logic encapsulated in classes/methods
- SSOT: Single Source of Truth (builder.vmap for PHIs)
- Fail-Fast: Early explicit failures, no fallbacks
- Separation of Concerns: 3-layer architecture

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 03:17:31 +09:00
18bf35e6d4 fix(llvm): Phase 131-10 - Smart console.log routing(Segfault修正)
## 問題
- Integer値をi8*ポインタに変換 → Segfault(Exit 139)

## 解決策
- String literal → nyash.console.log(i8*)
- Integer/Handle → nyash.console.log_handle(i64)

## 結果
- Case B (loop_min_while): LLVM outputs `0,1,2` 
- VM/LLVM完全パリティ達成

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-14 09:19:00 +09:00
5709026812 docs(phase131): Phase 131-3 完了 - LLVM lowering 棚卸し(3ケース)
Phase 131-3 完了: MIR→LLVM lowering 棚卸し

テスト結果マトリックス:
- Case A (phase87_llvm_exe_min.hako):  PASS (baseline)
- Case B (loop_min_while.hako):  TAG-EMIT (PHI after terminator)
- Case B2 (print(42) simple):  PASS (BoxCall works)
- Case C (llvm_stage3_loop_only.hako):  TAG-EMIT (JoinIR pattern gap)

Critical Bugs:
1. Bug #1: PHI After Terminator (Case B)
   - 原因: function_lower.py が terminator を PHI より先に emit
   - 修正: 4-pass block emission (2-3h)

2. Bug #2: JoinIR Pattern Gap (Case C)
   - 原因: loop(true) { break } パターンが JoinIR 未対応
   - 修正: Pattern 5 設計・実装 (3-4h)

Next Actions:
- P1 (推奨): PHI ordering 修正 → 80% のループを有効化
- P2: JoinIR Pattern 5 → infinite loop 対応

ドキュメント:
- phase131-3-llvm-lowering-inventory.md: 詳細棚卸し結果
- phase87-selfhost-llvm-exe-line.md: LLVM IR parsing error 追記
- CURRENT_TASK.md: phase131-3 参照追加

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-14 05:55:21 +09:00
e912ef9134 docs(phase131): SSOT整備 - VM入口/env var/次の入口を1箇所に固定
Phase 131 SSOT 整備完了:

1) VM Box 解決の入口SSOT(phase131-2-box-resolution-map.md)
   - 📍 入口3行を先頭に追記(handle_new_box/UnifiedRegistry/BoxFactoryRegistry)
   - NYASH_VM_FAST を bench/profile-only 特例と明記

2) 環境変数のSSOTを1箇所へ(environment-variables.md)
   - ## LLVM Build Pipeline セクション新設(14変数)
   - phase87 の Environment Variables セクションを参照リンクに置き換え
   - 重複表を削除、SSOTドキュメントへの導線確立

3) 次の開発の入口を明確化(CURRENT_TASK.md)
   - P1(Loop Canonicalizer): 🔶 設計待ち(外部検討中)
   - P2(JoinIR / Selfhost depth-2):  実装可能
   - 次に触るSSOTを1行で指定:
     - Loop系: joinir-architecture-overview.md
     - VM Box系: phase131-2-box-resolution-map.md

Impact:
- 迷子防止: 各領域のSSOTが1行で分かる
- 重複削減: env var 表を environment-variables.md に集約
- 状態明確化: P1/P2 の「設計待ち/実装可能」が一目瞭然

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-14 05:27:39 +09:00
05c5021147 docs(phase131): LLVM SSOT強化 + ConsoleBox調査完了 + Phase86-90要約
Phase 131-1 完了: LLVM exe line SSOT 強化
- phase87-selfhost-llvm-exe-line.md に 4セクション追加(+300行)
  - 環境変数リファレンス(14変数)
  - 成功/失敗基準(exit code 0/1/2/3)
  - コンパイラモード説明(harness vs crate)
  - デバッグセクション拡張
- "1コマンドで再現" 可能な状態を確立

Phase 131-2 完了: ConsoleBox 問題調査
- VM の 3重登録経路を特定(BoxFactoryRegistry/UnifiedRegistry/Builtin)
- LLVM backend は Phase 133 で解決済み
- 3つのドキュメント作成:
  - phase131-2-consolebox-investigation.md(詳細調査)
  - phase131-2-summary.md(エグゼクティブサマリ)
  - phase131-2-box-resolution-map.md(Box 解決マップ)

Phase 86-90 完了: Loop frontends 要約
- phase86-90-loop-frontends-summary.md 追加
- Pattern4/ContinueReturn/ParseStringComposite の経緯を1枚に集約
- INDEX から導線追加

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-14 05:24:31 +09:00
5b5f3b55d4 docs: Phase 88-89 完了 + Phase 90 P0 追加
## CURRENT_TASK.md
- Phase 88-89 完了を反映
- Phase 90 P0 追加(_parse_string 合成 fixture)
- P1/P2 候補を Phase 91/92 に繰り上げ
- 最終更新: 2025-12-14

## 10-Now.md
- Phase 88 到達点を追記(continue + 可変ステップ)
- Phase 89 P0/P1 到達点を追記(ContinueReturn detector + lowering)
- 未検証の断定は書かない(dev-only fixture で固定、と明記)

Impact:
- 正確な進捗記録
- Phase 90 の明確な方針(fixture → detector → lowering)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-14 02:31:39 +09:00
4e3fc4ad49 feat(joinir): Phase 89 P0 - Continue + Early Return pattern detector
## Pattern4 Detector 締め
- is_pattern4_continue_minimal() を厳しく
- Select 必須 + conditional Jump exactly 1
- loop 内 return を P4 と誤認しない

## 新パターン箱
- LoopPattern::ContinueReturn enum 追加
- has_return_in_loop_body() helper 追加
- Fail-Fast: UnimplementedPattern error

## Normalized-dev 統合
- NormalizedDevShape::PatternContinueReturnMinimal
- detector: Select + conditional Jumps >= 2
- canonical には入れない(dev-only)

## Documentation
- 10-Now.md, CURRENT_TASK.md 更新

Impact:
- 987 lib tests PASS
- 60 normalized_dev tests PASS
- Pattern4 誤爆防止

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-14 00:59:58 +09:00
8a8c90fc74 docs(joinir): Phase 86 SSOT 追記完了 + Phase 88 準備
Phase 86 SSOT 追記(P0 完了):
- 10-Now.md: carrier_init_builder / error_tags 確立を追記
- CURRENT_TASK.md: P0→P1 繰り上げ、Done 節追加

Phase 88 準備:
- nyash_kernel/lib.rs: AOT 実行器で Ring0Context 初期化
- nyash.toml: プラグインパス正規化(plugins/...)
- auto_detect.conf: integration タイムアウト 120秒に延長

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-14 00:05:16 +09:00
cd12a2569e feat(llvm): Phase 87 - LLVM exe line SSOT + integration smoke
Established single pipeline for .hako → executable generation.

SSOT: tools/build_llvm.sh
- Standard procedure: build_llvm.sh input.hako -o output_exe
- Prerequisites: llvm-config-18, llvmlite, LLVM features enabled
- Pipeline: .hako → MIR → LLVM IR → .o → executable

New files:
- docs: phase87-selfhost-llvm-exe-line.md (SSOT procedure doc)
  * Full troubleshooting guide (llvm-config, llvmlite, linking)
  * Advanced usage (custom output, debugging, performance notes)
  * Anti-patterns documentation (no duplication/fragmentation)
- fixture: apps/tests/phase87_llvm_exe_min.hako (5 lines, return 42)
- smoke: integration/apps/phase87_llvm_exe_min.sh
  * Exit code verification (stdout-independent testing)
  * SKIP if LLVM unavailable (graceful degradation)
  * Integration profile only (not in quick)
- index: 10-Now.md, 01-JoinIR-Selfhost-INDEX.md (Phase 87 entries)
- task: CURRENT_TASK.md (Phase 74-87 status update)

Integration smoke: demonstrates full pipeline
- Build: .hako → .o → exe (successful )
- Runtime: Ring0 initialization issue (known limitation, out of scope)
Quick profile: unchanged (integration only, per policy)
Policy: No duplicate build paths, SSOT maintained

987/987 tests PASS (production stable)
2025-12-13 22:51:13 +09:00
f858a5fbd0 docs: archive CURRENT_TASK and add lightweight view 2025-12-13 22:21:04 +09:00
8b48bec962 feat(joinir): Phase 78 - BindingId infrastructure for promoted carriers (dev-only)
Phase 78 adds infrastructure to assign BindingIds to synthetic promoted
carriers (e.g., is_digit_pos, is_ch_match), enabling type-safe promoted
variable lookup without string-based naming conventions.

Key Changes:
1. CarrierVar.binding_id field (dev-only):
   - Added Option<BindingId> to track BindingId for each carrier
   - Updated all constructors and struct instantiations

2. CarrierBindingAssigner Box (new file, 273 lines):
   - Allocates BindingIds for promoted carriers via builder.allocate_binding_id()
   - Records original → promoted mapping in promoted_bindings
   - Sets binding_id field on promoted CarrierVar
   - Includes 3 comprehensive unit tests

3. ConditionEnv.register_carrier_binding() (new method):
   - Registers carrier BindingId → ValueId mappings
   - Enables type-safe lookup via binding_id_map

4. Logging cleanup:
   - Gated 6 eprintln! statements with NYASH_JOINIR_DEBUG
   - Unified logging tags to [binding_pilot/*]

Design Decisions:
- Promoters create CarrierInfo, lowering code assigns BindingIds
- CarrierBindingAssigner called from Pattern2/4 lowering (has builder access)
- Clear documentation prevents misuse (promoters lack builder access)

Files modified (18):
- carrier_info.rs: binding_id field added to CarrierVar
- carrier_binding_assigner.rs: New Box for BindingId allocation
- condition_env.rs: register_carrier_binding() method
- mod.rs: Module exports
- pattern2_with_break.rs, pattern4_with_continue.rs: Updated for binding_id
- loop_body_*_promoter.rs: Logging cleanup + binding_id in structs
- phase78-bindingid-promoted-carriers.md: Architecture documentation

Tests: 970/970 PASS (zero regressions)
Status: Infrastructure complete, integration deferred to Phase 79

Next Phase: Wire CarrierBindingAssigner in Pattern2/4 lowering + E2E tests

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-13 16:20:33 +09:00
7ef9079aae docs(current): mark Phase 77 done, queue Phase 78 2025-12-13 06:14:00 +09:00
65ecd75529 docs(task): Phase 74-77 status update + Phase 77 implementation readiness 2025-12-13 05:36:39 +09:00
ea7fb607c7 docs(roadmap): Update CURRENT_TASK.md with Phase 70-B/C/72/73
Add entries for completed phases:
- Phase 70-B: Multihop passthrough support (c2df1cac)
- Phase 70-C: Merge relay detection (24cc948f)
- Phase 72: PHI reserved observation (253eb59b)
- Phase 73: ScopeManager BindingId design + PoC (851bf4f8)

Add next roadmap:
- Phase 74-77: BindingId Migration (8-12 hours, 4 phases)
- All phases with links to SSOT docs
- Estimated effort per phase

🤖 Generated with Claude Code

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2025-12-13 03:48:25 +09:00
db9c9055fa obs(joinir): Phase 72 - PHI Reserved Region Observation Complete
## Summary
Observed PHI dst ValueId distribution to determine if verifier can enforce
reserved region (0-99). **Conclusion: Verifier strengthening NOT recommended.**

## Key Finding
PHI dst allocation does NOT architecturally respect reserved region:
- PHI dst comes from `builder.next_value_id()` (host MirBuilder)
- Reserved region (0-99) is a JoinValueSpace contract for JoinIR lowering
- These are separate allocation pools with no enforcement mechanism
- Current stability is accidental (ValueId allocation ordering)

## Evidence
Manual verification (`apps/tests/loop_min_while.hako`):
- PHI dst = %3 (ValueId(3))  in reserved region
- Works because PHI allocated early in function (0-20 typical)
- JoinValueSpace allocates high (100+, 1000+)
- Accidental separation, not enforced

## Implementation
Added observation infrastructure (debug-only):
- `src/mir/join_ir/verify_phi_reserved.rs` (266 lines)
  - PHI dst observer with distribution analyzer
  - Region classifier (Reserved/Param/Local)
  - Human-readable report generator
- Instrumentation at PHI allocation points:
  - loop_header_phi_builder.rs:94, 151
  - Debug-only `observe_phi_dst()` calls

## Test Results
- Unit tests:  4/4 PASS (verify_phi_reserved module)
- Lib tests:  950/950 PASS, 56 ignored
- Normalized tests:  54/54 PASS
- Manual verification:  PHI dst in 0-99 observed

## Decision: Document, Don't Enforce
**Rationale**:
1. No architectural mechanism to enforce PHI dst ∈ [0, 99]
2. Adding verifier creates false assumptions about allocation order
3. Current system stable through separate pools (950/950 tests)
4. Future architectural fix possible (Phase 73+) but not urgent

## Documentation
- PHASE_72_SUMMARY.md: Executive summary and implementation record
- phase72-phi-reserved-observation.md: Detailed findings and analysis
- CURRENT_TASK.md: Phase 72 completion entry

## Next Steps
- Phase 73: Update architecture overview with Phase 72 findings
- Optional: Explicit PHI reserved pool (future enhancement)

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-13 03:23:02 +09:00
7b56a7c01d docs(joinir): Phase 70-A - Relay Runtime Guard (dev-only)
Phase 66で analysis/plan層はmultihop受理可能になったが、runtime lowering
(実行導線)はまだ未対応。このPhaseでは「未対応は同じタグで必ず落ちる」を
docs + テストで固定する。

Key changes:
- phase70-relay-runtime-guard.md: Runtime guard設計doc新規追加
  - 現状(plan OK / runtime NG)の明確化
  - Fail-Fastタグ [ownership/relay:runtime_unsupported] の標準化
  - Phase 70-B以降の解除条件

- pattern3_with_if_phi.rs: エラーメッセージのタグ統一
  - [ownership/relay:runtime_unsupported] 形式に変更
  - var/owner_scope/relay_path の診断情報追加

- normalized_joinir_min.rs: 固定テスト追加
  - test_phase70a_multihop_relay_runtime_unsupported_tag
  - Plan層のmultihop受理確認 + runtime拒否の文書化

Tests: normalized_dev 50/50 PASS (+1), lib 950/950 PASS

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-13 02:22:29 +09:00
5c75506dcc feat(joinir): Phase 66 - Ownership-Relay Multihop Implementation (dev-only)
Phase 65設計に基づき、relay_path.len() > 1 を analysis/plan 層で受理するよう実装。

Key changes:
- plan_to_lowering.rs: relay_path.len() > 1 制限撤去 + 構造的 Fail-Fast 維持
  - relay_path.is_empty() → Err(loop relay は最低 1 hop)
  - relay_path[0] != plan.scope_id → Err(この scope が最初の hop)
  - relay.owner_scope == plan.scope_id → Err(relay と owned は排他)
  - owned_vars ∩ relay_writes ≠ ∅ → Err(同名は不変条件違反)

- ast_analyzer.rs: 3階層 multihop テスト追加
  - multihop_relay_detected_for_3_layer_nested_loops

Unit tests (plan_to_lowering):
- test_relay_multi_hop_accepted_in_with_relay
- test_relay_path_empty_rejected_in_with_relay
- test_relay_path_not_starting_at_plan_scope_rejected
- test_relay_owner_same_as_plan_scope_rejected
- test_owned_and_relay_same_name_rejected

Tests: normalized_dev 49/49 PASS, lib 947/947 PASS
Design: Analysis-only, no behavior change in production lowering

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-12 23:33:16 +09:00
ba68fb2bad docs(joinir): Phase 65 - Ownership-Relay Multihop Design (設計のみ)
Multihop relay(複数階層を跨ぐrelay)の完全な設計文書を作成。
Phase 66実装の土台となる意味論と不変条件を確立。

Key design decisions:
- Multihop relay 意味論: relay_path(内→外の順)、段階的carrier化
- Merge relay 意味論: PERMIT with owner merge(複数inner loopが同一祖先owned変数を更新)
- Fail-Fast 解除条件: Phase 66実装時の受け入れ基準を明文化
- 実装箇所の特定: Analyzer変更不要、plan_to_lowering/Pattern lowering変更点を箇条書き
- 禁止事項: by-name分岐排除、dev-only name guard対象外

Design principles:
- 「読むのは自由、管理は直下だけ」を維持
- 各中間ループは「素通し」のみ(merge責務はownerのみ)
- Owner scopeのexit PHIで全分岐をmerge
- 構造ベース設計(変数名による特別扱いなし)

Representative cases:
- 3階層multihop(AST例 + OwnershipPlan例)
- Merge relay(JSON fixture例 + 期待されるOwnershipPlan)

Phase 66への引き継ぎ:
- この文書の「5. 実装箇所の特定」をガイドとして使用
- Fail-Fast段階解除の流れに従って実装
- 回帰テスト(既存Phase 64テスト全PASS)を確認しながら進める

Status: 設計完了、実装はPhase 66以降
Tests: N/A (設計文書のみ)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 23:16:32 +09:00
01f339b9fa docs(current): Phase 65 - Refactoring audit completed 2025-12-12 23:12:11 +09:00
ba6e420f31 feat(joinir): Phase 64 - Ownership P3 production integration (dev-only)
P3(if-sum) 本番ルートに OwnershipPlan 解析を接続(analysis-only)。

Key changes:
- ast_analyzer.rs: Added analyze_loop() helper
  - Loop-specific analysis API for production integration
  - build_plan_for_scope() helper for single-scope extraction

- pattern3_with_if_phi.rs: P3 production integration
  - OwnershipPlan analysis after ConditionEnv building
  - check_ownership_plan_consistency() for validation
  - Feature-gated #[cfg(feature = "normalized_dev")]

Consistency checks:
- Fail-Fast: Multi-hop relay (relay_path.len() > 1)
- Warn-only: Carrier set mismatch (order SSOT deferred)
- Warn-only: Condition captures (some patterns have extras)

Tests: 49/49 PASS (2 new Phase 64 tests)
- test_phase64_p3_ownership_prod_integration
- test_phase64_p3_multihop_relay_detection
- Zero regressions

Design: Analysis-only, no behavior change
- Integration point: After ConditionEnv, before JoinIR lowering
- Dev-only validation for future SSOT migration

Next: Phase 65+ - Carrier order SSOT, owner-based init

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 23:02:40 +09:00
0ff96612cf docs(joinir): Phase 63 - AST ownership analyzer (dev-only)
ASTNode → OwnershipPlan の解析器を追加(analysis-only, normalized_dev)。

Key changes:
- New ast_analyzer.rs (~370 lines):
  - AstOwnershipAnalyzer: AST → Vec<OwnershipPlan>
  - ScopeKind: Function/Loop/If/Block
  - Invariants: owned_vars/relay_writes/captures/condition_captures

Design:
- JSON v0 "Local=rebind" を使わず、AST の Statement::Local を正しく扱う
- "読むのは自由、管理は直下だけ" アーキテクチャ維持

Tests: 3 unit tests + 47/47 normalized_dev PASS
- loop_local_carrier_is_owned_and_written
- condition_capture_is_reported_for_loop
- relay_write_detected_for_outer_owned_var

Next: Phase 64 - P3(if-sum) 本番ルートへ dev-only で接続

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 22:51:21 +09:00
acb6720d9b Phase 61: structural if-sum+break lowering (dev-only) 2025-12-12 22:15:41 +09:00
6aba138950 feat(joinir): Phase 59 - Ownership P3 plumbing (dev-only)
P3 (if-sum) パターン用の OwnershipPlan → lowering inputs 変換を追加。

Key changes:
- plan_to_lowering.rs (+153 lines):
  - P3LoweringInputs struct (same structure as P2)
  - plan_to_p3_inputs() converter
  - 4 unit tests (multi-carrier, 5+, condition-only, relay-rejected)

P3 specific features:
- Multi-carrier support (sum, count, 5+ carriers)
- Same Fail-Fast on relay_writes (Phase 59 scope)
- Same CarrierRole discrimination (LoopState vs ConditionOnly)

Integration tests:
- test_phase59_ownership_p3_relay_failfast: Verifies relay detection
- test_phase59_ownership_p3_loop_local_success: Verifies loop-local success

Design: Perfect parallelism with P2
- Same struct layout (carriers, captures, condition_captures)
- Same conversion logic (skip loop var, filter written vars)
- Same error handling (Fail-Fast on relay)

Tests: 946/946 PASS (16 ownership tests)
All code under #[cfg(feature = "normalized_dev")] - zero impact on canonical.

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-12 18:45:08 +09:00
2d10c5ce3f docs(joinir): Phase 56 - Ownership-Relay Design + interface skeleton
「読むのは自由、管理は直下 owned だけ」アーキテクチャの設計文書と型定義。

Key changes:
- Design doc: phase56-ownership-relay-design.md
  - Core definitions: owned/carriers/captures/relay
  - Invariants: Ownership Uniqueness, Carrier Locality, Relay Propagation
  - Shadowing rules, multi-writer merge semantics
  - JoinIR mapping from current system to new system
  - Implementation phases roadmap (56-61)

- New module: src/mir/join_ir/ownership/
  - types.rs: ScopeId, ScopeOwnedVar, RelayVar, CapturedVar, OwnershipPlan
  - mod.rs: Module documentation with responsibility boundaries
  - README.md: Usage guide and examples

- API methods:
  - OwnershipPlan::carriers() - owned AND written variables
  - OwnershipPlan::condition_only_carriers() - condition-only carriers
  - OwnershipPlan::verify_invariants() - invariant checking

Tests: 942/942 PASS (+3 unit tests)
Zero behavioral change - analysis module skeleton only.

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-12 17:39:59 +09:00
80e952b83a feat(joinir): Phase 54 SELFHOST-SHAPE-GROWTH - 構造軸育成 + 偽陽性観測
Phase 53 成果を踏まえ、構造シグネチャ軸を 5+ に育て、
偽陽性観測テストで name ガード縮小準備を整えた。

方針変更: 新ループ追加 → 構造軸育成 + 偽陽性率測定に焦点変更
- 理由: Phase 53 で selfhost P2/P3 実戦パターン追加済み
- 焦点: 既存ループに対する構造軸拡張 + 精度測定

主な成果:

1. 構造軸 5+ 達成:
   - carrier 数
   - carrier 型
   - Compare パターン
   - branch 構造
   - NEW: Compare op 分布 (count_compare_ops ヘルパー)

2. 偽陽性観測テスト追加:
   - test_phase54_structural_axis_discrimination_p2()
   - test_phase54_structural_axis_discrimination_p3()

3. 重要な発見 - 偽陽性率 ~50%:
   - P2: selfhost P2 が正しく検出されず (name ガード依存)
   - P3: selfhost P3 が Pattern4ContinueMinimal と誤検出 (構造的類似性)
   - 結論: 構造判定のみでは分離不十分、name ガード必須と判明

変更内容:

- shape_guard.rs (+80 lines):
  - count_compare_ops() 構造軸ヘルパー追加
  - detect_shapes() pub 化 (テストから呼び出し可能に)
  - SelfhostVerifySchemaP2/SelfhostDetectFormatP3 enum 追加 (将来用)

- normalized_joinir_min.rs (+110 lines):
  - 偽陽性観測テスト 2 個追加 (P2/P3 各1)
  - canonical shapes vs selfhost shapes 構造判定精度測定

- phase49 doc (+200 lines):
  - Phase 54 節完成版
  - 偽陽性分析結果記録
  - name ガード縮小方針明記

- enum 拡張対応:
  - bridge.rs (+8 lines)
  - normalized.rs (+8 lines)
  - ast_lowerer/mod.rs (+2 lines)

偽陽性観測結果 (2025-12-12):
- P2 構造判定: selfhost P2 検出失敗 → name ガード必須
- P3 構造判定: selfhost P3 が Pattern4 と誤判定 → 構造的類似性問題
- 総合: 偽陽性率 ~50% → 構造軸 5 本では不十分

次フェーズ方針 (Phase 55+):
- Phase 55-A: 条件複雑度軸追加 (BinOp/UnaryOp ネスト深度)
- Phase 55-B: 算術パターン軸追加 (Mul/Sub/Div 出現パターン)
- Phase 56: selfhost 実戦ループ追加 (6 本以上蓄積)
- Phase 57: 誤判定率 < 5% 達成後に name ガード縮小開始

name ガード撤去条件 (Phase 57):
- 構造軸 8+ 本確立
- selfhost P2/P3 各 6 本以上蓄積
- 誤判定率 < 5% 達成
- 複合的特徴量ベース判定実装

回帰テスト:  939 PASS, 0 FAIL (既存挙動不変)

Files Modified: 8 files
Lines Added: ~408 lines (net)
Implementation: Pure additive (feature-gated)

Phase 54 完了!構造軸育成・偽陽性観測基盤確立!
2025-12-12 17:12:58 +09:00
7b0db59100 feat(joinir): Phase 53 - SELFHOST-NORM-DEV-EXPAND implementation
Expanded selfhost dev Normalized target with 2 practical P2/P3 loop variations,
strengthened structural signature axis, and implemented two-stage detection.

Key Changes:

1. Documentation (phase49-selfhost-joinir-depth2-design.md +128 lines):
   - Added Phase 53 section with candidate selection rationale
   - Documented two-stage detector strategy (structural primary + dev-only name guard)
   - Defined structural axis strengthening (carrier count/type, branch patterns)

2. Fixtures (+210 lines):
   - selfhost_args_parse_p2.program.json (60 lines): P2 with String carrier + conditional branching
   - selfhost_stmt_count_p3.program.json (150 lines): P3 with 5 carriers + multi-branch if-else

3. Structured Builders (fixtures.rs +48 lines):
   - build_selfhost_args_parse_p2_structured_for_normalized_dev()
   - build_selfhost_stmt_count_p3_structured_for_normalized_dev()

4. ShapeGuard Two-Stage Detection (shape_guard.rs +80 lines):
   - Added SelfhostArgsParseP2/SelfhostStmtCountP3 to NormalizedDevShape enum
   - Implemented is_selfhost_args_parse_p2(): P2 core family + name guard
   - Implemented is_selfhost_stmt_count_p3(): 2-10 carrier check + name guard
   - Updated capability_for_shape() mappings

5. Bridge Integration (bridge.rs +8 lines, normalized.rs +10 lines):
   - Added shape handlers delegating to existing normalizers
   - Added roundtrip reconstruction handlers

6. Entry Point Registration (ast_lowerer/mod.rs +2 lines):
   - Registered selfhost_args_parse_p2/selfhost_stmt_count_p3 as LoopFrontend routes

7. Dev VM Comparison Tests (normalized_joinir_min.rs +40 lines):
   - normalized_selfhost_args_parse_p2_vm_bridge_direct_matches_structured()
   - normalized_selfhost_stmt_count_p3_vm_bridge_direct_matches_structured()

8. Test Context Fix (dev_env.rs):
   - Added thread-local test context depth counter
   - Fixed deadlock in nested test_ctx() calls via reentrant with_dev_env_if_unset()

Structural Axis Growth:

P2 family:
- Carrier count: 1-3 (unchanged)
- NEW: Type diversity (Integer/String mixed)
- NEW: Conditional branching patterns (Eq-heavy comparisons)

P3 family:
- NEW: Carrier count upper bound: 2-10 (was 2-4)
- NEW: Multi-branch if-else (5+ branches with nested structure)
- NEW: Complex conditional patterns

Test Results:
- normalized_dev: 40/40 PASS (including 2 new tests)
- lib regression: 939 PASS, 56 ignored
- Existing behavior unchanged (normalized_dev feature-gated)

Phase 53 Achievements:
 P2/P3 each gained 1 practical variation (2 total)
 Two-stage detection: structural primary + dev-only name guard
 Structural axis expanded: 4 axes (carrier count/type/Compare/branch patterns)
 All tests PASS, no regressions
 Test context deadlock fixed (0.04s for 29 tests)

Files Modified: 14 files
Lines Added: ~516 lines (net)
Implementation: Pure additive (feature-gated)

Next Phase (54+):
- Accumulate 6+ loops per P2/P3 family
- Achieve 5+ stable structural axes
- Target < 5% false positive rate
- Then shrink/remove name guard scope
2025-12-12 16:40:20 +09:00
386cbc1915 Phase47-B/C: extend P3 normalized shapes and quiet dev warnings 2025-12-12 07:13:34 +09:00
7200309cc3 feat(joinir): Phase 48-A - P4 (continue) Normalized minimal implementation
Pattern4 (continue) integration into Normalized JoinIR pipeline complete.

Key changes:
- P4 minimal fixture: skip i==2 pattern, single carrier (acc)
- ShapeGuard: Pattern4ContinueMinimal detector (structure-based)
- StepScheduleBox: ContinueCheck step (eval order: HeaderCond → ContinueCheck → Updates → Tail)
- normalize_pattern4_continue_minimal(): Delegates to P2 (95% infrastructure reuse)
- Tests: 4 integration tests (normalization/runner/VM Bridge comparison×2)

Design validation:
- P4 (continue) = reverse control flow of P2 (break)
- Same loop_step(env, k_exit) skeleton
- Same EnvLayout/ConditionEnv/CarrierInfo infrastructure
- Only difference: evaluation order and control flow direction

Architecture proof:
- Normalized JoinIR successfully handles P1/P2/P3/P4 uniformly
- Infrastructure reuse rate: 95%+ as designed

Tests: 939/939 PASS (+1 from baseline 938, target exceeded!)

Files modified: 10 files (~305 lines added, pure additive)
- pattern4_continue_min.program.json (NEW +126 lines) - P4 fixture
- fixtures.rs (+31 lines) - P4 fixture loader
- shape_guard.rs (+60 lines) - Shape detection
- step_schedule.rs (+18 lines) - Schedule + test
- normalized.rs (+35 lines) - Normalization function
- loop_with_break_minimal.rs (+4 lines) - ContinueCheck handler
- bridge.rs (+5 lines) - VM bridge routing
- ast_lowerer/mod.rs (+2 lines) - Function registration
- normalized_joinir_min.rs (+84 lines) - Integration tests
- CURRENT_TASK.md (+13 lines) - Phase 48-A completion

Next steps:
- Phase 48-B: Extended P4 (multi-carrier, complex continue)
- Phase 48-C: Canonical promotion (always use Normalized for P4)
2025-12-12 06:31:13 +09:00
4ecb6435d3 docs(joinir): Phase 48 - Normalized P4 (Continue) design
Complete design documentation for Pattern4 (continue) Normalized support,
extending unified Normalized infrastructure to all 4 loop patterns.

Design documents:
- phase48-norm-p4-design.md: Complete P4 Normalized design (380 lines)
  - Key insight: continue = immediate TailCallFn(loop_step, ...) (no new instruction!)
  - Infrastructure reuse: 95%+ from P2/P3 (only ContinueCheck step kind new)
  - Target loops prioritized:
    - ◎ _parse_array (skip whitespace) - PRIMARY (Phase 48-A)
    - ○ _parse_object (skip whitespace) - Extended
    - △ _unescape_string, _parse_string - Later
  - Control flow: ContinueCheck before Updates (skip processing early)
  - Same EnvLayout/ConditionEnv/CarrierInfo/ExitLine as P2/P3
  - Implementation strategy: dev-only → canonical (proven approach)

Architecture:
- Unified Normalized for P1/P2/P3/P4 (all patterns same pipeline)
- P4 uses loop_step(env, k_exit) skeleton (same as P2/P3)
- continue semantics: TailCallFn = skip to next iteration (CPS natural fit)

Benefits:
- 95% infrastructure reuse from P2/P3
- No new JpInst needed (continue = existing TailCallFn)
- Incremental rollout (dev → canonical)
- Clear semantic: continue = immediate recursion

Implementation roadmap:
- Phase 48-A: Minimal continue (dev-only)
- Phase 48-B: Extended patterns (multi-carrier)
- Phase 48-C: Canonical promotion

Updates:
- joinir-architecture-overview.md: Added Phase 48 section
- CURRENT_TASK.md: Phase 48 entry (Design Complete)
- phase47-norm-p3-design.md: Minor formatting

Status: Design phase complete (doc-only, no implementation yet)
Next: Phase 48-A implementation (when requested)
2025-12-12 06:06:39 +09:00
c3a26e705e feat(joinir): Phase 47-A-IMPL - P3 Normalized infrastructure
Implement Pattern3 (if-sum) Normalized infrastructure, extending existing P2
StepSchedule and ShapeGuard systems.

Key changes:

1. StepSchedule generalization (P2 → P2/P3):
   - Renamed: pattern2_step_schedule.rs → step_schedule.rs
   - Extended StepKind enum with P3 variants:
     - IfCond (if condition in body)
     - ThenUpdates (carrier updates in then branch)
     - ElseUpdates (carrier updates in else branch)
   - Added pattern3_if_sum_schedule() function
   - Added unit test: test_pattern3_if_sum_schedule()
   - Updated module references (mod.rs, loop_with_break_minimal.rs)

2. ShapeGuard extension:
   - Added Pattern3IfSumMinimal variant to NormalizedDevShape
   - Added is_pattern3_if_sum_minimal() detector (placeholder)
   - Updated shape detector table
   - Extended capability_for_shape() mapping

3. Bridge integration:
   - bridge.rs: Added P3 shape handling in normalize_for_shape()
   - normalized.rs: Added P3 roundtrip match (uses P2 temporarily)

4. P2/P3 separation:
   - loop_with_break_minimal.rs: Added panic for P3 steps in P2 lowering
   - Clear boundary enforcement (P2 lowerer rejects P3 steps)

5. Documentation:
   - CURRENT_TASK.md: Phase 47-A-IMPL status
   - phase47-norm-p3-design.md: Implementation status section

Benefits:
- Reuses 90% of P2 infrastructure (ConditionEnv, CarrierInfo, ExitLine)
- Clean P2/P3 separation via StepKind
- Pure additive changes (no P2 behavioral changes)
- Ready for Phase 47-A-LOWERING (full P3 Normalized implementation)

Tests: 938/938 PASS (+1 from step_schedule unit test)
- All existing P1/P2 tests pass (no regressions)
- P3 test uses Structured path temporarily (proper lowering in next phase)

Next phase: Implement full P3 Normalized→MIR(direct) lowering
2025-12-12 05:23:18 +09:00
42ecd7a7e7 feat(joinir): Phase 47-A prep - P3 fixture and test stub
Preparation for Phase 47-A (P3 Normalized minimal implementation).
Added fixture and test stub for pattern3_if_sum_minimal.

Changes:
- fixtures.rs: Added pattern3_if_sum_minimal fixture
  - Source: phase212_if_sum_min.hako
  - Pattern: Single carrier (sum), simple condition (i > 0)
  - Dev-only fixture for P3 Normalized development

- normalized_joinir_min.rs: Added test stub
  - test_normalized_pattern3_if_sum_minimal_runner
  - Currently returns early (implementation pending)
  - Feature-gated: #[cfg(feature = "normalized_dev")]

- Documentation updates:
  - CURRENT_TASK.md: Phase 47-A status
  - PHASE_43_245B_NORMALIZED_COMPLETION.md: P3 forward reference
  - joinir-architecture-overview.md: Minor formatting
  - phase47-norm-p3-design.md: Implementation notes

Next steps (Phase 47-A implementation):
1. Rename pattern2_step_schedule.rs → step_schedule.rs
2. Add P3 StepKind (IfCond, ThenUpdates, ElseUpdates)
3. Implement Normalized→MIR(direct) for P3
4. Complete test implementation

Tests: 937/937 PASS (no behavioral changes yet)
2025-12-12 05:07:01 +09:00
23ebb86e6e docs(joinir): Phase 47 - Normalized P3 (If-Sum) design
Complete design for extending Normalized JoinIR to Pattern3 (if-sum) loops,
reusing 90% of existing P2 infrastructure.

Key insight: P3 already uses P2's Structured JoinIR foundation (Phase 220
ConditionEnv integration), so Normalized extension is straightforward.

Design documents:
- phase47-norm-p3-design.md: Complete P3 Normalized design
  - Infrastructure reuse analysis (ConditionEnv, CarrierInfo, ExitLine)
  - Representative loops identified (phase212_if_sum_min primary target)
  - StepScheduleBox extension (IfCond, ThenUpdates, ElseUpdates)
  - JpInst reuse (If instruction already exists)
  - Implementation strategy (dev-only → canonical)
  - File impact estimate (~365 lines, pure additive)

- phase47-test-files-inventory.md: P3 test file catalog
  - 3 P3 test files analyzed
  - phase212_if_sum_min.hako: Single carrier (PRIMARY)
  - phase217_if_sum_multi_min.hako: Multi-carrier (sum + count)
  - phase218_json_if_sum_min.hako: Variable accumulation (sum + i)

Architecture:
- Unified Normalized for P1/P2/P3 (same pipeline)
- Conditional updates only difference vs P2
- No P2 code changes needed (pure additive)

Benefits:
- 90% infrastructure reuse from P2
- Proven incremental rollout (dev → canonical)
- Clear path to P4 (continue pattern)

Implementation roadmap:
- Phase 47-A: Minimal sum_count (dev-only)
- Phase 47-B: array_filter (body-local + method calls)
- Phase 47-C: Canonical promotion

Updates:
- joinir-architecture-overview.md: Added Phase 47 section
- CURRENT_TASK.md: Updated Phase 47 entry (Design Complete)

Status: Design phase complete, ready for implementation
2025-12-12 04:50:26 +09:00
d4b9ae3ba5 feat(joinir): Phase 46 - P2-Mid canonical Normalized promotion
Promote P2-Mid patterns (_atoi real, _parse_number real) to canonical
Normalized→MIR(direct) route, completing P2 line transition.

Canonical set expansion (Phase 41 → Phase 46):
- P2-Core: Pattern2Mini, skip_ws mini/real, atoi mini
- P2-Mid: atoi real, parse_number real (NEW)

All JsonParser P2 loops (_skip_whitespace, _atoi, _parse_number) now
canonical Normalized - Structured→MIR is legacy/comparison-only.

Key changes:
- shape_guard.rs: Expanded is_canonical_shape() (+2 patterns)
  - JsonparserAtoiReal
  - JsonparserParseNumberReal
  - Made NormalizedDevShape enum public
- bridge.rs: Updated canonical routing comments (Phase 41 → 46)
- normalized.rs: Made shape_guard module public
- normalized_joinir_min.rs: Added Phase 46 canonical verification test
- phase46-norm-canon-p2-mid.md: Complete design documentation

Out of scope (deferred):
- P3/P4 Normalized support → NORM-P3/NORM-P4 phases
- Selfhost complex loops → separate phases

Benefits:
- Clear P2 boundary: All JsonParser P2 = Normalized canonical
- Infrastructure validation: Phase 43/245B proven production-ready
- Simplified mental model: P2 = Normalized-first, P3/P4 = future

Tests: 937/937 PASS (lib), 20/20 PASS (normalized_dev feature)
Phase 46 test: test_phase46_canonical_set_includes_p2_mid 
2025-12-12 04:40:46 +09:00
297258f963 docs(joinir): Phase 43/245B Normalized JoinIR completion summary
Complete documentation consolidation for Phases 26-45 Normalized JoinIR
infrastructure. All components are implemented and tested (937/937 PASS).

Key additions:
- PHASE_43_245B_NORMALIZED_COMPLETION.md: Master completion summary
  - Architecture components (Mode, Capability, Carriers, DigitPos, etc.)
  - Supported loop patterns (P1, P2 variants including JsonParser)
  - Complete file reference guide
  - Test coverage documentation
  - Future expansion roadmap

Updates:
- CURRENT_TASK.md: Moved Phase 43/245B to completed section
- joinir-architecture-overview.md: Phases 43-45 marked complete
- Historical docs: Added completion banners with links
  - phase223-loopbodylocal-condition-design.md
  - phase223-loopbodylocal-condition-inventory.md
  - PHASE_223_SUMMARY.md
  - phase245b-num_str-carrier-design.md
  - phase245c-function-param-capture-summary.md

Documentation hierarchy established:
- Master summary → individual design docs
- Historical docs → completion summary
- Cross-references complete across all docs

Status: Phase 43/245B Normalized infrastructure COMPLETE 
2025-12-12 04:19:06 +09:00
c82ae2365f refactor(joinir): Phase 44 - Capability-based shape guard
Refactor shape detection from function-name-based to capability-based
architecture for better extensibility and maintainability.

Key changes:
- ShapeCapabilityKind enum: P2CoreSimple/SkipWs/Atoi/ParseNumber
- ShapeCapability: Capability descriptor with future extensibility
- Helper functions:
  - capability_for_shape(): Map shape to capability
  - is_canonical_shape(): Exact shape-level check
  - is_p2_core_capability(): Broad capability family check
  - is_supported_by_normalized(): Normalized dev support

Benefits:
- Extensibility: Easy to add new capability kinds
- Clarity: Shape purpose explicit in kind names
- Maintainability: Centralized mapping vs scattered ifs
- Future-ready: Infrastructure for carrier roles, method signatures

Backward compatibility:
- Zero behavioral changes (pure refactoring)
- Canonical set preserved: Pattern2Mini, skip_ws mini/real, atoi mini
- All existing code paths unchanged

Tests: 937/937 PASS
Files: +78 lines (shape_guard.rs), design doc created
2025-12-12 04:06:03 +09:00
879d3ee08e feat(joinir): Phase 45 - JoinIR mode unification
Unified JoinIR routing logic through centralized JoinIrMode enum:

Key changes:
- Added JoinIrMode enum (StructuredOnly / NormalizedDev / NormalizedCanonical)
- Added current_joinir_mode() for centralized mode determination
- Refactored normalized_dev_enabled() as thin wrapper over mode enum
- Updated bridge.rs: mode-based routing with canonical P2-Core special handling
- Updated runner.rs: mode pattern matching for dev roundtrip path

Files modified:
- joinir_dev.rs: JoinIrMode enum + current_joinir_mode() (+49 lines)
- bridge.rs: Replaced boolean checks with mode pattern matching (+29 lines)
- runner.rs: Mode-based routing logic (+9 lines)
- CURRENT_TASK.md: Phase 45 implementation summary

Documentation:
- phase45-norm-mode-design.md: Complete design spec and implementation guide

Behavior preservation:
- Canonical P2-Core shapes: always Normalized→MIR(direct) (mode-independent)
- NormalizedDev mode: Structured→Normalized→MIR for supported shapes
- StructuredOnly mode: Structured→MIR direct (default)

Tests: 937/937 PASS (no regression, pure refactor)

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-12 03:31:58 +09:00