ryo-plugin-runtime 0.2.0

[experimental] WASM plugin runtime for ryo mutations (registry + executor)
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
//! Plugin Executor - Execute WASM plugins against source code

use super::registry::{MutationRegistry, RegistryError};
use ryo_plugin_loader::{Capture, MatchResult, NodeKind, TextEdit, TransformContext, TransformDef};
use std::path::Path;
use syn::visit::Visit;

/// Error type for plugin execution
#[derive(Debug, thiserror::Error)]
pub enum PluginExecutorError {
    #[error("Plugin not found: {0}")]
    PluginNotFound(String),

    #[error("Registry error: {0}")]
    Registry(#[from] RegistryError),

    #[error("Pattern match error: {0}")]
    PatternMatch(String),

    #[error("Transform error: {0}")]
    Transform(String),

    #[error("Parse error: {0}")]
    Parse(String),
}

/// Result of executing a plugin on a source file
#[derive(Debug)]
pub struct PluginExecutionResult {
    /// Number of matches found
    pub matches_found: usize,
    /// Text edits to apply
    pub edits: Vec<TextEdit>,
    /// New source after applying edits
    pub new_source: Option<String>,
}

/// Execute WASM plugins against source code
pub struct PluginExecutor<'a> {
    registry: &'a mut MutationRegistry,
}

impl<'a> PluginExecutor<'a> {
    /// Create a new plugin executor with a registry reference
    pub fn new(registry: &'a mut MutationRegistry) -> Self {
        Self { registry }
    }

    /// Execute a plugin by name on source code
    pub fn execute(
        &mut self,
        plugin_name: &str,
        file_path: &Path,
        source: &str,
    ) -> Result<PluginExecutionResult, PluginExecutorError> {
        // Get plugin from registry
        let plugin = self
            .registry
            .get_plugin_mut(plugin_name)
            .ok_or_else(|| PluginExecutorError::PluginNotFound(plugin_name.to_string()))?;

        // Parse the source code
        let syntax =
            syn::parse_file(source).map_err(|e| PluginExecutorError::Parse(e.to_string()))?;

        // Match patterns
        let pattern = &plugin.manifest.pattern;
        let matches = match_pattern(pattern, &syntax, source)?;

        if matches.is_empty() {
            return Ok(PluginExecutionResult {
                matches_found: 0,
                edits: vec![],
                new_source: None,
            });
        }

        // Extract function return types from the AST
        let fn_return_type = extract_function_return_type(&syntax);

        // Apply transform
        let edits = match &plugin.manifest.transform {
            TransformDef::Template(template) => {
                // Host-side template expansion
                expand_template(template, &matches)
            }
            TransformDef::WasmExecute => {
                // Call WASM for complex transform
                let context = TransformContext {
                    file_path: file_path.to_string_lossy().to_string(),
                    source_text: source.to_string(),
                    type_hints: vec![], // TODO: implement full type analysis
                    fn_return_type,
                };
                plugin
                    .execute_transform(matches.clone(), context)
                    .map_err(|e| PluginExecutorError::Transform(e.to_string()))?
            }
        };

        // Apply edits to source
        let new_source = apply_edits(source, &edits);

        Ok(PluginExecutionResult {
            matches_found: matches.len(),
            edits,
            new_source: Some(new_source),
        })
    }
}

// =============================================================================
// Type Analysis
// =============================================================================

/// Extract function return types from the parsed file
/// Returns the first function's return type found (simplified for now)
fn extract_function_return_type(file: &syn::File) -> Option<String> {
    use quote::ToTokens;

    for item in &file.items {
        if let syn::Item::Fn(func) = item {
            if let syn::ReturnType::Type(_, ty) = &func.sig.output {
                let type_str = ty.to_token_stream().to_string();
                return Some(type_str);
            }
        }
    }
    None
}

// =============================================================================
// Pattern Matching (syn-based)
// =============================================================================

/// Pattern matcher visitor for syn AST
struct PatternMatcher<'a> {
    pattern: ParsedPattern,
    source: &'a str,
    matches: Vec<MatchResult>,
}

/// Parsed pattern from DSL
#[derive(Debug)]
struct ParsedPattern {
    node_type: String,
    conditions: Vec<(String, String)>,
}

