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
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
use crate::cache::ParseCache;
use crate::discover::{CrateInfo, ModuleInfo, TargetInfo, TargetKind};
use crate::error::{AnalysisError, Result};
use crate::model::{AnalysisOptions, AnalysisResult};
use crate::parser::CrateAnalyzer;
use crate::reference::{GroupItem, PathSuffix, TypeReference};
use crate::resolve::resolve_glob;
use std::collections::{HashMap, HashSet};
use std::fmt::{Debug, Formatter, Result as FmtResult};
use std::path::{Path, PathBuf};
use tracing::{debug, error, info, trace};

/// Expand grouped and aliased imports into individual references.
///
/// - `None` / `Alias` → single reference (alias stripped, segments preserved)
/// - `Glob` → single reference (glob preserved)
/// - `Group` → one reference per group item, recursively expanded for nested groups
pub(crate) fn expand_groups(reference: &TypeReference) -> Vec<TypeReference> {
    match reference.suffix() {
        PathSuffix::None | PathSuffix::Alias(_) => vec![reference.clone_with(true, false)],
        PathSuffix::Glob => vec![reference.clone_with(true, true)],
        PathSuffix::Group(items) => {
            let mut result = Vec::new();
            for item in items {
                match item {
                    GroupItem::Simple(name) | GroupItem::Aliased { name, alias: _ } => {
                        result.push(reference.clone_with(true, false).append_segment(name));
                    }
                    GroupItem::SelfItem { alias: _ } => {
                        result.push(reference.clone_with(true, false));
                    }
                    GroupItem::Glob => {
                        result.push(reference.clone_with(true, true));
                    }
                    GroupItem::Nested {
                        prefix,
                        items: nested_items,
                    } => {
                        let mut nested = reference.clone_with(true, false);
                        for seg in prefix {
                            nested = nested.append_segment(seg);
                        }
                        let nested = nested.with_group(nested_items.clone());
                        result.extend(expand_groups(&nested));
                    }
                }
            }
            result
        }
    }
}

/// Analyzer for Rust module dependencies.
///
/// The main entry point for analyzing module dependencies in a Rust crate.
/// Create an analyzer with a crate root path, then call [`analyze_module`](Self::analyze_module)
/// to analyze specific modules.
///
/// # Thread Safety
///
/// `Analyzer` is **not** `Sync`: [`analyze_module`](Self::analyze_module) requires `&mut self`
/// due to an internal parse cache. To analyze modules in parallel, create a separate
/// `Analyzer` instance per thread.
///
/// # Examples
///
/// ```no_run
/// use crawk::{Analyzer, AnalysisOptions};
/// use std::path::Path;
///
/// let mut analyzer = Analyzer::new(Path::new("/path/to/my-crate"))?;
///
/// // Analyze the "utils" module
/// let result = analyzer.analyze_module("utils", &AnalysisOptions::default())?;
/// println!("Found {} dependencies", result.len());
///
/// // Analyze a nested module with custom options
/// let options = AnalysisOptions {
///     include_tests: true,
///     expand_groups: true,
///     ..Default::default()
/// };
/// let result = analyzer.analyze_module("foo::bar", &options)?;
/// # Ok::<(), crawk::AnalysisError>(())
/// ```
#[derive(Clone)]
pub struct Analyzer {
    /// Crate analyzer
    crate_info: CrateInfo,
    /// Module analyzer
    parser: CrateAnalyzer,
    /// Parse cache: avoids re-reading and re-parsing the same `.rs` file more than once.
    parse_cache: ParseCache,
}

impl Debug for Analyzer {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.debug_struct("Analyzer")
            .field("crate_info", &self.crate_info)
            .field("parser", &self.parser)
            .field(
                "parse_cache",
                &format!("<{} entries>", self.parse_cache.len()),
            )
            .finish()
    }
}

