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
//! Integration tests for AST Mutation Engine pipeline
//!
//! Tests the full pipeline: Mutation → ASTRegistry → FileDumper

#[cfg(test)]
mod integration {
    use ryo_analysis::{AnalysisContext, SymbolKind, SymbolPath};
    use ryo_mutations::basic::{AddFieldMutation, CreateModMutation};
    use ryo_source::pure::{PureField, PureFields, PureFile, PureItem, PureStruct, PureVis};
    use ryo_symbol::WorkspaceFilePath;
    use std::sync::Arc;

    use crate::engine::{multi_file_dumper, ASTMutationEngine};

    /// Create a minimal AnalysisContext for testing
    fn test_context() -> AnalysisContext {
        let file_path = WorkspaceFilePath::new_for_test("src/lib.rs", "/test", "crate");
        let file = Arc::new(PureFile::new());
        let mut files = im::HashMap::new();
        files.insert(file_path, file);
        AnalysisContext::from_im_files(files)
    }

    /// Helper to create a test struct
    fn create_test_struct(name: &str) -> PureStruct {
        PureStruct {
            attrs: vec![],
            vis: PureVis::Public,
            name: name.to_string(),
            generics: Default::default(),
            fields: PureFields::Named(vec![]),
        }
    }

    #[test]
    fn test_add_field_to_registry() {
        let mut ctx = test_context();

        // Register a struct symbol
        let path = SymbolPath::parse("test_crate::MyStruct").unwrap();
        let id = ctx
            .registry
            .register(path.clone(), SymbolKind::Struct)
            .unwrap();

        // Add AST to registry
        let struct_ast = create_test_struct("MyStruct");
        ctx.ast_registry.set(id, PureItem::Struct(struct_ast));

        // Create and execute mutation
        let mutation = AddFieldMutation::new(id, "new_field", "i32");
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        // Verify result
        assert!(result.has_changes(), "Mutation should have made changes");
        assert_eq!(result.result.changes, 1);
        assert!(!result.events.is_empty(), "Should have emitted events");

        // Verify AST was modified
        let ast = ctx.ast_registry.get(id).expect("AST should exist");
        if let PureItem::Struct(s) = ast {
            if let PureFields::Named(fields) = &s.fields {
                assert_eq!(fields.len(), 1, "Should have one field");
                assert_eq!(fields[0].name, "new_field");
            } else {
                panic!("Expected named fields");
            }
        } else {
            panic!("Expected struct");
        }
    }

    #[test]
    fn test_create_mod_to_registry() {
        let mut ctx = test_context();

        // Register the crate module manually
        let crate_path = SymbolPath::parse("test_crate").unwrap();
        let crate_id = ctx
            .registry
            .register(crate_path.clone(), SymbolKind::Mod)
            .unwrap();

        // Create and execute mutation (CreateMod = AddMod with optional content)
        let mutation = CreateModMutation::new(crate_id, "my_module").public();
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        // Verify result
        assert!(result.has_changes(), "Mutation should have made changes");
        assert_eq!(result.result.changes, 1);

        // Verify symbol was registered
        let path = SymbolPath::parse("test_crate::my_module").unwrap();
        let id = ctx.registry.lookup(&path);
        assert!(id.is_some(), "Module should be registered");

        // Note: CreateMod does NOT store mod declarations in ASTRegistry.
        // RegistryGenerator automatically generates mod declarations from module hierarchy.
        // The module exists in SymbolRegistry with Mod kind.
        let id = id.unwrap();
        assert_eq!(
            ctx.registry.kind(id),
            Some(SymbolKind::Mod),
            "Should be Mod kind"
        );
        // ast_registry.get(id) returns None because mod declarations are not stored
        assert!(
            ctx.ast_registry.get(id).is_none(),
            "Mod declarations should not be in ASTRegistry"
        );
    }

