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
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
//! Feature C — nested inline-mod descent (`--split-nested-mods`).
//!
//! A file dominated by one large inline module (`pub mod core { ... }`) was
//! previously unsplittable: the whole module was carried as a single opaque
//! standalone item. This module implements *recursion by reuse*: each
//! over-budget inline `mod x { ... }` body is structurally a `syn::File`-shaped
//! item list, so it is run through the SAME `FileAnalyzer` →
//! `group_by_module` → `generate_content` → `generate_mod_rs` pipeline and
//! emitted into `<output>/x/` with an `x/mod.rs`, recursively. The parent's
//! `mod.rs` declares the child with its original visibility, attributes and
//! doc comments, so every historical `crate::...::x::Item` path keeps
//! resolving.
//!
//! Key invariants:
//!
//! - **Spans stay absolute**: every recursive analyzer receives the FULL
//!   original source via `set_source`, never a sliced mod body, so the
//!   verbatim emission machinery keeps working.
//! - **`super` paths gain exactly one segment per descent level**: items move
//!   one module level deeper, so `super::helper()`, `use super::X;` and
//!   `pub(super)` are rewritten (+1 `super`) by [`deepen_module_items`]; any
//!   item whose text changed drops its verbatim slice (falls back to
//!   prettyplease) so the rewrite is actually emitted.
//! - **Child mods are declared, not re-exported**: `pub use child::*;` at the
//!   parent would widen the original API surface; the facade applies only
//!   *inside* each child's own `mod.rs`.

// Shared internal API between the lib and bin compilation units; some items
// are only called from one of the two targets (mirrors the established
// pattern in `file_analyzer` / `source_map`).
#![allow(dead_code)]

use crate::config::{FacadeStyle, TargetModule};
use crate::domain_router;
use crate::file_analyzer::FileAnalyzer;
use crate::module_generator::{
    collect_use_bound_names, deepen_super_in_use, deepen_super_in_use_tree,
    extract_test_module_path, generate_mod_rs_ext, generate_tests_rs_full, item_defined_ident,
    item_visibility, Module, RefVisitor,
};
use anyhow::{Context, Result};
use proc_macro2::{Group, Ident, Punct, Spacing, TokenStream, TokenTree};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use syn::visit::Visit;
use syn::visit_mut::VisitMut;

/// Options threaded through the recursive planning of nested inline modules.
/// Mirrors the effective top-level configuration so every descent level
/// splits with the same rules.
pub struct NestedSplitOptions<'a> {
    /// Whether large impl blocks are split (`--split-impl-blocks`).
    pub split_impl_blocks: bool,
    /// Line budget per impl block (`--max-impl-lines`).
    pub max_impl_lines: usize,
    /// Line budget per generated module (`--max-lines`); also the threshold an
    /// inline module must exceed to be descended.
    pub max_lines: usize,
    /// Whether inline `#[cfg(test)] mod` blocks are consolidated into a
    /// `tests.rs` at each level (`--extract-tests`).
    pub extract_tests: bool,
    /// Recursion depth guard (`--max-mod-depth`).
    pub max_mod_depth: usize,
    /// Whether `assign_unlisted = "seeded"` is active globally (F2).
    pub seeded_assignment: bool,
    /// The FULL merged `[[target_modules]]` rule list; rules whose `parent`
    /// matches a descended module's path are installed on that level's
    /// analyzer (F1 x F2 composition).
    pub all_rules: &'a [TargetModule],
}

/// The fully analyzed split plan for one descended inline module.
///
/// Planning is separated from writing so `--dry-run` can preview the whole
/// tree and tests can assert on the plan shape without touching the disk.
pub struct NestedModPlan {
    /// The module's identifier (`core` for `pub mod core { ... }`).
    pub name: String,
    /// Original declaration visibility, preserved on the parent's `mod` decl.
    pub vis: syn::Visibility,
    /// Outer attributes (`#[cfg(...)]`, `///` docs) for the parent's decl.
    pub outer_attrs: Vec<syn::Attribute>,
    /// Non-doc inner attributes (`#![allow(...)]`) re-emitted in `x/mod.rs`.
    pub inner_attrs: Vec<syn::Attribute>,
    /// The generated sibling modules of this level (`x/<module>.rs` each).
    pub modules: Vec<Module>,
    /// Recursively descended child modules (each becomes `x/<child>/`).
    pub children: Vec<NestedModPlan>,
    /// Inline test modules diverted at this level (emitted as `x/tests.rs`).
    pub extracted_tests: Vec<syn::Item>,
    /// The synthetic `syn::File` built from the module body; passed to
    /// `generate_content` as the "original file" for import analysis.
    pub synthetic_file: syn::File,
    /// The analyzer for this level (owns use statements, trackers, docs).
    pub analyzer: FileAnalyzer,
    /// Function names upgraded to `pub(super)` for cross-module access.
    pub needs_pub_super: HashSet<String>,
    /// module -> (source module -> fn names) import map for this level.
    pub cross_module_imports: HashMap<String, HashMap<String, Vec<String>>>,
    /// struct -> fields upgraded to `pub(super)` for cross-module access.
    pub fields_need_pub_super: HashMap<String, HashSet<String>>,
    /// `use` items recreating this level's scope bindings for the child
    /// directory modules (grandchildren) — emitted in this level's `mod.rs`.
    pub scope_uses: Vec<syn::Item>,
}

impl NestedModPlan {
    /// Build the declaration-form `mod` item (`<attrs> <vis> mod <name>;`)
    /// the PARENT `mod.rs` uses to hook this plan into the module tree.
    pub fn decl_item(&self) -> syn::ItemMod {
        syn::ItemMod {
            attrs: self.outer_attrs.clone(),
            vis: self.vis.clone(),
            unsafety: None,
            mod_token: Default::default(),
            ident: Ident::new(&self.name, proc_macro2::Span::call_site()),
            content: None,
            semi: Some(Default::default()),
        }
    }