impl Analyzer {
    /// Create a new analyzer for the given crate root directory.
    ///
    /// The crate root should be the directory containing `Cargo.toml`.
    /// The analyzer will look for source files in the `src/` subdirectory.
    ///
    /// # Arguments
    ///
    /// * `crate_root` - Path to the crate root directory
    ///
    /// # Errors
    ///
    /// Returns [`AnalysisError::InvalidCrateRoot`] if the path does not exist or is not a valid Rust project.
    /// Returns [`AnalysisError::CrateInfoError`] if there are issues retrieving crate metadata.
    /// Returns [`AnalysisError::ModuleAnalysisFailed`] if there are issues initializing the crate analyzer.
    /// Returns `Ok(Analyzer)` if the crate root is valid and the analyzer is successfully initialized.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use crawk::Analyzer;
    /// use std::path::Path;
    ///
    /// let analyzer = Analyzer::new(Path::new("/home/user/my-project"));
    /// ```
    pub fn new(crate_root: impl AsRef<Path>) -> Result<Self> {
        let crate_info = CrateInfo::new(crate_root.as_ref())?;
        let name = crate_info.root_package_name();
        let parser = CrateAnalyzer::new(name);

        Ok(Self {
            crate_info,
            parser,
            parse_cache: ParseCache::new(),
        })
    }

    /// List all modules discovered under the given module path.
    ///
    /// Returns a sorted list of all modules found recursively under
    /// `module_path`. If `module_path` is `"lib"`, lists the entire crate.
    ///
    /// # Arguments
    ///
    /// * `module_path` - Root module to list from (e.g., `"lib"`, `"parser"`)
    /// * `include_tests` - Whether to include `#[cfg(test)]` modules
    ///
    /// # Errors
    ///
    /// Returns [`AnalysisError::ModuleNotFound`] if the module doesn't exist.
    pub fn list_modules(
        &mut self,
        module_path: &str,
        include_tests: bool,
    ) -> Result<Vec<ModuleInfo>> {
        let default_target = self.default_lib_target();
        let modules = match self.crate_info.get_module_tree(
            module_path,
            true,
            include_tests,
            &default_target,
            &mut self.parse_cache,
        ) {
            Ok(mods) => mods,
            Err(ref e) if include_tests && e.is_module_not_found() => {
                self.list_from_test_target(module_path)?
            }
            Err(e) => return Err(e.into()),
        };
        // Rename root entry (empty path) to the requested module path
        let mut modules: Vec<ModuleInfo> = modules
            .into_iter()
            .map(|m| {
                if m.path().is_empty() {
                    m.with_path(module_path.to_owned())
                } else {
                    m
                }
            })
            .collect();
        modules.sort_by(|a, b| a.path().cmp(b.path()));
        modules.dedup_by(|a, b| a.path() == b.path());
        info!("Listed {} modules (after dedup)", modules.len());
        Ok(modules)
    }

    /// Searches integration test targets for the given module path.
    ///
    /// Discovers all test targets, collects their full module trees, and
    /// returns the subtree rooted at `module_path` if found.
    fn list_from_test_target(&mut self, module_path: &str) -> Result<Vec<ModuleInfo>> {
        let targets = self.crate_info.all_targets(true);
        let prefix_with_sep = format!("{module_path}::");

        for (target_info, src_path) in &targets {
            if *target_info.kind() != TargetKind::Test {
                continue;
            }

            let modules = CrateInfo::get_module_tree_for_file(
                src_path,
                target_info,
                true,
                &mut self.parse_cache,
            )?;

            let matched: Vec<ModuleInfo> = modules
                .into_iter()
                .filter(|m| m.path() == module_path || m.path().starts_with(&prefix_with_sep))
                .collect();

            if !matched.is_empty() {
                info!(
                    "Found {} modules for '{}' in test target '{}'",
                    matched.len(),
                    module_path,
                    target_info.name()
                );
                return Ok(matched);
            }
        }

        Err(AnalysisError::ModuleNotFound {
            module_path: module_path.to_owned(),
        })
    }