    #[test]
    fn test_file_dumper_output() {
        let mut ctx = test_context();

        // Setup: Register struct and add AST
        let path = SymbolPath::parse("test_crate::TestStruct").unwrap();
        let id = ctx
            .registry
            .register(path.clone(), SymbolKind::Struct)
            .unwrap();

        // Create struct with a field
        let struct_ast = PureStruct {
            attrs: vec![],
            vis: PureVis::Public,
            name: "TestStruct".to_string(),
            generics: Default::default(),
            fields: PureFields::Named(vec![PureField {
                attrs: vec![],
                vis: PureVis::Public,
                name: "value".to_string(),
                ty: ryo_source::pure::PureType::Path("i32".to_string()),
            }]),
        };
        ctx.ast_registry.set(id, PureItem::Struct(struct_ast));

        // Set span for file association
        let file_path = WorkspaceFilePath::new_for_test("src/lib.rs", "/test", "crate");
        let _ = ctx.registry.set_span(
            id,
            ryo_symbol::FileSpan {
                file: file_path.clone(),
                start: 0,
                end: 100,
            },
        );

        // Dump to files
        let files = multi_file_dumper().dump_all(&ctx).unwrap();

        // Verify output
        assert!(!files.is_empty(), "Should have generated files");

        if let Some(content) = files.get(&file_path) {
            assert!(content.contains("TestStruct"), "Should contain struct name");
            assert!(content.contains("value"), "Should contain field name");
            assert!(content.contains("i32"), "Should contain field type");
        } else {
            // File might not be found if span-based grouping doesn't match
            // This is expected in minimal test setup
            println!("Note: File not found in dump output (expected in minimal test)");
        }
    }

    #[test]
    fn test_full_pipeline_add_field() {
        let mut ctx = test_context();

        // Setup: Create a struct in the registry
        let path = SymbolPath::parse("test_crate::User").unwrap();
        let id = ctx.registry.register(path, SymbolKind::Struct).unwrap();
        let struct_ast = create_test_struct("User");
        ctx.ast_registry.set(id, PureItem::Struct(struct_ast));

        // Execute mutation
        let mutation = AddFieldMutation::new(id, "name", "String").public();
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        assert!(result.has_changes());

        // Verify AST state
        let ast = ctx.ast_registry.get(id).unwrap();
        if let PureItem::Struct(s) = ast {
            if let PureFields::Named(fields) = &s.fields {
                assert_eq!(fields.len(), 1);
                assert_eq!(fields[0].name, "name");
                assert!(matches!(fields[0].vis, PureVis::Public));
            }
        }
    }

    // ========================================================================
    // Integration tests using ContextBuilder (realistic file-based setup)
    // ========================================================================

    mod context_builder_tests {
        use super::*;
        use ryo_analysis::testing::ContextBuilder;
        use ryo_mutations::basic::RemoveFieldMutation;

        /// Verify ASTRegistry is populated from parsed files
        #[test]
        fn test_ast_registry_populated_from_file() {
            let ctx = ContextBuilder::new()
                .with_file("src/lib.rs", "pub struct Config { name: String }")
                .build();

            // Check that ASTRegistry has the struct
            let path = SymbolPath::parse("test_crate::Config").unwrap();
            let id = ctx
                .registry()
                .lookup(&path)
                .expect("Config should be registered");

            let ast = ctx.ast_registry.get(id).expect("AST should exist");
            if let PureItem::Struct(s) = ast {
                assert_eq!(s.name, "Config");
                if let PureFields::Named(fields) = &s.fields {
                    assert_eq!(fields.len(), 1);
                    assert_eq!(fields[0].name, "name");
                }
            } else {
                panic!("Expected struct item");
            }
        }

        /// Test AddField mutation with ContextBuilder-created context
        #[test]
        fn test_add_field_via_context_builder() {
            let mut ctx = ContextBuilder::new()
                .with_file("src/lib.rs", "pub struct User { id: u32 }")
                .build();

            // Verify initial state
            let path = SymbolPath::parse("test_crate::User").unwrap();
            let id = ctx.registry().lookup(&path).expect("User should exist");

            let ast = ctx.ast_registry.get(id).expect("AST should exist");
            if let PureItem::Struct(s) = ast {
                if let PureFields::Named(fields) = &s.fields {
                    assert_eq!(fields.len(), 1, "Should have 1 field initially");
                }
            }

            // Execute mutation via ASTMutationEngine
            let mutation = AddFieldMutation::new(id, "name", "String").public();
            let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

            assert!(result.has_changes(), "Mutation should succeed");
            assert_eq!(result.result.changes, 1);

            // Verify AST was modified
            let ast = ctx.ast_registry.get(id).unwrap();
            if let PureItem::Struct(s) = ast {
                if let PureFields::Named(fields) = &s.fields {
                    assert_eq!(fields.len(), 2, "Should have 2 fields after mutation");
                    assert_eq!(fields[1].name, "name");
                }
            }

            // Dump to files and verify output
            let files = multi_file_dumper().dump_all(&ctx).unwrap();
            let lib_path =
                ryo_symbol::WorkspaceFilePath::new_for_test("src/lib.rs", "/test", "crate");
            if let Some(content) = files.get(&lib_path) {
                assert!(content.contains("User"), "Should contain struct name");
                assert!(content.contains("name"), "Should contain new field");
                assert!(content.contains("String"), "Should contain field type");
            }
        }

