splitrs 0.3.5

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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
//! Integration tests for Feature C (`--split-nested-mods`): recursive descent
//! into inline `mod x { ... }` blocks, correct nested emission, visibility
//! preservation, doc/attr/cfg preservation, super-path deepening, and facade
//! generation.

use splitrs::config::{FacadeStyle, TargetModule};
use splitrs::file_analyzer::FileAnalyzer;
use splitrs::nested_mod_splitter::{
    add_child_mod_imports, dry_run_lines, plan_nested_split, write_plan, NestedModPlan,
    NestedSplitOptions,
};
use std::collections::HashSet;
use std::fs;
use std::path::Path;
use std::process::Command;
use tempfile::TempDir;

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// The motivating shape: a file dominated by one inline `pub mod core` with
/// structs, enums, impls (inherent + trait), fns, consts, and use statements.
const CORE_FIXTURE: &str = r#"
use std::collections::HashMap;

/// Top-level entry.
pub fn init() -> bool {
    true
}

/// Core module docs.
#[cfg(not(feature = "never"))]
pub mod core {
    //! Inner docs for core.
    use super::*;
    use std::path::PathBuf;

    /// A filesystem entry.
    #[derive(Debug, Clone)]
    pub struct FsEntry {
        pub path: PathBuf,
        size: u64,
    }

    impl FsEntry {
        pub fn new(path: PathBuf) -> Self {
            Self { path, size: 0 }
        }

        pub fn size(&self) -> u64 {
            self.size
        }
    }

    impl Default for FsEntry {
        fn default() -> Self {
            Self::new(PathBuf::new())
        }
    }

    /// Sorting options.
    pub enum SortBy {
        Name,
        Size,
    }

    pub const MAX_DEPTH: usize = 16;

    fn helper(map: &HashMap<String, u64>) -> usize {
        map.len()
    }

    pub fn list_entries(map: &HashMap<String, u64>) -> usize {
        helper(map)
    }

    pub fn watch_path(entry: &FsEntry) -> bool {
        super::init() && entry.size() == 0
    }
}
"#;

fn default_opts(rules: &[TargetModule], max_lines: usize) -> NestedSplitOptions<'_> {
    NestedSplitOptions {
        split_impl_blocks: false,
        max_impl_lines: 500,
        max_lines,
        extract_tests: false,
        max_mod_depth: 8,
        seeded_assignment: false,
        all_rules: rules,
    }
}

fn first_inline_mod(code: &str) -> syn::ItemMod {
    let file = syn::parse_file(code).expect("fixture parses");
    file.items
        .into_iter()
        .find_map(|item| match item {
            syn::Item::Mod(m) if m.content.is_some() => Some(m),
            _ => None,
        })
        .expect("fixture has an inline mod")
}

fn plan_fixture(code: &str, max_lines: usize) -> NestedModPlan {
    let mod_item = first_inline_mod(code);
    let mod_path = mod_item.ident.to_string();
    plan_nested_split(&mod_item, code, &default_opts(&[], max_lines), &mod_path, 1)
        .expect("planning succeeds")
}

/// Every name exported anywhere across a plan's own modules.
fn all_exported(plan: &NestedModPlan) -> HashSet<String> {
    plan.modules
        .iter()
        .flat_map(|m| m.get_exported_types())
        .collect()
}

/// Recursively assert that every generated `.rs` file parses as valid Rust.
fn assert_all_files_parse(dir: &Path) {
    for entry in fs::read_dir(dir).expect("read_dir") {
        let entry = entry.expect("dir entry");
        let path = entry.path();
        if path.is_dir() {
            assert_all_files_parse(&path);
        } else if path.extension().is_some_and(|e| e == "rs") {
            let content = fs::read_to_string(&path).expect("read generated file");
            syn::parse_file(&content)
                .unwrap_or_else(|e| panic!("generated file {:?} does not parse: {}", path, e));
        }
    }
}

fn read(path: &Path) -> String {
    fs::read_to_string(path).unwrap_or_else(|e| panic!("cannot read {:?}: {}", path, e))
}

// ---------------------------------------------------------------------------
// Analyzer diversion
// ---------------------------------------------------------------------------

#[test]
fn over_budget_inline_mod_is_diverted() {
    let file = syn::parse_file(CORE_FIXTURE).expect("parse");
    let mut analyzer = FileAnalyzer::new(false, 500);
    analyzer.set_split_nested_mods(true, 20);
    analyzer.set_source(CORE_FIXTURE);
    analyzer.analyze(&file);

    let nested = analyzer.take_nested_mods();
    assert_eq!(nested.len(), 1, "the big `mod core` must be diverted");
    assert_eq!(nested[0].ident.to_string(), "core");
    assert!(
        !analyzer
            .standalone_items
            .iter()
            .any(|i| matches!(i, syn::Item::Mod(_))),
        "diverted mod must not remain in standalone_items"
    );
}

