ryo-executor 0.1.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
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
//! ASTRegApply implementations for AddItemMutation, AddPureItemsMutation, RemoveItemMutation, and MoveItemMutation

use ryo_analysis::AnalysisContext;
use ryo_mutations::{
    AddItemMutation, AddPureItemsMutation, MoveItemMutation, MutationResult, RemoveItemMutation,
};
use ryo_source::pure::{PureFile, PureItem, PureUse, PureUseTree, PureVis};
use ryo_source::ItemKind;
use ryo_symbol::{SymbolKind, SymbolPath, Visibility};

use crate::engine::{ASTMutationContext, ASTRegApply, ExecutionResult};

/// Add an item from raw source code content
pub fn add_item_v2(
    ctx: &mut AnalysisContext,
    target: &SymbolPath,
    content: &str,
) -> ExecutionResult {
    let mut mutation_ctx = ASTMutationContext::new(&mut ctx.ast_registry, &mut ctx.registry);

    let result = add_item_impl(&mut mutation_ctx, target, content);
    let events = mutation_ctx.into_events();

    ExecutionResult::new(result, events)
}

fn add_item_impl(
    ctx: &mut ASTMutationContext,
    target: &SymbolPath,
    content: &str,
) -> MutationResult {
    // Parse the content to get PureItem(s)
    let parsed = match PureFile::from_source(content.trim()) {
        Ok(file) => file,
        Err(e) => {
            return MutationResult {
                mutation_type: "AddItem".to_string(),
                changes: 0,
                description: format!("Failed to parse content: {}", e),
            };
        }
    };

    let items = parsed.items;
    if items.is_empty() {
        return MutationResult {
            mutation_type: "AddItem".to_string(),
            changes: 0,
            description: "No items found in content".to_string(),
        };
    }

    add_pure_items_impl(ctx, target, items, "AddItem")
}

/// Add pre-built PureItems to a module (shared logic for AddItem and AddPureItems)
fn add_pure_items_impl(
    ctx: &mut ASTMutationContext,
    target: &SymbolPath,
    items: Vec<PureItem>,
    mutation_type: &'static str,
) -> MutationResult {
    let mut added = 0;
    let mut descriptions = Vec::new();
    let mut skipped = Vec::new();

    for item in items {
        // For Mod items, we need to preserve visibility for SymbolRegistry
        let mod_visibility = if let PureItem::Mod(m) = &item {
            Some(pure_vis_to_visibility(&m.vis))
        } else {
            None
        };

        let (name, kind) = match &item {
            PureItem::Fn(f) => (f.name.clone(), SymbolKind::Function),
            PureItem::Struct(s) => (s.name.clone(), SymbolKind::Struct),
            PureItem::Enum(e) => (e.name.clone(), SymbolKind::Enum),
            PureItem::Const(c) => (c.name.clone(), SymbolKind::Const),
            PureItem::Static(s) => (s.name.clone(), SymbolKind::Static),
            PureItem::Type(t) => (t.name.clone(), SymbolKind::TypeAlias),
            PureItem::Trait(t) => (t.name.clone(), SymbolKind::Trait),
            PureItem::Mod(m) => (m.name.clone(), SymbolKind::Mod),
            PureItem::Impl(i) => {
                // Use common impl block registration logic
                match super::utils::register_impl_block(ctx, target, i) {
                    Ok(result) => {
                        // Count methods added (impl block itself may be merged)
                        added += result.methods_added;
                        descriptions.push(result.description);
                    }
                    Err(e) => {
                        skipped.push(format!("Impl block for '{}': {}", i.self_ty, e));
                    }
                }
                continue;
            }
            PureItem::Use(u) => {
                // Use statements are added to module_items without symbol registration
                // They don't have a "name" in the symbol registry sense

                // Find the target module ID
                let target_str = target.to_string();
                if let Some(module_id) = ctx.symbol_registry.lookup(target) {
                    // Get current module items and add the use statement at the beginning
                    let mut items = ctx
                        .ast_registry
                        .get_module_items(module_id)
                        .cloned()
                        .unwrap_or_default();

                    // Insert use statement at the beginning (after any existing use statements)
                    let insert_pos = items
                        .iter()
                        .position(|i| !matches!(i, PureItem::Use(_)))
                        .unwrap_or(items.len());
                    items.insert(insert_pos, PureItem::Use(u.clone()));

                    ctx.ast_registry.set_module_items(module_id, items);

                    // Emit event so sync_files_and_rebuild regenerates this module's file
                    ctx.emit_modified(
                        module_id,
                        crate::engine::events::ModificationType::Other(
                            "use statement added".to_string(),
                        ),
                    );

                    added += 1;
                    descriptions.push(format!("Added use statement to '{}'", target_str));
                }
                continue;
            }
            PureItem::Macro(_) | PureItem::Other(_) => {
                // Skip these for now
                continue;
            }
        };

        // Build the full path
        let target_str = target.to_string();
        let full_path = if target_str == "crate" {
            SymbolPath::parse(&format!("crate::{}", name))
        } else {
            SymbolPath::parse(&format!("{}::{}", target_str, name))
        };

        let path = match full_path {
            Ok(p) => p,
            Err(e) => {
                skipped.push(format!(
                    "{} '{}': invalid path ({})",
                    kind.display_name(),
                    name,
                    e
                ));
                continue;
            }
        };

        // Register the new symbol with its AST
        match ctx.register_with_ast(path.clone(), kind, item.clone()) {
            Some(id) => {
                // For Mod items, set visibility in SymbolRegistry
                // This is needed for RegistryGenerator to determine mod visibility
                if let Some(vis) = mod_visibility {
                    let _ = ctx.symbol_registry.set_visibility(id, vis);
                }

                // Mark inline modules: modules with non-empty items should be marked
                // as inline so RegistryGenerator keeps them in the parent file
                // instead of creating separate files for them.
                // This is important for operations like DuplicateModTree.
                if let PureItem::Mod(m) = &item {
                    if !m.items.is_empty() {
                        ctx.ast_registry.mark_inline_module(id);
                    }
                }

                // Also add to parent module's module_items for inline module preservation
                // This ensures RegistryGenerator sees the item in the parent's PureMod.items
                if let Some(parent_id) = ctx.symbol_registry.lookup(target) {
                    let mut items = ctx
                        .ast_registry
                        .get_module_items(parent_id)
                        .cloned()
                        .unwrap_or_default();
                    items.push(item);
                    ctx.ast_registry.set_module_items(parent_id, items);
                }

                added += 1;
                descriptions.push(format!("Added {} '{}'", kind.display_name(), name));
            }
            None => {
                skipped.push(format!(
                    "{} '{}': registration failed (symbol may already exist with different kind)",
                    kind.display_name(),
                    name
                ));
            }
        }
    }

    // Build description with both successes and failures
    let description = match (descriptions.is_empty(), skipped.is_empty()) {
        (true, true) => "No items added".to_string(),
        (true, false) => format!("No items added. Skipped: {}", skipped.join("; ")),
        (false, true) => descriptions.join(", "),
        (false, false) => format!(
            "{}. Skipped: {}",
            descriptions.join(", "),
            skipped.join("; ")
        ),
    };

    MutationResult {
        mutation_type: mutation_type.to_string(),
        changes: added,
        description,
    }
}

