Commit Graph

2508 Commits

Author SHA1 Message Date
df4d0b1776 docs(phase287): Mark P6 complete, add P7 instructions 2025-12-27 13:26:33 +09:00
f225e27007 refactor(joinir): Phase 287 P6 - Remove scan stage (2-stage pipeline) 2025-12-27 13:25:15 +09:00
8d4472ddd3 docs(phase287): Mark P5 complete, add P6 instructions 2025-12-27 13:20:16 +09:00
ce2b4b97e5 refactor(joinir): Tighten plan stage helper visibility 2025-12-27 13:18:54 +09:00
8774bf2fde refactor(joinir): Phase 287 P5 - Stages facade re-export 2025-12-27 13:14:45 +09:00
ad5b6085c1 docs(phase287): Mark P4 complete, add P5 instructions 2025-12-27 12:50:17 +09:00
3c52ba954e refactor(joinir): Phase 287 P4 - Modularize plan stage (facade) 2025-12-27 12:48:33 +09:00
2f7061e2e5 docs(phase287): Mark P3 complete, add P4 instructions 2025-12-27 12:17:47 +09:00
3224d83a7b refactor(joinir): Phase 287 P3 - Split instruction_rewriter into stages 2025-12-27 12:17:34 +09:00
fe895e8838 refactor(joinir): Phase 287 P2 - Modularize contract_checks (facade pattern)
- contract_checks.rs (846行) を facade 化
- 6モジュールへ分割(1 module = 1 contract):
  - terminator_targets.rs (208行) - Branch/Jump検証
  - exit_bindings.rs (35行) - exit_bindings ↔ exit_phis
  - carrier_inputs.rs (145行) - carrier_inputs完全性
  - boundary_creation.rs (160行) - B1/C2不変条件
  - entry_params.rs (317行) - Entry param一貫性
  - mod.rs (30行) - Facade
- Total: 846 → 895行(+49行モジュール境界オーバーヘッド)
- 意味論不変: エラータグ/ヒント文すべて保存
- Fail-Fast遵守: silent fallback追加なし
- 検証: Build 0 errors / Pattern6 RC=9 / quick 154/154 PASS

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-27 11:05:40 +09:00
de1cd1fea0 refactor(joinir): Phase 287 P1 - Modularize ast_feature_extractor (facade pattern)
Extracted pattern recognizers from ast_feature_extractor.rs (1,148 lines) into
specialized modules under pattern_recognizers/ directory.

**Structure**:
- ast_feature_extractor.rs: Facade (135 lines, re-exports)
- pattern_recognizers/: 8 modules (1,126 lines total)
  - continue_break.rs: continue/break/return detection
  - infinite_loop.rs: loop(true) detection
  - if_else_phi.rs: if-else PHI pattern detection
  - carrier_count.rs: carrier variable counting
  - parse_number.rs: parse_number pattern (+ read_digits)
  - parse_string.rs: parse_string pattern (+ continue pattern)
  - skip_whitespace.rs: skip_whitespace pattern

**Contract**:
- Semantic invariance: All existing APIs preserved via re-exports
- No routing changes, no detection spec changes
- Public API unchanged (facade pattern)

**Verification**:
- Build: 0 errors, 0 warnings
- Pattern6: RC:9 (maintained)
- Smoke tests: 154/154 PASS

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-27 10:42:17 +09:00
e51777b448 refactor(joinir): Phase 287 P0.6 - Final mod.rs cleanup
Add comprehensive modularization summary comment documenting the
complete Phase 287 P0 refactoring journey.

Changes:
- MOD: merge/mod.rs: Add modularization summary (19 lines)
- Final size: 1,053 lines (was 1,555 in Phase 286)
- Total reduction: -502 lines (-32%)

Modularization Summary:
- P0.1: debug_assertions.rs (verification functions)
- P0.2: value_remapper.rs (ValueId remapping helper)
- P0.3: entry_selector.rs (SSOT entry function selection)
- P0.4: header_phi_prebuild.rs (PHI pre-build orchestration)
- P0.5: boundary_logging.rs (consolidated logging)

Remaining in mod.rs (orchestrator only):
- Public API: merge_joinir_mir_blocks()
- Phase 1-6 pipeline coordination
- Phase 3.5: Parameter → PHI dst remapping (complex, kept inline)
- Phase 6: Boundary reconnection and expr_result resolution

SSOT Principles Enforced:
 Entry selection: boundary.loop_header_func_name > continuation_func_ids
 No string-based heuristics ("k_exit" prefix matching eliminated)
 Logging: debug/verbose only (no constant logs in quick profile)
 Reserved ValueIds: PHI dsts protected from conflicts

