rust-split 0.1.3

A parser-based god-file splitter for Rust source.
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
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
//! Tier 2 step 2 — reassemble a planned split into output module files.
//!
//! Target: a **binary/crate-root** file (e.g. `src/main.rs`) whose items all
//! live in one module and reference each other by bare name. Splitting them
//! into sibling modules breaks those bare references, so the scheme is:
//!
//! - the crate root keeps the file preamble + imports, the source's own
//!   re-exports (`pub use ...` — dropping or demoting one would narrow the
//!   crate's public API) and content-less `mod name;` declarations verbatim,
//!   declares each part module, re-exports each part with a single glob whose
//!   visibility matches the part's widest item (`pub use` when the part has a
//!   public item, else `pub(crate) use`, and nothing for an `impl`-only part),
//!   and keeps `fn main` (the entry point must stay at the root);
//! - each part file copies the imports it references by name (preamble stays at
//!   the root), does `use crate::*` to see its siblings via the root re-exports,
//!   and carries its items with `pub(crate)` visibility bumped on so the
//!   re-exports can see them;
//! - a body-carrying `mod` (e.g. the test module) of **any size** is extracted
//!   whole to its own file — its attributes (`#[cfg(test)]` must keep gating
//!   it) and visibility travel to the root declaration, and its `super::*`
//!   keeps pointing at the root; one over the ceiling is split further into a
//!   `{name}/` subdirectory.
//!
//! Residual import/visibility that this mechanical scheme misses is left for the
//! compiler to enumerate (the documented O(n) finish) — but the LOC budget and
//! the byte-exact moves are done here.

use crate::{Exploded, SplitPlan, plan_split};
use syn::spanned::Spanned;

/// Per-part overhead beyond the imports: the `use crate::*;` sibling glob plus
/// blank-line separators.
const PART_OVERHEAD: usize = 3;

/// Plan and reassemble a binary crate-root split so that **every output file is
/// `< max_loc`**. The item budget reserves the full header LOC and the per-part
/// overhead; since a part now copies only the imports it references (a subset of
/// the header), this reservation is conservative — a packed part stays safely
/// under budget.
pub fn split_bin(exploded: &Exploded, max_loc: usize, root_stem: &str) -> SplitOutput {
    let header_loc: usize = exploded
        .manifest
        .rows
        .iter()
        .filter(|r| matches!(r.kind.as_str(), "use" | "preamble" | "extern_crate"))
        .map(|r| r.loc)
        .sum();
    let item_budget = max_loc.saturating_sub(header_loc + PART_OVERHEAD).max(1);
    let plan = plan_split(exploded, item_budget);
    reassemble_bin(exploded, &plan, root_stem, max_loc)
}

/// A file the split would write.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OutputFile {
    /// Path relative to the source file's directory (e.g. `main.rs`, `p00.rs`).
    pub path: String,
    pub contents: String,
    pub loc: usize,
}

/// The reassembled output plus the parts of the plan that could not be met.
#[derive(Debug, Clone)]
pub struct SplitOutput {
    pub files: Vec<OutputFile>,
    /// Names of items still at or above budget (e.g. an un-nested test mod).
    pub still_oversized: Vec<String>,
}

impl SplitOutput {
    /// The largest output file's LOC (the budget is met iff this is `< max_loc`
    /// and `still_oversized` is empty).
    pub fn max_loc(&self) -> usize {
        self.files.iter().map(|f| f.loc).max().unwrap_or(0)
    }
}

fn loc(text: &str) -> usize {
    if text.is_empty() {
        0
    } else {
        text.lines().count().max(1)
    }
}

/// How the split file sits in the module tree — fixes the sibling path prefix
/// and where sub-module files go. Re-export visibility is per part in both
/// topologies: `pub use` when the part has a public item (preserving the
/// crate's public API), else `pub(crate) use`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Topology {
    /// A binary or library crate root (`main.rs`, `lib.rs`): siblings reached
    /// via `crate::`, `fn main` (if any) kept at the root.
    Bin,
    /// A nested library module (`foo/mod.rs`, or a plain `foo.rs` file module):
    /// sub-modules reached via `super::` and re-exported with a single per-module
    /// glob — `pub use` to preserve a public API, else `pub(crate) use`. A plain
    /// `foo.rs` file module resolves `mod bar;` to `foo/bar.rs`, so its
    /// sub-modules are written into a `foo/` subdir.
    Mod,
}

/// Plan and reassemble a library module so every output file is `< max_loc`;
/// sub-modules see each other via `super::*`. Handles both a directory-owning
/// `foo/mod.rs` (sub-modules become siblings) and a plain `foo.rs` file module
/// (sub-modules go in a `foo/` subdir). `root_stem` is the source file's stem.
pub fn split_mod(exploded: &Exploded, max_loc: usize, root_stem: &str) -> SplitOutput {
    let header_loc: usize = exploded
        .manifest
        .rows
        .iter()
        .filter(|r| matches!(r.kind.as_str(), "use" | "preamble" | "extern_crate"))
        .map(|r| r.loc)
        .sum();
    let item_budget = max_loc.saturating_sub(header_loc + PART_OVERHEAD).max(1);
    let plan = plan_split(exploded, item_budget);
    reassemble(exploded, &plan, root_stem, Topology::Mod, max_loc)
}

/// Reassemble a binary crate-root split (back-compat wrapper).
pub fn reassemble_bin(
    exploded: &Exploded,
    plan: &SplitPlan,
    root_stem: &str,
    max_loc: usize,
) -> SplitOutput {
    reassemble(exploded, plan, root_stem, Topology::Bin, max_loc)
}

