ryo-mutations 0.1.0

[experimental] Code transformation primitives for Rust source code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! ManualMapMutation: Convert manual Option/Result mapping patterns
//!
//! Transforms:
//! - `match opt { Some(x) => Some(f(x)), None => None }` → `opt.map(|x| f(x))`
//! - `if let Some(x) = opt { Some(f(x)) } else { None }` → `opt.map(|x| f(x))`
//!
//! Similar patterns for Result:
//! - `match res { Ok(x) => Ok(f(x)), Err(e) => Err(e) }` → `res.map(|x| f(x))`
//!
//! Corresponds to Clippy lint: `clippy::manual_map`
//!
//! # Note
//!
//! This mutation currently has limited pattern support due to PurePattern
//! not having a TupleStruct variant for patterns like `Some(x)`.
//! Full support requires AST enhancement.

use ryo_source::pure::{
    PureBlock, PureClosureParam, PureExpr, PureMatchArm, PurePattern, PureStmt,
};
use ryo_symbol::SymbolId;

use crate::Mutation;

/// Convert manual Option/Result mapping to .map() method
///
/// # Example
///
/// ```rust,ignore
/// use ryo_mutations::idiom::ManualMapMutation;
///
/// let mutation = ManualMapMutation::new();
/// // Transforms:
/// //   match opt {
/// //       Some(x) => Some(x.to_string()),
/// //       None => None,
/// //   }
/// // Into:
/// //   opt.map(|x| x.to_string())
/// ```
///
/// # Limitations
///
/// Currently only detects patterns where the AST represents `Some(x)` as
/// a Struct pattern with path "Some". Full TupleStruct pattern support
/// is planned for future AST enhancements.
#[derive(Debug, Clone, Default)]
pub struct ManualMapMutation {
    /// Target function SymbolId. If None, applies to all functions.
    pub target_fn: Option<SymbolId>,
}

impl ManualMapMutation {
    pub fn new() -> Self {
        Self::default()
    }

    /// Only apply in a specific function
    pub fn in_function(mut self, id: SymbolId) -> Self {
        self.target_fn = Some(id);
        self
    }

    /// Check if pattern is Some(x) and extract the binding name
    ///
    /// Supports both Struct pattern `Some { 0: x }` (internal representation)
    /// and various other representations of tuple struct patterns.
    fn is_some_pattern(pattern: &PurePattern) -> Option<String> {
        match pattern {
            // Struct pattern: Some { 0: x } (how tuple struct patterns are represented)
            PurePattern::Struct { path, fields, .. } => {
                // Check for "Some" or "Option::Some" or "std::option::Option::Some"
                if (path == "Some" || path.ends_with("::Some")) && fields.len() == 1 {
                    // The field name is "0" for tuple structs
                    if let Some((_, PurePattern::Ident { name, .. })) = fields.first() {
                        return Some(name.clone());
                    }
                }
                None
            }
            _ => None,
        }
    }

    /// Check if pattern is None
    ///
    /// Note: `None` in a match arm is parsed by syn as `Pat::Ident` (not Pat::Path),
    /// so we need to check both Ident and Path variants.
    fn is_none_pattern(pattern: &PurePattern) -> bool {
        match pattern {
            PurePattern::Path(p) => p == "None" || p.ends_with("::None"),
            PurePattern::Ident { name, .. } => name == "None",
            _ => false,
        }
    }

    /// Check if pattern is Ok(x) and extract the binding name
    fn is_ok_pattern(pattern: &PurePattern) -> Option<String> {
        match pattern {
            PurePattern::Struct { path, fields, .. } => {
                if path == "Ok" && fields.len() == 1 {
                    if let (_, PurePattern::Ident { name, .. }) = &fields[0] {
                        return Some(name.clone());
                    }
                }
                None
            }
            _ => None,
        }
    }

    /// Check if pattern is Err(e) and extract the binding name
    fn is_err_pattern(pattern: &PurePattern) -> Option<String> {
        match pattern {
            PurePattern::Struct { path, fields, .. } => {
                if path == "Err" && fields.len() == 1 {
                    if let (_, PurePattern::Ident { name, .. }) = &fields[0] {
                        return Some(name.clone());
                    }
                }
                None
            }
            _ => None,
        }
    }

    /// Check if expression is Some(inner) and extract inner
    fn is_some_expr(expr: &PureExpr) -> Option<&PureExpr> {
        match expr {
            PureExpr::Call { func, args } => {
                if matches!(func.as_ref(), PureExpr::Path(p) if p == "Some" || p.ends_with("::Some"))
                    && args.len() == 1
                {
                    return Some(&args[0]);
                }
                None
            }
            _ => None,
        }
    }

