Files
hakorune/src/mir/join_ir/lowering/loop_pattern_router.rs
nyash-codex adccfe5a4e refactor(joinir): Phase 33-12 Large module modularization complete
Task 1: Split mod.rs into if/loop routers
- Created if_lowering_router.rs (172 lines): If-expression routing
- Created loop_pattern_router.rs (149 lines): Loop pattern routing
- Refactored mod.rs (511 → 221 lines): Thin re-export module

Task 2: Modularize loop_patterns per-pattern
- Created loop_patterns/ directory with 4 pattern files:
  - simple_while.rs (225 lines): Pattern 1 implementation
  - with_break.rs (129 lines): Pattern 2 implementation
  - with_if_phi.rs (123 lines): Pattern 3 implementation
  - with_continue.rs (129 lines): Pattern 4 stub
- Created mod.rs (178 lines): Dispatcher + shared utilities
- Removed old loop_patterns.rs (735 lines → directory)

Line count changes:
- mod.rs: 511 → 221 lines (57% reduction)
- loop_patterns: 735 → 784 lines (modularized)
- Total: Net +80 lines for better organization

Benefits:
- Single responsibility per file
- Clear pattern boundaries
- Improved testability
- Better maintainability
- Backward compatibility maintained

Testing:
- cargo build --release:  Success (0 errors)
- Regression test:  Pass (RC: 0)
2025-12-07 03:26:23 +09:00

150 lines
5.8 KiB
Rust

