ryo-executor 0.2.0

[experimental] Mutation execution engine for RYO - parallel execution, conflict detection, workspace management
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
//! StmtConverter: Converts statement-level MutationSpec variants to Mutations
//!
//! Handles:
//! - ReplaceExpr
//! - RemoveStatement
//! - InsertStatement
//! - ReplaceStatement

use crate::engine::ASTRegApply;
use crate::executor::registry::converters::ResolveTargetSymbol;
use crate::executor::registry::{ConvertError, MutationConverter};
use crate::executor::spec::{MutationSpec, StmtInsertPosition};
use ryo_analysis::AnalysisContext;
use ryo_analysis::SymbolPath;
use ryo_mutations::basic::stmt::{
    InsertPosition, InsertStatementMutation, RemoveStatementMutation, ReplaceExprAtMutation,
    ReplaceExprMutation, ReplaceStatementMutation,
};
use ryo_source::pure::{PureExpr, PureStmt, ToPure};

/// Converter for statement-level mutations
#[derive(Debug, Clone, Default)]
pub struct StmtConverter;

impl StmtConverter {
    pub fn new() -> Self {
        Self
    }

    /// Parse a Rust expression string into PureExpr (used for `old_expr` / match keys).
    ///
    /// Match keys go through full parse → `to_pure()` normalization so that
    /// whitespace / token-spacing variants on the *match side* don't perturb
    /// equality comparison.
    pub fn parse_expr(expr_str: &str) -> Result<PureExpr, ConvertError> {
        let expr: syn::Expr = syn::parse_str(expr_str).map_err(|e| {
            ConvertError::Parse(format!("Failed to parse expression '{}': {}", expr_str, e))
        })?;
        Ok(expr.to_pure())
    }

    /// Parse a Rust statement string into PureStmt (used for `old_stmt` / `reference_pattern`).
    ///
    /// See `parse_expr` for the match-key normalization rationale.
    pub fn parse_stmt(stmt_str: &str) -> Result<PureStmt, ConvertError> {
        // Try parsing as a statement first
        let stmt_with_semi = if stmt_str.ends_with(';') {
            stmt_str.to_string()
        } else {
            format!("{};", stmt_str)
        };

        let stmt: syn::Stmt = syn::parse_str(&stmt_with_semi).map_err(|e| {
            ConvertError::Parse(format!("Failed to parse statement '{}': {}", stmt_str, e))
        })?;

        // Use ToPure trait implementation for syn::Stmt
        Ok(stmt.to_pure())
    }

    /// Build a verbatim **replacement** expression carrier from a raw source string.
    ///
    /// Used for `new_expr` (the *output* side of ReplaceExpr / ReplaceExprAt).
    /// The string is still syntax-checked via `syn::parse_str` (so a malformed
    /// expression is rejected up-front and the converter never emits garbage),
    /// but the parsed AST is **discarded** — `PureExpr::Verbatim(raw)` preserves
    /// the user-provided byte sequence 1:1 through `to_source`.
    ///
    /// This is the wire that connects the B-3 carrier (PureExpr::Verbatim) to
    /// producer paths so that DSL-shaped replacements survive prettyplease.
    pub fn build_verbatim_expr(expr_str: &str) -> Result<PureExpr, ConvertError> {
        // Validate syntactic well-formedness; discard the parsed shape.
        let _: syn::Expr = syn::parse_str(expr_str).map_err(|e| {
            ConvertError::Parse(format!("Failed to parse expression '{}': {}", expr_str, e))
        })?;
        Ok(PureExpr::Verbatim(expr_str.to_string()))
    }

    /// Build a verbatim **replacement** statement carrier from a raw source string.
    ///
    /// Used for `new_stmt` (ReplaceStatement) and `stmt` (InsertStatement) —
    /// the *output* side. See `build_verbatim_expr` for the parse-then-discard
    /// rationale; this wraps in `PureStmt::Verbatim` (the B-3-cont carrier).
    pub fn build_verbatim_stmt(stmt_str: &str) -> Result<PureStmt, ConvertError> {
        let stmt_with_semi = if stmt_str.ends_with(';') {
            stmt_str.to_string()
        } else {
            format!("{};", stmt_str)
        };
        let _: syn::Stmt = syn::parse_str(&stmt_with_semi).map_err(|e| {
            ConvertError::Parse(format!("Failed to parse statement '{}': {}", stmt_str, e))
        })?;
        // The line-splice pass in `PureFile::to_source` replaces the **entire
        // stub line** (including the synthetic trailing `;` emitted by the
        // stub) with the raw bytes carried here. If the caller forgot the
        // terminator, the post-splice line would be a bare expression — and
        // a later round-trip through `syn::parse_file` would either drop or
        // re-shape it. Carrying the normalized `stmt_with_semi` keeps the
        // user's *interior* spacing 1:1 while guaranteeing a valid stmt line.
        Ok(PureStmt::Verbatim(stmt_with_semi))
    }