/// Reassemble a split for the given module topology. `root_stem` is the source
/// file's stem (`"main"` for `main.rs`, `"mod"` for `foo/mod.rs`). `max_loc` is
/// the ceiling, needed to recursively split an oversized test module.
fn reassemble(
    exploded: &Exploded,
    plan: &SplitPlan,
    root_stem: &str,
    topology: Topology,
    max_loc: usize,
) -> SplitOutput {
    let sibling = match topology {
        Topology::Bin => "crate",
        Topology::Mod => "super",
    };
    let chunk_text = |i: usize| exploded.chunks[i].text.as_str();
    let row = |i: usize| {
        exploded
            .manifest
            .rows
            .iter()
            .find(|r| r.chunk_index == i)
            .unwrap()
    };

    // Where sub-module files go. A directory-owning module file
    // (`main.rs`/`lib.rs`/`foo/mod.rs`) keeps them as siblings; a plain `foo.rs`
    // file module resolves `mod bar;` to `foo/bar.rs`, so its parts go in `foo/`.
    let sub_prefix = match topology {
        Topology::Bin => String::new(),
        Topology::Mod if matches!(root_stem, "mod" | "lib" | "main") => String::new(),
        Topology::Mod => format!("{root_stem}/"),
    };

    // The crate/module preamble (inner `//!` docs / `#![...]` attrs) stays at
    // the root only — a crate-root `#![feature]` is a hard error in a sub-module
    // file, and a crate-root `#![allow]` already covers descendants. The import
    // chunks (`use`/`extern crate`) are copied into each file, but only the ones
    // that file references by name (see `select_imports`). Re-exports
    // (`pub use ...`) are not imports — the planner routes them to
    // `plan.root_items`, kept at the root verbatim.
    let preamble: String = plan
        .header
        .iter()
        .filter(|&&i| row(i).kind == "preamble")
        .map(|&i| chunk_text(i))
        .collect();
    let import_chunks: Vec<usize> = plan
        .header
        .iter()
        .copied()
        .filter(|&i| row(i).kind != "preamble")
        .collect();

    // Source chunks that stay at the root verbatim: `pub use` re-exports (the
    // crate's public surface) and content-less `mod name;` declarations (which
    // bind files relative to the root's directory).
    let root_kept: String = plan.root_items.iter().map(|&i| chunk_text(i)).collect();

    // Module names fixed by the source — extracted body-mods and `mod name;`
    // declarations keep their own names — plus the root's stem; a generated
    // part that would collide is renamed with a `_` suffix.
    let mut reserved: std::collections::BTreeSet<&str> =
        plan.mods.iter().map(|&i| row(i).name.as_str()).collect();
    reserved.insert(root_stem);
    for &i in &plan.root_items {
        if row(i).kind == "mod" {
            reserved.insert(row(i).name.as_str());
        }
    }

    let mut files = Vec::new();
    let mut mod_decls = String::new();
    let mut reexports = String::new();
    let mut still_oversized = Vec::new();
    // Names referenced from the root file itself (`fn main`, extracted module
    // bodies whose `use super::*` reaches the root's imports).
    let mut root_refs = Refs::default();

    // Part modules, named after their cluster's dominant item.
    for part in &plan.parts {
        let module = if reserved.contains(part.name.as_str()) {
            format!("{}_", part.name)
        } else {
            part.name.clone()
        };
        let mut body = String::new();
        let mut root_main = None;
        // Widest visibility any moved item contributes to a glob re-export.
        let mut export_vis = ExportVis::None;
        // Names this part references, so only the imports it uses are copied in.
        let mut refs = Refs::default();
        for &i in &part.chunk_indices {
            let r = row(i);
            // `fn main` must stay at the crate root, not move into a submodule.
            if r.kind == "fn" && r.name == "main" {
                root_main = Some(i);
                continue;
            }
            export_vis = export_vis.max(item_export_vis(chunk_text(i)));
            refs.add(chunk_text(i));
            body.push_str(&bump_visibility(chunk_text(i)));
        }
        // If the part was only `fn main`, it produced no module file.
        if body.trim().is_empty() {
            if let Some(i) = root_main {
                // stash main to emit at root via a sentinel part with no module
                files.push(OutputFile {
                    path: String::from("__root_main__"),
                    contents: chunk_text(i).to_owned(),
                    loc: 0,
                });
            }
            continue;
        }
        if let Some(i) = root_main {
            files.push(OutputFile {
                path: String::from("__root_main__"),
                contents: chunk_text(i).to_owned(),
                loc: 0,
            });
        }
        let part_imports = select_imports(&import_chunks, &exploded.chunks, &refs);
        let contents = part_file(&part_imports, sibling, &body);
        mod_decls.push_str(&format!("mod {module};\n"));
        // One glob re-export per module, visibility chosen by the module's widest
        // item: `pub use` when it has a public item (a `pub use *` caps each item
        // at its own visibility, so it covers internal `pub(crate)` items in the
        // same line); else `pub(crate) use`; and nothing when the module exposes
        // no nameable item (e.g. a bare `impl` — a glob re-export would only warn
        // "doesn't reexport anything"). This keeps the crate's public surface
        // (`pub use`) reachable and avoids the redundant double re-export.
        if let Some(line) = reexport_line(export_vis, &module) {
            reexports.push_str(&line);
        }
        let l = loc(&contents);
        files.push(OutputFile {
            path: format!("{sub_prefix}{module}.rs"),
            contents,
            loc: l,
        });
    }

    // Body-carrying mods are extracted whole, whatever their size: packing a
    // `#[cfg(test)] mod tests { ... }` into a cluster would nest it inside a
    // part module and leave the root declaration ungated. The declaration —
    // leading comments, attributes, visibility — travels to the root; the
    // unwrapped body becomes the module's file, split further into a `{name}/`
    // subdir when it is itself over the ceiling.
    for &mod_index in &plan.mods {
        let chunk = chunk_text(mod_index);
        let name = row(mod_index).name.as_str();
        let Some((decl, inner)) = extract_mod(chunk) else {
            // Should not happen (the planner classified it by parsing); keep
            // the chunk intact at the root rather than lose it.
            mod_decls.push_str(chunk);
            continue;
        };
        mod_decls.push_str(&decl);
        // The body's `use super::*;` reaches the root's imports, so the root
        // must keep the imports the body names.
        root_refs.add_source(&inner);
        let inner_loc = loc(&inner);
        if inner_loc < max_loc {
            files.push(OutputFile {
                path: format!("{sub_prefix}{name}.rs"),
                contents: inner,
                loc: inner_loc,
            });
        } else {
            let (nested, nested_still) = split_nested_mod(name, &inner, max_loc);
            files.extend(nested.into_iter().map(|mut f| {
                f.path = format!("{sub_prefix}{}", f.path);
                f
            }));
            still_oversized.extend(nested_still);
        }
    }

    // Oversized leaves can't be moved mechanically.
    for over in &plan.oversized {
        still_oversized.push(format!(
            "{} ({} LOC {}, manual extraction)",
            over.name, over.loc, over.kind
        ));
    }

    // Pull the stashed `fn main` (if any) and build the root file.
    let mut root_main = String::new();
    files.retain(|f| {
        if f.path == "__root_main__" {
            root_main = f.contents.clone();
            false
        } else {
            true
        }
    });

    // The root keeps the preamble, then only the imports its own retained code
    // references — `fn main` (if any) plus extracted module bodies, whose
    // `use super::*;` resolves against the root. A root that is just module
    // declarations and re-exports needs no imports at all.
    if !root_main.trim().is_empty() {
        root_refs.add(&root_main);
    }
    let root_imports = if root_refs.is_empty() {
        String::new()
    } else {
        select_imports(&import_chunks, &exploded.chunks, &root_refs)
    };

    let mut root = String::new();
    root.push_str(&preamble);
    root.push_str(&root_imports);
    root.push_str(&root_kept);
    root.push('\n');
    root.push_str(&mod_decls);
    root.push('\n');
    root.push_str(&reexports);
    if !root_main.is_empty() {
        root.push('\n');
        root.push_str(&root_main);
    }
    let root_loc = loc(&root);
    files.insert(
        0,
        OutputFile {
            path: format!("{root_stem}.rs"),
            contents: root,
            loc: root_loc,
        },
    );

    SplitOutput {
        files,
        still_oversized,
    }
}