#[test]
fn under_budget_inline_mod_stays_standalone() {
    let file = syn::parse_file(CORE_FIXTURE).expect("parse");
    let mut analyzer = FileAnalyzer::new(false, 500);
    analyzer.set_split_nested_mods(true, 10_000);
    analyzer.set_source(CORE_FIXTURE);
    analyzer.analyze(&file);

    assert!(analyzer.take_nested_mods().is_empty());
    assert!(
        analyzer
            .standalone_items
            .iter()
            .any(|i| matches!(i, syn::Item::Mod(_))),
        "under-budget mod stays an opaque standalone item"
    );
}

#[test]
fn disabled_flag_keeps_all_mods_standalone() {
    let file = syn::parse_file(CORE_FIXTURE).expect("parse");
    let mut analyzer = FileAnalyzer::new(false, 500);
    analyzer.analyze(&file);
    assert!(analyzer.take_nested_mods().is_empty());
}

#[test]
fn cfg_test_mod_is_never_diverted_as_nested() {
    let code = r#"
        #[cfg(test)]
        mod tests {
            #[test] fn a() {}
            #[test] fn b() {}
            #[test] fn c() {}
            #[test] fn d() {}
        }
    "#;
    let file = syn::parse_file(code).expect("parse");
    let mut analyzer = FileAnalyzer::new(false, 500);
    analyzer.set_split_nested_mods(true, 2);
    analyzer.analyze(&file);
    assert!(
        analyzer.take_nested_mods().is_empty(),
        "test mods flow through the tests machinery, not Feature C"
    );
}

#[test]
fn cfg_feature_testkit_mod_is_not_misclassified_as_test() {
    // Regression for the token-substring heuristic: `feature = "testkit"`
    // must not count as `cfg(test)`.
    let code = r#"
        #[cfg(feature = "testkit")]
        pub mod kit {
            pub fn a() {}
            pub fn b() {}
            pub fn c() {}
            pub fn d() {}
        }
    "#;
    let file = syn::parse_file(code).expect("parse");
    let mut analyzer = FileAnalyzer::new(false, 500);
    analyzer.set_split_nested_mods(true, 2);
    analyzer.set_source(code);
    analyzer.analyze(&file);
    let nested = analyzer.take_nested_mods();
    assert_eq!(nested.len(), 1, "cfg(feature) mod must be divertible");
    assert_eq!(nested[0].ident.to_string(), "kit");
}

// ---------------------------------------------------------------------------
// Plan shape
// ---------------------------------------------------------------------------

#[test]
fn plan_covers_every_item_of_the_mod_body() {
    let plan = plan_fixture(CORE_FIXTURE, 20);
    assert_eq!(plan.name, "core");
    assert!(matches!(plan.vis, syn::Visibility::Public(_)));

    let exported = all_exported(&plan);
    for name in [
        "FsEntry",
        "SortBy",
        "MAX_DEPTH",
        "helper",
        "list_entries",
        "watch_path",
    ] {
        assert!(exported.contains(name), "missing {name} in plan modules");
    }
    assert!(plan.children.is_empty());
}

#[test]
fn plan_decl_preserves_outer_docs_cfg_and_visibility() {
    let plan = plan_fixture(CORE_FIXTURE, 20);
    let decl = plan.decl_item();
    let rendered = prettyplease::unparse(&syn::File {
        shebang: None,
        attrs: Vec::new(),
        items: vec![syn::Item::Mod(decl)],
    });
    assert!(rendered.contains("/// Core module docs."), "{rendered}");
    assert!(
        rendered.contains("#[cfg(not(feature = \"never\"))]"),
        "{rendered}"
    );
    assert!(rendered.contains("pub mod core;"), "{rendered}");
}

#[test]
fn private_mod_decl_stays_private() {
    let code = r#"
        mod internal {
            pub struct Hidden;
            fn helper() {}
            pub fn touch() { helper(); }
        }
    "#;
    let plan = plan_fixture(code, 2);
    assert!(matches!(plan.vis, syn::Visibility::Inherited));
    let rendered = prettyplease::unparse(&syn::File {
        shebang: None,
        attrs: Vec::new(),
        items: vec![syn::Item::Mod(plan.decl_item())],
    });
    assert!(rendered.contains("mod internal;"), "{rendered}");
    assert!(!rendered.contains("pub mod internal;"), "{rendered}");
}

#[test]
fn nested_in_nested_mods_recurse() {
    let code = r#"
        pub mod outer {
            pub fn outer_fn() -> usize { 1 }

            pub mod deep {
                pub struct DeepThing {
                    pub level: usize,
                }

                impl DeepThing {
                    pub fn level(&self) -> usize { self.level }
                }

                pub fn deep_fn() -> usize { 2 }
            }
        }
    "#;
    let plan = plan_fixture(code, 5);
    assert_eq!(plan.name, "outer");
    assert_eq!(plan.children.len(), 1);
    assert_eq!(plan.children[0].name, "deep");
    let deep_exports = all_exported(&plan.children[0]);
    assert!(deep_exports.contains("DeepThing"));
    assert!(deep_exports.contains("deep_fn"));
}