    /// Build a verbatim **replacement** statement carrier where a missing
    /// `;` terminator is honored as **tail-expression intent** instead of
    /// being auto-completed.
    ///
    /// Used for `new_stmt` (ReplaceStatement) only. RL043 (needless-return)
    /// replaces a trailing `return expr;` with the bare `expr` — with the
    /// `build_verbatim_stmt` semi auto-completion the splice emits `expr;`,
    /// the function loses its tail expression, and the post-mutation cargo
    /// check fails with "mismatched types" (2026-06-12 bulk-lint sweep v1).
    ///
    /// Contract: a terminator-less string that parses as a bare expression
    /// is carried verbatim (no `;`); anything else (e.g. `let x = 1`)
    /// falls back to the normalizing `build_verbatim_stmt` path, keeping
    /// existing semi-completion behavior for statement-shaped input.
    /// Mid-block placement of a non-unit bare expression is caught by the
    /// post-mutation cargo check (caller responsibility, same as any other
    /// type-changing replacement).
    pub fn build_verbatim_replacement_stmt(stmt_str: &str) -> Result<PureStmt, ConvertError> {
        let trimmed = stmt_str.trim_end();
        if !trimmed.ends_with(';') {
            match syn::parse_str::<syn::Expr>(trimmed) {
                // `let pat = init` parses as syn::Expr::Let (let-chain
                // grammar leniency) but is statement-shaped input — keep
                // it on the semi-completion path.
                Ok(expr) if !matches!(expr, syn::Expr::Let(_)) => {
                    return Ok(PureStmt::Verbatim(trimmed.to_string()));
                }
                _ => {}
            }
        }
        Self::build_verbatim_stmt(stmt_str)
    }

    /// Convert StmtInsertPosition to internal InsertPosition
    fn convert_position(pos: &StmtInsertPosition) -> InsertPosition {
        match pos {
            StmtInsertPosition::Start => InsertPosition::Start,
            StmtInsertPosition::End => InsertPosition::End,
            StmtInsertPosition::BeforePattern => InsertPosition::BeforePattern,
            StmtInsertPosition::AfterPattern => InsertPosition::AfterPattern,
        }
    }
}

// StmtConverter uses the default implementation of ResolveTargetSymbol
impl ResolveTargetSymbol for StmtConverter {}

