crawk 0.3.0

Dependency crawler for Rust. It crawls so you don't have to untangle
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
use syn::visit::Visit;
use syn::{ItemMod, ItemUse, UseTree};

use tracing::debug;

use crate::constants::{PATH_QUALIFIER_CRATE, PATH_QUALIFIER_SELF, PATH_QUALIFIER_SUPER};
use crate::reference::{GroupItem, PathPrefix, TypeReference};
use crate::utils::has_cfg_test;

/// Resolves relative paths (`self::`, `super::`) to absolute paths (`crate::`).
///
/// Given the current module path, converts relative references to absolute ones:
/// - `self::foo` in module `a::b` becomes `crate::a::b::foo`
/// - `super::foo` in module `a::b` becomes `crate::a::foo`
/// - `super::super::foo` in module `a::b::c` becomes `crate::a::foo`
/// - `crate::foo` stays as `crate::foo`
pub(crate) fn resolve_reference(reference: TypeReference, module_path: &[String]) -> TypeReference {
    match reference.prefix() {
        PathPrefix::SelfModule => {
            let mut new_segments = module_path.to_vec();
            new_segments.extend(reference.segments().iter().cloned());
            reference.with_segments_and_prefix(new_segments, PathPrefix::Crate)
        }
        PathPrefix::Super(levels) => {
            if module_path.len() >= levels {
                let parent_depth = module_path.len() - levels;
                let mut new_segments = module_path[..parent_depth].to_vec();
                new_segments.extend(reference.segments().iter().cloned());
                reference.with_segments_and_prefix(new_segments, PathPrefix::Crate)
            } else {
                // Can't go up that many levels, leave as-is
                debug!(
                    "Cannot resolve super::{} — {levels} levels from module {module_path:?}",
                    reference.segments().join("::")
                );
                reference
            }
        }
        PathPrefix::Crate | PathPrefix::None => reference,
    }
}

/// Type references collected from a single module, grouped by syntactic role.
///
/// Each category represents a distinct kind of dependency signal:
/// - `use_statements` — explicit imports (`use crate::foo::Bar`)
/// - `type_refs` — type-level dependencies (annotations, trait bounds, impl traits)
/// - `value_refs` — value-level dependencies (calls, struct construction, patterns)
/// - `macro_calls` — macro invocations (semantically opaque to static analysis)
pub(super) struct CollectedReferences {
    pub use_statements: Vec<TypeReference>,
    pub type_refs: Vec<TypeReference>,
    pub value_refs: Vec<TypeReference>,
    pub macro_calls: Vec<TypeReference>,
}

impl CollectedReferences {
    /// Creates a new empty [`CollectedReferences`] with all categories initialized.
    const fn new() -> Self {
        Self {
            use_statements: Vec::new(),
            type_refs: Vec::new(),
            value_refs: Vec::new(),
            macro_calls: Vec::new(),
        }
    }

    /// Iterates over all references in a consistent order.
    pub(super) fn all(&self) -> impl Iterator<Item = &TypeReference> {
        self.use_statements
            .iter()
            .chain(self.type_refs.iter())
            .chain(self.value_refs.iter())
            .chain(self.macro_calls.iter())
    }
}

/// Visitor for extracting type references from module AST.
pub(super) struct ModuleVisitor {
    /// Module name for filtering and identification (e.g., "foo::bar").
    /// Used to match against nested module declarations. Empty string means analyze all modules.
    module_name: String,

    /// Module path as segments for resolving relative paths (e.g., `["foo", "bar"]`).
    /// Used to convert `self::` and `super::` references to absolute `crate::` paths.
    module_path: Vec<String>,

    /// Collected type references found in this module, grouped by syntactic role.
    /// All relative paths are resolved to absolute paths before being added.
    pub(super) references: CollectedReferences,

    /// Track if we're currently visiting inside a test module.
    /// Updated as we traverse nested modules to filter test-only references.
    in_test_module: bool,
}

