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
//! HIR-based module analysis using rust-analyzer.
//!
//! Only `FeatureConfig` is always available. All HIR functions require `feature = "hir"`.

// FeatureConfig is always available (no ra_ap_* dependency)
#[allow(clippy::struct_excessive_bools)] // CLI flags map 1:1 to fields
#[derive(Debug, Clone, Default)]
pub struct FeatureConfig {
    pub features: Vec<String>,
    pub all_features: bool,
    pub no_default_features: bool,
    pub include_tests: bool,
    pub debug: bool,
}

#[cfg(feature = "hir")]
use {
    super::use_parser::{ResolutionContext, parse_workspace_dependencies_from_source},
    crate::model::normalize_crate_name,
    crate::model::{
        CrateExportMap, CrateInfo, DependencyRef, ModuleInfo, ModulePathMap, ModuleTree,
        WorkspaceCrates,
    },
    anyhow::{Context, Result},
    ra_ap_cfg::{CfgAtom, CfgDiff},
    ra_ap_hir as hir, ra_ap_ide as ide, ra_ap_load_cargo as load_cargo, ra_ap_paths as paths,
    ra_ap_project_model as project_model,
    std::collections::HashSet,
    std::path::{Path, PathBuf},
};

/// Creates a CargoConfig with feature and cfg overrides.
/// By default, cfg(test) is disabled.
#[cfg(feature = "hir")]
pub fn cargo_config_with_features(config: &FeatureConfig) -> project_model::CargoConfig {
    let features = if config.all_features {
        project_model::CargoFeatures::All
    } else if config.features.is_empty() && !config.no_default_features {
        project_model::CargoFeatures::default()
    } else {
        project_model::CargoFeatures::Selected {
            features: config.features.clone(),
            no_default_features: config.no_default_features,
        }
    };

    // Build enable list: features as KeyValue atoms, optionally test flag
    let mut enable_cfgs: Vec<CfgAtom> = config
        .features
        .iter()
        .map(|f| CfgAtom::KeyValue {
            key: hir::Symbol::intern("feature"),
            value: hir::Symbol::intern(f),
        })
        .collect();

    let include_test = config.include_tests;
    if include_test {
        enable_cfgs.push(CfgAtom::Flag(hir::Symbol::intern("test")));
    }

    // Build disable list: test flag unless explicitly enabled
    let disable_cfgs = if include_test {
        Vec::new()
    } else {
        vec![CfgAtom::Flag(hir::Symbol::intern("test"))]
    };

    let cfg_overrides = project_model::CfgOverrides {
        global: CfgDiff::new(enable_cfgs, disable_cfgs),
        selective: Default::default(),
    };

    project_model::CargoConfig {
        features,
        cfg_overrides,
        sysroot: Some(project_model::RustLibSource::Discover),
        ..Default::default()
    }
}

/// Loads the entire workspace into rust-analyzer once.
/// Returns the AnalysisHost and VFS for reuse across multiple crate analyses.
#[cfg(feature = "hir")]
pub fn load_workspace_hir(
    manifest_path: &Path,
    feature_config: &FeatureConfig,
) -> Result<(ide::AnalysisHost, ra_ap_vfs::Vfs)> {
    let project_path = manifest_path.canonicalize()?;
    let project_path = dunce::simplified(&project_path).to_path_buf();

    // Build cargo config with feature and cfg overrides
    let cargo_config = cargo_config_with_features(feature_config);

    // Load config - minimal for faster loading
    let load_config = load_cargo::LoadCargoConfig {
        load_out_dirs_from_check: false,
        prefill_caches: false,
        with_proc_macro_server: load_cargo::ProcMacroServerChoice::None,
        proc_macro_processes: 0,
    };

    // Discover project manifest - convert PathBuf -> Utf8PathBuf -> AbsPathBuf
    let utf8_path = paths::Utf8PathBuf::from_path_buf(project_path.clone())
        .map_err(|_| anyhow::anyhow!("Invalid UTF-8 path"))?;
    let root = paths::AbsPathBuf::assert(utf8_path);
    let manifest = project_model::ProjectManifest::discover_single(root.as_path())?;

    // Load project workspace
    let project_workspace =
        project_model::ProjectWorkspace::load(manifest, &cargo_config, &|_| {})?;

    // Load into analysis database
    let (db, vfs, _proc_macro) =
        load_cargo::load_workspace(project_workspace, &Default::default(), &load_config)?;

    let host = ide::AnalysisHost::with_database(db);
    Ok((host, vfs))
}

