cargo-arc 0.2.1

Visualize crate and module dependencies in Cargo workspaces
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
1341
//! Module discovery via syn + filesystem walk.

use anyhow::{Context, Result};
use std::collections::HashSet;
use std::path::{Path, PathBuf};

use super::mod_resolver::{
    ModDecl, child_resolve_dir, extract_mod_declarations, find_crate_root_files, resolve_mod_path,
};
use super::use_parser::ReExportMap;
use super::use_parser::{
    ResolutionContext, collect_all_path_refs, parse_path_ref_dependencies,
    parse_workspace_dependencies,
};
use crate::model::normalize_crate_name;
use crate::model::{
    CrateExportMap, CrateInfo, DependencyKind, DependencyRef, EdgeContext, ModuleInfo,
    ModulePathMap, ModuleTree, TestKind, WorkspaceCrates,
};

/// Find integration test files in `tests/*.rs`.
/// Each top-level `.rs` file is an independent test binary.
/// Subdirectory modules (e.g. `tests/common/mod.rs`) are NOT included.
fn find_integration_test_files(crate_path: &Path) -> Vec<PathBuf> {
    let tests_dir = crate_path.join("tests");
    if !tests_dir.is_dir() {
        return Vec::new();
    }
    let mut files = Vec::new();
    let Ok(entries) = std::fs::read_dir(&tests_dir) else {
        return Vec::new();
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_file() && path.extension().is_some_and(|e| e == "rs") {
            files.push(path);
        }
    }
    files.sort(); // deterministic order
    files
}

/// Parse a Rust source file and return all external `mod` declarations.
/// Convenience wrapper around `extract_mod_declarations` for callers with a file path.
fn parse_mod_declarations(file_path: &Path, include_tests: bool) -> Result<Vec<ModDecl>> {
    let source = std::fs::read_to_string(file_path)
        .with_context(|| format!("reading {}", file_path.display()))?;
    let syntax =
        syn::parse_file(&source).with_context(|| format!("parsing {}", file_path.display()))?;
    Ok(extract_mod_declarations(&syntax, include_tests))
}

// ---------------------------------------------------------------------------
// Public API: collect_syn_module_paths
// ---------------------------------------------------------------------------

/// Recursively walk `mod` declarations starting from `file_path`,
/// collecting relative module paths (e.g. `"foo"`, `"foo::bar"`).
fn walk_modules_for_paths(
    file_path: &Path,
    parent_path: &str,
    paths: &mut HashSet<String>,
    include_tests: bool,
) {
    let decls = match parse_mod_declarations(file_path, include_tests) {
        Ok(d) => d,
        Err(e) => {
            tracing::warn!("skipping {}: {e:#}", file_path.display());
            return;
        }
    };

    let resolve_dir = child_resolve_dir(file_path);

    for decl in decls {
        let child_path = if let Some(ref explicit) = decl.explicit_path {
            let p = resolve_dir.join(explicit);
            if p.exists() { Some(p) } else { None }
        } else {
            resolve_mod_path(&resolve_dir, &decl.name)
        };

        let child_full = if parent_path.is_empty() {
            decl.name.clone()
        } else {
            format!("{parent_path}::{}", decl.name)
        };
        paths.insert(child_full.clone());

        if let Some(resolved) = child_path {
            walk_modules_for_paths(&resolved, &child_full, paths, include_tests);
        }
    }
}

/// Collect all module paths reachable from `crate_root` via filesystem walk.
/// Returns relative paths without crate prefix, e.g. `{"analyze", "analyze::hir"}`.
pub(crate) fn collect_syn_module_paths(
    crate_root: &Path,
    crate_name: &str,
    include_tests: bool,
) -> HashSet<String> {
    let _ = crate_name; // unused; kept for API parity with collect_hir_module_paths
    let root_files = match find_crate_root_files(crate_root) {
        Ok(f) => f,
        Err(e) => {
            tracing::warn!("collect_syn_module_paths: {e:#}");
            return HashSet::new();
        }
    };
    let mut paths = HashSet::new();
    for root_file in root_files {
        walk_modules_for_paths(&root_file, "", &mut paths, include_tests);
    }
    paths
}

// ---------------------------------------------------------------------------
// Public API: collect_crate_exports
// ---------------------------------------------------------------------------

/// Extract the leaf name(s) from a `UseTree`.
/// Handles simple paths, aliases, and groups — but NOT globs.
fn collect_use_tree_names(tree: &syn::UseTree, names: &mut HashSet<String>) {
    match tree {
        syn::UseTree::Path(p) => collect_use_tree_names(&p.tree, names),
        syn::UseTree::Name(n) => {
            names.insert(n.ident.to_string());
        }
        syn::UseTree::Rename(r) => {
            names.insert(r.rename.to_string());
        }
        syn::UseTree::Group(g) => {
            for item in &g.items {
                collect_use_tree_names(item, names);
            }
        }
        syn::UseTree::Glob(_) => {} // out of scope
    }
}

/// Returns whether a `syn::Visibility` is `pub` (not `pub(crate)`, `pub(super)`, etc.).
fn is_pub(vis: &syn::Visibility) -> bool {
    matches!(vis, syn::Visibility::Public(_))
}