Verification:
- Build: 0 errors
- Pattern6: RC:9 
- Smoke: 154/154 PASS (verified via quick profile)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-27 10:27:44 +09:00
91daec104f refactor(joinir): Phase 287 P0.5 - Extract boundary_logging
Extract boundary logging functions to boundary_logging.rs (112 lines).
Consolidates scattered trace.stderr_if() calls into focused functions.

SSOT Principle:
- Only use trace.stderr_if(..., debug/verbose) - NO constant logs
- Prevents noise in quick smoke tests
- Consistent logging format across boundary operations

Changes:
- NEW: merge/boundary_logging.rs (112 lines)
- MOD: merge/mod.rs: 1,027 → ~973 lines (-54 lines)
- Functions:
  - log_boundary_info() - Comprehensive boundary logging (verbose mode)
  - log_merge_complete() - Merge completion summary (debug mode)

Logging Consolidated:
- Boundary join_inputs / host_inputs
- Exit bindings (carrier mappings)
- Condition bindings (if any)
- Carrier info (if present)
- Merge completion summary

Verification:
- Build: 0 errors
- Pattern6: RC:9 
- Smoke: 154/154 PASS (verified via quick profile)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-27 10:25:21 +09:00
5ee3b62042 refactor(joinir): Phase 287 P0.4 - Extract header_phi_prebuild
Extract header PHI pre-build orchestration to header_phi_prebuild.rs
(~220 lines). This is orchestration logic that coordinates entry
selection, block remapping, carrier extraction, and PHI building.

Changes:
- NEW: merge/header_phi_prebuild.rs (220 lines)
- MOD: merge/mod.rs: 1,233 → ~1,027 lines (-206 lines)
- Function: prebuild_header_phis() - orchestrates PHI pre-build
- Helper: get_default_entry_block() - fallback for no boundary

Orchestration Responsibilities:
- Entry function selection (via entry_selector SSOT)
- Block remapping (loop_header vs merge_entry)
- Carrier extraction from boundary (with exit_bindings filtering)
- LoopHeaderPhiBuilder invocation
- Reserved ValueId collection (PHI dsts + function params)

Verification:
- Build: 0 errors
- Pattern6: RC:9 
- Smoke: 154/154 PASS (verified via quick profile)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-27 10:21:28 +09:00
fb2ac627da refactor(joinir): Phase 287 P0.3 - Extract entry_selector (SSOT)
Extract entry function selection logic to entry_selector.rs (93 lines).
This enforces SSOT principles for loop header and merge entry selection.

SSOT Strategy:
1. Prefer boundary.loop_header_func_name (explicit specification)
2. Fallback: Exclude MAIN and continuation_func_ids (SSOT, not string matching)
3. Never use "k_exit" prefix heuristics

Changes:
- NEW: merge/entry_selector.rs (43 lines net after extraction)
- MOD: merge/mod.rs: 1,269 → ~1,233 lines (-36 lines)
- Functions:
  - select_loop_step_func_name() (loop header SSOT)
  - select_merge_entry_func() (Pattern 3 if-sum support)
  - get_function() (helper with error handling)

Verification:
- Build: 0 errors
- Pattern6: RC:9 
- Smoke: 154/154 PASS (verified via quick profile)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-27 10:17:49 +09:00
95fef8696d refactor(joinir): Phase 287 P0.2 - Extract value_remapper
Extract remap_values() to value_remapper.rs (46 lines). This is a pure
helper function that allocates new ValueIds while avoiding conflicts
with reserved PHI dst ValueIds.

Changes:
- NEW: merge/value_remapper.rs (Phase 3 helper)
- MOD: merge/mod.rs: 1,315 → ~1,269 lines (-46 lines)
- Delegation: value_remapper::remap_values() called from orchestrator

Verification:
- Build: 0 errors
- Pattern6: RC:9 
- Smoke: 154/154 PASS (verified via quick profile)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-27 10:14:27 +09:00
433e1d45c0 refactor(joinir): Phase 287 P0.1 - Move verification to debug_assertions
- Move verify_no_phi_dst_overwrite() to debug_assertions.rs
- Move verify_phi_inputs_defined() to debug_assertions.rs
- Move verify_joinir_contracts() to debug_assertions.rs
- Remove duplicate get_instruction_dst() from mod.rs
- mod.rs: 1,555 → ~1,380 lines (-176 lines)
- Semantic invariance: 154/154 smoke tests PASS, Pattern6 RC:9

Phase 287 P0: Big Files Refactoring (意味論不変)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-27 10:10:59 +09:00
a04b48416e fix(joinir): Phase 287 P2 - Pattern6 nested loop latch overwrite fix
Fix infinite loop in Pattern6 (nested loop minimal) caused by main→loop_step
overwriting k_inner_exit→loop_step latch values.

