cargo-mend 0.20.1

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
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
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::ffi::OsStr;
use std::fs;
use std::path::Path;

use anyhow::Context;
use anyhow::Result;
use syn::File;
use syn::Item;
use syn::ItemMod;
use syn::ItemUse;
use syn::UseTree;
use syn::parse_file;
use syn::spanned::Spanned;
use syn::visit::Visit;
use syn::visit::visit_item_mod;
use walkdir::WalkDir;

use super::attribute_references;
use super::function_imports::ImportDetector;
use super::function_imports::ImportTarget;
use super::function_imports::RawCandidate;
use super::inline_calls;
use super::inline_calls::InlineCallCandidate;
use super::inline_calls::InlineCallDetector;
use super::references::BareReference;
use super::references::ReferenceCollector;
use super::support;
use crate::compiler::SOURCE_DIR_SRC;
use crate::config::DiagnosticCode;
use crate::fixes::imports::ConditionalAttributes;
use crate::fixes::imports::ImportGroup;
use crate::fixes::imports::UseFix;
use crate::fixes::imports::ValidatedFixSet;
use crate::reporting::Finding;
use crate::reporting::FixSupport;
use crate::reporting::ItemVisibility;
use crate::reporting::Severity;
use crate::rust_syntax;
use crate::selection::Selection;

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

pub(super) struct ScanFileContext<'a> {
    pub(super) analysis_root: &'a Path,
    pub(super) path:          &'a Path,
    pub(super) text:          &'a str,
    pub(super) offsets:       &'a [usize],
}

impl ScanFileContext<'_> {
    pub(super) fn display_path(&self) -> String {
        self.path
            .strip_prefix(self.analysis_root)
            .unwrap_or(self.path)
            .to_string_lossy()
            .replace('\\', "/")
    }
}

/// A bare module import (`use path::to::module;`) recorded with the inline
/// `mod` chain that contains it — empty for file top level. An import inside
/// `mod tests` binds nothing at file top level (and vice versa), so every
/// decision that reuses or dedups against an existing import must compare
/// scopes, not just module paths.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(super) struct ScopedModuleImport {
    pub(super) inline_scope:    Vec<String>,
    pub(super) absolute_module: Vec<String>,
}

pub(super) struct ImportFindingInputs<'a> {
    module_to_functions:     &'a BTreeMap<String, Vec<RawCandidate>>,
    func_to_module:          &'a BTreeMap<&'a str, (&'a str, ImportTarget)>,
    references:              &'a [BareReference],
    /// Modules the file already imports with a bare `use module;`, keyed by
    /// scope. A function import whose target module is in this set at the same
    /// scope is rewritten to nothing (deleted) instead of to `use module;`,
    /// which would duplicate the existing import and fail to compile (E0252).
    existing_module_imports: &'a BTreeSet<ScopedModuleImport>,
}

pub(super) struct InlineCallFindingInputs<'a> {
    pub(super) candidates:            &'a [InlineCallCandidate],
    pub(super) will_import_modules:   &'a BTreeSet<Vec<String>>,
    pub(super) file_insertion_offset: usize,
}

pub(crate) 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 source_root = package_root.join(SOURCE_DIR_SRC);
        if !source_root.is_dir() {
            continue;
        }
        for entry in WalkDir::new(&source_root)
            .into_iter()
            .filter_map(Result::ok)
        {
            let path = entry.path();
            if !entry.file_type().is_file()
                || path.extension().and_then(OsStr::to_str) != Some("rs")
            {
                continue;
            }
            let (findings, fixes) =
                scan_file(selection.analysis_root.as_path(), &source_root, path)?;
            all_findings.extend(findings);
            all_fixes.extend(fixes);
        }
    }
    all_findings.sort_by(|left, right| {
        (&left.path, left.line, left.column).cmp(&(&right.path, right.line, right.column))
    });
    all_findings.dedup_by(|left, right| {
        left.path == right.path && left.line == right.line && left.column == right.column
    });
    Ok(PreferModuleImportScan {
        findings: all_findings,
        fixes:    ValidatedFixSet::try_from(all_fixes)?,
    })
}

