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
//! Shared Data Structures
//!
//! Types used across analyze and graph modules, extracted to break circular dependencies.

use std::collections::{HashMap, HashSet};
use std::ops::Deref;
use std::path::PathBuf;

#[derive(Debug, Clone)]
pub struct SourceLocation {
    pub file: PathBuf,
    pub line: usize,
    pub symbols: Vec<String>,
    pub module_path: String,
}

/// Workspace crate names, stored in normalized form (hyphens → underscores).
///
/// All insertion paths normalize names, and `contains()` normalizes its input,
/// so lookups are O(1) and callers never need to think about normalization.
#[derive(Debug, Default, Clone)]
pub struct WorkspaceCrates(HashSet<String>);

impl FromIterator<String> for WorkspaceCrates {
    fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> Self {
        Self(iter.into_iter().map(|s| normalize_crate_name(&s)).collect())
    }
}

impl<'a> FromIterator<&'a str> for WorkspaceCrates {
    fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> Self {
        Self(iter.into_iter().map(normalize_crate_name).collect())
    }
}

impl WorkspaceCrates {
    pub fn insert(&mut self, name: &str) -> bool {
        self.0.insert(normalize_crate_name(name))
    }

    /// Check membership, normalizing the input name.
    #[must_use]
    pub fn contains(&self, name: &str) -> bool {
        self.0.contains(&normalize_crate_name(name))
    }