Root cause: JoinIR main entry block was incorrectly treated as BackEdge,
causing it to overwrite the correct latch incoming values set by the true
back edge (k_inner_exit → loop_step).

Solution:
- Restrict latch recording to TailCallKind::BackEdge only
- Treat only MAIN's entry block as entry-like (not loop_step's entry block)
- Add debug_assert! to detect double latch set in future

Refactoring:
- Extract latch recording to latch_incoming_recorder module (SSOT)
- Add boundary.loop_header_func_name for explicit header identification
- Strengthen tail_call_classifier with is_source_entry_like parameter

Tests: apps/tests/phase1883_nested_minimal.hako → RC:9 (was infinite loop)
Smoke: 154/154 PASS, no regressions

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-27 09:39:29 +09:00
bbfc3c1d94 refactor(joinir): Phase 287 P2 - Strengthen BackEdge/latch conditions (WIP)
**Problem**: Phase 188.3 Pattern6 (nested loop) encounters infinite loop
- inner_step → inner_step (self-recursion) incorrectly classified as BackEdge
- → redirects to outer header (loop_step) instead of inner_step entry
- is_recursive_call causes inner recursion to overwrite outer latch values
- → PHI receives wrong values → i doesn't increment → infinite loop

**Fix 1: BackEdge classification strictness** (tail_call_classifier.rs)
- Add `is_target_loop_entry` parameter to classify_tail_call()
- BackEdge ONLY when target==loop_step (entry_func), not inner_step
- Prevents inner_step → inner_step from redirecting to outer header

**Fix 2: latch_incoming guard** (instruction_rewriter.rs)
- Change condition from `is_recursive_call || is_target_loop_entry`
  to `is_target_loop_entry` only
- Prevents inner_step self-recursion from overwriting outer loop's latch
- set_latch_incoming() now called with correct values (verified by debug)

**Status**: 🚧 WIP - Infinite loop still occurs
- set_latch_incoming('i', BasicBlockId(8), ValueId(21))  Called correctly
- But final PHI: `phi [%4, bb8]` instead of `phi [%21, bb8]` 
- Root cause likely in PHI generation (merge/mod.rs), not latch_incoming
- Next: Investigate why latch_incoming values aren't used in PHI

**Files**:
- src/mir/builder/control_flow/joinir/merge/tail_call_classifier.rs
- src/mir/builder/control_flow/joinir/merge/instruction_rewriter.rs

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-27 08:32:14 +09:00
d0527bcc2a feat(joinir): Phase 188.3-P3.3 - Pattern6 continuation generation + Call callee fix
Phase 3-3 完了: 4関数モデル JoinIR 生成
- nested_loop_minimal.rs (337行, 新規): 4関数モデル実装
  - main(): エントリーポイント
  - loop_step(i, sum): outer loop header
  - inner_step(j, i_outer, sum): inner loop (tail recursion)
  - k_inner_exit(i, sum): outer continuation after inner loop
  - k_exit(sum): 最終 exit
- pattern6_nested_minimal.rs: lowering pipeline 実装
  - boundary 構築 (continuation_func_ids 設定)
  - JoinIRConversionPipeline 呼び出し
- instruction_rewriter.rs: latch incoming 拡張
  - continuation→header 呼び出し対応

Call callee 修正:
- call_generator.rs: callee フィールドを Callee::Global に設定
- joinir_block_converter.rs: emit_call_pair 使用に統一

smoke test 追加:
- phase1883_nested_minimal_vm.sh (integration)

既知の問題 (次タスク):
- ValueId(104) undefined: PHI/merge 問題
- JoinIR 関数パラメータの MIR マッピングが不完全

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-27 06:51:43 +09:00
c6ffc06660 feat(joinir): Phase 188.3-P3.1,3.2 - AST extraction & validation helpers
Phase 3-1 完了: extract_inner_loop_ast() 実装
- 外側 loop body から内側 loop を抽出
- 正確に 1 つの inner loop を検証
- 0 個 or 2+ 個の場合は明示エラー (Fail-Fast)

Phase 3-2 完了: validate_strict_mode() プレースホルダー
- 現在は大半の検証を is_pattern6_lowerable() で実施
- 将来の strict mode チェック用の足場

ドキュメント追加:
- P1-INSTRUCTIONS.md: Phase 3-3 実装指示書 (4関数モデル詳細)
- README.md: max_loop_depth 定義の明確化
- 10-Now.md: Phase 188.3 方針の整合性維持

