ryo-executor 0.2.0

[experimental] Mutation execution engine for RYO - parallel execution, conflict detection, workspace management
Documentation
//! V2 ASTRegApply implementation for LoopToIteratorMutation
//!
//! Converts for loops to iterator chains:
//! - `let mut v = Vec::new(); for x in iter { v.push(f(x)) }` → `let v = iter.map(f).collect()`
//! - `for x in iter { if cond { v.push(x) } }` → `iter.filter(cond).collect()`

use ryo_analysis::SymbolKind;
use ryo_mutations::idiom::LoopToIteratorMutation;
use ryo_mutations::{Mutation, MutationResult};
use ryo_source::pure::{PureImplItem, PureItem};

use crate::engine::{ASTMutationContext, ASTRegApply, ModificationType};

impl ASTRegApply for LoopToIteratorMutation {
    fn apply_to_registry(&self, ctx: &mut ASTMutationContext) -> MutationResult {
        let mut total_changes = 0;

        if let Some(target_id) = self.target_fn {
            // Target function specified: standalone Function only.
            // Methods inside Impl blocks are not handled in scoped mode
            // (pre-existing limitation across all scoped idioms).
            if let Some(PureItem::Fn(f)) = ctx.ast_registry.get_mut(target_id) {
                let changes = self.transform_block(&mut f.body);
                if changes > 0 {
                    ctx.emit_modified(target_id, ModificationType::BodyModified);
                    total_changes += changes;
                }
            }
        } else {
            // Process standalone functions
            let fn_ids: Vec<_> = ctx
                .symbol_registry
                .iter()
                .filter(|(id, _)| {
                    matches!(ctx.symbol_registry.kind(*id), Some(SymbolKind::Function))
                })
                .map(|(id, _)| id)
                .collect();

            for id in fn_ids {
                if let Some(PureItem::Fn(f)) = ctx.ast_registry.get_mut(id) {
                    let changes = self.transform_block(&mut f.body);
                    if changes > 0 {
                        ctx.emit_modified(id, ModificationType::BodyModified);
                        total_changes += changes;
                    }
                }
            }

            // Process impl blocks (methods)
            let impl_ids: Vec<_> = ctx
                .symbol_registry
                .iter()
                .filter(|(id, _)| matches!(ctx.symbol_registry.kind(*id), Some(SymbolKind::Impl)))
                .map(|(id, _)| id)
                .collect();

            for id in impl_ids {
                let mut impl_changes = 0;
                if let Some(PureItem::Impl(imp)) = ctx.ast_registry.get_mut(id) {
                    for impl_item in &mut imp.items {
                        if let PureImplItem::Fn(f) = impl_item {
                            impl_changes += self.transform_block(&mut f.body);
                        }
                    }
                }
                if impl_changes > 0 {
                    ctx.emit_modified(id, ModificationType::BodyModified);
                    total_changes += impl_changes;
                }
            }
        }

        MutationResult {
            mutation_type: self.mutation_type().to_string(),
            changes: total_changes,
            description: if total_changes > 0 {
                format!("Converted {} for loop(s) to iterator chains", total_changes)
            } else {
                "No for loops converted".to_string()
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::ASTMutationEngine;
    use ryo_analysis::testing::ContextBuilder;

    #[test]
    fn test_v2_loop_to_iter_target_fn_scopes_to_target_only() {
        // Boundary regression: target_fn must restrict transform to ONE fn.
        // Pre-fix the converter discarded module_id via `..`, leaking across
        // every fn that contained a convertible for-loop.
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                r#"
fn foo(items: Vec<i32>) -> Vec<i32> {
    let mut result = Vec::new();
    for x in items {
        result.push(x * 2);
    }
    result
}

fn bar(items: Vec<i32>) -> Vec<i32> {
    let mut result = Vec::new();
    for x in items {
        result.push(x + 1);
    }
    result
}
"#,
            )
            .build();

        let foo_id = ctx
            .registry
            .iter()
            .find(|(id, path)| {
                matches!(ctx.registry.kind(*id), Some(SymbolKind::Function)) && path.name() == "foo"
            })
            .map(|(id, _)| id)
            .expect("foo function not found");

        let mutation = LoopToIteratorMutation::new().in_function(foo_id);
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        assert_eq!(result.result.changes, 1, "target_fn must scope to foo only");
    }

    #[test]
    fn test_v2_loop_to_iter_map_collect() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                r#"
fn process(items: Vec<i32>) -> Vec<i32> {
    let mut result = Vec::new();
    for x in items {
        result.push(x * 2);
    }
    result
}
"#,
            )
            .build();

        let mutation = LoopToIteratorMutation::new();
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        assert_eq!(result.result.changes, 1);
    }

    #[test]
    fn test_v2_loop_to_iter_no_changes() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                r#"
fn process(items: Vec<i32>) -> Vec<i32> {
    items.into_iter().map(|x| x * 2).collect()
}
"#,
            )
            .build();

        let mutation = LoopToIteratorMutation::new();
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        assert_eq!(result.result.changes, 0);
    }
}