// ---------------------------------------------------------------------------
// Emission
// ---------------------------------------------------------------------------

#[test]
fn write_plan_emits_parseable_tree_with_facade_and_inner_docs() {
    let plan = plan_fixture(CORE_FIXTURE, 20);
    let dir = TempDir::new().expect("tempdir");
    let created = write_plan(&plan, dir.path(), FacadeStyle::Glob).expect("write_plan");
    assert!(!created.is_empty());
    assert_all_files_parse(dir.path());

    let mod_rs = read(&dir.path().join("core").join("mod.rs"));
    // Inner `//!` docs of the mod body land at the top of core/mod.rs.
    assert!(mod_rs.contains("//! Inner docs for core."), "{mod_rs}");
    // Glob facade so `crate::core::FsEntry` keeps resolving.
    assert!(mod_rs.contains("pub use "), "{mod_rs}");
    assert!(mod_rs.contains("pub mod "), "{mod_rs}");
    // Child mods are declared by the PARENT mod.rs, never re-exported here.
    assert!(!mod_rs.contains("pub mod core;"), "{mod_rs}");
}

#[test]
fn super_paths_are_deepened_in_emitted_files() {
    let plan = plan_fixture(CORE_FIXTURE, 20);
    let dir = TempDir::new().expect("tempdir");
    write_plan(&plan, dir.path(), FacadeStyle::Glob).expect("write_plan");

    // Collect the concatenated content of every generated core/*.rs file.
    let core_dir = dir.path().join("core");
    let mut combined = String::new();
    for entry in fs::read_dir(&core_dir).expect("read core dir") {
        let path = entry.expect("entry").path();
        if path.extension().is_some_and(|e| e == "rs") {
            combined.push_str(&read(&path));
        }
    }
    // `super::init()` in the mod body sits one level deeper now.
    assert!(
        combined.contains("super::super::init()"),
        "body super path was not deepened:\n{combined}"
    );
    assert!(
        !combined.contains("super::super::super::init()"),
        "body super path was deepened more than once:\n{combined}"
    );
    // The mod-body `use super::*;` is forwarded one level deeper (when kept).
    assert!(
        !combined.contains("use super::*;\nuse super::*;"),
        "sanity: no duplicated globs"
    );
}

#[test]
fn cross_module_visibility_upgrades_apply_inside_the_nested_mod() {
    // Force `helper` (private) and `list_entries` into DIFFERENT generated
    // modules by routing list_entries to a named module; the cross-module
    // pass must upgrade helper to pub(super) and import it.
    let rules = vec![TargetModule {
        name: "listing".to_string(),
        items: vec!["list_entries".to_string()],
        parent: Some("core".to_string()),
        ..Default::default()
    }];
    let mod_item = first_inline_mod(CORE_FIXTURE);
    let plan = plan_nested_split(
        &mod_item,
        CORE_FIXTURE,
        &default_opts(&rules, 20),
        "core",
        1,
    )
    .expect("planning succeeds");

    assert!(
        plan.needs_pub_super.contains("helper"),
        "private helper called cross-module must be upgraded: {:?}",
        plan.needs_pub_super
    );

    let dir = TempDir::new().expect("tempdir");
    write_plan(&plan, dir.path(), FacadeStyle::Glob).expect("write_plan");
    let listing = read(&dir.path().join("core").join("listing.rs"));
    assert!(
        listing.contains("::helper"),
        "listing.rs must import the relocated helper:\n{listing}"
    );
    assert_all_files_parse(dir.path());
}

#[test]
fn named_facade_lists_public_items_explicitly() {
    let plan = plan_fixture(CORE_FIXTURE, 20);
    let dir = TempDir::new().expect("tempdir");
    write_plan(&plan, dir.path(), FacadeStyle::Named).expect("write_plan");
    let mod_rs = read(&dir.path().join("core").join("mod.rs"));
    assert!(
        !mod_rs.contains("::*;"),
        "named facade must not glob:\n{mod_rs}"
    );
    assert!(mod_rs.contains("FsEntry"), "{mod_rs}");
    assert!(mod_rs.contains("list_entries"), "{mod_rs}");
    // Private helper must NOT be re-exported.
    assert!(!mod_rs.contains("helper"), "{mod_rs}");
    assert_all_files_parse(dir.path());
}

#[test]
fn none_facade_emits_declarations_only() {
    let plan = plan_fixture(CORE_FIXTURE, 20);
    let dir = TempDir::new().expect("tempdir");
    write_plan(&plan, dir.path(), FacadeStyle::None).expect("write_plan");
    let mod_rs = read(&dir.path().join("core").join("mod.rs"));
    assert!(!mod_rs.contains("pub use"), "{mod_rs}");
    assert!(mod_rs.contains("pub mod"), "{mod_rs}");
}

