cargo-mend 0.3.2

Opinionated visibility auditing for Rust crates and workspaces
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
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::fs;
use std::path::Path;

use anyhow::Context;
use anyhow::Result;
use proc_macro2::LineColumn;
use syn::Expr;
use syn::ItemUse;
use syn::UseTree;
use syn::parse_file;
use syn::spanned::Spanned;
use syn::visit::Visit;
use walkdir::WalkDir;

use super::config::DiagnosticCode;
use super::diagnostics::Finding;
use super::diagnostics::Severity;
use super::fix_support::FixSupport;
use super::imports::UseFix;
use super::imports::ValidatedFixSet;
use super::module_paths;
use super::selection::Selection;

pub struct PreferModuleImportScan {
    pub findings: Vec<Finding>,
    pub fixes:    ValidatedFixSet,
}

pub fn scan_selection(selection: &Selection) -> Result<PreferModuleImportScan> {
    let mut all_findings = Vec::new();
    let mut all_fixes = Vec::new();
    for package_root in &selection.package_roots {
        let src_root = package_root.join("src");
        if !src_root.is_dir() {
            continue;
        }
        for entry in WalkDir::new(&src_root).into_iter().filter_map(Result::ok) {
            let path = entry.path();
            if !entry.file_type().is_file()
                || path.extension().and_then(|ext| ext.to_str()) != Some("rs")
            {
                continue;
            }
            let (findings, fixes) = scan_file(selection.analysis_root.as_path(), &src_root, path)?;
            all_findings.extend(findings);
            all_fixes.extend(fixes);
        }
    }
    all_findings.sort_by(|a, b| (&a.path, a.line, a.column).cmp(&(&b.path, b.line, b.column)));
    all_findings.dedup_by(|a, b| a.path == b.path && a.line == b.line && a.column == b.column);
    Ok(PreferModuleImportScan {
        findings: all_findings,
        fixes:    ValidatedFixSet::from_vec(all_fixes)?,
    })
}

struct RawCandidate {
    function_name:   String,
    module_name:     String,
    module_path:     String,
    replacement_use: String,
    span_start:      LineColumn,
    span_end:        LineColumn,
}

fn scan_file(
    analysis_root: &Path,
    src_root: &Path,
    path: &Path,
) -> Result<(Vec<Finding>, Vec<UseFix>)> {
    let text =
        fs::read_to_string(path).with_context(|| format!("failed to read {}", path.display()))?;
    let syntax =
        parse_file(&text).with_context(|| format!("failed to parse {}", path.display()))?;
    let current_module_path = module_paths::file_module_path(src_root, path)
        .with_context(|| format!("failed to determine module path for {}", path.display()))?;
    let offsets = line_offsets(&text);

    // Collect `mod` declarations in this file to avoid conflicts
    let declared_modules: BTreeSet<String> = syntax
        .items
        .iter()
        .filter_map(|item| {
            if let syn::Item::Mod(item_mod) = item
                && item_mod.content.is_none()
            {
                Some(item_mod.ident.to_string())
            } else {
                None
            }
        })
        .collect();

    // Pass 1: detect candidate function imports
    let mut detector = ImportDetector {
        src_root,
        current_module_path: &current_module_path,
        declared_modules: &declared_modules,
        candidates: Vec::new(),
    };
    detector.visit_file(&syntax);

    if detector.candidates.is_empty() {
        return Ok((Vec::new(), Vec::new()));
    }

    // Group by module path: multiple functions from the same module get one module import
    let mut module_to_functions: BTreeMap<String, Vec<RawCandidate>> = BTreeMap::new();
    for candidate in detector.candidates {
        module_to_functions
            .entry(candidate.module_path.clone())
            .or_default()
            .push(candidate);
    }

    // Collect all imported function names for reference collection
    let imported_names: BTreeSet<String> = module_to_functions
        .values()
        .flatten()
        .map(|c| c.function_name.clone())
        .collect();

    // Pass 2: find bare references to these function names
    let mut collector = ReferenceCollector {
        offsets:        &offsets,
        imported_names: &imported_names,
        references:     Vec::new(),
    };
    collector.visit_file(&syntax);

    // Build lookup: function name → module name
    let mut func_to_module: BTreeMap<&str, &str> = BTreeMap::new();
    for functions in module_to_functions.values() {
        for func in functions {
            func_to_module.insert(func.function_name.as_str(), func.module_name.as_str());
        }
    }

    let (findings, fixes) = build_findings_and_fixes(
        analysis_root,
        path,
        &text,
        &offsets,
        &module_to_functions,
        &func_to_module,
        &collector.references,
    );

    Ok((findings, fixes))
}