/// Finds a specific crate in an already-loaded workspace by matching its path.
#[cfg(feature = "hir")]
pub(crate) fn find_crate_in_workspace(
    crate_info: &CrateInfo,
    host: &ide::AnalysisHost,
    vfs: &ra_ap_vfs::Vfs,
) -> Result<hir::Crate> {
    let crate_path = crate_info.path.canonicalize()?;
    let crate_path = dunce::simplified(&crate_path).to_path_buf();
    let crate_utf8 = paths::Utf8PathBuf::from_path_buf(crate_path)
        .map_err(|_| anyhow::anyhow!("Invalid UTF-8 path"))?;
    let crate_dir = paths::AbsPathBuf::assert(crate_utf8);

    let crates = hir::Crate::all(host.raw_database());
    crates
        .into_iter()
        .find(|k| {
            let root_file = k.root_file(host.raw_database());
            let vfs_path = vfs.file_path(root_file);
            vfs_path
                .as_path()
                .map(|p| p.starts_with(&crate_dir))
                .unwrap_or(false)
        })
        .context(format!(
            "Crate '{}' not found in loaded workspace",
            crate_info.name
        ))
}

/// Resolves a module's display name and full path.
/// Root modules use the crate's display name; child modules use their declared name.
#[cfg(feature = "hir")]
fn resolve_module_name_and_path(
    module: hir::Module,
    db: &ide::RootDatabase,
    parent_path: &str,
) -> (String, String) {
    let name = if module.is_crate_root(db) {
        module
            .krate(db)
            .display_name(db)
            .map(|n| normalize_crate_name(n.as_str()))
            .unwrap_or_else(|| "crate".to_string())
    } else {
        module
            .name(db)
            .map(|n| n.as_str().to_string())
            .unwrap_or_else(|| "<anonymous>".to_string())
    };

    let full_path = if module.is_crate_root(db) {
        parent_path.to_string()
    } else {
        format!("{}::{}", parent_path, name)
    };

    (name, full_path)
}

/// Collects all module paths from hir::Module tree (lightweight, no dependency analysis).
/// Returns relative paths without crate prefix, e.g. {"analyze", "analyze::use_parser"}.
#[cfg(feature = "hir")]
pub(crate) fn collect_hir_module_paths(
    module: hir::Module,
    db: &ide::RootDatabase,
    parent_path: &str,
    crate_name: &str,
) -> HashSet<String> {
    let mut result = HashSet::new();
    collect_module_paths_recursive(module, db, parent_path, crate_name, &mut result);
    result
}

#[cfg(feature = "hir")]
fn collect_module_paths_recursive(
    module: hir::Module,
    db: &ide::RootDatabase,
    parent_path: &str,
    crate_name: &str,
    result: &mut HashSet<String>,
) {
    let (_name, full_path) = resolve_module_name_and_path(module, db, parent_path);

    // Add relative path (without crate prefix) for non-root modules
    if !module.is_crate_root(db) {
        let prefix = format!("{}::", crate_name);
        if let Some(relative) = full_path.strip_prefix(&prefix) {
            result.insert(relative.to_string());
        }
    }

    for decl in module.declarations(db) {
        if let hir::ModuleDef::Module(child_module) = decl {
            collect_module_paths_recursive(child_module, db, &full_path, crate_name, result);
        }
    }
}

/// Analyzes the module hierarchy of a crate using rust-analyzer's HIR.
/// The `host` and `vfs` should be obtained from `load_workspace_hir()`.
/// `workspace_crates` should contain all workspace crate names for inter-crate dependency detection.
#[cfg(feature = "hir")]
pub fn analyze_modules(
    crate_info: &CrateInfo,
    host: &ide::AnalysisHost,
    vfs: &ra_ap_vfs::Vfs,
    workspace_crates: &WorkspaceCrates,
    all_module_paths: &ModulePathMap,
    crate_exports: &CrateExportMap,
    external_crate_names: &std::collections::HashMap<String, String>,
) -> Result<ModuleTree> {
    // Find crate in already-loaded workspace
    let krate = find_crate_in_workspace(crate_info, host, vfs)?;
    let db = host.raw_database();

    // Walk module tree starting from crate root
    let root_module = krate.root_module(db);
    let crate_name = &crate_info.name;
    // Use actual crate name (normalized) as root path for inter-crate dependency resolution
    let normalized_crate_name = normalize_crate_name(crate_name);
    let ctx = HirWalkContext {
        db,
        vfs,
        crate_root: &crate_info.path,
        crate_name,
        workspace_crates,
        all_module_paths,
        crate_exports,
        external_crate_names,
    };
    let root = walk_module(root_module, &normalized_crate_name, &ctx);

    Ok(ModuleTree { root })
}

/// Invariant parameters shared across the recursive HIR module walk.
#[cfg(feature = "hir")]
struct HirWalkContext<'a> {
    db: &'a ide::RootDatabase,
    vfs: &'a ra_ap_vfs::Vfs,
    crate_root: &'a Path,
    crate_name: &'a str,
    workspace_crates: &'a WorkspaceCrates,
    all_module_paths: &'a ModulePathMap,
    crate_exports: &'a CrateExportMap,
    external_crate_names: &'a std::collections::HashMap<String, String>,
}