#[test]
fn nested_in_nested_write_creates_grandchild_directory() {
    let code = r#"
        pub mod outer {
            pub fn outer_fn() -> usize { deep::deep_fn() }

            pub mod deep {
                pub fn deep_fn() -> usize { 2 }
                pub fn other_fn() -> usize { 3 }
                pub struct DeepThing;
            }
        }
    "#;
    let plan = plan_fixture(code, 4);
    let dir = TempDir::new().expect("tempdir");
    write_plan(&plan, dir.path(), FacadeStyle::Glob).expect("write_plan");

    let outer_mod = read(&dir.path().join("outer").join("mod.rs"));
    assert!(outer_mod.contains("pub mod deep;"), "{outer_mod}");
    assert!(
        dir.path()
            .join("outer")
            .join("deep")
            .join("mod.rs")
            .exists(),
        "grandchild mod.rs missing"
    );
    // The sibling file calling `deep::deep_fn()` needs `use super::deep;`.
    let mut combined = String::new();
    for entry in fs::read_dir(dir.path().join("outer")).expect("read outer") {
        let path = entry.expect("entry").path();
        if path.is_file() && path.extension().is_some_and(|e| e == "rs") {
            combined.push_str(&read(&path));
        }
    }
    assert!(
        combined.contains("use super::deep;"),
        "sibling child-mod import missing:\n{combined}"
    );
    assert_all_files_parse(dir.path());
}

#[test]
fn generated_bucket_name_yields_to_real_child_mod_name() {
    // A nested `mod types` (a real module) must keep its name; the generated
    // `types.rs` bucket must be renamed.
    let code = r#"
        pub mod outer {
            pub struct Standalone {
                pub x: u8,
            }

            pub mod types {
                pub struct Inner;
                pub fn make() -> Inner { Inner }
                pub fn destroy(_: Inner) {}
            }
        }
    "#;
    let plan = plan_fixture(code, 4);
    assert_eq!(plan.children.len(), 1);
    assert_eq!(plan.children[0].name, "types");
    assert!(
        plan.modules.iter().all(|m| m.name != "types"),
        "generated bucket must have been renamed: {:?}",
        plan.modules.iter().map(|m| &m.name).collect::<Vec<_>>()
    );
    let dir = TempDir::new().expect("tempdir");
    write_plan(&plan, dir.path(), FacadeStyle::Glob).expect("write_plan");
    assert!(dir
        .path()
        .join("outer")
        .join("types")
        .join("mod.rs")
        .exists());
    assert_all_files_parse(dir.path());
}

#[test]
fn extracted_tests_inside_nested_mod_become_tests_rs() {
    let code = r#"
        pub mod core {
            pub fn answer() -> i32 { 42 }
            pub fn double(x: i32) -> i32 { x * 2 }
            pub struct Marker;

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

                #[test]
                fn answer_is_42() {
                    assert_eq!(answer(), 42);
                }
            }
        }
    "#;
    let mod_item = first_inline_mod(code);
    let mut opts = default_opts(&[], 5);
    opts.extract_tests = true;
    let plan = plan_nested_split(&mod_item, code, &opts, "core", 1).expect("plan");
    assert_eq!(plan.extracted_tests.len(), 1);

    let dir = TempDir::new().expect("tempdir");
    write_plan(&plan, dir.path(), FacadeStyle::Glob).expect("write_plan");
    let tests_rs = read(&dir.path().join("core").join("tests.rs"));
    assert!(tests_rs.contains("answer_is_42"), "{tests_rs}");
    let mod_rs = read(&dir.path().join("core").join("mod.rs"));
    assert!(mod_rs.contains("#[cfg(test)]"), "{mod_rs}");
    assert!(mod_rs.contains("mod tests;"), "{mod_rs}");
    assert_all_files_parse(dir.path());
}

#[test]
fn dry_run_lines_render_the_full_tree() {
    let code = r#"
        pub mod outer {
            pub fn f1() {}
            pub mod deep {
                pub fn f2() {}
                pub fn f3() {}
                pub struct S;
            }
        }
    "#;
    let plan = plan_fixture(code, 3);
    let lines = dry_run_lines(&plan, 0);
    let joined = lines.join("\n");
    assert!(joined.contains("outer/"), "{joined}");
    assert!(joined.contains("deep/"), "{joined}");
    assert!(joined.contains("mod.rs"), "{joined}");
}

// ---------------------------------------------------------------------------
// Sibling child-mod imports (top-level composition unit)
// ---------------------------------------------------------------------------