/// Remove an item by SymbolId
pub fn remove_item_v2(
    ctx: &mut AnalysisContext,
    symbol_id: ryo_symbol::SymbolId,
    item_kind: &crate::ItemKind,
) -> ExecutionResult {
    let mut mutation_ctx = ASTMutationContext::new(&mut ctx.ast_registry, &mut ctx.registry);

    let result = remove_item_impl(&mut mutation_ctx, symbol_id, item_kind);
    let events = mutation_ctx.into_events();

    ExecutionResult::new(result, events)
}

fn remove_item_impl(
    ctx: &mut ASTMutationContext,
    symbol_id: ryo_symbol::SymbolId,
    item_kind: &crate::ItemKind,
) -> MutationResult {
    // Remove the symbol directly via O(1) lookup
    ctx.remove_symbol(symbol_id);

    MutationResult {
        mutation_type: "RemoveItem".to_string(),
        changes: 1,
        description: format!("Removed {:?} ({:?})", item_kind, symbol_id),
    }
}

// ============================================================================
// ASTRegApply implementations
// ============================================================================

impl ASTRegApply for AddItemMutation {
    fn apply_to_registry(&self, ctx: &mut ASTMutationContext) -> MutationResult {
        // Use the provided symbol_id as the parent module
        let module_id = self.parent;

        // Verify the target is a module
        if ctx.symbol_registry.kind(module_id) != Some(SymbolKind::Mod) {
            return MutationResult {
                mutation_type: "AddItem".to_string(),
                changes: 0,
                description: format!("Target symbol {} is not a module", module_id),
            };
        }

        // Get the module path
        let target = match ctx.symbol_registry.path(module_id) {
            Some(p) => p.clone(),
            None => {
                return MutationResult {
                    mutation_type: "AddItem".to_string(),
                    changes: 0,
                    description: format!("Module {} not found in registry", module_id),
                };
            }
        };

        add_item_impl(ctx, &target, &self.content)
    }
}