/// Collect publicly exported symbol names from a crate's entry point (lib.rs/main.rs).
///
/// Includes:
/// - `pub fn`, `pub struct`, `pub enum`, `pub trait`, `pub const`, `pub static`, `pub type`
/// - `pub use` re-exports (simple, aliased, grouped — NOT glob)
///
/// Ignores `pub mod` declarations (module structure, not exports).
/// Returns an empty set on any error (no entry file, parse failure).
pub(crate) fn collect_crate_exports(crate_root: &Path) -> HashSet<String> {
    let Ok(root_files) = find_crate_root_files(crate_root) else {
        return HashSet::new();
    };
    // Only lib.rs exports — binary targets export nothing
    let Some(root_file) = root_files
        .iter()
        .find(|p| p.file_name().is_some_and(|n| n == "lib.rs"))
    else {
        return HashSet::new();
    };

    let Ok(source) = std::fs::read_to_string(root_file) else {
        return HashSet::new();
    };

    let Ok(syntax) = syn::parse_file(&source) else {
        return HashSet::new();
    };

    let mut exports = HashSet::new();

    for item in &syntax.items {
        match item {
            syn::Item::Fn(i) if is_pub(&i.vis) => {
                exports.insert(i.sig.ident.to_string());
            }
            syn::Item::Struct(i) if is_pub(&i.vis) => {
                exports.insert(i.ident.to_string());
            }
            syn::Item::Enum(i) if is_pub(&i.vis) => {
                exports.insert(i.ident.to_string());
            }
            syn::Item::Trait(i) if is_pub(&i.vis) => {
                exports.insert(i.ident.to_string());
            }
            syn::Item::Const(i) if is_pub(&i.vis) => {
                exports.insert(i.ident.to_string());
            }
            syn::Item::Static(i) if is_pub(&i.vis) => {
                exports.insert(i.ident.to_string());
            }
            syn::Item::Type(i) if is_pub(&i.vis) => {
                exports.insert(i.ident.to_string());
            }
            syn::Item::Use(i) if is_pub(&i.vis) => {
                collect_use_tree_names(&i.tree, &mut exports);
            }
            _ => {}
        }
    }

    exports
}

// ---------------------------------------------------------------------------
// Public API: analyze_modules_syn
// ---------------------------------------------------------------------------

/// Invariant parameters shared across the recursive module walk.
#[derive(Clone)]
struct WalkContext<'a> {
    crate_name: &'a str,
    crate_root: &'a Path,
    workspace_crates: &'a WorkspaceCrates,
    all_module_paths: &'a ModulePathMap,
    crate_exports: &'a CrateExportMap,
    reexport_map: &'a ReExportMap,
    external_crate_names: &'a std::collections::HashMap<String, String>,
    include_tests: bool,
    base_context: EdgeContext,
}

/// Recursively walk a module, building `ModuleInfo` with dependency extraction.
fn walk_module_syn(
    ctx: &WalkContext,
    file_path: &Path,
    module_name: &str,
    parent_path: &str,
    is_crate_root: bool,
) -> ModuleInfo {
    let full_path = if parent_path == module_name {
        // root module: full_path == crate name
        module_name.to_string()
    } else {
        format!("{parent_path}::{module_name}")
    };

    // Single read + single parse for both dependency extraction and mod discovery
    let source_text = match std::fs::read_to_string(file_path) {
        Ok(s) => s,
        Err(e) => {
            tracing::warn!("reading {}: {e:#}", file_path.display());
            return ModuleInfo {
                name: module_name.to_string(),
                full_path,
                children: Vec::new(),
                dependencies: Vec::new(),
            };
        }
    };
    let syntax = match syn::parse_file(&source_text) {
        Ok(f) => f,
        Err(e) => {
            tracing::warn!("parsing {}: {e:#}", file_path.display());
            return ModuleInfo {
                name: module_name.to_string(),
                full_path,
                children: Vec::new(),
                dependencies: Vec::new(),
            };
        }
    };

    let source_file = file_path
        .strip_prefix(ctx.crate_root)
        .map_or_else(|_| file_path.to_path_buf(), std::path::Path::to_path_buf);

    // Relative module path within the crate (e.g. "render" for render/mod.rs, "" for root)
    let current_module_path = full_path
        .strip_prefix(&format!("{}::", ctx.crate_name))
        .unwrap_or("");

    // Extract use items from all scopes (top-level + fn bodies + nested blocks)
    let use_items = super::use_parser::collect_all_use_items(&syntax, ctx.base_context.clone());
    let res_ctx = ResolutionContext {
        current_crate: ctx.crate_name,
        workspace_crates: ctx.workspace_crates,
        source_file: &source_file,
        all_module_paths: ctx.all_module_paths,
        crate_exports: ctx.crate_exports,
        current_module_path,
        reexport_map: ctx.reexport_map,
        external_crate_names: ctx.external_crate_names,
    };
    let use_deps = parse_workspace_dependencies(&use_items, &res_ctx);

    // Extract qualified path references (e.g. my_lib::run(), let x: my_lib::Config)
    let path_refs = collect_all_path_refs(&syntax, ctx.base_context.clone());
    let path_deps = parse_path_ref_dependencies(&path_refs, &res_ctx);

    // Merge: use-dependencies first (have priority), then path-dependencies (dedup by (full_target, kind))
    let mut seen = DependencyRef::build_seen_index(&use_deps);
    let mut dependencies = use_deps;
    for dep in path_deps {
        DependencyRef::dedup_push(&mut dependencies, &mut seen, dep);
    }

    if !ctx.include_tests {
        dependencies.retain(|d| d.context.kind == DependencyKind::Production);
    }

    // Extract mod declarations from the same AST (no second file read)
    let decls = extract_mod_declarations(&syntax, ctx.include_tests);

    // Integration test files (tests/smoke.rs) are crate roots: resolve modules
    // from their parent directory (tests/), not from a stem-based subdirectory.
    let resolve_dir = if is_crate_root {
        file_path.parent().unwrap_or(Path::new(".")).to_path_buf()
    } else {
        child_resolve_dir(file_path)
    };

    let children: Vec<ModuleInfo> = decls
        .into_iter()
        .filter_map(|decl| {
            let child_file = if let Some(ref explicit) = decl.explicit_path {
                let p = resolve_dir.join(explicit);
                if p.exists() { Some(p) } else { None }
            } else {
                resolve_mod_path(&resolve_dir, &decl.name)
            };

            child_file.map(|cf| walk_module_syn(ctx, &cf, &decl.name, &full_path, false))
        })
        .collect();

    ModuleInfo {
        name: module_name.to_string(),
        full_path,
        children,
        dependencies,
    }
}