        /// Test RemoveField mutation
        #[test]
        fn test_remove_field_via_context_builder() {
            let mut ctx = ContextBuilder::new()
                .with_file(
                    "src/lib.rs",
                    "pub struct Config { name: String, value: i32 }",
                )
                .build();

            let path = SymbolPath::parse("test_crate::Config").unwrap();
            let id = ctx.registry().lookup(&path).expect("Config should exist");

            // Execute RemoveField mutation
            let mutation = RemoveFieldMutation::new(id, "name");
            let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

            assert!(result.has_changes());

            // Verify field was removed
            let ast = ctx.ast_registry.get(id).unwrap();
            if let PureItem::Struct(s) = ast {
                if let PureFields::Named(fields) = &s.fields {
                    assert_eq!(fields.len(), 1, "Should have 1 field after removal");
                    assert_eq!(fields[0].name, "value", "Remaining field should be 'value'");
                }
            }
        }

        /// Test multiple mutations in sequence
        #[test]
        fn test_multiple_mutations_sequence() {
            let mut ctx = ContextBuilder::new()
                .with_file("src/lib.rs", "pub struct Entity {}")
                .build();

            // Lookup the struct id before creating mutations
            let path = SymbolPath::parse("test_crate::Entity").unwrap();
            let id = ctx.registry().lookup(&path).unwrap();

            // Add multiple fields
            let mutations = vec![
                AddFieldMutation::new(id, "id", "u64").public(),
                AddFieldMutation::new(id, "name", "String").public(),
                AddFieldMutation::new(id, "created_at", "i64"),
            ];

            for mutation in &mutations {
                let result = ASTMutationEngine::execute_ast_reg(mutation, &mut ctx);
                assert!(result.has_changes());
            }

            // Verify all fields were added
            let ast = ctx.ast_registry.get(id).unwrap();

            if let PureItem::Struct(s) = ast {
                if let PureFields::Named(fields) = &s.fields {
                    assert_eq!(fields.len(), 3);
                    assert_eq!(fields[0].name, "id");
                    assert_eq!(fields[1].name, "name");
                    assert_eq!(fields[2].name, "created_at");
                }
            }
        }

        /// Test CreateMod creates new module
        #[test]
        fn test_create_mod_creates_module() {
            let mut ctx = ContextBuilder::new()
                .with_file("src/lib.rs", "// lib.rs")
                .build();

            // Get the crate module SymbolId
            let crate_path = SymbolPath::parse("test_crate").unwrap();
            let crate_id = ctx
                .registry
                .lookup(&crate_path)
                .expect("crate module should exist");

            let mutation = CreateModMutation::new(crate_id, "models").public();
            let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

            assert!(result.has_changes());

            // Verify module was registered
            let path = SymbolPath::parse("test_crate::models").unwrap();
            let id = ctx.registry().lookup(&path);
            assert!(id.is_some(), "Module should be registered");

            // Note: CreateMod does NOT store mod declarations in ASTRegistry.
            // RegistryGenerator generates mod declarations from module hierarchy.
            let id = id.unwrap();
            assert_eq!(
                ctx.registry().kind(id),
                Some(SymbolKind::Mod),
                "Should be Mod kind"
            );
            assert!(
                ctx.ast_registry.get(id).is_none(),
                "Mod declarations should not be in ASTRegistry"
            );
        }

        /// Test idempotent behavior: adding same field twice should fail
        #[test]
        fn test_add_field_idempotent() {
            let mut ctx = ContextBuilder::new()
                .with_file("src/lib.rs", "pub struct Data {}")
                .build();

            let path = SymbolPath::parse("test_crate::Data").unwrap();
            let id = ctx.registry().lookup(&path).unwrap();

            let mutation = AddFieldMutation::new(id, "value", "i32");

            // First add should succeed
            let result1 = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);
            assert!(result1.has_changes());