    /// This plan's path and every descendant's path (`core`, `core::deep`, ...).
    fn collect_paths(&self, prefix: &str, out: &mut HashSet<String>) {
        let path = if prefix.is_empty() {
            self.name.clone()
        } else {
            format!("{}::{}", prefix, self.name)
        };
        for child in &self.children {
            child.collect_paths(&path, out);
        }
        out.insert(path);
    }
}

/// Recursively plan the split of one inline module.
///
/// * `mod_item` — the diverted `syn::ItemMod` (must have inline content).
/// * `original_source` — the FULL original file text (spans are absolute; a
///   sliced body would desynchronize the verbatim `SourceMap`).
/// * `mod_path` — `::`-joined path of this module (`core`, `core::deep`);
///   matched against per-rule `parent` values.
/// * `depth` — 1 for a top-level inline module; children get `depth + 1`.
pub fn plan_nested_split(
    mod_item: &syn::ItemMod,
    original_source: &str,
    opts: &NestedSplitOptions<'_>,
    mod_path: &str,
    depth: usize,
) -> Result<NestedModPlan> {
    let Some((_, body_items)) = &mod_item.content else {
        anyhow::bail!(
            "internal error: nested module `{}` has no inline body",
            mod_item.ident
        );
    };

    // Partition the mod's attributes: inner ones travel with the body (they
    // become the synthetic file's attrs), outer ones stay on the declaration.
    let inner_all: Vec<syn::Attribute> = mod_item
        .attrs
        .iter()
        .filter(|attr| matches!(attr.style, syn::AttrStyle::Inner(_)))
        .cloned()
        .collect();
    let outer_attrs: Vec<syn::Attribute> = mod_item
        .attrs
        .iter()
        .filter(|attr| matches!(attr.style, syn::AttrStyle::Outer))
        .cloned()
        .collect();
    let inner_attrs: Vec<syn::Attribute> = inner_all
        .iter()
        .filter(|attr| !attr.path().is_ident("doc"))
        .cloned()
        .collect();

    let synthetic_file = syn::File {
        shebang: None,
        attrs: inner_all,
        items: body_items.clone(),
    };

    // Same pipeline, one level down.
    let mut analyzer = FileAnalyzer::new(opts.split_impl_blocks, opts.max_impl_lines);
    analyzer.set_extract_tests(opts.extract_tests);
    analyzer.set_seeded_assignment(opts.seeded_assignment);
    let my_rules: Vec<TargetModule> = opts
        .all_rules
        .iter()
        .filter(|rule| rule.parent.as_deref() == Some(mod_path))
        .cloned()
        .collect();
    analyzer.set_target_modules(my_rules.clone());
    // CRITICAL: full original text — spans are absolute (see module docs).
    analyzer.set_source(original_source);
    if depth < opts.max_mod_depth {
        analyzer.set_split_nested_mods(true, opts.max_lines);
    }
    analyzer.analyze(&synthetic_file);

    // Unknown exact names in this scope's rules are a hard error (F2).
    domain_router::check_unmatched_patterns(&domain_router::routable_names(&analyzer), &my_rules)
        .with_context(|| format!("in target-modules rules for parent `{}`", mod_path))?;

    // Recurse into grandchildren first (they were diverted out of the pools).
    let child_mods = analyzer.take_nested_mods();
    let mut children = Vec::new();
    for child in &child_mods {
        let child_path = format!("{}::{}", mod_path, child.ident);
        children.push(plan_nested_split(
            child,
            original_source,
            opts,
            &child_path,
            depth + 1,
        )?);
    }

    let has_extracted_tests = !analyzer.extracted_tests.is_empty();
    if has_extracted_tests && children.iter().any(|c| c.name == "tests") {
        anyhow::bail!(
            "nested module `{}::tests` conflicts with the tests.rs produced by --extract-tests; \
             re-run without --extract-tests or rename the module",
            mod_path
        );
    }

    let mut modules = analyzer.group_by_module(opts.max_lines);

    // Generated bucket names must not collide with real child module names
    // (a nested `mod types` vs. a generated `types.rs`), nor with the
    // reserved `tests` when a tests.rs will be written.
    let mut reserved: HashSet<String> = children.iter().map(|c| c.name.clone()).collect();
    if has_extracted_tests {
        reserved.insert("tests".to_string());
    }
    rename_module_collisions(&mut modules, &reserved);

    // Content moved from `<mod>::item` to `<mod>::<module>::item` sits one
    // level deeper: deepen every `super` path by one segment.
    for module in &mut modules {
        deepen_module_items(module);
    }

    // Bare references to descended child mods (e.g. `deep::helper()`) need
    // `use super::deep;` in the generated sibling files.
    let child_names: Vec<String> = children.iter().map(|c| c.name.clone()).collect();
    add_child_mod_imports(&mut modules, &child_names);

    // Register trait definitions for trait-method import tracking (same as
    // the top-level pipeline).
    for module in &modules {
        for item in &module.standalone_items {
            if let syn::Item::Trait(trait_item) = item {
                let trait_name = trait_item.ident.to_string();
                analyzer
                    .trait_tracker
                    .register_trait_module(&trait_name, &module.name);
            }
        }
    }

    // Cross-module visibility fixups (pub(super) upgrades + import map),
    // computed while the extracted tests are still on the analyzer so the
    // reserved `tests` import key is populated.
    let (mut needs_pub_super, cross_module_imports, fields_need_pub_super) =
        analyzer.compute_cross_module_visibility(&modules);
    let extracted_tests = analyzer.take_extracted_tests();

    // Grandchildren reference THIS level's scope through `super::` paths and
    // forwarded globs; recreate the needed bindings in this level's mod.rs.
    // No deepening: `x/mod.rs` IS the module `x`, the same scope depth the
    // mod body had.
    let scope = compute_parent_scope_items(
        &child_mods,
        &analyzer.use_statements,
        &modules,
        &mut needs_pub_super,
        false,
    );
    // Grandchildren reach those bindings only through their forwarded
    // `use super::*;` globs — tell their emission which names keep them alive.
    install_parent_scope_provisions(&mut children, &scope);
    let scope_uses = scope.items;

    Ok(NestedModPlan {
        name: mod_item.ident.to_string(),
        vis: mod_item.vis.clone(),
        outer_attrs,
        inner_attrs,
        modules,
        children,
        extracted_tests,
        synthetic_file,
        analyzer,
        needs_pub_super,
        cross_module_imports,
        fields_need_pub_super,
        scope_uses,
    })
}

