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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
//! ryo-mutations: Code transformation primitives for Rust source code
//!
//! This crate provides a unified interface for AST-level mutations with
//! validation, serialization, and parallel execution support.
//!
//! ## Module Structure
//!
//! - `basic/` - Fundamental AST operations (add, remove, rename, visibility)
//! - `refactor/` - Structural transformations (extract, inline, split, merge)
//! - `idiom/` - Idiomatic Rust patterns (unwrap→?, loops→iterators, Default)
//! - `clippy/` - Clippy lint integration
//! - `analyzer/` - rust-analyzer LSP integration
//! - `debugger/` - Debug logging utilities
//!
//! ## Validation
//!
//! Mutations can be validated before execution using [`Mutation::validate`].
//! The validation result can be controlled by [`ValidationStrategy`]:
//!
//! - `AllowAll` - For FactionBoard/speculative execution (proceed regardless)
//! - `BlockFatalOnly` - For speculative execution (block only fatal errors)
//! - `BlockConflicts` - For sequential execution (block potential conflicts)
//! - `Strict` - For debugging (block all issues)

pub mod analyzer;
pub mod basic;
pub mod clippy;
pub mod debugger;
pub mod idiom;
pub mod serializable;

use ryo_source::pure::PureFile;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

// ============================================================================
// Validation Types
// ============================================================================

/// Validation severity level (ordered by severity)
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum ValidationLevel {
    /// Information only (no impact on execution)
    Info,
    /// Warning (may cause issues in parallel execution, but safe alone)
    Warning,
    /// Potential conflict with other mutations
    Conflict,
    /// Fatal error (mutation will definitely fail)
    Fatal,
}

impl ValidationLevel {
    pub fn is_fatal(&self) -> bool {
        *self == ValidationLevel::Fatal
    }

    pub fn is_blocking(&self) -> bool {
        *self >= ValidationLevel::Conflict
    }
}

/// Validation issue code for categorization
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ValidationCode {
    // === Fatal ===
    /// Target symbol does not exist (Rename/Remove)
    TargetNotFound,
    /// Symbol already exists (Add)
    DuplicateSymbol,
    /// Generated code would fail syn parse
    InvalidSyntax,
    /// Required type/trait not found
    MissingDependency,

    // === Conflict ===
    /// Symbol is referenced elsewhere (Remove may break references)
    SymbolReferenced,
    /// Another mutation targets the same symbol
    SameSymbolTarget,
    /// Impl block target type not found in file
    ImplTargetNotFound,

    // === Warning ===
    /// Added import may be unused
    PotentiallyUnusedImport,
    /// Visibility may not be sufficient
    VisibilityMismatch,
    /// Naming convention violation
    NamingConvention,

    // === Info ===
    /// No changes would be made (already applied, etc.)
    NoOp,
    /// Symbol has no references (safe to remove)
    UnreferencedSymbol,
}

impl ValidationCode {
    /// Get the default level for this code
    pub fn default_level(&self) -> ValidationLevel {
        match self {
            // Fatal
            ValidationCode::TargetNotFound
            | ValidationCode::DuplicateSymbol
            | ValidationCode::InvalidSyntax
            | ValidationCode::MissingDependency => ValidationLevel::Fatal,

            // Conflict
            ValidationCode::SymbolReferenced
            | ValidationCode::SameSymbolTarget
            | ValidationCode::ImplTargetNotFound => ValidationLevel::Conflict,

            // Warning
            ValidationCode::PotentiallyUnusedImport
            | ValidationCode::VisibilityMismatch
            | ValidationCode::NamingConvention => ValidationLevel::Warning,

            // Info
            ValidationCode::NoOp | ValidationCode::UnreferencedSymbol => ValidationLevel::Info,
        }
    }