impl ModuleVisitor {
    /// Creates a new [`ModuleVisitor`] scoped to `module_name`.
    ///
    /// Pass an empty string to visit all modules without filtering.
    /// The module path for relative-reference resolution is derived from `module_name`
    /// by splitting on `::`.
    pub(super) fn new(module_name: impl Into<String>) -> Self {
        let module_name = module_name.into();
        let module_path: Vec<String> = if module_name.is_empty() {
            vec![]
        } else {
            module_name.split("::").map(String::from).collect()
        };

        Self {
            module_name,
            module_path,
            references: CollectedReferences::new(),
            in_test_module: false,
        }
    }

    /// Checks if a syn::Path is an internal crate reference.
    /// Returns true if the path starts with crate::, self::, or super::.
    fn is_internal_path(path: &syn::Path) -> bool {
        path.segments.first().is_some_and(|first_segment| {
            let ident = first_segment.ident.to_string();
            matches!(
                ident.as_str(),
                PATH_QUALIFIER_CRATE | PATH_QUALIFIER_SELF | PATH_QUALIFIER_SUPER
            )
        })
    }

    /// Builds a TypeReference from a syn::Path if it's an internal crate reference.
    fn build_reference(&self, path: &syn::Path) -> Option<TypeReference> {
        if !Self::is_internal_path(path) {
            return None;
        }

        let mut segments = Vec::new();
        let mut path_prefix = PathPrefix::None;

        for (i, segment) in path.segments.iter().enumerate() {
            let ident = segment.ident.to_string();

            // Handle special prefixes at the start
            if i == 0 {
                match ident.as_str() {
                    PATH_QUALIFIER_CRATE => {
                        path_prefix = PathPrefix::Crate;
                        continue;
                    }
                    PATH_QUALIFIER_SELF => {
                        path_prefix = PathPrefix::SelfModule;
                        continue;
                    }
                    PATH_QUALIFIER_SUPER => {
                        path_prefix = PathPrefix::Super(1);
                        continue;
                    }
                    _ => {}
                }
            } else if ident == PATH_QUALIFIER_SUPER {
                // Handle chained super::
                let levels = match path_prefix {
                    PathPrefix::Super(n) => n + 1,
                    _ => 1,
                };
                path_prefix = PathPrefix::Super(levels);
                continue;
            }

            segments.push(ident);
        }

        if segments.is_empty() {
            return None;
        }

        Some(resolve_reference(
            TypeReference::new(segments).with_prefix(path_prefix),
            &self.module_path,
        ))
    }

    /// Recursively walks a `use` tree and pushes resolved [`TypeReference`]s into
    /// `self.references.use_statements`.
    ///
    /// `prefix` accumulates path segments seen so far; `path_prefix` tracks any
    /// leading keyword (`crate`, `self`, `super`) encountered during traversal.
    fn process_use_tree(&mut self, tree: &UseTree, prefix: Vec<String>, path_prefix: PathPrefix) {
        match tree {
            UseTree::Path(p) => {
                let ident = p.ident.to_string();

                // Check for special prefixes at the start
                let (new_prefix, new_path_prefix) = if prefix.is_empty() {
                    match ident.as_str() {
                        PATH_QUALIFIER_CRATE => (Vec::new(), PathPrefix::Crate),
                        PATH_QUALIFIER_SELF => (Vec::new(), PathPrefix::SelfModule),
                        PATH_QUALIFIER_SUPER => {
                            let levels = match path_prefix {
                                PathPrefix::Super(n) => n + 1,
                                _ => 1,
                            };
                            (Vec::new(), PathPrefix::Super(levels))
                        }
                        _ => {
                            let mut new_prefix = prefix;
                            new_prefix.push(ident);
                            (new_prefix, path_prefix)
                        }
                    }
                } else if ident == PATH_QUALIFIER_SUPER {
                    // Handle chained super:: in the middle of path
                    let levels = match path_prefix {
                        PathPrefix::Super(n) => n + 1,
                        _ => 1,
                    };
                    (prefix, PathPrefix::Super(levels))
                } else {
                    let mut new_prefix = prefix;
                    new_prefix.push(ident);
                    (new_prefix, path_prefix)
                };

                self.process_use_tree(&p.tree, new_prefix, new_path_prefix);
            }

            UseTree::Name(n) => {
                let mut segments = prefix;
                segments.push(n.ident.to_string());

                let reference = resolve_reference(
                    TypeReference::new(segments).with_prefix(path_prefix),
                    &self.module_path,
                );
                self.references.use_statements.push(reference);
            }

            UseTree::Rename(r) => {
                let mut segments = prefix;
                segments.push(r.ident.to_string());

                let reference = resolve_reference(
                    TypeReference::new(segments)
                        .with_prefix(path_prefix)
                        .with_alias(r.rename.to_string()),
                    &self.module_path,
                );
                self.references.use_statements.push(reference);
            }

            UseTree::Glob(_) => {
                let reference = resolve_reference(
                    TypeReference::new(prefix)
                        .with_prefix(path_prefix)
                        .with_glob(),
                    &self.module_path,
                );
                self.references.use_statements.push(reference);
            }

            UseTree::Group(g) => {
                let group_items = self.convert_group(&g.items);

                let reference = resolve_reference(
                    TypeReference::new(prefix)
                        .with_prefix(path_prefix)
                        .with_group(group_items),
                    &self.module_path,
                );
                self.references.use_statements.push(reference);
            }
        }
    }