/// Write a planned nested split under `parent_dir`, creating
/// `<parent_dir>/<name>/` with one file per module, an optional `tests.rs`,
/// recursive child directories, and the level's `mod.rs`. Returns every file
/// path created (depth-first, `mod.rs` last per level).
pub fn write_plan(
    plan: &NestedModPlan,
    parent_dir: &Path,
    facade: FacadeStyle,
) -> Result<Vec<PathBuf>> {
    let dir = parent_dir.join(&plan.name);
    fs::create_dir_all(&dir)
        .with_context(|| format!("Failed to create nested module directory {:?}", dir))?;
    let mut created = Vec::new();

    let mut type_to_module: HashMap<String, String> = HashMap::new();
    for module in &plan.modules {
        // NOT `get_exported_types`: `macro_rules!` names are not
        // path-importable and must never become `use super::macros::name;`.
        for exported in module.importable_exported_names() {
            type_to_module.insert(exported, module.name.clone());
        }
    }

    // File-backed `mod x;` declarations pinned to THIS level's root
    // `mod.rs` (see `FileAnalyzer::file_backed_mods`) — forwarded original
    // `use` statements referencing one of these by bare name need a
    // `super::` prefix once relocated into a sibling generated file.
    let pinned_root_mod_names: HashSet<String> = plan
        .analyzer
        .file_backed_mods
        .iter()
        .map(|m| m.ident.to_string())
        .collect();

    for module in &plan.modules {
        let content = module.generate_content(
            &plan.synthetic_file,
            &plan.analyzer.use_statements,
            &type_to_module,
            &plan.needs_pub_super,
            plan.cross_module_imports.get(&module.name),
            &plan.fields_need_pub_super,
            Some(&plan.analyzer.trait_tracker),
            &pinned_root_mod_names,
        );
        let module_path = dir.join(format!("{}.rs", module.name));
        fs::write(&module_path, &content)
            .with_context(|| format!("Failed to write nested module file {:?}", module_path))?;
        if let Err(e) = syn::parse_file(&content) {
            eprintln!(
                "Warning: generated nested module {:?} may contain syntax errors: {}",
                module_path, e
            );
        }
        created.push(module_path);
    }

    let has_extracted_tests = !plan.extracted_tests.is_empty();
    if has_extracted_tests {
        let empty_imports = HashMap::new();
        let tests_sibling_imports = plan
            .cross_module_imports
            .get("tests")
            .unwrap_or(&empty_imports);
        let tests_parent_resolvable: HashSet<String> = type_to_module.keys().cloned().collect();
        // `deepen_super = true`: the mod-body `use super::X;` statements
        // forwarded into tests.rs sit one level deeper now.
        let tests_content = generate_tests_rs_full(
            &plan.extracted_tests,
            &plan.analyzer.use_statements,
            tests_sibling_imports,
            true,
            &tests_parent_resolvable,
            // TODO: `NestedModPlan` doesn't currently carry the original file's
            // source text, so nested-mod-split test bodies still lose non-doc
            // comments to the prettyplease round-trip. Thread it through if/when
            // this path needs the same byte-verbatim treatment as the top-level
            // `--extract-tests` output in `main.rs`.
            None,
        );
        let tests_path = dir.join("tests.rs");
        fs::write(&tests_path, &tests_content)
            .with_context(|| format!("Failed to write nested tests file {:?}", tests_path))?;
        if let Err(e) = syn::parse_file(&tests_content) {
            eprintln!(
                "Warning: generated nested tests.rs may contain syntax errors: {}",
                e
            );
        }
        created.push(tests_path);
    }

    let mut child_decls: Vec<syn::ItemMod> = Vec::new();
    for child in &plan.children {
        created.extend(write_plan(child, &dir, facade)?);
        child_decls.push(child.decl_item());
    }
    child_decls.extend(plan.analyzer.file_backed_mods.iter().cloned());

    let test_module_path = extract_test_module_path(&plan.synthetic_file);
    let mod_content = generate_mod_rs_ext(
        &plan.modules,
        &dir,
        test_module_path.as_deref(),
        has_extracted_tests,
        &plan.analyzer.file_inner_docs,
        &plan.inner_attrs,
        &child_decls,
        facade,
        &plan.scope_uses,
    )?;
    let mod_path = dir.join("mod.rs");
    fs::write(&mod_path, &mod_content)
        .with_context(|| format!("Failed to write nested mod.rs {:?}", mod_path))?;
    if let Err(e) = syn::parse_file(&mod_content) {
        eprintln!(
            "Warning: generated nested mod.rs {:?} may contain syntax errors: {}",
            mod_path, e
        );
    }
    created.push(mod_path);

    Ok(created)
}