    /// Get a user-friendly description of this error code
    pub fn user_friendly_message(&self) -> &'static str {
        match self {
            // Fatal
            ValidationCode::TargetNotFound => {
                "The symbol you're trying to modify doesn't exist in the codebase"
            }
            ValidationCode::DuplicateSymbol => "A symbol with this name already exists",
            ValidationCode::InvalidSyntax => "The transformation would produce invalid Rust code",
            ValidationCode::MissingDependency => "A required type or trait is not available",

            // Conflict
            ValidationCode::SymbolReferenced => {
                "This symbol is used elsewhere; removing it may break other code"
            }
            ValidationCode::SameSymbolTarget => "Multiple mutations are targeting the same symbol",
            ValidationCode::ImplTargetNotFound => "The type for this impl block was not found",

            // Warning
            ValidationCode::PotentiallyUnusedImport => "This import might not be used anywhere",
            ValidationCode::VisibilityMismatch => {
                "The visibility might not be sufficient for intended usage"
            }
            ValidationCode::NamingConvention => "The name doesn't follow Rust naming conventions",

            // Info
            ValidationCode::NoOp => "No changes are needed (already in desired state)",
            ValidationCode::UnreferencedSymbol => "This symbol has no references (safe to remove)",
        }
    }

    /// Get a suggestion for how to fix this issue
    pub fn suggestion(&self) -> Option<&'static str> {
        match self {
            ValidationCode::TargetNotFound => Some(
                "Check the symbol name for typos, or use 'ryo discover' to find available symbols"
            ),
            ValidationCode::DuplicateSymbol => Some(
                "Choose a different name, or remove the existing symbol first"
            ),
            ValidationCode::InvalidSyntax => Some(
                "Review the transformation parameters; ensure the generated code is valid Rust"
            ),
            ValidationCode::MissingDependency => Some(
                "Add the required dependency to Cargo.toml, or import the type/trait"
            ),
            ValidationCode::SymbolReferenced => Some(
                "Update all references before removing, or use 'ryo graph cascade' to see impact"
            ),
            ValidationCode::SameSymbolTarget => Some(
                "Merge mutations into a single operation, or execute them sequentially"
            ),
            ValidationCode::ImplTargetNotFound => Some(
                "Ensure the target type is defined in the same file, or specify the full path"
            ),
            ValidationCode::NamingConvention => Some(
                "Use snake_case for functions/variables, PascalCase for types, SCREAMING_CASE for constants"
            ),
            // No suggestions needed for these
            ValidationCode::PotentiallyUnusedImport => None,
            ValidationCode::VisibilityMismatch => None,
            ValidationCode::NoOp => None,
            ValidationCode::UnreferencedSymbol => None,
        }
    }

    /// Get an example of correct usage (for common errors)
    pub fn example(&self) -> Option<&'static str> {
        match self {
            ValidationCode::TargetNotFound => Some(
                r#"Example: { "intent": "RenameIdent", "from": "existing_fn", "to": "new_name" }"#,
            ),
            ValidationCode::DuplicateSymbol => {
                Some(r#"Example: First rename or remove 'foo', then add the new symbol"#)
            }
            ValidationCode::NamingConvention => {
                Some(r#"Examples: fn my_function(), struct MyStruct, const MAX_SIZE"#)
            }
            _ => None,
        }
    }
}

/// A validation issue found during pre-execution validation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationIssue {
    /// Severity level
    pub level: ValidationLevel,
    /// Issue code for categorization
    pub code: ValidationCode,
    /// Human-readable message
    pub message: String,
    /// Affected symbol name (if applicable)
    pub affected_symbol: Option<String>,
}

impl ValidationIssue {
    /// Create a new validation issue
    pub fn new(code: ValidationCode, message: impl Into<String>) -> Self {
        Self {
            level: code.default_level(),
            code,
            message: message.into(),
            affected_symbol: None,
        }
    }

    /// Create with a custom level (override default)
    pub fn with_level(mut self, level: ValidationLevel) -> Self {
        self.level = level;
        self
    }

    /// Add affected symbol information
    pub fn with_symbol(mut self, symbol: impl Into<String>) -> Self {
        self.affected_symbol = Some(symbol.into());
        self
    }

    // Convenience constructors for common issues
    pub fn target_not_found(symbol: &str) -> Self {
        Self::new(
            ValidationCode::TargetNotFound,
            format!("Target symbol '{}' not found", symbol),
        )
        .with_symbol(symbol)
    }