    fn convert_group(
        &self,
        items: &syn::punctuated::Punctuated<UseTree, syn::token::Comma>,
    ) -> Vec<GroupItem> {
        items
            .iter()
            .map(|item| self.convert_use_tree(item))
            .collect()
    }

    fn convert_use_tree(&self, tree: &UseTree) -> GroupItem {
        match tree {
            UseTree::Name(n) => {
                let ident = n.ident.to_string();
                if ident == PATH_QUALIFIER_SELF {
                    GroupItem::SelfItem { alias: None }
                } else {
                    GroupItem::Simple(ident)
                }
            }

            UseTree::Rename(r) => {
                let ident = r.ident.to_string();
                let alias = r.rename.to_string();
                if ident == PATH_QUALIFIER_SELF {
                    GroupItem::SelfItem { alias: Some(alias) }
                } else {
                    GroupItem::Aliased { name: ident, alias }
                }
            }

            UseTree::Glob(_) => GroupItem::Glob,

            UseTree::Path(p) => {
                let mut prefix = vec![p.ident.to_string()];
                let mut current = &*p.tree;

                // Flatten nested paths
                while let UseTree::Path(inner) = current {
                    prefix.push(inner.ident.to_string());
                    current = &*inner.tree;
                }

                match current {
                    UseTree::Group(g) => GroupItem::Nested {
                        prefix,
                        items: self.convert_group(&g.items),
                    },
                    UseTree::Name(n) => {
                        prefix.push(n.ident.to_string());
                        GroupItem::Nested {
                            prefix,
                            items: Vec::new(),
                        }
                    }
                    UseTree::Rename(r) => {
                        prefix.push(r.ident.to_string());
                        GroupItem::Nested {
                            prefix: prefix[..prefix.len() - 1].to_vec(),
                            items: vec![GroupItem::Aliased {
                                name: r.ident.to_string(),
                                alias: r.rename.to_string(),
                            }],
                        }
                    }
                    UseTree::Glob(_) => GroupItem::Nested {
                        prefix,
                        items: vec![GroupItem::Glob],
                    },
                    UseTree::Path(_) => GroupItem::Nested {
                        prefix,
                        items: Vec::new(),
                    },
                }
            }

            UseTree::Group(g) => GroupItem::Nested {
                prefix: Vec::new(),
                items: self.convert_group(&g.items),
            },
        }
    }
}

impl<'ast> Visit<'ast> for ModuleVisitor {
    fn visit_item_mod(&mut self, i: &'ast ItemMod) {
        let was_in_test = self.in_test_module;

        // Check if this module is a test module (has #[cfg(test)] attribute)
        if has_cfg_test(&i.attrs) {
            self.in_test_module = true;
        }

        // Check if this module matches the target module or is on the path to it
        let module_ident = i.ident.to_string();
        let should_visit = if self.module_name.is_empty() {
            // No filter, visit all modules
            true
        } else if self.module_name == module_ident {
            // Exact match
            true
        } else if self.module_name.contains("::") {
            // For nested modules like "foo::bar::baz", check if this module
            // is on the path (e.g., ident is "foo" and module_name starts with "foo::")
            // or if this module is the final segment
            self.module_name.split("::").any(|seg| seg == module_ident)
                || self.module_name.ends_with(&format!("::{module_ident}"))
        } else {
            // Single-segment module name, check exact match
            self.module_name == module_ident
        };

        if !should_visit {
            debug!(
                "Skipping module '{module_ident}' (filter: '{}')",
                self.module_name
            );
        }
        if should_visit && let Some((_, items)) = &i.content {
            for item in items {
                self.visit_item(item);
            }
        }

        // Restore previous test module state
        self.in_test_module = was_in_test;
    }

