splitrs 0.3.1

AST-based Rust refactoring tool with trait separation, config files, and intelligent module generation
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
//! Integration tests for SplitRS
//!
//! These tests verify end-to-end functionality by:
//! - Creating temporary test files
//! - Running the full refactoring pipeline
//! - Verifying the generated modules compile and work correctly

use std::fs;
use std::path::PathBuf;
use tempfile::TempDir;

/// Helper function to create a temporary directory with a test file
fn create_test_file(content: &str) -> (TempDir, PathBuf) {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let test_file = temp_dir.path().join("test.rs");
    fs::write(&test_file, content).expect("Failed to write test file");
    (temp_dir, test_file)
}

#[test]
fn test_simple_struct_splitting() {
    let code = r#"
        use std::collections::HashMap;

        pub struct User {
            name: String,
            age: u32,
        }

        impl User {
            pub fn new(name: String, age: u32) -> Self {
                Self { name, age }
            }

            pub fn get_name(&self) -> &str {
                &self.name
            }

            pub fn get_age(&self) -> u32 {
                self.age
            }

            pub fn set_age(&mut self, age: u32) {
                self.age = age;
            }
        }

        pub struct Product {
            id: u64,
            name: String,
            price: f64,
        }

        impl Product {
            pub fn new(id: u64, name: String, price: f64) -> Self {
                Self { id, name, price }
            }

            pub fn get_price(&self) -> f64 {
                self.price
            }
        }
    "#;

    let (_temp_dir, test_file) = create_test_file(code);
    let output_dir = _temp_dir.path().join("output");
    fs::create_dir_all(&output_dir).expect("Failed to create output dir");

    // Parse and verify
    let source_code = fs::read_to_string(&test_file).expect("Failed to read file");
    let syntax_tree = syn::parse_file(&source_code).expect("Failed to parse");

    // Should have parsed successfully
    assert!(!syntax_tree.items.is_empty());

    // Verify we found the structs
    let structs: Vec<_> = syntax_tree
        .items
        .iter()
        .filter_map(|item| match item {
            syn::Item::Struct(s) => Some(s.ident.to_string()),
            _ => None,
        })
        .collect();

    assert_eq!(structs.len(), 2);
    assert!(structs.contains(&"User".to_string()));
    assert!(structs.contains(&"Product".to_string()));
}

#[test]
fn test_trait_implementations_parsing() {
    let code = r#"
        use std::fmt::{Debug, Display};

        pub struct User {
            name: String,
            age: u32,
        }

        impl Debug for User {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_struct("User")
                    .field("name", &self.name)
                    .field("age", &self.age)
                    .finish()
            }
        }

        impl Display for User {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{} ({})", self.name, self.age)
            }
        }

        impl User {
            pub fn new(name: String, age: u32) -> Self {
                Self { name, age }
            }
        }
    "#;

    let (_temp_dir, test_file) = create_test_file(code);

    let source_code = fs::read_to_string(&test_file).expect("Failed to read file");
    let syntax_tree = syn::parse_file(&source_code).expect("Failed to parse");

    // Count impl blocks
    let impl_blocks: Vec<_> = syntax_tree
        .items
        .iter()
        .filter_map(|item| match item {
            syn::Item::Impl(impl_item) => Some(impl_item),
            _ => None,
        })
        .collect();

    // Should have 3 impl blocks: Debug, Display, and inherent impl
    assert_eq!(impl_blocks.len(), 3);

    // Verify we have trait impls
    let trait_impls = impl_blocks
        .iter()
        .filter(|impl_item| impl_item.trait_.is_some())
        .count();

    assert_eq!(trait_impls, 2);
}

#[test]
fn test_generic_types_parsing() {
    let code = r#"
        pub struct Container<T, U>
        where
            T: Clone,
            U: Default,
        {
            data: Vec<T>,
            metadata: U,
        }

        impl<T, U> Container<T, U>
        where
            T: Clone,
            U: Default,
        {
            pub fn new(data: Vec<T>, metadata: U) -> Self {
                Self { data, metadata }
            }

            pub fn clone_data(&self) -> Vec<T>
            where
                T: Clone,
            {
                self.data.clone()
            }
        }
    "#;

    let (_temp_dir, test_file) = create_test_file(code);

    let source_code = fs::read_to_string(&test_file).expect("Failed to read file");
    let syntax_tree = syn::parse_file(&source_code).expect("Failed to parse");

    // Find the struct
    let structs: Vec<_> = syntax_tree
        .items
        .iter()
        .filter_map(|item| match item {
            syn::Item::Struct(s) => Some(s),
            _ => None,
        })
        .collect();

    assert_eq!(structs.len(), 1);

    // Verify generics exist
    let s = structs[0];
    assert!(!s.generics.params.is_empty());

    // Find impl blocks
    let impls: Vec<_> = syntax_tree
        .items
        .iter()
        .filter_map(|item| match item {
            syn::Item::Impl(impl_item) => Some(impl_item),
            _ => None,
        })
        .collect();

    assert_eq!(impls.len(), 1);

    // Verify impl has generics
    let impl_item = impls[0];
    assert!(!impl_item.generics.params.is_empty());
}