#[cfg(feature = "hir")]
fn walk_module(module: hir::Module, parent_path: &str, ctx: &HirWalkContext) -> ModuleInfo {
    let (name, full_path) = resolve_module_name_and_path(module, ctx.db, parent_path);

    // 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("");

    let dependencies = extract_module_dependencies(module, current_module_path, ctx);

    let children: Vec<ModuleInfo> = module
        .declarations(ctx.db)
        .into_iter()
        .filter_map(|decl| {
            if let hir::ModuleDef::Module(child_module) = decl {
                Some(walk_module(child_module, &full_path, ctx))
            } else {
                None
            }
        })
        .collect();

    ModuleInfo {
        name,
        full_path,
        children,
        dependencies,
    }
}

/// Extract module-level dependencies by parsing use statements from source
#[cfg(feature = "hir")]
fn extract_module_dependencies(
    module: hir::Module,
    current_module_path: &str,
    ctx: &HirWalkContext,
) -> Vec<DependencyRef> {
    // Get the source file for this module
    let source = module.definition_source(ctx.db);
    let editioned_file_id = source.file_id.original_file(ctx.db);
    let file_id = editioned_file_id.file_id(ctx.db);

    // Get file path from VFS and read from disk
    let vfs_path = ctx.vfs.file_path(file_id);
    let Some(abs_path) = vfs_path.as_path() else {
        return Vec::new();
    };
    // Make path relative to crate root
    let abs_path_buf = PathBuf::from(abs_path.as_str());
    let source_file = abs_path_buf
        .strip_prefix(ctx.crate_root)
        .map(|p| p.to_path_buf())
        .unwrap_or(abs_path_buf);
    // Graceful degradation: rust-analyzer already parsed this file successfully,
    // so read errors here are rare edge cases (file deleted mid-run, permissions).
    // Missing deps are acceptable - the module still appears, just without edges.
    let source_text = match std::fs::read_to_string(abs_path.as_str()) {
        Ok(s) => s,
        Err(_) => return Vec::new(),
    };

    let empty_reexport_map = super::use_parser::ReExportMap::default();
    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: &empty_reexport_map,
        external_crate_names: ctx.external_crate_names,
    };
    parse_workspace_dependencies_from_source(&source_text, &res_ctx)
}

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

    #[test]
    fn test_feature_config_default() {
        let config = FeatureConfig::default();
        assert!(config.features.is_empty());
        assert!(!config.all_features);
        assert!(!config.include_tests);
        assert!(!config.no_default_features);
    }

    #[test]
    fn test_feature_config_no_default_features() {
        let config = FeatureConfig {
            no_default_features: true,
            ..Default::default()
        };
        assert!(config.no_default_features);
    }
}

#[cfg(all(test, feature = "hir"))]
mod hir_tests {
    use super::*;
    use ra_ap_project_model as project_model;

    #[test]
    fn test_cfg_overrides_include_features() {
        let config = FeatureConfig {
            features: vec!["server".to_string()],
            ..Default::default()
        };
        let cargo_config = cargo_config_with_features(&config);

        let diff_str = format!("{}", cargo_config.cfg_overrides.global);
        assert!(
            diff_str.contains("feature") && diff_str.contains("server"),
            "Expected feature = \"server\" in cfg_overrides, got: {}",
            diff_str
        );
    }

    #[test]
    fn test_cargo_config_default_excludes_test() {
        let config = FeatureConfig::default();
        let cargo_config = cargo_config_with_features(&config);

        let diff_str = format!("{}", cargo_config.cfg_overrides.global);
        assert!(
            diff_str.contains("disable") && diff_str.contains("test"),
            "Expected cfg(test) to be disabled, got: {}",
            diff_str
        );
    }

    #[test]
    fn test_cargo_config_includes_test_when_flag_set() {
        let config = FeatureConfig {
            include_tests: true,
            ..Default::default()
        };
        let cargo_config = cargo_config_with_features(&config);

        let diff_str = format!("{}", cargo_config.cfg_overrides.global);
        assert!(
            diff_str.contains("enable") && diff_str.contains("test"),
            "Expected cfg(test) to be enabled, got: {}",
            diff_str
        );
    }

    #[test]
    fn test_cargo_config_selected_features() {
        let config = FeatureConfig {
            features: vec!["web".to_string()],
            ..Default::default()
        };
        let cargo_config = cargo_config_with_features(&config);

        match cargo_config.features {
            project_model::CargoFeatures::Selected { features, .. } => {
                assert_eq!(features, vec!["web"]);
            }
            _ => panic!("expected Selected"),
        }
    }