//! Phase 33-12: Loop Pattern JoinIR Lowering Router
//!
//! Routes loop patterns to appropriate JoinIR lowering strategies
//! (Pattern 1-4: simple while, break, if+phi, continue)
//!
//! # Routing Strategy
//!
//! This router uses structure-based pattern classification (Phase 194):
//! 1. Extract CFG features from LoopForm
//! 2. Classify into pattern kind (1-4 or Unknown)
//! 3. Route to appropriate pattern lowerer
//!
//! # Pattern Priority (Phase 188)
//!
//! Patterns are tried in complexity order:
//! - **Pattern 4: Continue** (highest complexity)
//! - **Pattern 3: If-Else PHI** (leverages If lowering)
//! - **Pattern 2: Break** (medium complexity)
//! - **Pattern 1: Simple While** (foundational, easiest)
//!
//! # Integration Points
//!
//! Called from:
//! - `loop_to_join.rs::LoopToJoinLowerer::lower_loop()`
//! - `loop_form_intake.rs::handle_loop_form()`
use crate::mir::join_ir::JoinInst;
use crate::mir::loop_form::LoopForm;
/// Phase 188: Try to lower loop to JoinIR using pattern-based approach
///
/// This function routes loop lowering to specific pattern handlers based on
/// loop structure characteristics. It tries patterns in order of complexity:
///
/// 1. **Pattern 1: Simple While** (foundational, easiest)
/// 2. **Pattern 2: Break** (medium complexity)
/// 3. **Pattern 3: If-Else PHI** (leverages existing If lowering)
/// 4. **Pattern 4: Continue** (highest complexity)
///
/// # Arguments
///
/// * `loop_form` - The loop structure to lower
/// * `lowerer` - The LoopToJoinLowerer builder (provides ValueId allocation, etc.)
///
/// # Returns
///
/// * `Some(JoinInst)` - Successfully lowered to JoinIR
/// * `None` - No pattern matched (fallback to existing lowering)
///
/// # Pattern Selection Strategy
///
/// Patterns are tried sequentially. First matching pattern wins.
/// If no pattern matches, returns `None` to trigger fallback.
///
/// ## Pattern 1: Simple While Loop
/// - **Condition**: Empty break/continue targets, single latch
/// - **Handler**: `loop_patterns::lower_simple_while_to_joinir()`
/// - **Priority**: First (most common, simplest)
///
/// ## Pattern 2: Loop with Conditional Break
/// - **Condition**: Non-empty break_targets, exactly 1 break
/// - **Handler**: `loop_patterns::lower_loop_with_break_to_joinir()`
/// - **Priority**: Second (common, medium complexity)
///
/// ## Pattern 3: Loop with If-Else PHI
/// - **Condition**: Empty break/continue, if-else in body
/// - **Handler**: `loop_patterns::lower_loop_with_conditional_phi_to_joinir()`
/// - **Priority**: Third (reuses If lowering infrastructure)
///
/// ## Pattern 4: Loop with Continue
/// - **Condition**: Non-empty continue_targets
/// - **Handler**: `loop_patterns::lower_loop_with_continue_to_joinir()`
/// - **Priority**: Fourth (most complex)
///
/// # Integration Point
///
/// This function should be called from loop lowering entry points:
/// - `loop_to_join.rs::LoopToJoinLowerer::lower_loop()`
/// - `loop_form_intake.rs::handle_loop_form()`
///
/// # Example Usage
///
/// ```rust,ignore
/// use crate::mir::join_ir::lowering::try_lower_loop_pattern_to_joinir;
///
/// // In loop lowering entry point:
/// if let Some(joinir_inst) = try_lower_loop_pattern_to_joinir(&loop_form, &mut lowerer) {
/// // Pattern matched, use JoinIR
/// return Some(joinir_inst);
/// }
/// // No pattern matched, use existing lowering
/// existing_loop_lowering(&loop_form, &mut lowerer)
/// ```
///
/// # Reference
///
/// See design.md for complete pattern specifications and transformation rules:
/// `docs/private/roadmap2/phases/phase-188-joinir-loop-pattern-expansion/design.md`
pub fn try_lower_loop_pattern_to_joinir(
loop_form: &LoopForm,
lowerer: &mut crate::mir::join_ir::lowering::LoopToJoinLowerer,
) -> Option<JoinInst> {
// Phase 194: Structure-based pattern classification
// Tries patterns based on CFG structure, not function names
use crate::mir::loop_pattern_detection::{classify, extract_features, LoopPatternKind};
// Step 1: Extract features from LoopForm (no LoopScope needed for now)
let features = extract_features(loop_form, None);
// Step 2: Classify pattern based on structure
let pattern = classify(&features);
// Step 3: Route to appropriate lowerer based on pattern
match pattern {
LoopPatternKind::Pattern4Continue => {
if let Some(inst) = super::loop_patterns::lower_loop_with_continue_to_joinir(loop_form, lowerer) {
eprintln!("[try_lower_loop_pattern] ✅ Pattern 4 (Continue) matched");
return Some(inst);
}
}
LoopPatternKind::Pattern3IfPhi => {
if let Some(inst) = super::loop_patterns::lower_loop_with_conditional_phi_to_joinir(loop_form, lowerer) {
eprintln!("[try_lower_loop_pattern] ✅ Pattern 3 (If-Else PHI) matched");
return Some(inst);
}
}
LoopPatternKind::Pattern2Break => {
if let Some(inst) = super::loop_patterns::lower_loop_with_break_to_joinir(loop_form, lowerer) {
eprintln!("[try_lower_loop_pattern] ✅ Pattern 2 (Break) matched");
return Some(inst);
}
}
LoopPatternKind::Pattern1SimpleWhile => {
if let Some(inst) = super::loop_patterns::lower_simple_while_to_joinir(loop_form, lowerer) {
eprintln!("[try_lower_loop_pattern] ✅ Pattern 1 (Simple While) matched");
return Some(inst);
}
}
LoopPatternKind::Unknown => {
eprintln!("[try_lower_loop_pattern] ❌ Unknown pattern, fallback to existing lowering");
}
}
// No Pattern Matched (fallback to existing lowering)
// ===================================================
eprintln!("[try_lower_loop_pattern] ❌ Pattern lowering failed, fallback to existing lowering");
None
}