ryo_executor/engine/impls/
match_to_if_let.rs1use ryo_analysis::SymbolKind;
7use ryo_mutations::idiom::MatchToIfLetMutation;
8use ryo_mutations::{Mutation, MutationResult};
9use ryo_source::pure::{PureImplItem, PureItem};
10
11use crate::engine::{ASTMutationContext, ASTRegApply, ModificationType};
12
13impl ASTRegApply for MatchToIfLetMutation {
14 fn apply_to_registry(&self, ctx: &mut ASTMutationContext) -> MutationResult {
15 let mut total_changes = 0;
16
17 if let Some(target_id) = self.target_fn {
18 if let Some(PureItem::Fn(f)) = ctx.ast_registry.get_mut(target_id) {
20 let changes = self.transform_block(&mut f.body);
21 if changes > 0 {
22 ctx.emit_modified(target_id, ModificationType::BodyModified);
23 total_changes += changes;
24 }
25 }
26 } else {
27 let fn_ids: Vec<_> = ctx
29 .symbol_registry
30 .iter()
31 .filter(|(id, _)| {
32 matches!(ctx.symbol_registry.kind(*id), Some(SymbolKind::Function))
33 })
34 .map(|(id, _)| id)
35 .collect();
36
37 for id in fn_ids {
38 if let Some(PureItem::Fn(f)) = ctx.ast_registry.get_mut(id) {
39 let changes = self.transform_block(&mut f.body);
40 if changes > 0 {
41 ctx.emit_modified(id, ModificationType::BodyModified);
42 total_changes += changes;
43 }
44 }
45 }
46
47 let impl_ids: Vec<_> = ctx
49 .symbol_registry
50 .iter()
51 .filter(|(id, _)| matches!(ctx.symbol_registry.kind(*id), Some(SymbolKind::Impl)))
52 .map(|(id, _)| id)
53 .collect();
54
55 for id in impl_ids {
56 let mut impl_changes = 0;
57 if let Some(PureItem::Impl(imp)) = ctx.ast_registry.get_mut(id) {
58 for impl_item in &mut imp.items {
59 if let PureImplItem::Fn(f) = impl_item {
60 impl_changes += self.transform_block(&mut f.body);
61 }
62 }
63 }
64 if impl_changes > 0 {
65 ctx.emit_modified(id, ModificationType::BodyModified);
66 total_changes += impl_changes;
67 }
68 }
69 }
70
71 MutationResult {
72 mutation_type: self.mutation_type().to_string(),
73 changes: total_changes,
74 description: if total_changes > 0 {
75 format!("Converted {} match(es) to if let", total_changes)
76 } else {
77 "No matches converted to if let".to_string()
78 },
79 }
80 }
81}
82
83#[cfg(test)]
84mod tests {
85 use super::*;
86 use crate::engine::ASTMutationEngine;
87 use ryo_analysis::testing::ContextBuilder;
88
89 #[test]
90 fn test_v2_match_to_if_let_no_changes() {
91 let mut ctx = ContextBuilder::new()
93 .with_file(
94 "src/lib.rs",
95 r#"
96fn process(opt: Option<i32>) {
97 if let Some(x) = opt {
98 println!("{}", x);
99 }
100}
101"#,
102 )
103 .build();
104
105 let mutation = MatchToIfLetMutation::new();
106 let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);
107
108 assert_eq!(result.result.changes, 0);
109 }
110}