#[test]
fn add_child_mod_imports_records_only_real_references() {
    let code = r#"
        pub fn boot() -> usize { core::count() }
        pub fn independent() -> usize { 7 }
    "#;
    let file = syn::parse_file(code).expect("parse");
    let mut analyzer = FileAnalyzer::new(false, 500);
    analyzer.analyze(&file);
    let mut modules = analyzer.group_by_module(1000);
    add_child_mod_imports(&mut modules, &["core".to_string()]);
    let functions = modules
        .iter()
        .find(|m| m.name == "functions")
        .expect("functions bucket");
    assert_eq!(functions.sibling_mod_imports, vec!["core".to_string()]);

    let content = functions.generate_content(
        &file,
        &analyzer.use_statements,
        &std::collections::HashMap::new(),
        &HashSet::new(),
        None,
        &std::collections::HashMap::new(),
        None,
        &HashSet::new(),
    );
    assert!(
        content.contains("use super::core;"),
        "sibling child-mod import not emitted:\n{content}"
    );
}

// ---------------------------------------------------------------------------
// CLI end-to-end
// ---------------------------------------------------------------------------

#[test]
fn cli_split_nested_mods_end_to_end() {
    let dir = TempDir::new().expect("tempdir");
    let input = dir.path().join("lib_fixture.rs");
    fs::write(&input, CORE_FIXTURE).expect("write fixture");
    let output = dir.path().join("out");

    let status = Command::new(env!("CARGO_BIN_EXE_splitrs"))
        .arg("-i")
        .arg(&input)
        .arg("-o")
        .arg(&output)
        .arg("--split-nested-mods")
        .arg("true")
        .arg("--max-lines")
        .arg("20")
        .status()
        .expect("run splitrs");
    assert!(status.success(), "splitrs exited with {status}");

    let mod_rs = read(&output.join("mod.rs"));
    assert!(mod_rs.contains("pub mod core;"), "{mod_rs}");
    assert!(mod_rs.contains("/// Core module docs."), "{mod_rs}");
    assert!(
        mod_rs.contains("#[cfg(not(feature = \"never\"))]"),
        "{mod_rs}"
    );
    // The child mod is declared but NOT re-exported at the parent: items must
    // stay at crate::core::Item exactly where they were.
    assert!(!mod_rs.contains("pub use core::*;"), "{mod_rs}");
    // The mod body resolved `HashMap` through `use super::*;` — the original
    // file-scope binding must be recreated in mod.rs so the chain still works.
    assert!(
        mod_rs.contains("use std::collections::HashMap;"),
        "file-scope use binding not recreated for the descended mod:\n{mod_rs}"
    );
    assert!(output.join("core").join("mod.rs").exists());
    assert_all_files_parse(&output);
    assert_output_compiles(&output);
}

#[test]
fn parent_scope_items_bind_private_fns_and_prune_uses() {
    use splitrs::nested_mod_splitter::compute_parent_scope_items;

    let code = r#"
        use std::collections::HashMap;
        use std::path::PathBuf;

        fn top_helper() -> u64 { 41 }

        pub mod core {
            use super::*;

            pub fn probe(map: &HashMap<String, u64>) -> u64 {
                super::top_helper() + map.len() as u64
            }
        }
    "#;
    let file = syn::parse_file(code).expect("parse");
    let mut analyzer = FileAnalyzer::new(false, 500);
    analyzer.set_split_nested_mods(true, 3);
    analyzer.set_source(code);
    analyzer.analyze(&file);
    let nested = analyzer.take_nested_mods();
    assert_eq!(nested.len(), 1);
    let modules = analyzer.group_by_module(1000);

    let mut needs_pub_super = HashSet::new();
    let scope = compute_parent_scope_items(
        &nested,
        &analyzer.use_statements,
        &modules,
        &mut needs_pub_super,
        false,
    );
    let rendered = prettyplease::unparse(&syn::File {
        shebang: None,
        attrs: Vec::new(),
        items: scope.items,
    });
    // The referenced file-scope import is kept; the unreferenced one pruned.
    assert!(
        rendered.contains("use std::collections::HashMap;"),
        "{rendered}"
    );
    assert!(!rendered.contains("PathBuf"), "{rendered}");
    // The private fn referenced via `super::` gets a binding + an upgrade.
    assert!(
        rendered.contains("use self::functions::top_helper;"),
        "{rendered}"
    );
    assert!(needs_pub_super.contains("top_helper"));
    // Both provided names are advertised to the descended module's emission
    // so its forwarded `use super::*;` glob survives.
    assert!(scope.provided_names.contains("top_helper"));
    assert!(scope.provided_names.contains("HashMap"));
}