次タスク: Phase 3-3 (Continuation 生成) - P1-INSTRUCTIONS.md 参照

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-27 06:22:59 +09:00
a2c5fd90fe feat(joinir): Phase 188.3 - Pattern6 (NestedLoopMinimal) 選択ロジック実装
## Phase 188.3 進捗: Phase 2 完了 (6/13 tasks)

### 実装完了 

**Phase 1: Fixture作成**
- apps/tests/phase1883_nested_minimal.hako 追加
  - Add/Compare のみ(乗算なし)
  - 期待 exit code: 9 (3×3 nested loops)
- 既存 lowering で fallback 動作確認

**Phase 2: 選択ロジック (SSOT)**
- LoopPatternContext に step_tree_max_loop_depth フィールド追加
- choose_pattern_kind() に Pattern6 選択ロジック実装:
  1. Cheap check (has_inner_loop)
  2. StepTree 構築 (max_loop_depth 取得)
  3. AST validation (is_pattern6_lowerable)
- pattern6_nested_minimal.rs モジュール作成 (stub)
- LOOP_PATTERNS に Pattern6 entry 追加
- **検証**: Pattern6 が正しく選択される 

### 設計原則 (確認済み)

1. **Fail-Fast**: Pattern6 選択後は Ok(None) で逃げない
2. **outer 変数 write-back 検出 → validation false** (Phase 188.4+)
3. **最小実装**: inner local だけ、Pattern1 モデル二重化
4. **cfg! 依存なし**: production で動作

### 検証結果

```
[choose_pattern_kind] has_inner_loop=true
[choose_pattern_kind] max_loop_depth=2
[choose_pattern_kind] is_pattern6_lowerable=true
 Pattern6 SELECTED!
```

Stub からの期待エラー:
```
[ERROR]  [Pattern6] Nested loop lowering not yet implemented
```

### 次: Phase 3 (Lowering 実装 - 推定4時間)

残りタスク:
- Phase 3-1: AST 抽出ヘルパー
- Phase 3-2: Validation ヘルパー
- Phase 3-3: Continuation 生成 (outer_step, inner_step, k_inner_exit)
- Phase 3-4: fixture が exit=9 を返すことを検証

### 変更ファイル

**新規**:
- apps/tests/phase1883_nested_minimal.hako
- src/mir/builder/control_flow/joinir/patterns/pattern6_nested_minimal.rs
- docs/development/current/main/phases/phase-188.{1,2,3}/README.md

**変更**:
- src/mir/builder/control_flow/joinir/routing.rs (Pattern6 選択)
- src/mir/builder/control_flow/joinir/patterns/router.rs (Context 拡張)
- src/mir/builder/control_flow/joinir/patterns/mod.rs (module 宣言)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-27 05:45:12 +09:00
229553f7a4 refactor(nyrt): consolidate ny_release_strong into lifecycle module
Phase 29y.1 cleanup: Eliminate duplicate ny_release_strong implementation.

Changes:
- Remove duplicate ny_release_strong from lib.rs (11 lines)
- Consolidate into ffi/lifecycle.rs (rename shim → legacy name)
- Maintain backward compatibility with existing LLVM lowering

Verification:
- quick: 154/154 PASS
- integration phase29y: 2/2 PASS

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-27 02:15:13 +09:00
26a739189d docs(phase-29y): note pilot plumbing completion in Now/Backlog 2025-12-27 02:07:54 +09:00
2e99b14e24 phase-29y.1: add lifecycle pilot plumbing (ABI shim, rc pass skeleton, root summary) 2025-12-27 02:07:10 +09:00
8a5218a9ad docs(phase-29y): add ABI/RC-insertion/observability SSOT stubs 2025-12-27 01:11:36 +09:00
47493b95ce docs(mir): document KeepAlive/ReleaseStrong lifecycle directives 2025-12-27 01:07:46 +09:00
348b19f42d docs(phase-29y): self-contained consult packet + entry 2025-12-27 01:03:24 +09:00
ba1fc21375 docs(phase-29y): tighten lifecycle vocab consult packet 2025-12-27 00:38:21 +09:00
64bc2746df docs(phase-285): add ret.py boxification appendix 2025-12-27 00:36:32 +09:00
bd0783fa85 docs(phase-285): Complete P4 Post-Completion documentation
Phase 285 P4 Post-Completion activities (2025-12-27):

1. Phase 284 P2 Integration Fix (commit 225600b5f)
   - Fixed phase284_p2_return_in_loop_llvm (unreachable instruction)
   - Integration LLVM tests: 3/3 PASS (no FAIL remaining)

2. ret.py Box-First Refactoring (commits 32aa0ddf6, 5a88c4eb2)
   - Phase 1-2: UnreachableReturnHandlerBox + ReturnTypeAdjusterBox
   - Phase 3: StringBoxerBox + ReturnPhiSynthesizerBox
   - Reduced lower_return(): 166→117 lines (-29%)

