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
442
443
444
445
446
447
448
449
450
451
452
453
//! Lock Optimization Mutations
//!
//! Performance and safety mutations for lock usage:
//!
//! - `UseAtomicMutation`: Replace Mutex with atomic types for simple fields
//! - `UseRwLockMutation`: Replace Mutex with RwLock for read-heavy access
//! - `LockScopeMutation`: Detect locks held across await points
//!
//! # Note
//!
//! These mutations currently only detect opportunities. The actual refactoring
//! is not yet implemented (TODO).

use ryo_source::pure::{PureFields, PureFile, PureItem, PureType};
use ryo_symbol::SymbolId;

use super::detect::{Detect, DetectCategory, DetectLocation, DetectOperation, DetectOpportunity};
use crate::Mutation;

// ============================================================================
// UseAtomicMutation
// ============================================================================

/// Suggests replacing Mutex<T> with atomic types for simple counter/flag fields.
///
/// Detection: Fields protected by Mutex that could use AtomicUsize, AtomicBool, etc.
///
/// # Example
///
/// ```rust,ignore
/// // Before
/// struct Counter {
///     count: Mutex<usize>,
///     is_ready: Mutex<bool>,
/// }
///
/// // After (suggested)
/// struct Counter {
///     count: AtomicUsize,
///     is_ready: AtomicBool,
/// }
/// ```
#[derive(Debug, Clone, Default)]
pub struct UseAtomicMutation {
    /// Only apply to specific struct
    pub target_struct: Option<String>,
}

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

    /// Only apply to a specific struct
    pub fn for_struct(mut self, name: impl Into<String>) -> Self {
        self.target_struct = Some(name.into());
        self
    }

    /// Check if field name suggests atomic usage
    fn is_atomic_candidate(field_name: &str) -> Option<&'static str> {
        let lower = field_name.to_lowercase();

        // Counter-like
        if lower.contains("count")
            || lower.contains("counter")
            || lower.contains("num")
            || lower.contains("total")
            || lower.contains("size")
            || lower.contains("len")
        {
            return Some("AtomicUsize");
        }

        // Flag-like
        if lower.contains("flag")
            || lower.contains("enabled")
            || lower.contains("active")
            || lower.contains("ready")
            || lower.contains("done")
            || lower.starts_with("is_")
        {
            return Some("AtomicBool");
        }

        // ID-like
        if lower.contains("id") || lower.contains("index") || lower.contains("seq") {
            return Some("AtomicU64");
        }

        None
    }

    /// Detect atomic opportunities in a file
    fn detect_opportunities(&self, file: &PureFile) -> Vec<AtomicOpportunity> {
        let mut opportunities = Vec::new();

        for item in &file.items {
            if let PureItem::Struct(s) = item {
                // Apply target filter
                if let Some(ref target) = self.target_struct {
                    if &s.name != target {
                        continue;
                    }
                }

                if let PureFields::Named(fields) = &s.fields {
                    for field in fields {
                        let type_str = match &field.ty {
                            PureType::Path(p) => p.as_str(),
                            _ => continue,
                        };

                        if type_str.contains("Mutex<") {
                            if let Some(atomic_type) = Self::is_atomic_candidate(&field.name) {
                                opportunities.push(AtomicOpportunity {
                                    struct_name: s.name.clone(),
                                    field_name: field.name.clone(),
                                    suggested_type: atomic_type.to_string(),
                                });
                            }
                        }
                    }
                }
            }
        }

        opportunities
    }
}

#[derive(Debug)]
struct AtomicOpportunity {
    struct_name: String,
    field_name: String,
    suggested_type: String,
}

impl Mutation for UseAtomicMutation {
    fn describe(&self) -> String {
        "Replace Mutex<T> with atomic types for simple counter/flag fields".to_string()
    }

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

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

impl Detect for UseAtomicMutation {
    fn detect(&self, file: &PureFile) -> Vec<DetectOpportunity> {
        self.detect_opportunities(file)
            .into_iter()
            .map(|o| {
                DetectOpportunity::new(
                    DetectLocation::struct_item(&o.struct_name),
                    format!(
                        "Consider using {} for field '{}' instead of Mutex",
                        o.suggested_type, o.field_name
                    ),
                )
                .with_operations(vec![DetectOperation::Refactor])
                .with_confidence(0.7)
                .with_context(format!(
                    "field:{},suggested:{}",
                    o.field_name, o.suggested_type
                ))
            })
            .collect()
    }

    fn category(&self) -> DetectCategory {
        DetectCategory::Performance
    }

    fn detect_name(&self) -> &'static str {
        "UseAtomic"
    }

    fn detect_description(&self) -> &str {
        "Replace Mutex<T> with atomic types for simple counter/flag fields"
    }
}

// ============================================================================
// UseRwLockMutation
// ============================================================================