#[test]
fn test_lifetime_parameters_parsing() {
    let code = r#"
        pub struct Holder<'a, T> {
            reference: &'a T,
        }

        impl<'a, T> Holder<'a, T> {
            pub fn new(reference: &'a T) -> Self {
                Self { reference }
            }

            pub fn get(&self) -> &'a T {
                self.reference
            }
        }
    "#;

    let (_temp_dir, test_file) = create_test_file(code);

    let source_code = fs::read_to_string(&test_file).expect("Failed to read file");
    let syntax_tree = syn::parse_file(&source_code).expect("Failed to parse");

    // Find impl blocks
    let impls: Vec<_> = syntax_tree
        .items
        .iter()
        .filter_map(|item| match item {
            syn::Item::Impl(impl_item) => Some(impl_item),
            _ => None,
        })
        .collect();

    assert_eq!(impls.len(), 1);

    // Verify impl has generics (including lifetime parameters)
    let impl_item = impls[0];
    assert!(!impl_item.generics.params.is_empty());

    // Check that we have at least one lifetime parameter
    let has_lifetime = impl_item
        .generics
        .params
        .iter()
        .any(|param| matches!(param, syn::GenericParam::Lifetime(_)));

    assert!(has_lifetime, "Should have lifetime parameter");
}

#[test]
fn test_cfg_attributes_parsing() {
    let code = r#"
        pub struct PlatformSpecific {
            data: Vec<u8>,
        }

        #[cfg(target_os = "linux")]
        impl PlatformSpecific {
            pub fn linux_specific(&self) -> usize {
                self.data.len()
            }
        }

        #[cfg(target_os = "windows")]
        impl PlatformSpecific {
            pub fn windows_specific(&self) -> usize {
                self.data.len() + 1
            }
        }
    "#;

    let (_temp_dir, test_file) = create_test_file(code);

    let source_code = fs::read_to_string(&test_file).expect("Failed to read file");
    let syntax_tree = syn::parse_file(&source_code).expect("Failed to parse");

    // Find impl blocks
    let impls: Vec<_> = syntax_tree
        .items
        .iter()
        .filter_map(|item| match item {
            syn::Item::Impl(impl_item) => Some(impl_item),
            _ => None,
        })
        .collect();

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

    // Verify both impls have cfg attributes
    for impl_item in impls {
        let has_cfg = impl_item.attrs.iter().any(|attr| {
            attr.path()
                .segments
                .first()
                .map(|s| s.ident == "cfg")
                .unwrap_or(false)
        });
        assert!(has_cfg, "Impl should have cfg attribute");
    }
}

#[test]
fn test_complex_nested_types() {
    let code = r#"
        use std::collections::{HashMap, HashSet};
        use std::sync::{Arc, Mutex};

        pub struct ComplexStore {
            data: HashMap<String, Vec<u8>>,
            cache: HashSet<String>,
            connections: Arc<Mutex<Vec<Connection>>>,
        }

        pub struct Connection {
            id: usize,
            active: bool,
        }

        impl ComplexStore {
            pub fn new() -> Self {
                Self {
                    data: HashMap::new(),
                    cache: HashSet::new(),
                    connections: Arc::new(Mutex::new(Vec::new())),
                }
            }

            pub fn insert(&mut self, key: String, value: Vec<u8>) {
                self.data.insert(key.clone(), value);
                self.cache.insert(key);
            }
        }
    "#;

    let (_temp_dir, test_file) = create_test_file(code);

    let source_code = fs::read_to_string(&test_file).expect("Failed to read file");
    let syntax_tree = syn::parse_file(&source_code).expect("Failed to parse");

    // Should parse complex types successfully
    let structs: Vec<_> = syntax_tree
        .items
        .iter()
        .filter_map(|item| match item {
            syn::Item::Struct(s) => Some(s.ident.to_string()),
            _ => None,
        })
        .collect();

    assert_eq!(structs.len(), 2);
    assert!(structs.contains(&"ComplexStore".to_string()));
    assert!(structs.contains(&"Connection".to_string()));
}