            // Second add should fail (field already exists)
            let result2 = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);
            assert!(
                !result2.has_changes(),
                "Adding same field twice should not change anything"
            );
        }
    }

    // ========================================================================
    // BlueprintExecutor V2 tests
    // ========================================================================

    mod blueprint_v2_tests {
        use crate::executor::{
            BlueprintExecutor, MutationSpec, MutationTargetSymbol, ParallelBlueprint, Visibility,
        };
        use ryo_analysis::testing::ContextBuilder;
        use ryo_analysis::SymbolPath;

        #[test]
        fn test_execute_v2_add_field() {
            let mut ctx = ContextBuilder::new()
                .with_file("src/lib.rs", "pub struct Config { name: String }")
                .build();

            // Lookup the actual SymbolId
            let path = SymbolPath::parse("test_crate::Config").unwrap();
            let symbol_id = ctx.registry().lookup(&path).expect("Config should exist");

            let spec = MutationSpec::AddField {
                target: MutationTargetSymbol::ById(symbol_id),
                field_name: "value".to_string(),
                field_type: "i32".to_string(),
                visibility: Visibility::Pub,
            };

            let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
            let executor = BlueprintExecutor::new();
            let result = executor.execute_v2(&blueprint, &mut ctx);

            assert!(
                result.success,
                "execute_v2 should succeed: {:?}",
                result.error
            );
            assert_eq!(result.results.len(), 1);
            assert!(result.results[0].success);

            // Sync files after execute_v2 (required for ctx.files() to see changes)
            let _ = BlueprintExecutor::sync_files_and_rebuild(&result, &mut ctx);

            // Verify the file was regenerated with new field
            let file = ctx.files().iter().next().unwrap().1;
            let source = file.to_source().unwrap();
            assert!(
                source.contains("value"),
                "Output should contain new field: {}",
                source
            );
        }

        #[test]
        fn test_execute_v2_remove_field() {
            let mut ctx = ContextBuilder::new()
                .with_file("src/lib.rs", "pub struct User { id: u32, name: String }")
                .build();

            // Lookup the actual SymbolId
            let path = SymbolPath::parse("test_crate::User").unwrap();
            let symbol_id = ctx.registry().lookup(&path).expect("User should exist");

            let spec = MutationSpec::RemoveField {
                target: MutationTargetSymbol::ById(symbol_id),
                field_name: "name".to_string(),
            };

            let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
            let executor = BlueprintExecutor::new();
            let result = executor.execute_v2(&blueprint, &mut ctx);

            assert!(result.success);

            // Sync files after execute_v2 (required for ctx.files() to see changes)
            let _ = BlueprintExecutor::sync_files_and_rebuild(&result, &mut ctx);

            let file = ctx.files().iter().next().unwrap().1;
            let source = file.to_source().unwrap();
            assert!(source.contains("id"), "Should still have id field");
            assert!(
                !source.contains("name"),
                "Should not have name field: {}",
                source
            );
        }

        #[test]
        fn test_execute_v2_create_mod() {
            let mut ctx = ContextBuilder::new()
                .with_file("src/lib.rs", "// lib.rs")
                .build();

            let spec = MutationSpec::CreateMod {
                target: MutationTargetSymbol::ByPath(Box::new(
                    SymbolPath::parse("test_crate").unwrap(),
                )),
                mod_name: "models".to_string(),
                content: String::new(),
                is_pub: true,
            };

            let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
            let executor = BlueprintExecutor::new();
            let result = executor.execute_v2(&blueprint, &mut ctx);

            assert!(
                result.success,
                "CreateMod should succeed: {:?}",
                result.error
            );

            // Verify module was registered
            let path = SymbolPath::parse("test_crate::models").unwrap();
            assert!(
                ctx.registry().lookup(&path).is_some(),
                "Module should be registered"
            );
        }

        #[test]
        fn test_execute_v2_multiple_specs() {
            let mut ctx = ContextBuilder::new()
                .with_file("src/lib.rs", "pub struct Entity {}")
                .build();

            // Lookup the actual SymbolId
            let path = SymbolPath::parse("test_crate::Entity").unwrap();
            let symbol_id = ctx.registry().lookup(&path).expect("Entity should exist");

            let specs = vec![
                MutationSpec::AddField {
                    target: MutationTargetSymbol::ById(symbol_id),
                    field_name: "id".to_string(),
                    field_type: "u64".to_string(),
                    visibility: Visibility::Pub,
                },
                MutationSpec::AddField {
                    target: MutationTargetSymbol::ById(symbol_id),
                    field_name: "name".to_string(),
                    field_type: "String".to_string(),
                    visibility: Visibility::Pub,
                },
            ];

            let blueprint = ParallelBlueprint::from_mutations(specs);
            let executor = BlueprintExecutor::new();
            let result = executor.execute_v2(&blueprint, &mut ctx);

            assert!(result.success);
            assert_eq!(result.results.len(), 2);

            // Sync files after execute_v2 (required for ctx.files() to see changes)
            let _ = BlueprintExecutor::sync_files_and_rebuild(&result, &mut ctx);

            let file = ctx.files().iter().next().unwrap().1;
            let source = file.to_source().unwrap();
            assert!(source.contains("id"), "Should have id field: {}", source);
            assert!(
                source.contains("name"),
                "Should have name field: {}",
                source
            );
        }

        // Note: test_execute_v2_unimplemented_panics was removed because
        // LoopToIterator is now implemented in V2
    }
}