    pub fn duplicate_symbol(symbol: &str) -> Self {
        Self::new(
            ValidationCode::DuplicateSymbol,
            format!("Symbol '{}' already exists", symbol),
        )
        .with_symbol(symbol)
    }

    pub fn symbol_referenced(symbol: &str, ref_count: usize) -> Self {
        Self::new(
            ValidationCode::SymbolReferenced,
            format!(
                "Symbol '{}' is referenced {} time(s); removal may break code",
                symbol, ref_count
            ),
        )
        .with_symbol(symbol)
    }

    pub fn no_op(reason: &str) -> Self {
        Self::new(ValidationCode::NoOp, reason.to_string())
    }

    /// Format this issue as a user-friendly message with suggestions
    pub fn format_user_friendly(&self) -> String {
        let mut output = String::new();

        // Level indicator
        let level_indicator = match self.level {
            ValidationLevel::Fatal => "[ERROR]",
            ValidationLevel::Conflict => "[CONFLICT]",
            ValidationLevel::Warning => "[WARNING]",
            ValidationLevel::Info => "[INFO]",
        };

        // Main message
        output.push_str(&format!(
            "{} {}\n",
            level_indicator,
            self.code.user_friendly_message()
        ));

        // Technical details
        if let Some(ref symbol) = self.affected_symbol {
            output.push_str(&format!("  Symbol: {}\n", symbol));
        }
        if !self.message.is_empty() && self.message != self.code.user_friendly_message() {
            output.push_str(&format!("  Detail: {}\n", self.message));
        }

        // Suggestion
        if let Some(suggestion) = self.code.suggestion() {
            output.push_str(&format!("  Suggestion: {}\n", suggestion));
        }

        // Example
        if let Some(example) = self.code.example() {
            output.push_str(&format!("  {}\n", example));
        }

        output
    }
}

impl std::fmt::Display for ValidationIssue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.format_user_friendly())
    }
}

/// Validation result containing all issues
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ValidationResult {
    pub issues: Vec<ValidationIssue>,
}

impl ValidationResult {
    pub fn new() -> Self {
        Self { issues: Vec::new() }
    }

    pub fn ok() -> Self {
        Self::new()
    }

    pub fn with_issue(mut self, issue: ValidationIssue) -> Self {
        self.issues.push(issue);
        self
    }

    pub fn add(&mut self, issue: ValidationIssue) {
        self.issues.push(issue);
    }

    pub fn is_ok(&self) -> bool {
        self.issues.is_empty()
    }

    pub fn has_fatal(&self) -> bool {
        self.issues
            .iter()
            .any(|i| i.level == ValidationLevel::Fatal)
    }

    pub fn has_conflicts(&self) -> bool {
        self.issues
            .iter()
            .any(|i| i.level >= ValidationLevel::Conflict)
    }

    pub fn has_warnings(&self) -> bool {
        self.issues
            .iter()
            .any(|i| i.level >= ValidationLevel::Warning)
    }

    pub fn max_level(&self) -> Option<ValidationLevel> {
        self.issues.iter().map(|i| i.level).max()
    }

    pub fn by_level(&self, level: ValidationLevel) -> Vec<&ValidationIssue> {
        self.issues.iter().filter(|i| i.level == level).collect()
    }

    /// Format all issues as user-friendly messages
    pub fn format_user_friendly(&self) -> String {
        if self.issues.is_empty() {
            return String::new();
        }

        let mut output = String::new();

        // Group by level for better readability
        let fatal: Vec<_> = self.by_level(ValidationLevel::Fatal);
        let conflicts: Vec<_> = self.by_level(ValidationLevel::Conflict);
        let warnings: Vec<_> = self.by_level(ValidationLevel::Warning);
        let info: Vec<_> = self.by_level(ValidationLevel::Info);

        if !fatal.is_empty() {
            output.push_str(&format!("=== {} Error(s) ===\n", fatal.len()));
            for issue in fatal {
                output.push_str(&issue.format_user_friendly());
                output.push('\n');
            }
        }

        if !conflicts.is_empty() {
            output.push_str(&format!("=== {} Conflict(s) ===\n", conflicts.len()));
            for issue in conflicts {
                output.push_str(&issue.format_user_friendly());
                output.push('\n');
            }
        }

        if !warnings.is_empty() {
            output.push_str(&format!("=== {} Warning(s) ===\n", warnings.len()));
            for issue in warnings {
                output.push_str(&issue.format_user_friendly());
                output.push('\n');
            }
        }

        if !info.is_empty() {
            output.push_str(&format!("=== {} Info ===\n", info.len()));
            for issue in info {
                output.push_str(&issue.format_user_friendly());
                output.push('\n');
            }
        }

        output
    }
}

