Files
hakorune/src/mir/builder/control_flow/joinir/merge/mod.rs

58 lines
2.5 KiB
Rust
Raw Normal View History

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
//! JoinIR MIR Block Merging Coordinator
//!
//! This module coordinates the merging of JoinIR-generated MIR functions
//! into the host MIR builder. The process is broken into 6 phases:
//!
//! 1. Block ID allocation (block_allocator.rs)
//! 2. Value collection (value_collector.rs)
//! 3. ValueId remapping (uses JoinIrIdRemapper)
//! 4. Instruction rewriting (instruction_rewriter.rs)
//! 5. Exit PHI construction (exit_phi_builder.rs)
//! 6. Boundary reconnection (coordinator.rs)
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
//!
//! Phase 4 Refactoring: Breaking down 714-line merge_joinir_mir_blocks() into focused modules
mod block_allocator;
refactor(phase284): P1 SSOT Consolidation - Block Remapper & Return Emitter ## Summary Refactored Phase 284 P1 codebase to consolidate scattered logic into SSOT (Single Source of Truth) modules, improving maintainability and enabling Pattern4/5 code reuse. ## New Modules ### 1. Block Remapper SSOT **File**: `src/mir/builder/control_flow/joinir/merge/block_remapper.rs` (152 lines) - **Purpose**: Consolidate block ID remapping logic (Phase 284 P1 fix) - **Function**: `remap_block_id(block_id, local_block_map, skipped_entry_redirects)` - **Rule**: local_block_map priority > skipped_entry_redirects (prevents ID collision) - **Tests**: 4 unit tests (priority cascade, collision handling, etc.) ### 2. Return Jump Emitter **File**: `src/mir/join_ir/lowering/return_jump_emitter.rs` (354 lines) - **Purpose**: Reusable return handling helper for Pattern4/5 - **Function**: `emit_return_conditional_jump(loop_step_func, return_info, k_return_id, ...)` - **Scope**: P1 - unconditional return + conditional (loop_var == N) only - **Tests**: 3 unit tests (unconditional, no return, conditional) ## Modified Files **merge/instruction_rewriter.rs** (-15 lines): - Replaced inline block remapping with `remap_block_id()` call - Cleaner Branch remap logic **merge/rewriter/terminator.rs** (-43 lines): - Delegates remap_jump/remap_branch to block_remapper SSOT - Simplified duplicate logic **lowering/loop_with_continue_minimal.rs** (-108 lines): - Replaced ~100 line return handling with `emit_return_conditional_jump()` call - Extracted helper functions to return_jump_emitter.rs - Line reduction: 57% decrease in function complexity **merge/mod.rs, lowering/mod.rs**: - Added new module exports (block_remapper, return_jump_emitter) **phase-284/README.md**: - Updated completion status (P1 Complete + Refactored) - Added SSOT consolidation notes - Documented module architecture ## Code Quality Improvements | Metric | Before | After | Change | |--------|--------|-------|--------| | Duplicate block remap logic | 2 places | SSOT | -15 lines | | Return handling code | inline (100L) | helper call | -99 lines | | Testability | Limited | Unit tests (7) | +7 tests | | Module cohesion | Low (scattered) | High (consolidated) | Better | ## Testing ✅ Build: Success (cargo build --release) ✅ Smoke tests: All pass (46 PASS, 1 pre-existing FAIL) ✅ Regression: Zero ✅ Unit tests: 7 new tests added ## Future Benefits 1. **Pattern5 Reuse**: Direct use of `emit_return_conditional_jump()` helper 2. **Phase 285 (P2)**: Nested if/loop returns via same infrastructure 3. **Maintainability**: SSOT reduces debugging surface area 4. **Clarity**: Each module has single responsibility ## Architectural Notes **Block Remapper SSOT Rule**: ``` remap_block_id(id, local_block_map, skipped_entry_redirects): 1. Check local_block_map (function-local priority) 2. Fall back to skipped_entry_redirects (global redirects) 3. Return original if not found ``` Prevents function-local block ID collisions with global remap entries. **Return Emitter Pattern**: ``` emit_return_conditional_jump(func, return_info, k_return_id, alloc_value): - Pattern1-5: All use same infrastructure - P1 scope: top-level return only (nested if/loop → P2) - Returns: JoinInst::Jump(cont=k_return, cond=Some(return_cond)) ``` 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2025-12-23 14:37:01 +09:00
mod block_remapper; // Phase 284 P1: Block ID remap SSOT
mod boundary_carrier_layout; // Phase 29af P3: Carrier order SSOT
mod boundary_logging; // Phase 287 P0.5: Boundary logging consolidation
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
mod carrier_init_builder;
mod config;
mod coordinator;
mod dev_log; // Phase 29ae: Dev logging SSOT
pub(super) mod contract_checks; // Phase 256 P1.5-DBG: Exposed for patterns to access verify_boundary_entry_params
refactor(joinir): Split contract_checks.rs into 2 files (Phase 286C-4.3) Split 1,239-line contract_checks.rs into responsibility-based modules for better maintainability and clarity. ## Changes 1. **New file: debug_assertions.rs** (440 lines) - 6 debug-only verification functions (panic! on violation) - All functions guarded with #[cfg(debug_assertions)] - Excluded from release builds - Functions: * verify_loop_header_phis() * verify_exit_line() * verify_exit_phi_no_collision() * verify_valueid_regions() * verify_condition_bindings_consistent() * verify_header_phi_dsts_not_redefined() 2. **Updated: contract_checks.rs** (1,239 → 848 lines, -391 lines) - Kept 6 Fail-Fast functions (Result<(), String>) - Kept all 13 unit tests - Removed debug-only functions and imports 3. **Updated: mod.rs** - Added `mod debug_assertions;` declaration ## Responsibility Split - **contract_checks.rs**: Fail-Fast contracts (production) - Return errors with diagnostic messages - Run in both debug and release builds - **debug_assertions.rs**: Debug-only assertions (development) - Panic on contract violations - Excluded from release builds (#[cfg(debug_assertions)]) ## Benefits - Single Responsibility Principle (each file <850 lines) - Clear separation: Fail-Fast vs Debug-only - Improved maintainability (localized changes) - Better build performance (debug code stripped in release) ## Test Results - ✅ Build: 0 errors - ✅ Smoke tests: 45/46 PASS (no regression) - ❌ core_direct_array_oob_set_rc_vm: FAIL (existing known issue) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-25 06:08:46 +09:00
mod debug_assertions; // Phase 286C-4.3: Debug-only assertions (split from contract_checks)
mod entry_selector; // Phase 287 P0.3: Entry function selection (SSOT)
pub mod exit_args_collector; // Phase 118: Exit args collection box
mod header_phi_prebuild; // Phase 287 P0.4: Loop header PHI pre-build orchestration
mod header_pred_policy; // Phase 29ae P1: Header pred SSOT
pub mod exit_line;
mod exit_phi_builder;
mod expr_result_resolver;
mod instruction_rewriter; // Phase 260 P0.1: Keep for gradual migration
mod rewriter; // Phase 260 P0.1: New modularized rewriter (forwards to instruction_rewriter)
mod loop_header_phi_builder;
mod loop_header_phi_info;
mod merge_result;
mod phi_block_remapper; // Phase 94: Phi block-id remap box
mod tail_call_classifier;
mod tail_call_lowering_policy; // Phase 131 Task 2: k_exit exit edge normalization
mod value_collector;
mod value_remapper; // Phase 287 P0.2: ValueId remapping helper
#[cfg(test)]
mod tests; // Phase 132-R0 Task 3: Continuation contract tests
use crate::mir::builder::control_flow::joinir::trace;
// Phase 33-17: Re-export for use by other modules
pub use loop_header_phi_builder::LoopHeaderPhiBuilder;
pub use loop_header_phi_info::LoopHeaderPhiInfo;
// Phase 131 P1 Task 1: Re-export MergeContracts for SSOT visibility
#[allow(unused_imports)]
pub use merge_result::MergeContracts;
// Phase 131 P1 Task 6: MergeConfig is defined in config.rs (re-exported here)
#[allow(unused_imports)]
pub use config::MergeConfig;
pub(in crate::mir::builder) use coordinator::merge_joinir_mir_blocks;