3. Code Quality Improvements (4 commits)
   - LLVM exit code SSOT (d7c6df367)
   - nyash_kernel FFI split (798c193cb)
   - LLVM detection consolidation (1869396fd)
   - auto_detect.conf clarity (095213c58)

Final status:
- Integration LLVM tests: 3/3 PASS
- Quick profile: 154/154 PASS
- Current Focus: Phase 29y (post self-host, docs-first)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-27 00:31:29 +09:00
095213c580 refactor(smoke): Clarify auto_detect.conf responsibilities with profile parameter
**Problem**:
- detect_optimal_config() took no arguments (line 11)
- Quick profile SSOT forcing scattered outside function (line 134-137)
- Profile-specific logic split between detect_optimal_config() and auto_configure()
- Hard to understand flow: "why is this logic duplicated?"

**Solution** (Task 4 - Low Priority):
- Accept profile parameter: `detect_optimal_config(profile)`
- Move quick profile SSOT forcing inside function (top priority)
- Eliminate duplicate logic in auto_configure()
- Update show_auto_config() to pass profile parameter

**Changes**:
- detect_optimal_config(): Add `local profile="${1:-quick}"`
- Quick SSOT check: Move to function top (early return)
- auto_configure(): Pass `"$profile"` to detect_optimal_config
- show_auto_config(): Pass `"${SMOKES_CURRENT_PROFILE:-quick}"`
- Remove 6 lines of duplicate quick forcing logic

**Benefits**:
- Single responsibility: Profile logic inside detect_optimal_config
- Clearer flow: All detection in one function
- Maintainability: One place to modify profile behavior
- Readability: Intent is explicit (profile parameter)

**Verification**:
-  detect_optimal_config "quick": returns rust_vm_dynamic (SSOT)
-  detect_optimal_config "integration": returns llvm_static
-  Quick profile: 154/154 PASS

**Note**: This is a low-impact refactoring (code organization only)
- Behavior unchanged (same logic, better location)
- No performance impact
- Future-proof for profile-specific detection

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-26 17:32:48 +09:00
1869396fd7 refactor(smoke): Consolidate LLVM detection to can_run_llvm() SSOT
**Problem**:
- LLVM availability check scattered across 9+ test files
- Duplicate grep patterns: `--version | grep -q "features.*llvm"`
- Hard to maintain when detection logic changes
- Potential SKIP hell when conditions diverge

**Solution** (Task 3 - Medium Priority):
- Create `can_run_llvm()` function in test_runner.sh (SSOT)
- Consolidate both detection methods:
  1. Primary: `--version | grep features.*llvm`
  2. Fallback: `strings | grep ny-llvmc|NYASH_LLVM_USE_HARNESS`
- Replace all inline checks with function call

**Files Changed**:
- test_runner.sh: Add can_run_llvm() + update run_nyash_llvm()
- 9 test files: Replace inline grep with can_run_llvm()
  - quick: phase285_weak_basic_llvm.sh
  - integration: phase284/285, json_{lint,pp,query}, parity tests

**Benefits**:
- Single point of maintenance (SSOT)
- Consistent LLVM detection across all tests
- Easy to extend (e.g., add Python llvmlite check)
- Prevents future SKIP divergence

**Verification**:
-  phase284_p2_return_in_loop_llvm: PASS
-  phase285_weak_basic_llvm: PASS
-  Quick profile: 154/154 PASS

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-26 17:31:19 +09:00
798c193cbe refactor(kernel): Extract weak reference FFI to ffi/weak.rs module
**Problem**:
- nyash_kernel/src/lib.rs is 1295 lines (monolithic FFI functions)
- Hard to navigate and maintain
- No clear module boundaries

**Solution** (Task 2 - Medium Priority):
- Create `ffi/` module structure
- Extract weak reference functions to `ffi/weak.rs` (74 lines)
  - nyrt_weak_new
  - nyrt_weak_to_strong
  - nyrt_weak_drop
- lib.rs: 1295 → 1221 lines (-74 lines, -5.7%)
- Re-export via `pub use ffi::weak::*` for ABI compatibility

**Architecture**:
- Box-First: Clear module boundaries (SSOT for weak refs)
- Reversible: Can merge back if needed (small, safe step)
- ABI stable: #[no_mangle] exports preserved

**Verification**:
-  Build successful (cargo build -p nyash_kernel)
-  phase285_p2_weak_upgrade_success_llvm: PASS
-  phase285_p2_weak_upgrade_fail_llvm: PASS
-  Quick profile: 154/154 PASS