impl ASTRegApply for AddPureItemsMutation {
    fn apply_to_registry(&self, ctx: &mut ASTMutationContext) -> MutationResult {
        // Use the provided symbol_id as the parent module
        let module_id = self.parent;

        // Verify the target is a module
        if ctx.symbol_registry.kind(module_id) != Some(SymbolKind::Mod) {
            return MutationResult {
                mutation_type: "AddPureItems".to_string(),
                changes: 0,
                description: format!("Target symbol {} is not a module", module_id),
            };
        }

        // Get the module path
        let target = match ctx.symbol_registry.path(module_id) {
            Some(p) => p.clone(),
            None => {
                return MutationResult {
                    mutation_type: "AddPureItems".to_string(),
                    changes: 0,
                    description: format!("Module {} not found in registry", module_id),
                };
            }
        };

        add_pure_items_impl(ctx, &target, self.items.clone(), "AddPureItems")
    }
}

impl ASTRegApply for RemoveItemMutation {
    fn apply_to_registry(&self, ctx: &mut ASTMutationContext) -> MutationResult {
        remove_item_impl(ctx, self.symbol_id, &self.item_kind)
    }
}

impl ASTRegApply for MoveItemMutation {
    fn apply_to_registry(&self, ctx: &mut ASTMutationContext) -> MutationResult {
        move_item_impl(
            ctx,
            &self.source,
            &self.target,
            &self.item_name,
            &self.item_kind,
            self.add_use,
        )
    }
}

/// Move an item from one module to another
fn move_item_impl(
    ctx: &mut ASTMutationContext,
    source: &SymbolPath,
    target: &SymbolPath,
    item_name: &str,
    item_kind: &ItemKind,
    add_use: bool,
) -> MutationResult {
    // Convert ItemKind to SymbolKind for lookup
    let expected_kind = match item_kind {
        ItemKind::Struct => Some(SymbolKind::Struct),
        ItemKind::Enum => Some(SymbolKind::Enum),
        ItemKind::Function => Some(SymbolKind::Function),
        ItemKind::Trait => Some(SymbolKind::Trait),
        ItemKind::Impl => Some(SymbolKind::Impl),
        ItemKind::TypeAlias => Some(SymbolKind::TypeAlias),
        ItemKind::Const => Some(SymbolKind::Const),
        ItemKind::Static => Some(SymbolKind::Static),
        ItemKind::Mod => Some(SymbolKind::Mod),
        _ => None,
    };

    // 1. Find source symbol by iterating registry (to match kind)
    let source_id = ctx
        .symbol_registry
        .iter()
        .find(|(id, path)| {
            let path_matches = path.name() == item_name && path.parent() == Some(source.clone());
            let kind_matches = expected_kind
                .map(|k| ctx.symbol_registry.kind(*id) == Some(k))
                .unwrap_or(true);
            path_matches && kind_matches
        })
        .map(|(id, _)| id);

    let source_id = match source_id {
        Some(id) => id,
        None => {
            return MutationResult {
                mutation_type: "MoveItem".to_string(),
                changes: 0,
                description: format!("Item '{}' not found in {}", item_name, source),
            };
        }
    };

    // 2. Get AST and kind before removing
    let ast = match ctx.get_ast(source_id).cloned() {
        Some(ast) => ast,
        None => {
            return MutationResult {
                mutation_type: "MoveItem".to_string(),
                changes: 0,
                description: format!("No AST found for '{}'", item_name),
            };
        }
    };
    let kind = ctx.kind(source_id).unwrap_or(SymbolKind::Struct);

    // 3. Remove from old location
    ctx.remove_symbol(source_id);

    // 4. Build target path
    let target_path = match target.child(item_name) {
        Ok(p) => p,
        Err(_) => {
            return MutationResult {
                mutation_type: "MoveItem".to_string(),
                changes: 0,
                description: format!("Invalid target path: {}::{}", target, item_name),
            };
        }
    };

    // 5. Register at new location
    if ctx
        .register_with_ast(target_path.clone(), kind, ast)
        .is_none()
    {
        return MutationResult {
            mutation_type: "MoveItem".to_string(),
            changes: 0,
            description: format!("Failed to register at new path: {}", target_path),
        };
    }

    // 6. Optionally add use statement in source module
    if add_use {
        // Build use path: target::item_name
        let use_path_str = format!("{}::{}", target, item_name);

        // Parse path into PureUseTree
        // e.g., "crate::core::Task" -> Path("crate", Path("core", Name("Task")))
        let parts: Vec<&str> = use_path_str.split("::").collect();
        let tree = parts
            .iter()
            .rev()
            .fold(None, |acc: Option<PureUseTree>, part| {
                Some(match acc {
                    None => PureUseTree::Name(part.to_string()),
                    Some(subtree) => PureUseTree::Path {
                        path: part.to_string(),
                        tree: Box::new(subtree),
                    },
                })
            })
            .unwrap_or(PureUseTree::Name(item_name.to_string()));

        let use_item = PureItem::Use(PureUse {
            vis: PureVis::Private,
            tree,
        });

        // Find source module and add use to its module_items
        if let Some(source_mod_id) = ctx.lookup(source) {
            let mut items = ctx
                .ast_registry
                .get_module_items(source_mod_id)
                .cloned()
                .unwrap_or_default();

            // Insert after existing use statements
            let insert_pos = items
                .iter()
                .position(|i| !matches!(i, PureItem::Use(_)))
                .unwrap_or(items.len());
            items.insert(insert_pos, use_item);

            ctx.ast_registry.set_module_items(source_mod_id, items);
        }
    }

    MutationResult {
        mutation_type: "MoveItem".to_string(),
        changes: 1,
        description: format!(
            "Moved {} '{}' from {} to {}",
            kind.display_name(),
            item_name,
            source,
            target
        ),
    }
}