    /// List modules from all compilation targets in the crate.
    ///
    /// Returns modules from library and binary targets. When `include_tests`
    /// is `true`, also includes integration test targets and `#[cfg(test)]`
    /// modules.
    ///
    /// # Errors
    ///
    /// Returns an error if any target's source file cannot be read or parsed.
    pub fn list_all_modules(&mut self, include_tests: bool) -> Result<Vec<ModuleInfo>> {
        let targets = self.crate_info.all_targets(include_tests);
        let mut all_modules = Vec::new();

        for (target_info, src_path) in &targets {
            let canonical_name = Self::target_module_path(target_info, src_path);
            let modules = match target_info.kind() {
                TargetKind::Lib | TargetKind::Bin => self.crate_info.get_module_tree(
                    &canonical_name,
                    true,
                    include_tests,
                    target_info,
                    &mut self.parse_cache,
                )?,
                TargetKind::Test => CrateInfo::get_module_tree_for_file(
                    src_path,
                    target_info,
                    include_tests,
                    &mut self.parse_cache,
                )?,
            };
            // Rename root entry from "" to canonical name (e.g. "lib", "main")
            let modules = modules.into_iter().map(|m| {
                if m.path().is_empty() {
                    m.with_path(canonical_name.clone())
                } else {
                    m
                }
            });
            all_modules.extend(modules);
        }

        // Sort: target kind (Lib < Bin < Test), then target name, then module path
        all_modules.sort_by(|a, b| {
            a.target()
                .kind()
                .cmp(b.target().kind())
                .then_with(|| a.target().name().cmp(b.target().name()))
                .then_with(|| a.path().cmp(b.path()))
        });
        all_modules.dedup_by(|a, b| a.target() == b.target() && a.path() == b.path());

        info!(
            "Listed {} modules across {} targets",
            all_modules.len(),
            targets.len()
        );
        Ok(all_modules)
    }

    /// Analyze dependencies for a specific module.
    ///
    /// Recursively analyzes the module and all its submodules, collecting
    /// all internal crate dependencies. Returns an [`AnalysisResult`]
    /// populated according to the given [`AnalysisOptions`].
    ///
    /// # Arguments
    ///
    /// * `module_path` - Module path components (e.g., `["utils", "parser"]`)
    /// * `options` - Analysis options controlling output format
    ///
    /// # Errors
    ///
    /// Returns [`AnalysisError::ModuleNotFound`] if the module doesn't exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use crawk::{Analyzer, AnalysisOptions};
    /// use std::path::Path;
    ///
    /// let mut analyzer = Analyzer::new(Path::new("/path/to/crate"))?;
    /// let result = analyzer.analyze_module("utils::parser", &AnalysisOptions::default())?;
    ///
    /// for (module, refs) in result.dependencies() {
    ///     println!("{module}");
    ///     for reference in refs {
    ///         println!("  {reference}");
    ///     }
    /// }
    /// # Ok::<(), crawk::AnalysisError>(())
    /// ```
    pub fn analyze_module(
        &mut self,
        module_path: impl Into<String>,
        options: &AnalysisOptions,
    ) -> Result<AnalysisResult> {
        let module_path = module_path.into();

        let default_target = self.default_lib_target();
        let modules = match self.crate_info.get_module_tree(
            &module_path,
            options.recursive,
            options.include_tests,
            &default_target,
            &mut self.parse_cache,
        ) {
            Ok(mods) => mods,
            Err(ref e) if options.include_tests && e.is_module_not_found() => {
                self.list_from_test_target(&module_path)?
            }
            Err(e) => return Err(e.into()),
        };

        let source_file = modules
            .first()
            .map(|m| m.source().to_path_buf())
            .unwrap_or_default();

        let file_root = self.build_file_root_map(&modules);
        self.parse_all_modules(modules, &file_root)?;
        let dependencies = self.collect_references(options);

        Ok(AnalysisResult::new(module_path, dependencies, source_file))
    }

    /// Returns a default `TargetInfo` for the library target.
    fn default_lib_target(&self) -> TargetInfo {
        TargetInfo::new(TargetKind::Lib, self.crate_info.root_package_name())
    }

    /// Computes the module path string to pass to `get_module_tree` for a target.
    ///
    /// Library targets use `"lib"`, binary targets use the file stem of their
    /// source path (e.g., `"main"` for `src/main.rs`).
    fn target_module_path(target: &TargetInfo, src_path: &Path) -> String {
        match target.kind() {
            TargetKind::Lib => "lib".to_owned(),
            TargetKind::Bin => src_path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("main")
                .to_owned(),
            TargetKind::Test => src_path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("test")
                .to_owned(),
        }
    }