impl std::fmt::Display for ValidationResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.format_user_friendly())
    }
}

/// Strategy for handling validation results
///
/// Different execution contexts require different validation strictness:
/// - FactionBoard: Each agent operates in isolation, conflicts resolved at compose time
/// - Speculative: Optimistic execution, rollback on conflict
/// - Sequential: Traditional execution, block on potential conflicts
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum ValidationStrategy {
    /// Allow all issues (for FactionBoard / fully speculative execution)
    /// Conflicts will be detected at compose/merge time
    AllowAll,

    /// Block only fatal errors (for speculative execution)
    /// Conflicts are allowed, will be resolved at merge time
    #[default]
    BlockFatalOnly,

    /// Block conflicts and fatal errors (for sequential execution)
    /// Only warnings and info are allowed
    BlockConflicts,

    /// Block all issues including warnings (for debugging / strict mode)
    Strict,
}

impl ValidationStrategy {
    /// Check if execution can proceed given the validation result
    pub fn can_proceed(&self, result: &ValidationResult) -> bool {
        match self {
            ValidationStrategy::AllowAll => true,
            ValidationStrategy::BlockFatalOnly => !result.has_fatal(),
            ValidationStrategy::BlockConflicts => !result.has_conflicts(),
            ValidationStrategy::Strict => result.is_ok(),
        }
    }

    /// Get the minimum blocking level for this strategy
    pub fn blocking_level(&self) -> Option<ValidationLevel> {
        match self {
            ValidationStrategy::AllowAll => None,
            ValidationStrategy::BlockFatalOnly => Some(ValidationLevel::Fatal),
            ValidationStrategy::BlockConflicts => Some(ValidationLevel::Conflict),
            ValidationStrategy::Strict => Some(ValidationLevel::Info),
        }
    }
}

// Re-export all mutations for convenience
// Basic mutations
pub use basic::{
    AddConstMutation, AddDeriveMutation, AddEnumMutation, AddFieldMutation, AddFunctionMutation,
    AddImplMutation, AddItemMutation, AddMatchArmMutation, AddMethodMutation, AddPureItemsMutation,
    AddStructLiteralFieldMutation, AddStructMutation, AddTypeAliasMutation, AddUseMutation,
    AddVariantMutation, ChangeVisibilityMutation, CreateModMutation, EnumToTraitMutation,
    EnumToTraitStrategy, ExtractTraitMutation, FieldInfo, InlineTraitMutation, MatchHandling,
    MoveItemMutation, RemoveConstMutation, RemoveDeriveMutation, RemoveEnumMutation,
    RemoveFieldMutation, RemoveFunctionMutation, RemoveImplMutation, RemoveItemMutation,
    RemoveMatchArmMutation, RemoveMethodMutation, RemoveModMutation,
    RemoveStructLiteralFieldMutation, RemoveStructMutation, RemoveTraitMutation,
    RemoveTypeAliasMutation, RemoveUseMutation, RemoveVariantMutation, RenameMutation,
    ReplaceMatchArmMutation, VariantInfo,
};

// Refactor mutations
// (Currently empty - use basic mutations for refactoring operations)