#[test]
fn macro_defining_module_gets_macro_use_and_first_position() {
    let code = r#"
        macro_rules! twice {
            ($e:expr) => { $e + $e };
        }

        pub fn use_it() -> u64 { twice!(21) }
    "#;
    let file = syn::parse_file(code).expect("parse");
    let mut analyzer = FileAnalyzer::new(false, 500);
    analyzer.set_source(code);
    analyzer.analyze(&file);
    let modules = analyzer.group_by_module(1000);
    // The output-dir parameter is reserved/unused by generate_mod_rs; per
    // policy, temporary paths in tests come from std::env::temp_dir().
    let unused_output_dir = std::env::temp_dir();
    let mod_rs =
        splitrs::module_generator::generate_mod_rs(&modules, &unused_output_dir, None, false, &[])
            .expect("generate_mod_rs");
    assert!(mod_rs.contains("#[macro_use]\npub mod macros;"), "{mod_rs}");
    let macros_pos = mod_rs.find("pub mod macros;").expect("macros decl");
    let functions_pos = mod_rs.find("pub mod functions;").expect("functions decl");
    assert!(
        macros_pos < functions_pos,
        "macro-defining module must be declared first:\n{mod_rs}"
    );
}

/// Depth-2 fixture shared by the CLI facade / depth-guard tests: `deep` is
/// itself over budget at `--max-lines 4`, so unrestricted runs descend twice.
const DEPTH2_FIXTURE: &str = r#"
pub mod outer {
    /// Outer worker.
    pub fn outer_fn() -> usize { deep::deep_fn() }
    pub struct OuterThing {
        pub id: usize,
    }
    impl OuterThing {
        pub fn id(&self) -> usize { self.id }
    }
    pub mod deep {
        pub struct DeepThing;
        pub fn deep_fn() -> usize { 2 }
        pub fn other_fn() -> usize { 3 }
        pub fn third_fn() -> usize { 4 }
    }
}
"#;

fn run_depth2_cli(dir: &TempDir, extra: &[&str]) -> std::path::PathBuf {
    let input = dir.path().join("lib_fixture.rs");
    fs::write(&input, DEPTH2_FIXTURE).expect("write fixture");
    let output = dir.path().join("out");
    let cmd = Command::new(env!("CARGO_BIN_EXE_splitrs"))
        .arg("-i")
        .arg(&input)
        .arg("-o")
        .arg(&output)
        .arg("--split-nested-mods")
        .arg("true")
        .arg("--max-lines")
        .arg("4")
        .args(extra)
        .output()
        .expect("run splitrs");
    assert!(
        cmd.status.success(),
        "splitrs failed:\n{}\n{}",
        String::from_utf8_lossy(&cmd.stdout),
        String::from_utf8_lossy(&cmd.stderr)
    );
    output
}

#[test]
fn cli_facade_named_lists_explicit_reexports() {
    let dir = TempDir::new().expect("tempdir");
    let output = run_depth2_cli(&dir, &["--facade", "named"]);

    let outer_mod = read(&output.join("outer").join("mod.rs"));
    assert!(
        !outer_mod.contains("::*;"),
        "named facade must not glob:\n{outer_mod}"
    );
    assert!(
        outer_mod.contains("pub use types::OuterThing;"),
        "named facade must re-export public items explicitly:\n{outer_mod}"
    );
    // The descended grandchild is declared, never re-exported: items must
    // stay reachable at their original `outer::deep::*` paths only.
    assert!(outer_mod.contains("pub mod deep;"), "{outer_mod}");
    assert!(!outer_mod.contains("pub use deep"), "{outer_mod}");
    assert_all_files_parse(&output);
}

#[test]
fn cli_facade_none_emits_declarations_only() {
    let dir = TempDir::new().expect("tempdir");
    let output = run_depth2_cli(&dir, &["--facade", "none"]);

    let outer_mod = read(&output.join("outer").join("mod.rs"));
    assert!(
        !outer_mod.contains("pub use"),
        "facade none must not re-export anything:\n{outer_mod}"
    );
    assert!(outer_mod.contains("pub mod deep;"), "{outer_mod}");
    assert_all_files_parse(&output);
}

#[test]
fn cli_max_mod_depth_keeps_deeper_mods_opaque() {
    // Unrestricted control run: depth 2 is reached.
    let free = TempDir::new().expect("tempdir");
    let free_out = run_depth2_cli(&free, &[]);
    assert!(
        free_out.join("outer").join("deep").join("mod.rs").exists(),
        "control run must descend into outer/deep/"
    );

    // Guarded run: --max-mod-depth 1 descends into `outer` but must leave
    // the over-budget `deep` as an opaque inline mod inside outer/*.rs.
    let guarded = TempDir::new().expect("tempdir");
    let out = run_depth2_cli(&guarded, &["--max-mod-depth", "1"]);
    assert!(
        !out.join("outer").join("deep").exists(),
        "--max-mod-depth 1 must not create outer/deep/"
    );
    let mut inline_deep = false;
    for entry in fs::read_dir(out.join("outer")).expect("read outer") {
        let path = entry.expect("entry").path();
        if path.is_file() && path.extension().is_some_and(|e| e == "rs") {
            inline_deep |= read(&path).contains("pub mod deep {");
        }
    }
    assert!(
        inline_deep,
        "the depth-limited mod must survive as an inline `pub mod deep {{ ... }}`"
    );
    assert_all_files_parse(&out);
}