    fn visit_item_use(&mut self, node: &'ast ItemUse) {
        if !self.in_test_module {
            self.process_use_tree(&node.tree, Vec::new(), PathPrefix::None);
        }
    }

    /// Visit expression paths - captures paths in expressions like `crate::foo::bar()`
    fn visit_expr_path(&mut self, node: &'ast syn::ExprPath) {
        if !self.in_test_module {
            if let Some(r) = self.build_reference(&node.path) {
                self.references.value_refs.push(r);
            }
        }
        syn::visit::visit_expr_path(self, node);
    }

    /// Visit type paths - captures type annotations like `let x: crate::Foo`
    fn visit_type_path(&mut self, node: &'ast syn::TypePath) {
        if !self.in_test_module {
            if let Some(r) = self.build_reference(&node.path) {
                self.references.type_refs.push(r);
            }

            // Also check the qself if present (e.g., <crate::Foo as Trait>::Item)
            if let Some(qself) = &node.qself {
                syn::visit::visit_type(self, &qself.ty);
            }
        }
        syn::visit::visit_type_path(self, node);
    }

    /// Visit pattern structs - captures struct patterns in match arms
    fn visit_pat_struct(&mut self, node: &'ast syn::PatStruct) {
        if !self.in_test_module {
            if let Some(r) = self.build_reference(&node.path) {
                self.references.value_refs.push(r);
            }
        }
        syn::visit::visit_pat_struct(self, node);
    }

    /// Visit pattern tuple structs - captures tuple struct patterns
    fn visit_pat_tuple_struct(&mut self, node: &'ast syn::PatTupleStruct) {
        if !self.in_test_module {
            if let Some(r) = self.build_reference(&node.path) {
                self.references.value_refs.push(r);
            }
        }
        syn::visit::visit_pat_tuple_struct(self, node);
    }

    /// Visit struct expressions - captures struct literal construction
    fn visit_expr_struct(&mut self, node: &'ast syn::ExprStruct) {
        if !self.in_test_module {
            if let Some(r) = self.build_reference(&node.path) {
                self.references.value_refs.push(r);
            }
        }
        syn::visit::visit_expr_struct(self, node);
    }

    /// Visit trait bounds - captures trait bounds in generics
    fn visit_trait_bound(&mut self, node: &'ast syn::TraitBound) {
        if !self.in_test_module {
            if let Some(r) = self.build_reference(&node.path) {
                self.references.type_refs.push(r);
            }
        }
        syn::visit::visit_trait_bound(self, node);
    }