/// Convert PureVis to ryo_symbol::Visibility
fn pure_vis_to_visibility(vis: &PureVis) -> Visibility {
    match vis {
        PureVis::Public => Visibility::Public,
        PureVis::Crate => Visibility::Crate,
        PureVis::Super => Visibility::Super,
        PureVis::Private => Visibility::Private,
        PureVis::In(path) => {
            // Try to parse as SymbolPath, fallback to Private if invalid
            ryo_symbol::SymbolPath::parse(path)
                .map(|p| Visibility::Restricted(Box::new(p)))
                .unwrap_or(Visibility::Private)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ryo_analysis::{ASTRegistry, SymbolRegistry};

    /// Test: Impl block methods are registered directly on parent type
    ///
    /// New design: impl blocks are file-level construct.
    /// Methods are registered as Struct::method, not <impl Struct>::N::method.
    #[test]
    fn test_add_impl_block_registers_methods_on_parent_type() {
        let mut ast_registry = ASTRegistry::new();
        let mut symbol_registry = SymbolRegistry::new();
        let mut ctx = ASTMutationContext::new(&mut ast_registry, &mut symbol_registry);

        // Register the parent struct first
        let struct_path = SymbolPath::parse("test_crate::TodoList").unwrap();
        ctx.register(struct_path.clone(), SymbolKind::Struct);

        let target = SymbolPath::parse("test_crate").unwrap();

        // Add impl block with method
        let impl_code = r#"
            impl TodoList {
                pub fn new() -> Self {
                    Self { items: vec![] }
                }
            }
        "#;
        let result = add_item_impl(&mut ctx, &target, impl_code);
        assert_eq!(result.changes, 1);

        // Verify method is registered as TodoList::new (not <impl TodoList>::N::new)
        let method_path = SymbolPath::parse("test_crate::TodoList::new").unwrap();
        let method_id = ctx.lookup(&method_path);
        assert!(
            method_id.is_some(),
            "Method should be registered as TodoList::new"
        );
        assert_eq!(ctx.kind(method_id.unwrap()), Some(SymbolKind::Method));
    }

    /// Test: Multiple impl blocks merge methods on parent type
    ///
    /// New design: All methods from different impl blocks are registered
    /// under the same parent type path.
    #[test]
    fn test_multiple_impl_blocks_methods_merged() {
        let mut ast_registry = ASTRegistry::new();
        let mut symbol_registry = SymbolRegistry::new();
        let mut ctx = ASTMutationContext::new(&mut ast_registry, &mut symbol_registry);

        // Register the parent struct first
        let struct_path = SymbolPath::parse("test_crate::TodoList").unwrap();
        ctx.register(struct_path.clone(), SymbolKind::Struct);

        let target = SymbolPath::parse("test_crate").unwrap();

        // Add first impl block
        let impl1 = r#"
            impl TodoList {
                pub fn new() -> Self {
                    Self { items: vec![] }
                }
            }
        "#;
        add_item_impl(&mut ctx, &target, impl1);

        // Add second impl block
        let impl2 = r#"
            impl TodoList {
                pub fn add(&mut self, item: String) {
                    self.items.push(item);
                }
            }
        "#;
        add_item_impl(&mut ctx, &target, impl2);

        // Verify both methods are under TodoList::
        let new_path = SymbolPath::parse("test_crate::TodoList::new").unwrap();
        let add_path = SymbolPath::parse("test_crate::TodoList::add").unwrap();

        assert!(
            ctx.lookup(&new_path).is_some(),
            "TodoList::new should exist"
        );
        assert!(
            ctx.lookup(&add_path).is_some(),
            "TodoList::add should exist"
        );

        // Verify both are methods
        assert_eq!(
            ctx.kind(ctx.lookup(&new_path).unwrap()),
            Some(SymbolKind::Method)
        );
        assert_eq!(
            ctx.kind(ctx.lookup(&add_path).unwrap()),
            Some(SymbolKind::Method)
        );
    }
}