/// Analyze module hierarchy via syn + filesystem walk (no rust-analyzer needed).
/// Drop-in replacement for `hir::analyze_modules()`.
pub(crate) fn analyze_modules_syn(
    crate_info: &CrateInfo,
    workspace_crates: &WorkspaceCrates,
    all_module_paths: &ModulePathMap,
    crate_exports: &CrateExportMap,
    reexport_map: &ReExportMap,
    external_crate_names: &std::collections::HashMap<String, String>,
    include_tests: bool,
) -> Result<ModuleTree> {
    let root_files = find_crate_root_files(&crate_info.path)?;
    let normalized = normalize_crate_name(&crate_info.name);

    let ctx = WalkContext {
        crate_name: &normalized,
        crate_root: &crate_info.path,
        workspace_crates,
        all_module_paths,
        crate_exports,
        reexport_map,
        external_crate_names,
        include_tests,
        base_context: EdgeContext::production(),
    };

    let mut root: Option<ModuleInfo> = None;
    for root_file in &root_files {
        let tree = walk_module_syn(
            &ctx,
            root_file,
            &normalized,
            &normalized, // parent_path == name for root → triggers identity check
            false,
        );
        match &mut root {
            None => root = Some(tree),
            Some(existing) => {
                for child in tree.children {
                    if !existing.children.iter().any(|c| c.name == child.name) {
                        existing.children.push(child);
                    }
                }
                // Dedup via PartialEq (compares kind + features). With empty
                // features this is correct; ca-0134 may need feature-merge here.
                for dep in tree.dependencies {
                    if !existing.dependencies.contains(&dep) {
                        existing.dependencies.push(dep);
                    }
                }
            }
        }
    }

    // For test-only crates (no src/), create an empty root module
    if root.is_none() {
        root = Some(ModuleInfo {
            name: normalized.clone(),
            full_path: normalized.clone(),
            children: Vec::new(),
            dependencies: Vec::new(),
        });
    }

    // Walk integration test files (tests/*.rs) when --include-tests is active
    if include_tests {
        let test_ctx = WalkContext {
            base_context: EdgeContext::test(TestKind::Integration),
            ..ctx.clone()
        };
        let test_files = find_integration_test_files(&crate_info.path);
        let root = root.as_mut().unwrap();
        for test_file in test_files {
            let test_name = test_file
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("unknown");
            let tree = walk_module_syn(
                &test_ctx,
                &test_file,
                test_name,
                &format!("{normalized}::tests"),
                true,
            );
            root.children.push(tree);
        }
    }

    let root = root.unwrap();
    Ok(ModuleTree { root })
}

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

    struct TestProject {
        files: Vec<(PathBuf, String)>,
    }

    impl TestProject {
        fn new() -> Self {
            Self { files: vec![] }
        }

        fn file(mut self, path: &str, content: &str) -> Self {
            self.files.push((PathBuf::from(path), content.to_string()));
            self
        }

        fn build(self) -> TempDir {
            let tmp = TempDir::new().unwrap();
            for (path, content) in &self.files {
                let full = tmp.path().join(path);
                if let Some(parent) = full.parent() {
                    std::fs::create_dir_all(parent).unwrap();
                }
                std::fs::write(&full, content).unwrap();
            }
            tmp
        }
    }

    mod parse_mod {
        use super::*;

        #[test]
        fn test_parse_mod_simple() {
            let tmp = TestProject::new().file("test.rs", "mod foo;").build();
            let path = tmp.path().join("test.rs");

            let decls = parse_mod_declarations(&path, false).unwrap();
            assert_eq!(decls.len(), 1);
            assert_eq!(decls[0].name, "foo");
            assert!(decls[0].explicit_path.is_none());
        }

        #[test]
        fn test_parse_mod_cfg_test_filtered() {
            let tmp = TestProject::new()
                .file("test.rs", "#[cfg(test)]\nmod tests;")
                .build();
            let path = tmp.path().join("test.rs");

            let decls = parse_mod_declarations(&path, false).unwrap();
            assert!(decls.is_empty());
        }

        #[test]
        fn test_parse_mod_multiple() {
            let tmp = TestProject::new()
                .file("test.rs", "mod alpha;\nmod beta;\nmod gamma;")
                .build();
            let path = tmp.path().join("test.rs");

            let decls = parse_mod_declarations(&path, false).unwrap();
            let names: Vec<&str> = decls.iter().map(|d| d.name.as_str()).collect();
            assert_eq!(names, vec!["alpha", "beta", "gamma"]);
        }

        #[test]
        fn test_parse_mod_inline_ignored() {
            let tmp = TestProject::new()
                .file("test.rs", "mod foo { fn bar() {} }")
                .build();
            let path = tmp.path().join("test.rs");

            let decls = parse_mod_declarations(&path, false).unwrap();
            assert!(decls.is_empty());
        }

        #[test]
        fn test_parse_mod_with_path_attribute() {
            let tmp = TestProject::new()
                .file("test.rs", "#[path = \"custom.rs\"]\nmod foo;")
                .build();
            let path = tmp.path().join("test.rs");

            let decls = parse_mod_declarations(&path, false).unwrap();
            assert_eq!(decls.len(), 1);
            assert_eq!(decls[0].name, "foo");
            assert_eq!(decls[0].explicit_path.as_deref(), Some("custom.rs"));
        }
    }

    mod collect_paths {
        use super::*;

        #[test]
        fn test_collect_paths_synthetic() {
            // lib.rs → mod foo; → foo.rs → mod bar; → foo/bar.rs
            let tmp = TestProject::new()
                .file("src/lib.rs", "mod foo;")
                .file("src/foo.rs", "mod bar;")
                .file("src/foo/bar.rs", "")
                .build();

            let paths = collect_syn_module_paths(tmp.path(), "synth", false);
            assert!(
                paths.contains("foo"),
                "should contain 'foo', found: {paths:?}"
            );
            assert!(
                paths.contains("foo::bar"),
                "should contain 'foo::bar', found: {paths:?}"
            );
            assert_eq!(paths.len(), 2);
        }

        #[test]
        fn test_collect_paths_own_crate() {
            let crate_root = Path::new(env!("CARGO_MANIFEST_DIR"));
            let paths = collect_syn_module_paths(crate_root, "cargo_arc", false);

            for expected in [
                "analyze",
                "cli",
                "model",
                "graph",
                "analyze::hir",
                "analyze::use_parser",
            ] {
                assert!(
                    paths.contains(expected),
                    "should contain '{expected}', found: {paths:?}"
                );
            }
            // Must NOT contain crate prefix
            assert!(
                !paths.iter().any(|p| p.starts_with("cargo_arc::")),
                "paths should be relative, found: {paths:?}"
            );
        }

        #[test]
        fn test_collect_paths_empty_crate() {
            let tmp = TestProject::new()
                .file("src/lib.rs", "// empty crate")
                .build();

            let paths = collect_syn_module_paths(tmp.path(), "empty", false);
            assert!(paths.is_empty(), "expected empty set, found: {paths:?}");
        }

        #[test]
        fn test_mixed_crate_module_paths() {
            let tmp = TestProject::new()
                .file("src/lib.rs", "mod a;")
                .file("src/main.rs", "mod b;")
                .file("src/a.rs", "")
                .file("src/b.rs", "")
                .build();

            let paths = collect_syn_module_paths(tmp.path(), "mixed", false);
            assert!(paths.contains("a"), "should contain 'a', found: {paths:?}");
            assert!(paths.contains("b"), "should contain 'b', found: {paths:?}");
            assert_eq!(paths.len(), 2);
        }
    }

    mod collect_exports {
        use super::*;

        #[test]
        fn test_collect_exports_pub_items() {
            let tmp = TestProject::new()
                .file(
                    "src/lib.rs",
                    r"
                    pub fn helper() {}
                    pub struct MyStruct;
                    pub enum MyEnum { A, B }
                    pub trait MyTrait {}
                    pub const MAX: usize = 10;
                    pub static GLOBAL: i32 = 0;
                    pub type Alias = i32;
                ",
                )
                .build();

            let exports = collect_crate_exports(tmp.path());
            for name in [
                "helper", "MyStruct", "MyEnum", "MyTrait", "MAX", "GLOBAL", "Alias",
            ] {
                assert!(
                    exports.contains(name),
                    "should contain '{name}', found: {exports:?}"
                );
            }
            assert_eq!(exports.len(), 7);
        }

        #[test]
        fn test_collect_exports_reexports() {
            let tmp = TestProject::new()
                .file("src/lib.rs", "pub use some_crate::Widget;\n")
                .build();

            let exports = collect_crate_exports(tmp.path());
            assert!(exports.contains("Widget"), "found: {exports:?}");
            assert_eq!(exports.len(), 1);
        }

        #[test]
        fn test_collect_exports_alias_reexport() {
            let tmp = TestProject::new()
                .file("src/lib.rs", "pub use some_crate::Original as Alias;\n")
                .build();

            let exports = collect_crate_exports(tmp.path());
            assert!(exports.contains("Alias"), "found: {exports:?}");
            assert!(!exports.contains("Original"), "should not contain Original");
            assert_eq!(exports.len(), 1);
        }

        #[test]
        fn test_collect_exports_multi_reexport() {
            let tmp = TestProject::new()
                .file("src/lib.rs", "pub use some_crate::{Alpha, Beta};\n")
                .build();

            let exports = collect_crate_exports(tmp.path());
            assert!(exports.contains("Alpha"), "found: {exports:?}");
            assert!(exports.contains("Beta"), "found: {exports:?}");
            assert_eq!(exports.len(), 2);
        }

        #[test]
        fn test_collect_exports_non_pub_ignored() {
            let tmp = TestProject::new()
                .file(
                    "src/lib.rs",
                    r"
                    fn private_fn() {}
                    struct PrivateStruct;
                    pub fn public_fn() {}
                    pub(crate) fn crate_fn() {}
                ",
                )
                .build();

            let exports = collect_crate_exports(tmp.path());
            assert!(exports.contains("public_fn"), "found: {exports:?}");
            assert!(!exports.contains("private_fn"));
            assert!(!exports.contains("PrivateStruct"));
            assert!(!exports.contains("crate_fn"));
            assert_eq!(exports.len(), 1);
        }

        #[test]
        fn test_collect_exports_mod_ignored() {
            let tmp = TestProject::new()
                .file("src/lib.rs", "pub mod foo;\npub fn real_export() {}\n")
                .build();

            let exports = collect_crate_exports(tmp.path());
            assert!(exports.contains("real_export"), "found: {exports:?}");
            assert!(!exports.contains("foo"), "pub mod should not be an export");
            assert_eq!(exports.len(), 1);
        }

        #[test]
        fn test_collect_exports_no_entry_file() {
            let tmp = TestProject::new().build();

            let exports = collect_crate_exports(tmp.path());
            assert!(exports.is_empty(), "found: {exports:?}");
        }

        #[test]
        fn test_mixed_crate_exports_only_lib() {
            let tmp = TestProject::new()
                .file("src/lib.rs", "pub fn from_lib() {}")
                .file("src/main.rs", "pub fn from_main() {}")
                .build();

            let exports = collect_crate_exports(tmp.path());
            assert!(
                exports.contains("from_lib"),
                "should contain 'from_lib', found: {exports:?}"
            );
            assert!(
                !exports.contains("from_main"),
                "should NOT contain 'from_main', found: {exports:?}"
            );
            assert_eq!(exports.len(), 1);
        }
    }

    mod analyze_syn {
        use super::*;

        #[test]
        fn test_analyze_modules_syn_structure() {
            let crate_root = Path::new(env!("CARGO_MANIFEST_DIR"));
            let crate_info = CrateInfo {
                name: "cargo-arc".to_string(),
                path: crate_root.to_path_buf(),
                dependencies: vec![],
                dev_dependencies: vec![],
            };
            let workspace_crates: WorkspaceCrates = ["cargo-arc"]
                .iter()
                .map(std::string::ToString::to_string)
                .collect();

            let tree = analyze_modules_syn(
                &crate_info,
                &workspace_crates,
                &ModulePathMap::default(),
                &CrateExportMap::default(),
                &ReExportMap::default(),
                &std::collections::HashMap::new(),
                false,
            )
            .expect("should analyze");

            assert_eq!(tree.root.name, "cargo_arc");
            assert_eq!(tree.root.full_path, "cargo_arc");

            let child_names: Vec<&str> =
                tree.root.children.iter().map(|m| m.name.as_str()).collect();
            assert!(
                child_names.contains(&"analyze"),
                "should contain 'analyze', found: {child_names:?}"
            );
            assert!(
                child_names.contains(&"graph"),
                "should contain 'graph', found: {child_names:?}"
            );

            // Check submodule hierarchy
            let analyze_mod = tree
                .root
                .children
                .iter()
                .find(|m| m.name == "analyze")
                .unwrap();
            let sub_names: Vec<&str> = analyze_mod
                .children
                .iter()
                .map(|m| m.name.as_str())
                .collect();
            assert!(
                sub_names.contains(&"hir"),
                "analyze should contain 'hir', found: {sub_names:?}"
            );
            assert!(
                sub_names.contains(&"use_parser"),
                "analyze should contain 'use_parser', found: {sub_names:?}"
            );
        }

        #[test]
        fn test_analyze_modules_syn_dependencies() {
            let crate_root = Path::new(env!("CARGO_MANIFEST_DIR"));
            let crate_info = CrateInfo {
                name: "cargo-arc".to_string(),
                path: crate_root.to_path_buf(),
                dependencies: vec![],
                dev_dependencies: vec![],
            };
            let workspace_crates: WorkspaceCrates = ["cargo-arc"]
                .iter()
                .map(std::string::ToString::to_string)
                .collect();

            // Collect module paths for accurate dependency resolution
            let paths = collect_syn_module_paths(crate_root, "cargo_arc", false);
            let all_module_paths: ModulePathMap =
                [("cargo_arc".to_string(), paths)].into_iter().collect();

            let tree = analyze_modules_syn(
                &crate_info,
                &workspace_crates,
                &all_module_paths,
                &CrateExportMap::default(),
                &ReExportMap::default(),
                &std::collections::HashMap::new(),
                false,
            )
            .expect("should analyze");

            let graph_mod = tree
                .root
                .children
                .iter()
                .find(|m| m.name == "graph")
                .unwrap();
            assert!(
                graph_mod
                    .dependencies
                    .iter()
                    .any(|d| d.module_target() == "cargo_arc::model"),
                "graph should depend on model, found: {:?}",
                graph_mod.dependencies
            );
        }

        #[test]
        fn test_binary_only_crate() {
            let tmp = TestProject::new()
                .file("src/main.rs", "mod cli;")
                .file("src/cli.rs", "")
                .build();

            // collect_syn_module_paths finds "cli"
            let paths = collect_syn_module_paths(tmp.path(), "binonly", false);
            assert!(
                paths.contains("cli"),
                "should contain 'cli', found: {paths:?}"
            );

            // collect_crate_exports returns empty (no lib.rs)
            let exports = collect_crate_exports(tmp.path());
            assert!(
                exports.is_empty(),
                "binary-only should have no exports, found: {exports:?}"
            );

            // analyze_modules_syn builds tree with "cli" child
            let crate_info = CrateInfo {
                name: "binonly".to_string(),
                path: tmp.path().to_path_buf(),
                dependencies: vec![],
                dev_dependencies: vec![],
            };
            let tree = analyze_modules_syn(
                &crate_info,
                &WorkspaceCrates::default(),
                &ModulePathMap::default(),
                &CrateExportMap::default(),
                &ReExportMap::default(),
                &std::collections::HashMap::new(),
                false,
            )
            .expect("should analyze binary-only crate");

            let child_names: Vec<&str> =
                tree.root.children.iter().map(|m| m.name.as_str()).collect();
            assert!(
                child_names.contains(&"cli"),
                "should contain 'cli', found: {child_names:?}"
            );
        }

        #[test]
        fn test_path_ref_dependencies_collected() {
            let tmp = TestProject::new()
                .file(
                    "src/main.rs",
                    r"
fn main() {
    other_crate::module::run();
    let _x: other_crate::module::Config = todo!();
}
",
                )
                .build();

            let ws: WorkspaceCrates = ["other_crate".to_string()].into_iter().collect();
            let mp: ModulePathMap = [("other_crate".to_string(), HashSet::from(["module".into()]))]
                .into_iter()
                .collect();
            let crate_info = CrateInfo {
                name: "app".to_string(),
                path: tmp.path().to_path_buf(),
                dependencies: vec![],
                dev_dependencies: vec![],
            };
            let tree = analyze_modules_syn(
                &crate_info,
                &ws,
                &mp,
                &CrateExportMap::default(),
                &ReExportMap::default(),
                &std::collections::HashMap::new(),
                false,
            )
            .expect("should analyze");

            // Path expressions should be detected as dependencies
            assert!(
                tree.root
                    .dependencies
                    .iter()
                    .any(|d| d.target_crate == "other_crate" && d.target_module == "module"),
                "should detect path-ref dependency on other_crate::module, found: {:?}",
                tree.root.dependencies
            );
        }

        #[test]
        fn test_path_ref_dedup_with_use() {
            let tmp = TestProject::new()
                .file(
                    "src/main.rs",
                    r"
use other_crate::module::Item;
fn main() {
    other_crate::module::Item::new();
}
",
                )
                .build();

            let ws: WorkspaceCrates = ["other_crate".to_string()].into_iter().collect();
            let mp: ModulePathMap = [("other_crate".to_string(), HashSet::from(["module".into()]))]
                .into_iter()
                .collect();
            let crate_info = CrateInfo {
                name: "app".to_string(),
                path: tmp.path().to_path_buf(),
                dependencies: vec![],
                dev_dependencies: vec![],
            };
            let tree = analyze_modules_syn(
                &crate_info,
                &ws,
                &mp,
                &CrateExportMap::default(),
                &ReExportMap::default(),
                &std::collections::HashMap::new(),
                false,
            )
            .expect("should analyze");

            // Should have exactly 1 dep for other_crate::module::Item (deduped)
            let item_deps: Vec<_> = tree
                .root
                .dependencies
                .iter()
                .filter(|d| {
                    d.target_crate == "other_crate"
                        && d.target_module == "module"
                        && d.target_item == Some("Item".to_string())
                })
                .collect();
            assert_eq!(
                item_deps.len(),
                1,
                "same target should be deduped, found: {:?}",
                tree.root.dependencies
            );
        }

        #[test]
        fn test_mixed_crate_module_tree() {
            let tmp = TestProject::new()
                .file("src/lib.rs", "mod a;")
                .file("src/main.rs", "mod b;")
                .file("src/a.rs", "")
                .file("src/b.rs", "")
                .build();

            let crate_info = CrateInfo {
                name: "mixed".to_string(),
                path: tmp.path().to_path_buf(),
                dependencies: vec![],
                dev_dependencies: vec![],
            };
            let tree = analyze_modules_syn(
                &crate_info,
                &WorkspaceCrates::default(),
                &ModulePathMap::default(),
                &CrateExportMap::default(),
                &ReExportMap::default(),
                &std::collections::HashMap::new(),
                false,
            )
            .expect("should analyze mixed crate");

            let child_names: Vec<&str> =
                tree.root.children.iter().map(|m| m.name.as_str()).collect();
            assert!(
                child_names.contains(&"a"),
                "should contain 'a' from lib.rs, found: {child_names:?}"
            );
            assert!(
                child_names.contains(&"b"),
                "should contain 'b' from main.rs, found: {child_names:?}"
            );
        }
    }

    mod child_module_resolution {
        use super::*;

        #[test]
        fn test_child_module_bare_use_resolved() {
            // cargo-arc analyzes itself: render module must have deps on render::css and render::elements
            let crate_root = Path::new(env!("CARGO_MANIFEST_DIR"));
            let crate_info = CrateInfo {
                name: "cargo-arc".to_string(),
                path: crate_root.to_path_buf(),
                dependencies: vec![],
                dev_dependencies: vec![],
            };
            let workspace_crates: WorkspaceCrates = ["cargo-arc"]
                .iter()
                .map(std::string::ToString::to_string)
                .collect();
            let paths = collect_syn_module_paths(crate_root, "cargo_arc", false);
            let all_module_paths: ModulePathMap =
                [("cargo_arc".to_string(), paths)].into_iter().collect();

            let tree = analyze_modules_syn(
                &crate_info,
                &workspace_crates,
                &all_module_paths,
                &CrateExportMap::default(),
                &ReExportMap::default(),
                &std::collections::HashMap::new(),
                false,
            )
            .expect("should analyze");

            let render_mod = tree
                .root
                .children
                .iter()
                .find(|m| m.name == "render")
                .expect("should find render module");

            let dep_targets: Vec<String> = render_mod
                .dependencies
                .iter()
                .map(crate::model::DependencyRef::module_target)
                .collect();

            assert!(
                dep_targets.iter().any(|t| t == "cargo_arc::render::css"),
                "render should depend on render::css, found: {dep_targets:?}"
            );
            assert!(
                dep_targets
                    .iter()
                    .any(|t| t == "cargo_arc::render::elements"),
                "render should depend on render::elements, found: {dep_targets:?}"
            );
        }
    }

    mod find_integration_tests {
        use super::*;

        #[test]
        fn test_find_integration_test_files() {
            let tmp = TestProject::new()
                .file("tests/smoke.rs", "")
                .file("tests/check.rs", "")
                .file("tests/common/mod.rs", "")
                .build();

            let files = find_integration_test_files(tmp.path());
            let names: Vec<&str> = files
                .iter()
                .filter_map(|p| p.file_stem()?.to_str())
                .collect();
            assert!(names.contains(&"smoke"), "should contain smoke: {names:?}");
            assert!(names.contains(&"check"), "should contain check: {names:?}");
            assert_eq!(
                files.len(),
                2,
                "should not include common/mod.rs: {names:?}"
            );
        }

        #[test]
        fn test_find_integration_test_files_no_tests_dir() {
            let tmp = TestProject::new().build();
            let files = find_integration_test_files(tmp.path());
            assert!(files.is_empty());
        }

        #[test]
        fn test_find_crate_root_test_only_crate() {
            let tmp = TestProject::new().file("tests/check.rs", "").build();

            let roots = find_crate_root_files(tmp.path()).unwrap();
            assert!(
                roots.is_empty(),
                "test-only crate should return empty roots"
            );
        }

        #[test]
        fn test_find_crate_root_no_src_no_tests_errors() {
            let tmp = TestProject::new().build();
            let result = find_crate_root_files(tmp.path());
            assert!(result.is_err());
        }
    }

    mod integration_test_analysis {
        use super::*;
        use crate::model::TestKind;

        #[test]
        fn test_analyze_crate_with_integration_tests() {
            let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .join("tests/fixtures/integration_test_crate/crate_with_tests");
            let crate_info = CrateInfo {
                name: "crate_with_tests".to_string(),
                path: fixture,
                dependencies: vec!["crate_lib".to_string()],
                dev_dependencies: vec![],
            };
            let ws: WorkspaceCrates = ["crate_with_tests", "crate_lib"]
                .iter()
                .map(std::string::ToString::to_string)
                .collect();

            let tree = analyze_modules_syn(
                &crate_info,
                &ws,
                &ModulePathMap::default(),
                &CrateExportMap::default(),
                &ReExportMap::default(),
                &std::collections::HashMap::new(),
                true,
            )
            .expect("should analyze");

            let child_names: Vec<&str> =
                tree.root.children.iter().map(|m| m.name.as_str()).collect();
            assert!(
                child_names.contains(&"smoke"),
                "should contain integration test 'smoke': {child_names:?}"
            );

            let smoke = tree
                .root
                .children
                .iter()
                .find(|m| m.name == "smoke")
                .unwrap();
            for dep in &smoke.dependencies {
                assert_eq!(
                    dep.context,
                    EdgeContext::test(TestKind::Integration),
                    "integration test deps should have Integration context: {dep:?}"
                );
            }
        }

        #[test]
        fn test_analyze_crate_without_include_tests_flag() {
            let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .join("tests/fixtures/integration_test_crate/crate_with_tests");
            let crate_info = CrateInfo {
                name: "crate_with_tests".to_string(),
                path: fixture,
                dependencies: vec![],
                dev_dependencies: vec![],
            };

            let tree = analyze_modules_syn(
                &crate_info,
                &WorkspaceCrates::default(),
                &ModulePathMap::default(),
                &CrateExportMap::default(),
                &ReExportMap::default(),
                &std::collections::HashMap::new(),
                false,
            )
            .expect("should analyze");

            let child_names: Vec<&str> =
                tree.root.children.iter().map(|m| m.name.as_str()).collect();
            assert!(
                !child_names.contains(&"smoke"),
                "without --include-tests, integration tests should not appear: {child_names:?}"
            );
        }

        #[test]
        fn test_analyze_test_only_crate() {
            let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .join("tests/fixtures/integration_test_crate/test_only_crate");
            let crate_info = CrateInfo {
                name: "test_only_crate".to_string(),
                path: fixture,
                dependencies: vec!["crate_lib".to_string()],
                dev_dependencies: vec![],
            };
            let ws: WorkspaceCrates = ["test_only_crate", "crate_lib"]
                .iter()
                .map(std::string::ToString::to_string)
                .collect();

            let tree = analyze_modules_syn(
                &crate_info,
                &ws,
                &ModulePathMap::default(),
                &CrateExportMap::default(),
                &ReExportMap::default(),
                &std::collections::HashMap::new(),
                true,
            )
            .expect("should analyze test-only crate");

            assert_eq!(tree.root.name, "test_only_crate");
            let child_names: Vec<&str> =
                tree.root.children.iter().map(|m| m.name.as_str()).collect();
            assert!(
                child_names.contains(&"check"),
                "test-only crate should have 'check' integration test: {child_names:?}"
            );
        }

        #[test]
        fn test_test_only_crate_errors_without_flag() {
            let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .join("tests/fixtures/integration_test_crate/test_only_crate");
            let crate_info = CrateInfo {
                name: "test_only_crate".to_string(),
                path: fixture,
                dependencies: vec![],
                dev_dependencies: vec![],
            };

            let tree = analyze_modules_syn(
                &crate_info,
                &WorkspaceCrates::default(),
                &ModulePathMap::default(),
                &CrateExportMap::default(),
                &ReExportMap::default(),
                &std::collections::HashMap::new(),
                false,
            )
            .expect("should not error for test-only crate");
            assert!(tree.root.children.is_empty());
        }

        #[test]
        fn test_inline_cfg_test_deps_excluded_without_flag() {
            let tmp = TestProject::new()
                .file("src/lib.rs", "mod alpha;\n")
                .file(
                    "src/alpha.rs",
                    r"
use crate::beta::helper;

pub fn process() {}

#[cfg(test)]
mod tests {
    use crate::gamma::test_util;
}
",
                )
                .build();

            let mp: ModulePathMap = [(
                "my_crate".to_string(),
                HashSet::from(["alpha".into(), "beta".into(), "gamma".into()]),
            )]
            .into_iter()
            .collect();
            let crate_info = CrateInfo {
                name: "my_crate".to_string(),
                path: tmp.path().to_path_buf(),
                dependencies: vec![],
                dev_dependencies: vec![],
            };

            let tree = analyze_modules_syn(
                &crate_info,
                &WorkspaceCrates::default(),
                &mp,
                &CrateExportMap::default(),
                &ReExportMap::default(),
                &std::collections::HashMap::new(),
                false,
            )
            .expect("should analyze");

            let alpha = tree
                .root
                .children
                .iter()
                .find(|m| m.name == "alpha")
                .expect("alpha module should exist");

            let dep_modules: Vec<&str> = alpha
                .dependencies
                .iter()
                .map(|d| d.target_module.as_str())
                .collect();
            assert!(
                dep_modules.contains(&"beta"),
                "production dep on beta should be present: {dep_modules:?}"
            );
            assert!(
                !dep_modules.contains(&"gamma"),
                "test dep on gamma should be excluded without --include-tests: {dep_modules:?}"
            );
        }
    }
}