    #[test]
    fn test_cargo_features_no_default() {
        let config = FeatureConfig {
            features: vec!["x".to_string()],
            no_default_features: true,
            ..Default::default()
        };
        let cargo_config = cargo_config_with_features(&config);

        match cargo_config.features {
            project_model::CargoFeatures::Selected {
                features,
                no_default_features,
            } => {
                assert_eq!(features, vec!["x"]);
                assert!(no_default_features, "no_default_features should be true");
            }
            _ => panic!("expected Selected"),
        }
    }

    mod smoke_tests {
        use super::*;
        use crate::analyze::workspace::analyze_workspace;

        #[test]
        #[ignore] // Smoke test - requires rust-analyzer (~30s)
        fn test_collect_hir_module_paths() {
            let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
            let crates = analyze_workspace(&manifest, &FeatureConfig::default())
                .expect("should analyze workspace");
            let cargo_arc = crates.iter().find(|c| c.name == "cargo-arc").unwrap();

            let (host, vfs) = load_workspace_hir(&manifest, &FeatureConfig::default())
                .expect("should load workspace");
            let krate = find_crate_in_workspace(cargo_arc, &host, &vfs).expect("should find crate");
            let db = host.raw_database();
            let crate_name = normalize_crate_name(&cargo_arc.name);
            let paths =
                collect_hir_module_paths(krate.root_module(db), db, &crate_name, &crate_name);

            assert!(
                paths.contains("analyze"),
                "should contain 'analyze', found: {:?}",
                paths
            );
            assert!(
                paths.contains("analyze::hir"),
                "should contain 'analyze::hir', found: {:?}",
                paths
            );
            assert!(
                paths.contains("analyze::use_parser"),
                "should contain 'analyze::use_parser', found: {:?}",
                paths
            );
            // Must NOT contain crate prefix
            assert!(
                !paths.iter().any(|p| p.starts_with("cargo_arc::")),
                "paths should be relative (no crate prefix), found: {:?}",
                paths
            );
        }

        #[test]
        #[ignore] // Smoke test - requires rust-analyzer (~30s)
        fn test_analyze_modules_self() {
            let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
            let crates = analyze_workspace(&manifest, &FeatureConfig::default())
                .expect("should analyze workspace");
            let workspace_crates: WorkspaceCrates = crates.iter().map(|c| c.name.clone()).collect();
            let cargo_arc = crates.iter().find(|c| c.name == "cargo-arc").unwrap();

            let (host, vfs) = load_workspace_hir(&manifest, &FeatureConfig::default())
                .expect("should load workspace");
            let tree = analyze_modules(
                cargo_arc,
                &host,
                &vfs,
                &workspace_crates,
                &ModulePathMap::default(),
                &CrateExportMap::default(),
            )
            .expect("should analyze modules");

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

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

        #[test]
        #[ignore] // Smoke test - requires rust-analyzer (~30s)
        fn test_module_full_path() {
            let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
            let crates = analyze_workspace(&manifest, &FeatureConfig::default())
                .expect("should analyze workspace");
            let workspace_crates: WorkspaceCrates = crates.iter().map(|c| c.name.clone()).collect();
            let cargo_arc = crates.iter().find(|c| c.name == "cargo-arc").unwrap();

            let (host, vfs) = load_workspace_hir(&manifest, &FeatureConfig::default())
                .expect("should load workspace");
            let tree = analyze_modules(
                cargo_arc,
                &host,
                &vfs,
                &workspace_crates,
                &ModulePathMap::default(),
                &CrateExportMap::default(),
            )
            .expect("should analyze modules");

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

            let analyze_module = tree
                .root
                .children
                .iter()
                .find(|m| m.name == "analyze")
                .expect("should find analyze module");
            assert_eq!(analyze_module.full_path, "cargo_arc::analyze");
        }

        #[test]
        #[ignore] // Smoke test - requires rust-analyzer (~30s)
        fn test_module_dependencies() {
            let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
            let crates = analyze_workspace(&manifest, &FeatureConfig::default())
                .expect("should analyze workspace");
            let workspace_crates: WorkspaceCrates = crates.iter().map(|c| c.name.clone()).collect();
            let cargo_arc = crates.iter().find(|c| c.name == "cargo-arc").unwrap();

            let (host, vfs) = load_workspace_hir(&manifest, &FeatureConfig::default())
                .expect("should load workspace");
            let tree = analyze_modules(
                cargo_arc,
                &host,
                &vfs,
                &workspace_crates,
                &ModulePathMap::default(),
                &CrateExportMap::default(),
            )
            .expect("should analyze modules");

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

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

            let render_module = tree
                .root
                .children
                .iter()
                .find(|m| m.name == "render")
                .expect("should find render module");
            assert!(
                render_module
                    .dependencies
                    .iter()
                    .any(|d| d.module_target() == "cargo_arc::layout"),
                "render should depend on layout, found: {:?}",
                render_module.dependencies
            );
        }
    }
}