1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
//! Resolution and tree collection logic for [`CrateInfo`].
//!
//! This module contains the heavy lifting of module discovery: resolving module
//! paths to files on disk, traversing the module tree recursively, and detecting
//! inline modules. All items are additional `impl CrateInfo` blocks — the type
//! itself is defined in the parent module.
//!
//! # Responsibilities
//!
//! - **Path resolution**: mapping `crate::foo::bar` paths to `.rs` files, handling
//! both `foo.rs` (2018+ style) and `foo/mod.rs` (legacy style) layouts
//! - **Binary target support**: resolving paths rooted at binary targets by matching
//! source file stems (e.g., `main` → `src/main.rs`)
//! - **Inline module detection**: identifying when a module path resolves to an
//! inline `mod { ... }` block rather than a separate file
//! - **Tree collection**: recursively or shallowly enumerating submodules, with
//! optional inclusion of `#[cfg(test)]` modules
use std::fs;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use crate::cache::ParseCache;
use cargo_metadata::Package;
use syn::Item;
use crate::constants::{LIB_FILE_NAME, MAIN_FILE_NAME, MODULE_FILE_NAME};
use crate::utils::has_cfg_test;
use super::{CrateInfo, CrateInfoError, ModuleInfo, Result};
impl CrateInfo {
/// Resolves a module path to a file path.
///
/// This method handles both fully qualified paths (with crate name prefix)
/// and relative module paths.
///
/// # Arguments
///
/// * `module_path` - A module path like `analysis::collect` or `crawk::analysis::collect`
///
/// # Returns
///
/// Returns `Ok(PathBuf)` if the module file is found.
///
/// # Errors
///
/// Returns an error if:
/// - The module path is empty
/// - The module cannot be found
/// - The crate root cannot be determined
pub(super) fn resolve_module(&self, module_path: &str) -> Result<PathBuf> {
let package = self.root_package().ok_or(CrateInfoError::PackageNotFound)?;
self.resolve_module_path_with_crate(package, module_path)
}
/// Resolves a module path within a specific package.
///
/// # Arguments
///
/// * `package` - The package to search within
/// * `module_path` - A module path like `analysis::collect`
///
/// # Errors
///
/// Returns an error if the module path is empty or the module cannot be found.
fn resolve_module_path(package: &Package, module_path: &str) -> Result<PathBuf> {
let parts: Vec<&str> = module_path.split("::").collect();
if parts.is_empty() || module_path.is_empty() {
return Err(CrateInfoError::EmptyModulePath);
}
let crate_root = Self::find_crate_root(package)
.ok_or_else(|| CrateInfoError::NoCrateRoot(package.name.to_string()))?;
let crate_root_dir = crate_root
.parent()
.ok_or_else(|| CrateInfoError::NoCrateRoot(package.name.to_string()))?;
let resolved = Self::resolve_module_parts(crate_root_dir, &parts, Some(&crate_root))?
.ok_or_else(|| CrateInfoError::ModuleNotFound {
module_path: module_path.to_owned(),
})?;
Self::check_within_root(&resolved, crate_root_dir)?;
Ok(resolved)
}
/// Resolves a fully qualified module path that may include the crate name.
///
/// E.g., `crawk::analysis::collect` or just `analysis::collect`
/// Also treats "lib" as an alias for the library root (same as crate name).
/// Also matches binary targets by their source file stem (e.g., "main" for main.rs, "app" for app.rs).
fn resolve_module_path_with_crate(
&self,
package: &Package,
module_path: &str,
) -> Result<PathBuf> {
let parts: Vec<&str> = module_path.split("::").collect();
if parts.is_empty() || module_path.is_empty() {
return Err(CrateInfoError::EmptyModulePath);
}
// Check if the first part is the crate name itself or "lib" alias
let is_lib_root = parts[0] == self.root_package_name() || parts[0] == "lib";
if is_lib_root {
// Skip the crate name/alias and resolve the rest
return if parts.len() > 1 {
let remaining_path = parts[1..].join("::");
Self::resolve_module_path(package, &remaining_path)
} else {
// Just the crate name/alias, return the crate root (library)
Self::find_crate_root(package)
.ok_or_else(|| CrateInfoError::NoCrateRoot(package.name.to_string()))
};
}
// Check if the first part matches any binary target's source file stem
if Self::find_binary_by_file_stem(package, parts[0]).is_some() {
return if parts.len() > 1 {
let remaining = parts[1..].join("::");
Self::resolve_module_path_from_binary(package, parts[0], &remaining)
} else {
Self::find_binary_by_file_stem(package, parts[0])
.ok_or_else(|| CrateInfoError::NoCrateRoot(package.name.to_string()))
};
}
// Otherwise, resolve as-is
Self::resolve_module_path(package, module_path)
}
/// Finds the crate root file (lib.rs, main.rs, or the first target's src_path).
///
/// Preference order:
/// 1. Library target (lib.rs)
/// 2. Binary target (main.rs)
/// 3. First target's source path
fn find_crate_root(package: &Package) -> Option<PathBuf> {
// Prefer lib.rs
for target in &package.targets {
if target.is_lib() {
return Some(target.src_path.clone().into());
}
}
// Then main.rs
for target in &package.targets {
if target.is_bin() {
return Some(target.src_path.clone().into());
}
}
// Fallback to first target
package.targets.first().map(|t| t.src_path.clone().into())
}
/// Finds a binary target by matching its source file's filename against `"{file_stem}.rs"`.
pub(super) fn find_binary_by_file_stem(package: &Package, file_stem: &str) -> Option<PathBuf> {
let expected_filename = format!("{file_stem}.rs");
package
.targets
.iter()
.find(|t| {
t.is_bin()
&& Path::new(t.src_path.as_str())
.file_name()
.and_then(|f| f.to_str())
.is_some_and(|name| name == expected_filename)
})
.map(|t| t.src_path.clone().into())
}
/// Resolves a module path relative to a binary target identified by its source file stem.
///
/// Similar to `resolve_module_path`, but uses the specified binary as the root.
fn resolve_module_path_from_binary(
package: &Package,
file_stem: &str,
module_path: &str,
) -> Result<PathBuf> {
let parts: Vec<&str> = module_path.split("::").collect();
if parts.is_empty() || module_path.is_empty() {
return Err(CrateInfoError::EmptyModulePath);
}
let bin_root = Self::find_binary_by_file_stem(package, file_stem)
.ok_or_else(|| CrateInfoError::NoCrateRoot(package.name.to_string()))?;
let bin_root_dir = bin_root
.parent()
.ok_or_else(|| CrateInfoError::NoCrateRoot(package.name.to_string()))?;
let resolved = Self::resolve_module_parts(bin_root_dir, &parts, Some(&bin_root))?
.ok_or_else(|| CrateInfoError::ModuleNotFound {
module_path: module_path.to_owned(),
})?;
Self::check_within_root(&resolved, bin_root_dir)?;
Ok(resolved)
}
/// Validates a single module path segment against path traversal and illegal characters.
///
/// A valid segment is a non-empty Rust identifier with no path separators or
/// parent-directory references.
///
/// # Errors
///
/// Returns [`CrateInfoError::InvalidModuleSegment`] if the segment is empty, equals `..`,
/// contains `/` or `\`, or is an absolute path.
fn validate_segment(part: &str) -> Result<()> {
if part.is_empty()
|| part == ".."
|| part.contains('/')
|| part.contains('\\')
|| Path::new(part).is_absolute()
{
return Err(CrateInfoError::InvalidModuleSegment {
segment: part.to_owned(),
});
}
Ok(())
}
/// Verifies that `path` is contained within `root`.
///
/// Uses [`std::fs::canonicalize`] to resolve symlinks before comparison,
/// acting as a safety net against traversal that bypasses segment validation.
///
/// # Errors
///
/// Returns [`CrateInfoError::PathTraversal`] if the resolved path escapes `root`,
/// or [`CrateInfoError::FileRead`] if canonicalization fails.
fn check_within_root(path: &Path, root: &Path) -> Result<()> {
let canonical_path = path
.canonicalize()
.map_err(|source| CrateInfoError::FileRead {
path: path.to_path_buf(),
source,
})?;
let canonical_root = root
.canonicalize()
.map_err(|source| CrateInfoError::FileRead {
path: root.to_path_buf(),
source,
})?;
if canonical_path.starts_with(&canonical_root) {
Ok(())
} else {
Err(CrateInfoError::PathTraversal)
}
}
/// Resolves module parts to a file path.
///
/// Checks both `module.rs` (Rust 2018+ style) and `module/mod.rs` (older style) conventions.
/// If a file-based module is not found, also searches for inline module declarations in the parent file.
/// When `root_file` is provided, inline modules in that file are checked when the first part
/// has no corresponding file on disk.
fn resolve_module_parts(
base_dir: &Path,
parts: &[&str],
root_file: Option<&Path>,
) -> Result<Option<PathBuf>> {
if parts.is_empty() {
return Ok(None);
}
let mut current_dir = base_dir.to_path_buf();
let mut current_file: Option<PathBuf> = root_file.map(Path::to_path_buf);
// Navigate through all parts
for (idx, &part) in parts.iter().enumerate() {
Self::validate_segment(part)?;
let is_last = idx == parts.len() - 1;
let part_dir = current_dir.join(part);
// Check for `part.rs` (Rust 2018+ style)
let file_path = current_dir.join(format!("{part}.rs"));
if file_path.exists() {
if is_last {
return Ok(Some(file_path));
}
// For non-last parts, remember this file and try to navigate into companion directory
if part_dir.is_dir() {
current_file = Some(file_path);
current_dir = part_dir;
continue;
}
// No companion directory, but we have a file - check for inline module
return Self::check_inline_module(&file_path, &parts[idx + 1..]);
}
// Check for `part/mod.rs` (older style)
let mod_path = part_dir.join(MODULE_FILE_NAME);
if mod_path.exists() {
if is_last {
return Ok(Some(mod_path));
}
// Navigate into this module's directory
current_file = Some(mod_path);
current_dir = part_dir;
continue;
}
// Module not found as a file - check if it's an inline module in the parent file
if let Some(parent_file) = ¤t_file {
return Self::check_inline_module(parent_file, &parts[idx..]);
}
return Ok(None);
}
Ok(None)
}
/// Checks if a sequence of module names exists as inline modules in the given file.
/// Returns the file path if all parts exist as nested inline modules, None otherwise.
fn check_inline_module(file_path: &Path, module_parts: &[&str]) -> Result<Option<PathBuf>> {
if module_parts.is_empty() {
return Ok(Some(file_path.to_path_buf()));
}
let syntax = Self::parse_source_file(file_path)?;
Ok(Self::find_nested_inline_module(
&syntax.items,
module_parts,
file_path,
))
}
/// Recursively checks for nested inline modules within a list of items.
fn find_nested_inline_module(
items: &[Item],
module_parts: &[&str],
file_path: &Path,
) -> Option<PathBuf> {
if module_parts.is_empty() {
return Some(file_path.to_path_buf());
}
let target_name = module_parts[0];
for item in items {
if let Item::Mod(item_mod) = item
&& item_mod.ident == target_name
&& let Some((_, nested_items)) = &item_mod.content
{
if module_parts.len() == 1 {
return Some(file_path.to_path_buf());
}
return Self::find_nested_inline_module(
nested_items,
&module_parts[1..],
file_path,
);
}
}
None
}
/// Collects only the current module (non-recursive, no submodules).
///
/// When `include_tests` is `true`, also includes the direct test module
/// (marked with `#[cfg(test)]`) if one exists directly under the given module.
pub(super) fn collect_submodules_shallow(
file_path: &Path,
current_module_path: &str,
include_tests: bool,
cache: &mut ParseCache,
) -> Result<Vec<ModuleInfo>> {
let mut result = Vec::new();
// Add only the current module itself
result.push(ModuleInfo::new(
current_module_path.to_owned(),
file_path.to_path_buf(),
));
if include_tests {
// Read and parse the file to find a direct test module
let syntax = Self::parse_cached(file_path, cache)?;
for item in &syntax.items {
if let Item::Mod(item_mod) = item
&& has_cfg_test(&item_mod.attrs)
{
let mod_name = item_mod.ident.to_string();
let submodule_path = if current_module_path.is_empty() {
mod_name
} else {
format!("{current_module_path}::{mod_name}")
};
result.push(ModuleInfo::new(submodule_path, file_path.to_path_buf()));
}
}
}
Ok(result)
}
#[allow(clippy::doc_link_with_quotes)]
/// Recursively collects all submodules from a file.
///
/// The `inline_scope` parameter specifies which inline modules to descend into
/// within the file. For file-based modules, this should be empty. For inline
/// modules, it contains the path segments to navigate (e.g., ["tests"] for
/// an inline module `mod tests` in the file).
pub(super) fn collect_submodules_recursive(
file_path: &Path,
current_module_path: &str,
inline_scope: &[String],
include_tests: bool,
cache: &mut ParseCache,
) -> Result<Vec<ModuleInfo>> {
let mut result = Vec::new();
// Add the current module to results
result.push(ModuleInfo::new(
current_module_path.to_owned(),
file_path.to_path_buf(),
));
// Read and parse the file
let syntax = Self::parse_cached(file_path, cache)?;
// Get the directory containing this file for resolving submodules
let base_dir = Self::get_module_base_dir(file_path);
// Determine which items to iterate over based on inline scope
let items_to_process = if inline_scope.is_empty() {
// File-based module - process all top-level items
&syntax.items
} else {
// Inline module - navigate to the inline module and process its items
Self::get_inline_module_items(&syntax.items, inline_scope)?
};
// Extract module declarations
for item in items_to_process {
if let Item::Mod(item_mod) = item {
let mod_name = item_mod.ident.to_string();
// Check if this is a test module
let is_test_module = has_cfg_test(&item_mod.attrs);
// Skip test modules if not including them
if is_test_module && !include_tests {
continue;
}
// Build the full module path for this submodule
let submodule_path = if current_module_path.is_empty() {
mod_name.clone()
} else {
format!("{current_module_path}::{mod_name}")
};
// Check if this is an inline module (has content) or external (file-based)
if let Some((_, items)) = &item_mod.content {
// Inline module - add it with current file path and recursively process its items
result.push(ModuleInfo::new(
submodule_path.clone(),
file_path.to_path_buf(),
));
result.extend(Self::collect_inline_submodules(
items,
&submodule_path,
file_path,
&base_dir,
include_tests,
cache,
)?);
} else {
// External module - find and parse its file
if let Some(sub_mod_file) =
Self::resolve_module_parts(&base_dir, &[&mod_name], None)?
{
// External modules are file-based, so inline_scope is empty
result.extend(Self::collect_submodules_recursive(
&sub_mod_file,
&submodule_path,
&[], // Empty inline scope for file-based modules
include_tests,
cache,
)?);
}
}
}
}
Ok(result)
}
/// Gets the base directory for resolving submodules from a file.
///
/// For `module.rs` files, submodules are in a `module/` directory.
/// For `mod.rs` files, submodules are in the same directory.
fn get_module_base_dir(file_path: &Path) -> PathBuf {
let file_name = file_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
let parent = file_path.parent().unwrap_or_else(|| Path::new(""));
if file_name == MODULE_FILE_NAME
|| file_name == LIB_FILE_NAME
|| file_name == MAIN_FILE_NAME
{
// Submodules are in the same directory
parent.to_path_buf()
} else {
// For `module.rs`, submodules are in `module/` directory
let stem = file_path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
parent.join(stem)
}
}
/// Collects submodules from inline module items.
fn collect_inline_submodules(
items: &[Item],
current_module_path: &str,
containing_file: &Path,
base_dir: &Path,
include_tests: bool,
cache: &mut ParseCache,
) -> Result<Vec<ModuleInfo>> {
let mut result = Vec::new();
for item in items {
if let Item::Mod(item_mod) = item {
let mod_name = item_mod.ident.to_string();
// Check if this is a test module
let is_test_module = has_cfg_test(&item_mod.attrs);
// Skip test modules if not including them
if is_test_module && !include_tests {
continue;
}
let submodule_path = format!("{current_module_path}::{mod_name}");
if let Some((_, nested_items)) = &item_mod.content {
// Inline module - record with containing file and recurse into items
result.push(ModuleInfo::new(
submodule_path.clone(),
containing_file.to_path_buf(),
));
result.extend(Self::collect_inline_submodules(
nested_items,
&submodule_path,
containing_file,
base_dir,
include_tests,
cache,
)?);
} else {
// File-based module declared inside an inline module
if let Some(sub_mod_file) =
Self::resolve_module_parts(base_dir, &[&mod_name], None)?
{
// File-based modules have empty inline scope
result.extend(Self::collect_submodules_recursive(
&sub_mod_file,
&submodule_path,
&[], // Empty inline scope for file-based modules
include_tests,
cache,
)?);
}
}
}
}
Ok(result)
}
#[allow(clippy::doc_link_with_quotes)]
/// Computes the inline scope for a module path within a file.
///
/// Returns the segments of the module path that represent inline modules
/// within the file. For example, if `module_path` is "foo::bar::tests" and
/// the file is lib.rs containing an inline module "foo" with an inline module "bar"
/// with an inline module "tests", returns ["foo", "bar", "tests"].
///
/// Returns empty vector if the module is file-based (not inline).
pub(super) fn compute_inline_scope_for_path(
&self,
module_path: &str,
file_path: &Path,
) -> Vec<String> {
if module_path.is_empty() {
return vec![];
}
let segments: Vec<&str> = module_path.split("::").collect();
// Try progressively shorter prefixes to find the file root
for len in (1..segments.len()).rev() {
let prefix = segments[..len].join("::");
if let Ok(resolved) = self.resolve_module_path_to_file(&prefix)
&& resolved == *file_path
{
// Found file root at this prefix
// The remaining segments are inline scope
return segments[len..].iter().map(ToString::to_string).collect();
}
}
// Check if the file is crate root
let is_crate_root = file_path.to_string_lossy().ends_with("src/lib.rs")
|| file_path.to_string_lossy().ends_with("src/main.rs");
if is_crate_root {
// The entire module path is inline scope within crate root
return segments.iter().map(ToString::to_string).collect();
}
// Not an inline module
vec![]
}
/// Reads and parses a Rust source file (no cache).
fn parse_source_file(path: &Path) -> Result<syn::File> {
let content = fs::read_to_string(path).map_err(|e| CrateInfoError::FileRead {
path: path.to_path_buf(),
source: e,
})?;
syn::parse_file(&content).map_err(|e| CrateInfoError::ParseError {
path: path.to_path_buf(),
message: e.to_string(),
})
}
/// Reads and parses a Rust source file, returning a cached `Rc<syn::File>`.
///
/// On first access the file is read and parsed; subsequent calls for the same
/// path return a clone of the existing `Rc` without any I/O or parsing.
fn parse_cached(path: &Path, cache: &mut ParseCache) -> Result<Rc<syn::File>> {
cache.get_or_parse(path, Self::parse_source_file)
}
#[allow(clippy::doc_link_with_quotes)]
/// Navigates through nested inline modules and returns the items at the target scope.
///
/// Given a list of items and an inline scope (e.g., ["tests", "submod"]), this function
/// navigates through the nested inline module declarations and returns the items
/// inside the target module.
///
/// Returns the top-level items if inline_scope is empty.
fn get_inline_module_items<'a>(
items: &'a [Item],
inline_scope: &[String],
) -> Result<&'a [Item]> {
if inline_scope.is_empty() {
return Ok(items);
}
let module_name = &inline_scope[0];
for item in items {
if let Item::Mod(item_mod) = item
&& item_mod.ident == module_name
&& let Some((_, nested_items)) = &item_mod.content
{
// Found the inline module, recurse if there are more segments
if inline_scope.len() > 1 {
return Self::get_inline_module_items(nested_items, &inline_scope[1..]);
}
return Ok(nested_items);
}
}
// Module not found in inline scope
Err(CrateInfoError::ModuleNotFound {
module_path: inline_scope.join("::"),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn items_from(code: &str) -> Vec<syn::Item> {
syn::parse_file(code).unwrap().items
}
#[test]
fn base_dir_mod_rs_returns_parent() {
assert_eq!(
CrateInfo::get_module_base_dir(Path::new("/src/foo/mod.rs")),
Path::new("/src/foo")
);
}
#[test]
fn base_dir_lib_rs_returns_parent() {
assert_eq!(
CrateInfo::get_module_base_dir(Path::new("/src/lib.rs")),
Path::new("/src")
);
}
#[test]
fn base_dir_main_rs_returns_parent() {
assert_eq!(
CrateInfo::get_module_base_dir(Path::new("/src/main.rs")),
Path::new("/src")
);
}
#[test]
fn base_dir_named_file_returns_stem_subdir() {
assert_eq!(
CrateInfo::get_module_base_dir(Path::new("/src/parser.rs")),
Path::new("/src/parser")
);
}
#[test]
fn find_nested_inline_module_empty_parts_returns_file() {
let items = items_from("pub fn foo() {}");
let path = Path::new("/fake/file.rs");
assert_eq!(
CrateInfo::find_nested_inline_module(&items, &[], path),
Some(path.to_path_buf())
);
}
#[test]
fn find_nested_inline_module_finds_existing_module() {
let items = items_from("pub mod foo { pub fn inner() {} }");
let path = Path::new("/fake/file.rs");
assert_eq!(
CrateInfo::find_nested_inline_module(&items, &["foo"], path),
Some(path.to_path_buf())
);
}
#[test]
fn find_nested_inline_module_returns_none_for_missing() {
let items = items_from("pub fn foo() {}");
assert!(
CrateInfo::find_nested_inline_module(&items, &["missing"], Path::new("/f.rs"))
.is_none()
);
}
#[test]
fn find_nested_inline_module_finds_nested() {
let items = items_from("pub mod outer { pub mod inner { pub fn f() {} } }");
let path = Path::new("/fake/file.rs");
assert_eq!(
CrateInfo::find_nested_inline_module(&items, &["outer", "inner"], path),
Some(path.to_path_buf())
);
}
#[test]
fn find_nested_inline_module_returns_none_for_missing_nested() {
let items = items_from("pub mod outer {}");
assert!(
CrateInfo::find_nested_inline_module(
&items,
&["outer", "nonexistent"],
Path::new("/f.rs")
)
.is_none()
);
}
#[test]
fn get_inline_module_items_empty_scope_returns_all_items() {
let items = items_from("pub fn foo() {} pub struct Bar;");
let result = CrateInfo::get_inline_module_items(&items, &[]).unwrap();
assert_eq!(result.len(), 2);
}
#[test]
fn get_inline_module_items_finds_named_module() {
let items = items_from("pub mod foo { pub fn inner() {} pub struct S; }");
let result = CrateInfo::get_inline_module_items(&items, &["foo".to_owned()]).unwrap();
assert_eq!(result.len(), 2);
}
#[test]
fn get_inline_module_items_finds_nested_scope() {
let items = items_from("pub mod a { pub mod b { pub fn deep() {} } }");
let result =
CrateInfo::get_inline_module_items(&items, &["a".to_owned(), "b".to_owned()]).unwrap();
assert_eq!(result.len(), 1);
}
#[test]
fn get_inline_module_items_returns_error_for_missing_module() {
let items = items_from("pub fn foo() {}");
let err = CrateInfo::get_inline_module_items(&items, &["nonexistent".to_owned()])
.err()
.unwrap();
assert!(matches!(err, CrateInfoError::ModuleNotFound { .. }));
}
#[test]
fn get_inline_module_items_returns_error_for_missing_nested() {
let items = items_from("pub mod a { pub fn foo() {} }");
let err =
CrateInfo::get_inline_module_items(&items, &["a".to_owned(), "missing".to_owned()])
.err()
.unwrap();
assert!(matches!(err, CrateInfoError::ModuleNotFound { .. }));
}
#[test]
fn test_validate_segment_valid() {
assert!(CrateInfo::validate_segment("foo").is_ok());
assert!(CrateInfo::validate_segment("my_module").is_ok());
assert!(CrateInfo::validate_segment("module123").is_ok());
}
#[test]
fn test_validate_segment_rejects_dotdot() {
let err = CrateInfo::validate_segment("..").unwrap_err();
assert!(matches!(err, CrateInfoError::InvalidModuleSegment { .. }));
}
#[test]
fn test_validate_segment_rejects_forward_slash() {
let err = CrateInfo::validate_segment("foo/bar").unwrap_err();
assert!(matches!(err, CrateInfoError::InvalidModuleSegment { .. }));
}
#[test]
fn test_validate_segment_rejects_backslash() {
let err = CrateInfo::validate_segment("foo\\bar").unwrap_err();
assert!(matches!(err, CrateInfoError::InvalidModuleSegment { .. }));
}
#[test]
fn test_validate_segment_rejects_absolute_path() {
let err = CrateInfo::validate_segment("/etc/passwd").unwrap_err();
assert!(matches!(err, CrateInfoError::InvalidModuleSegment { .. }));
}
#[test]
fn test_validate_segment_rejects_empty() {
let err = CrateInfo::validate_segment("").unwrap_err();
assert!(matches!(err, CrateInfoError::InvalidModuleSegment { .. }));
}
#[test]
fn test_check_within_root_accepts_child() {
let dir = tempfile::tempdir().unwrap();
let child = dir.path().join("foo.rs");
fs::write(&child, "").unwrap();
assert!(CrateInfo::check_within_root(&child, dir.path()).is_ok());
}
#[test]
fn test_check_within_root_rejects_escape() {
let parent = tempfile::tempdir().unwrap();
let child = tempfile::tempdir().unwrap();
// child is outside parent
let err = CrateInfo::check_within_root(child.path(), parent.path()).unwrap_err();
assert!(matches!(err, CrateInfoError::PathTraversal));
}
#[test]
fn resolve_module_parts_empty_parts_returns_none() {
let dir = tempfile::tempdir().unwrap();
let result = CrateInfo::resolve_module_parts(dir.path(), &[], None).unwrap();
assert!(result.is_none());
}
#[test]
fn resolve_module_parts_2018_style_foo_rs() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("foo.rs");
fs::write(&file, "").unwrap();
let result = CrateInfo::resolve_module_parts(dir.path(), &["foo"], None).unwrap();
assert_eq!(result, Some(file));
}
#[test]
fn resolve_module_parts_legacy_mod_rs() {
let dir = tempfile::tempdir().unwrap();
let mod_dir = dir.path().join("bar");
fs::create_dir(&mod_dir).unwrap();
let file = mod_dir.join("mod.rs");
fs::write(&file, "").unwrap();
let result = CrateInfo::resolve_module_parts(dir.path(), &["bar"], None).unwrap();
assert_eq!(result, Some(file));
}
#[test]
fn resolve_module_parts_nested_via_companion_dir() {
// foo.rs + foo/ companion directory — submodule is in foo/sub.rs
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join("foo.rs"), "").unwrap();
let sub_dir = dir.path().join("foo");
fs::create_dir(&sub_dir).unwrap();
let sub_file = sub_dir.join("sub.rs");
fs::write(&sub_file, "").unwrap();
let result = CrateInfo::resolve_module_parts(dir.path(), &["foo", "sub"], None).unwrap();
assert_eq!(result, Some(sub_file));
}
#[test]
fn resolve_module_parts_nested_via_legacy_subdir() {
// bar/mod.rs + bar/sub.rs
let dir = tempfile::tempdir().unwrap();
let bar_dir = dir.path().join("bar");
fs::create_dir(&bar_dir).unwrap();
fs::write(bar_dir.join("mod.rs"), "").unwrap();
let sub_file = bar_dir.join("sub.rs");
fs::write(&sub_file, "").unwrap();
let result = CrateInfo::resolve_module_parts(dir.path(), &["bar", "sub"], None).unwrap();
assert_eq!(result, Some(sub_file));
}
#[test]
fn resolve_module_parts_inline_fallback_when_no_companion_dir() {
// foo.rs exists (with inline mod inner {}), no foo/ directory
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("foo.rs");
fs::write(&file, "pub mod inner {}").unwrap();
let result = CrateInfo::resolve_module_parts(dir.path(), &["foo", "inner"], None).unwrap();
assert_eq!(result, Some(file));
}
#[test]
fn resolve_module_parts_inline_module_via_root_file() {
// root_file contains `mod tests {}`, no tests.rs on disk
let dir = tempfile::tempdir().unwrap();
let lib_rs = dir.path().join("lib.rs");
fs::write(&lib_rs, "pub mod tests {}").unwrap();
let result =
CrateInfo::resolve_module_parts(dir.path(), &["tests"], Some(&lib_rs)).unwrap();
assert_eq!(result, Some(lib_rs));
}
#[test]
fn resolve_module_parts_returns_none_for_nonexistent() {
let dir = tempfile::tempdir().unwrap();
let result = CrateInfo::resolve_module_parts(dir.path(), &["missing"], None).unwrap();
assert!(result.is_none());
}
#[test]
fn resolve_module_parts_rejects_invalid_segment() {
let dir = tempfile::tempdir().unwrap();
let err = CrateInfo::resolve_module_parts(dir.path(), &[".."], None).unwrap_err();
assert!(matches!(err, CrateInfoError::InvalidModuleSegment { .. }));
}
#[test]
fn resolve_module_parts_inline_module_not_found_returns_none() {
// foo.rs exists but has no inline mod missing {}
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("foo.rs");
fs::write(&file, "pub fn bar() {}").unwrap();
let result =
CrateInfo::resolve_module_parts(dir.path(), &["foo", "missing"], None).unwrap();
assert!(result.is_none());
}
}