    /// Parse each discovered module and accumulate its references into the parser.
    fn parse_all_modules(
        &mut self,
        modules: Vec<ModuleInfo>,
        file_root: &HashMap<PathBuf, String>,
    ) -> Result<()> {
        for module in modules {
            let root_path = &file_root[module.source()];
            let inline_scope = Self::compute_inline_scope(module.path(), root_path);

            trace!(
                "Module '{}' inline_scope={:?} (file root: '{}')",
                module.path(),
                inline_scope,
                root_path
            );

            info!(
                "Analyzing module: {} (file: {})",
                module.path(),
                module.source().display()
            );

            match self.parser.parse_file(
                module.path(),
                module.source(),
                &inline_scope,
                &mut self.parse_cache,
            ) {
                Err(e) => {
                    error!("Error while analyzing module '{}': {e}", module.path());
                    return Err(AnalysisError::ModuleAnalysisFailed {
                        module_path: module.path().to_owned(),
                        file: module.source().to_path_buf(),
                        message: e.to_string(),
                    });
                }
                Ok(type_list) => {
                    for reference in &type_list {
                        debug!("Found reference: {}", reference.to_path_string());
                    }
                }
            }
        }
        Ok(())
    }

    /// Transform parsed references: expand groups and resolve globs per the given options.
    fn collect_references(
        &mut self,
        options: &AnalysisOptions,
    ) -> HashMap<String, HashSet<TypeReference>> {
        let mut dependencies = HashMap::new();
        for (module, module_references) in self.parser.all_crate_references() {
            debug!("Processing module: {}", module);
            let mut refs = HashSet::new();
            for reference in module_references {
                debug!("Found crate reference: {}", reference.to_path_string());

                // Pass 1: expand groups if requested
                let after_expand = if options.expand_groups {
                    debug!(
                        "Expanding groups for reference: {}",
                        reference.to_path_string()
                    );
                    let expanded = expand_groups(reference);
                    for exp in &expanded {
                        debug!("Expanded reference: {}", exp.to_path_string());
                    }
                    expanded
                } else {
                    vec![reference.clone()]
                };

                // Pass 2: resolve globs if requested
                for r in after_expand {
                    if options.resolve_globs && r.has_glob() {
                        debug!("Resolving glob: {}", r.to_path_string());
                        let resolved =
                            resolve_glob(&r, module, &self.crate_info, &mut self.parse_cache);
                        for res in resolved {
                            debug!("Resolved glob item: {}", res.to_path_string());
                            refs.insert(res);
                        }
                    } else {
                        refs.insert(r);
                    }
                }
            }

            debug!(
                "Processing module: {module} complete, found {} dependencies",
                dependencies.len()
            );
            dependencies.insert(module.clone(), refs);
        }
        dependencies
    }

    /// Build a mapping from source file to the shortest (file-level) module path.
    ///
    /// When multiple modules share the same source file (inline modules),
    /// the one with the shortest path is the file-level owner.
    fn build_file_root_map(&self, modules: &[ModuleInfo]) -> HashMap<PathBuf, String> {
        let mut file_root: HashMap<PathBuf, String> = HashMap::new();
        for module in modules {
            let source_path = module.source().to_path_buf();
            let actual_root = self.find_actual_file_root(module.path(), &source_path);
            debug!(
                "File root: '{}' \u{2192} '{}' (file: {})",
                module.path(),
                actual_root,
                source_path.display()
            );

            match file_root.entry(source_path) {
                std::collections::hash_map::Entry::Occupied(mut e) => {
                    if actual_root.len() < e.get().len() {
                        *e.get_mut() = actual_root;
                    }
                }
                std::collections::hash_map::Entry::Vacant(e) => {
                    e.insert(actual_root);
                }
            }
        }
        info!(
            "File root map: {} files for {} modules",
            file_root.len(),
            modules.len()
        );
        file_root
    }