// ---------------------------------------------------------------------------
// Compile-level regressions (each emitted tree must actually build)
// ---------------------------------------------------------------------------

/// Write `code` to a fixture, run the splitrs CLI on it with the given extra
/// args, and return the output directory.
fn run_cli(dir: &TempDir, code: &str, extra: &[&str]) -> std::path::PathBuf {
    let input = dir.path().join("lib_fixture.rs");
    fs::write(&input, code).expect("write fixture");
    let output = dir.path().join("out");
    let cmd = Command::new(env!("CARGO_BIN_EXE_splitrs"))
        .arg("-i")
        .arg(&input)
        .arg("-o")
        .arg(&output)
        .args(extra)
        .output()
        .expect("run splitrs");
    assert!(
        cmd.status.success(),
        "splitrs failed:\n{}\n{}",
        String::from_utf8_lossy(&cmd.stdout),
        String::from_utf8_lossy(&cmd.stderr)
    );
    output
}

/// Compile the emitted tree as the module graph of a probe crate
/// (`rustc --crate-type lib`). Text-level assertions alone let visibility
/// and name-resolution regressions slip through — rustc is the only arbiter
/// that the split output still builds.
fn assert_output_compiles(output: &Path) {
    let parent = output.parent().expect("output dir has a parent");
    let mod_dir = output
        .file_name()
        .and_then(|name| name.to_str())
        .expect("output dir name is utf-8");
    let probe = parent.join("compile_probe.rs");
    fs::write(
        &probe,
        format!("#[path = \"{mod_dir}/mod.rs\"]\nmod split_output;\n"),
    )
    .expect("write compile probe");
    let rustc = Command::new("rustc")
        .arg("--edition")
        .arg("2021")
        .arg("--crate-type")
        .arg("lib")
        .arg("--out-dir")
        .arg(parent)
        .arg(&probe)
        .output()
        .expect("run rustc");
    assert!(
        rustc.status.success(),
        "emitted tree does not compile:\n{}",
        String::from_utf8_lossy(&rustc.stderr)
    );
}

/// Concatenated content of every `.rs` file directly inside `dir`.
fn read_dir_combined(dir: &Path) -> String {
    let mut combined = String::new();
    for entry in fs::read_dir(dir).expect("read_dir") {
        let path = entry.expect("dir entry").path();
        if path.is_file() && path.extension().is_some_and(|e| e == "rs") {
            combined.push_str(&read(&path));
        }
    }
    combined
}

#[test]
fn nested_body_reference_to_private_sibling_mod_compiles() {
    // Regression: a private inline `mod util` relocated into a generated
    // bucket used to stay private while mod.rs emitted
    // `use self::functions::util;` -> error[E0603]: module `util` is private.
    let code = r#"
mod util {
    pub fn helper() -> u64 { 7 }
}

pub mod core {
    use super::*;

    pub fn call_util() -> u64 { super::util::helper() }
    pub fn pad_a() -> u64 { 1 }
    pub fn pad_b() -> u64 { 2 }
    pub fn pad_c() -> u64 { 3 }
}
"#;
    let dir = TempDir::new().expect("tempdir");
    let output = run_cli(
        &dir,
        code,
        &["--split-nested-mods", "true", "--max-lines", "4"],
    );
    let top_level = read_dir_combined(&output);
    assert!(
        top_level.contains("pub(super) mod util"),
        "relocated private mod must be widened to pub(super):\n{top_level}"
    );
    let mod_rs = read(&output.join("mod.rs"));
    assert!(mod_rs.contains("::util;"), "{mod_rs}");
    assert_output_compiles(&output);
}

#[test]
fn nested_body_bare_call_to_private_parent_fn_compiles() {
    // Regression: `make_hidden()` resolved through the body's
    // `use super::*;`; mod.rs re-bound it, but the forwarded glob in the
    // descended module was dropped (lowercase names are invisible to the
    // uppercase glob-keep heuristic) -> error[E0425].
    let code = r#"
fn make_hidden() -> u64 { 3 }

pub mod core {
    use super::*;

    pub fn get() -> u64 { make_hidden() }
    pub fn pad_a() -> u64 { 1 }
    pub fn pad_b() -> u64 { 2 }
    pub fn pad_c() -> u64 { 3 }
}
"#;
    let dir = TempDir::new().expect("tempdir");
    let output = run_cli(
        &dir,
        code,
        &["--split-nested-mods", "true", "--max-lines", "4"],
    );
    let mod_rs = read(&output.join("mod.rs"));
    assert!(
        mod_rs.contains("use self::functions::make_hidden;"),
        "{mod_rs}"
    );
    let core_files = read_dir_combined(&output.join("core"));
    assert!(
        core_files.contains("use super::super::*;"),
        "forwarded glob must survive for the lowercase parent binding:\n{core_files}"
    );
    assert_output_compiles(&output);
}

