22b0c14adb
feat(joinir): Phase 135 P1 - Contract checks Fail-Fast (二度と破れない設計)
...
## Summary
Adds early Fail-Fast contract verification to prevent Phase 135 P0 issues from recurring.
Two new verifiers catch allocator SSOT violations and boundary inconsistencies before --verify.
## Changes
### Step 1: verify_condition_bindings_consistent
**Location**: `src/mir/builder/control_flow/joinir/merge/contract_checks.rs`
**Contract**: condition_bindings can have aliases (multiple names for same join_value),
but same join_value with different host_value is a violation.
**Example Error**:
```
[JoinIRVerifier/Phase135-P1] condition_bindings conflict:
join_value ValueId(104) mapped to both ValueId(12) and ValueId(18)
```
**Catches**: ConditionLoweringBox bypassing SSOT allocator before BoundaryInjector
### Step 2: verify_header_phi_dsts_not_redefined
**Location**: `src/mir/builder/control_flow/joinir/merge/contract_checks.rs`
**Contract**: Loop header PHI dst ValueIds must not be reused as dst in non-PHI instructions.
Violation breaks MIR SSA (PHI dst overwrite).
**Example Error**:
```
[JoinIRVerifier/Phase135-P1] Header PHI dst ValueId(14) redefined by non-PHI instruction in block 3:
Instruction: Call { dst: Some(ValueId(14)), ... }
```
**Catches**: ValueId collisions between header PHI dsts and lowered instructions
### Integration
**Location**: `src/mir/builder/control_flow/joinir/merge/mod.rs`
Added to `verify_joinir_contracts()`:
1. Step 1 runs before merge (validates boundary)
2. Step 2 runs after merge (validates func with PHI dst set)
### Documentation
- Updated `phase135_trim_mir_verify.sh` - Added P1 contract_checks description
- Updated `phase-135/README.md` - Added P1 section with contract details and effects
## Acceptance
✅ Build: SUCCESS
✅ Smoke: phase135_trim_mir_verify.sh - PASS
✅ Regression: phase132_exit_phi_parity.sh - 3/3 PASS
✅ Regression: phase133_json_skip_whitespace_llvm_exe.sh - PASS
## Effect
- **Prevention**: Future Box implementations catch SSOT violations immediately
- **Explicit Errors**: Phase 135-specific messages instead of generic --verify failures
- **Unbreakable**: Debug builds always detect violations, enforced by CI/CD
🤖 Generated with Claude Code
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-15 19:25:33 +09:00
33f03d9775
refactor(joinir): Phase 86 - Carrier init builder, debug migration, error tags
...
P1: Carrier Initialization Builder (HIGH) ✅
- New module: carrier_init_builder.rs (197 lines, 8 tests)
- Refactored loop_header_phi_builder.rs (-34 lines)
- Centralized CarrierInit value generation (SSOT)
- Eliminates scattered match patterns across header PHI, exit line
- Consistent debug output: [carrier_init_builder] format
- Net: -34 lines of duplicated logic
P2: Remaining DebugOutputBox Migration (QUICK) ✅
- Migrated carrier_info.rs::record_promoted_binding()
- Uses DebugOutputBox for JOINIR_DEBUG checks
- Maintains JOINIR_TEST_DEBUG override for test diagnostics
- Consistent log formatting: [context/category] message
- Net: +3 lines (SSOT migration)
P3: Error Message Centralization (LOW) ✅
- New module: error_tags.rs (136 lines, 5 tests)
- Migrated 3 error sites:
* ownership/relay:runtime_unsupported (plan_validator.rs)
* joinir/freeze (control_flow/mod.rs)
* (ExitLine errors were debug messages, not returns)
- Centralized error tag generation (freeze, exit_line_contract, ownership_relay_unsupported, etc.)
- Net: +133 lines (SSOT module + tests)
Total changes:
- New files: carrier_init_builder.rs (197), error_tags.rs (136)
- Modified: 6 files
- Production code: +162 lines (SSOT investment)
- Tests: 987/987 PASS (982→987, +5 new tests)
- Phase 81 ExitLine: 2/2 PASS
- Zero compilation errors/warnings
Benefits:
✅ Single Responsibility: Each helper has one concern
✅ Testability: 13 new unit tests (8 carrier init, 5 error tags)
✅ Consistency: Uniform debug/error formatting
✅ SSOT: Centralized CarrierInit and error tag generation
✅ Discoverability: Easy to find all error types
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-13 21:48:02 +09:00
af6f95cd4b
Phase 33 NORM canon test: enforce normalized dev route for P1/P2/JP mini
2025-12-11 20:54:33 +09:00
eb00d97fdb
feat(joinir): Phase 246-EX Part 2 - Exit PHI & step scheduling fixes
...
Phase 246-EX Part 2 completes the _atoi JoinIR integration:
Key fixes:
- Exit PHI connection: ExitLineReconnector now correctly uses exit PHI dsts
- Jump args preservation: BasicBlock.jump_args field stores JoinIR exit values
- instruction_rewriter: Reads jump_args, remaps JoinIR→HOST values by carrier order
- step_schedule.rs: New module for body-local init step ordering
Files changed:
- reconnector.rs: Exit PHI connection improvements
- instruction_rewriter.rs: Jump args reading & carrier value mapping
- loop_with_break_minimal.rs: Refactored step scheduling
- step_schedule.rs: NEW - Step ordering logic extracted
Tests: 931/931 PASS (no regression)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com >
2025-12-11 17:16:10 +09:00
d4597dacfa
feat(joinir): Phase 245C - Function parameter capture + test fix
...
Extend CapturedEnv to include function parameters used in loop conditions,
enabling ExprLowerer to resolve variables like `s` in `loop(p < s.length())`.
Phase 245C changes:
- function_scope_capture.rs: Add collect_names_in_loop_parts() helper
- function_scope_capture.rs: Extend analyze_captured_vars_v2() with param capture logic
- function_scope_capture.rs: Add 4 new comprehensive tests
Test fix:
- expr_lowerer/ast_support.rs: Accept all MethodCall nodes for syntax support
(validation happens during lowering in MethodCallLowerer)
Problem solved: "Variable not found: s" errors in loop conditions
Test results: 924/924 PASS (+13 from baseline 911)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com >
2025-12-11 13:13:08 +09:00
192620f842
feat(joinir): Phase 228 - CarrierInit for ConditionOnly header PHI initialization
...
- Add CarrierInit enum (FromHost/BoolConst) for explicit initialization policy
- LoopHeaderPhiBuilder generates Const instruction for BoolConst carriers
- merge/mod.rs uses carrier_info to include ALL carriers in header PHI
- Pattern 2/4 pass carrier_info to boundary builder
- ConditionOnly carriers (is_digit_pos) now included in header PHI
Remaining: latch incoming for ConditionOnly carriers (Phase 228-8)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com >
2025-12-10 21:10:28 +09:00
33e80637dd
refactor(joinir): Phase 221-R ExprResultResolver Box extraction
...
Extracted 64 lines of expr_result handling from merge/mod.rs into
dedicated ExprResultResolver Box following Phase 33 modularization.
- New module: expr_result_resolver.rs (185 lines, 4 unit tests)
- merge/mod.rs: -37 lines (net reduction)
- Single responsibility: expr_result resolution only
- Improved testability and maintainability
Phase 221-R completes the box-first refactoring of Phase 221's
expr_result routing implementation, aligning with Phase 33
modularization patterns (ExitMetaCollector, ExitLineReconnector).
Test results:
✅ phase212_if_sum_min.hako: RC=2
✅ loop_if_phi.hako: sum=9 (legacy mode)
✅ loop_min_while.hako: correct output
2025-12-10 04:23:34 +09:00
8f7c6c5637
feat(joinir): Phase 221 ExprResult routing in merge pipeline
...
- Add expr_result handling in merge_joinir_mir_blocks
- When expr_result matches a carrier, return carrier PHI dst
- Enables expr-position loops to properly return accumulator values
Note: Phase 219 regression (loop_if_phi.hako) to be fixed in next commit
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com >
2025-12-10 03:47:23 +09:00
757ba6b877
fix(joinir): Phase 220-C condition variable remap and self-copy skip
...
- Pre-populate remap with condition_bindings (join_value → host_value)
- Skip self-copy param bindings to avoid `%6 = copy %6`
- ConditionEnv remap verified: ValueId(101) → ValueId(6) correctly
Note: RC=0 issue remains - ExprResult routing to be investigated in Phase 221
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com >
2025-12-10 03:20:09 +09:00
d7805e5974
feat(joinir): Phase 213-2 Step 2-2 & 2-3 Data structure extensions
...
Extended PatternPipelineContext and CarrierUpdateInfo for Pattern 3 AST-based generalization.
Changes:
1. PatternPipelineContext:
- Added loop_condition: Option<ASTNode>
- Added loop_body: Option<Vec<ASTNode>>
- Added loop_update_summary: Option<LoopUpdateSummary>
- Updated build_pattern_context() for Pattern 3
2. CarrierUpdateInfo:
- Added then_expr: Option<ASTNode>
- Added else_expr: Option<ASTNode>
- Updated analyze_loop_updates() with None defaults
Status: Phase 213-2 Steps 2-2 & 2-3 complete
Next: Create Pattern3IfAnalyzer to extract if statement and populate update summary
2025-12-10 00:01:53 +09:00
76a36333c2
feat(joinir): Phase 204 PHI Contract Verifier complete
...
Phase 204-3/5/6/7: PHI inputs verification, integration, testing, docs
Implementation:
- verify_phi_inputs_defined(): Conservative sanity checks (ValueId < 100000)
- Integration: All verifiers in verify_joinir_contracts()
- Testing: 821 tests PASS, no regressions
Task Status:
- ✅ 204-1: Design document (phase204-phi-contract-verifier.md)
- ✅ 204-2: PHI dst overwrite detection
- ✅ 204-3: PHI inputs sanity checks
- ⚠️ 204-4: JoinValueSpace region verification (deferred to Phase 205+)
- Rationale: Requires LoopHeaderPhiInfo extension (4+ files)
- Alternative: Conservative threshold checks in verify_phi_inputs_defined()
- ✅ 204-5: Integration (verify_joinir_contracts)
- ✅ 204-6: Tests (821 PASS)
- ✅ 204-7: Documentation (phase204 doc + CURRENT_TASK.md)
Verification Coverage:
- ✅ PHI exists (Phase 200-3)
- ✅ PHI dst match (Phase 200-3)
- ✅ PHI dst not overwritten (Phase 204-2) ✨
- ✅ PHI inputs sanity (Phase 204-3) ✨
- ⚠️ PHI inputs DFA (Phase 205+)
- ⚠️ ValueId regions (Phase 205+)
Design Principles:
- Debug-only (#[cfg(debug_assertions)])
- Fail-Fast (panic on violation)
- Zero cost in release builds
Files Modified:
- src/mir/builder/control_flow/joinir/merge/mod.rs (+115 lines)
- src/mir/builder/control_flow/joinir/merge/exit_line/reconnector.rs (1 line)
- docs/development/current/main/phase204-phi-contract-verifier.md (updated)
- CURRENT_TASK.md (Phase 204 complete)
Success Criteria: 4/5 met (1 deferred with rationale)
2025-12-09 19:57:32 +09:00
0175e62d9e
feat(joinir): Phase 204-2 PHI dst overwrite detection
...
Task 204-2: Implement verify_no_phi_dst_overwrite()
- Added PHI dst overwrite detection in merge/mod.rs
- Helper get_instruction_dst() extracts dst from MirInstruction
- Integrated into verify_joinir_contracts()
- Fixed pre-existing bugs:
- entry_block_remapped → entry_block (line 592)
- HashMap → BTreeMap in reconnector.rs (line 174)
- All instructions covered with wildcard pattern
Design:
- Debug-only (#[cfg(debug_assertions)])
- Fail-Fast panic on violation
- Checks PHI dst not overwritten by later instructions in header block
Status: Build SUCCESS (Task 204-2 complete)
Next: Task 204-3 (PHI inputs verification)
2025-12-09 19:53:33 +09:00
32a91e31ac
feat(joinir): Phase 200-B/C/D capture analysis + Phase 201-A reserved_value_ids infra
...
Phase 200-B: FunctionScopeCaptureAnalyzer implementation
- analyze_captured_vars_v2() with structural loop matching
- CapturedEnv for immutable function-scope variables
- ParamRole::Condition for condition-only variables
Phase 200-C: ConditionEnvBuilder extension
- build_with_captures() integrates CapturedEnv into ConditionEnv
- fn_body propagation through LoopPatternContext to Pattern 2
Phase 200-D: E2E verification
- capture detection working for base, limit, n etc.
- Test files: phase200d_capture_minimal.hako, phase200d_capture_in_condition.hako
Phase 201-A: MirBuilder reserved_value_ids infrastructure
- reserved_value_ids: HashSet<ValueId> field in MirBuilder
- next_value_id() skips reserved IDs
- merge/mod.rs sets/clears reserved IDs around JoinIR merge
Phase 201: JoinValueSpace design document
- Param/Local/PHI disjoint regions design
- API: alloc_param(), alloc_local(), reserve_phi()
- Migration plan for Pattern 1-4 lowerers
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com >
2025-12-09 18:32:03 +09:00
440f8646b1
feat(joinir): Phase 183 LoopBodyLocal role separation + test fixes
...
Phase 183 Implementation:
- Added is_var_used_in_condition() helper for AST variable detection
- Implemented LoopBodyLocal filtering in TrimLoopLowerer
- Created 4 test files for P1/P2 patterns
- Added 5 unit tests for variable detection
Test Fixes:
- Fixed test_is_outer_scope_variable_pinned (BasicBlockId import)
- Fixed test_pattern2_accepts_loop_param_only (literal node usage)
Refactoring:
- Unified pattern detection documentation
- Consolidated CarrierInfo initialization
- Documented LoopScopeShape construction paths
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-08 23:43:26 +09:00
95f3aa429e
refactor(joinir): Extract legacy binding path to routing_legacy_binding.rs
...
Phase 179-A Step 2: Separate LoopFrontendBinding JSON construction logic
into dedicated module for better organization.
Changes:
- New file: routing_legacy_binding.rs (223 lines)
- routing.rs: cf_loop_joinir_impl() simplified to 15 lines (delegates to legacy path)
- Routing now clearly separates pattern-based vs. legacy binding paths
Benefits:
- Clear separation of concerns (pattern router vs. legacy whitelist)
- routing.rs reduced from 364 to 146 lines (60% reduction)
- Legacy path isolated for future deprecation
2025-12-08 18:36:13 +09:00
7a01ffe522
fix(joinir): Phase 177-3 ValueId collision fix for multi-carrier loops
...
Root cause: JoinIR ValueId collision between function parameters and condition bindings
- Same ValueId used for both `result_init` (carrier param) and `limit` (condition var)
- Phase 33-21 was overwriting condition bindings when remapping carrier PHIs
Fix implemented (Option B - immediate protection):
1. Phase 177-3: Protect condition-only variables from Phase 33-21 override
- Collect condition_bindings that are NOT carriers (by checking exit_bindings)
- Skip remapping for these protected ValueIds
2. Phase 177-3-B: Handle body-only carriers explicitly
- Carriers that appear in condition_bindings (added by Phase 176-5)
- Map them to correct PHI dsts by name lookup
Investigation tools added:
- [DEBUG-177] trace logs for remapper state tracking
- Phase 177-3 protection logging
- BoundaryInjector PHI collision detection
Test results:
- ✅ Integer multi-carrier test: Output 3 (expected)
- ⚠️ String test: RC=0 but empty output (separate issue - string concat emit)
Design docs created:
- phase177-parse-string-design.md: _parse_string loop analysis
- phase177-carrier-evolution.md: Carrier progression Phase 174-179
Next: Investigate string concatenation emit for full _parse_string support
2025-12-08 16:34:04 +09:00
99d329096f
feat(joinir): Phase 176 Pattern2 multi-carrier lowering complete
...
Task 176-1: Pattern2 limitation investigation
- Identified 10 limitation points where only position carrier was handled
- Added TODO markers for Phase 176-2/3 implementation
- Created phase176-pattern2-limitations.md documentation
Task 176-2: CarrierUpdateLowerer helper implementation
- Implemented emit_carrier_update() helper function
- Supports CounterLike and AccumulationLike UpdateExpr patterns
- Added 6 unit tests (all passing)
- Fail-Fast error handling for carrier/variable not found
Task 176-3: Pattern2 lowerer multi-carrier extension
- Extended header PHI generation for all carriers
- Implemented loop update for all carriers using emit_carrier_update()
- Extended ExitLine/ExitMeta construction for all carriers
- Updated function call/jump args to include all carriers
- 9/10 tests passing (1 pre-existing test issue)
Task 176-4: E2E testing and bug fixes
- Fixed Trim pattern loop_var_name overwrite bug (pattern2_with_break.rs)
- Fixed InstructionRewriter latch_incoming mapping bug
- All E2E tests passing (RC=0): pos + result dual-carrier loops work
- test_jsonparser_parse_string_min2.hako verified
Task 176-5: Documentation updates
- Created phase176-completion-report.md
- Updated phase175-multicarrier-design.md with completion status
- Updated joinir-architecture-overview.md roadmap
- Updated CURRENT_TASK.md with Phase 176 completion + Phase 177 TODO
- Updated loop_pattern_space.md F-axis (multi-carrier support complete)
Technical achievements:
- Pattern2 now handles single/multiple carriers uniformly
- CarrierInfo architecture proven to work end-to-end
- Two critical bugs fixed (loop_var overwrite, latch_incoming mapping)
- No regressions in existing tests
Next: Phase 177 - Apply to JsonParser _parse_string full implementation
2025-12-08 15:17:53 +09:00
c63e6deb32
feat(joinir): Task 200-3 - JoinIRVerifier for LoopHeader PHI and ExitLine contracts
...
Debug-only verification module to catch JoinIR contract violations early:
- verify_loop_header_phis: Checks loop_var_name → PHI exists in header block
- verify_exit_line: Checks exit_bindings → values exist, exit block in range
- verify_joinir_contracts: Main entry point, runs all checks
Implementation:
- Added verification functions to merge/mod.rs (private module has type access)
- Called from merge_joinir_mir_blocks after exit block setup
- Only active in debug builds (#[cfg(debug_assertions)])
Benefits:
- Catches "动くけど header PHI 無い" bugs immediately
- Validates exit_bindings before variable_map reconnection
- Prevents silent contract violations during development
2025-12-08 04:33:33 +09:00
53af63c96c
feat(joinir): Phase 33-21 Pattern 4 parameter remapping fix and debug improvements
...
## Problem
Pattern 4 (loop with continue) was producing SSA-undef errors due to function_params
key mismatch. function_params uses 'join_func_0'/'join_func_1' format (from join_func_name()),
but code was looking for 'main'/'loop_step'.
## Solution
- Fix mod.rs: Use correct function keys 'join_func_0' and 'join_func_1'
- Add warning logs to detect future key mismatches immediately
- Update pattern4_with_continue.rs: Mark as fully implemented (not stub)
- Remove unused imports: MergeResult, TailCallKind, classify_tail_call, etc.
## Testing
- Pattern 3 (If PHI): sum=9 ✅
- Pattern 4 (Continue): 25 ✅ (1+3+5+7+9)
- No SSA-undef errors
- No new warnings on successful execution
## Debug Improvements
Added pre-flight checks in merge/mod.rs Phase 33-21:
```
[cf_loop/joinir] WARNING: function_params.get('join_func_0') returned None.
Available keys: [...]
```
This will save significant debugging time for future parameter mapping issues.
🤖 Generated with Claude Code
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com >
2025-12-07 18:47:24 +09:00
a6a97b3781
refactor(joinir): Phase 33-17-B LoopHeaderPhiInfo extraction
...
## Changes
- Extract LoopHeaderPhiInfo Box (116 lines) from loop_header_phi_builder
- loop_header_phi_builder.rs reduced: 318 → 217 lines (-32%)
- Proper separation of data structures from builder logic
## Module Structure
- loop_header_phi_info.rs: LoopHeaderPhiInfo, CarrierPhiEntry structs + tests
- loop_header_phi_builder.rs: LoopHeaderPhiBuilder implementation
## Box Theory Compliance
- Data structures separated from builder logic
- Each file has clear single responsibility
- Clean re-exports through mod.rs
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-07 12:28:11 +09:00
8baca953ca
refactor(joinir): Phase 33-17-A TailCallClassifier and MergeResult extraction
...
## Changes
- Extract TailCallClassifier Box (107 lines) with 4 unit tests
- Extract MergeResult Box (44 lines) for merge result data structure
- instruction_rewriter.rs reduced: 649 → 580 lines (-10.6%)
## Box Theory Compliance
- TailCallClassifier: Single responsibility for tail call classification
- MergeResult: Clean data structure separation
- Both modules follow naming conventions (Classifier, Result)
## Quality
- 4 unit tests added for TailCallClassifier
- Build verified ✅
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-07 12:23:37 +09:00
287ceca18d
feat(joinir): Phase 33-16 Loop Header PHI SSOT with TailCallKind refactoring
...
## Problem
- joinir_min_loop.hako returned 0 instead of expected 2
- Entry block's tail call was redirected to itself (bb4 → bb4 self-loop)
- JoinIR function parameters lack SSA definition when inlined
## Solution
- Distinguish entry calls from back edges using TailCallKind enum
- Entry block (LoopEntry) stays at target, back edges redirect to header PHI
- Added explicit classification: LoopEntry, BackEdge, ExitJump
## Key Changes
- instruction_rewriter.rs: TailCallKind enum + classify_tail_call()
- Renamed is_entry_func_entry_block → is_loop_entry_point (clearer intent)
- loop_header_phi_builder.rs: New module for header PHI generation
- joinir_inline_boundary_injector.rs: Skip loop var Copy when header PHI handles it
## Verified
- joinir_min_loop.hako: returns 2 ✅
- NYASH_SSA_UNDEF_DEBUG: no undefined errors ✅
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-07 12:01:54 +09:00
a09ce0cbff
feat(joinir): Phase 33-14 JoinFragmentMeta for expr/carrier separation
...
Introduces JoinFragmentMeta to distinguish between loop expression results
and carrier variable updates, fixing SSA correctness issues.
## Changes
### New: JoinFragmentMeta struct (carrier_info.rs)
- `expr_result: Option<ValueId>` - Loop as expression (return loop(...))
- `exit_meta: ExitMeta` - Carrier updates for variable_map
- Helper methods: with_expr_result(), carrier_only(), empty()
### Pattern 2 Lowerer Updates
- loop_with_break_minimal.rs: Returns (JoinModule, JoinFragmentMeta)
- pattern2_with_break.rs: Sets boundary.expr_result from fragment_meta
### instruction_rewriter.rs
- Phase 33-14: Only add to exit_phi_inputs when boundary.expr_result is Some
- Phase 33-13: MergeResult struct with carrier_inputs map
### JoinInlineBoundary (inline_boundary.rs)
- New field: expr_result: Option<ValueId>
- All constructors updated with expr_result: None default
## Design Philosophy
Previously, exit_phi_inputs mixed expr results with carrier updates, causing:
- PHI inputs referencing undefined remapped values
- SSA-undef errors in VM execution
With JoinFragmentMeta:
- expr_result → exit_phi_inputs (generates PHI for expr value)
- exit_meta → carrier_inputs (updates variable_map via carrier PHIs)
## Test Results
- Pattern 1 (carrier-only): Works correctly (no exit_phi_inputs)
- Pattern 2 (expr result): Design complete, SSA-undef fix deferred to Phase 33-15
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-07 05:07:28 +09:00
eabef39748
feat(joinir/refactor): Phase 33-10-P1 ExitMetaCollector Box modularization
...
Box theory refactoring: Extract exit_bindings construction logic from
pattern lowerers into focused, reusable ExitMetaCollector Box.
**Changes**:
1. Created meta_collector.rs (+102 lines):
- ExitMetaCollector::collect() builds exit_bindings from ExitMeta
- Pure function (no side effects)
- Reusable by all pattern lowerers
2. Updated pattern2_with_break.rs (-20 lines):
- Use ExitMetaCollector::collect() instead of inline filter_map
- Removed manual binding construction loop
- Cleaner caller code
3. Made exit_line module public:
- Allows pattern lowerers to use ExitMetaCollector
- Clear module visibility boundaries
**Box Design**:
- Single responsibility: Convert ExitMeta + variable_map → exit_bindings
- Pure function: No side effects, testable independently
- Reusable: Can be used by Pattern 3, Pattern 4, etc.
**Testing**:
- Build: ✅ Success (1m 04s)
- Execution: ✅ RC: 0 (Pattern 2 verified)
- Regression: ✅ No issues
**Metrics**:
- New lines: +102 (meta_collector.rs)
- Removed lines: -20 (pattern2_with_break.rs)
- Net change: +82 lines
- Code clarity: Significantly improved
🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-07 02:37:12 +09:00
547be29a1f
feat(joinir/refactor): Phase 33-10-P0 ExitLineReconnector Box modularization
...
Box theory application: Extract Phase 6 reconnect_boundary logic into
focused, testable exit_line module with clear responsibilities.
**Changes**:
1. Created exit_line submodule (2 new files):
- reconnector.rs: ExitLineReconnector Box (+130 lines)
- mod.rs: ExitLineOrchestrator facade (+58 lines)
2. Simplified merge/mod.rs (-91 lines):
- Removed reconnect_boundary() function
- Delegate to ExitLineOrchestrator::execute()
- Clear separation of concerns
**Box Design**:
- ExitLineReconnector: Single responsibility - update variable_map with
remapped exit values from JoinIR k_exit parameters
- ExitLineOrchestrator: Facade for Phase 6 orchestration
- Phase 197-B multi-carrier support: Each carrier gets specific exit value
**Testing**:
- Build: ✅ Success (0.11s)
- Execution: ✅ RC: 0 (Pattern 2 simple loop verified)
- Regression: ✅ No regression in existing logic
**Metrics**:
- New lines: +188 (exit_line module)
- Removed lines: -91 (merge/mod.rs)
- Net change: +97 lines
- Maintainability: Significantly improved
- Test coverage ready: Isolated Box can be tested independently
🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-07 02:34:36 +09:00
41c50e4780
feat(joinir): Phase 172-3 ExitMeta unified return from Pattern2 lowerer
...
Implement loop exit contract boxification for JoinIR Pattern2:
- lower_loop_with_break_minimal now returns (JoinModule, ExitMeta)
- ExitMeta contains k_exit parameter ValueId for carrier variables
- Pattern2 caller builds exit_bindings from ExitMeta
- merge/mod.rs adds exit_bindings join_exit_values to used_values for remap
- reconnect_boundary uses remapped exit values for variable_map updates
This completes Phases 172-3 through 172-5 of the Loop Exit Contract
boxification plan, enabling proper loop variable propagation after exit.
Test: joinir_min_loop.hako passes (RC: 0)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-07 02:03:55 +09:00
e30116f53d
feat(joinir): Phase 171-fix ConditionEnv/ConditionBinding architecture
...
Proper HOST↔JoinIR ValueId separation for condition variables:
- Add ConditionEnv struct (name → JoinIR-local ValueId mapping)
- Add ConditionBinding struct (HOST/JoinIR ValueId pairs)
- Modify condition_to_joinir to use ConditionEnv instead of builder.variable_map
- Update Pattern2 lowerer to build ConditionEnv and ConditionBindings
- Extend JoinInlineBoundary with condition_bindings field
- Update BoundaryInjector to inject Copy instructions for condition variables
This fixes the undefined ValueId errors where HOST ValueIds were being
used directly in JoinIR instructions. Programs now execute (RC: 0),
though loop variable exit values still need Phase 172 work.
Key invariants established:
1. JoinIR uses ONLY JoinIR-local ValueIds
2. HOST↔JoinIR bridging is ONLY through JoinInlineBoundary
3. condition_to_joinir NEVER accesses builder.variable_map
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-07 01:45:03 +09:00
ae61226691
feat(joinir): Phase 197 Pattern4 multi-carrier exit fix & AST-based update
...
Phase 197-B: Multi-Carrier Exit Mechanism
- Fixed reconnect_boundary() to use remapper for per-carrier exit values
- ExitMeta now uses carrier_param_ids (Jump arguments) instead of
carrier_exit_ids (k_exit parameters)
- Root cause: k_exit parameters aren't defined when JoinIR functions
merge into host MIR
Phase 197-C: AST-Based Update Expression
- LoopUpdateAnalyzer extracts update patterns from loop body AST
- Pattern4 lowerer uses UpdateExpr for semantically correct RHS
- sum = sum + i → uses i_next (current iteration value)
- count = count + 1 → uses const_1
Files modified:
- src/mir/builder/control_flow/joinir/merge/mod.rs
- src/mir/join_ir/lowering/loop_with_continue_minimal.rs
- src/mir/join_ir/lowering/loop_update_analyzer.rs (new)
Test results:
- loop_continue_multi_carrier.hako: 25, 5 ✅
- loop_continue_pattern4.hako: 25 ✅
Pattern 1–4 now unified with:
- Structure-based detection (LoopFeatures + classify)
- Carrier/Exit metadata (CarrierInfo + ExitMeta)
- Boundary connection (JoinInlineBoundary + LoopExitBinding)
- AST-based update expressions (LoopUpdateAnalyzer)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-06 14:46:33 +09:00
9764ca3052
refactor: Break down merge_joinir_mir_blocks into 6 modules (Phase 4)
...
Phase 4 Implementation Complete: Successfully modularized the 714-line
merge_joinir_mir_blocks() function into 6 focused, maintainable modules.
## Changes Made
### 1. Created Module Structure
- `src/mir/builder/control_flow/joinir/merge/` directory
- 5 sub-modules + 1 coordinator (6 files total)
### 2. Module Breakdown (848 lines total)
- **mod.rs** (223 lines) - Coordinator function
- Orchestrates all 6 phases
- Handles boundary reconnection
- Manages entry/exit block jumps
- **block_allocator.rs** (70 lines) - Block ID allocation
- Allocates new BlockIds for all JoinIR functions
- Maintains determinism via sorted iteration
- **value_collector.rs** (90 lines) - Value collection
- Collects all ValueIds from JoinIR functions
- Builds auxiliary maps for Call→Jump conversion
- **instruction_rewriter.rs** (405 lines) - Instruction rewriting
- Rewrites instructions with remapped IDs
- Handles tail call optimization
- Converts Return → Jump to exit block
- **exit_phi_builder.rs** (60 lines) - Exit PHI construction
- Builds PHI node merging return values
- Creates exit block
### 3. Updated control_flow/mod.rs
- Replaced 714-line function with 18-line delegation
- Reduced from 904 lines → 312 lines (65% reduction)
- Added documentation explaining Phase 4 refactoring
## Verification Results
✅ **Build**: `cargo build --release` - SUCCESS (23.36s)
✅ **Smoke Test**: loop_min_while.hako - PASS (correct output: 0,1,2)
✅ **Determinism**: 3 consecutive runs - IDENTICAL OUTPUT
✅ **Debug Traces**: NYASH_OPTION_C_DEBUG=1 traces work correctly
✅ **No Regressions**: Behavior preserved 100%
## Benefits
1. **Maintainability**: 714 lines → 6 focused modules (100-150 lines each)
2. **Readability**: Each phase isolated in its own file
3. **Testability**: Individual modules can be tested separately
4. **Future Development**: Easy to modify individual phases
5. **Zero Breaking Changes**: Backward compatible, no API changes
## Technical Notes
- Uses JoinIrIdRemapper (already existed) for ID translation
- Preserves all debug output and trace functionality
- Maintains determinism via BTreeSet/BTreeMap
- All Phase 189 features intact (multi-function support, etc.)
Generated with Claude Code (https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-05 21:00:55 +09:00