/// Parse pattern DSL like `binary_expr[op=="==", right=="true"]`
fn parse_pattern(pattern: &str) -> Result<ParsedPattern, PluginExecutorError> {
    // Very simple pattern parser for now
    // Format: node_type[cond1="val1", cond2="val2"]

    let bracket_start = pattern.find('[');
    let bracket_end = pattern.rfind(']');

    let (node_type, conditions) = match (bracket_start, bracket_end) {
        (Some(start), Some(end)) if end > start => {
            let node_type = pattern[..start].to_string();
            let conds_str = &pattern[start + 1..end];
            let conditions = parse_conditions(conds_str)?;
            (node_type, conditions)
        }
        _ => (pattern.to_string(), vec![]),
    };

    Ok(ParsedPattern {
        node_type,
        conditions,
    })
}

fn parse_conditions(conds_str: &str) -> Result<Vec<(String, String)>, PluginExecutorError> {
    let mut conditions = Vec::new();

    for cond in conds_str.split(',') {
        let cond = cond.trim();
        if cond.is_empty() {
            continue;
        }

        // Parse: key=="value" or key="value"
        let parts: Vec<&str> = cond.splitn(2, "==").collect();
        if parts.len() == 2 {
            let key = parts[0].trim().to_string();
            let value = parts[1].trim().trim_matches('"').to_string();
            conditions.push((key, value));
        }
    }

    Ok(conditions)
}

/// Match pattern against parsed AST
fn match_pattern(
    pattern: &str,
    file: &syn::File,
    source: &str,
) -> Result<Vec<MatchResult>, PluginExecutorError> {
    let parsed = parse_pattern(pattern)?;

    let mut matcher = PatternMatcher {
        pattern: parsed,
        source,
        matches: Vec::new(),
    };

    matcher.visit_file(file);

    Ok(matcher.matches)
}

impl<'ast> Visit<'ast> for PatternMatcher<'ast> {
    fn visit_expr(&mut self, expr: &'ast syn::Expr) {
        // Match binary expressions
        if self.pattern.node_type == "binary_expr" {
            if let syn::Expr::Binary(bin) = expr {
                if self.matches_binary_expr(bin) {
                    self.add_binary_match(bin);
                }
            }
        }

        // Match method calls (e.g., x.unwrap(), x.expect("msg"))
        if self.pattern.node_type == "method_call" {
            if let syn::Expr::MethodCall(call) = expr {
                if self.matches_method_call(call) {
                    self.add_method_call_match(call);
                }
            }
        }

        // Continue visiting children
        syn::visit::visit_expr(self, expr);
    }
}

impl<'a> PatternMatcher<'a> {
    fn matches_binary_expr(&self, bin: &syn::ExprBinary) -> bool {
        for (key, value) in &self.pattern.conditions {
            match key.as_str() {
                "op" => {
                    let op_str = op_to_string(&bin.op);
                    if op_str != *value {
                        return false;
                    }
                }
                "right" => {
                    let right_src = self.expr_to_string(&bin.right);
                    if right_src.trim() != *value {
                        return false;
                    }
                }
                "left" => {
                    let left_src = self.expr_to_string(&bin.left);
                    if left_src.trim() != *value {
                        return false;
                    }
                }
                _ => {}
            }
        }
        true
    }

    fn add_binary_match(&mut self, bin: &syn::ExprBinary) {
        // Find byte offsets using simple source text search
        let expr_str = self.expr_to_string_with_box(&syn::Expr::Binary(bin.clone()));

        // Search for the expression in source
        if let Some(start_byte) = self.source.find(&expr_str) {
            let end_byte = start_byte + expr_str.len();

            let left_text = self.expr_to_string(&bin.left);
            let right_text = self.expr_to_string(&bin.right);

            self.matches.push(MatchResult {
                kind: NodeKind::BinaryExpr,
                start_byte: start_byte as u64,
                end_byte: end_byte as u64,
                captures: vec![
                    Capture {
                        name: "left".to_string(),
                        start_byte: 0,
                        end_byte: 0,
                        text: left_text,
                    },
                    Capture {
                        name: "right".to_string(),
                        start_byte: 0,
                        end_byte: 0,
                        text: right_text,
                    },
                ],
            });
        }
    }