    /// Find the actual file-level module path for a given module.
    ///
    /// This detects if a module is actually an inline module by checking if
    /// shorter prefixes (or empty path for crate root) resolve to the same file.
    fn find_actual_file_root(&self, module_path: &str, source_file: &Path) -> String {
        trace!(
            "Finding file root for module '{}' in file '{}'",
            module_path,
            source_file.display()
        );

        if module_path.is_empty() {
            return String::new();
        }

        // First check if this file is the crate root (lib.rs or main.rs in src/)
        let is_crate_root = source_file.to_string_lossy().ends_with("src/lib.rs")
            || source_file.to_string_lossy().ends_with("src/main.rs");

        if is_crate_root {
            trace!(
                "Source file is crate root, returning empty string for module '{}'",
                module_path
            );
            return String::new();
        }

        let segments: Vec<&str> = module_path.split("::").collect();

        // Try progressively shorter prefixes
        for len in (1..segments.len()).rev() {
            let prefix = segments[..len].join("::");

            trace!("Trying prefix: '{}'", prefix);

            // Check if this prefix resolves to the same file
            match self.crate_info.resolve_module_path_to_file(&prefix) {
                Ok(ref resolved) => {
                    trace!("Prefix '{}' resolved to '{}'", prefix, resolved.display());
                    if resolved == source_file {
                        trace!("Found file root: '{}' for module '{}'", prefix, module_path);
                        return prefix;
                    }
                }
                Err(e) => {
                    trace!("Prefix '{}' failed to resolve: {}", prefix, e);
                }
            }
        }

        // Fallback to the original module path
        trace!("No shorter prefix found, using original: '{}'", module_path);
        module_path.to_owned()
    }