fn scan_file(
    analysis_root: &Path,
    source_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 = rust_syntax::file_module_path(source_root, path)
        .with_context(|| format!("failed to determine module path for {}", path.display()))?;
    let offsets = support::line_offsets(&text);
    let file_context = ScanFileContext {
        analysis_root,
        path,
        text: &text,
        offsets: &offsets,
    };

    let declared_modules = collect_declared_modules(&syntax);

    let mut detector = ImportDetector {
        source_root,
        text: &text,
        offsets: &offsets,
        current_module_path: current_module_path.clone(),
        inline_scope: Vec::new(),
        declared_modules: &declared_modules,
        candidates: Vec::new(),
    };
    Visit::visit_file(&mut detector, &syntax);

    let mut inline_detector = InlineCallDetector {
        source_root,
        text: &text,
        offsets: &offsets,
        current_module_path: &current_module_path,
        declared_modules: &declared_modules,
        candidates: Vec::new(),
        inline_mod_depth: 0,
        conditional_attributes: ConditionalAttributes::default(),
    };
    Visit::visit_file(&mut inline_detector, &syntax);

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

    let existing_module_imports =
        collect_existing_module_imports(&syntax, source_root, &current_module_path);

    let mut module_to_functions = group_candidates_by_module(detector.candidates);

    drop_colliding_candidates(
        &existing_module_imports,
        &mut module_to_functions,
        &mut inline_detector.candidates,
    );

    drop_attribute_referenced_candidates(&syntax, &mut module_to_functions);

    drop_candidates_reimported_by_inline_modules(&syntax, &mut module_to_functions);

    // Last, so the drops above get to un-collide a pair by removing one side.
    drop_candidates_colliding_with_each_other(
        &mut module_to_functions,
        &mut inline_detector.candidates,
    );

    if module_to_functions.is_empty() && inline_detector.candidates.is_empty() {
        return Ok((Vec::new(), Vec::new()));
    }

    let imported_names: BTreeSet<String> = module_to_functions
        .values()
        .flatten()
        .map(|candidate| candidate.function_name.clone())
        .collect();

    let mut collector = ReferenceCollector::new(&offsets, &imported_names);
    Visit::visit_file(&mut collector, &syntax);

    let mut func_to_module: BTreeMap<&str, (&str, ImportTarget)> = BTreeMap::new();
    for functions in module_to_functions.values() {
        for function in functions {
            func_to_module.insert(
                function.function_name.as_str(),
                (function.module_name.as_str(), function.import_target),
            );
        }
    }

    let (mut findings, mut fixes) = build_findings_and_fixes(
        &file_context,
        &ImportFindingInputs {
            module_to_functions:     &module_to_functions,
            func_to_module:          &func_to_module,
            references:              &collector.references,
            existing_module_imports: &existing_module_imports,
        },
    );

    if !inline_detector.candidates.is_empty() {
        let will_import_modules =
            build_will_import_modules(&existing_module_imports, &module_to_functions);
        let file_insertion_offset = file_level_insertion_offset(&syntax, &text, &offsets);
        let (inline_findings, inline_fixes) = inline_calls::build_inline_call_findings_and_fixes(
            &file_context,
            &InlineCallFindingInputs {
                candidates: &inline_detector.candidates,
                will_import_modules: &will_import_modules,
                file_insertion_offset,
            },
        );
        findings.extend(inline_findings);
        fixes.extend(inline_fixes);
    }

    Ok((findings, fixes))
}

fn group_candidates_by_module(
    candidates: Vec<RawCandidate>,
) -> BTreeMap<String, Vec<RawCandidate>> {
    let mut grouped: BTreeMap<String, Vec<RawCandidate>> = BTreeMap::new();
    for candidate in candidates {
        grouped
            .entry(candidate.module_path.clone())
            .or_default()
            .push(candidate);
    }
    grouped
}

fn collect_declared_modules(syntax: &File) -> BTreeSet<String> {
    syntax
        .items
        .iter()
        .filter_map(|item| {
            if let Item::Mod(item_mod) = item
                && item_mod.content.is_none()
            {
                Some(item_mod.ident.to_string())
            } else {
                None
            }
        })
        .collect()
}