#[test]
fn test_large_number_of_methods() {
    let mut code = String::from(
        r#"
        pub struct LargeImpl {
            data: Vec<u8>,
        }

        impl LargeImpl {
            pub fn new() -> Self {
                Self { data: Vec::new() }
            }
    "#,
    );

    // Add many methods
    for i in 0..100 {
        code.push_str(&format!(
            r#"
            pub fn method_{}(&self) -> usize {{
                self.data.len() + {}
            }}
        "#,
            i, i
        ));
    }

    code.push_str("}\n");

    let (_temp_dir, test_file) = create_test_file(&code);

    let source_code = fs::read_to_string(&test_file).expect("Failed to read file");
    let syntax_tree = syn::parse_file(&source_code).expect("Failed to parse");

    // Find impl blocks
    let impls: Vec<_> = syntax_tree
        .items
        .iter()
        .filter_map(|item| match item {
            syn::Item::Impl(impl_item) => Some(impl_item),
            _ => None,
        })
        .collect();

    assert_eq!(impls.len(), 1);

    // Count methods in the impl
    let method_count = impls[0].items.len();
    assert_eq!(method_count, 101); // 100 generated + 1 new()
}

#[test]
fn test_unicode_identifiers() {
    let code = r#"
        pub struct データ構造 {
            値: i32,
        }

        impl データ構造 {
            pub fn 新規作成(値: i32) -> Self {
                Self { 値 }
            }

            pub fn 値取得(&self) -> i32 {
                self.値
            }
        }
    "#;

    let (_temp_dir, test_file) = create_test_file(code);

    let source_code = fs::read_to_string(&test_file).expect("Failed to read file");

    // Should parse successfully even with Unicode identifiers
    let result = syn::parse_file(&source_code);
    assert!(result.is_ok(), "Should parse Unicode identifiers");

    let syntax_tree = result.unwrap();

    // Should find the struct
    let structs: Vec<_> = syntax_tree
        .items
        .iter()
        .filter_map(|item| match item {
            syn::Item::Struct(_) => Some(()),
            _ => None,
        })
        .collect();

    assert_eq!(structs.len(), 1);
}

#[test]
fn test_module_visibility_variants() {
    let code = r#"
        pub struct Public {
            pub public_field: i32,
            pub(crate) crate_field: i32,
            pub(super) super_field: i32,
            private_field: i32,
        }

        impl Public {
            pub fn public_method(&self) -> i32 {
                self.public_field
            }

            pub(crate) fn crate_method(&self) -> i32 {
                self.crate_field
            }

            pub(super) fn super_method(&self) -> i32 {
                self.super_field
            }

            fn private_method(&self) -> i32 {
                self.private_field
            }
        }
    "#;

    let (_temp_dir, test_file) = create_test_file(code);

    let source_code = fs::read_to_string(&test_file).expect("Failed to read file");
    let syntax_tree = syn::parse_file(&source_code).expect("Failed to parse");

    // Should parse all visibility variants correctly
    let structs: Vec<_> = syntax_tree
        .items
        .iter()
        .filter_map(|item| match item {
            syn::Item::Struct(s) => Some(s),
            _ => None,
        })
        .collect();

    assert_eq!(structs.len(), 1);

    // Verify fields with different visibility levels exist
    let struct_item = structs[0];
    if let syn::Fields::Named(ref fields) = struct_item.fields {
        assert_eq!(fields.named.len(), 4);
    }
}

// ======================================================================
// Integration tests for v0.2.4 new features
// ======================================================================

#[test]
fn test_trait_bound_tracking() {
    use splitrs::trait_bound_analyzer::TraitBoundAnalyzer;

    let code = r#"
        struct Container<T: Clone + Send> {
            data: T,
        }

        impl<T: Clone + Send> Container<T> {
            fn new(data: T) -> Self {
                Self { data }
            }
        }

        impl Clone for Container<i32> {
            fn clone(&self) -> Self {
                Self { data: self.data }
            }
        }
    "#;

    let file = syn::parse_file(code).expect("Failed to parse");
    let mut analyzer = TraitBoundAnalyzer::new();
    analyzer.analyze_file(&file);

    // Should detect trait bounds on Container
    assert!(analyzer.requires_trait_bounds("Container"));

    let traits = analyzer.get_required_traits("Container");
    assert!(traits.contains(&"Clone".to_string()));
    assert!(traits.contains(&"Send".to_string()));

    // Should detect Clone implementation
    let implemented = analyzer.get_implemented_traits("Container");
    assert!(implemented.contains(&"Clone".to_string()));
}

#[test]
fn test_helper_dependency_tracking() {
    use splitrs::helper_dependency_tracker::HelperDependencyTracker;

    let code = r#"
        struct Processor;

        impl Processor {
            pub fn process(&self) -> i32 {
                self.validate() + self.transform()
            }

            fn validate(&self) -> i32 {
                self.check_invariants()
            }

            fn transform(&self) -> i32 {
                42
            }

            fn check_invariants(&self) -> i32 {
                0
            }
        }
    "#;

    let file = syn::parse_file(code).expect("Failed to parse");
    let mut tracker = HelperDependencyTracker::new();
    tracker.analyze_file(&file);

    // Should detect all helper dependencies
    let helpers = tracker.get_required_helpers("process");
    assert!(helpers.contains(&"validate".to_string()));
    assert!(helpers.contains(&"transform".to_string()));

    // Should detect transitive dependencies
    assert!(helpers.contains(&"check_invariants".to_string()));

    // Helper should be recognized as private
    assert!(tracker.is_private_helper("validate"));
    assert!(tracker.is_private_helper("transform"));
    assert!(!tracker.is_private_helper("process"));
}

#[test]
fn test_glob_import_analysis() {
    use splitrs::glob_import_analyzer::GlobImportAnalyzer;

    let code = r#"
        use std::collections::*;
        use std::fmt::Debug;

        struct Container {
            map: HashMap<String, i32>,
            set: HashSet<i32>,
        }

        impl Debug for Container {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                Ok(())
            }
        }
    "#;

    let file = syn::parse_file(code).expect("Failed to parse");
    let mut analyzer = GlobImportAnalyzer::new();
    analyzer.analyze_file(&file);

    // Should detect glob import
    assert!(analyzer.has_glob_imports());

    // HashMap and HashSet should be from glob
    assert!(analyzer.is_from_glob_import("HashMap"));
    assert!(analyzer.is_from_glob_import("HashSet"));

    // Debug is specifically imported, not from glob
    assert!(!analyzer.is_from_glob_import("Debug"));

    // Should track specific imports
    let specific = analyzer.get_used_specific_imports();
    assert!(specific.contains(&"Debug".to_string()));
}