**Next steps** (deferred to future):
- Extract string FFI (~11 functions)
- Extract memory management FFI
- Extract box operations FFI

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-26 17:29:15 +09:00
d7c6df3675 refactor(smoke): Phase 284 P2 - LLVM harness exit code SSOT
**Problem**:
- phase284_p2_return_in_loop_llvm.sh used fallback: exit code OR output grep
- Inconsistent with exit code SSOT policy for LLVM harness tests
- Output pollution from harness logs makes grep unreliable

**Solution** (Task 1 - High Priority):
- Remove `|| echo "$OUTPUT" | grep -qE "(^7$|RC: 7$)"` fallback
- Pure exit code validation: `if [ "$EXIT_CODE" -eq 7 ]`
- OUTPUT kept for error debugging only (line 40)
- Align with phase285_p2 tests (already using exit code SSOT)

**Verification**:
-  phase284_p2_return_in_loop_llvm: PASS (exit 7)
-  phase285_p2_weak_upgrade_success_llvm: PASS (exit 2)
-  phase285_p2_weak_upgrade_fail_llvm: PASS (exit 1)
-  Quick profile: 154/154 PASS

**Impact**:
- 1 file changed, 5 lines modified
- More reliable LLVM test validation
- No regression in existing tests

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-26 17:25:25 +09:00
5a88c4eb23 refactor(llvm-py): Phase 3 boxification - Strategic extraction
Extract complex logic while keeping simple parts inline:

1. StringBoxerBox (15 lines)
   - Box string pointers (i8*) to handles (i64)
   - Eliminate function declaration boilerplate
   - Clear single responsibility

2. ReturnPhiSynthesizerBox (101 lines)
   - Synthesize PHI nodes for return values
   - should_synthesize_phi(): Zero-like detection
   - synthesize_phi(): PHI creation with predecessors
   - Respects _disable_phi_synthesis flag

What was NOT boxified (good decisions):
- Fast path vmap lookup (13 lines): Too simple
- Global vmap fallback (7 lines): Too small
- Default value generation (18 lines): Clear as-is

Impact:
- lower_return(): 166→117 lines (-29% reduction)
- File size: 250→352 lines (+102 for organization)
- Testable units: 2→4 (+2 new Boxes)

Tests:
- phase286_pattern5_return_min.hako: PASS (exit 7)
- phase284_p1_return_in_loop_llvm.sh: PASS
- phase284_p2_return_in_loop_llvm.sh: PASS

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 17:12:34 +09:00
32aa0ddf69 refactor(llvm-py): Box-First refactoring of ret.py (Phase 1-2)
Extract two responsibility Boxes following Box-First principle:

1. UnreachableReturnHandlerBox (Phase 1)
   - Handle unreachable block returns with Fail-Fast principle
   - Implements Phase 284-P2 unreachable semantics
   - Moved os/sys imports to file header

2. ReturnTypeAdjusterBox (Phase 2)
   - Handle ptr↔int conversion and int width adjustment
   - Isolate type coercion logic for LLVM compatibility
   - Support truncate/extend for integer width mismatches

Changes:
- File size: 205→249 lines (+21% for better organization)
- Reduced lower_return() complexity
- Preserved all Phase 284-P2 comments and semantics
- No breaking changes

Tests:
- phase286_pattern5_return_min.hako: PASS (exit 7)
- phase284_p2_return_in_loop_llvm.sh: PASS
- Quick profile: 154/154 PASS

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 17:04:42 +09:00
225600b5f9 fix(llvm): Phase 284 P2 - Use unreachable for null returns (Fail-Fast)
MIR generates unreachable blocks with null return values (e.g., after loop(true)).
LLVM type-checks ALL blocks, so we must match function signatures.

Solution: Use builder.unreachable() instead of ret void for non-void functions.
- Type-safe: Satisfies LLVM type checker without return value
- Fail-Fast: Immediate crash if "unreachable" block is executed
- No silent failures

Test results:
 phase284_p2_return_in_loop_llvm: PASS (integration)
 phase285_p2_weak_upgrade_success_llvm: PASS (already passing)
 quick 154/154: PASS (no regression)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-26 16:58:06 +09:00
606e236d6d fix(phase-285): restore weak_basic_llvm + complete LLVM detection/quick SSOT 2025-12-26 16:32:37 +09:00
ce2baa0d47 feat(llvm): Phase 285 P3 - KeepAlive/ReleaseStrong LLVM implementation
Phase 285 P3: LLVM One-Pass (VM/LLVM一気通貫の最小ゲート)

## 実装内容

### 1. LLVM Backend (Python)
- src/llvm_py/instructions/lifecycle.py: NEW
  - lower_keepalive(): no-op (DCE/liveness only)
  - lower_release_strong(): ny_release_strong() 呼び出し