fn collect_existing_module_imports(
    syntax: &File,
    source_root: &Path,
    current_module_path: &[String],
) -> BTreeSet<ScopedModuleImport> {
    let mut collector = ExistingModuleImportCollector {
        source_root,
        current_module_path: current_module_path.to_vec(),
        inline_scope: Vec::new(),
        imports: BTreeSet::new(),
    };
    Visit::visit_file(&mut collector, syntax);
    collector.imports
}

struct ExistingModuleImportCollector<'a> {
    source_root:         &'a Path,
    current_module_path: Vec<String>,
    inline_scope:        Vec<String>,
    imports:             BTreeSet<ScopedModuleImport>,
}

impl Visit<'_> for ExistingModuleImportCollector<'_> {
    fn visit_item_use(&mut self, node: &ItemUse) {
        if let Some(flat) = support::flatten_use_tree(&node.tree)
            && flat.rename.is_none()
            && let Some(absolute) =
                support::resolve_to_absolute(&flat.segments, &self.current_module_path)
            && !absolute.is_empty()
            && support::leaf_is_module(self.source_root, &absolute)
        {
            self.imports.insert(ScopedModuleImport {
                inline_scope:    self.inline_scope.clone(),
                absolute_module: absolute,
            });
        }
    }

    fn visit_item_mod(&mut self, node: &ItemMod) {
        if node.content.is_some() {
            self.current_module_path.push(node.ident.to_string());
            self.inline_scope.push(node.ident.to_string());
            visit_item_mod(self, node);
            self.inline_scope.pop();
            self.current_module_path.pop();
        } else {
            visit_item_mod(self, node);
        }
    }
}

/// Drop candidates that would bind one module name to two different modules in
/// the same scope. Two deep imports whose modules share a leaf name — say
/// `crate::orbit_cam::controller` alongside `crate::free_cam::controller` — each
/// want `use <leaf>;`, which collides (E0252) and leaves the call sites
/// resolving to whichever import won (E0425).
///
/// The combining layer drops these fixes before anything is written, so
/// reporting them advertised a fix that never arrived: every run named the same
/// two imports as fixable, wrote nothing, and named them again. Leave them
/// untouched, as [`drop_colliding_candidates`] does for the same collision
/// against an import the file already has.
fn drop_candidates_colliding_with_each_other(
    module_to_functions: &mut BTreeMap<String, Vec<RawCandidate>>,
    inline_candidates: &mut Vec<InlineCallCandidate>,
) {
    // Inline call candidates are only detected at file top level, so their
    // scope is always the empty chain — the same key the detector gives a
    // top-level `RawCandidate`.
    let mut name_to_modules: BTreeMap<(Vec<String>, String), BTreeSet<Vec<String>>> =
        BTreeMap::new();
    for candidate in module_to_functions.values().flatten() {
        name_to_modules
            .entry((
                candidate.inline_scope.clone(),
                candidate.module_name.clone(),
            ))
            .or_default()
            .insert(candidate.absolute_module.clone());
    }
    for candidate in inline_candidates.iter() {
        name_to_modules
            .entry((Vec::new(), candidate.module_name.clone()))
            .or_default()
            .insert(candidate.absolute_module.clone());
    }

    let colliding: BTreeSet<(Vec<String>, String)> = name_to_modules
        .into_iter()
        .filter(|(_, modules)| modules.len() > 1)
        .map(|(key, _)| key)
        .collect();

    if colliding.is_empty() {
        return;
    }

    module_to_functions.retain(|_, functions| {
        functions.retain(|candidate| {
            !colliding.contains(&(
                candidate.inline_scope.clone(),
                candidate.module_name.clone(),
            ))
        });
        !functions.is_empty()
    });
    inline_candidates
        .retain(|candidate| !colliding.contains(&(Vec::new(), candidate.module_name.clone())));
}

/// Drop candidates whose target module name is already bound in the same scope
/// to a *different* module. Introducing `use <module>;` would collide with that
/// existing import (E0252), and rewriting the call to `name::fn(...)` would
/// resolve to the wrong module (E0425). Leave such imports untouched rather than
/// emit an unfixable finding.
fn drop_colliding_candidates(
    existing_module_imports: &BTreeSet<ScopedModuleImport>,
    module_to_functions: &mut BTreeMap<String, Vec<RawCandidate>>,
    inline_candidates: &mut Vec<InlineCallCandidate>,
) {
    module_to_functions.retain(|_, functions| {
        functions.retain(|candidate| {
            !module_name_collides(
                existing_module_imports,
                &candidate.inline_scope,
                &candidate.module_name,
                &candidate.absolute_module,
            )
        });
        !functions.is_empty()
    });
    // Inline call candidates are only detected at file top level (the detector
    // skips inline `mod` bodies), so their scope is always the empty chain.
    inline_candidates.retain(|candidate| {
        !module_name_collides(
            existing_module_imports,
            &[],
            &candidate.module_name,
            &candidate.absolute_module,
        )
    });
}