    /// Visit impl items - captures impl blocks
    fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
        if !self.in_test_module {
            // Check the trait being implemented (if any)
            if let Some((_, trait_path, _)) = &node.trait_ {
                if let Some(r) = self.build_reference(trait_path) {
                    self.references.type_refs.push(r);
                }
            }
        }
        syn::visit::visit_item_impl(self, node);
    }

    /// Visit macro invocations - captures macro paths
    fn visit_macro(&mut self, node: &'ast syn::Macro) {
        if !self.in_test_module {
            if let Some(r) = self.build_reference(&node.path) {
                self.references.macro_calls.push(r);
            }
        }
        syn::visit::visit_macro(self, node);
    }
}

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

    #[test]
    fn test_resolve_self_prefix() {
        let r = TypeReference::new(["foo", "Bar"]).with_self_prefix();
        let module_path = vec!["utils".to_owned(), "parser".to_owned()];
        let resolved = resolve_reference(r, &module_path);

        assert_eq!(resolved.prefix(), PathPrefix::Crate);
        assert_eq!(resolved.segments(), &["utils", "parser", "foo", "Bar"]);
        assert_eq!(resolved.to_path_string(), "crate::utils::parser::foo::Bar");
    }

    #[test]
    fn test_resolve_self_prefix_at_crate_root() {
        let r = TypeReference::new(["foo", "Bar"]).with_self_prefix();
        let module_path: Vec<String> = vec![];
        let resolved = resolve_reference(r, &module_path);

        assert_eq!(resolved.prefix(), PathPrefix::Crate);
        assert_eq!(resolved.segments(), &["foo", "Bar"]);
        assert_eq!(resolved.to_path_string(), "crate::foo::Bar");
    }

    #[test]
    fn test_resolve_super_single_level() {
        let r = TypeReference::new(["sibling", "Type"]).with_super(1);
        let module_path = vec!["parent".to_owned(), "child".to_owned()];
        let resolved = resolve_reference(r, &module_path);

        assert_eq!(resolved.prefix(), PathPrefix::Crate);
        assert_eq!(resolved.segments(), &["parent", "sibling", "Type"]);
        assert_eq!(resolved.to_path_string(), "crate::parent::sibling::Type");
    }

    #[test]
    fn test_resolve_super_multiple_levels() {
        let r = TypeReference::new(["ancestor", "Type"]).with_super(2);
        let module_path = vec!["a".to_owned(), "b".to_owned(), "c".to_owned()];
        let resolved = resolve_reference(r, &module_path);

        assert_eq!(resolved.prefix(), PathPrefix::Crate);
        assert_eq!(resolved.segments(), &["a", "ancestor", "Type"]);
        assert_eq!(resolved.to_path_string(), "crate::a::ancestor::Type");
    }

    #[test]
    fn test_resolve_super_at_crate_root() {
        let r = TypeReference::new(["foo", "Bar"]).with_super(1);
        let module_path: Vec<String> = vec![];
        let resolved = resolve_reference(r, &module_path);

        assert_eq!(resolved.prefix(), PathPrefix::Super(1));
        assert_eq!(resolved.segments(), &["foo", "Bar"]);
    }

    #[test]
    fn test_resolve_super_too_many_levels() {
        let r = TypeReference::new(["foo", "Bar"]).with_super(5);
        let module_path = vec!["a".to_owned(), "b".to_owned()];
        let resolved = resolve_reference(r, &module_path);

        assert_eq!(resolved.prefix(), PathPrefix::Super(5));
        assert_eq!(resolved.segments(), &["foo", "Bar"]);
    }

    #[test]
    fn test_resolve_crate_prefix_unchanged() {
        let r = TypeReference::new(["module", "Type"]).with_crate_prefix();
        let module_path = vec!["utils".to_owned()];
        let resolved = resolve_reference(r, &module_path);

        assert_eq!(resolved.prefix(), PathPrefix::Crate);
        assert_eq!(resolved.segments(), &["module", "Type"]);
        assert_eq!(resolved.to_path_string(), "crate::module::Type");
    }

    #[test]
    fn test_resolve_no_prefix_unchanged() {
        let r = TypeReference::new(["std", "collections", "HashMap"]);
        let module_path = vec!["utils".to_owned()];
        let resolved = resolve_reference(r, &module_path);

        assert_eq!(resolved.prefix(), PathPrefix::None);
        assert_eq!(resolved.segments(), &["std", "collections", "HashMap"]);
        assert_eq!(resolved.to_path_string(), "std::collections::HashMap");
    }

    #[test]
    fn test_resolve_preserves_suffix() {
        let r = TypeReference::new(["foo", "Bar"])
            .with_self_prefix()
            .with_alias("MyBar");
        let module_path = vec!["utils".to_owned()];
        let resolved = resolve_reference(r, &module_path);

        assert_eq!(resolved.to_path_string(), "crate::utils::foo::Bar as MyBar");
    }

    #[test]
    fn test_resolve_with_glob() {
        let r = TypeReference::new(["foo"]).with_self_prefix().with_glob();
        let module_path = vec!["utils".to_owned()];
        let resolved = resolve_reference(r, &module_path);

        assert_eq!(resolved.to_path_string(), "crate::utils::foo::*");
    }
}