/// Raise a moved item — and the struct fields / impl members referenced across
/// the new module boundaries — to `pub(crate)`, so the crate-root re-exports can
/// see them. Span-driven (parse the chunk, insert at exact offsets), so it is
/// attribute-safe and handles `fn` modifiers, multi-line attrs, etc. Items
/// already `pub`/`pub(crate)` are left alone. Over-exposes within the crate,
/// which is the mechanical, behavior-preserving choice.
fn bump_visibility(chunk_text: &str) -> String {
    let Ok(item) = syn::parse_str::<syn::Item>(chunk_text) else {
        return chunk_text.to_owned();
    };
    let mut offsets = Vec::new();
    collect_vis_offsets(&item, &mut offsets);
    apply_inserts(chunk_text, &offsets)
}

fn is_inherited(vis: &syn::Visibility) -> bool {
    matches!(vis, syn::Visibility::Inherited)
}

fn start<T: Spanned>(node: &T) -> usize {
    node.span().byte_range().start
}

/// Byte offset where a function's visibility belongs: before any
/// `const`/`async`/`unsafe`/`extern` modifier, else before `fn`.
fn fn_sig_start(sig: &syn::Signature) -> usize {
    let mut min = start(&sig.fn_token);
    if let Some(t) = &sig.constness {
        min = min.min(start(t));
    }
    if let Some(t) = &sig.asyncness {
        min = min.min(start(t));
    }
    if let Some(t) = &sig.unsafety {
        min = min.min(start(t));
    }
    if let Some(abi) = &sig.abi {
        min = min.min(start(&abi.extern_token));
    }
    min
}

fn field_offsets(fields: &syn::Fields, offsets: &mut Vec<usize>) {
    for field in fields {
        if is_inherited(&field.vis) {
            match &field.ident {
                Some(ident) => offsets.push(start(ident)),
                None => offsets.push(start(&field.ty)),
            }
        }
    }
}

fn collect_vis_offsets(item: &syn::Item, offsets: &mut Vec<usize>) {
    use syn::Item;
    match item {
        Item::Fn(f) => {
            if is_inherited(&f.vis) {
                offsets.push(fn_sig_start(&f.sig));
            }
        }
        Item::Struct(s) => {
            if is_inherited(&s.vis) {
                offsets.push(start(&s.struct_token));
            }
            field_offsets(&s.fields, offsets);
        }
        Item::Enum(e) => {
            if is_inherited(&e.vis) {
                offsets.push(start(&e.enum_token));
            }
        }
        Item::Union(u) => {
            if is_inherited(&u.vis) {
                offsets.push(start(&u.union_token));
            }
            field_offsets(&syn::Fields::Named(u.fields.clone()), offsets);
        }
        Item::Const(c) if is_inherited(&c.vis) => offsets.push(start(&c.const_token)),
        Item::Static(s) if is_inherited(&s.vis) => offsets.push(start(&s.static_token)),
        Item::Type(t) if is_inherited(&t.vis) => offsets.push(start(&t.type_token)),
        Item::Trait(t) if is_inherited(&t.vis) => offsets.push(start(&t.trait_token)),
        Item::TraitAlias(t) if is_inherited(&t.vis) => offsets.push(start(&t.trait_token)),
        // Only inherent impls (`impl Type`) allow member visibility; trait-impl
        // members (`impl Trait for Type`) inherit the trait's and must not.
        Item::Impl(i) if i.trait_.is_none() => {
            for member in &i.items {
                match member {
                    syn::ImplItem::Fn(f) if is_inherited(&f.vis) => {
                        offsets.push(fn_sig_start(&f.sig))
                    }
                    syn::ImplItem::Const(c) if is_inherited(&c.vis) => {
                        offsets.push(start(&c.const_token))
                    }
                    syn::ImplItem::Type(t) if is_inherited(&t.vis) => {
                        offsets.push(start(&t.type_token))
                    }
                    _ => {}
                }
            }
        }
        _ => {}
    }
}

fn apply_inserts(text: &str, offsets: &[usize]) -> String {
    let mut offsets: Vec<usize> = offsets.to_vec();
    offsets.sort_unstable();
    offsets.dedup();
    let mut out = String::with_capacity(text.len() + offsets.len() * 11);
    let mut prev = 0;
    for &offset in &offsets {
        out.push_str(&text[prev..offset]);
        out.push_str("pub(crate) ");
        prev = offset;
    }
    out.push_str(&text[prev..]);
    out
}

/// Assemble a part file: its selected imports, the sibling glob so it can reach
/// the rest of the module via the root re-exports, then the moved items.
fn part_file(imports: &str, sibling: &str, body: &str) -> String {
    if imports.trim().is_empty() {
        format!("use {sibling}::*;\n\n{body}")
    } else {
        format!("{imports}\nuse {sibling}::*;\n\n{body}")
    }
}

/// The glob re-export line for a module given the widest visibility of its
/// items — or `None` when it exposes nothing nameable (re-exporting an
/// `impl`-only module would only warn).
fn reexport_line(vis: ExportVis, module: &str) -> Option<String> {
    match vis {
        ExportVis::None => None,
        ExportVis::Crate => Some(format!("pub(crate) use {module}::*;\n")),
        ExportVis::Pub => Some(format!("pub use {module}::*;\n")),
    }
}

/// What a moved item contributes to its module's glob re-export. Ordered so the
/// widest contribution across a module's items picks the re-export visibility.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum ExportVis {
    /// No nameable export (a bare `impl`, a macro invocation, parse failure).
    None,
    /// A crate-visible name: a private item (bumped to `pub(crate)`), or one
    /// already `pub(crate)`/`pub(super)`/`pub(in …)`.
    Crate,
    /// A fully public name — part of the crate/module's public surface.
    Pub,
}