/// Every rule with a `parent` must name a module path that was actually
/// descended; otherwise the rule would be silently dead. Hard error with the
/// known paths listed.
pub fn validate_parent_rules(rules: &[TargetModule], plans: &[NestedModPlan]) -> Result<()> {
    let mut known_paths: HashSet<String> = HashSet::new();
    for plan in plans {
        plan.collect_paths("", &mut known_paths);
    }
    for rule in rules {
        let Some(parent) = &rule.parent else { continue };
        if known_paths.contains(parent) {
            continue;
        }
        let mut known: Vec<&String> = known_paths.iter().collect();
        known.sort();
        let listing = if known.is_empty() {
            "none (no inline module exceeded the --max-lines budget)".to_string()
        } else {
            known
                .iter()
                .map(|s| s.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        };
        anyhow::bail!(
            "target-modules rule `{}` declares parent = \"{}\", but no such nested module was \
             descended. Descended module paths: {}. Check the path spelling, ensure the module \
             body exceeds --max-lines, and that --split-nested-mods is enabled.",
            rule.name,
            parent,
            listing
        );
    }
    Ok(())
}

/// Rename generated modules whose names collide with `reserved` (real child
/// module names and the `tests` file). Child mods keep their true names —
/// they are addressable API — so the mechanically named buckets yield.
pub fn rename_module_collisions(modules: &mut [Module], reserved: &HashSet<String>) {
    if reserved.is_empty() {
        return;
    }
    let mut used: HashSet<String> = modules.iter().map(|m| m.name.clone()).collect();
    used.extend(reserved.iter().cloned());
    for module in modules.iter_mut() {
        if !reserved.contains(&module.name) {
            continue;
        }
        let mut suffix = 2usize;
        loop {
            let candidate = format!("{}_{}", module.name, suffix);
            if !used.contains(&candidate) {
                used.insert(candidate.clone());
                module.name = candidate;
                break;
            }
            suffix += 1;
        }
    }
}

/// Record, per module, which sibling directory-module names its items
/// reference by bare path, so `generate_content` emits `use super::<name>;`.
pub fn add_child_mod_imports(modules: &mut [Module], child_names: &[String]) {
    if child_names.is_empty() {
        return;
    }
    for module in modules.iter_mut() {
        let refs = module.analyze_references();
        let local = module.local_item_names();
        for child in child_names {
            if refs.path_roots.contains(child) && !local.contains(child) {
                module.sibling_mod_imports.push(child.clone());
            }
        }
    }
}

/// Result of [`compute_parent_scope_items`].
///
/// `items` is what the parent-level `mod.rs` must carry; the two name sets
/// describe what descended child modules can resolve THROUGH that `mod.rs`,
/// so their emission can decide whether the forwarded `use super::*;` glob
/// is still load-bearing (see [`install_parent_scope_provisions`]).
#[derive(Default)]
pub struct ParentScopeItems {
    /// The `use` items to emit in the parent's `mod.rs`.
    pub items: Vec<syn::Item>,
    /// Names the parent scope provides to descendants: leaves bound by the
    /// kept parent `use` statements, the `use self::<module>::<name>;`
    /// re-bindings, `pub` item names (reachable through the facade
    /// re-exports), and the declared child module names themselves.
    pub provided_names: HashSet<String>,
    /// Method names of traits reachable from descendants through the parent
    /// scope (`pub` traits plus privately re-bound ones). A child module
    /// calling one of these methods still needs its forwarded glob even
    /// though the trait never appears as a path root.
    pub provided_trait_methods: HashSet<String>,
}

/// Recreate the parent-scope bindings that descended mod bodies depend on.
///
/// Inside an inline `mod x { ... }`, `use super::*;` and `super::name` paths
/// resolved against the surrounding FILE scope. After the split that scope is
/// the generated `mod.rs`, which by default holds only `pub use` re-exports
/// of public items — private file-level `use` bindings (e.g.
/// `use std::collections::HashMap;`) and private items would no longer
/// resolve from inside `x/`. This computes the `use` items `mod.rs` must
/// carry to restore the original resolution chain:
///
/// - the parent's own `use` statements, pruned to the names the nested
///   bodies actually reference (a private `use` binding in a module IS
///   visible to its descendants, so this widens nothing);
/// - `use self::<module>::<name>;` bindings for non-`pub` items that moved
///   into generated sibling modules but are referenced from the nested
///   bodies — including traits reached purely through method-call syntax;
///   referenced private functions are additionally added to
///   `needs_pub_super` so their definition site is upgraded.
///
/// The returned [`ParentScopeItems`] also carries the provided-name sets the
/// caller must stamp onto the direct child plans via
/// [`install_parent_scope_provisions`], so child emission keeps the forwarded
/// `use super::*;` globs these bindings are reached through.
///
/// `deepen` adds one `super` segment to the pruned parent `use`s for the
/// in-place `--deepen-super` workflow (where `mod.rs` itself sits one level
/// deeper than the original file did).
pub fn compute_parent_scope_items(
    nested_mods: &[syn::ItemMod],
    use_statements: &[syn::Item],
    modules: &[Module],
    needs_pub_super: &mut HashSet<String>,
    deepen: bool,
) -> ParentScopeItems {
    if nested_mods.is_empty() {
        return ParentScopeItems::default();
    }

    // Names the nested bodies may resolve at the parent scope: bare path
    // roots (resolved through the body's `use super::*;`) and attribute
    // idents (derives) — minus the names each body binds itself (its item
    // definitions AND the leaves of its own non-`super` use statements, so a
    // body-local `use std::collections::HashMap;` does not force the parent
    // to re-import HashMap it would never use) — plus the first non-`super`
    // segment of `super::...` paths, which resolve at the parent scope
    // REGARDLESS of local bindings and are therefore never subtracted.
    let mut referenced: HashSet<String> = HashSet::new();
    let mut method_calls: HashSet<String> = HashSet::new();
    for mod_item in nested_mods {
        let Some((_, body_items)) = &mod_item.content else {
            continue;
        };
        let mut plain = RefVisitor::default();
        let mut supers = SuperTargetCollector::default();
        let mut locally_bound: HashSet<String> = HashSet::new();
        for item in body_items {
            plain.visit_item(item);
            supers.visit_item(item);
            if let Some(name) = item_defined_ident(item) {
                locally_bound.insert(name);
            }
            collect_non_super_use_bound_names(item, &mut locally_bound);
        }
        method_calls.extend(plain.method_calls.iter().cloned());
        let mut names: HashSet<String> = plain.path_roots;
        names.extend(plain.attr_idents);
        for name in names {
            if !locally_bound.contains(&name) {
                referenced.insert(name);
            }
        }
        referenced.extend(supers.names);
    }
    for keyword in ["super", "crate", "self", "Self"] {
        referenced.remove(keyword);
    }

    let mut out: Vec<syn::Item> = Vec::new();
    let mut provided_names: HashSet<String> = HashSet::new();
    // The children themselves are declared in the parent's mod.rs, so a
    // sibling child mod referenced by bare path resolves there too.
    for mod_item in nested_mods {
        provided_names.insert(mod_item.ident.to_string());
    }

    // 1. The parent's own use statements, pruned to what the bodies need.
    for use_item in use_statements {
        let Some(pruned) = Module::prune_unused_use(use_item, &referenced, &method_calls) else {
            continue;
        };
        collect_use_bound_names(&pruned, &mut provided_names);
        if deepen {
            out.push(deepen_super_in_use(&pruned));
        } else {
            out.push(pruned);
        }
    }

    // 2. Bindings for non-pub items relocated into generated modules. A
    //    private trait is needed even when it never appears as a path root:
    //    a body method call like `41u64.describe()` requires the trait in
    //    scope at the (relocated) call site.
    let mut bound: HashSet<String> = HashSet::new();
    for module in modules {
        let mut push_binding = |module_name: &str, name: &str, bound: &mut HashSet<String>| {
            if !bound.insert(name.to_string()) {
                return;
            }
            if let Ok(item) =
                syn::parse_str::<syn::Item>(&format!("use self::{}::{};", module_name, name))
            {
                out.push(item);
            }
        };
        for type_info in &module.types {
            if !referenced.contains(&type_info.name) {
                continue;
            }
            if matches!(
                item_visibility(&type_info.item),
                Some(syn::Visibility::Public(_))
            ) {
                continue; // reachable through the facade re-exports
            }
            push_binding(&module.name, &type_info.name, &mut bound);
        }
        for item in &module.standalone_items {
            if matches!(item, syn::Item::Macro(_)) {
                continue; // macro_rules flow through #[macro_use] instead
            }
            let Some(name) = item_defined_ident(item) else {
                continue;
            };
            if !referenced.contains(&name) && !trait_method_called(item, &method_calls) {
                continue;
            }
            if matches!(item_visibility(item), Some(syn::Visibility::Public(_))) {
                continue;
            }
            if matches!(item, syn::Item::Fn(_)) {
                // Private fns are upgraded at their definition site so the
                // binding (and the callers behind it) can see them.
                needs_pub_super.insert(name.clone());
            }
            push_binding(&module.name, &name, &mut bound);
        }
    }
    provided_names.extend(bound.iter().cloned());

    // 3. Public item names (reachable through the facade re-exports) and the
    //    method sets of every trait the children can reach — recorded so
    //    child emission knows which unresolved references its forwarded glob
    //    still serves. `macro_rules!` names are excluded: they are not
    //    path-importable and flow through `#[macro_use]` instead.
    let mut provided_trait_methods: HashSet<String> = HashSet::new();
    for module in modules {
        for type_info in &module.types {
            if matches!(
                item_visibility(&type_info.item),
                Some(syn::Visibility::Public(_))
            ) {
                provided_names.insert(type_info.name.clone());
            }
        }
        for item in &module.standalone_items {
            let Some(name) = item_defined_ident(item) else {
                continue;
            };
            let is_pub = matches!(item_visibility(item), Some(syn::Visibility::Public(_)));
            if is_pub {
                provided_names.insert(name.clone());
            }
            if let syn::Item::Trait(trait_item) = item {
                if is_pub || bound.contains(&name) {
                    provided_trait_methods.extend(trait_declared_method_names(trait_item));
                }
            }
        }
    }

    ParentScopeItems {
        items: out,
        provided_names,
        provided_trait_methods,
    }
}

/// Stamp what the parent scope provides onto every module of each DIRECT
/// child plan, so child emission keeps the forwarded `use super::*;` glob
/// exactly when it is still load-bearing. Lowercase re-bindings
/// (`use self::functions::make_hidden;`) and method-dispatched traits are
/// invisible to the uppercase unresolved-type heuristic, so without this
/// information the glob — their only resolution route — would be dropped.
pub fn install_parent_scope_provisions(children: &mut [NestedModPlan], scope: &ParentScopeItems) {
    if scope.provided_names.is_empty() && scope.provided_trait_methods.is_empty() {
        return;
    }
    for child in children.iter_mut() {
        for module in &mut child.modules {
            module
                .parent_scope_names
                .extend(scope.provided_names.iter().cloned());
            module
                .parent_scope_trait_methods
                .extend(scope.provided_trait_methods.iter().cloned());
        }
    }
}

/// Leaf names a body-local `use` statement binds WITHOUT going through
/// `super` (its own `std::` / `crate::` / `self::` imports). These names
/// resolve inside the descended module itself — the statement is forwarded
/// into the generated files — so the parent scope must not re-import them
/// (doing so leaves a provably unused import in the parent `mod.rs`).
fn collect_non_super_use_bound_names(item: &syn::Item, out: &mut HashSet<String>) {
    let syn::Item::Use(use_stmt) = item else {
        return;
    };
    fn walk(tree: &syn::UseTree, under_super: bool, out: &mut HashSet<String>) {
        match tree {
            syn::UseTree::Path(path) => {
                walk(&path.tree, under_super || path.ident == "super", out);
            }
            syn::UseTree::Name(name) if !under_super => {
                out.insert(name.ident.to_string());
            }
            syn::UseTree::Rename(rename) if !under_super => {
                out.insert(rename.rename.to_string());
            }
            syn::UseTree::Group(group) => {
                for tree in &group.items {
                    walk(tree, under_super, out);
                }
            }
            _ => {}
        }
    }
    walk(&use_stmt.tree, false, out);
}

/// Whether `item` is a trait one of whose declared methods appears in
/// `method_calls` — the signal that a nested body reaches the trait purely
/// through method-call syntax (`41u64.describe()`), where the trait name
/// itself never shows up as a path root.
fn trait_method_called(item: &syn::Item, method_calls: &HashSet<String>) -> bool {
    let syn::Item::Trait(trait_item) = item else {
        return false;
    };
    trait_item.items.iter().any(|member| {
        matches!(member, syn::TraitItem::Fn(f) if method_calls.contains(&f.sig.ident.to_string()))
    })
}

/// The method names a trait declares (seeds `provided_trait_methods`).
fn trait_declared_method_names(trait_item: &syn::ItemTrait) -> Vec<String> {
    trait_item
        .items
        .iter()
        .filter_map(|member| match member {
            syn::TraitItem::Fn(f) => Some(f.sig.ident.to_string()),
            _ => None,
        })
        .collect()
}

/// Read-only visitor collecting, for every `super::...`-rooted path or use
/// tree, the first non-`super` segment — the name that must resolve in the
/// parent scope after the body moves one level down.
#[derive(Default)]
struct SuperTargetCollector {
    names: HashSet<String>,
}

impl<'ast> Visit<'ast> for SuperTargetCollector {
    fn visit_path(&mut self, path: &'ast syn::Path) {
        if path.leading_colon.is_none() {
            if let Some(first) = path.segments.first() {
                if first.ident == "super" {
                    if let Some(target) = path
                        .segments
                        .iter()
                        .map(|segment| segment.ident.to_string())
                        .find(|ident| ident != "super")
                    {
                        self.names.insert(target);
                    }
                }
            }
        }
        syn::visit::visit_path(self, path);
    }

    fn visit_macro(&mut self, mac: &'ast syn::Macro) {
        // Mirror RefVisitor's macro handling: paths inside macro bodies (e.g.
        // `twice!(super::VALUE)`) matter for parent-scope resolution too.
        let tokens = mac.tokens.clone();
        if let Ok(exprs) = syn::parse::Parser::parse2(
            syn::punctuated::Punctuated::<syn::Expr, syn::Token![,]>::parse_terminated,
            tokens.clone(),
        ) {
            for expr in &exprs {
                self.visit_expr(expr);
            }
        } else if let Ok(expr) = syn::parse2::<syn::Expr>(tokens) {
            self.visit_expr(&expr);
        }
        syn::visit::visit_macro(self, mac);
    }

    fn visit_item_use(&mut self, item: &'ast syn::ItemUse) {
        fn walk(tree: &syn::UseTree, seen_super: bool, names: &mut HashSet<String>) {
            match tree {
                syn::UseTree::Path(path) => {
                    if path.ident == "super" {
                        walk(&path.tree, true, names);
                    } else if seen_super {
                        names.insert(path.ident.to_string());
                    }
                }
                syn::UseTree::Name(name) if seen_super => {
                    names.insert(name.ident.to_string());
                }
                syn::UseTree::Rename(rename) if seen_super => {
                    names.insert(rename.ident.to_string());
                }
                syn::UseTree::Group(group) => {
                    for tree in &group.items {
                        walk(tree, seen_super, names);
                    }
                }
                _ => {}
            }
        }
        walk(&item.tree, false, &mut self.names);
        syn::visit::visit_item_use(self, item);
    }
}

/// Human-readable dry-run tree for a plan: directory, per-file summaries,
/// recursive children, and the level's `mod.rs`.
pub fn dry_run_lines(plan: &NestedModPlan, indent: usize) -> Vec<String> {
    let pad = "  ".repeat(indent);
    let mut lines = vec![format!("{}📁 {}/", pad, plan.name)];
    for module in &plan.modules {
        lines.push(format!(
            "{}  📄 {}.rs ({} types, {} items, {} trait impls)",
            pad,
            module.name,
            module.types.len(),
            module.standalone_items.len(),
            module.trait_impls.len()
        ));
    }
    if !plan.extracted_tests.is_empty() {
        lines.push(format!("{}  📄 tests.rs", pad));
    }
    for child in &plan.children {
        lines.extend(dry_run_lines(child, indent + 1));
    }
    lines.push(format!("{}  📄 mod.rs", pad));
    lines
}

// ---------------------------------------------------------------------------
// `super`-path deepening
// ---------------------------------------------------------------------------

/// Mark a module as one-level-deeper and rewrite every `super`-headed path in
/// its owned items (+1 `super`). Items whose text changed drop their verbatim
/// slice so the rewritten form is actually emitted (prettyplease fallback);
/// untouched items keep byte-faithful verbatim emission.
pub fn deepen_module_items(module: &mut Module) {
    // The flag handles the forwarded file-level `use` statements at emission.
    module.deepen_super = true;

    let aligned = module.standalone_verbatim.len() == module.standalone_items.len();
    for (idx, item) in module.standalone_items.iter_mut().enumerate() {
        if deepen_super_in_item(item) && aligned {
            module.standalone_verbatim[idx] = None;
        }
    }
    for type_info in &mut module.types {
        if deepen_super_in_item(&mut type_info.item) {
            type_info.verbatim = None;
        }
        for impl_item in &mut type_info.impls {
            deepen_super_in_item(impl_item);
        }
        for trait_impl in &mut type_info.trait_impls {
            if deepen_super_in_item(&mut trait_impl.impl_item) {
                trait_impl.verbatim = None;
            }
        }
    }
    for trait_impl in &mut module.trait_impls {
        if deepen_super_in_item(&mut trait_impl.impl_item) {
            trait_impl.verbatim = None;
        }
    }
    if let Some(group) = &mut module.method_group {
        for method in &mut group.methods {
            let mut deepener = SuperDeepener { changed: false };
            deepener.visit_impl_item_fn_mut(&mut method.item);
            if deepener.changed {
                method.verbatim = None;
            }
        }
    }
    if let Some(self_ty) = &mut module.impl_self_ty {
        let mut deepener = SuperDeepener { changed: false };
        deepener.visit_type_mut(self_ty);
        if deepener.changed {
            module.impl_header_verbatim = None;
        }
    }
    if let Some(generics) = &mut module.impl_generics {
        let mut deepener = SuperDeepener { changed: false };
        deepener.visit_generics_mut(generics);
        if deepener.changed {
            module.impl_header_verbatim = None;
        }
    }
}

/// Rewrite every `super`-headed path inside `item` (+1 `super`). Returns
/// whether anything changed.
pub fn deepen_super_in_item(item: &mut syn::Item) -> bool {
    let mut deepener = SuperDeepener { changed: false };
    deepener.visit_item_mut(item);
    deepener.changed
}

/// `visit_mut` pass that adds one `super` segment to the head of every
/// `super::`-rooted path: expression/type/pattern paths, `use` trees,
/// restricted visibilities (`pub(super)` → `pub(in super::super)`), and —
/// textually — `super::` runs inside macro token streams.
struct SuperDeepener {
    changed: bool,
}

/// Whether a path is rooted at a bare `super` segment (no leading `::`).
fn path_head_is_super(path: &syn::Path) -> bool {
    path.leading_colon.is_none()
        && path
            .segments
            .first()
            .is_some_and(|segment| segment.ident == "super")
}

/// Insert one leading `super` segment when the path head is `super`.
fn deepen_path_head(path: &mut syn::Path) -> bool {
    if !path_head_is_super(path) {
        return false;
    }
    let span = path
        .segments
        .first()
        .map(|segment| segment.ident.span())
        .unwrap_or_else(proc_macro2::Span::call_site);
    path.segments.insert(
        0,
        syn::PathSegment {
            ident: Ident::new("super", span),
            arguments: syn::PathArguments::None,
        },
    );
    true
}

/// Whether a use tree is rooted at `super`.
fn use_tree_head_is_super(tree: &syn::UseTree) -> bool {
    matches!(tree, syn::UseTree::Path(p) if p.ident == "super")
}

impl VisitMut for SuperDeepener {
    fn visit_path_mut(&mut self, path: &mut syn::Path) {
        if deepen_path_head(path) {
            self.changed = true;
        }
        // Descend into segment arguments (`super::Foo<super::Bar>`): each
        // inner path is a separate node and gets its own +1.
        syn::visit_mut::visit_path_mut(self, path);
    }

    fn visit_expr_path_mut(&mut self, node: &mut syn::ExprPath) {
        // Qualified paths (`<super::T as super::Tr>::call`) store the trait
        // part inside `path` with `qself.position` counting its segments; the
        // head insertion done by `visit_path_mut` (default recursion below)
        // must shift that boundary by one. Pattern paths are `ExprPath` in
        // syn 2, so this covers them too.
        let deepened = path_head_is_super(&node.path);
        syn::visit_mut::visit_expr_path_mut(self, node);
        if deepened {
            if let Some(qself) = &mut node.qself {
                qself.position += 1;
            }
        }
    }

    fn visit_type_path_mut(&mut self, node: &mut syn::TypePath) {
        let deepened = path_head_is_super(&node.path);
        syn::visit_mut::visit_type_path_mut(self, node);
        if deepened {
            if let Some(qself) = &mut node.qself {
                qself.position += 1;
            }
        }
    }

    fn visit_vis_restricted_mut(&mut self, vis: &mut syn::VisRestricted) {
        let first = vis
            .path
            .segments
            .first()
            .map(|segment| segment.ident.to_string());
        match first.as_deref() {
            Some("super") => {
                // `pub(super)` → `pub(in super::super)`;
                // `pub(in super::x)` → `pub(in super::super::x)`.
                let span = vis
                    .path
                    .segments
                    .first()
                    .map(|segment| segment.ident.span())
                    .unwrap_or_else(proc_macro2::Span::call_site);
                vis.path.segments.insert(
                    0,
                    syn::PathSegment {
                        ident: Ident::new("super", span),
                        arguments: syn::PathArguments::None,
                    },
                );
                vis.in_token = Some(Default::default());
                self.changed = true;
            }
            Some("self") if vis.path.segments.len() == 1 && vis.in_token.is_none() => {
                // `pub(self)` (private to the mod body) — the body became the
                // directory module, i.e. `super` from the item's new file.
                if let Some(segment) = vis.path.segments.first_mut() {
                    segment.ident = Ident::new("super", segment.ident.span());
                }
                self.changed = true;
            }
            _ => {}
        }
        // No default recursion: the restricted path is fully handled above;
        // recursing into it would double-deepen via `visit_path_mut`.
    }

    fn visit_item_use_mut(&mut self, item: &mut syn::ItemUse) {
        if use_tree_head_is_super(&item.tree) {
            deepen_super_in_use_tree(&mut item.tree);
            self.changed = true;
        }
        // Use trees contain no other rewrite targets.
    }

    fn visit_macro_mut(&mut self, mac: &mut syn::Macro) {
        let (tokens, changed) = deepen_super_tokens(&mac.tokens);
        if changed {
            mac.tokens = tokens;
            self.changed = true;
        }
        // Default recursion still handles the macro's own path
        // (`super::my_macro!(...)`) via `visit_path_mut`.
        syn::visit_mut::visit_macro_mut(self, mac);
    }
}

/// Token-level deepening for macro bodies: every `super ::` run that is not
/// itself preceded by `::` gains one `super ::` prefix. Recurses into groups.
fn deepen_super_tokens(tokens: &TokenStream) -> (TokenStream, bool) {
    let mut changed = false;
    let items: Vec<TokenTree> = tokens.clone().into_iter().collect();
    let mut out: Vec<TokenTree> = Vec::with_capacity(items.len());
    for (i, tt) in items.iter().enumerate() {
        match tt {
            TokenTree::Group(group) => {
                let (inner, inner_changed) = deepen_super_tokens(&group.stream());
                changed |= inner_changed;
                let mut new_group = Group::new(group.delimiter(), inner);
                new_group.set_span(group.span());
                out.push(TokenTree::Group(new_group));
            }
            TokenTree::Ident(ident) if ident == "super" => {
                let followed_by_colons = matches!(
                    (items.get(i + 1), items.get(i + 2)),
                    (Some(TokenTree::Punct(a)), Some(TokenTree::Punct(b)))
                        if a.as_char() == ':' && b.as_char() == ':'
                );
                let preceded_by_colons = out.len() >= 2
                    && matches!(
                        (&out[out.len() - 2], &out[out.len() - 1]),
                        (TokenTree::Punct(a), TokenTree::Punct(b))
                            if a.as_char() == ':' && b.as_char() == ':'
                    );
                if followed_by_colons && !preceded_by_colons {
                    out.push(TokenTree::Ident(Ident::new("super", ident.span())));
                    let mut c1 = Punct::new(':', Spacing::Joint);
                    c1.set_span(ident.span());
                    let mut c2 = Punct::new(':', Spacing::Alone);
                    c2.set_span(ident.span());
                    out.push(TokenTree::Punct(c1));
                    out.push(TokenTree::Punct(c2));
                    changed = true;
                }
                out.push(tt.clone());
            }
            _ => out.push(tt.clone()),
        }
    }
    (out.into_iter().collect(), changed)
}

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

    fn render_item(item: &syn::Item) -> String {
        prettyplease::unparse(&syn::File {
            shebang: None,
            attrs: Vec::new(),
            items: vec![item.clone()],
        })
    }

    #[test]
    fn deepens_use_statement_head() {
        let mut item: syn::Item = syn::parse_quote! { use super::helper::Foo; };
        assert!(deepen_super_in_item(&mut item));
        assert!(render_item(&item).contains("use super::super::helper::Foo;"));
    }

    #[test]
    fn deepens_expression_and_type_paths() {
        let mut item: syn::Item = syn::parse_quote! {
            fn f(x: super::Foo) -> super::Bar {
                super::helper(x)
            }
        };
        assert!(deepen_super_in_item(&mut item));
        let rendered = render_item(&item);
        assert!(rendered.contains("super::super::Foo"), "{rendered}");
        assert!(rendered.contains("super::super::Bar"), "{rendered}");
        assert!(rendered.contains("super::super::helper(x)"), "{rendered}");
    }

    #[test]
    fn deepens_qualified_and_nested_generic_paths_once_each() {
        let mut item: syn::Item = syn::parse_quote! {
            fn f() -> super::Wrapper<super::Inner> {
                <super::T as super::Tr>::call()
            }
        };
        assert!(deepen_super_in_item(&mut item));
        let rendered = render_item(&item);
        assert!(
            rendered.contains("super::super::Wrapper<super::super::Inner>"),
            "{rendered}"
        );
        assert!(
            rendered.contains("<super::super::T as super::super::Tr>::call()"),
            "{rendered}"
        );
        assert!(!rendered.contains("super::super::super"), "{rendered}");
    }

    #[test]
    fn deepens_pub_super_visibility() {
        let mut item: syn::Item = syn::parse_quote! {
            pub(super) fn f() {}
        };
        assert!(deepen_super_in_item(&mut item));
        let rendered = render_item(&item);
        assert!(
            rendered.contains("pub(in super::super) fn f()"),
            "{rendered}"
        );
    }

    #[test]
    fn deepens_pub_in_super_path_visibility() {
        let mut item: syn::Item = syn::parse_quote! {
            pub(in super::x) fn f() {}
        };
        assert!(deepen_super_in_item(&mut item));
        let rendered = render_item(&item);
        assert!(
            rendered.contains("pub(in super::super::x) fn f()"),
            "{rendered}"
        );
    }

    #[test]
    fn leaves_crate_and_external_paths_untouched() {
        let mut item: syn::Item = syn::parse_quote! {
            pub(crate) fn f(x: crate::Foo) -> std::io::Result<()> {
                crate::helper(x)
            }
        };
        assert!(!deepen_super_in_item(&mut item));
    }

    #[test]
    fn deepens_super_inside_macro_tokens() {
        let mut item: syn::Item = syn::parse_quote! {
            fn f() {
                println!("{}", super::VALUE);
            }
        };
        assert!(deepen_super_in_item(&mut item));
        let rendered = render_item(&item);
        assert!(
            rendered.contains("super :: super :: VALUE")
                || rendered.contains("super::super::VALUE"),
            "{rendered}"
        );
    }

    #[test]
    fn multi_super_paths_gain_exactly_one_level() {
        let mut item: syn::Item = syn::parse_quote! {
            fn f() {
                super::super::helper();
            }
        };
        assert!(deepen_super_in_item(&mut item));
        let rendered = render_item(&item);
        assert!(
            rendered.contains("super::super::super::helper()"),
            "{rendered}"
        );
        assert!(
            !rendered.contains("super::super::super::super"),
            "{rendered}"
        );
    }

    #[test]
    fn rename_module_collisions_yields_to_child_names() {
        let mut modules = vec![
            Module::new("types".to_string()),
            Module::new("functions".to_string()),
        ];
        let mut reserved = HashSet::new();
        reserved.insert("types".to_string());
        rename_module_collisions(&mut modules, &reserved);
        assert_eq!(modules[0].name, "types_2");
        assert_eq!(modules[1].name, "functions");
    }
}