ryo-source 0.1.0

High-speed Rust AST manipulation engine
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
//! Multi-file generator.
//!
//! Generates code into multiple files following Rust module conventions.
//! Supports both modern (`module.rs` + `module/`) and legacy (`module/mod.rs`) styles.

use super::{GeneratedSource, ModuleTree};
use crate::pure::{PureFile, PureItem, PureMod};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Result of multi-file generation.
#[derive(Debug, Clone, Default)]
pub struct GeneratedFiles {
    /// Map of relative file paths to generated source.
    pub files: HashMap<PathBuf, GeneratedSource>,
}

impl GeneratedFiles {
    /// Create empty GeneratedFiles.
    pub fn new() -> Self {
        Self::default()
    }

    /// Get all file paths.
    pub fn paths(&self) -> impl Iterator<Item = &PathBuf> {
        self.files.keys()
    }

    /// Get a specific file.
    pub fn get(&self, path: &Path) -> Option<&GeneratedSource> {
        self.files.get(path)
    }

    /// Get number of files.
    pub fn len(&self) -> usize {
        self.files.len()
    }

    /// Check if empty.
    pub fn is_empty(&self) -> bool {
        self.files.is_empty()
    }

    /// Compute diff against existing PureFiles.
    ///
    /// Returns only the files that have changed (or are new).
    /// Comparison is done on PureFile structure, not source text,
    /// so formatting differences are ignored.
    pub fn diff(&self, existing: &HashMap<PathBuf, PureFile>) -> GeneratedFiles {
        let mut changed = GeneratedFiles::new();

        for (path, generated) in &self.files {
            let is_changed = match existing.get(path) {
                None => true, // New file
                Some(existing_pure) => {
                    // Compare PureFile structures
                    // We use Debug representation for structural comparison
                    // This is not perfect but works for most cases
                    format!("{:?}", generated.pure_file) != format!("{:?}", existing_pure)
                }
            };

            if is_changed {
                changed.files.insert(path.clone(), generated.clone());
            }
        }

        changed
    }

    /// Get paths of files that would be deleted (exist in `existing` but not in generated).
    pub fn deleted_paths<'a>(&self, existing: &'a HashMap<PathBuf, PureFile>) -> Vec<&'a PathBuf> {
        existing
            .keys()
            .filter(|path| !self.files.contains_key(*path))
            .collect()
    }
}

/// Generator that outputs code into multiple files.
///
/// This generator follows Rust's module conventions:
///
/// **Modern style** (`use_mod_rs = false`):
/// ```text
/// src/
///   lib.rs           # crate root
///   models.rs        # mod models
///   models/
///     user.rs        # mod models::user
///     post.rs        # mod models::post
/// ```
///
/// **Legacy style** (`use_mod_rs = true`):
/// ```text
/// src/
///   lib.rs           # crate root
///   models/
///     mod.rs         # mod models
///     user.rs        # mod models::user
///     post.rs        # mod models::post
/// ```
#[derive(Debug, Clone)]
pub struct MultiFileGenerator {
    /// Use mod.rs style (legacy) instead of module.rs style (modern).
    pub use_mod_rs: bool,
    /// Root file name (default: "lib.rs").
    pub root_file: String,
}

impl Default for MultiFileGenerator {
    fn default() -> Self {
        Self {
            use_mod_rs: false,
            root_file: "lib.rs".to_string(),
        }
    }
}

impl MultiFileGenerator {
    /// Create a new multi-file generator with modern style.
    pub fn new() -> Self {
        Self::default()
    }

    /// Use legacy mod.rs style.
    pub fn with_mod_rs_style(mut self) -> Self {
        self.use_mod_rs = true;
        self
    }

    /// Set root file name (e.g., "main.rs" for binaries).
    pub fn with_root_file(mut self, name: impl Into<String>) -> Self {
        self.root_file = name.into();
        self
    }

    /// Generate files from a ModuleTree.
    pub fn generate(&self, tree: &ModuleTree) -> Result<GeneratedFiles, crate::pure::ToSynError> {
        let mut files = GeneratedFiles::new();
        let root_path = PathBuf::from(&self.root_file);

        self.generate_module(tree, &root_path, &PathBuf::new(), true, &mut files)?;

        Ok(files)
    }