- src/llvm_py/builders/instruction_lower.py:
  - KeepAlive/ReleaseStrong ディスパッチエントリ追加

### 2. Runtime (Rust)
- crates/nyash_kernel/src/lib.rs:
  - ny_release_strong(handle: i64): handles::drop() 呼び出し
  - Phase 287対応(変数上書きセマンティクス)

### 3. MIR JSON Serialization
- src/runner/mir_json_emit.rs:
  - KeepAlive/ReleaseStrong JSON emit 追加(両関数)
  - {"op":"keepalive","values":[...]}
  - {"op":"release_strong","values":[...]}

## テスト結果

 **phase285_p2_weak_upgrade_fail_llvm**: PASS (exit 1, weak_to_strong null)
⏸️ **phase285_p2_weak_upgrade_success_llvm**: SKIP (--version に features 表示なし)
⏸️ **phase284_p2_return_in_loop_llvm**: SKIP (同上)

## SKIP理由(--version feature表示問題)

テストスクリプトが `--version | grep "features.*llvm"` で環境チェックするが、
現在の --version は "nyash 1.0" のみ出力。LLVM feature有効でも SKIP される。

**対応方針**: Phase 285 P3 目的(KeepAlive/ReleaseStrong LLVM実装)達成。
--version feature表示は Phase 286以降で対応予定。

## 検証

- cargo build --release --features llvm: OK
- weak_upgrade_fail_llvm: PASS (VM/LLVM parity確認)
- quick gate: 154/154 PASS (退行なし)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-26 14:34:05 +09:00
72552cddfb docs(phase-285): add P3 LLVM one-pass instructions 2025-12-26 14:21:12 +09:00
fbd9c83b62 docs: reflect Phase 285 P2.2 completion (KeepAlive/ReleaseStrong) 2025-12-26 14:17:19 +09:00
3bb865c6b0 refactor(mir): Separate KeepAlive/ReleaseStrong instructions (Phase 287)
Phase 287: KeepAlive/ReleaseStrong 命令分離

## 変更内容(2つの側面)

### 1. 命令セマンティクスの分離
- KeepAlive { values, drop_after: bool } を2命令に分離
  - KeepAlive { values }: スコープ終了での生存維持(PURE)
  - ReleaseStrong { values }: 変数上書き時の強参照解放(WRITE)
- 効果分析の明確化: PURE vs WRITE の境界確定

### 2. VM実行サポート
- handlers/mod.rs: KeepAlive → 完全 no-op
- handlers/mod.rs: ReleaseStrong → release_strong_refs() 呼び出し
- handlers/lifecycle.rs: handle_keepalive() 削除

## 影響範囲
- 10 ファイル修正(31箇所の出現を全変換)
- instruction.rs, builder.rs, lexical_scope.rs, methods.rs,
  display.rs, printer_helpers.rs, query.rs, joinir_id_remapper.rs,
  handlers/mod.rs, handlers/lifecycle.rs

## 検証
- 154/154 quick smoke PASS
- weak テスト回帰なし(weak_upgrade_fail, weak_basic)
- rg -n drop_after src → 0 件(完全除去確認)
- MIRダンプで release_strong/keepalive 正常表示

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-26 14:12:58 +09:00
f74ff6116c refactor(lifecycle): Phase 285 P2.1 hygiene - lifecycle.rs 箱化完了
責務分離により KeepAlive 処理を handlers/lifecycle.rs に隔離:
- handlers/lifecycle.rs 新規作成(47行)
  - handle_keepalive() で drop_after 判定
  - release_strong_refs() で Arc 同一性探索を集約
  - HashSet による O(1) 検索最適化
- handlers/mod.rs を dispatch 専用化(49行削除→1行呼び出し)
- README.md に P2.1 完了状態を記載(SKIP→PASS)
- phase-29y 将来設計相談パケット追加(NyRT ABI/RC insertion pass)

Test: 154/154 PASS 

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-26 13:36:17 +09:00
3bf0dee2b0 feat(mir): Phase 285 P2.1 - KeepAlive instruction for weak ref semantics
Add KeepAlive instruction to fix hidden root problem where x = null
doesn't properly drop the strong reference.

Key changes:
- Add KeepAlive { values, drop_after } instruction to MIR
- Emit KeepAlive[drop=true] in build_assignment() before variable overwrite
- Emit KeepAlive[drop=false] in pop_lexical_scope() at scope end
- VM handler: when drop_after=true, remove ALL ValueIds pointing to
  the same Arc (handles SSA Copy chains)