/// Classify one chunk's contribution to its module's glob re-export, mirroring
/// `bump_visibility`: items it raises to `pub(crate)` count as crate-visible;
/// `mod`/`use` are not raised, so a private one is invisible to the re-export.
fn item_export_vis(chunk_text: &str) -> ExportVis {
    use syn::{Item, Visibility};
    let Ok(item) = syn::parse_str::<syn::Item>(chunk_text) else {
        // Unparseable: bump_visibility also left it private, so a glob re-export
        // could not see it either — contribute nothing.
        return ExportVis::None;
    };
    let (vis, bumped) = match &item {
        Item::Fn(f) => (&f.vis, true),
        Item::Struct(s) => (&s.vis, true),
        Item::Enum(e) => (&e.vis, true),
        Item::Const(c) => (&c.vis, true),
        Item::Static(s) => (&s.vis, true),
        Item::Trait(t) => (&t.vis, true),
        Item::TraitAlias(t) => (&t.vis, true),
        Item::Type(t) => (&t.vis, true),
        Item::Union(u) => (&u.vis, true),
        Item::Mod(m) => (&m.vis, false),
        Item::Use(u) => (&u.vis, false),
        // impl / macro / foreign_mod / extern_crate / verbatim: nothing nameable.
        _ => return ExportVis::None,
    };
    match vis {
        Visibility::Public(_) => ExportVis::Pub,
        Visibility::Restricted(_) => ExportVis::Crate,
        Visibility::Inherited if bumped => ExportVis::Crate,
        Visibility::Inherited => ExportVis::None,
    }
}

/// The identifiers a set of moved items references — the basis for copying only
/// the imports they use. An item that does not re-parse flips `keep_all`, so the
/// caller falls back to copying every import rather than dropping a needed one.
#[derive(Default)]
struct Refs {
    names: std::collections::BTreeSet<String>,
    keep_all: bool,
}

impl Refs {
    fn add(&mut self, chunk_text: &str) {
        match crate::referenced_idents(chunk_text) {
            Some(names) => self.names.extend(names),
            None => self.keep_all = true,
        }
    }

    /// Add every identifier a multi-item source fragment (an extracted module
    /// body) references.
    fn add_source(&mut self, src: &str) {
        match crate::referenced_idents_in_source(src) {
            Some(names) => self.names.extend(names),
            None => self.keep_all = true,
        }
    }

    /// True when nothing was added — no import can be needed.
    fn is_empty(&self) -> bool {
        self.names.is_empty() && !self.keep_all
    }

    /// Whether an import providing `names` should be copied in. A name-less
    /// import (`None`: a `*` glob or `as _`) is always kept, since its usage
    /// can't be detected by name.
    fn keeps(&self, provided: &Option<std::collections::BTreeSet<String>>) -> bool {
        match provided {
            None => true,
            Some(names) => self.keep_all || names.iter().any(|n| self.names.contains(n)),
        }
    }
}

/// Concatenate, in source order, the import chunks referenced by `refs` (plus
/// name-less imports like `*` globs and `as _`, always kept). This is the
/// aggressive policy: an import whose every name is unreferenced is dropped —
/// including an extension trait used only via its methods, whose `use` the
/// compiler will then ask to be re-added.
fn select_imports(import_chunks: &[usize], chunks: &[crate::Chunk], refs: &Refs) -> String {
    let mut out = String::new();
    for &i in import_chunks {
        let text = chunks[i].text.as_str();
        if refs.keeps(&import_provided_names(text)) {
            out.push_str(text);
        }
    }
    out
}

/// The names a `use`/`extern crate` chunk introduces, or `None` when it exposes
/// nothing referenceable by name — a `*` glob or an `as _` import — which is
/// then kept in every file rather than dropped.
fn import_provided_names(chunk_text: &str) -> Option<std::collections::BTreeSet<String>> {
    match syn::parse_str::<syn::Item>(chunk_text).ok()? {
        syn::Item::Use(u) => {
            let mut names = std::collections::BTreeSet::new();
            let mut name_less = false;
            collect_use_names(&u.tree, &mut names, &mut name_less);
            if name_less { None } else { Some(names) }
        }
        syn::Item::ExternCrate(c) => {
            let name = c
                .rename
                .map(|(_, id)| id.to_string())
                .unwrap_or_else(|| c.ident.to_string());
            Some(std::collections::BTreeSet::from([name]))
        }
        // An unparseable header chunk has no detectable name -> keep it.
        _ => None,
    }
}

/// Collect the bound names a `use` tree introduces. `name_less` is set for a
/// `*` glob or an `as _` rename, which bind no referenceable name.
fn collect_use_names(
    tree: &syn::UseTree,
    names: &mut std::collections::BTreeSet<String>,
    name_less: &mut bool,
) {
    match tree {
        syn::UseTree::Path(p) => collect_use_names(&p.tree, names, name_less),
        syn::UseTree::Name(n) => {
            names.insert(n.ident.to_string());
        }
        syn::UseTree::Rename(r) => {
            if r.rename == "_" {
                *name_less = true;
            } else {
                names.insert(r.rename.to_string());
            }
        }
        syn::UseTree::Glob(_) => *name_less = true,
        syn::UseTree::Group(g) => {
            for item in &g.items {
                collect_use_names(item, names, name_less);
            }
        }
    }
}

/// Split a `mod NAME { ... }` chunk into the root-side declaration and the
/// unwrapped inner body for the extracted file. The declaration is everything
/// up to the mod's identifier — leading comments, attributes (a `#[cfg(test)]`
/// gate must keep gating the declaration), and visibility (`pub mod` stays
/// `pub mod`) — closed with `;`. Span-driven on the re-parsed chunk, so it is
/// exact where the old line-based scan dropped the visibility. `None` when the
/// chunk does not re-parse as a body-carrying mod.
fn extract_mod(chunk_text: &str) -> Option<(String, String)> {
    let Ok(syn::Item::Mod(item)) = syn::parse_str::<syn::Item>(chunk_text) else {
        return None;
    };
    let (brace, _) = item.content.as_ref()?;
    let ident_end = item.ident.span().byte_range().end;
    let decl = format!("{};\n", &chunk_text[..ident_end]);

    let open_end = brace.span.open().byte_range().end;
    let close_start = brace.span.close().byte_range().start;
    let inner = &chunk_text[open_end..close_start];
    // Drop the newline that followed `{` and the closing brace's indentation.
    let inner = inner.strip_prefix('\n').unwrap_or(inner);
    let mut inner = inner.trim_end_matches([' ', '\t']).to_owned();
    if !inner.is_empty() && !inner.ends_with('\n') {
        inner.push('\n');
    }
    Some((decl, inner))
}