    fn matches_method_call(&self, call: &syn::ExprMethodCall) -> bool {
        for (key, value) in &self.pattern.conditions {
            if key.as_str() == "method" {
                let method_name = call.method.to_string();
                if method_name != *value {
                    return false;
                }
            }
        }
        true
    }

    fn add_method_call_match(&mut self, call: &syn::ExprMethodCall) {
        let receiver_text = self.expr_to_string(&call.receiver);
        let method_text = call.method.to_string();

        // Search for .method( pattern in source
        let method_pattern = format!(".{}(", method_text);

        // Find all occurrences and pick the one that makes sense
        let mut search_start = 0;
        while let Some(method_pos) = self.source[search_start..].find(&method_pattern) {
            let method_abs_pos = search_start + method_pos;

            // Find the end of the method call (matching closing paren)
            let args_start = method_abs_pos + method_pattern.len();
            let after_method = &self.source[args_start..];

            if let Some(paren_pos) = self.find_matching_paren(after_method) {
                let end_pos = args_start + paren_pos + 1;

                // Walk backwards to find the start of the expression
                // Look for a character that can't be part of an expression
                let start_pos = self.find_expr_start(method_abs_pos);

                // Extract the actual receiver from source
                let actual_receiver = self.source[start_pos..method_abs_pos].to_string();

                // Verify this looks like the right match by checking receiver similarity
                // (normalized comparison - remove all spaces)
                let actual_normalized: String = actual_receiver
                    .chars()
                    .filter(|c| !c.is_whitespace())
                    .collect();
                let expected_normalized: String = receiver_text
                    .chars()
                    .filter(|c| !c.is_whitespace())
                    .collect();

                if actual_normalized == expected_normalized {
                    self.matches.push(MatchResult {
                        kind: NodeKind::MethodCall,
                        start_byte: start_pos as u64,
                        end_byte: end_pos as u64,
                        captures: vec![
                            Capture {
                                name: "receiver".to_string(),
                                start_byte: start_pos as u64,
                                end_byte: method_abs_pos as u64,
                                text: actual_receiver,
                            },
                            Capture {
                                name: "method".to_string(),
                                start_byte: method_abs_pos as u64,
                                end_byte: end_pos as u64,
                                text: method_text.clone(),
                            },
                        ],
                    });
                    return; // Found the match
                }
            }

            search_start = method_abs_pos + 1;
        }
    }

    /// Find the start of an expression by walking backwards from a position
    fn find_expr_start(&self, from: usize) -> usize {
        let bytes = self.source.as_bytes();
        let mut pos = from;
        let mut paren_depth = 0;
        let mut bracket_depth = 0;

        while pos > 0 {
            pos -= 1;
            let c = bytes[pos] as char;

            match c {
                ')' => paren_depth += 1,
                '(' => {
                    if paren_depth > 0 {
                        paren_depth -= 1;
                    } else {
                        // Unmatched open paren - expression starts after this
                        return pos + 1;
                    }
                }
                ']' => bracket_depth += 1,
                '[' => {
                    if bracket_depth > 0 {
                        bracket_depth -= 1;
                    } else {
                        return pos + 1;
                    }
                }
                // These characters indicate the start of the expression
                '=' | ';' | '{' | ',' | ':' if paren_depth == 0 && bracket_depth == 0 => {
                    // Skip any whitespace after the delimiter
                    let mut start = pos + 1;
                    while start < from && self.source.as_bytes()[start].is_ascii_whitespace() {
                        start += 1;
                    }
                    return start;
                }
                _ => {}
            }
        }

        0
    }

    fn find_matching_paren(&self, s: &str) -> Option<usize> {
        let mut depth = 1;
        for (i, c) in s.chars().enumerate() {
            match c {
                '(' => depth += 1,
                ')' => {
                    depth -= 1;
                    if depth == 0 {
                        return Some(i);
                    }
                }
                _ => {}
            }
        }
        None
    }

    fn expr_to_string(&self, expr: &syn::Expr) -> String {
        use quote::ToTokens;
        expr.to_token_stream().to_string()
    }

    fn expr_to_string_with_box(&self, expr: &syn::Expr) -> String {
        use quote::ToTokens;
        expr.to_token_stream().to_string()
    }
}