/// True when the same scope already imports a *different* module under the same
/// bare name that a prefer-module-import rewrite would introduce. Rewriting to
/// `use <module>;` in that case duplicates the name (E0252) and misroutes the
/// qualified call (E0425). The same-module case (`absolute_module` equal to an
/// existing import) is handled separately by deleting the redundant import.
fn module_name_collides(
    existing_module_imports: &BTreeSet<ScopedModuleImport>,
    inline_scope: &[String],
    module_name: &str,
    absolute_module: &[String],
) -> bool {
    existing_module_imports.iter().any(|imported| {
        imported.inline_scope == inline_scope
            && imported.absolute_module.last().map(String::as_str) == Some(module_name)
            && imported.absolute_module.as_slice() != absolute_module
    })
}

/// Drop candidates whose function name is mentioned by an attribute. Attribute
/// payloads belong to the attribute macro's grammar rather than to the path
/// graph the rewrite walks — `#[serde(default = "make_default")]` names the
/// function as a string literal — so the reference collector never sees them and
/// removing the import would leave the name unresolved (E0425). Leave such
/// imports untouched rather than emit a fix that does not compile.
///
/// Inline call candidates are unaffected: they add a module import and shorten a
/// path that is already fully qualified, so nothing an attribute names stops
/// resolving.
/// Drop candidates an inline `mod` re-imports from the file's own top level.
///
/// `#[cfg(test)] mod tests { use super::reflect_component_for; }` sitting under
/// a file-scope `use crate::capabilities::reflect_component_for;` names that
/// file-scope binding. Rewriting the outer import to `use crate::capabilities;`
/// leaves the inner `use` naming nothing (E0432), and the module has no
/// `capabilities` binding to reach the function through (E0433). The pair only
/// works rewritten together, so leave both alone and report nothing rather than
/// emit a fix that compiles in the file but not in the module below it.
///
/// A glob (`use super::*;`) is not a re-import: it makes whatever the file
/// binds visible, so the new `use crate::capabilities;` arrives with it and the
/// references inside the module follow the rewrite normally.
fn drop_candidates_reimported_by_inline_modules(
    syntax: &File,
    module_to_functions: &mut BTreeMap<String, Vec<RawCandidate>>,
) {
    let mut collector = InlineSuperReimportCollector {
        inline_mod_depth: 0,
        names:            BTreeSet::new(),
    };
    Visit::visit_file(&mut collector, syntax);
    if collector.names.is_empty() {
        return;
    }

    module_to_functions.retain(|_, functions| {
        functions.retain(|candidate| {
            !candidate.inline_scope.is_empty()
                || !collector.names.contains(&candidate.function_name)
        });
        !functions.is_empty()
    });
}

struct InlineSuperReimportCollector {
    inline_mod_depth: usize,
    names:            BTreeSet<String>,
}

impl Visit<'_> for InlineSuperReimportCollector {
    fn visit_item_mod(&mut self, node: &ItemMod) {
        if node.content.is_some() {
            self.inline_mod_depth += 1;
            visit_item_mod(self, node);
            self.inline_mod_depth -= 1;
        } else {
            visit_item_mod(self, node);
        }
    }

    fn visit_item_use(&mut self, node: &ItemUse) {
        if self.inline_mod_depth == 0 {
            return;
        }
        collect_super_reimports(
            &node.tree,
            &mut Vec::new(),
            self.inline_mod_depth,
            &mut self.names,
        );
    }
}