fn build_findings_and_fixes(
    analysis_root: &Path,
    path: &Path,
    text: &str,
    offsets: &[usize],
    module_to_functions: &BTreeMap<String, Vec<RawCandidate>>,
    func_to_module: &BTreeMap<&str, &str>,
    references: &[BareReference],
) -> (Vec<Finding>, Vec<UseFix>) {
    let display_path = path
        .strip_prefix(analysis_root)
        .unwrap_or(path)
        .to_string_lossy()
        .replace('\\', "/");

    let mut findings = Vec::new();
    let mut fixes = Vec::new();

    let mut rewritten_modules: BTreeSet<String> = BTreeSet::new();
    for functions in module_to_functions.values() {
        for func in functions {
            let byte_start = offset(offsets, func.span_start);
            let byte_end = offset(offsets, func.span_end);
            let byte_end_with_newline = if text.as_bytes().get(byte_end) == Some(&b'\n') {
                byte_end + 1
            } else {
                byte_end
            };

            let source_line = text
                .lines()
                .nth(func.span_start.line.saturating_sub(1))
                .unwrap_or_default()
                .to_string();

            findings.push(Finding {
                severity: Severity::Warning,
                code: DiagnosticCode::PreferModuleImport,
                path: display_path.clone(),
                line: func.span_start.line,
                column: func.span_start.column + 1,
                highlight_len: func.function_name.len().max(1),
                source_line,
                item: None,
                message: format!(
                    "import the module `{}` instead of the function `{}`",
                    func.module_name, func.function_name
                ),
                suggestion: Some(format!("consider using: `{}`", func.replacement_use)),
                fix_support: FixSupport::PreferModuleImport,
                related: None,
            });

            if rewritten_modules.insert(func.module_path.clone()) {
                fixes.push(UseFix {
                    path:        path.to_path_buf(),
                    start:       byte_start,
                    end:         byte_end,
                    replacement: func.replacement_use.clone(),
                });
            } else {
                fixes.push(UseFix {
                    path:        path.to_path_buf(),
                    start:       byte_start,
                    end:         byte_end_with_newline,
                    replacement: String::new(),
                });
            }
        }
    }

    for reference in references {
        if let Some(&module_name) = func_to_module.get(reference.name.as_str()) {
            fixes.push(UseFix {
                path:        path.to_path_buf(),
                start:       reference.byte_start,
                end:         reference.byte_end,
                replacement: format!("{module_name}::{}", reference.name),
            });
        }
    }

    (findings, fixes)
}

// --- Pass 1: Detect function imports ---

struct ImportDetector<'a> {
    src_root:            &'a Path,
    current_module_path: &'a [String],
    declared_modules:    &'a BTreeSet<String>,
    candidates:          Vec<RawCandidate>,
}

impl Visit<'_> for ImportDetector<'_> {
    fn visit_item_use(&mut self, node: &ItemUse) {
        if let Some(candidate) = analyze_function_import(
            self.src_root,
            self.current_module_path,
            self.declared_modules,
            node,
        ) {
            self.candidates.push(candidate);
        }
    }
}