// Idiom mutations
pub use idiom::{
    // Tier 1: Clippy high-frequency
    AssignOpMutation,
    BoolSimplifyMutation,
    CloneOnCopyMutation,
    CollapsibleIfMutation,
    ComparisonToMethodMutation,
    // Tier 3: Code generation (Design patterns)
    DefaultMutation,
    DeriveDefaultMutation,
    FilterNextMutation,
    // Tier 2: Pattern transformations
    FindDuplicateExpressions,
    IntroduceVariableMutation,
    // Tier 4: Performance/Safety
    LockScopeMutation,
    LoopPattern,
    LoopToIteratorMutation,
    ManualMapMutation,
    MapUnwrapOrMutation,
    MatchToIfLetMutation,
    NoOpArmToTodoMutation,
    OrganizeImportsMutation,
    RedundantClosureMutation,
    UnwrapToQuestionMutation,
    UseAtomicMutation,
    UseRwLockMutation,
};

// Detection trait and types
pub use idiom::detect::{
    create_default_registry, Detect, DetectCategory, DetectLocation, DetectOperation,
    DetectOpportunity, DetectRegistry,
};

// Statement-level mutations (from basic::stmt)
pub use basic::stmt::{
    InsertPosition, InsertStatementMutation, RemoveStatementMutation, ReplaceExprAtMutation,
    ReplaceExprMutation, ReplaceStatementMutation, WrapExprMutation,
};

// Debugger mutations
pub use debugger::{
    DbgWrapMutation, DebugMarker, DebugSession, InsertInspectMutation, RemovalTarget,
    RemoveDebugLogsMutation, MARKER_PREFIX,
};

// Serializable mutation representation
pub use serializable::{SerializableMutation, ToSerializable};

/// Result of applying a mutation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MutationResult {
    pub mutation_type: String,
    pub changes: usize,
    pub description: String,
}

/// A mutation that can be applied to AST.
///
/// # Execution APIs
///
/// - **`ASTRegApply::apply_to_registry()`** (V2, preferred): Registry-based execution
///   via `ASTMutationContext`. Defined in `ryo-executor` to avoid circular dependencies.
///
/// - **`apply()`** (Legacy, deprecated): File-based execution via `&mut PureFile`.
///   Will be removed in future versions.
///
/// # Migration Guide
///
/// New mutations should implement `ASTRegApply` trait in `ryo-executor::engine`.
/// See `ryo-executor::engine::impls` for implementation examples.
pub trait Mutation: Send + Sync {
    /// Validate the mutation before applying
    ///
    /// Returns validation issues that may indicate:
    /// - Fatal errors (mutation will fail)
    /// - Conflicts (may conflict with parallel mutations)
    /// - Warnings (potential issues)
    /// - Info (informational, no impact)
    ///
    /// Default implementation returns no issues (always valid).
    fn validate(&self, _file: &PureFile) -> ValidationResult {
        ValidationResult::ok()
    }

    /// Check if this mutation can proceed with the given strategy
    fn can_proceed(&self, file: &PureFile, strategy: ValidationStrategy) -> bool {
        strategy.can_proceed(&self.validate(file))
    }

    /// Get a description of this mutation
    fn describe(&self) -> String;

    /// Get the mutation type name
    fn mutation_type(&self) -> &'static str;

    /// Clone this mutation into a new Box
    fn box_clone(&self) -> Box<dyn Mutation>;
}

/// Clone a boxed mutation
pub fn clone_mutation(mutation: &dyn Mutation) -> Box<dyn Mutation> {
    mutation.box_clone()
}

/// A collection of mutations to apply
#[derive(Debug)]
pub struct MutationBatch {
    pub mutations: Vec<Box<dyn Mutation>>,
}

// Manual Debug impl because Box<dyn Mutation> doesn't implement Debug
impl std::fmt::Debug for Box<dyn Mutation> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Mutation({})", self.mutation_type())
    }
}

impl MutationBatch {
    pub fn new() -> Self {
        Self {
            mutations: Vec::new(),
        }
    }

    pub fn with_mutation<M: Mutation + 'static>(mut self, mutation: M) -> Self {
        self.mutations.push(Box::new(mutation));
        self
    }
}

impl Default for MutationBatch {
    fn default() -> Self {
        Self::new()
    }
}

// Suppress unused warning when parallel feature is not enabled
#[allow(dead_code)]
fn _use_path_buf(_: PathBuf) {}