    /// Compute the inline scope for a module relative to its file root.
    ///
    /// Returns the path segments that identify the inline module within the file.
    /// For example, if `module_path` is `"foo::bar::baz"` and `root_path` is `"foo"`,
    /// returns `["bar", "baz"]`. Returns an empty vec if the module is the file root.
    fn compute_inline_scope(module_path: &str, root_path: &str) -> Vec<String> {
        if module_path == root_path {
            vec![]
        } else if root_path.is_empty() {
            // When root_path is empty (crate root), the entire module_path is the inline scope
            module_path.split("::").map(String::from).collect()
        } else {
            module_path
                .strip_prefix(root_path)
                .and_then(|s| s.strip_prefix("::"))
                .map(|s| s.split("::").map(String::from).collect())
                .unwrap_or_default()
        }
    }
}

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

    fn make_ref(segments: &[&str], suffix: PathSuffix) -> TypeReference {
        let base = TypeReference::new(segments.iter().copied());
        match suffix {
            PathSuffix::None => base,
            PathSuffix::Alias(a) => base.with_alias(a),
            PathSuffix::Glob => base.with_glob(),
            PathSuffix::Group(g) => base.with_group(g),
        }
    }

    fn expand_to_segments(r: &TypeReference) -> Vec<Vec<String>> {
        expand_groups(r)
            .into_iter()
            .map(|t| t.segments().to_vec())
            .collect()
    }

    #[test]
    fn test_expand_groups_none_passthrough() {
        let r = make_ref(&["std", "collections"], PathSuffix::None);
        assert_eq!(expand_to_segments(&r), vec![vec!["std", "collections"]]);
    }

    #[test]
    fn test_expand_groups_alias_passthrough() {
        let r = make_ref(
            &["std", "collections", "HashMap"],
            PathSuffix::Alias("Map".into()),
        );
        assert_eq!(
            expand_to_segments(&r),
            vec![vec!["std", "collections", "HashMap"]]
        );
    }

    #[test]
    fn test_expand_groups_glob_passthrough() {
        let r = make_ref(&["std", "collections"], PathSuffix::Glob);
        assert_eq!(expand_to_segments(&r), vec![vec!["std", "collections"]]);
    }

    #[test]
    fn test_expand_groups_simple() {
        let r = make_ref(
            &["std", "collections"],
            PathSuffix::Group(vec![
                GroupItem::Simple("HashMap".into()),
                GroupItem::Simple("HashSet".into()),
            ]),
        );
        assert_eq!(
            expand_to_segments(&r),
            vec![
                vec!["std", "collections", "HashMap"],
                vec!["std", "collections", "HashSet"],
            ]
        );
    }

    #[test]
    fn test_expand_groups_aliased_uses_original_name() {
        let r = make_ref(
            &["std", "collections"],
            PathSuffix::Group(vec![GroupItem::Aliased {
                name: "HashMap".into(),
                alias: "Map".into(),
            }]),
        );
        assert_eq!(
            expand_to_segments(&r),
            vec![vec!["std", "collections", "HashMap"]]
        );
    }

    #[test]
    fn test_expand_groups_self_item_no_alias() {
        let r = make_ref(
            &["std", "collections", "module"],
            PathSuffix::Group(vec![GroupItem::SelfItem { alias: None }]),
        );
        assert_eq!(
            expand_to_segments(&r),
            vec![vec!["std", "collections", "module"]]
        );
    }

    #[test]
    fn test_expand_groups_self_item_with_alias() {
        let r = make_ref(
            &["std", "collections", "module"],
            PathSuffix::Group(vec![GroupItem::SelfItem {
                alias: Some("Alias".into()),
            }]),
        );
        assert_eq!(
            expand_to_segments(&r),
            vec![vec!["std", "collections", "module"]]
        );
    }

    #[test]
    fn test_expand_groups_self_item_empty_base_no_alias() {
        let r = make_ref(
            &[],
            PathSuffix::Group(vec![GroupItem::SelfItem { alias: None }]),
        );
        assert_eq!(expand_to_segments(&r), vec![vec![] as Vec<String>]);
    }

    #[test]
    fn test_expand_groups_glob_returns_base() {
        let r = make_ref(
            &["std", "collections"],
            PathSuffix::Group(vec![GroupItem::Glob]),
        );
        assert_eq!(expand_to_segments(&r), vec![vec!["std", "collections"]]);
    }

    #[test]
    fn test_expand_groups_nested() {
        let r = make_ref(
            &["std"],
            PathSuffix::Group(vec![GroupItem::Nested {
                prefix: vec!["collections".into()],
                items: vec![
                    GroupItem::Simple("HashMap".into()),
                    GroupItem::Simple("HashSet".into()),
                ],
            }]),
        );
        assert_eq!(
            expand_to_segments(&r),
            vec![
                vec!["std", "collections", "HashMap"],
                vec!["std", "collections", "HashSet"],
            ]
        );
    }

    #[test]
    fn test_expand_groups_mixed() {
        let r = make_ref(
            &["m", "n"],
            PathSuffix::Group(vec![
                GroupItem::Simple("a".into()),
                GroupItem::Aliased {
                    name: "b".into(),
                    alias: "B".into(),
                },
                GroupItem::Nested {
                    prefix: vec!["c".into()],
                    items: vec![GroupItem::Simple("x".into()), GroupItem::Simple("y".into())],
                },
                GroupItem::Glob,
            ]),
        );
        assert_eq!(
            expand_to_segments(&r),
            vec![
                vec!["m", "n", "a"],
                vec!["m", "n", "b"],
                vec!["m", "n", "c", "x"],
                vec!["m", "n", "c", "y"],
                vec!["m", "n"],
            ]
        );
    }

    #[test]
    fn test_expand_groups_deeply_nested() {
        let r = make_ref(
            &["a"],
            PathSuffix::Group(vec![GroupItem::Nested {
                prefix: vec!["b".into()],
                items: vec![GroupItem::Nested {
                    prefix: vec!["c".into()],
                    items: vec![
                        GroupItem::Simple("d".into()),
                        GroupItem::Simple("e".into()),
                        GroupItem::Simple("f".into()),
                    ],
                }],
            }]),
        );
        assert_eq!(
            expand_to_segments(&r),
            vec![
                vec!["a", "b", "c", "d"],
                vec!["a", "b", "c", "e"],
                vec!["a", "b", "c", "f"],
            ]
        );
    }
}