/// Convert binary operator to string
fn op_to_string(op: &syn::BinOp) -> String {
    match op {
        syn::BinOp::Eq(_) => "==".to_string(),
        syn::BinOp::Ne(_) => "!=".to_string(),
        syn::BinOp::Lt(_) => "<".to_string(),
        syn::BinOp::Le(_) => "<=".to_string(),
        syn::BinOp::Gt(_) => ">".to_string(),
        syn::BinOp::Ge(_) => ">=".to_string(),
        syn::BinOp::And(_) => "&&".to_string(),
        syn::BinOp::Or(_) => "||".to_string(),
        syn::BinOp::Add(_) => "+".to_string(),
        syn::BinOp::Sub(_) => "-".to_string(),
        syn::BinOp::Mul(_) => "*".to_string(),
        syn::BinOp::Div(_) => "/".to_string(),
        syn::BinOp::Rem(_) => "%".to_string(),
        syn::BinOp::BitAnd(_) => "&".to_string(),
        syn::BinOp::BitOr(_) => "|".to_string(),
        syn::BinOp::BitXor(_) => "^".to_string(),
        syn::BinOp::Shl(_) => "<<".to_string(),
        syn::BinOp::Shr(_) => ">>".to_string(),
        syn::BinOp::AddAssign(_) => "+=".to_string(),
        syn::BinOp::SubAssign(_) => "-=".to_string(),
        syn::BinOp::MulAssign(_) => "*=".to_string(),
        syn::BinOp::DivAssign(_) => "/=".to_string(),
        syn::BinOp::RemAssign(_) => "%=".to_string(),
        syn::BinOp::BitAndAssign(_) => "&=".to_string(),
        syn::BinOp::BitOrAssign(_) => "|=".to_string(),
        syn::BinOp::BitXorAssign(_) => "^=".to_string(),
        syn::BinOp::ShlAssign(_) => "<<=".to_string(),
        syn::BinOp::ShrAssign(_) => ">>=".to_string(),
        _ => "?".to_string(),
    }
}

// =============================================================================
// Template Expansion
// =============================================================================

/// Expand template with captured values
fn expand_template(template: &str, matches: &[MatchResult]) -> Vec<TextEdit> {
    let mut edits = Vec::new();

    for m in matches {
        let mut replacement = template.to_string();

        // Replace {{capture_name}} with captured text
        for capture in &m.captures {
            let placeholder = format!("{{{{{}}}}}", capture.name);
            replacement = replacement.replace(&placeholder, &capture.text);
        }

        edits.push(TextEdit {
            start_byte: m.start_byte,
            end_byte: m.end_byte,
            replacement,
        });
    }

    edits
}

// =============================================================================
// Edit Application
// =============================================================================

/// Apply text edits to source (in reverse order to preserve offsets)
fn apply_edits(source: &str, edits: &[TextEdit]) -> String {
    let mut result = source.to_string();

    // Sort edits in reverse order by start position
    let mut sorted_edits: Vec<_> = edits.iter().collect();
    sorted_edits.sort_by_key(|b| std::cmp::Reverse(b.start_byte));

    for edit in sorted_edits {
        let start = edit.start_byte as usize;
        let end = edit.end_byte as usize;

        if start <= end && end <= result.len() {
            result.replace_range(start..end, &edit.replacement);
        }
    }

    result
}

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

    #[test]
    fn test_parse_pattern() {
        let pattern = "binary_expr[op==\"==\", right==\"true\"]";
        let parsed = parse_pattern(pattern).unwrap();

        assert_eq!(parsed.node_type, "binary_expr");
        assert_eq!(parsed.conditions.len(), 2);
    }

    #[test]
    fn test_expand_template() {
        let template = "{{left}}";
        let matches = vec![MatchResult {
            kind: NodeKind::BinaryExpr,
            start_byte: 0,
            end_byte: 10,
            captures: vec![Capture {
                name: "left".to_string(),
                start_byte: 0,
                end_byte: 5,
                text: "is_ok".to_string(),
            }],
        }];

        let edits = expand_template(template, &matches);
        assert_eq!(edits.len(), 1);
        assert_eq!(edits[0].replacement, "is_ok");
    }

    #[test]
    fn test_op_to_string() {
        let eq_op = syn::BinOp::Eq(Default::default());
        assert_eq!(op_to_string(&eq_op), "==");
    }
}