    /// Check if expression is None
    fn is_none_expr(expr: &PureExpr) -> bool {
        matches!(expr, PureExpr::Path(p) if p == "None" || p.ends_with("::None"))
    }

    /// Check if expression is Ok(inner) and extract inner
    fn is_ok_expr(expr: &PureExpr) -> Option<&PureExpr> {
        match expr {
            PureExpr::Call { func, args } => {
                if matches!(func.as_ref(), PureExpr::Path(p) if p == "Ok") && args.len() == 1 {
                    return Some(&args[0]);
                }
                None
            }
            _ => None,
        }
    }

    /// Check if expression is Err(e) where e matches the given name
    fn is_err_passthrough(expr: &PureExpr, err_name: &str) -> bool {
        match expr {
            PureExpr::Call { func, args } => {
                if matches!(func.as_ref(), PureExpr::Path(p) if p == "Err") && args.len() == 1 {
                    return matches!(&args[0], PureExpr::Path(p) if p == err_name);
                }
                false
            }
            _ => false,
        }
    }

    /// Try to convert a match expression to .map() call
    fn try_convert_match(scrutinee: &PureExpr, arms: &[PureMatchArm]) -> Option<PureExpr> {
        if arms.len() != 2 {
            return None;
        }

        // Try Option pattern: Some(x) => Some(f(x)), None => None
        if let Some(var_name) = Self::is_some_pattern(&arms[0].pattern) {
            if Self::is_none_pattern(&arms[1].pattern) && Self::is_none_expr(&arms[1].body) {
                if let Some(inner) = Self::is_some_expr(&arms[0].body) {
                    return Some(Self::create_map_call(
                        scrutinee.clone(),
                        var_name,
                        inner.clone(),
                    ));
                }
            }
        }

        // Try reversed Option pattern: None => None, Some(x) => Some(f(x))
        if Self::is_none_pattern(&arms[0].pattern) && Self::is_none_expr(&arms[0].body) {
            if let Some(var_name) = Self::is_some_pattern(&arms[1].pattern) {
                if let Some(inner) = Self::is_some_expr(&arms[1].body) {
                    return Some(Self::create_map_call(
                        scrutinee.clone(),
                        var_name,
                        inner.clone(),
                    ));
                }
            }
        }

        // Try Result pattern: Ok(x) => Ok(f(x)), Err(e) => Err(e)
        if let Some(ok_var) = Self::is_ok_pattern(&arms[0].pattern) {
            if let Some(err_var) = Self::is_err_pattern(&arms[1].pattern) {
                if Self::is_err_passthrough(&arms[1].body, &err_var) {
                    if let Some(inner) = Self::is_ok_expr(&arms[0].body) {
                        return Some(Self::create_map_call(
                            scrutinee.clone(),
                            ok_var,
                            inner.clone(),
                        ));
                    }
                }
            }
        }

        None
    }

    /// Create a .map(|var| body) call
    fn create_map_call(receiver: PureExpr, var_name: String, body: PureExpr) -> PureExpr {
        PureExpr::MethodCall {
            receiver: Box::new(receiver),
            method: "map".to_string(),
            turbofish: None,
            args: vec![PureExpr::Closure {
                is_async: false,
                is_move: false,
                params: vec![PureClosureParam::untyped(PurePattern::Ident {
                    name: var_name,
                    is_mut: false,
                })],
                ret: None,
                body: Box::new(body),
            }],
        }
    }

