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
49cc829ad2
refactor(joinir): Phase 193-2 - CarrierInfo Builder Enhancement
...
**Phase 193-2**: Add flexible builder methods to CarrierInfo and ExitMeta
## Summary
Enhanced CarrierInfo and ExitMeta with convenient builder methods that support
multiple construction patterns. This reduces boilerplate and makes carrier info
generation more flexible for different lowering scenarios.
## Changes
### CarrierInfo New Methods
- **from_variable_map()**: Automatically extract carriers from variable_map
- Eliminates manual carrier listing for simple cases
- Auto-discovers all non-loop-control variables
- Deterministic sorting for reproducibility
- **with_explicit_carriers()**: Selective carrier extraction
- Choose which variables to treat as carriers
- Useful for Pattern 5+ with complex variable sets
- Validates all carriers exist in variable_map
- **with_carriers()**: Direct CarrierVar construction
- Most explicit method for advanced use cases
- Use when CarrierVar structs already exist
- Auto-sorts for determinism
### CarrierInfo Query Methods
- **carrier_count()**: Get number of carriers
- **is_multi_carrier()**: Check if multi-carrier loop
- **find_carrier()**: Lookup specific carrier by name
### ExitMeta New Methods
- **binding_count()**: Get number of exit bindings
- **is_empty()**: Check if any exit values exist
- **find_binding()**: Lookup exit value by carrier name
- **with_binding()**: Chainable binding addition
## Design Benefits
| Aspect | Benefit |
|--------|---------|
| **Flexibility** | 3 construction patterns for different scenarios |
| **Clarity** | Explicit method names document intent |
| **Ergonomics** | Reduced boilerplate in lowerers |
| **Validation** | Error handling for missing variables |
| **Determinism** | Automatic sorting in all methods |
## Usage Examples
```rust
// Pattern 1: Auto-discover from variable_map
let info = CarrierInfo::from_variable_map("i", &variable_map)?;
// Pattern 2: Selective carriers
let info = CarrierInfo::with_explicit_carriers(
"i", loop_id,
vec!["sum".into(), "count".into()],
&variable_map
)?;
// Pattern 3: Manual construction
let info = CarrierInfo::with_carriers("i", loop_id, carriers);
// Query methods
if info.is_multi_carrier() {
println!("Multi-carrier loop with {} carriers", info.carrier_count());
}
// ExitMeta chaining
let meta = ExitMeta::empty()
.with_binding("sum".into(), ValueId(15))
.with_binding("count".into(), ValueId(16));
```
## Metrics
- CarrierInfo: +3 construction methods, +3 query methods
- ExitMeta: +4 new methods (existing 3 methods unchanged)
- Total lines added: ~150 (including docs)
- Build time: 1m 05s ✅
- Zero regressions ✅
## Next Steps
- Phase 193-3: Pattern Classification Improvement
- Phase 194: Further optimization opportunities
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-06 10:27:18 +09:00
60bd5487e6
refactor(joinir): Pattern 4 modularization with CarrierInfo/ExitMeta
...
Removes hardcoded "sum" and ValueId(15) from Pattern 4 lowerer by
introducing CarrierInfo and ExitMeta structures.
Changes:
- New carrier_info.rs: CarrierInfo, CarrierVar, ExitMeta structs
- loop_with_continue_minimal.rs: Returns (JoinModule, ExitMeta)
- pattern4_with_continue.rs: Dynamic binding generation from metadata
Design approach: "Thin meta on existing boxes" (ChatGPT proposal)
- CarrierInfo: Built from variable_map, not AST re-analysis
- ExitMeta: Carrier name + JoinIR ValueId pairs from lowerer
- LoopExitBinding: Auto-generated from CarrierInfo + ExitMeta
Test: loop_continue_pattern4.hako outputs 25 (unchanged)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-06 02:05:19 +09:00
ee04ba4406
fix(joinir): Pattern 4 use Select instead of conditional Jump
...
Change from dual-path (continue Jump + normal Call) to single-path
using Select to merge sum values before tail call.
- Replace conditional Jump with Select instruction
- sum_merged = Select(continue_cond, sum_param, sum_next)
- Single tail call: Call(loop_step, [i_next, sum_merged])
Known issue: PHI generated at JoinIR level but lost in MIR merge.
Need to investigate JoinIR→MIR merge layer.
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-06 01:00:04 +09:00
120cd37451
feat(joinir): Pattern 4 (continue) JoinIR lowering implementation
...
- Add loop_with_continue_minimal.rs (330 lines)
- Generate JoinIR: main → loop_step → k_exit for continue patterns
- Integrate pattern4_with_continue.rs to call minimal lowerer
- Known issue: JoinIR→MIR bridge doesn't handle multiple carriers
(output=0 instead of expected=25, needs PHI fix in merge layer)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-06 00:20:45 +09:00
a21501286e
feat(joinir): Structural pattern detection + Pattern 4 scaffold
...
- Add LoopFeatures struct for structure-based detection (no name deps)
- Add LoopPatternKind enum and classify() function
- Pattern 3: has_if_else_phi && !has_break && !has_continue
- Pattern 4: has_continue == true (detection only, lowering TODO)
- Unify router to use extract_features()/classify() instead of legacy
- Remove AST dependency, use LoopForm/LoopScope only
- Add Pattern 4 test file (loop_continue_pattern4.hako)
- Pattern 3 test passes (sum=9)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-06 00:10:27 +09:00
89e138a2f8
docs: Complete generic_case_a modularization (Phase 5)
...
- Updated mod.rs with comprehensive module organization documentation
- Documented before/after line counts and size reductions
- Removed old generic_case_a_old.rs monolith file
- Verified all imports are clean (no unused warnings)
- Verified all visibility is correct (pub(crate) for public API)
Final statistics:
- Before: 1,056 lines in single file
- After: 1,634 lines across 7 focused modules
- Main coordinator: 93 lines (91% reduction)
- Average module size: 233 lines (manageable, focused)
- Largest module: trim.rs at 537 lines (still maintainable)
All success criteria met:
✅ All 7 modules created
✅ cargo build --release succeeds
✅ Zero breaking changes (all APIs compatible)
✅ Module documentation comprehensive
✅ All visibility correct
Ref: Phase 192 modularization effort
2025-12-05 21:44:07 +09:00
e44e36b9cd
refactor: Extract append_defs and stage1 lowerers (Phase 4)
...
- Created append_defs.rs with lower_case_a_append_defs_with_scope()
- Extracted 173 lines of append_defs lowering logic
- Implements array concatenation loop (ArrayBox.get/push)
- ValueId allocation: entry(8000-8999), loop_step(9000-9999)
- Created stage1_using_resolver.rs with lower_case_a_stage1_usingresolver_with_scope()
- Extracted 185 lines of stage1 using resolver logic
- Implements namespace resolution loop with OR accumulation
- ValueId allocation: entry(10000-10999), loop_step(11000-11999)
Both modules use EntryFunctionBuilder helper for boilerplate initialization.
Sizes: append_defs (173 lines), stage1 (185 lines)
Ref: Phase 192 modularization effort
2025-12-05 21:39:22 +09:00
957917b08b
refactor: Extract trim lowerer from generic_case_a (Phase 3)
...
- Created trim.rs with lower_case_a_trim_with_scope() and helpers
- Extracted 480 lines of trim-specific lowering logic (largest module)
- Implements 3 functions: trim_main (entry), loop_step, skip_leading
- Comprehensive whitespace detection (space/tab/newline/CR)
- ValueId allocation: entry(5000-5999), loop_step(6000-6999), skip(7000-7999)
Size: 480 lines (largest extracted module from 1,056-line monolith)
Ref: Phase 192 modularization effort
2025-12-05 21:35:31 +09:00
f71d58a46f
refactor: Extract skip_ws lowerer from generic_case_a (Phase 2)
...
- Created skip_ws.rs with lower_case_a_skip_ws_with_scope() and helper
- Extracted 233 lines of skip_ws-specific lowering logic
- Added comprehensive module documentation
- Uses EntryFunctionBuilder from helper module
- ValueId allocation: entry(3000-3999), loop_step(4000-5999)
Size: 233 lines (extracted from 1,056-line monolith)
Ref: Phase 192 modularization effort
2025-12-05 21:33:49 +09:00
1d7b499f4d
refactor: Create generic_case_a directory structure (Phase 1)
...
- Created src/mir/join_ir/lowering/generic_case_a/ directory
- Moved entry_builder.rs and whitespace_check.rs into new directory
- Created mod.rs with public API exports and comprehensive documentation
- Renamed old generic_case_a.rs to generic_case_a_old.rs temporarily
- Updated parent mod.rs to import from new structure
Ref: Phase 192 modularization effort
2025-12-05 21:32:41 +09:00
caf38dba19
feat(joinir): Phase 190 - LoopExitBinding boxification
...
Formalize exit PHI → variable_map reconnection with explicit LoopExitBinding
structure. Eliminates hardcoded variable names and prepares for Pattern 4+
multi-carrier support.
Key changes:
1. **New LoopExitBinding struct**:
- carrier_name: String (e.g., "sum", "count")
- join_exit_value: ValueId (JoinIR exit value)
- host_slot: ValueId (variable_map destination)
Makes it explicit: WHICH variable, FROM where, TO where.
2. **Updated JoinInlineBoundary**:
- Replaced implicit host_outputs: Vec<ValueId>
- With explicit exit_bindings: Vec<LoopExitBinding>
- Old APIs marked #[deprecated] for backward compatibility
3. **Pattern 3 now uses explicit bindings**:
Before: boundary.host_outputs = vec![sum_var_id] // implicit
After: boundary.exit_bindings = vec![LoopExitBinding {
carrier_name: "sum".to_string(),
join_exit_value: ValueId(18),
host_slot: sum_var_id,
}]
4. **merge_joinir_mir_blocks() updated**:
- Consumes exit_bindings instead of bare ValueIds
- Enhanced debug output shows carrier names
- Validates carrier name matches variable_map expectations
Benefits:
- Self-documenting code: bindings explain themselves
- Multi-carrier ready: Pattern 4+ just extend the vec![]
- Type-safe: No implicit semantics
- Debuggable: Explicit carrier name in logs
Test status:
- Build: ✅ SUCCESS (0 errors, 47 warnings)
- Pattern 3: ✅ PASS (no regressions)
- Backward compatibility: ✅ Maintained via #[deprecated]
Prepare for Phase 191: Pattern Router Table and Phase 192: JoinLoopTrace
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: ChatGPT <noreply@openai.com >
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-05 19:59:40 +09:00
0397df5240
refactor(joinir): Phase 189 - Remove hardcoded 'sum' variable, generalize exit PHI connection
...
Key improvements:
1. **Eliminate hardcoded variable name**: Replace hardcoded "sum" with generic
ValueId-based variable_map updates. Add new JoinInlineBoundary constructor
`new_with_input_and_host_outputs()` for Pattern 3.
2. **Generalize output slot mapping**: Exit PHI result now updates all host_outputs
entries in variable_map, not just hardcoded "sum". Prepares for future
multi-carrier patterns.
3. **PHI preservation in blocks**: Fix block finalization to preserve existing
PHI instructions (from handle_select) instead of overwriting them.
4. **Stable function name→ValueId mapping**: Ensure consistent ValueId
assignment for tail call detection across multi-function merges.
5. **Enhanced debugging**: Add detailed logging in block converter and meta
analysis for PHI verification.
Files modified:
- src/mir/builder/control_flow.rs: Remove hardcoded "sum", use boundary outputs
- src/mir/join_ir/lowering/inline_boundary.rs: Add new constructor
- src/mir/join_ir_vm_bridge/joinir_block_converter.rs: Stable mappings, PHI preservation
- src/mir/join_ir_vm_bridge/meta.rs: Debug output for PHI tracking
- src/mir/builder/joinir_id_remapper.rs: PHI value remapping
- src/mir/builder/joinir_inline_boundary_injector.rs: Span preservation
Test status: Pattern 3 (loop_if_phi.hako) still produces correct result (sum=9, RC=9)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: ChatGPT <noreply@openai.com >
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-05 19:39:54 +09:00
c4c0814fd6
fix(joinir): Use BTreeMap for MirModule.functions deterministic iteration
...
HashMap iteration order is non-deterministic due to HashDoS protection.
This caused merge_joinir_mir_blocks to sometimes process functions in
wrong order, leading to incorrect block remapping.
Changed:
- MirModule.functions: HashMap → BTreeMap
- MirInterpreter.functions: HashMap → BTreeMap
- IfLoweringDryRunner.scan_module: HashMap → BTreeMap parameter
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-05 17:22:14 +09:00
638182a8a2
feat(joinir): Phase 188-Impl-3 Pattern 3 (Loop with If-Else PHI) implementation
...
Add Pattern 3 lowerer for `loop { if cond { x = a } else { x = b } ... }` pattern.
New files:
- loop_with_if_phi_minimal.rs (381 lines): JoinIR lowerer for Pattern 3
- Multiple loop variables (counter + accumulator)
- In-loop if/else PHI using Select instruction
- Carriers passed to next iteration via tail recursion
Modified files:
- join_ir/mod.rs: Add Mod to BinOpKind, Select to MirLikeInst
- loop_pattern_detection.rs: Add is_loop_with_conditional_phi_pattern() detection
- lowering/mod.rs: Pattern 3 router integration
- loop_patterns.rs: Pattern 3 entry point delegation
- json.rs: Mod/Select JSON serialization
- join_ir_ops.rs: Mod operation evaluation (a % b)
- join_ir_runner.rs: Select instruction execution
- join_ir_vm_bridge/convert.rs: Mod/Select conversion handlers
Implementation:
- Pattern 3 generates 3 JoinIR functions: main, loop_step(i, sum), k_exit(sum_final)
- Exit condition: !(i <= 5) with Jump to k_exit
- In-loop if/else: if (i % 2 == 1) { sum + i } else { sum + 0 }
- Select instruction: sum_new = Select(if_cond, sum_then, sum_else)
- Both carriers updated: Call(loop_step, [i_next, sum_new])
Build status: ✅ Compiles successfully (0 errors, 34 warnings)
Integration: Infrastructure complete, MIR boundary mapping pending
All 3 patterns now have lowering infrastructure in place for Phase 188.
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-05 15:45:42 +09:00
87e477b13e
feat(joinir): Phase 188-Impl-2 Pattern 2 (Loop with Conditional Break) implementation
...
Add Pattern 2 lowerer for `loop { if cond { break } body }` pattern.
New files:
- loop_with_break_minimal.rs (291 lines): JoinIR lowerer for Pattern 2
- Exit PHI receives values from both natural exit and break path
- Tail-recursive loop_step function design
Modified files:
- loop_pattern_detection.rs: Add is_loop_with_break_pattern() detection
- mod.rs: Router integration (Pattern 1 → Pattern 2 ordering)
- control_flow.rs: Add cf_loop_pattern2_with_break() helper
- loop_patterns.rs: Simplified skeleton (defer until patterns stabilize)
Test results:
- Pattern 1 (loop_min_while.hako): ✅ PASS
- Pattern 2 (joinir_min_loop.hako): ✅ PASS
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-05 15:28:54 +09:00
4e4a56f8c9
refactor(joinir): Phase 192 generic_case_a.rs modularization
...
- generic_case_a_entry_builder.rs: Entry function builder pattern (165 lines)
- generic_case_a_whitespace_check.rs: Whitespace detector utilities (151 lines)
- generic_case_a.rs: Refactored to use EntryFunctionBuilder
- Boilerplate BTreeMap initialization delegated to builder pattern
- 4 functions (skip_ws, trim, append_defs, stage1) now use unified builder
- Improved maintainability and reduced code duplication
2025-12-05 15:05:25 +09:00
d303d24b43
feat(joinir): Phase 188 JoinInlineBoundary + Pattern 1 working! 🎉
...
Major milestone: loop_min_while.hako outputs "0 1 2" correctly!
## JoinInlineBoundary (Option D from ChatGPT Pro design review)
- New struct for clean SSA boundary between JoinIR and host function
- JoinIR uses local ValueIds (0,1,2...) - no host ValueId dependency
- Copy injection at entry block connects host → JoinIR values
## Pattern 1 Simple While Loop
- Refactored to use pure local ValueIds
- Removed Pattern1Context dependency on host ValueIds
- Clean separation: lowerer generates, merger connects
## Key Design Principles (Box Theory)
- Box A: JoinIR Frontend (host-agnostic)
- Box B: Join→MIR Bridge (independent functions)
- Box C: JoinInlineBoundary (boundary info only)
- Box D: JoinMirInlineMerger (Copy injection)
## Files Changed
- NEW: inline_boundary.rs - JoinInlineBoundary struct
- control_flow.rs - merge with boundary, void return fix
- simple_while_minimal.rs - pure local ValueIds
- mod.rs - module export
Test: NYASH_DISABLE_PLUGINS=1 ./target/release/hakorune apps/tests/loop_min_while.hako
Output: 0\n1\n2 ✅
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-05 13:46:44 +09:00
a7f3200fba
wip(joinir): Phase 188-Impl-2 Pattern1Context host variable integration
...
Work in progress - ValueId mismatch issue needs resolution.
Changes:
- Add Pattern1Context struct with loop_var and value_allocator
- Extract loop variable from condition in cf_loop_pattern1_minimal
- Pass host's ValueId to Pattern 1 lowerer
Problem discovered:
- merge_joinir_mir_blocks() remaps ALL ValueIds
- Host's i (ValueId(2)) gets remapped to ValueId(5)
- ValueId(5) has no initialization → undefined value error
Options under consideration:
- Option A: Pinned Values (don't remap host ValueIds)
- Option B: Inline Block Generation (no JoinModule)
- Option C: Continuation Passing
- Option D: SSA Copy Injection
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-05 13:03:48 +09:00
6d069ba61d
feat(joinir): Phase 188 Print instruction + Router integration
...
- Add MirLikeInst::Print variant for direct output operations
- Implement Print instruction in JSON serialization
- Update simple_while_minimal.rs to use Print instead of BoxCall
- Add Print handling in JoinIR VM bridge and runner
- Add router logic to call Pattern 1 lowerer from main pipeline
Note: Router integration exposes ValueId mismatch issue between
Pattern 1's hardcoded IDs and host function's variables.
This architectural issue needs resolution in next phase.
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-05 12:50:05 +09:00
5bc0fa861f
feat(joinir): Phase 188 Pattern 1 Core Implementation + Phase 189 Planning
...
Phase 188 Status: Planning & Foundation Complete (100%)
Completed Tasks:
✅ Task 188-1: Error Inventory (5 patterns identified)
✅ Task 188-2: Pattern Classification (3 patterns selected)
✅ Task 188-3: Design (51KB comprehensive blueprint)
✅ Task 188-4: Implementation Foundation (1,802 lines scaffolding)
✅ Task 188-5: Verification & Documentation
✅ Pattern 1 Core Implementation: Detection + Lowering + Routing
Pattern 1 Implementation (322 lines):
- Pattern Detection: is_simple_while_pattern() in loop_pattern_detection.rs
- JoinIR Lowering: lower_simple_while_to_joinir() in simple_while_minimal.rs (219 lines)
- Generates 3 functions: entry, loop_step (tail-recursive), k_exit
- Implements condition negation: exit_cond = !(i < 3)
- Tail-recursive Call pattern with state propagation
- Routing: Added "main" to function routing list in control_flow.rs
- Build: ✅ SUCCESS (0 errors, 34 warnings)
Infrastructure Blocker Identified:
- merge_joinir_mir_blocks() only handles single-function JoinIR modules
- Pattern 1 generates 3 functions (entry + loop_step + k_exit)
- Current implementation only merges first function → loop body never executes
- Root cause: control_flow.rs line ~850 takes only .next() function
Phase 189 Planning Complete:
- Goal: Refactor merge_joinir_mir_blocks() for multi-function support
- Strategy: Sequential Merge (Option A) - merge all functions in call order
- Effort estimate: 5.5-7.5 hours
- Deliverables: README.md (16KB), current-analysis.md (15KB), QUICKSTART.md (5.8KB)
Files Modified/Created:
- src/mir/loop_pattern_detection.rs (+50 lines) - Pattern detection
- src/mir/join_ir/lowering/simple_while_minimal.rs (+219 lines) - Lowering
- src/mir/join_ir/lowering/loop_patterns.rs (+803 lines) - Foundation skeleton
- src/mir/join_ir/lowering/mod.rs (+2 lines) - Module registration
- src/mir/builder/control_flow.rs (+1 line) - Routing fix
- src/mir/builder/loop_frontend_binding.rs (+20 lines) - Binding updates
- tools/test_phase188_foundation.sh (executable) - Foundation verification
- CURRENT_TASK.md (updated) - Phase 188/189 status
Next: Phase 189 implementation (merge_joinir_mir_blocks refactor)
🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-05 07:47:22 +09:00
c2f524bb26
refactor(joinir): Phase 185 code cleanup - extract shared function, remove dead code
...
- Extract infer_type_from_mir_pattern() to common.rs (was duplicated in if_select.rs & if_merge.rs)
- Remove unused JOINIR_HEADER_BYPASS_TARGETS and is_joinir_header_bypass_target() from loopform_builder.rs
- Warnings reduced: 13 → 11
Lines removed: ~45 (duplicate function + dead code)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-04 22:33:56 +09:00
6561832545
feat(joinir): Phase 185 Strict Mode Semantics Cleanup
...
Remove redundant strict checks from If lowering (3 → 1 check point):
- mod.rs: Remove 2 strict panic blocks from try_lower_if_to_joinir()
- mod.rs: Comment out unused strict_on variable
- Keep single strict check at caller level (if_form.rs)
This aligns If lowering architecture with Loop lowering:
- Lowerers are thin Result-returning boxes (no policy decisions)
- Strict mode check happens at router/caller level (single source of truth)
- Fail-Fast principle: panic at ONE location when strict=ON
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-04 22:27:12 +09:00
7c68f710d3
feat(joinir): Phase 184 If lowering mainline & JOINIR_IF_TARGETS
...
Establish If lowering infrastructure with dedicated JOINIR_IF_TARGETS
table, separate from loop lowering (JOINIR_TARGETS).
Implementation:
- Add JOINIR_IF_TARGETS table with 6 representative functions
- Add is_if_lowered_function() for table-based lookup
- Update is_if_mainline_target() to use table (SSOT)
- Update is_joinir_if_toplevel_target() with table-first lookup
- Export via join_ir_vm_bridge_dispatch public API
Representative functions:
- IfSelectTest.test/1 (simple return pattern)
- IfSelectLocalTest.main/0 (local variable pattern)
- IfMergeTest.simple_true/0, simple_false/0 (multiple variables)
- JsonShapeToMap._read_value_from_pair/1 (Stage-1 production)
- Stage1JsonScannerBox.value_start_after_key_pos/2 (Stage-B production)
Architecture: Loop/If separation complete (1関数につき1 lowering)
Verification: All representative paths pass with NYASH_JOINIR_DEBUG=1
Phase 184 complete → Phase 185+ ready
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-04 21:58:45 +09:00
79342a8617
feat(method_return_hint): Add TypeOp support for .is()/.as() type inference
...
Phase 83 P3-D 拡張: TypeOp 命令の戻り値型推論を追加。
## 変更内容
- TypeOpKind::Check (.is()) → Bool
- TypeOpKind::Cast (.as()) → 対象型
- ユニットテスト 2 件追加 (test_infer_from_typeop_check, test_infer_from_typeop_cast)
## 成果
- Case D 削減: 20 → 15 (5件削減, 25%)
- Unit tests: 7/7 passed
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-02 18:16:21 +09:00
8ae1eabcfa
feat(lifecycle): Phase 83 P3-D MethodReturnHintBox implementation
...
ChatGPT Pro設計に基づき、既知メソッド戻り値型推論箱(P3-D)を実装。
## 変更内容
- method_return_hint.rs: MethodReturnHintBox 新規作成
- BoxCall/Call のメソッド名から戻り値型を推論
- TypeAnnotationBox と同等のマッピングを適用
- length/size/len → Integer, push → Void, str/substring → String
- lifecycle.rs: P3-D 経路を P3-C の前に挿入
- mod.rs: method_return_hint モジュール登録
## 成果
- Case D 削減: 20 → 16 (4件削減, 20%)
- Unit tests: 5/5 passed
## 設計原則
- 単一責務: P3-D 推論のみ
- TypeAnnotationBox 薄ラップ: 型マッピングの SSOT は TypeAnnotationBox
- 将来移行性: MethodRegistry 導入時も API 不変
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-02 18:09:04 +09:00
93f51e40ae
refactor(joinir): Phase 82 SSOT統一化 - テーブル化とヘルパー抽象化
...
Phase 82: JoinIR関数リストとExecルートの SSOT 統一化
## 変更内容
### 1. JOINIR_TARGETS テーブル統一化
**targets.rs**: vm_bridge_dispatch テーブルが唯一のSSO
- FuncScannerBox.append_defs/2 を Exec に追加
- is_loop_lowered_function() はここから参照
- コメントに Phase 82 SSOT マーク
**mod.rs**: is_loop_lowered_function() 簡素化
- JOINIR_TARGETS テーブルから参照に統一
- Exec/LowerOnly 両方を Loop lowered対象とする
- ハードコード関数リストを削除 ✅
### 2. Exec routes 統一ヘルパー
**exec_routes.rs**: run_generic_joinir_route() 追加
- try_run_skip_ws() / try_run_trim() の共通パターンを抽象化
- 入出力値フォーマッタ、終了コードエキスプレッサをコールバック化
- 後方互換性のため既存関数は保持
- 将来フェーズで統合可能 (#[allow(dead_code)])
## テスト結果
✅ test_is_loop_lowered_function PASS
✅ cargo build --release SUCCESS
## 重複排除の効果
- テーブル重複: ハードコード関数リスト完全排除
- ロジック重複: 統一ヘルパーで28行削減可能(将来)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-02 14:01:44 +09:00
c61f4bc742
feat(joinir): Phase 80 JoinIR Mainline Unification
...
Phase 80: JoinIR 本線化(Core ON 対応)
## 変更内容
### Phase 80-1: SSOT 関数群の追加 (mod.rs)
- `is_loop_mainline_target()`: Loop本線化対象判定
- `is_if_mainline_target()`: If本線化対象判定
- `should_try_joinir_mainline()`: Core ON時の本線試行判定
- `should_panic_on_joinir_failure()`: Strict時のパニック判定
### Phase 80-2: If本線化 (if_form.rs)
- Core ON (`joinir_core_enabled()`) 時に代表関数でJoinIRを本線として試行
- Strict mode (`joinir_strict_enabled()`) でパターン不一致時にパニック
### Phase 80-3: Loop本線化 (vm_bridge_dispatch/mod.rs)
- Core ON 時に本線対象関数でJoinIR VMブリッジを優先試行
- Strict mode で失敗時にパニック
## 対象関数
- Loop: Main.skip/1, FuncScannerBox.trim/1, etc. (6本)
- If: IfSelectTest.*, IfMergeTest.*, JsonShapeToMap.* etc.
## 環境変数
- NYASH_JOINIR_CORE=1: Core ON(本線化有効)
- NYASH_JOINIR_STRICT=1: Strict ON(フォールバック禁止)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-02 13:45:47 +09:00
8633224061
JoinIR/SSA/Stage-3: sync CURRENT_TASK and dev env
2025-12-01 11:10:46 +09:00
a3d5bacc55
Phase 30.1 & 73: Stage-3 features env and JoinIR flag cleanup
2025-11-30 14:30:28 +09:00
2ea0f2a202
Remove Trio boxes and tidy loop scope warnings
2025-11-30 11:46:14 +09:00
375bb66b41
feat(phi_core): Phase 69-4.2 Trio公開面削減方針明文化
...
## 変更内容
### src/mir/phi_core/mod.rs
- Trio Legacy Boxes (3箱) の削除方針をコメント追加
- LoopVarClassBox (578行)
- LoopExitLivenessBox (414行)
- LocalScopeInspectorBox (361行)
- 外部依存2箇所を明記:
1. loop_form_intake.rs (~30行)
2. loop_snapshot_merge.rs (~60行)
- TODO(Phase 70) マーカー設置(削減見込み ~1,443行)
### docs/development/current/main/phase69-4-trio-deletion-plan.md
- Phase 69-4 全体計画文書作成
- Phase 69-4.1: Trio callsite 棚卸し結果記録 ✅
- Phase 69-4.2: phi_core 公開面削減完了記録 ✅
- Phase 69-4.3-5: 未実施タスク整理 ⏳
## Phase 69-4.2 達成内容
**達成**:
- ✅ Trio 削除計画の明文化
- ✅ 外部依存箇所の記録
- ✅ Phase 70 削除条件の TODO 化
**未達成(Phase 70 で実施)**:
- ❌ pub 公開除去(外部依存残存のため継続)
- ❌ phi_core 内部化(LoopScopeShape 移行後に実現)
## 次のステップ
Phase 69-4.3: json_v0_bridge の Trio 依存を LoopScopeShape に寄せる設計
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-30 10:01:49 +09:00
7de192aa6b
feat(mir): Phase 69-3 Fix MIR non-determinism with BTreeSet
...
Replace HashSet with BTreeSet for CFG predecessors/successors:
- BasicBlock.predecessors: HashSet → BTreeSet
- BasicBlock.successors: HashSet → BTreeSet
- LoopFormOps.get_block_predecessors(): returns BTreeSet
- BasicBlock.dominates(): takes &[BTreeSet<BasicBlockId>]
This ensures deterministic PHI generation and test stability.
Test results:
- loop_with_continue_and_break tests: now deterministic (3/3 same output)
- loopform tests: 14/14 PASS (no regressions)
- merge_exit_with_classification tests: 3/3 PASS
Technical changes (6 files):
- basic_block.rs: BTreeSet types + new() initialization
- loopform_builder.rs: trait signature + 2 mock implementations
- phi_ops.rs: return type
- json_v0_bridge/loop_.rs: return type
Same pattern as Phase 25.1 (MirFunction.blocks HashMap → BTreeMap).
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-30 09:38:28 +09:00
58c5d8c9bc
feat(joinir): Phase 66-68 GenericTypeResolver + JoinIR First Chapter Wrap
...
Phase 66: P3-C ジェネリック型推論箱化
- generic_type_resolver.rs 新設 (180行)
- is_generic_method(): ArrayBox.get/pop/first/last, MapBox.get 判定
- resolve_from_phi(): PHI解析によるジェネリック型推論
- TypeHintPolicy::is_p3c_target() 追加
- P1/P2/P3-A/P3-B 以外を P3-C 候補として判定
Phase 67: P3-C 実利用への一歩
- phase67_generic_type_resolver.rs テスト追加 (3テスト)
- lifecycle.rs に P3-C 経路フック追加
- GenericTypeResolver を P3-C 対象関数で優先使用
- A/B テストで旧経路との一致確認 (11 tests PASS)
Phase 68: JoinIR First Chapter Wrap (ドキュメント整理)
- 68-1: phase-30 README.md に Section 9 追加 (JoinIR 第1章完了サマリー)
- 68-2: README.md に JoinIR status セクション追加
- 68-3: CURRENT_TASK.md スリム化 (351→132行, 62%削減)
- 68-4: PHI_BOX_INVENTORY.md に Phase 66-67 完了セクション追加
Phase 69-1: Trio 棚卸し
- phase69-1-trio-inventory.md 作成
- Trio 使用箇所の完全棚卸し完了 (削減見込み 457-707行)
🐱 JoinIR 第1章完了!4つの柱確立:
- Structure (LoopForm)
- Scope (LoopScopeShape)
- JoinIR (Select/IfMerge/Loop)
- Type Hints (P1-P3-C)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-30 08:54:18 +09:00
aef9374b5a
refactor(joinir): LoopScopeShape モジュール箱化
...
## 目的
loop_scope_shape.rs(1274行)を責務別に7ファイルに分割し、
箱理論に基づいた保守性の高い構造に再構成。
## 箱化構造
```
loop_scope_shape/
├── README.md - 責務説明
├── mod.rs - モジュール統合
├── shape.rs - 変数分類のSSOT + 質問系API(Phase 48-4)
├── builder.rs - LoopForm/Trio からの組み立て
├── case_a.rs - Case-A minimal ターゲット判定
├── context.rs - generic_case_a 共通コンテキスト
└── tests.rs - 回帰テスト(13本)
```
## 責務分離
### shape.rs(核心)
- **SSOT**: 変数分類(pinned/carrier/body_local/exit_live)
- **Phase 48-4 API**:
- `get_exit_live()`: LoopExitLivenessBox 代替
- `is_available_in_all()`: LocalScopeInspectorBox 代替
- `variable_definitions`: Phase 48-5+ で統合予定
### builder.rs(組み立て)
- `from_existing_boxes_legacy()`: Trio → LoopScopeShape
- `from_loop_form()`: Phase 48-2 で内部化(Trio 依存削減)
- Case-A ルーティング込み
### case_a.rs(判定)
- `is_case_a_minimal_target()`: Phase 30 F-3.1 ハードコード集合
### context.rs(共通化)
- `CaseAContext`: generic_case_a 共通ロジック
### tests.rs(検証)
- 13本のテスト(Phase 48-4 の2本含む)
- 回帰防止の完全カバレッジ
## Phase 48-4 テスト復活
リファクタリング時に削除された2本のテストを復活:
- `test_is_available_in_all_phase48_4`: 空の variable_definitions
- `test_is_available_in_all_phase48_5_future`: Phase 48-5+ シミュレート
## テスト結果
```
running 13 tests
test test_get_exit_live ... ok
test test_is_available_in_all_phase48_4 ... ok
test test_is_available_in_all_phase48_5_future ... ok
[... 10 other tests ...]
test result: ok. 13 passed; 0 failed
```
## 箱理論の実践
### 箱化の利点
- ✅ 単一責務: shape.rs が SSOT、builder.rs が組み立て
- ✅ 拡張容易: 新しい入力経路は builder.rs に箱追加
- ✅ テスタビリティ: tests.rs で独立検証
- ✅ API安定性: shape.rs の質問系 API が外部インターフェース
### Phase 48-5+ への橋渡し
- shape.rs に Phase 48-4 API が配置済み
- builder.rs で Trio 依存を段階削除可能
- variable_definitions 統合の準備完了
## 修正ファイル
- 削除: `src/mir/join_ir/lowering/loop_scope_shape.rs` (1274行)
- 新規: `src/mir/join_ir/lowering/loop_scope_shape/` (7ファイル)
🎉 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-30 07:14:50 +09:00
b4bb6a3dca
feat(joinir): Phase 48-4 LoopScopeShape Trio質問API統合
...
## 目的
Trio(LoopVarClassBox/LoopExitLivenessBox/LocalScopeInspectorBox)が
答えている「質問」を LoopScopeShape に移し、JoinIR lowering が
LoopScopeShape だけを見るようにする。
## Phase 48-4 実装内容
### 新規フィールド追加
- **variable_definitions**: `BTreeMap<String, BTreeSet<BasicBlockId>>`
- LocalScopeInspectorBox の var_definitions 情報を統合
- Phase 48-4: 空の BTreeMap で初期化(API のみ提供)
- Phase 48-5+: from_existing_boxes_legacy で情報抽出予定
### 新規 API 追加
#### 1. get_exit_live() - exit_live 系 API
```rust
pub fn get_exit_live(&self) -> &BTreeSet<String>
```
- **目的**: LoopExitLivenessBox::compute_live_at_exit() の代替
- **設計**: 「質問だけの薄い箱」原則に基づく
- callsite は `scope.get_exit_live()` という質問形式でアクセス
- フィールド直接参照より API 安定性が高い
#### 2. is_available_in_all() - available 系 API
```rust
pub fn is_available_in_all(&self, var_name: &str, required_blocks: &[BasicBlockId]) -> bool
```
- **目的**: LocalScopeInspectorBox::is_available_in_all() の代替
- **Phase 48-4 実装**: variable_definitions が空のため常に false を返す
- **Phase 48-5+ 計画**: LocalScopeInspectorBox から情報抽出して統合
### from_existing_boxes_legacy 修正
- `variable_definitions` を空で初期化(L503-505)
- return 文に variable_definitions フィールド追加(L519-520)
### テストコード
#### 新規テスト(3本)
1. **test_get_exit_live**: get_exit_live() API の動作確認
2. **test_is_available_in_all_phase48_4**: Phase 48-4(空の variable_definitions)での動作確認
3. **test_is_available_in_all_phase48_5_future**: Phase 48-5+ での統合状態をシミュレート
#### 既存テスト修正
- 3箇所の手動構築箇所に `variable_definitions: BTreeMap::new()` 追加
- test_from_scope_validation_header_eq_exit (L967)
- test_classify_method (L1118)
- test_classify_phi_consistency (L1155)
## テスト結果
```
running 13 tests
test test_get_exit_live ... ok
test test_is_available_in_all_phase48_4 ... ok
test test_is_available_in_all_phase48_5_future ... ok
[... 10 other tests ...]
test result: ok. 13 passed; 0 failed
```
## 箱理論の実践
### 「質問だけの薄い箱」原則
- ✅ Trio の型を知らない形で API を提供
- ✅ callsite が質問形式でアクセス(`scope.get_exit_live()`)
- ✅ 内部実装は段階的に構築(Phase 48-4: API, Phase 48-5+: 実装)
### 段階的移行戦略
- **Phase 48-4**: API のみ提供(variable_definitions 空)
- **Phase 48-5**: JoinIR lowering から Trio を外す
- **Phase 48-6**: Trio を from_existing_boxes_legacy だけに押し込む
## Phase 48-3 棚卸し結果との整合性
Phase 48-3 で洗い出した Trio 使用箇所(P1: 22箇所)のうち、
10箇所の legacy 経路を Phase 48-5+ で段階削除可能に。
## 次のステップ(Phase 48-5)
- JoinIR lowering から Trio を外す
- LoopScopeShape のメソッド呼び出しに差し替え
- variable_definitions に LocalScopeInspectorBox の情報を統合
🎉 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-30 07:03:44 +09:00
74a6f0f93e
feat(joinir): Phase 65.5 TypeHintPolicy箱化モジュール化
...
## 目的
lifecycle.rs の型ヒント判定ロジックを箱化モジュール化し、
単一責務原則に基づいたクリーンなアーキテクチャを実現。
## 主な変更
### 新規ファイル
- **type_hint_policy.rs** (237行): 型ヒントポリシー専用モジュール
- `TypeHintPolicy` 構造体: 型ヒント対象関数の判定
- `is_target()`: P1/P2/P3-A/P3-B 統合判定
- `extract_phi_type_hint()`: PHI から型ヒント抽出
- 7つの単体テスト(パターン別カバレッジ)
### 既存ファイル修正
- **lifecycle.rs**: 60行削減
- `get_phi_type_hint()` 削除 → `TypeHintPolicy::extract_phi_type_hint()` に移行
- `is_type_hint_target()` 削除 → `TypeHintPolicy::is_target()` に移行
- 2箇所の呼び出し箇所を TypeHintPolicy 使用に更新
- **lowering/mod.rs**: type_hint_policy モジュール宣言追加
## 箱化の利点
- ✅ 単一責務:ポリシー判定のみを担当
- ✅ テスト可能:独立した単体テスト(7テスト)
- ✅ 拡張容易:Phase 66+ で P3-C 追加が簡単
- ✅ 可読性向上:関数型スタイル(flat_map/find_map)
## テスト結果
```
running 6 tests
test type_hint_policy::tests::test_is_p1_target ... ok
test type_hint_policy::tests::test_is_p2_target ... ok
test type_hint_policy::tests::test_is_p3a_target ... ok
test type_hint_policy::tests::test_is_p3b_target ... ok
test type_hint_policy::tests::test_is_target ... ok
test type_hint_policy::tests::test_p2_p3a_overlap ... ok
```
## Phase 65 完了状況
- ✅ Phase 65-1: 型マッピング設計文書作成
- ✅ Phase 65-2-A: StringBox メソッド型ヒント実装
- ✅ Phase 65-2-B: Box コンストラクタ型ヒント実装
- ✅ Phase 65-3: lifecycle.rs への P3-A/B 統合
- ✅ Phase 65-4/65-5: 削除条件 5/5 達成、if_phi.rs を P3-C フォールバックに位置づけ
- ✅ Phase 65.5: TypeHintPolicy 箱化モジュール化(今回)
🎉 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-30 06:37:34 +09:00
b4b6a01b92
feat(joinir): Phase 65-2-A StringBox メソッド型ヒント実装
...
Phase 65-2-A 完了:P3-A(StringBox メソッド)型ヒント実装
## 実装内容
### 1. type_inference.rs 新規作成
- `infer_method_return_type()`: StringBox/ArrayBox/MapBox メソッド型推論
- `infer_box_type()`: Box コンストラクタ型推論(Phase 65-2-B 用)
- 8 テスト全て PASS
### 2. JoinInst::MethodCall に type_hint 追加
- `src/mir/join_ir/mod.rs`: `type_hint: Option<MirType>` フィールド追加
- 段階的拡大のため Optional 設計(既存コード破壊なし)
### 3. read_quoted.rs で型ヒント設定
- substring() → String(4箇所)
- length() → Integer(1箇所)
- read_quoted 系関数で完全な型ヒント供給
### 4. 汎用経路は None で後方互換性維持
- expr.rs: 汎用 MethodCall は `type_hint: None`
- convert.rs: 型ヒント追加(Phase 65-3 で活用予定)
- json.rs: JSON シリアライズ対応
## テスト結果
- ✅ type_inference モジュール: 8/8 PASS
- ✅ ビルド: 0 エラー
## 次のステップ
- Phase 65-2-B: Box コンストラクタ型ヒント実装
---
🌟 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-30 06:10:58 +09:00
e669f124d2
feat(joinir): Phase 64-1/2 P2型ヒント実装 & 削減条件準備
...
Phase 64-1: P2/P3 対象関数分類完了
- P2 対象リスト作成: read_quoted_from, IfMerge Simple/Multiple
- P3 将来拡張: MethodCall戻り値型, Box コンストラクタ
- 実装戦略確立: P2から1関数ずつ段階的拡大
Phase 64-2: P2 型ヒント供給実装完了
- read_quoted.rs: ループカウンタ i (Integer), 文字列 ch (String) 型確定
- if_merge.rs: infer_type_from_mir_pattern() 追加 (Const命令から型推論)
- A/B テスト追加: test_p2_if_merge_type_hint() で型ヒント伝播検証 ✅
技術的成果:
- JoinIR MergePair の type_hint 自動推論システム完成
- Phase 63 P1実装パターンを P2 に拡大適用
- 次ステップ: Phase 64-3 lifecycle.rs で P2 hint経路統合
修正ファイル:
- phase-63-joinir-type-info/README.md: Phase 64-1/2 セクション追加
- read_quoted.rs: MergePair 型ヒント追加 (Integer/String)
- if_merge.rs: infer_type_from_mir_pattern() + 型ヒント推論
- mir_joinir_if_select.rs: test_p2_if_merge_type_hint() 追加
🎯 削除条件 4/5 維持 (P1完了), Phase 64-3で P2拡大へ
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-30 05:12:59 +09:00
c6edbaaf3a
feat(mir): Phase 63-6-1/2 MIR Phi type_hint field & JoinIR propagation
...
Phase 63-6-1: MirInstruction::Phi に type_hint フィールド追加
- Added `type_hint: Option<MirType>` field to Phi instruction
- Updated 21 files with type_hint initialization (all set to None for legacy paths)
- Pattern matching updated across codebase (11 files)
- Test code updated (basic_block.rs)
Phase 63-6-2: JoinIR→MIR Bridge で型ヒント伝播実装
- Modified convert.rs: Select → MIR now creates PHI with type_hint
- Removed Copy instructions from then/else blocks
- PHI instruction at merge block receives type_hint from JoinIR Select
- Test verification: ✅ Type hint propagation successful (Some(Integer))
Modified files:
- instruction.rs: Added type_hint field definition
- join_ir_vm_bridge/convert.rs: Select lowering with PHI + type_hint
- 19 other files: type_hint field initialization
Test results:
- ✅ test_type_hint_propagation_simple: Type hint = Some(Integer) confirmed
- ✅ 7/8 if_select tests passing (1 race condition, passes individually)
Next: Phase 63-6-3 (lifecycle.rs で型ヒント使用)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-30 04:35:40 +09:00
8f736358c4
feat(joinir): Phase 63-4 infer_type_from_phi degradation design
...
Phase 63-4: infer_type_from_phi を『JoinIR 型ヒント優先+従来ロジックフォールバック』に縮退する仕様を設計(実装は Phase 63-5+)
## Changes
### Documentation Updates
- **README.md**: Added complete Phase 63-4 design (63-4.1 through 63-4.5)
- 63-4.1: Current state analysis (definition location, callsites, role, JoinIR preparation)
- 63-4.2: Degradation spec (type_hint priority + fallback pattern)
- 63-4.3: Representative cases and A/B testing strategy (P1/P2/P3)
- 63-4.4: Deletion conditions (5 conditions, current: 2/5 = 40%)
- 63-4.5: Phase 63-5 handoff (infer_type_from_phi_with_hint() implementation tasks)
- **PHI_BOX_INVENTORY.md**: Updated if_phi.rs entry with Phase 63-4 deletion plan
- Added: "Phase 63-4完了: infer_type_from_phi の JoinIR type_hint 優先への縮退案を設計(実装は Phase 63-5+)"
- **CURRENT_TASK.md**: Added Phase 63-4 section with summary of design work
## Design Highlights
### Degradation Pattern
```rust
pub fn infer_type_from_phi_with_hint(
function: &MirFunction,
ret_val: ValueId,
types: &BTreeMap<ValueId, MirType>,
type_hint: Option<MirType>,
) -> Option<MirType> {
if let Some(hint) = type_hint {
return Some(hint); // Route B: JoinIR priority (SSOT)
}
infer_type_from_phi(function, ret_val, types) // Route A: Fallback
}
```
### Representative Cases
- **P1**: IfSelectTest.simple/local (Phase 63-5 target)
- **P2**: read_quoted_from (Phase 63-6+ target)
- **P3**: MethodCall/Box constructors (Phase 64+ expansion)
### Deletion Conditions (2/5 achieved)
1. ✅ JoinIR has type_hint field (Phase 63-3)
2. ✅ Type hints populated for representative cases (Phase 63-2)
3. ⏳ Degraded to type_hint priority (Phase 63-5)
4. ⏳ P1 cases determined by type_hint only (Phase 63-5)
5. ⏳ All functions use type hints (Phase 64+)
## Files Changed
- docs/private/roadmap2/phases/phase-63-joinir-type-info/README.md
- docs/private/roadmap2/phases/phase-30-final-joinir-world/PHI_BOX_INVENTORY.md
- CURRENT_TASK.md
## Next Steps
Phase 63-5: Implement degradation for P1 cases (IfSelectTest.simple/local)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-29 17:58:06 +09:00
80ebec2559
feat(joinir): Phase 61-6.2 Delete A/B test observation code (-71 lines)
...
Phase 61-6.2 実装完了: A/B 比較観察コード完全削除
## 変更内容
### if_phi_spec.rs
- ✅ extract_phi_spec_from_builder() 削除(L85-115, 31行)
- ✅ compare_and_log_phi_specs() 削除(L117-140, 24行)
- ✅ 未使用 import 削除(ValueId, BTreeMap)
- ✅ 削除記録コメント追加(L85-91)
- ✅ SSOT 確立: compute_phi_spec_from_joinir() のみが PHI 仕様計算
### if_lowering.rs
- ✅ A/B 比較ブロック削除(L271-295, 25行)
- ✅ 簡潔な削除理由コメント追加(L271-273)
## 削減効果
- **純削減**: -71 行(予想 -50 行を大幅に上回る)
- **SSOT 確立**: JoinIR 経路のみが PHI 計算の責務を持つ
- **観察コード完全削除**: PhiBuilderBox 経路の観察用コード根絶
## テスト結果
- ✅ JoinIR tests 全通過(56 passed)
- ✅ ビルド成功(0 error, 0 warning)
## 技術的成果
- Phase 61-3 で JoinIR 経路が完全動作確認済み
- A/B 比較は完了、観察用コードは不要に
- PhiBuilderBox 経路はフォールバック専用に
## Phase 61-6 総計
- Wave 1: set_if_context 削除(-26 行)
- Wave 2: A/B テスト削除(-71 行)
- **合計削減**: -97 行(予想 -76 行を 27% 上回る成果)
次: Phase 61-7 or Phase 62 (更なる統合・削除)
2025-11-29 16:11:39 +09:00
3194cc1e6c
feat(joinir): Phase 61-4-F ToplevelOps and production path integration
...
Phase 61-4-F: Loop-outside If JoinIR production path
Changes:
- F.1: Add ToplevelOps struct implementing PhiBuilderOps for MirBuilder
- Enables emit_toplevel_phis() to emit PHI instructions via MirBuilder
- Uses insert_phi_at_head_spanned for proper PHI placement
- ~70 lines, thin wrapper following box theory
- F.2: Integrate production path with emit_toplevel_phis
- Replace TODO with actual PHI emission call
- Build IfShape from branch blocks
- Log PHI count on dry-run
- Add IfToplevelTest.* to try_lower_if_to_joinir allowed list
- Fixes function name guard that blocked testing
Note: Pattern matching currently only supports return patterns
(IfMerge/IfSelect). Local variable assignment patterns fall back
to existing PHI generation, which correctly produces valid MIR.
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-29 15:32:40 +09:00
3439de0f65
feat(joinir): Phase 61-4-D/E function guard and toplevel emitter
...
Phase 61-4 追加実装:
1. Phase 61-4-D: 関数名ガード整理
- is_joinir_if_toplevel_target() ヘルパー追加
- IfSelectTest.*, IfToplevelTest.*, IfMergeTest.* 対応
- if_form.rs で関数名チェック統合
2. Phase 61-4-E: emit_toplevel_phis() 追加
- IfInLoopPhiEmitter に toplevel 用メソッド追加
- carrier_names 不要(PhiSpec の全変数を対象)
- HAKO_JOINIR_IF_TOPLEVEL_TRACE でトレース可能
現状:
- dry-run モードでパターンマッチング確認可能
- 本番経路のPHI生成統合は次フェーズ(MirBuilder PHI emit 方式検討必要)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-29 15:15:22 +09:00
b73413566d
feat(joinir): Phase 61-4 loop-outside If JoinIR infrastructure
...
Phase 61-4 ループ外 If の JoinIR 基盤実装:
1. env フラグ追加:
- HAKO_JOINIR_IF_TOPLEVEL: 本番経路有効化
- HAKO_JOINIR_IF_TOPLEVEL_DRYRUN: dry-run モード
2. IfPhiContext 拡張:
- pure_if() コンストラクタ追加(ループ外 if 用)
3. if_form.rs 統合:
- JoinIR 試行コード追加(dry-run対応)
- フォールバック経路維持(既存PHI生成)
現状:
- dry-run モード動作確認済み
- 関数名ガードにより main 関数はスキップ
- 本番経路は未実装(関数名ガード拡張が必要)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-29 15:08:23 +09:00
9037467ac7
feat(joinir): Phase 61-3 IfInLoopPhiEmitter箱実装
...
If-in-loop PHI生成を箱化モジュール化:
## 新規ファイル
- if_in_loop_phi_emitter.rs: IfInLoopPhiEmitter 箱(~250行)
- emit_header_phis(): VarLookup方式でPHI生成
- ユニットテスト2件: basic / same_value
## 変更ファイル
- mod.rs: IfInLoopPhiEmitter モジュール追加・pub use
- if_lowering.rs: Phase 61-3本番経路統合
- HAKO_JOINIR_IF_IN_LOOP_ENABLE=1 で IfInLoopPhiEmitter 使用
- JoinIRパターンマッチ成功時のみ動作
- if_phi_context.rs: unused imports削除
## 箱理論
- IfInLoopPhiEmitter: PHI命令発行に専念(Thin Box)
- VarLookup方式: snapshot lookup + pre_val fallback
- CFG非依存: incoming値はsnapshotから直接取得
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-29 14:39:51 +09:00
f4fb798ec8
feat(joinir): Phase 61-3 devフラグ・if_phi_context拡張準備
...
Phase 61-3(If-in-loop JoinIR本番切り替え)の基盤準備:
- env.rs: joinir_if_in_loop_enable() 追加
- HAKO_JOINIR_IF_IN_LOOP_ENABLE=1 で本番経路有効化
- デフォルトOFF(安全第一)
- if_phi_context.rs: Phase 61-3拡張準備
- BTreeMap, ValueId, BasicBlockId import追加
- ドキュメント更新(incoming値解決メソッド予告)
設計書: docs/private/.../phase61-3-box-design.md(別途)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-29 14:19:53 +09:00
7a1a4bd964
refactor(mir): loop_builder.rs モジュール化 - 6ファイルに分割
...
## リファクタリング内容
### ファイル構造変更
- `src/mir/loop_builder.rs` (1515行) 削除
- `src/mir/loop_builder/` ディレクトリ新設(6ファイル、1529行)
### 新規モジュール構成
1. **mod.rs** (6,293行 → 実際は約150行)
- モジュール定義とre-export
- LoopBuilder構造体定義
2. **loop_form.rs** (25,988行 → 実際は約650行)
- メインループlowering pipeline
- デバッグ/実験フラグ集約
3. **if_lowering.rs** (15,600行 → 実際は約390行)
- In-loop if lowering with JoinIR/PHI bridge
- **Phase 61-2コード完全保持**:
- JoinIR dry-run検証モード
- PhiSpec計算とA/B比較
4. **phi_ops.rs** (12,844行 → 実際は約320行)
- PHI emit helpers
- LoopFormOps/PhiBuilderOps impls
5. **control.rs** (4,261行 → 実際は約107行)
- break/continue capture
- predecessor bookkeeping
6. **statements.rs** (1,673行 → 実際は約42行)
- loop-body statement lowering entry point
7. **README.md** (752行 → 実際は約19行)
- モジュール責務とサブモジュール説明
### 設計原則
- **責務分離**: CFG構築/PHI生成/制御フロー/文処理を分離
- **Phase 61-2保持**: if_lowering.rsにJoinIR dry-run完全移行
- **phi_core委譲**: PHI構築ロジックは`phi_core`に委譲
## テスト結果
- Phase 61-2テスト: ✅ 2/2 PASS(dry-runフラグ、PhiSpec)
- loopformテスト: ✅ 14/14 PASS(退行なし)
- ビルド: ✅ 成功(エラー0件)
## 統計
- **純削減**: -1,521行(25ファイル変更)
- **loop_builder**: 1515行 → 1529行(+14行、6ファイル化)
- **可読性**: 巨大単一ファイル → 責務別モジュール
## ChatGPT設計・Claude確認
大規模リファクタリングをChatGPTが実施、Claudeが検証完了。
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-29 12:44:40 +09:00