Test results:
- weak_upgrade_fail: exit 1  (weak_to_strong returns null after x=null)
- weak_basic: exit 2  (weak_to_strong succeeds while x alive)
- quick smoke: 154/154 PASS 

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 13:08:32 +09:00
58ceb3de2f feat(smoke): Phase 285 P2 - weak conformance smokes (success pattern)
Phase 285 P2: weak の意味論(weak <expr> + weak_to_strong() 成功/失敗)を integration smoke で固定

実装内容:
- Fixture A(成功パターン): exit 0 → exit 2 に変更(fail=1, success=2 で明確化)
- Fixture B(失敗パターン): 明示 drop (x = null) 方式で作成
- VM smoke success: PASS
- LLVM smoke success: SKIP(backend unavailable)
- VM/LLVM smoke fail: SKIP(hidden root 問題で理由付き)

既知の問題:
- x = null で明示 drop しても weak_to_strong が成功(hidden root が strong ref を保持)
- Phase 285 P2.1 (investigation) で root 保持箇所を棚卸し予定

スコープ:
- Block scope drop conformance は別タスク(未整合の可能性あり)
- P2 では明示 drop 方式で weak の最小意味論(non-owning)のみを検証

検証:
- quick smoke 154/154 PASS 維持
- integration smoke 4本(success 2本 PASS/SKIP、fail 2本 SKIP)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-26 11:33:12 +09:00
b7f14e38d7 docs(lifecycle): Phase 285 P1 - Box lifecycle 実装棚卸し完了
## Rust VM 実装棚卸し(11項目)
- WeakBox 生成/観測/真実値判定: value.rs
- weak_to_strong: upgrade_weak() 失敗時 Void
- Finalizer: finalization.rs (scope レベル、InstanceBox 限定)
- Scope 追跡: scope_tracker.rs (Arc/Weak 管理)
- MIR WeakNew/WeakLoad: handlers/weak.rs

## LLVM harness 状況
- WeakNew/WeakLoad:  実装済み (llvm_py/instructions/weak.py)
- Finalizer:  未実装 (scope 管理なし)
- GC:  未実装 (RC のみ)

## P2 smoke 候補絞り込み(4本)
- weak_basic_vm/llvm: 既存+LLVM版
- weak_to_strong_fail: null 確認(新規)
- weak_cycle_report: leak report(新規)

**重要な発見**:
- WeakRef は両バックエンド完全実装(仕様通り)
- Finalizer は VM scope レベルで実装あり、LLVM 未対応

quick smoke 154/154 PASS

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-26 10:55:33 +09:00
5ec0056059 docs(lifecycle): Phase 285 P0 - Box lifecycle/weakref/GC SSOT 固定
## 言語 SSOT との境界明文化
- lifecycle/weak/fini: lifecycle.md
- null/void/truthiness: types.md
- Phase 285 は実装状況・差分追跡のみ(言語SSOT書き換えなし)

## 用語・禁止事項固定
- Roots/Strong/Weak/Finalizer/GC 定義
- 禁止: finalizer 再入・例外・allocation・silent fallback

## VM/LLVM 差分分類
- (A) 仕様通り: weak/weak_to_strong/leak report
- (B) 未実装: finalizer/GC cycle collection

## P1/P2 導線
- P1: 棚卸し対象ファイル一覧(value.rs, finalization.rs等)
- P2: smoke 候補(weak_basic, weak_to_strong_fail, leak_report)

quick smoke 154/154 PASS

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-26 10:51:17 +09:00
03f9bbe1aa feat(smoke): Phase 284 P2 - return-in-loop VM/LLVM parity smoke
- VM smoke: phase284_p2_return_in_loop_vm.sh (PASS)
- LLVM smoke: phase284_p2_return_in_loop_llvm.sh (SKIP if no LLVM feature)
- Reuse existing fixture: phase286_pattern5_return_min.hako (exit 7)
- P2-INSTRUCTIONS.md: 手順書作成
- quick smoke 154/154 PASS

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 10:45:54 +09:00
7a575e30cc refactor(joinir): Phase 286 P3.2 cleanup + normalizer modularization
## Legacy Pattern5 削除 (488行)
- pattern5_infinite_early_exit.rs 完全削除
- LOOP_PATTERNS テーブルからエントリ削除
- Plan extractor が SSOT

## Normalizer 分割 (3294行 → 12ファイル)
- helpers.rs: 共通ヘルパー関数
- pattern*.rs: 各パターン専用ファイル
- mod.rs: ディスパッチャ

## ドキュメント更新
- Phase 286 README: クリーンアップ完了・Fail-Fast方針記載
- Phase 287 README: 将来計画

quick smoke 154/154 PASS

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 10:30:08 +09:00