    /// Transform expressions, returns changes count
    fn transform_expr(&self, expr: &mut PureExpr) -> usize {
        let mut changes = 0;

        // Check for match pattern
        if let PureExpr::Match {
            expr: scrutinee,
            arms,
        } = expr
        {
            if let Some(map_call) = Self::try_convert_match(scrutinee, arms) {
                *expr = map_call;
                return 1;
            }
        }

        // Note: if let pattern support requires IfLet variant in PureExpr
        // which may not exist. For now, we focus on match expressions.
        // Future: if let Some(x) = opt { Some(f(x)) } else { None } → opt.map(|x| f(x))

        // Recursively transform sub-expressions
        match expr {
            PureExpr::Binary { left, right, .. } => {
                changes += self.transform_expr(left);
                changes += self.transform_expr(right);
            }
            PureExpr::Unary { expr: inner, .. } => {
                changes += self.transform_expr(inner);
            }
            PureExpr::Call { func, args } => {
                changes += self.transform_expr(func);
                for arg in args {
                    changes += self.transform_expr(arg);
                }
            }
            PureExpr::MethodCall { receiver, args, .. } => {
                changes += self.transform_expr(receiver);
                for arg in args {
                    changes += self.transform_expr(arg);
                }
            }
            PureExpr::Block { block, .. } => {
                changes += self.transform_block(block);
            }
            PureExpr::If {
                cond,
                then_branch,
                else_branch,
            } => {
                changes += self.transform_expr(cond);
                changes += self.transform_block(then_branch);
                if let Some(else_expr) = else_branch {
                    changes += self.transform_expr(else_expr);
                }
            }
            PureExpr::Match { expr: e, arms } => {
                changes += self.transform_expr(e);
                for arm in arms {
                    changes += self.transform_expr(&mut arm.body);
                }
            }
            PureExpr::Loop { body: block, .. } | PureExpr::While { body: block, .. } => {
                changes += self.transform_block(block);
            }
            PureExpr::For {
                expr: iter_expr,
                body,
                ..
            } => {
                changes += self.transform_expr(iter_expr);
                changes += self.transform_block(body);
            }
            PureExpr::Closure { body, .. } => {
                changes += self.transform_expr(body);
            }
            _ => {}
        }

        changes
    }

    pub fn transform_block(&self, block: &mut PureBlock) -> usize {
        let mut changes = 0;
        for stmt in &mut block.stmts {
            changes += self.transform_stmt(stmt);
        }
        changes
    }

    fn transform_stmt(&self, stmt: &mut PureStmt) -> usize {
        match stmt {
            PureStmt::Local { init: Some(e), .. } => self.transform_expr(e),
            PureStmt::Semi(e) | PureStmt::Expr(e) => self.transform_expr(e),
            _ => 0,
        }
    }
}

impl Mutation for ManualMapMutation {
    fn describe(&self) -> String {
        "Convert manual Option/Result map patterns to .map()".to_string()
    }

    fn mutation_type(&self) -> &'static str {
        "ManualMap"
    }

    fn box_clone(&self) -> Box<dyn Mutation> {
        Box::new(self.clone())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_is_some_pattern_struct() {
        // PurePattern::Struct is used to represent Some(x) patterns
        let pattern = PurePattern::Struct {
            path: "Some".to_string(),
            fields: vec![(
                "0".to_string(),
                PurePattern::Ident {
                    name: "x".to_string(),
                    is_mut: false,
                },
            )],
            rest: false,
        };
        assert_eq!(
            ManualMapMutation::is_some_pattern(&pattern),
            Some("x".to_string())
        );
    }

    #[test]
    fn test_is_none_pattern() {
        let pattern = PurePattern::Path("None".to_string());
        assert!(ManualMapMutation::is_none_pattern(&pattern));
    }

    #[test]
    fn test_is_some_expr() {
        let expr = PureExpr::Call {
            func: Box::new(PureExpr::Path("Some".to_string())),
            args: vec![PureExpr::Path("value".to_string())],
        };
        assert!(ManualMapMutation::is_some_expr(&expr).is_some());
    }

    #[test]
    fn test_is_none_expr() {
        let expr = PureExpr::Path("None".to_string());
        assert!(ManualMapMutation::is_none_expr(&expr));
    }

    #[test]
    fn test_try_convert_match_option() {
        let scrutinee = PureExpr::Path("opt".to_string());
        let arms = vec![
            PureMatchArm {
                pattern: PurePattern::Struct {
                    path: "Some".to_string(),
                    fields: vec![(
                        "0".to_string(),
                        PurePattern::Ident {
                            name: "x".to_string(),
                            is_mut: false,
                        },
                    )],
                    rest: false,
                },
                guard: None,
                body: PureExpr::Call {
                    func: Box::new(PureExpr::Path("Some".to_string())),
                    args: vec![PureExpr::Binary {
                        op: "+".to_string(),
                        left: Box::new(PureExpr::Path("x".to_string())),
                        right: Box::new(PureExpr::Lit("1".to_string())),
                    }],
                },
            },
            PureMatchArm {
                pattern: PurePattern::Path("None".to_string()),
                guard: None,
                body: PureExpr::Path("None".to_string()),
            },
        ];

        let result = ManualMapMutation::try_convert_match(&scrutinee, &arms);
        assert!(result.is_some());

        if let Some(PureExpr::MethodCall { method, .. }) = result {
            assert_eq!(method, "map");
        } else {
            panic!("Expected MethodCall");
        }
    }
}