/// Leaf names of `use` paths that climb exactly `depth` `super` segments — from
/// inside an inline `mod` nested `depth` deep, that is the file's own top level.
fn collect_super_reimports(
    tree: &UseTree,
    prefix: &mut Vec<String>,
    depth: usize,
    names: &mut BTreeSet<String>,
) {
    match tree {
        UseTree::Path(path) => {
            prefix.push(path.ident.to_string());
            collect_super_reimports(&path.tree, prefix, depth, names);
            prefix.pop();
        },
        UseTree::Name(name) => {
            if reaches_file_top_level(prefix, depth) {
                names.insert(name.ident.to_string());
            }
        },
        UseTree::Rename(rename) => {
            if reaches_file_top_level(prefix, depth) {
                names.insert(rename.ident.to_string());
            }
        },
        UseTree::Group(group) => {
            for item in &group.items {
                collect_super_reimports(item, prefix, depth, names);
            }
        },
        UseTree::Glob(_) => {},
    }
}

fn reaches_file_top_level(prefix: &[String], depth: usize) -> bool {
    prefix.len() == depth && prefix.iter().all(|segment| segment == "super")
}

fn drop_attribute_referenced_candidates(
    syntax: &File,
    module_to_functions: &mut BTreeMap<String, Vec<RawCandidate>>,
) {
    let attribute_names = attribute_references::collect(syntax);
    module_to_functions.retain(|_, functions| {
        functions.retain(|candidate| !attribute_names.contains(&candidate.function_name));
        !functions.is_empty()
    });
}

/// Modules that will be importable at file top level once the planned `use`
/// rewrites are applied. Imports and candidates inside inline `mod` blocks are
/// excluded: a `use` inside `mod tests` does not cover a top-level call site,
/// so it must not suppress the insertion of a top-level `use`.
fn build_will_import_modules(
    existing_module_imports: &BTreeSet<ScopedModuleImport>,
    module_to_functions: &BTreeMap<String, Vec<RawCandidate>>,
) -> BTreeSet<Vec<String>> {
    let mut will_import_modules: BTreeSet<Vec<String>> = existing_module_imports
        .iter()
        .filter(|import| import.inline_scope.is_empty())
        .map(|import| import.absolute_module.clone())
        .collect();
    for functions in module_to_functions.values() {
        for candidate in functions {
            if candidate.inline_scope.is_empty() {
                will_import_modules.insert(candidate.absolute_module.clone());
            }
        }
    }
    will_import_modules
}

fn file_level_insertion_offset(syntax: &File, text: &str, offsets: &[usize]) -> usize {
    let mut last_use_end: Option<usize> = None;
    let mut first_item_start: Option<usize> = None;
    for item in &syntax.items {
        let item_start = support::offset(offsets, item.span().start());
        first_item_start.get_or_insert(item_start);
        if let Item::Use(item_use) = item {
            let end = support::offset(offsets, item_use.span().end());
            let end = if text.as_bytes().get(end) == Some(&b'\n') {
                end + 1
            } else {
                end
            };
            last_use_end = Some(end);
        }
    }
    last_use_end.or(first_item_start).unwrap_or(0)
}

fn build_findings_and_fixes(
    file_context: &ScanFileContext<'_>,
    import_inputs: &ImportFindingInputs<'_>,
) -> (Vec<Finding>, Vec<UseFix>) {
    let display_path = file_context.display_path();
    let mut findings = Vec::new();
    let mut fixes = Vec::new();
    let mut rewritten_modules: BTreeSet<ScopedModuleImport> = BTreeSet::new();

    for functions in import_inputs.module_to_functions.values() {
        for function in functions {
            findings.push(build_function_finding(
                function,
                &display_path,
                file_context,
            ));
            fixes.push(build_function_use_fix(
                function,
                file_context,
                import_inputs.existing_module_imports,
                &mut rewritten_modules,
            ));
        }
    }

    fixes.extend(build_reference_fixes(file_context, import_inputs));

    (findings, fixes)
}