/// Recursively split an over-budget module's inner body into a `{name}/`
/// subdirectory: `{name}/mod.rs` forwards the enclosing module's items
/// (`pub(crate) use super::*`), keeps the body's own re-exports and `mod`
/// declarations verbatim, and re-exports the clusters; each `{name}/gNN.rs`
/// holds a cohesive cluster and reaches everything via `super::*`. A nested
/// body-carrying mod is extracted whole (attributes and visibility on its
/// declaration), recursing when it is itself over the ceiling. Used for big
/// test modules.
fn split_nested_mod(name: &str, inner: &str, max_loc: usize) -> (Vec<OutputFile>, Vec<String>) {
    let Ok(exploded) = crate::explode(inner) else {
        return (
            vec![OutputFile {
                path: format!("{name}.rs"),
                contents: inner.to_owned(),
                loc: loc(inner),
            }],
            vec![format!("{name} (could not parse for nested split)")],
        );
    };
    let row = |i: usize| {
        exploded
            .manifest
            .rows
            .iter()
            .find(|r| r.chunk_index == i)
            .unwrap()
    };

    // Budget from a conservative header estimate (every use/preamble/extern
    // chunk), then plan once. The copied group header is the plan's header —
    // the module's own plain imports — minus `use super::*` (the parent glob,
    // which `{name}/mod.rs` forwards instead). Re-exports and `mod`
    // declarations are in `root_items`, kept in `{name}/mod.rs`; a nested
    // `mod x;` still resolves to `{name}/x.rs` after the move.
    let header_estimate: usize = exploded
        .manifest
        .rows
        .iter()
        .filter(|r| matches!(r.kind.as_str(), "use" | "preamble" | "extern_crate"))
        .map(|r| r.loc)
        .sum();
    let item_budget = max_loc
        .saturating_sub(header_estimate + PART_OVERHEAD)
        .max(1);
    let plan = plan_split(&exploded, item_budget);
    let is_super_glob = |t: &str| t.replace(' ', "").contains("usesuper::*;");
    let group_header: String = plan
        .header
        .iter()
        .map(|&i| exploded.chunks[i].text.as_str())
        .filter(|t| !is_super_glob(t))
        .collect();

    let mut files = Vec::new();
    let mut decls = String::new();
    let mut reexports = String::new();
    let mut still = Vec::new();
    for (idx, part) in plan.parts.iter().enumerate() {
        let module = format!("g{idx:02}");
        let mut body = String::new();
        for &ci in &part.chunk_indices {
            body.push_str(&bump_visibility(exploded.chunks[ci].text.as_str()));
        }
        let contents = format!("{group_header}\nuse super::*;\n\n{body}");
        files.push(OutputFile {
            path: format!("{name}/{module}.rs"),
            loc: loc(&contents),
            contents,
        });
        decls.push_str(&format!("mod {module};\n"));
        reexports.push_str(&format!("pub(crate) use {module}::*;\n"));
    }
    for &mod_index in &plan.mods {
        let chunk = exploded.chunks[mod_index].text.as_str();
        let mod_name = row(mod_index).name.as_str();
        let Some((decl, mod_inner)) = extract_mod(chunk) else {
            decls.push_str(chunk);
            continue;
        };
        decls.push_str(&decl);
        let mod_loc = loc(&mod_inner);
        if mod_loc < max_loc {
            files.push(OutputFile {
                path: format!("{name}/{mod_name}.rs"),
                contents: mod_inner,
                loc: mod_loc,
            });
        } else {
            let (nested, nested_still) = split_nested_mod(mod_name, &mod_inner, max_loc);
            files.extend(nested.into_iter().map(|mut f| {
                f.path = format!("{name}/{}", f.path);
                f
            }));
            still.extend(
                nested_still
                    .into_iter()
                    .map(|message| format!("{name}::{message}")),
            );
        }
    }
    for over in &plan.oversized {
        still.push(format!(
            "{name}::{} ({} LOC {}, leaf needs manual extraction)",
            over.name, over.loc, over.kind
        ));
    }

    let root_kept: String = plan
        .root_items
        .iter()
        .map(|&i| exploded.chunks[i].text.as_str())
        .collect();
    let modrs = format!("pub(crate) use super::*;\n\n{root_kept}{decls}\n{reexports}");
    files.insert(
        0,
        OutputFile {
            path: format!("{name}/mod.rs"),
            loc: loc(&modrs),
            contents: modrs,
        },
    );
    (files, still)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{explode, plan_split};

    #[test]
    fn splits_a_flat_bin_root_into_cohesive_under_budget_modules() {
        // four cohesive groups (g{k}_0 -> g{k}_1 -> g{k}_2 -> g{k}_3); main calls g0_0
        let mut src = String::from("use std::fmt;\n\n");
        for k in 0..4 {
            for n in 0..4 {
                let call = if n < 3 {
                    format!("    g{k}_{}();\n", n + 1)
                } else {
                    String::new()
                };
                src.push_str(&format!("fn g{k}_{n}() {{\n{call}}}\n\n"));
            }
        }
        src.push_str("fn main() {\n    g0_0();\n}\n");
        let exploded = explode(&src).unwrap();
        let max_loc = 60;
        let out = split_bin(&exploded, max_loc, "main");

        assert!(out.still_oversized.is_empty());
        for f in &out.files {
            assert!(f.loc < max_loc, "{} over budget: {}", f.path, f.loc);
        }
        let root = out.files.iter().find(|f| f.path == "main.rs").unwrap();
        assert!(root.contents.contains("fn main"), "main stays at root");
        assert!(root.contents.contains("pub(crate) use "));
        let part = out.files.iter().find(|f| f.path != "main.rs").unwrap();
        assert!(part.contents.contains("use crate::*;"));
        assert!(part.contents.contains("pub(crate) fn "));
        // cohesion: the whole g0 group lands in ONE module
        let g0 = out
            .files
            .iter()
            .find(|f| f.contents.contains("fn g0_1"))
            .unwrap();
        for n in 0..4 {
            assert!(
                g0.contents.contains(&format!("fn g0_{n}")),
                "g0 group together"
            );
        }
    }

    #[test]
    fn oversized_mod_is_extracted_to_its_own_file() {
        let mut inner = String::new();
        for i in 0..10 {
            inner.push_str(&format!("    fn t{i}() {{}}\n"));
        }
        let src = format!("fn main() {{}}\n\n#[cfg(test)]\nmod tests {{\n{inner}}}\n");
        let exploded = explode(&src).unwrap();
        let plan = plan_split(&exploded, 6);
        // ceiling large enough that the test mod fits whole -> single tests.rs
        let out = reassemble_bin(&exploded, &plan, "main", 1000);
        let tests = out.files.iter().find(|f| f.path == "tests.rs").unwrap();
        assert!(tests.contents.contains("fn t0()"));
        assert!(!tests.contents.contains("mod tests"));
        let root = out.files.iter().find(|f| f.path == "main.rs").unwrap();
        assert!(root.contents.contains("#[cfg(test)]\nmod tests;"));
    }

    #[test]
    fn an_over_ceiling_test_mod_is_nested_into_a_subdir() {
        // 30 test fns referencing a shared helper -> test mod far over a tiny ceiling
        let mut inner =
            String::from("    use super::*;\n\n    fn helper() -> i32 {\n        1\n    }\n");
        for i in 0..30 {
            inner.push_str(&format!(
                "\n    #[test]\n    fn t{i}() {{\n        assert_eq!(helper(), 1);\n    }}\n"
            ));
        }
        let src = format!(
            "pub fn helper() -> i32 {{\n    1\n}}\n\nfn main() {{}}\n\n#[cfg(test)]\nmod tests {{\n{inner}}}\n"
        );
        let exploded = explode(&src).unwrap();
        let out = split_bin(&exploded, 60, "main");

        // the test mod became a `tests/` subdir, every file under the ceiling
        let mod_rs = out.files.iter().find(|f| f.path == "tests/mod.rs").unwrap();
        assert!(
            mod_rs.contents.contains("pub(crate) use super::*;"),
            "forwards the parent"
        );
        assert!(mod_rs.contents.contains("mod g00;"));
        assert!(out.files.iter().any(|f| f.path == "tests/g00.rs"));
        for f in &out.files {
            assert!(f.loc < 60, "{} over ceiling: {}", f.path, f.loc);
        }
        let root = out.files.iter().find(|f| f.path == "main.rs").unwrap();
        assert!(root.contents.contains("#[cfg(test)]\nmod tests;"));
    }

    #[test]
    fn split_mod_uses_super_and_preserves_pub_api() {
        // alpha (pub, the module's API) calls beta (private helper) -> one cluster
        let src = "use std::fmt;\n\npub fn alpha() -> i32 {\n    beta()\n}\n\nfn beta() -> i32 {\n    1\n}\n";
        let exploded = explode(src).unwrap();
        let out = split_mod(&exploded, 10_000, "mod");

        let root = out.files.iter().find(|f| f.path == "mod.rs").unwrap();
        assert!(
            root.contents.contains("pub use "),
            "pub re-export preserves the API"
        );
        assert!(
            !root.contents.contains("pub(crate) use "),
            "a single `pub use *` caps each item at its own visibility — no \
             redundant second `pub(crate) use` line"
        );

        let sub = out.files.iter().find(|f| f.path != "mod.rs").unwrap();
        assert!(
            sub.contents.contains("use super::*;"),
            "siblings reached via super, not crate"
        );
        assert!(!sub.contents.contains("use crate::*;"));
        assert!(sub.contents.contains("pub fn alpha"), "pub item stays pub");
        assert!(
            sub.contents.contains("pub(crate) fn beta"),
            "private bumped to pub(crate)"
        );
    }

    // ----- issue 1: a plain `foo.rs` file module places sub-modules in `foo/` ---

    #[test]
    fn file_module_places_submodules_in_a_subdir() {
        // A plain `foo.rs` file module (stem != "mod"): `mod bar;` in it resolves
        // to `foo/bar.rs`, so parts must be written under a `foo/` subdir, not as
        // siblings of `foo.rs` (which would not compile — E0583).
        let mut src = String::new();
        for k in 0..3 {
            // three items that reference nothing -> three separate parts
            src.push_str(&format!("pub fn item{k}() -> i32 {{\n    {k}\n}}\n\n"));
        }
        let exploded = explode(&src).unwrap();
        let out = split_mod(&exploded, 10_000, "wstest");

        let root = out.files.iter().find(|f| f.path == "wstest.rs").unwrap();
        assert!(
            root.contents.contains("mod item0;"),
            "root file-module declares the sub-modules"
        );
        let subs: Vec<&str> = out
            .files
            .iter()
            .map(|f| f.path.as_str())
            .filter(|p| *p != "wstest.rs")
            .collect();
        assert!(!subs.is_empty(), "produced sub-module files");
        for path in &subs {
            assert!(
                path.starts_with("wstest/"),
                "sub-module {path} must live under wstest/ (file-module subdir)"
            );
        }
    }

    #[test]
    fn mod_rs_keeps_submodules_as_siblings() {
        // The `foo/mod.rs` case (stem == "mod"): sub-modules stay siblings, no subdir.
        let mut src = String::new();
        for k in 0..3 {
            src.push_str(&format!("pub fn item{k}() -> i32 {{\n    {k}\n}}\n\n"));
        }
        let exploded = explode(&src).unwrap();
        let out = split_mod(&exploded, 10_000, "mod");
        for f in &out.files {
            assert!(
                !f.path.contains('/'),
                "mod.rs sub-modules are siblings, not in a subdir: {}",
                f.path
            );
        }
    }

    // ----- issue 2: per-module pub vs pub(crate) vs no re-export decision -------

    #[test]
    fn private_only_module_reexports_pub_crate_not_pub() {
        // No `pub` item: `pub use *` would warn "nothing public enough", so the
        // re-export must be `pub(crate) use`.
        let src = "fn helper() -> i32 {\n    leaf()\n}\n\nfn leaf() -> i32 {\n    1\n}\n";
        let exploded = explode(src).unwrap();
        let out = split_mod(&exploded, 10_000, "mod");
        let root = out.files.iter().find(|f| f.path == "mod.rs").unwrap();
        assert!(
            root.contents.contains("pub(crate) use "),
            "all-private module re-exports pub(crate):\n{}",
            root.contents
        );
        assert!(
            !root.contents.contains("pub use "),
            "no `pub use` for a module with no public item"
        );
    }

    #[test]
    fn impl_only_module_is_declared_but_not_reexported() {
        // `api` is a normal part; the bare impl references no sibling, so it
        // clusters alone with nothing nameable -> declared, but no glob re-export
        // (re-exporting it would only warn "doesn't reexport anything").
        let src = "pub fn api() -> i32 {\n    1\n}\n\nimpl Worker for External {\n    fn run(&self) {}\n}\n";
        let exploded = explode(src).unwrap();
        let out = split_mod(&exploded, 10_000, "mod");
        let root = out.files.iter().find(|f| f.path == "mod.rs").unwrap();

        // exactly one glob re-export line (for `api`) though two modules declared
        let reexports = root
            .contents
            .lines()
            .filter(|l| l.contains(" use ") && l.trim_end().ends_with("::*;"))
            .count();
        assert_eq!(
            reexports, 1,
            "only the nameable module is re-exported:\n{}",
            root.contents
        );
        assert!(root.contents.contains("pub use api::*;"));
        assert_eq!(
            root.contents.matches("mod ").count(),
            2,
            "both modules are still declared:\n{}",
            root.contents
        );
    }

    // ----- issue 3: crate-public entry fn is preserved as `pub use` -------------

    #[test]
    fn bin_public_entry_fn_is_reexported_pub_so_it_stays_crate_visible() {
        // A lib crate root where `run` is the public entry (the bin calls
        // `crate_name::run`). It must be re-exported `pub`, not `pub(crate)`, or
        // `crate_name::run` is no longer visible to main.rs after the split.
        let src = "fn helper() -> i32 {\n    1\n}\n\npub fn run() -> i32 {\n    helper()\n}\n";
        let exploded = explode(src).unwrap();
        let out = split_bin(&exploded, 10_000, "lib");

        let root = out.files.iter().find(|f| f.path == "lib.rs").unwrap();
        assert!(
            root.contents.contains("pub use "),
            "public `run` re-exported at pub keeps `crate::run` visible:\n{}",
            root.contents
        );
        assert!(
            !root.contents.contains("pub(crate) use "),
            "the module has a pub item, so one `pub use *` suffices (no double line)"
        );
    }

    // ----- preamble (inner `//!`/`#![…]`) stays at the root, not copied to parts -

    #[test]
    fn crate_preamble_stays_at_root_not_copied_into_parts() {
        // `#![allow]` / `//!` belong at the crate root (and `#![feature]` is a
        // hard error anywhere else); a crate-root attr already covers sub-modules.
        let src = "//! crate docs\n#![allow(dead_code)]\n\npub fn alpha() -> i32 {\n    beta()\n}\n\nfn beta() -> i32 {\n    1\n}\n";
        let exploded = explode(src).unwrap();
        let out = split_bin(&exploded, 10_000, "lib");

        let root = out.files.iter().find(|f| f.path == "lib.rs").unwrap();
        assert!(
            root.contents.contains("#![allow(dead_code)]"),
            "preamble stays at the root"
        );
        for f in &out.files {
            if f.path != "lib.rs" {
                assert!(
                    !f.contents.contains("#!["),
                    "part {} must not carry crate-level inner attrs",
                    f.path
                );
                assert!(
                    !f.contents.contains("//! crate docs"),
                    "part {} must not duplicate the crate docs",
                    f.path
                );
            }
        }
    }

    // ----- issue 3a: copy only the imports each file actually references -------

    #[test]
    fn parts_copy_only_the_imports_they_reference() {
        // alpha names `Display`; bravo names nothing from the header. Each part
        // gets only the imports it references.
        let src = "use std::fmt::Display;\nuse std::collections::HashMap;\n\npub fn alpha(d: &dyn Display) {\n    let _ = d;\n}\n\npub fn bravo() -> i32 {\n    1\n}\n";
        let exploded = explode(src).unwrap();
        let out = split_mod(&exploded, 10_000, "mod");

        let alpha = out
            .files
            .iter()
            .find(|f| f.contents.contains("fn alpha"))
            .unwrap();
        let bravo = out
            .files
            .iter()
            .find(|f| f.contents.contains("fn bravo"))
            .unwrap();
        assert!(
            alpha.contents.contains("use std::fmt::Display;"),
            "alpha references Display:\n{}",
            alpha.contents
        );
        assert!(
            !alpha.contents.contains("HashMap"),
            "alpha never names HashMap -> import dropped:\n{}",
            alpha.contents
        );
        assert!(
            !bravo.contents.contains("use std::fmt::Display;"),
            "bravo references nothing from the header:\n{}",
            bravo.contents
        );
        assert!(!bravo.contents.contains("HashMap"));
    }

    #[test]
    fn globs_and_anonymous_trait_imports_are_always_copied() {
        // `use ...::*` and `use Trait as _` expose no name to match, so every
        // part keeps them — the safe choice for a trait used only via methods.
        let src = "use std::fmt::Write as _;\nuse std::prelude::v1::*;\n\npub fn writes(s: &mut String) {\n    let _ = write!(s, \"x\");\n}\n\npub fn other() -> i32 {\n    2\n}\n";
        let exploded = explode(src).unwrap();
        let out = split_mod(&exploded, 10_000, "mod");
        for f in &out.files {
            if f.path == "mod.rs" {
                continue;
            }
            assert!(
                f.contents.contains("use std::fmt::Write as _;"),
                "{} must keep the `as _` trait import:\n{}",
                f.path,
                f.contents
            );
            assert!(
                f.contents.contains("use std::prelude::v1::*;"),
                "{} must keep the glob import:\n{}",
                f.path,
                f.contents
            );
        }
    }

    #[test]
    fn item_less_root_keeps_no_imports() {
        // A module root whose items all moved out is just decls + re-exports; it
        // needs no imports, while the part that uses one keeps it.
        let src = "use std::collections::HashMap;\n\npub fn solo(m: HashMap<u8, u8>) {\n    let _ = m;\n}\n";
        let exploded = explode(src).unwrap();
        let out = split_mod(&exploded, 10_000, "mod");

        let root = out.files.iter().find(|f| f.path == "mod.rs").unwrap();
        assert!(
            !root.contents.contains("use std::collections::HashMap;"),
            "item-less root drops imports it doesn't use:\n{}",
            root.contents
        );
        let part = out.files.iter().find(|f| f.path != "mod.rs").unwrap();
        assert!(
            part.contents.contains("use std::collections::HashMap;"),
            "the part that uses HashMap keeps it"
        );
    }

    // ----- razel regression 1: source re-exports must stay `pub use` at root --

    #[test]
    fn source_pub_use_reexports_stay_pub_use_at_the_root() {
        // The original file's `pub use` lines ARE the crate's public API.
        // Treating them as droppable header imports (or demoting them to
        // `pub(crate) use`) silently breaks every dependent's paths.
        let src = "mod helpers;\n\npub use helpers::Helper;\n\nuse std::fmt::Display;\n\n\
                   pub fn api(d: &dyn Display) {\n    let _ = d;\n}\n";
        let exploded = explode(src).unwrap();
        let out = split_bin(&exploded, 10_000, "lib");

        let root = out.files.iter().find(|f| f.path == "lib.rs").unwrap();
        assert!(
            root.contents.contains("mod helpers;"),
            "content-less mod decl stays at the root (it binds helpers.rs):\n{}",
            root.contents
        );
        assert!(
            root.contents.contains("pub use helpers::Helper;"),
            "source re-export stays verbatim at the root:\n{}",
            root.contents
        );
        assert!(
            !root.contents.contains("pub(crate) use helpers"),
            "a source re-export must never be demoted"
        );
        for f in &out.files {
            if f.path != "lib.rs" {
                assert!(
                    !f.contents.contains("pub use helpers::Helper;"),
                    "{} must not carry the root's re-export",
                    f.path
                );
                assert!(
                    !f.contents.contains("mod helpers;"),
                    "{} must not carry the root's mod decl (would look for a \
                     sibling subdir file)",
                    f.path
                );
            }
        }
    }

    // ----- razel regression 2: the cfg(test) gate travels with the tests mod --

    #[test]
    fn under_budget_cfg_test_mod_is_extracted_whole_with_its_gate() {
        // The razel failure: the tests mod fit under the item budget, so it was
        // CLUSTERED — wrapped inside a part module with an ungated root decl —
        // instead of extracted. A body mod must always move whole, its
        // `#[cfg(test)]` gating the root declaration.
        let src = "pub fn alpha() -> i32 {\n    1\n}\n\n\
                   #[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    \
                   fn smoke() {\n        assert_eq!(alpha(), 1);\n    }\n}\n";
        let exploded = explode(src).unwrap();
        // Budget far above the tests mod's size: it would have been clustered.
        let out = split_bin(&exploded, 10_000, "lib");

        let root = out.files.iter().find(|f| f.path == "lib.rs").unwrap();
        assert!(
            root.contents.contains("#[cfg(test)]\nmod tests;"),
            "the gate must travel to the root declaration:\n{}",
            root.contents
        );
        assert!(
            !root.contents.contains("use tests::*"),
            "an extracted mod is declared, not glob re-exported:\n{}",
            root.contents
        );
        let tests = out.files.iter().find(|f| f.path == "tests.rs").unwrap();
        assert!(tests.contents.contains("fn smoke()"));
        assert!(
            !tests.contents.contains("mod tests"),
            "the body is unwrapped — no double nesting:\n{}",
            tests.contents
        );
    }

    #[test]
    fn pub_mod_keeps_its_visibility_on_the_extracted_decl() {
        let src = "pub fn api() -> i32 {\n    1\n}\n\n\
                   /// Config store.\npub mod config {\n    pub fn get() -> i32 {\n        2\n    }\n}\n";
        let exploded = explode(src).unwrap();
        let out = split_bin(&exploded, 10_000, "lib");

        let root = out.files.iter().find(|f| f.path == "lib.rs").unwrap();
        assert!(
            root.contents.contains("/// Config store.\npub mod config;"),
            "docs and `pub` travel to the declaration:\n{}",
            root.contents
        );
        let config = out.files.iter().find(|f| f.path == "config.rs").unwrap();
        assert!(config.contents.contains("pub fn get()"));
    }

    #[test]
    fn part_colliding_with_an_extracted_mod_name_is_renamed() {
        // `fn tests` (value namespace) and `mod tests` (type namespace) can
        // coexist in the source; the extracted mod owns `tests.rs`, so the
        // part named after the fn must yield.
        let src = "fn tests() -> i32 {\n    1\n}\n\n\
                   #[cfg(test)]\nmod tests {\n    fn smoke() {}\n}\n";
        let exploded = explode(src).unwrap();
        let out = split_bin(&exploded, 10_000, "lib");

        let paths: Vec<&str> = out.files.iter().map(|f| f.path.as_str()).collect();
        assert!(paths.contains(&"tests.rs"), "extracted mod file: {paths:?}");
        assert!(paths.contains(&"tests_.rs"), "renamed part file: {paths:?}");
        let root = out.files.iter().find(|f| f.path == "lib.rs").unwrap();
        assert!(root.contents.contains("mod tests_;"));
        assert!(root.contents.contains("#[cfg(test)]\nmod tests;"));
    }

    #[test]
    fn root_keeps_imports_an_extracted_mod_body_references() {
        // The extracted tests mod reaches the root's imports via
        // `use super::*;` — dropping HashMap from the root would break it.
        let src = "use std::collections::HashMap;\n\n\
                   pub fn alpha() -> i32 {\n    1\n}\n\n\
                   #[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    \
                   fn smoke() {\n        let _m: HashMap<u8, u8> = HashMap::new();\n        \
                   assert_eq!(alpha(), 1);\n    }\n}\n";
        let exploded = explode(src).unwrap();
        let out = split_bin(&exploded, 10_000, "lib");

        let root = out.files.iter().find(|f| f.path == "lib.rs").unwrap();
        assert!(
            root.contents.contains("use std::collections::HashMap;"),
            "root must keep imports the extracted body names:\n{}",
            root.contents
        );
    }

    #[test]
    fn bin_root_keeps_only_imports_main_references() {
        // `main` names `exit` but not `HashMap` (the moved `worker` does), so the
        // root keeps `exit` and drops `HashMap`.
        let src = "use std::process::exit;\nuse std::collections::HashMap;\n\nfn worker() -> HashMap<u8, u8> {\n    HashMap::new()\n}\n\nfn main() {\n    let _ = worker();\n    exit(0);\n}\n";
        let exploded = explode(src).unwrap();
        let out = split_bin(&exploded, 10_000, "main");

        let root = out.files.iter().find(|f| f.path == "main.rs").unwrap();
        assert!(
            root.contents.contains("use std::process::exit;"),
            "main references exit:\n{}",
            root.contents
        );
        assert!(
            !root.contents.contains("HashMap"),
            "main never names HashMap (worker does) -> dropped from root:\n{}",
            root.contents
        );
    }
}