    /// Generate a module and its children recursively.
    ///
    /// - `tree`: The module tree to generate
    /// - `file_path`: Path to the file for this module
    /// - `dir_path`: Directory path for child modules
    /// - `is_root`: Whether this is the crate root
    /// - `files`: Output map
    fn generate_module(
        &self,
        tree: &ModuleTree,
        file_path: &Path,
        dir_path: &Path,
        is_root: bool,
        files: &mut GeneratedFiles,
    ) -> Result<(), crate::pure::ToSynError> {
        // Build items for this module
        let mut items = Vec::new();

        // Add uses first
        for u in &tree.uses {
            items.push(PureItem::Use(u.clone()));
        }

        // Add items
        items.extend(tree.items.iter().cloned());

        // Add mod declarations for children (without content - they're in separate files)
        for child in &tree.children {
            items.push(PureItem::Mod(PureMod {
                attrs: vec![],
                vis: child.vis.clone(),
                name: child.name.clone(),
                items: vec![], // External module - no inline content
            }));
        }

        // Create PureFile for this module
        let pure_file = PureFile {
            attrs: tree.inner_attrs.clone(),
            items,
        };

        let source = pure_file.to_source()?;
        files.files.insert(
            file_path.to_path_buf(),
            GeneratedSource { source, pure_file },
        );

        // Generate child modules recursively
        for child in &tree.children {
            let (child_file_path, child_dir_path) = if self.use_mod_rs {
                // Legacy style: module/mod.rs
                let child_dir = dir_path.join(&child.name);
                let child_file = child_dir.join("mod.rs");
                (child_file, child_dir)
            } else {
                // Modern style: module.rs + module/
                if child.children.is_empty() && is_root {
                    // Leaf module at root level: just module.rs
                    let child_file = dir_path.join(format!("{}.rs", child.name));
                    (child_file, dir_path.join(&child.name))
                } else if child.children.is_empty() {
                    // Leaf module in subdir: dir/module.rs
                    let child_file = dir_path.join(format!("{}.rs", child.name));
                    (child_file, dir_path.join(&child.name))
                } else {
                    // Non-leaf module: module.rs + module/
                    let child_file = dir_path.join(format!("{}.rs", child.name));
                    let child_dir = dir_path.join(&child.name);
                    (child_file, child_dir)
                }
            };

            self.generate_module(child, &child_file_path, &child_dir_path, false, files)?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pure::{
        PureBlock, PureFields, PureFn, PureGenerics, PureStruct, PureUse, PureUseTree, PureVis,
    };

    fn make_struct(name: &str) -> PureItem {
        PureItem::Struct(PureStruct {
            attrs: vec![],
            vis: PureVis::Public,
            name: name.to_string(),
            generics: PureGenerics::default(),
            fields: PureFields::Unit,
        })
    }

    fn make_fn(name: &str) -> PureItem {
        PureItem::Fn(PureFn {
            attrs: vec![],
            vis: PureVis::Public,
            is_async: false,
            is_async_inferred: false,
            is_const: false,
            is_unsafe: false,
            abi: None,
            name: name.to_string(),
            generics: PureGenerics::default(),
            params: vec![],
            ret: None,
            body: PureBlock::default(),
        })
    }

    fn make_use(path: &str) -> PureUse {
        let parts: Vec<&str> = path.split("::").collect();
        let tree = build_use_tree(&parts);
        PureUse {
            vis: PureVis::Private,
            tree,
        }
    }

    fn build_use_tree(parts: &[&str]) -> PureUseTree {
        if parts.len() == 1 {
            PureUseTree::Name(parts[0].to_string())
        } else {
            PureUseTree::Path {
                path: parts[0].to_string(),
                tree: Box::new(build_use_tree(&parts[1..])),
            }
        }
    }

    // ========================================================================
    // Basic Tests
    // ========================================================================

    #[test]
    fn test_multi_file_single_module() {
        let tree = ModuleTree::crate_root().with_item(make_struct("Config"));

        let generator = MultiFileGenerator::new();
        let result = generator.generate(&tree).unwrap();

        assert_eq!(result.len(), 1);
        assert!(result.get(Path::new("lib.rs")).is_some());

        let lib = result.get(Path::new("lib.rs")).unwrap();
        assert!(lib.source.contains("struct Config"));
    }

    #[test]
    fn test_multi_file_with_child_modern_style() {
        let tree = ModuleTree::crate_root()
            .with_item(make_struct("Config"))
            .with_child(
                ModuleTree::new("models")
                    .with_vis(PureVis::Public)
                    .with_item(make_struct("User")),
            );

        let generator = MultiFileGenerator::new();
        let result = generator.generate(&tree).unwrap();

        assert_eq!(result.len(), 2);

        // lib.rs should have mod declaration
        let lib = result.get(Path::new("lib.rs")).unwrap();
        assert!(lib.source.contains("struct Config"));
        assert!(lib.source.contains("pub mod models;"));
        assert!(!lib.source.contains("struct User")); // User is in separate file

        // models.rs should have User
        let models = result.get(Path::new("models.rs")).unwrap();
        assert!(models.source.contains("struct User"));
    }

    #[test]
    fn test_multi_file_with_child_mod_rs_style() {
        let tree = ModuleTree::crate_root()
            .with_item(make_struct("Config"))
            .with_child(
                ModuleTree::new("models")
                    .with_vis(PureVis::Public)
                    .with_item(make_struct("User")),
            );

        let generator = MultiFileGenerator::new().with_mod_rs_style();
        let result = generator.generate(&tree).unwrap();

        assert_eq!(result.len(), 2);

        // lib.rs should have mod declaration
        let lib = result.get(Path::new("lib.rs")).unwrap();
        assert!(lib.source.contains("pub mod models;"));

        // models/mod.rs should have User
        let models = result.get(Path::new("models/mod.rs")).unwrap();
        assert!(models.source.contains("struct User"));
    }

    #[test]
    fn test_multi_file_nested_modules() {
        let tree = ModuleTree::crate_root().with_child(
            ModuleTree::new("models")
                .with_vis(PureVis::Public)
                .with_item(make_struct("User"))
                .with_child(
                    ModuleTree::new("dto")
                        .with_vis(PureVis::Public)
                        .with_item(make_struct("UserDto")),
                ),
        );

        let generator = MultiFileGenerator::new();
        let result = generator.generate(&tree).unwrap();

        assert_eq!(result.len(), 3);

        // Check file structure
        assert!(result.get(Path::new("lib.rs")).is_some());
        assert!(result.get(Path::new("models.rs")).is_some());
        assert!(result.get(Path::new("models/dto.rs")).is_some());

        // Check content
        let lib = result.get(Path::new("lib.rs")).unwrap();
        assert!(lib.source.contains("pub mod models;"));

        let models = result.get(Path::new("models.rs")).unwrap();
        assert!(models.source.contains("struct User"));
        assert!(models.source.contains("pub mod dto;"));

        let dto = result.get(Path::new("models/dto.rs")).unwrap();
        assert!(dto.source.contains("struct UserDto"));
    }

    #[test]
    fn test_multi_file_with_uses() {
        let tree = ModuleTree::crate_root()
            .with_use(make_use("std::io"))
            .with_child(
                ModuleTree::new("utils")
                    .with_use(make_use("std::fmt"))
                    .with_item(make_fn("helper")),
            );

        let generator = MultiFileGenerator::new();
        let result = generator.generate(&tree).unwrap();

        let lib = result.get(Path::new("lib.rs")).unwrap();
        assert!(lib.source.contains("use std") && lib.source.contains("io"));

        let utils = result.get(Path::new("utils.rs")).unwrap();
        assert!(utils.source.contains("use std") && utils.source.contains("fmt"));
    }

    // ========================================================================
    // Diff Tests
    // ========================================================================

    #[test]
    fn test_diff_new_file() {
        let tree = ModuleTree::crate_root().with_item(make_struct("Config"));

        let generator = MultiFileGenerator::new();
        let generated = generator.generate(&tree).unwrap();

        // No existing files
        let existing: HashMap<PathBuf, PureFile> = HashMap::new();
        let diff = generated.diff(&existing);

        // All files should be in diff (they're new)
        assert_eq!(diff.len(), 1);
    }

    #[test]
    fn test_diff_unchanged() {
        let tree = ModuleTree::crate_root().with_item(make_struct("Config"));

        let generator = MultiFileGenerator::new();
        let generated = generator.generate(&tree).unwrap();

        // Same PureFile as generated
        let mut existing: HashMap<PathBuf, PureFile> = HashMap::new();
        existing.insert(
            PathBuf::from("lib.rs"),
            generated
                .get(Path::new("lib.rs"))
                .unwrap()
                .pure_file
                .clone(),
        );

        let diff = generated.diff(&existing);

        // No changes
        assert_eq!(diff.len(), 0);
    }

    #[test]
    fn test_diff_changed() {
        let tree = ModuleTree::crate_root().with_item(make_struct("Config"));

        let generator = MultiFileGenerator::new();
        let generated = generator.generate(&tree).unwrap();

        // Different PureFile
        let mut existing: HashMap<PathBuf, PureFile> = HashMap::new();
        existing.insert(
            PathBuf::from("lib.rs"),
            PureFile {
                attrs: vec![],
                items: vec![make_struct("OldConfig")], // Different!
            },
        );

        let diff = generated.diff(&existing);

        // lib.rs changed
        assert_eq!(diff.len(), 1);
        assert!(diff.get(Path::new("lib.rs")).is_some());
    }

    #[test]
    fn test_deleted_paths() {
        let tree = ModuleTree::crate_root().with_item(make_struct("Config"));

        let generator = MultiFileGenerator::new();
        let generated = generator.generate(&tree).unwrap();

        // Existing has extra file
        let mut existing: HashMap<PathBuf, PureFile> = HashMap::new();
        existing.insert(PathBuf::from("lib.rs"), PureFile::default());
        existing.insert(PathBuf::from("old_module.rs"), PureFile::default());

        let deleted = generated.deleted_paths(&existing);

        assert_eq!(deleted.len(), 1);
        assert_eq!(deleted[0], &PathBuf::from("old_module.rs"));
    }

    // ========================================================================
    // Main.rs Tests
    // ========================================================================

    #[test]
    fn test_multi_file_main_rs() {
        let tree = ModuleTree::crate_root().with_item(make_fn("main"));

        let generator = MultiFileGenerator::new().with_root_file("main.rs");
        let result = generator.generate(&tree).unwrap();

        assert!(result.get(Path::new("main.rs")).is_some());
        assert!(result.get(Path::new("lib.rs")).is_none());
    }

    // ========================================================================
    // Deep Nesting Tests
    // ========================================================================

    #[test]
    fn test_multi_file_deep_nesting() {
        let tree = ModuleTree::crate_root().with_child(ModuleTree::new("a").with_child(
            ModuleTree::new("b").with_child(ModuleTree::new("c").with_item(make_struct("Deep"))),
        ));

        let generator = MultiFileGenerator::new();
        let result = generator.generate(&tree).unwrap();

        // Should have: lib.rs, a.rs, a/b.rs, a/b/c.rs
        assert_eq!(result.len(), 4);
        assert!(result.get(Path::new("lib.rs")).is_some());
        assert!(result.get(Path::new("a.rs")).is_some());
        assert!(result.get(Path::new("a/b.rs")).is_some());
        assert!(result.get(Path::new("a/b/c.rs")).is_some());

        let c = result.get(Path::new("a/b/c.rs")).unwrap();
        assert!(c.source.contains("struct Deep"));
    }

    #[test]
    fn test_multi_file_deep_nesting_mod_rs() {
        let tree = ModuleTree::crate_root().with_child(
            ModuleTree::new("a").with_child(ModuleTree::new("b").with_item(make_struct("Deep"))),
        );

        let generator = MultiFileGenerator::new().with_mod_rs_style();
        let result = generator.generate(&tree).unwrap();

        // Should have: lib.rs, a/mod.rs, a/b/mod.rs
        assert_eq!(result.len(), 3);
        assert!(result.get(Path::new("lib.rs")).is_some());
        assert!(result.get(Path::new("a/mod.rs")).is_some());
        assert!(result.get(Path::new("a/b/mod.rs")).is_some());
    }

    // ========================================================================
    // Valid Rust Tests
    // ========================================================================

    #[test]
    fn test_all_generated_files_are_valid_rust() {
        let tree = ModuleTree::crate_root()
            .with_use(make_use("std::collections::HashMap"))
            .with_item(make_struct("App"))
            .with_child(
                ModuleTree::new("models")
                    .with_vis(PureVis::Public)
                    .with_item(make_struct("User"))
                    .with_child(
                        ModuleTree::new("dto")
                            .with_vis(PureVis::Public)
                            .with_item(make_struct("UserDto")),
                    ),
            )
            .with_child(ModuleTree::new("utils").with_item(make_fn("helper")));

        let generator = MultiFileGenerator::new();
        let result = generator.generate(&tree).unwrap();

        for (path, generated) in &result.files {
            syn::parse_str::<syn::File>(&generated.source).unwrap_or_else(|_| {
                panic!(
                    "File {} should be valid Rust:\n{}",
                    path.display(),
                    generated.source
                )
            });
        }
    }
}