fn build_function_finding(
    function: &RawCandidate,
    display_path: &str,
    file_context: &ScanFileContext<'_>,
) -> Finding {
    let source_line = file_context
        .text
        .lines()
        .nth(function.span_start.line.saturating_sub(1))
        .unwrap_or_default()
        .to_string();

    let (message, suggestion) = if function.import_target == ImportTarget::ParentModule {
        (
            format!(
                "drop the import and call `super::{}` directly",
                function.function_name
            ),
            Some(format!(
                "remove this `use` and call `super::{}` at the use sites",
                function.function_name
            )),
        )
    } else {
        (
            format!(
                "import the module `{}` instead of the function `{}`",
                function.module_name, function.function_name
            ),
            Some(format!("consider using: `{}`", function.replacement_use)),
        )
    };

    Finding {
        severity: Severity::Warning,
        diagnostic_code: DiagnosticCode::PreferModuleImport,
        path: display_path.to_string(),
        line: function.span_start.line,
        column: function.span_start.column + 1,
        highlight_len: function.function_name.len().max(1),
        source_line,
        item: None,
        message,
        suggestion,
        fix_support: FixSupport::PreferModuleImport,
        related: None,
        item_visibility: ItemVisibility::default(),
    }
}

fn build_function_use_fix(
    function: &RawCandidate,
    file_context: &ScanFileContext<'_>,
    existing_module_imports: &BTreeSet<ScopedModuleImport>,
    rewritten_modules: &mut BTreeSet<ScopedModuleImport>,
) -> UseFix {
    let byte_start = support::offset(file_context.offsets, function.span_start);
    let byte_end = support::offset(file_context.offsets, function.span_end);
    let byte_end_with_newline = if file_context.text.as_bytes().get(byte_end) == Some(&b'\n') {
        byte_end + 1
    } else {
        byte_end
    };
    let group = Some(ImportGroup {
        bare_name: function.module_name.clone(),
        full_path: function.absolute_module.join("::"),
    });
    let scoped_module = ScopedModuleImport {
        inline_scope:    function.inline_scope.clone(),
        absolute_module: function.absolute_module.clone(),
    };

    if function.import_target == ImportTarget::ParentModule
        || existing_module_imports.contains(&scoped_module)
    {
        // Either call sites become `super::fn(...)` (parent module, no `use`
        // needed), or the same scope already imports the target module — so
        // the function import is redundant. Delete the line in both cases;
        // rewriting it to `use module;` when the module is already imported
        // would produce a duplicate import (E0252).
        UseFix {
            path:         file_context.path.to_path_buf(),
            start:        byte_start,
            end:          byte_end_with_newline,
            replacement:  String::new(),
            import_group: group,
        }
    } else if rewritten_modules.insert(scoped_module) {
        UseFix {
            path:         file_context.path.to_path_buf(),
            start:        byte_start,
            end:          byte_end,
            replacement:  replacement_use_with_conditional_attributes(function),
            import_group: group,
        }
    } else {
        UseFix {
            path:         file_context.path.to_path_buf(),
            start:        byte_start,
            end:          byte_end_with_newline,
            replacement:  String::new(),
            import_group: group,
        }
    }
}

fn replacement_use_with_conditional_attributes(function: &RawCandidate) -> String {
    if function.conditional_attributes.is_empty() {
        return function.replacement_use.clone();
    }

    let mut replacement = function.conditional_attributes.render("");
    replacement.push_str(&" ".repeat(function.span_start.column));
    replacement.push_str(&function.replacement_use);
    replacement
}

fn build_reference_fixes(
    file_context: &ScanFileContext<'_>,
    import_inputs: &ImportFindingInputs<'_>,
) -> Vec<UseFix> {
    let mut fixes = Vec::new();
    for reference in import_inputs.references {
        if let Some(&(module_name, import_target)) =
            import_inputs.func_to_module.get(reference.name.as_str())
        {
            let group = import_inputs
                .module_to_functions
                .values()
                .flatten()
                .find(|function| function.module_name == module_name)
                .map(|function| ImportGroup {
                    bare_name: function.module_name.clone(),
                    full_path: function.absolute_module.join("::"),
                });
            let replacement = if import_target == ImportTarget::ParentModule {
                // Inside an inline `mod` (e.g. `#[cfg(test)] mod tests`) the
                // file's parent is one `super` further away per nesting level.
                let supers = "super::".repeat(reference.inline_mod_depth + 1);
                format!("{supers}{}", reference.name)
            } else {
                format!("{module_name}::{}", reference.name)
            };
            fixes.push(UseFix {
                path: file_context.path.to_path_buf(),
                start: reference.byte_start,
                end: reference.byte_end,
                replacement,
                import_group: group,
            });
        }
    }
    fixes
}