//! Pattern Router - Table-driven dispatch for loop patterns //! //! Phase 194: Replace if/else chain with table-driven routing //! Phase 193: Modularized feature extraction using ast_feature_extractor module //! //! # Architecture //! //! - Each pattern registers a detect function and a lower function //! - Patterns are tried in priority order (lower = tried first) //! - First matching pattern wins //! - Feature extraction delegated to ast_feature_extractor module //! //! # Adding New Patterns //! //! 1. Create a new module in `patterns/` (e.g., `pattern4_your_name.rs`) //! 2. Implement `pub fn can_lower(ctx: &LoopPatternContext) -> bool` //! 3. Implement `pub fn lower(builder: &mut MirBuilder, ctx: &LoopPatternContext) -> Result, String>` //! 4. Add entry to `LOOP_PATTERNS` table below //! //! That's it! No need to modify routing logic. use crate::ast::ASTNode; use crate::mir::builder::MirBuilder; use crate::mir::ValueId; use crate::mir::loop_pattern_detection::{LoopFeatures, LoopPatternKind}; /// Phase 193: Import AST Feature Extractor Box /// (declared in mod.rs as pub module, import from parent) use super::ast_feature_extractor as ast_features; /// Context passed to pattern detect/lower functions pub struct LoopPatternContext<'a> { /// Loop condition AST node pub condition: &'a ASTNode, /// Loop body statements pub body: &'a [ASTNode], /// Current function name (for routing) pub func_name: &'a str, /// Debug logging enabled pub debug: bool, /// Has continue statement(s) in body? (Phase 194+) pub has_continue: bool, /// Has break statement(s) in body? (Phase 194+) pub has_break: bool, /// Phase 192: Loop features extracted from AST pub features: LoopFeatures, /// Phase 192: Pattern classification based on features pub pattern_kind: LoopPatternKind, } impl<'a> LoopPatternContext<'a> { /// Create new context from routing parameters /// /// Phase 194+: Automatically detects continue/break statements in body /// Phase 192: Extract features and classify pattern from AST /// Phase 193: Feature extraction delegated to ast_feature_extractor module pub fn new( condition: &'a ASTNode, body: &'a [ASTNode], func_name: &'a str, debug: bool, ) -> Self { // Phase 193: Use AST Feature Extractor Box for break/continue detection let has_continue = ast_features::detect_continue_in_body(body); let has_break = ast_features::detect_break_in_body(body); // Phase 193: Extract features using modularized extractor let features = ast_features::extract_features(body, has_continue, has_break); // Phase 192: Classify pattern based on features let pattern_kind = crate::mir::loop_pattern_detection::classify(&features); Self { condition, body, func_name, debug, has_continue, has_break, features, pattern_kind, } } } /// Phase 193: Feature extraction moved to ast_feature_extractor module /// See: src/mir/builder/control_flow/joinir/patterns/ast_feature_extractor.rs /// Entry in the loop pattern router table. /// Each pattern registers a detect function and a lower function. pub struct LoopPatternEntry { /// Human-readable pattern name for debugging pub name: &'static str, /// Priority (lower = tried first). Pattern1=10, Pattern2=20, Pattern3=30 pub priority: u8, /// Detection function: returns true if this pattern matches pub detect: fn(&MirBuilder, &LoopPatternContext) -> bool, /// Lowering function: performs the actual JoinIR generation pub lower: fn(&mut MirBuilder, &LoopPatternContext) -> Result, String>, } /// Static table of all registered loop patterns. /// Patterns are tried in priority order (lowest first). /// /// # Current Patterns (Phase 192: Structure-based detection) /// /// All patterns now use structure-based detection via LoopFeatures and classify(): /// /// - Pattern 4 (priority 5): Loop with Continue (loop_continue_pattern4.hako) /// - Detection: pattern_kind == Pattern4Continue /// - Structure: has_continue && !has_break /// /// - Pattern 3 (priority 30): Loop with If-Else PHI (loop_if_phi.hako) /// - Detection: pattern_kind == Pattern3IfPhi /// - Structure: has_if_else_phi && !has_break && !has_continue /// /// - Pattern 1 (priority 10): Simple While Loop (loop_min_while.hako) /// - Detection: pattern_kind == Pattern1SimpleWhile /// - Structure: !has_break && !has_continue && !has_if_else_phi /// /// - Pattern 2 (priority 20): Loop with Conditional Break (joinir_min_loop.hako) /// - Detection: pattern_kind == Pattern2Break /// - Structure: has_break && !has_continue /// /// Note: func_name is now only used for debug logging, not pattern detection pub static LOOP_PATTERNS: &[LoopPatternEntry] = &[ LoopPatternEntry { name: "Pattern4_WithContinue", priority: 5, // Highest priority - continue is most specific detect: super::pattern4_with_continue::can_lower, lower: super::pattern4_with_continue::lower, }, LoopPatternEntry { name: "Pattern3_WithIfPhi", priority: 30, // NOTE: Pattern 3 must be checked BEFORE Pattern 1 (both use "main") detect: super::pattern3_with_if_phi::can_lower, lower: super::pattern3_with_if_phi::lower, }, LoopPatternEntry { name: "Pattern1_Minimal", priority: 10, detect: super::pattern1_minimal::can_lower, lower: super::pattern1_minimal::lower, }, LoopPatternEntry { name: "Pattern2_WithBreak", priority: 20, detect: super::pattern2_with_break::can_lower, lower: super::pattern2_with_break::lower, }, ]; /// Try all registered patterns in priority order. /// /// Returns Ok(Some(value_id)) if a pattern matched and lowered successfully. /// Returns Ok(None) if no pattern matched. /// Returns Err if a pattern matched but lowering failed. pub fn route_loop_pattern( builder: &mut MirBuilder, ctx: &LoopPatternContext, ) -> Result, String> { use super::super::trace; // Patterns are already sorted by priority in the table // (Pattern 3 with priority 30 comes first, then Pattern 1 with priority 10, etc.) // This ensures Pattern 3 is checked before Pattern 1, avoiding incorrect routing. for entry in LOOP_PATTERNS { if (entry.detect)(builder, ctx) { // Phase 195: Use unified trace for pattern matching trace::trace().pattern("route", entry.name, true); return (entry.lower)(builder, ctx); } } // No pattern matched - return None (caller will handle error) // Phase 187-2: Legacy LoopBuilder removed, all loops must use JoinIR if ctx.debug { trace::trace().debug("route", &format!("No pattern matched for function '{}'", ctx.func_name)); } Ok(None) }