/// Suggests replacing Mutex with RwLock for read-heavy access patterns.
///
/// Detection: Mutex fields with collections (HashMap, Vec, etc.) that are
/// typically read more often than written.
///
/// # Example
///
/// ```rust,ignore
/// // Before
/// struct Cache {
///     data: Mutex<HashMap<String, Value>>,
/// }
///
/// // After (suggested)
/// struct Cache {
///     data: RwLock<HashMap<String, Value>>,
/// }
/// ```
#[derive(Debug, Clone, Default)]
pub struct UseRwLockMutation {
    /// Only apply to specific struct
    pub target_struct: Option<String>,
}

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

    /// Only apply to a specific struct
    pub fn for_struct(mut self, name: impl Into<String>) -> Self {
        self.target_struct = Some(name.into());
        self
    }

    /// Detect RwLock opportunities in a file
    fn detect_opportunities(&self, file: &PureFile) -> Vec<RwLockOpportunity> {
        let mut opportunities = Vec::new();

        for item in &file.items {
            if let PureItem::Struct(s) = item {
                // Apply target filter
                if let Some(ref target) = self.target_struct {
                    if &s.name != target {
                        continue;
                    }
                }

                if let PureFields::Named(fields) = &s.fields {
                    for field in fields {
                        let type_str = match &field.ty {
                            PureType::Path(p) => p.as_str(),
                            _ => continue,
                        };

                        // Check for Mutex<Collection> patterns
                        if type_str.contains("Mutex<")
                            && (type_str.contains("HashMap")
                                || type_str.contains("BTreeMap")
                                || type_str.contains("Vec<")
                                || type_str.contains("HashSet")
                                || field.name.to_lowercase().contains("cache")
                                || field.name.to_lowercase().contains("registry")
                                || field.name.to_lowercase().contains("store"))
                        {
                            opportunities.push(RwLockOpportunity {
                                struct_name: s.name.clone(),
                                field_name: field.name.clone(),
                            });
                        }
                    }
                }
            }
        }

        opportunities
    }
}

#[derive(Debug)]
struct RwLockOpportunity {
    struct_name: String,
    field_name: String,
}

impl Mutation for UseRwLockMutation {
    fn describe(&self) -> String {
        "Replace Mutex with RwLock for read-heavy data structures".to_string()
    }

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

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

impl Detect for UseRwLockMutation {
    fn detect(&self, file: &PureFile) -> Vec<DetectOpportunity> {
        self.detect_opportunities(file)
            .into_iter()
            .map(|o| {
                DetectOpportunity::new(
                    DetectLocation::struct_item(&o.struct_name),
                    format!(
                        "Consider using RwLock for field '{}' if reads outnumber writes",
                        o.field_name
                    ),
                )
                .with_operations(vec![DetectOperation::Refactor])
                .with_confidence(0.5)
                .with_context(format!("field:{}", o.field_name))
            })
            .collect()
    }

    fn category(&self) -> DetectCategory {
        DetectCategory::Performance
    }

    fn detect_name(&self) -> &'static str {
        "UseRwLock"
    }

    fn detect_description(&self) -> &str {
        "Replace Mutex with RwLock for read-heavy data structures"
    }
}

// ============================================================================
// LockScopeMutation
// ============================================================================

/// Detects locks held across await points or with unnecessarily wide scope.
///
/// This is a safety pattern that helps prevent deadlocks and improves
/// concurrency by reducing lock hold times.
///
/// # Example
///
/// ```rust,ignore
/// // Problematic: lock held across await
/// async fn bad() {
///     let guard = self.data.lock().unwrap();
///     some_async_operation().await; // Lock still held!
///     drop(guard);
/// }
///
/// // Better: release lock before await
/// async fn good() {
///     let value = {
///         let guard = self.data.lock().unwrap();
///         guard.clone()
///     }; // Lock released
///     some_async_operation().await;
/// }
/// ```
#[derive(Debug, Clone, Default)]
pub struct LockScopeMutation {
    /// Target function SymbolId. If None, applies to all functions.
    pub target_fn: Option<SymbolId>,
}

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

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

    /// Detect lock scope issues in a file
    fn detect_opportunities(&self, file: &PureFile) -> Vec<LockScopeOpportunity> {
        let mut opportunities = Vec::new();

        for item in &file.items {
            if let PureItem::Impl(impl_block) = item {
                for impl_item in &impl_block.items {
                    if let ryo_source::pure::PureImplItem::Fn(func) = impl_item {
                        // Note: target_fn filtering requires SymbolId comparison at executor layer.
                        // This method is called from executor with pre-filtered functions.

                        if func.is_async {
                            // Heuristic: check if body contains .lock() and .await
                            let body_str = format!("{:?}", func.body);

                            if body_str.contains("lock()")
                                && (body_str.contains(".await") || body_str.contains("await"))
                            {
                                opportunities.push(LockScopeOpportunity {
                                    impl_type: impl_block.self_ty.clone(),
                                    fn_name: func.name.clone(),
                                    issue: "lock_across_await".to_string(),
                                });
                            }
                        }
                    }
                }
            }
        }

        opportunities
    }
}

#[derive(Debug)]
struct LockScopeOpportunity {
    impl_type: String,
    fn_name: String,
    issue: String,
}

impl Mutation for LockScopeMutation {
    fn describe(&self) -> String {
        "Detect locks held across await points or with unnecessarily wide scope".to_string()
    }

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

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

impl Detect for LockScopeMutation {
    fn detect(&self, file: &PureFile) -> Vec<DetectOpportunity> {
        self.detect_opportunities(file)
            .into_iter()
            .map(|o| {
                DetectOpportunity::new(
                    DetectLocation::fn_item(&o.fn_name),
                    format!(
                        "Async method '{}::{}' may hold lock across await point",
                        o.impl_type, o.fn_name
                    ),
                )
                .with_operations(vec![DetectOperation::Refactor])
                .with_confidence(0.6)
                .with_context(o.issue)
            })
            .collect()
    }

    fn category(&self) -> DetectCategory {
        DetectCategory::Safety
    }

    fn detect_name(&self) -> &'static str {
        "LockScope"
    }

    fn detect_description(&self) -> &str {
        "Detect locks held across await points or with unnecessarily wide scope"
    }
}