    pub fn iter(&self) -> impl Iterator<Item = &String> {
        self.0.iter()
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

pub(crate) fn normalize_crate_name(name: &str) -> String {
    name.replace('-', "_")
}

/// Crate name → set of module paths (e.g. `{"analyze", "analyze::hir"}`).
#[derive(Debug, Default, Clone)]
pub struct ModulePathMap(HashMap<String, HashSet<String>>);

impl ModulePathMap {
    /// Return the module paths for a crate, or an empty set if unknown.
    #[must_use]
    pub fn get_or_empty(&self, key: &str) -> &HashSet<String> {
        static EMPTY: std::sync::LazyLock<HashSet<String>> = std::sync::LazyLock::new(HashSet::new);
        self.0.get(key).unwrap_or(&EMPTY)
    }
}

impl Deref for ModulePathMap {
    type Target = HashMap<String, HashSet<String>>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl FromIterator<(String, HashSet<String>)> for ModulePathMap {
    fn from_iter<I: IntoIterator<Item = (String, HashSet<String>)>>(iter: I) -> Self {
        Self(iter.into_iter().collect())
    }
}

/// Crate name → set of exported symbol names.
#[derive(Debug, Default, Clone)]
pub struct CrateExportMap(HashMap<String, HashSet<String>>);

impl Deref for CrateExportMap {
    type Target = HashMap<String, HashSet<String>>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl FromIterator<(String, HashSet<String>)> for CrateExportMap {
    fn from_iter<I: IntoIterator<Item = (String, HashSet<String>)>>(iter: I) -> Self {
        Self(iter.into_iter().collect())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DependencyKind {
    Production,
    Test(TestKind),
    Build,
}

impl DependencyKind {
    #[must_use]
    pub fn kind_js(&self) -> &str {
        match self {
            Self::Production => "production",
            Self::Test(_) => "test",
            Self::Build => "build",
        }
    }

    #[must_use]
    pub fn sub_kind_js(&self) -> Option<&str> {
        match self {
            Self::Test(TestKind::Unit) => Some("unit"),
            Self::Test(TestKind::Integration) => Some("integration"),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EdgeContext {
    pub kind: DependencyKind,
    pub features: Vec<String>,
}

impl EdgeContext {
    #[must_use]
    pub fn production() -> Self {
        Self {
            kind: DependencyKind::Production,
            features: vec![],
        }
    }
    #[must_use]
    pub fn test(kind: TestKind) -> Self {
        Self {
            kind: DependencyKind::Test(kind),
            features: vec![],
        }
    }
    #[must_use]
    pub fn build() -> Self {
        Self {
            kind: DependencyKind::Build,
            features: vec![],
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TestKind {
    Unit,
    Integration,
}

#[derive(Debug, Clone)]
pub struct CrateInfo {
    pub name: String,
    pub path: PathBuf,
    pub dependencies: Vec<String>,
    pub dev_dependencies: Vec<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct DependencyRef {
    pub target_crate: String,
    pub target_module: String,
    pub target_item: Option<String>,
    pub source_file: PathBuf,
    pub line: usize,
    pub context: EdgeContext,
}

impl DependencyRef {
    /// Returns full target path: "`crate::module::item`" or "`crate::module`" if no item.
    /// For empty `target_module` (entry-point): "`crate::item`" or just "crate".
    #[must_use]
    pub fn full_target(&self) -> String {
        match (&self.target_item, self.target_module.is_empty()) {
            (Some(item), true) => format!("{}::{}", self.target_crate, item),
            (Some(item), false) => {
                format!("{}::{}::{}", self.target_crate, self.target_module, item)
            }
            (None, true) => self.target_crate.clone(),
            (None, false) => format!("{}::{}", self.target_crate, self.target_module),
        }
    }

    /// Returns module-level target: "`crate::module`" (ignores item).
    /// For empty `target_module` (entry-point): just "crate".
    #[must_use]
    pub fn module_target(&self) -> String {
        if self.target_module.is_empty() {
            self.target_crate.clone()
        } else {
            format!("{}::{}", self.target_crate, self.target_module)
        }
    }

    /// Build a lookup index from an existing slice of dependencies.
    /// Maps `(full_target, kind)` to the position in the slice.
    pub(crate) fn build_seen_index(
        deps: &[DependencyRef],
    ) -> HashMap<(String, DependencyKind), usize> {
        deps.iter()
            .enumerate()
            .map(|(i, d)| ((d.full_target(), d.context.kind), i))
            .collect()
    }

    /// Insert a dependency, deduplicating by `(full_target, kind)`.
    /// If a duplicate exists, merges features into the existing entry.
    pub(crate) fn dedup_push(
        deps: &mut Vec<DependencyRef>,
        seen: &mut HashMap<(String, DependencyKind), usize>,
        dep: DependencyRef,
    ) {
        let key = (dep.full_target(), dep.context.kind);
        if let Some(&idx) = seen.get(&key) {
            deps[idx].context.features.extend(dep.context.features);
        } else {
            seen.insert(key, deps.len());
            deps.push(dep);
        }
    }
}

#[derive(Debug, Clone)]
pub struct ModuleInfo {
    pub name: String,
    pub full_path: String,
    pub children: Vec<ModuleInfo>,
    pub dependencies: Vec<DependencyRef>,
}

#[derive(Debug, Clone)]
pub struct ModuleTree {
    pub root: ModuleInfo,
}

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

    #[test]
    fn test_edgecontext_struct_basics() {
        let ctx = EdgeContext::production();
        assert_eq!(ctx.kind, DependencyKind::Production);
        assert!(ctx.features.is_empty());
        let test_ctx = EdgeContext::test(TestKind::Unit);
        assert_eq!(test_ctx.kind, DependencyKind::Test(TestKind::Unit));
        assert_ne!(ctx, test_ctx);
        let cloned = ctx.clone();
        assert_eq!(ctx, cloned);
    }

    #[test]
    fn test_dependency_kind_js_strings() {
        assert_eq!(DependencyKind::Production.kind_js(), "production");
        assert_eq!(DependencyKind::Production.sub_kind_js(), None);

        assert_eq!(DependencyKind::Test(TestKind::Unit).kind_js(), "test");
        assert_eq!(
            DependencyKind::Test(TestKind::Unit).sub_kind_js(),
            Some("unit")
        );

        assert_eq!(
            DependencyKind::Test(TestKind::Integration).kind_js(),
            "test"
        );
        assert_eq!(
            DependencyKind::Test(TestKind::Integration).sub_kind_js(),
            Some("integration")
        );

        assert_eq!(DependencyKind::Build.kind_js(), "build");
        assert_eq!(DependencyKind::Build.sub_kind_js(), None);
    }

    #[test]
    fn test_dependency_kind_is_copy_and_hash() {
        use std::collections::HashSet;
        let a = DependencyKind::Production;
        let b = a; // Copy
        assert_eq!(a, b);
        let mut set = HashSet::new();
        set.insert(DependencyKind::Test(TestKind::Unit));
        set.insert(DependencyKind::Build);
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn test_dependency_ref_carries_context() {
        let prod_dep = DependencyRef {
            target_crate: "my_crate".to_string(),
            target_module: "graph".to_string(),
            target_item: None,
            source_file: PathBuf::from("src/lib.rs"),
            line: 1,
            context: EdgeContext::production(),
        };
        assert_eq!(prod_dep.context, EdgeContext::production());

        let test_dep = DependencyRef {
            target_crate: "my_crate".to_string(),
            target_module: "graph".to_string(),
            target_item: None,
            source_file: PathBuf::from("src/lib.rs"),
            line: 1,
            context: EdgeContext::test(TestKind::Unit),
        };
        assert_eq!(test_dep.context, EdgeContext::test(TestKind::Unit));

        // Different context → not equal (PartialEq includes context)
        assert_ne!(prod_dep, test_dep);
    }

    #[test]
    fn test_dependency_ref_struct() {
        let dep = DependencyRef {
            target_crate: "my_crate".to_string(),
            target_module: "graph".to_string(),
            target_item: None,
            source_file: PathBuf::from("src/cli.rs"),
            line: 42,
            context: EdgeContext::production(),
        };
        assert_eq!(dep.target_crate, "my_crate");
        assert_eq!(dep.target_module, "graph");
        assert!(dep.target_item.is_none());
        assert_eq!(dep.source_file, PathBuf::from("src/cli.rs"));
        assert_eq!(dep.line, 42);
    }

    #[test]
    fn test_dependency_ref_full_target() {
        let dep = DependencyRef {
            target_crate: "crate".to_string(),
            target_module: "graph".to_string(),
            target_item: Some("build".to_string()),
            source_file: PathBuf::new(),
            line: 1,
            context: EdgeContext::production(),
        };
        assert_eq!(dep.full_target(), "crate::graph::build");
    }

    #[test]
    fn test_dependency_ref_module_target() {
        let dep = DependencyRef {
            target_crate: "crate".to_string(),
            target_module: "graph".to_string(),
            target_item: Some("build".to_string()),
            source_file: PathBuf::new(),
            line: 1,
            context: EdgeContext::production(),
        };
        assert_eq!(dep.module_target(), "crate::graph");
    }

    #[test]
    fn test_dependency_ref_full_target_no_item() {
        let dep = DependencyRef {
            target_crate: "crate".to_string(),
            target_module: "graph".to_string(),
            target_item: None,
            source_file: PathBuf::new(),
            line: 1,
            context: EdgeContext::production(),
        };
        assert_eq!(dep.full_target(), "crate::graph");
    }

    #[test]
    fn test_module_target_empty_module() {
        let dep = DependencyRef {
            target_crate: "crate_b".to_string(),
            target_module: String::new(),
            target_item: None,
            source_file: PathBuf::new(),
            line: 1,
            context: EdgeContext::production(),
        };
        assert_eq!(dep.module_target(), "crate_b");
    }

    #[test]
    fn test_full_target_empty_module_with_item() {
        let dep = DependencyRef {
            target_crate: "crate_b".to_string(),
            target_module: String::new(),
            target_item: Some("Symbol".to_string()),
            source_file: PathBuf::new(),
            line: 1,
            context: EdgeContext::production(),
        };
        assert_eq!(dep.full_target(), "crate_b::Symbol");
    }

    #[test]
    fn test_full_target_empty_module_no_item() {
        let dep = DependencyRef {
            target_crate: "crate_b".to_string(),
            target_module: String::new(),
            target_item: None,
            source_file: PathBuf::new(),
            line: 1,
            context: EdgeContext::production(),
        };
        assert_eq!(dep.full_target(), "crate_b");
    }

    #[test]
    fn test_workspace_crates_normalizes_on_insert() {
        let mut ws = WorkspaceCrates::default();
        ws.insert("my-lib");
        assert!(ws.contains("my_lib"), "should find normalized name");
        assert!(
            ws.contains("my-lib"),
            "should find hyphenated name via normalization"
        );
    }

    #[test]
    fn test_workspace_crates_from_iter_normalizes() {
        let ws: WorkspaceCrates = ["core-utils", "my-lib"].into_iter().collect();
        assert!(ws.contains("core_utils"));
        assert!(ws.contains("core-utils"));
        assert!(ws.contains("my_lib"));
        assert!(ws.contains("my-lib"));
    }

    #[test]
    fn test_workspace_crates_iter_returns_normalized() {
        let ws: WorkspaceCrates = ["core-utils"].into_iter().collect();
        let names: Vec<&str> = ws.iter().map(std::string::String::as_str).collect();
        assert_eq!(names, vec!["core_utils"]);
    }

    #[test]
    fn test_workspace_crates_len_and_is_empty() {
        let empty = WorkspaceCrates::default();
        assert!(empty.is_empty());
        assert_eq!(empty.len(), 0);

        let ws: WorkspaceCrates = ["a", "b"].into_iter().collect();
        assert!(!ws.is_empty());
        assert_eq!(ws.len(), 2);
    }

    #[test]
    fn test_module_info_has_dependency_refs() {
        let module = ModuleInfo {
            name: "cli".to_string(),
            full_path: "crate::cli".to_string(),
            children: vec![],
            dependencies: vec![DependencyRef {
                target_crate: "crate".to_string(),
                target_module: "graph".to_string(),
                target_item: None,
                source_file: PathBuf::from("src/cli.rs"),
                line: 5,
                context: EdgeContext::production(),
            }],
        };
        assert!(
            module
                .dependencies
                .iter()
                .any(|d| d.module_target() == "crate::graph")
        );
    }
}