#[test]
fn test_trait_bounds_with_where_clause() {
    use splitrs::trait_bound_analyzer::TraitBoundAnalyzer;

    let code = r#"
        struct Cache<K, V>
        where
            K: std::hash::Hash + Eq,
            V: Clone,
        {
            data: std::collections::HashMap<K, V>,
        }
    "#;

    let file = syn::parse_file(code).expect("Failed to parse");
    let mut analyzer = TraitBoundAnalyzer::new();
    analyzer.analyze_file(&file);

    let traits = analyzer.get_required_traits("Cache");
    assert!(traits.contains(&"Clone".to_string()));
    assert!(traits.contains(&"Hash".to_string()));
    assert!(traits.contains(&"Eq".to_string()));
}

#[test]
fn test_helper_grouping_for_methods() {
    use splitrs::helper_dependency_tracker::HelperDependencyTracker;

    let code = r#"
        struct Service;

        impl Service {
            pub fn operation_a(&self) -> i32 {
                self.helper_a()
            }

            pub fn operation_b(&self) -> i32 {
                self.helper_b()
            }

            fn helper_a(&self) -> i32 {
                self.shared_helper()
            }

            fn helper_b(&self) -> i32 {
                self.shared_helper()
            }

            fn shared_helper(&self) -> i32 {
                42
            }
        }
    "#;

    let file = syn::parse_file(code).expect("Failed to parse");
    let mut tracker = HelperDependencyTracker::new();
    tracker.analyze_file(&file);

    // Get helpers for a group of methods
    let methods = vec!["operation_a".to_string(), "operation_b".to_string()];
    let helpers = tracker.get_helpers_for_method_group(&methods);

    // Should include all helpers used by both methods
    assert!(helpers.contains(&"helper_a".to_string()));
    assert!(helpers.contains(&"helper_b".to_string()));
    assert!(helpers.contains(&"shared_helper".to_string()));
}

#[test]
fn test_glob_import_suggestions() {
    use splitrs::glob_import_analyzer::GlobImportAnalyzer;

    let code = r#"
        use std::collections::*;

        struct Data {
            map: HashMap<String, i32>,
            set: HashSet<String>,
        }
    "#;

    let file = syn::parse_file(code).expect("Failed to parse");
    let mut analyzer = GlobImportAnalyzer::new();
    analyzer.analyze_file(&file);

    let suggestions = analyzer.suggest_specific_imports();

    // Should suggest HashMap and HashSet from std::collections
    assert!(!suggestions.is_empty());
    if let Some(symbols) = suggestions.get("std::collections") {
        assert!(
            symbols.contains(&"HashMap".to_string()) || symbols.contains(&"HashSet".to_string())
        );
    }
}