#[test]
fn nested_body_private_trait_method_call_compiles() {
    // Regression: a private trait reached ONLY through method-call syntax
    // (`41u64.describe()`) got neither a mod.rs re-binding (the `referenced`
    // check ignored method_calls) nor a kept glob -> error[E0599].
    let code = r#"
trait Describe {
    fn describe(&self) -> u64;
}

impl Describe for u64 {
    fn describe(&self) -> u64 { *self }
}

pub mod core {
    use super::*;

    pub fn label() -> u64 { 41u64.describe() }
    pub fn pad_a() -> u64 { 1 }
    pub fn pad_b() -> u64 { 2 }
    pub fn pad_c() -> u64 { 3 }
}
"#;
    let dir = TempDir::new().expect("tempdir");
    let output = run_cli(
        &dir,
        code,
        &["--split-nested-mods", "true", "--max-lines", "6"],
    );
    let mod_rs = read(&output.join("mod.rs"));
    assert!(
        mod_rs.contains("::Describe;"),
        "method-dispatched private trait must be re-bound in mod.rs:\n{mod_rs}"
    );
    assert_output_compiles(&output);
}

#[test]
fn macro_defining_split_output_compiles_without_bogus_macro_import() {
    // Regression: the importable-name map included `macro_rules!` names, so
    // sibling modules got `use super::macros::twice;` (E0432) which the
    // `#[macro_use]` declaration then made E0659-ambiguous at every call.
    let code = r#"
macro_rules! twice {
    ($e:expr) => { $e + $e };
}

pub fn use_it() -> u64 { twice!(21) }
"#;
    let dir = TempDir::new().expect("tempdir");
    let output = run_cli(&dir, code, &["--max-lines", "100"]);
    let mod_rs = read(&output.join("mod.rs"));
    assert!(mod_rs.contains("#[macro_use]\npub mod macros;"), "{mod_rs}");
    let top_level = read_dir_combined(&output);
    assert!(
        !top_level.contains("use super::macros::twice;"),
        "macro_rules names must not be path-imported:\n{top_level}"
    );
    assert_output_compiles(&output);
}

#[test]
fn body_self_resolved_imports_are_not_duplicated_into_parent_scope() {
    use splitrs::nested_mod_splitter::compute_parent_scope_items;

    // Regression: names the body resolves through its OWN use statements
    // stayed in `referenced`, so the parent's matching import was carried
    // into mod.rs unused -> `warning: unused import` on the emitted crate.
    let code = r#"
        use std::collections::HashMap;

        pub fn top(map: &HashMap<String, u64>) -> usize { map.len() }

        pub mod core {
            use std::collections::HashMap;

            pub fn probe(map: &HashMap<String, u64>) -> usize { map.len() }
            pub fn pad_a() -> u64 { 1 }
            pub fn pad_b() -> u64 { 2 }
        }
    "#;
    let file = syn::parse_file(code).expect("parse");
    let mut analyzer = FileAnalyzer::new(false, 500);
    analyzer.set_split_nested_mods(true, 3);
    analyzer.set_source(code);
    analyzer.analyze(&file);
    let nested = analyzer.take_nested_mods();
    assert_eq!(nested.len(), 1);
    let modules = analyzer.group_by_module(1000);

    let mut needs_pub_super = HashSet::new();
    let scope = compute_parent_scope_items(
        &nested,
        &analyzer.use_statements,
        &modules,
        &mut needs_pub_super,
        false,
    );
    let rendered = prettyplease::unparse(&syn::File {
        shebang: None,
        attrs: Vec::new(),
        items: scope.items,
    });
    assert!(
        !rendered.contains("HashMap"),
        "parent must not re-import a name the body binds itself:\n{rendered}"
    );
}

#[test]
fn cli_dry_run_previews_nested_tree_without_writing() {
    let dir = TempDir::new().expect("tempdir");
    let input = dir.path().join("lib_fixture.rs");
    fs::write(&input, CORE_FIXTURE).expect("write fixture");
    let output = dir.path().join("out");

    let cmd = Command::new(env!("CARGO_BIN_EXE_splitrs"))
        .arg("-i")
        .arg(&input)
        .arg("-o")
        .arg(&output)
        .arg("--split-nested-mods")
        .arg("true")
        .arg("--max-lines")
        .arg("20")
        .arg("--dry-run")
        .output()
        .expect("run splitrs");
    assert!(cmd.status.success());
    let stdout = String::from_utf8_lossy(&cmd.stdout);
    assert!(stdout.contains("core/"), "{stdout}");
    assert!(!output.exists(), "dry run must not create files");
}