fn analyze_function_import(
    src_root: &Path,
    current_module_path: &[String],
    declared_modules: &BTreeSet<String>,
    node: &ItemUse,
) -> Option<RawCandidate> {
    let flat = flatten_use_tree(&node.tree)?;

    // Skip renames
    if flat.rename.is_some() {
        return None;
    }

    // Must start with crate or super
    let first = flat.segments.first()?;
    if first != "crate" && first != "super" {
        return None;
    }

    // Need at least 3 segments: crate::module::function or super::module::function
    // With only 2 segments (e.g., `super::mesh`), the leaf is the module itself, not a function
    if flat.segments.len() < 3 {
        return None;
    }

    // The leaf must be snake_case (function)
    let leaf = flat.segments.last()?;
    if !is_snake_case_function_name(leaf) {
        return None;
    }

    // Resolve the import to absolute module segments for filesystem checks
    let absolute_segments = resolve_to_absolute(&flat.segments, current_module_path)?;

    // Check if the leaf is actually a module on the filesystem — module names are also
    // snake_case, so naming alone cannot distinguish them from functions
    if leaf_is_module(src_root, &absolute_segments) {
        return None;
    }

    // Build the module import path (everything except the leaf)
    let module_segments = &flat.segments[..flat.segments.len() - 1];
    let module_name = flat.segments[flat.segments.len() - 2].clone();

    // Skip if the module name is `super` — `use super::super;` is nonsensical
    if module_name == "super" || module_name == "crate" {
        return None;
    }

    // Skip if the module has a `mod` declaration in the same file — `use crate::foo;`
    // would conflict with `mod foo;`
    if declared_modules.contains(&module_name) {
        return None;
    }

    // Apply path shortening: try to use super:: instead of crate:: when possible
    let shortened_module_segments = shorten_module_path(current_module_path, module_segments);
    let module_path = shortened_module_segments.join("::");

    // Reconstruct the replacement use statement preserving visibility
    let vis_prefix = extract_visibility_prefix(node);
    let replacement_use = format!("{vis_prefix}use {module_path};");

    let span = node.span();

    Some(RawCandidate {
        function_name: leaf.clone(),
        module_name,
        module_path,
        replacement_use,
        span_start: span.start(),
        span_end: span.end(),
    })
}

fn resolve_to_absolute(segments: &[String], current_module_path: &[String]) -> Option<Vec<String>> {
    let first = segments.first()?;
    if first == "crate" {
        Some(segments[1..].to_vec())
    } else if first == "super" {
        let super_count = segments.iter().take_while(|s| *s == "super").count();
        if super_count > current_module_path.len() {
            return None;
        }
        let mut absolute = current_module_path[..current_module_path.len() - super_count].to_vec();
        absolute.extend(segments[super_count..].iter().cloned());
        Some(absolute)
    } else {
        None
    }
}

fn leaf_is_module(src_root: &Path, absolute_segments: &[String]) -> bool {
    if absolute_segments.is_empty() {
        return false;
    }
    // The parent segments form the directory path, the leaf is the potential module
    let parent_segments = &absolute_segments[..absolute_segments.len() - 1];
    let leaf = &absolute_segments[absolute_segments.len() - 1];

    let mut parent_dir = src_root.to_path_buf();
    for seg in parent_segments {
        parent_dir.push(seg);
    }

    // Check for leaf.rs or leaf/mod.rs under the parent directory
    parent_dir.join(format!("{leaf}.rs")).is_file()
        || parent_dir.join(leaf).join("mod.rs").is_file()
}

fn shorten_module_path(current_module_path: &[String], module_segments: &[String]) -> Vec<String> {
    // If the path already starts with super, keep it
    if module_segments.first().is_some_and(|s| s == "super") {
        return module_segments.to_vec();
    }

    // Only try to shorten crate:: paths
    let Some(first) = module_segments.first() else {
        return module_segments.to_vec();
    };
    if first != "crate" {
        return module_segments.to_vec();
    }

    // The target segments are everything after "crate"
    let target = &module_segments[1..];
    if target.is_empty() {
        return module_segments.to_vec();
    }

    let common = common_prefix_len(current_module_path, target);
    if common == 0 {
        return module_segments.to_vec();
    }

    let up_count = current_module_path.len().saturating_sub(common);
    // Only shorten if we go up at most 1 level
    if up_count > 1 {
        return module_segments.to_vec();
    }

    let mut relative = Vec::new();
    if up_count == 1 {
        relative.push("super".to_string());
    }
    relative.extend(target[common..].iter().cloned());

    // Only use shortened form if it's actually shorter or starts with super
    if relative.is_empty() || relative == module_segments[1..] {
        return module_segments.to_vec();
    }

    relative
}

fn common_prefix_len(left: &[String], right: &[String]) -> usize {
    left.iter()
        .zip(right.iter())
        .take_while(|(l, r)| l == r)
        .count()
}