impl MutationConverter for StmtConverter {
    fn spec_kinds(&self) -> &'static [&'static str] {
        &[
            "ReplaceExpr",
            "RemoveStatement",
            "InsertStatement",
            "ReplaceStatement",
        ]
    }

    fn convert_v2(
        &self,
        spec: &MutationSpec,
        ctx: &AnalysisContext,
    ) -> Result<Vec<Box<dyn ASTRegApply>>, ConvertError> {
        match spec {
            MutationSpec::ReplaceExpr {
                fn_id,
                old_expr,
                new_expr,
                replace_all,
                symbol_path,
                ..
            } => {
                // B-3 carrier wire-up: preserve user-provided bytes for the
                // *output* expression. `old_expr` still goes through
                // parse-normalize because it's a match key.
                let new = Self::build_verbatim_expr(new_expr)?;

                // If symbol_path is provided, use position-based replacement
                if let Some(path_str) = symbol_path {
                    let path = SymbolPath::parse(path_str).map_err(|e| {
                        ConvertError::Parse(format!("Invalid symbol_path '{}': {}", path_str, e))
                    })?;

                    if !path.has_body_segment() {
                        return Err(ConvertError::Parse(format!(
                            "symbol_path '{}' must contain $body segment for position-based replacement",
                            path_str
                        )));
                    }

                    let (fn_path, indices) = path.split_at_body().ok_or_else(|| {
                        ConvertError::Parse(format!(
                            "Failed to extract function path from symbol_path '{}'",
                            path_str
                        ))
                    })?;

                    // Lookup SymbolId from function path
                    let fn_id = ctx.registry.lookup(&fn_path).ok_or_else(|| {
                        ConvertError::TargetNotFound(format!(
                            "Function '{}' not found in registry",
                            fn_path
                        ))
                    })?;

                    let mutation = ReplaceExprAtMutation::new(fn_id, indices, new);
                    return Ok(vec![Box::new(mutation)]);
                }

                let old = Self::parse_expr(old_expr)?;

                // If fn_id is None, generate mutations for all functions
                let mutations: Vec<Box<dyn ASTRegApply>> = if let Some(id) = fn_id {
                    let mut mutation = ReplaceExprMutation::new(old.clone(), new.clone(), *id);
                    mutation.replace_all = *replace_all;
                    vec![Box::new(mutation)]
                } else {
                    use ryo_analysis::SymbolKind;
                    ctx.registry
                        .iter()
                        .filter(|(id, _)| {
                            matches!(ctx.registry.kind(*id), Some(SymbolKind::Function))
                        })
                        .map(|(id, _)| {
                            let mut mutation =
                                ReplaceExprMutation::new(old.clone(), new.clone(), id);
                            mutation.replace_all = *replace_all;
                            Box::new(mutation) as Box<dyn ASTRegApply>
                        })
                        .collect()
                };

                Ok(mutations)
            }

            MutationSpec::RemoveStatement {
                fn_id,
                pattern,
                remove_all,
                ..
            } => {
                let target_stmt = Self::parse_stmt(pattern)?;

                // If fn_id is None, generate mutations for all functions
                let mutations: Vec<Box<dyn ASTRegApply>> = if let Some(id) = fn_id {
                    let mut mutation =
                        RemoveStatementMutation::new(target_stmt.clone(), pattern.clone(), *id);
                    mutation.remove_all = *remove_all;
                    vec![Box::new(mutation)]
                } else {
                    use ryo_analysis::SymbolKind;
                    ctx.registry
                        .iter()
                        .filter(|(id, _)| {
                            matches!(ctx.registry.kind(*id), Some(SymbolKind::Function))
                        })
                        .map(|(id, _)| {
                            let mut mutation = RemoveStatementMutation::new(
                                target_stmt.clone(),
                                pattern.clone(),
                                id,
                            );
                            mutation.remove_all = *remove_all;
                            Box::new(mutation) as Box<dyn ASTRegApply>
                        })
                        .collect()
                };

                Ok(mutations)
            }

            MutationSpec::InsertStatement {
                fn_id,
                stmt,
                position,
                reference_pattern,
                ..
            } => {
                // B-3-cont carrier wire-up: preserve user-provided bytes for
                // the *inserted* statement. `reference_pattern` stays parsed
                // because it's used as a structural match key.
                let pure_stmt = Self::build_verbatim_stmt(stmt)?;
                let reference_stmt = reference_pattern
                    .as_ref()
                    .map(|p| Self::parse_stmt(p))
                    .transpose()?;

                let mut mutation = InsertStatementMutation::new(pure_stmt, *fn_id);
                mutation.position = Self::convert_position(position);
                mutation.reference_stmt = reference_stmt;

                Ok(vec![Box::new(mutation)])
            }

            MutationSpec::ReplaceStatement {
                fn_id,
                old_stmt,
                new_stmt,
                ..
            } => {
                let old = Self::parse_stmt(old_stmt)?;
                // B-3-cont carrier wire-up for the *output* statement.
                // Terminator-less expression input is honored as
                // tail-expression intent (RL043 `return x;` → `x`).
                let new = Self::build_verbatim_replacement_stmt(new_stmt)?;

                // If fn_id is None, generate mutations for all functions
                let mutations: Vec<Box<dyn ASTRegApply>> = if let Some(id) = fn_id {
                    vec![Box::new(ReplaceStatementMutation::new(
                        old.clone(),
                        new.clone(),
                        *id,
                    ))]
                } else {
                    use ryo_analysis::SymbolKind;
                    ctx.registry
                        .iter()
                        .filter(|(id, _)| {
                            matches!(ctx.registry.kind(*id), Some(SymbolKind::Function))
                        })
                        .map(|(id, _)| {
                            Box::new(ReplaceStatementMutation::new(old.clone(), new.clone(), id))
                                as Box<dyn ASTRegApply>
                        })
                        .collect()
                };

                Ok(mutations)
            }

            _ => Err(ConvertError::TypeMismatch {
                expected: "ReplaceExpr|RemoveStatement|InsertStatement|ReplaceStatement",
                actual: spec.kind_name().to_string(),
            }),
        }
    }
}

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

    #[test]
    fn test_stmt_converter_spec_kinds() {
        let converter = StmtConverter::new();
        let kinds = converter.spec_kinds();
        assert!(kinds.contains(&"ReplaceExpr"));
        assert!(kinds.contains(&"RemoveStatement"));
        assert!(kinds.contains(&"InsertStatement"));
        assert!(kinds.contains(&"ReplaceStatement"));
    }

    #[test]
    fn test_stmt_converter_can_handle() {
        let converter = StmtConverter::new();

        let replace_expr_spec = MutationSpec::ReplaceExpr {
            module_id: None,
            fn_id: None,
            old_expr: "a + b".into(),
            new_expr: "c + d".into(),
            replace_all: true,
            symbol_path: None,
        };
        assert!(converter.can_handle(&replace_expr_spec));

        let remove_stmt_spec = MutationSpec::RemoveStatement {
            module_id: None,
            fn_id: None,
            pattern: "println!".into(),
            remove_all: true,
            symbol_path: None,
        };
        assert!(converter.can_handle(&remove_stmt_spec));

        let insert_stmt_spec = MutationSpec::InsertStatement {
            module_id: None,
            fn_id: SymbolId::default(),
            stmt: "let x = 1".into(),
            position: StmtInsertPosition::Start,
            reference_pattern: None,
            symbol_path: None,
        };
        assert!(converter.can_handle(&insert_stmt_spec));

        let replace_stmt_spec = MutationSpec::ReplaceStatement {
            module_id: None,
            fn_id: None,
            old_stmt: "let x = 1".into(),
            new_stmt: "let x = 2".into(),
            symbol_path: None,
        };
        assert!(converter.can_handle(&replace_stmt_spec));
    }

    // -------------------------------------------------------------------------
    // A-patch: B-3 / B-3-cont carrier wire-up — `new_expr` / `new_stmt` / `stmt`
    // are emitted as Verbatim, preserving user-provided byte sequences so that
    // DSL-shaped replacements survive prettyplease.
    // -------------------------------------------------------------------------

    #[test]
    fn build_verbatim_expr_preserves_raw_bytes_with_unusual_spacing() {
        // prettyplease would normally collapse the doubled spaces and the
        // unusual macro spacing — Verbatim must pass them through 1:1.
        let raw = "html ! { < div   id = \"x\" > { value } < / div > }";
        match StmtConverter::build_verbatim_expr(raw).unwrap() {
            PureExpr::Verbatim(s) => assert_eq!(s, raw),
            other => panic!("expected PureExpr::Verbatim, got {:?}", other),
        }
    }

    #[test]
    fn build_verbatim_stmt_appends_trailing_semicolon_if_missing() {
        // The line-splice pass replaces the whole stub line (which includes
        // a synthetic `;`), so the carrier MUST itself terminate the stmt.
        match StmtConverter::build_verbatim_stmt("let x = 1").unwrap() {
            PureStmt::Verbatim(s) => assert_eq!(s, "let x = 1;"),
            other => panic!("expected PureStmt::Verbatim, got {:?}", other),
        }
    }

    #[test]
    fn build_verbatim_stmt_preserves_user_terminator_and_interior_spacing() {
        // Interior raw spacing is preserved; the existing `;` is not doubled.
        let raw = "let  x   =   foo ! { a , b } ;";
        match StmtConverter::build_verbatim_stmt(raw).unwrap() {
            PureStmt::Verbatim(s) => assert_eq!(s, raw),
            other => panic!("expected PureStmt::Verbatim, got {:?}", other),
        }
    }

    #[test]
    fn build_verbatim_expr_rejects_syntactically_invalid_input() {
        // Malformed inputs must be caught at the converter boundary so the
        // raw stub never reaches `PureFile::to_source`.
        assert!(StmtConverter::build_verbatim_expr("let x = ;").is_err());
    }

    #[test]
    fn build_verbatim_stmt_rejects_syntactically_invalid_input() {
        assert!(StmtConverter::build_verbatim_stmt("@@@ nonsense @@@").is_err());
    }

    // -------------------------------------------------------------------------
    // RL043 tail-expression replacement pins (2026-06-12 bulk-lint sweep)
    // -------------------------------------------------------------------------

    #[test]
    fn build_verbatim_replacement_stmt_honors_tail_expr_intent() {
        // Terminator-less bare expression is carried verbatim WITHOUT a
        // synthetic `;`, so the replaced statement can become the block's
        // tail expression (RL043 `return x;` → `x`). With semi
        // auto-completion the splice emitted `x;` and the post-mutation
        // cargo check failed with "mismatched types".
        match StmtConverter::build_verbatim_replacement_stmt("sum").unwrap() {
            PureStmt::Verbatim(s) => assert_eq!(s, "sum"),
            other => panic!("expected PureStmt::Verbatim, got {:?}", other),
        }
    }

    #[test]
    fn build_verbatim_replacement_stmt_keeps_semi_completion_for_let() {
        // `let pat = init` parses as syn::Expr::Let (let-chain grammar
        // leniency) but is statement-shaped input — it must stay on the
        // normalizing semi-completion path (regression pin for
        // v2_replace_statement_basic).
        match StmtConverter::build_verbatim_replacement_stmt("let new_value = 20").unwrap() {
            PureStmt::Verbatim(s) => assert_eq!(s, "let new_value = 20;"),
            other => panic!("expected PureStmt::Verbatim, got {:?}", other),
        }
    }

    #[test]
    fn build_verbatim_replacement_stmt_passes_explicit_terminator_through() {
        // An explicit `;` is statement intent — unchanged passthrough.
        match StmtConverter::build_verbatim_replacement_stmt("foo();").unwrap() {
            PureStmt::Verbatim(s) => assert_eq!(s, "foo();"),
            other => panic!("expected PureStmt::Verbatim, got {:?}", other),
        }
    }
}