fn extract_visibility_prefix(node: &ItemUse) -> String {
    match &node.vis {
        syn::Visibility::Public(_) => "pub ".to_string(),
        syn::Visibility::Restricted(vis) => {
            let path = &vis.path;
            format!("pub({}) ", quote::quote!(#path))
        },
        syn::Visibility::Inherited => String::new(),
    }
}

fn flatten_use_tree(tree: &UseTree) -> Option<FlattenedImport> {
    let mut segments = Vec::new();
    let mut rename = None;
    let mut cursor = tree;
    loop {
        match cursor {
            UseTree::Path(path) => {
                segments.push(path.ident.to_string());
                cursor = &path.tree;
            },
            UseTree::Name(name) => {
                segments.push(name.ident.to_string());
                break;
            },
            UseTree::Rename(rename_tree) => {
                segments.push(rename_tree.ident.to_string());
                rename = Some(rename_tree.rename.to_string());
                break;
            },
            // Grouped imports (`UseTree::Group`) or glob (`UseTree::Glob`) — skip
            _ => return None,
        }
    }
    Some(FlattenedImport { segments, rename })
}

struct FlattenedImport {
    segments: Vec<String>,
    rename:   Option<String>,
}

fn is_snake_case_function_name(name: &str) -> bool {
    let Some(first) = name.chars().next() else {
        return false;
    };
    if !first.is_ascii_lowercase() && first != '_' {
        return false;
    }
    // Reject UPPER_SNAKE_CASE constants (all uppercase + underscores + digits)
    if name
        .chars()
        .all(|ch| ch.is_ascii_uppercase() || ch == '_' || ch.is_ascii_digit())
    {
        return false;
    }
    name.chars()
        .all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_')
}

// --- Pass 2: Collect bare references ---

struct BareReference {
    name:       String,
    byte_start: usize,
    byte_end:   usize,
}

struct ReferenceCollector<'a> {
    offsets:        &'a [usize],
    imported_names: &'a BTreeSet<String>,
    references:     Vec<BareReference>,
}

impl Visit<'_> for ReferenceCollector<'_> {
    fn visit_item_use(&mut self, _: &ItemUse) {
        // Skip use statements — don't qualify references inside them
    }

    fn visit_expr(&mut self, node: &Expr) {
        match node {
            Expr::Path(expr_path) => {
                if expr_path.qself.is_none() && expr_path.path.segments.len() == 1 {
                    let seg = &expr_path.path.segments[0];
                    let name = seg.ident.to_string();
                    if self.imported_names.contains(&name) {
                        let span = seg.ident.span();
                        let start = offset(self.offsets, span.start());
                        let end = offset(self.offsets, span.end());
                        self.references.push(BareReference {
                            name,
                            byte_start: start,
                            byte_end: end,
                        });
                    }
                }
            },
            _ => syn::visit::visit_expr(self, node),
        }
    }
}

// --- Utilities ---

fn line_offsets(text: &str) -> Vec<usize> {
    let mut offsets = vec![0];
    for (idx, ch) in text.char_indices() {
        if ch == '\n' {
            offsets.push(idx + 1);
        }
    }
    offsets
}

fn offset(line_offsets: &[usize], position: LineColumn) -> usize {
    line_offsets
        .get(position.line.saturating_sub(1))
        .copied()
        .unwrap_or(0)
        + position.column
}

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

    #[test]
    fn snake_case_detects_functions() {
        assert!(is_snake_case_function_name("do_thing"));
        assert!(is_snake_case_function_name("func_a"));
        assert!(is_snake_case_function_name("process_data"));
        assert!(is_snake_case_function_name("a"));
    }

    #[test]
    fn snake_case_rejects_types() {
        assert!(!is_snake_case_function_name("MyType"));
        assert!(!is_snake_case_function_name("Thing"));
        assert!(!is_snake_case_function_name("PublicContainer"));
    }

    #[test]
    fn snake_case_rejects_constants() {
        assert!(!is_snake_case_function_name("MAX_SIZE"));
        assert!(!is_snake_case_function_name("DEFAULT_PORT"));
    }

    #[test]
    fn snake_case_rejects_empty() {
        assert!(!is_snake_case_function_name(""));
    }
}