Skip to main content

fallow_engine/health/
scoring.rs

1use fallow_output::{DirectCallerEvidence, DirectCallerSymbolEvidence, FileHealthScore};
2
3use crate::module_graph::StaticTestCoverage;
4
5use super::coverage_gaps::compute_coverage_gaps;
6pub(super) use super::coverage_gaps::{CoverageGapData, build_coverage_summary};
7use super::coverage_input::{CoverageInput, read_coverage_input};
8use super::test_reach::build_test_referenced_exports;
9use super::threshold_overrides::ThresholdOverrideResolver;
10
11const MAX_FUNCTION_EVIDENCE: usize = 3;
12
13/// Output from `compute_file_scores`, including auxiliary data for refactoring targets.
14pub struct FileScoreOutput {
15    pub(crate) scores: Vec<FileHealthScore>,
16    /// Static coverage gaps derived from runtime-vs-test reachability.
17    pub(crate) coverage: CoverageGapData,
18    /// Files participating in circular dependencies (absolute paths).
19    pub(crate) circular_files: rustc_hash::FxHashSet<std::path::PathBuf>,
20    /// Top 3 functions by cognitive complexity per file (name, line, cognitive score).
21    pub(crate) top_complex_fns: rustc_hash::FxHashMap<std::path::PathBuf, Vec<(String, u32, u16)>>,
22    /// Eligible CRAP breaches, ranked and capped separately from structural evidence.
23    pub(crate) crap_target_fns: rustc_hash::FxHashMap<std::path::PathBuf, Vec<(String, u32, u16)>>,
24    /// Files that are configured entry points.
25    pub(crate) entry_points: rustc_hash::FxHashSet<std::path::PathBuf>,
26    /// Total number of value exports per file (for dead code gate: total_value_exports >= 3).
27    pub(crate) value_export_counts: rustc_hash::FxHashMap<std::path::PathBuf, usize>,
28    /// Unused export names per file (for evidence linking).
29    pub(crate) unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
30    /// Cycle members per file: maps each file to the other files in its cycle.
31    pub(crate) cycle_members: rustc_hash::FxHashMap<std::path::PathBuf, Vec<std::path::PathBuf>>,
32    /// Direct importers per file, with the symbols imported by each caller.
33    pub(crate) direct_callers: rustc_hash::FxHashMap<std::path::PathBuf, Vec<DirectCallerEvidence>>,
34    /// Aggregate counts from AnalysisResults for vital signs (project-wide).
35    pub(crate) analysis_counts: crate::vital_signs::AnalysisCounts,
36    /// Located prop-drilling chains from the analysis results (empty when the
37    /// opt-in `prop-drilling` rule is off, since the detector populates no chains
38    /// then). Drives the small capped health penalty, the hotspot surface, and
39    /// the `health --format json` `prop_drilling_chains` array.
40    pub(crate) prop_drilling_chains: Vec<fallow_types::output_dead_code::PropDrillingChainFinding>,
41    /// Per-component render fan-in (JSX render SITES + distinct parents) plus the
42    /// precomputed concentration aggregates, cloned from the analysis results.
43    /// `None` on non-React projects. Descriptive blast-radius signal: feeds the
44    /// `VitalSigns` render-fan-in aggregates and the hotspot/react drill-down
45    /// `rendered in N places` line (keyed back to file paths).
46    pub(crate) render_fan_in: Option<fallow_types::results::RenderFanInMetric>,
47    /// Per-path snapshot of analysis findings, used to recompute
48    /// [`crate::vital_signs::AnalysisCounts`] for an arbitrary subset of files
49    /// (workspace scoping, `--group-by` partitioning).
50    pub(crate) analysis_snapshot: AnalysisCountsSnapshot,
51    /// Istanbul match stats: functions matched / total (only meaningful with Istanbul model).
52    pub(crate) istanbul_matched: usize,
53    pub(crate) istanbul_total: usize,
54    /// Analyzed files the coverage map carried an entry for. Read against the
55    /// map's own file count, this separates a map that did not join from code
56    /// the map says nothing ran in.
57    pub(crate) istanbul_files_joined: usize,
58    /// Files the coverage map describes, joined or not. Zero without a map.
59    pub(crate) istanbul_files_total: usize,
60    /// Input format of the coverage map. `None` without a map.
61    pub(crate) coverage_input_format: Option<fallow_output::CoverageInputFormat>,
62    /// Per-file, per-function CRAP data used to emit `--max-crap` findings.
63    /// Absolute paths match `FileHealthScore.path`. Absent entries indicate the
64    /// file had zero functions.
65    pub(crate) per_function_crap: rustc_hash::FxHashMap<std::path::PathBuf, Vec<PerFunctionCrap>>,
66    /// Provenance map for synthetic Angular `<template>` findings whose CRAP
67    /// was inherited from the owning `.component.ts` via the inverse
68    /// `templateUrl` edge. Keys are the template `.html` absolute paths,
69    /// values are the owner `.ts` absolute paths (the path used for the
70    /// `inherited from foo.component.ts` human-output suffix). Absent for
71    /// non-template files and for templates with no `.ts` owner.
72    pub(crate) template_inherit_provenance:
73        rustc_hash::FxHashMap<std::path::PathBuf, std::path::PathBuf>,
74    /// Static edges between analyzed files. Change coupling reads it to tell a
75    /// hidden co-change pair from a pair that an import already explains.
76    /// `None` when the run reads no commit history.
77    pub(crate) static_links: Option<crate::change_coupling::StaticLinkIndex>,
78}
79
80struct FileScoreOutputParts<'a> {
81    graph: &'a fallow_graph::graph::ModuleGraph,
82    with_static_links: bool,
83    file_paths: &'a rustc_hash::FxHashMap<crate::discover::FileId, &'a std::path::PathBuf>,
84    results: &'a crate::results::AnalysisResults,
85    scores: Vec<FileHealthScore>,
86    coverage: CoverageGapData,
87    circular_files: rustc_hash::FxHashSet<std::path::PathBuf>,
88    top_complex_fns: rustc_hash::FxHashMap<std::path::PathBuf, Vec<(String, u32, u16)>>,
89    crap_target_fns: rustc_hash::FxHashMap<std::path::PathBuf, Vec<(String, u32, u16)>>,
90    entry_points: rustc_hash::FxHashSet<std::path::PathBuf>,
91    value_export_counts: rustc_hash::FxHashMap<std::path::PathBuf, usize>,
92    unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
93    cycle_members: rustc_hash::FxHashMap<std::path::PathBuf, Vec<std::path::PathBuf>>,
94    direct_callers: rustc_hash::FxHashMap<std::path::PathBuf, Vec<DirectCallerEvidence>>,
95    istanbul_matched: usize,
96    istanbul_total: usize,
97    istanbul_files_joined: usize,
98    istanbul_files_total: usize,
99    coverage_input_format: Option<fallow_output::CoverageInputFormat>,
100    per_function_crap: rustc_hash::FxHashMap<std::path::PathBuf, Vec<PerFunctionCrap>>,
101    template_inherit: rustc_hash::FxHashMap<crate::discover::FileId, TemplateInheritContext>,
102}
103
104/// Per-path snapshot of analysis-pipeline findings, retained alongside the
105/// pre-aggregated `analysis_counts` so that workspace- or group-scoped runs
106/// can recompute counts without re-running the full pipeline.
107///
108/// All paths are absolute (matching `AnalysisResults` and `FileHealthScore`).
109#[derive(Clone, Default)]
110pub struct AnalysisCountsSnapshot {
111    /// One entry per unused file.
112    unused_file_paths: Vec<std::path::PathBuf>,
113    /// One entry per unused value or type export, keyed by the file containing
114    /// the export.
115    unused_export_paths: Vec<std::path::PathBuf>,
116    /// One entry per unused dependency across `dependencies`,
117    /// `devDependencies`, and `optionalDependencies`, keyed by the
118    /// `package.json` path that declared it.
119    unused_dep_package_paths: Vec<std::path::PathBuf>,
120    /// Each cycle as the set of file paths it contains. Used to count cycles
121    /// that touch any file inside a workspace.
122    circular_dep_groups: Vec<Vec<std::path::PathBuf>>,
123    /// Total exports per module (`module.exports.len()` in the graph), used
124    /// as the denominator for `dead_export_pct`.
125    module_export_counts: rustc_hash::FxHashMap<std::path::PathBuf, usize>,
126}
127
128impl AnalysisCountsSnapshot {
129    /// Compute analysis counts for the file subset selected by `subset`.
130    ///
131    /// Returns `*defaults` when `subset.is_full()`. Otherwise recomputes
132    /// every count by retaining paths the subset accepts. Cycles are counted
133    /// when any cycle member is in the subset.
134    ///
135    /// Unused-dep counting is special-cased: dep entries are keyed by their
136    /// `package.json` path, which is never a source file and therefore never
137    /// matches the source-file membership of a `Paths` subset. For
138    /// `SubsetFilter::Paths`, a `package.json` is considered
139    /// in scope when at least one source file in the subset sits inside its
140    /// directory (the dep's owning workspace).
141    ///
142    /// `total_deps` is propagated unchanged from `defaults`; it is not
143    /// available per-subset today (mirrors the project-wide behaviour).
144    pub(crate) fn counts_for(
145        &self,
146        subset: &crate::health::SubsetFilter<'_>,
147        defaults: &crate::vital_signs::AnalysisCounts,
148    ) -> crate::vital_signs::AnalysisCounts {
149        if subset.is_full() {
150            return *defaults;
151        }
152        let dead_files = self
153            .unused_file_paths
154            .iter()
155            .filter(|p| subset.matches(p))
156            .count();
157        let dead_exports = self
158            .unused_export_paths
159            .iter()
160            .filter(|p| subset.matches(p))
161            .count();
162        let unused_deps = self
163            .unused_dep_package_paths
164            .iter()
165            .filter(|dep_path| dep_in_subset(subset, dep_path))
166            .count();
167        let circular_deps = self
168            .circular_dep_groups
169            .iter()
170            .filter(|cycle| cycle.iter().any(|p| subset.matches(p)))
171            .count();
172        let total_exports = self
173            .module_export_counts
174            .iter()
175            .filter(|(p, _)| subset.matches(p))
176            .map(|(_, n)| *n)
177            .sum();
178        crate::vital_signs::AnalysisCounts {
179            total_exports,
180            dead_files,
181            dead_exports,
182            unused_deps,
183            circular_deps,
184            total_deps: defaults.total_deps,
185        }
186    }
187}
188
189/// Return true when an unused dependency's `package.json` path belongs to
190/// the subset.
191///
192/// For [`crate::health::SubsetFilter::Paths`] the dep's containing workspace
193/// (its `package.json` parent directory) is considered in scope when at
194/// least one source file in the subset lives under that directory.
195fn dep_in_subset(subset: &crate::health::SubsetFilter<'_>, dep_path: &std::path::Path) -> bool {
196    match subset {
197        crate::health::SubsetFilter::Full => true,
198        crate::health::SubsetFilter::Paths(set) => {
199            let Some(workspace_root) = dep_path.parent() else {
200                return false;
201            };
202            set.iter().any(|p| p.starts_with(workspace_root))
203        }
204    }
205}
206
207/// Aggregate complexity totals from a parsed module.
208///
209/// Returns `(total_cyclomatic, total_cognitive, function_count, lines)`.
210///
211/// Every unit counts, including the synthetic `<module>` unit that carries the
212/// file's module-scope decision points. `function_count` therefore counts a
213/// non-function unit on files that branch outside every function, which is the
214/// point: complexity density measured against a total that skipped module
215/// scope understated the file.
216#[expect(
217    clippy::cast_possible_truncation,
218    reason = "line count is bounded by source file size"
219)]
220fn aggregate_complexity(module: &crate::source::ModuleInfo) -> (u32, u32, usize, u32) {
221    let cyc: u32 = module
222        .complexity
223        .iter()
224        .map(|f| u32::from(f.cyclomatic))
225        .sum();
226    let cog: u32 = module
227        .complexity
228        .iter()
229        .map(|f| u32::from(f.cognitive))
230        .sum();
231    let funcs = module.complexity.len();
232    let lines = module.line_offsets.len() as u32;
233    (cyc, cog, funcs, lines)
234}
235
236/// Compute the dead code ratio for a single file.
237///
238/// Returns the fraction of VALUE exports with zero references (0.0-1.0).
239/// Type-only exports (interfaces, type aliases) are excluded from both
240/// numerator and denominator to avoid inflating the ratio for well-typed
241/// codebases. Returns 1.0 if the entire file is unused, 0.0 if it has no
242/// value exports.
243fn compute_dead_code_ratio(
244    path: &std::path::Path,
245    exports: &[fallow_graph::graph::ExportSymbol],
246    unused_files: &rustc_hash::FxHashSet<&std::path::Path>,
247    unused_exports_by_path: &rustc_hash::FxHashMap<&std::path::Path, usize>,
248) -> f64 {
249    if unused_files.contains(path) {
250        return 1.0;
251    }
252    let value_exports = exports.iter().filter(|e| !e.is_type_only).count();
253    if value_exports == 0 {
254        return 0.0;
255    }
256    let unused = unused_exports_by_path.get(path).copied().unwrap_or(0);
257    (unused as f64 / value_exports as f64).min(1.0)
258}
259
260/// Compute complexity density: total cyclomatic / lines of code.
261///
262/// Returns 0.0 when the file has no lines.
263fn compute_complexity_density(total_cyclomatic: u32, lines: u32) -> f64 {
264    if lines > 0 {
265        f64::from(total_cyclomatic) / f64::from(lines)
266    } else {
267        0.0
268    }
269}
270
271/// CRAP score threshold (inclusive). CC=5 untested gives exactly 30 (5^2 + 5),
272/// matching the canonical CRAP threshold from Savoia & Evans (2007).
273const CRAP_THRESHOLD: f64 = 30.0;
274
275/// Effective-threshold inputs for the CRAP columns of file scoring: the run
276/// resolver plus the `enforce_crap` bit from the health scope.
277#[derive(Clone, Copy)]
278pub(super) struct CrapScoreThresholds<'a> {
279    pub(super) resolver: &'a ThresholdOverrideResolver,
280    pub(super) enforce_crap: bool,
281}
282
283/// Per-function effective-CRAP-ceiling lookup for one file's scoring loop:
284/// the run resolver bound to the file's project-relative path, so the CRAP
285/// loops can resolve each function's ceiling where the function name is in
286/// hand. `enforce_crap` mirrors `HealthScope::enforce_crap`: a global ceiling
287/// of `0` disables CRAP enforcement, so every function counts as exempt at the
288/// canonical baseline instead of breaching a degenerate `0` ceiling.
289pub(super) struct CrapCeilingLookup<'a> {
290    resolver: &'a ThresholdOverrideResolver,
291    relative: &'a std::path::Path,
292    enforce_crap: bool,
293    suppressions: &'a [crate::suppress::Suppression],
294}
295
296/// Threshold-relative CRAP signals accumulated over one file's functions.
297///
298/// `above` and `exempted` count the ROUNDED per-function CRAP value, the same
299/// value the findings pipeline compares against the effective ceiling, so a
300/// boundary function cannot produce a finding without being counted here, or
301/// be counted here without producing a finding.
302#[derive(Debug, Default)]
303struct CrapThresholdSignals {
304    /// Functions whose rounded CRAP meets or exceeds their effective ceiling.
305    above: usize,
306    /// Functions at or above the canonical 30.0 baseline whose effective
307    /// ceiling exempts them (all baseline-breaching functions when CRAP
308    /// enforcement is disabled).
309    exempted: usize,
310    /// Lowest effective ceiling among the observed functions.
311    min_ceiling: Option<f64>,
312    suppressed: usize,
313    unsuppressed_max: f64,
314    unsuppressed_min_ceiling: Option<f64>,
315    /// Unsuppressed effective-ceiling breaches, before evidence sorting/capping.
316    eligible_functions: Vec<(String, u32, u16)>,
317}
318
319impl<'a> CrapCeilingLookup<'a> {
320    pub(super) fn new(
321        thresholds: CrapScoreThresholds<'a>,
322        relative: &'a std::path::Path,
323        suppressions: &'a [crate::suppress::Suppression],
324    ) -> Self {
325        Self {
326            resolver: thresholds.resolver,
327            relative,
328            enforce_crap: thresholds.enforce_crap,
329            suppressions,
330        }
331    }
332
333    /// Fold one function's rounded CRAP value into the file's
334    /// threshold-relative signals.
335    fn observe(
336        &self,
337        function: &fallow_types::extract::FunctionComplexity,
338        crap_rounded: f64,
339        signals: &mut CrapThresholdSignals,
340    ) {
341        let ceiling =
342            self.resolver
343                .effective_max_crap(self.relative, &function.name, function.line);
344        signals.min_ceiling = Some(signals.min_ceiling.map_or(ceiling, |m| m.min(ceiling)));
345        if (!self.enforce_crap || crap_rounded < ceiling) && crap_rounded >= CRAP_THRESHOLD {
346            signals.exempted += 1;
347        }
348        if crate::suppress::is_suppressed(
349            self.suppressions,
350            function.line,
351            crate::suppress::IssueKind::Complexity,
352        ) {
353            signals.suppressed += 1;
354            return;
355        }
356        signals.unsuppressed_max = signals.unsuppressed_max.max(crap_rounded);
357        signals.unsuppressed_min_ceiling = Some(
358            signals
359                .unsuppressed_min_ceiling
360                .map_or(ceiling, |minimum| minimum.min(ceiling)),
361        );
362        if self.enforce_crap && crap_rounded >= ceiling {
363            signals.above += 1;
364            signals.eligible_functions.push((
365                function.name.clone(),
366                function.line,
367                function.cognitive,
368            ));
369        }
370    }
371}
372
373/// Per-function CRAP data used to emit `--max-crap` findings.
374#[derive(Debug, Clone, Copy)]
375pub struct PerFunctionCrap {
376    /// 1-based line number of the function's definition.
377    pub(crate) line: u32,
378    /// 0-based column of the function's definition. Required alongside `line`
379    /// to disambiguate curried arrows that share a start line, e.g.
380    /// `(x) => (y) => {...}`. Without `col`, two `PerFunctionCrap` entries
381    /// would collide in the (path, line) finding index and one function's
382    /// CRAP score could be attached to another function's identity.
383    pub(crate) col: u32,
384    /// Computed CRAP score, rounded to one decimal place.
385    pub(crate) crap: f64,
386    /// Coverage percentage used to compute `crap`, when Istanbul matched the
387    /// function. `None` for estimated coverage or unmatched functions.
388    pub(crate) coverage_pct: Option<f64>,
389    /// Bucketed coverage tier used to drive action selection in JSON output.
390    /// Populated for both Istanbul-matched and estimated CRAP rows so the
391    /// action builder does not need to recompute reachability state.
392    pub(crate) coverage_tier: fallow_output::CoverageTier,
393    /// Provenance of `coverage_tier` and `crap`. `Istanbul` for direct fnMap
394    /// matches, `Estimated` for graph-based fallbacks against the finding's
395    /// own file, `EstimatedComponentInherited` for the template-inherit path
396    /// that reaches the owning Angular `.component.ts` through the inverse
397    /// `templateUrl` edge. Threaded into `ComplexityViolation.coverage_source` by
398    /// `merge_crap_findings`.
399    pub(crate) coverage_source: fallow_output::CoverageSource,
400}
401
402/// Istanbul CRAP result: CRAP scores plus match statistics.
403#[derive(Debug)]
404struct IstanbulCrapResult {
405    pub max_crap: f64,
406    /// Threshold-relative counts and the lowest effective ceiling.
407    pub signals: CrapThresholdSignals,
408    /// Functions that found a match in Istanbul data.
409    pub matched: usize,
410    /// Total functions evaluated.
411    pub total: usize,
412    /// Per-function CRAP data indexed by function position within `complexity`.
413    pub per_function: Vec<PerFunctionCrap>,
414}
415
416/// Compute per-function CRAP scores using Istanbul coverage data.
417///
418/// For each function, looks up its per-function statement coverage percentage
419/// from the Istanbul data and applies the canonical CRAP formula:
420/// `CRAP = CC^2 * (1 - cov/100)^3 + CC`
421///
422/// Functions not found in the coverage data fall back to the estimated model
423/// using the file's test-reachability status.
424///
425/// Returns CRAP scores and match statistics for reporting.
426fn compute_crap_scores_istanbul(
427    complexity: &[fallow_types::extract::FunctionComplexity],
428    file_coverage: Option<&IstanbulFileCoverage>,
429    is_test_reachable: bool,
430    ceilings: &CrapCeilingLookup<'_>,
431) -> IstanbulCrapResult {
432    if complexity.is_empty() {
433        return IstanbulCrapResult {
434            max_crap: 0.0,
435            signals: CrapThresholdSignals::default(),
436            matched: 0,
437            total: 0,
438            per_function: Vec::new(),
439        };
440    }
441    let mut max = 0.0_f64;
442    let mut signals = CrapThresholdSignals::default();
443    let mut matched = 0usize;
444    let mut total = 0usize;
445    let mut per_function = Vec::with_capacity(complexity.len());
446    for f in complexity {
447        // Synthetic template-family units carry no measurable coverage (an
448        // Istanbul fnMap can never contain them), so they are excluded from
449        // the CRAP dimension entirely: no per-function entry, no max /
450        // above-threshold contribution, no match-statistics slot. The
451        // module-scope unit leaves for the same reason plus one more: it has no
452        // fnMap identity to match, so counting it would score every branching
453        // file as one more uncovered high-CRAP unit and drag the reported
454        // Istanbul match rate down.
455        if fallow_types::extract::is_synthetic_template_unit(&f.name)
456            || fallow_types::extract::is_synthetic_module_unit(&f.name)
457        {
458            continue;
459        }
460        total += 1;
461        let cc = f64::from(ceilings.resolver.gate_cyclomatic(f));
462        let (crap, coverage_pct, tier, source) =
463            crap_for_function(f, cc, file_coverage, is_test_reachable, &mut matched);
464        let crap_rounded = (crap * 10.0).round() / 10.0;
465        max = max.max(crap);
466        ceilings.observe(f, crap_rounded, &mut signals);
467        per_function.push(PerFunctionCrap {
468            line: f.line,
469            col: f.col,
470            crap: crap_rounded,
471            coverage_pct,
472            coverage_tier: tier,
473            coverage_source: source,
474        });
475    }
476    IstanbulCrapResult {
477        max_crap: (max * 10.0).round() / 10.0,
478        signals,
479        matched,
480        total,
481        per_function,
482    }
483}
484
485/// Resolve one function's `(crap, coverage_pct, tier, source)` from Istanbul
486/// coverage, falling back to the test-reachability estimate model. Increments
487/// `matched` when a real coverage value is found.
488#[expect(
489    clippy::suboptimal_flops,
490    reason = "cc * cc + cc matches the CRAP formula specification"
491)]
492fn crap_for_function(
493    f: &fallow_types::extract::FunctionComplexity,
494    cc: f64,
495    file_coverage: Option<&IstanbulFileCoverage>,
496    is_test_reachable: bool,
497    matched: &mut usize,
498) -> (
499    f64,
500    Option<f64>,
501    fallow_output::CoverageTier,
502    fallow_output::CoverageSource,
503) {
504    let lookup = file_coverage.and_then(|fc| fc.lookup_function(f));
505    if let Some(cov_pct) = lookup {
506        *matched += 1;
507        return (
508            crap_formula(cc, cov_pct),
509            Some(cov_pct),
510            fallow_output::CoverageTier::from_pct(cov_pct),
511            fallow_output::CoverageSource::Istanbul,
512        );
513    }
514    // The same static estimate the run without a coverage map would have
515    // used. A map that says nothing about this function is not evidence that
516    // it ran, so passing one must never lower its CRAP below the estimate.
517    if is_test_reachable {
518        return (
519            crap_formula(cc, INDIRECT_TEST_COVERAGE_ESTIMATE),
520            None,
521            fallow_output::CoverageTier::from_pct(INDIRECT_TEST_COVERAGE_ESTIMATE),
522            fallow_output::CoverageSource::Estimated,
523        );
524    }
525    (
526        cc * cc + cc,
527        None,
528        fallow_output::CoverageTier::None,
529        fallow_output::CoverageSource::Estimated,
530    )
531}
532
533/// Estimated coverage for functions directly referenced by test-reachable modules.
534/// An export imported in a test file likely exercises most of the function body.
535const DIRECT_TEST_COVERAGE_ESTIMATE: f64 = 85.0;
536
537/// Estimated coverage for functions in test-reachable files but not directly
538/// referenced by tests. The file is imported by tests, so the function may
539/// be exercised indirectly, but with lower confidence.
540const INDIRECT_TEST_COVERAGE_ESTIMATE: f64 = 40.0;
541const MAX_DIRECT_CALLER_EVIDENCE: usize = 5;
542
543/// Compute per-function CRAP scores using graph-based coverage estimation.
544///
545/// For each function, estimates coverage from the module graph:
546/// - Function name matches an export with test-reachable references: 85%
547/// - File is test-reachable but function not directly referenced: 40%
548/// - File is not test-reachable at all: 0%
549///
550/// Applies the canonical CRAP formula with these estimates.
551/// Estimated CRAP result: score aggregates plus per-function data.
552#[derive(Debug)]
553struct EstimatedCrapResult {
554    pub max_crap: f64,
555    /// Threshold-relative counts and the lowest effective ceiling.
556    pub signals: CrapThresholdSignals,
557    pub per_function: Vec<PerFunctionCrap>,
558}
559
560fn compute_crap_scores_estimated(
561    complexity: &[fallow_types::extract::FunctionComplexity],
562    test_referenced_exports: &rustc_hash::FxHashSet<String>,
563    is_test_reachable: bool,
564    coverage_source: fallow_output::CoverageSource,
565    ceilings: &CrapCeilingLookup<'_>,
566) -> EstimatedCrapResult {
567    if complexity.is_empty() {
568        return EstimatedCrapResult {
569            max_crap: 0.0,
570            signals: CrapThresholdSignals::default(),
571            per_function: Vec::new(),
572        };
573    }
574    let mut max = 0.0_f64;
575    let mut signals = CrapThresholdSignals::default();
576    let mut per_function = Vec::with_capacity(complexity.len());
577    for f in complexity {
578        // Template-family units leave the CRAP dimension: their name never
579        // appears in `test_referenced_exports`, so the estimate could only
580        // ever restate the file's reachability as a disguised cyclomatic gate.
581        // The module-scope unit is not an export either, so it leaves too.
582        if fallow_types::extract::is_synthetic_template_unit(&f.name)
583            || fallow_types::extract::is_synthetic_module_unit(&f.name)
584        {
585            continue;
586        }
587        let cc = f64::from(ceilings.resolver.gate_cyclomatic(f));
588        // A context name is not an export name, also when it repeats the name
589        // of the export that returns the function (`const load = () =>
590        // Effect.gen(...)`), so the lookup uses the identity name.
591        let estimated_coverage = if test_referenced_exports.contains(f.identity_name()) {
592            DIRECT_TEST_COVERAGE_ESTIMATE
593        } else if is_test_reachable {
594            INDIRECT_TEST_COVERAGE_ESTIMATE
595        } else {
596            0.0
597        };
598        let crap = crap_formula(cc, estimated_coverage);
599        let crap_rounded = (crap * 10.0).round() / 10.0;
600        max = max.max(crap);
601        ceilings.observe(f, crap_rounded, &mut signals);
602        per_function.push(PerFunctionCrap {
603            line: f.line,
604            col: f.col,
605            crap: crap_rounded,
606            coverage_pct: None,
607            coverage_tier: fallow_output::CoverageTier::from_pct(estimated_coverage),
608            coverage_source,
609        });
610    }
611    EstimatedCrapResult {
612        max_crap: (max * 10.0).round() / 10.0,
613        signals,
614        per_function,
615    }
616}
617
618/// Inherited CRAP context for a synthetic `<template>` finding on an Angular
619/// `.html` template. Populated by `build_template_inherit_contexts` for every
620/// `.html` module that has a `<template>` `FunctionComplexity` entry AND is
621/// reached by at least one non-test `.ts` importer via the `templateUrl`
622/// `SideEffect` edge.
623///
624/// The reachability bit is the OR across all non-test `.ts` owners (any
625/// tested owner makes the template tested); the `test_referenced_exports`
626/// set is the union of each owner's directly-test-referenced export names;
627/// the provenance path points at the chosen owner for human output. When
628/// multiple owners exist, prefer the first test-reachable one so the
629/// "inherited from" suffix points at a meaningful owner rather than an
630/// arbitrary first match.
631#[derive(Debug, Clone)]
632struct TemplateInheritContext {
633    pub is_test_reachable: bool,
634    pub test_referenced_exports: rustc_hash::FxHashSet<String>,
635    /// The owning `.ts` file path used for human-output provenance
636    /// (`coverage: partial (inherited from foo.component.ts)`). Set to the
637    /// first test-reachable owner when one exists, otherwise the first
638    /// non-test owner. Absolute path; the human formatter strips it.
639    pub provenance_owner: std::path::PathBuf,
640}
641
642/// Build the inverse `templateUrl` redirect map: for every `.html` module
643/// carrying a synthetic `<template>` `FunctionComplexity` entry, walk
644/// `reverse_deps` to find every `.ts` (or `.component.ts`) importer that is
645/// NOT a test entry point, and compute an aggregate `TemplateInheritContext`
646/// that the CRAP scoring loop can use to redirect reachability + test refs
647/// to the owning component file.
648///
649/// Test-file owners are excluded because Angular spec files do not declare
650/// `templateUrl`; if a `.spec.ts` is the only importer of a `.html`, the
651/// template is genuinely orphaned and the existing fallback (estimated
652/// against the `.html`'s own reachability) is the right answer.
653///
654/// The `.ts` / `.tsx` / `.mts` / `.cts` extension gate intentionally lets
655/// `.d.ts` ambient declarations through, but Angular component classes are
656/// not emitted into `.d.ts` files (which model APIs, not runtime behaviour)
657/// and `templateUrl` SideEffect edges flow only from concrete `@Component`
658/// decorators. A `.d.ts` importer of a `.html` would be a structural
659/// anomaly upstream, not a meaningful owner, so the gate stays simple.
660///
661/// Templates with zero non-test `.ts` owners receive no entry, so the
662/// scoring loop falls through to the existing path unchanged.
663fn build_template_inherit_contexts(
664    graph: &fallow_graph::graph::ModuleGraph,
665    test_coverage: StaticTestCoverage<'_>,
666    module_by_id: &rustc_hash::FxHashMap<crate::discover::FileId, &crate::source::ModuleInfo>,
667    file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
668) -> rustc_hash::FxHashMap<crate::discover::FileId, TemplateInheritContext> {
669    let mut out = rustc_hash::FxHashMap::default();
670    for node in &graph.modules {
671        if let Some(context) =
672            template_inherit_context_for_node(node, graph, test_coverage, module_by_id, file_paths)
673        {
674            out.insert(node.file_id, context);
675        }
676    }
677    out
678}
679
680fn template_inherit_context_for_node(
681    node: &fallow_graph::graph::ModuleNode,
682    graph: &fallow_graph::graph::ModuleGraph,
683    test_coverage: StaticTestCoverage<'_>,
684    module_by_id: &rustc_hash::FxHashMap<crate::discover::FileId, &crate::source::ModuleInfo>,
685    file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
686) -> Option<TemplateInheritContext> {
687    if !is_template_inherit_candidate(node, module_by_id, file_paths) {
688        return None;
689    }
690    let importers = graph.reverse_deps.get(node.file_id.0 as usize)?;
691    template_inherit_context_from_importers(
692        importers,
693        graph,
694        test_coverage,
695        module_by_id,
696        file_paths,
697    )
698}
699
700fn is_template_inherit_candidate(
701    node: &fallow_graph::graph::ModuleNode,
702    module_by_id: &rustc_hash::FxHashMap<crate::discover::FileId, &crate::source::ModuleInfo>,
703    file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
704) -> bool {
705    let Some(path) = file_paths.get(&node.file_id) else {
706        return false;
707    };
708    if !path
709        .extension()
710        .and_then(|ext| ext.to_str())
711        .is_some_and(|ext| ext.eq_ignore_ascii_case("html"))
712    {
713        return false;
714    }
715    module_by_id.get(&node.file_id).is_some_and(|module| {
716        module
717            .complexity
718            .iter()
719            .any(|finding| finding.name.as_str() == "<template>")
720    })
721}
722
723fn template_inherit_context_from_importers(
724    importers: &[crate::discover::FileId],
725    graph: &fallow_graph::graph::ModuleGraph,
726    test_coverage: StaticTestCoverage<'_>,
727    module_by_id: &rustc_hash::FxHashMap<crate::discover::FileId, &crate::source::ModuleInfo>,
728    file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
729) -> Option<TemplateInheritContext> {
730    let mut any_reachable = false;
731    let mut combined_refs = rustc_hash::FxHashSet::default();
732    let mut provenance: Option<std::path::PathBuf> = None;
733    let mut first_owner: Option<std::path::PathBuf> = None;
734
735    for &importer_id in importers {
736        let Some((owner_node, owner_path)) =
737            template_owner(importer_id, graph, module_by_id, file_paths)
738        else {
739            continue;
740        };
741        if first_owner.is_none() {
742            first_owner = Some((*owner_path).clone());
743        }
744        if test_coverage.covers_file(owner_node.file_id) {
745            any_reachable = true;
746            provenance.get_or_insert_with(|| (*owner_path).clone());
747            let refs = build_test_referenced_exports(
748                owner_node.file_id,
749                &owner_node.exports,
750                test_coverage,
751            );
752            combined_refs.extend(refs);
753        }
754    }
755
756    let provenance_owner = provenance.or(first_owner)?;
757    Some(TemplateInheritContext {
758        is_test_reachable: any_reachable,
759        test_referenced_exports: combined_refs,
760        provenance_owner,
761    })
762}
763
764fn template_owner<'a>(
765    importer_id: crate::discover::FileId,
766    graph: &'a fallow_graph::graph::ModuleGraph,
767    module_by_id: &rustc_hash::FxHashMap<crate::discover::FileId, &crate::source::ModuleInfo>,
768    file_paths: &'a rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
769) -> Option<(&'a fallow_graph::graph::ModuleNode, &'a std::path::PathBuf)> {
770    let owner_node = graph.modules.get(importer_id.0 as usize)?;
771    let owner_path = *file_paths.get(&importer_id)?;
772    if !is_template_owner_path(owner_path) || graph.test_entry_points.contains(&importer_id) {
773        return None;
774    }
775    let owner_has_component = module_by_id
776        .get(&importer_id)
777        .is_some_and(|module| module.has_angular_component_template_url);
778    owner_has_component.then_some((owner_node, owner_path))
779}
780
781fn is_template_owner_path(path: &std::path::Path) -> bool {
782    path.extension()
783        .and_then(|ext| ext.to_str())
784        .is_some_and(|ext| {
785            matches!(
786                ext.to_ascii_lowercase().as_str(),
787                "ts" | "tsx" | "mts" | "cts"
788            )
789        })
790}
791
792fn collect_direct_callers(
793    graph: &fallow_graph::graph::ModuleGraph,
794    file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
795) -> rustc_hash::FxHashMap<std::path::PathBuf, Vec<DirectCallerEvidence>> {
796    let mut callers_by_target = rustc_hash::FxHashMap::default();
797    for node in &graph.modules {
798        let Some(target_path) = file_paths.get(&node.file_id) else {
799            continue;
800        };
801        let mut callers = graph
802            .direct_importer_summaries(node.file_id)
803            .into_iter()
804            .filter_map(|summary| {
805                file_paths
806                    .get(&summary.source)
807                    .map(|caller_path| DirectCallerEvidence {
808                        path: (*caller_path).clone(),
809                        symbols: summary
810                            .symbols
811                            .into_iter()
812                            .map(|symbol| DirectCallerSymbolEvidence {
813                                imported: symbol.imported,
814                                local: symbol.local,
815                                type_only: symbol.type_only,
816                            })
817                            .collect(),
818                    })
819            })
820            .collect::<Vec<_>>();
821        callers.sort_by(|a, b| a.path.cmp(&b.path));
822        callers.truncate(MAX_DIRECT_CALLER_EVIDENCE);
823        if !callers.is_empty() {
824            callers_by_target.insert((*target_path).clone(), callers);
825        }
826    }
827    callers_by_target
828}
829
830/// Canonical CRAP formula: `CC^2 * (1 - cov/100)^3 + CC`.
831/// At 100% coverage: CRAP = CC. At 0% coverage: CRAP = CC^2 + CC.
832#[expect(
833    clippy::suboptimal_flops,
834    reason = "explicit multiplication matches the CRAP formula specification"
835)]
836fn crap_formula(cc: f64, coverage_pct: f64) -> f64 {
837    let uncovered = 1.0 - coverage_pct / 100.0;
838    cc * cc * uncovered * uncovered * uncovered + cc
839}
840
841/// Maximum column drift tolerated when the anonymous-by-position fallback
842/// matches a candidate on a nearby line. Wide enough to accept curried arrows
843/// and chained callbacks that share a leading indent, tight enough to reject
844/// `function foo()` at column 0 when the only candidate is a multiline-arrow
845/// declaration alias at the typical `const x = async (` column.
846const ANONYMOUS_FALLBACK_MAX_COLUMN_DRIFT: u32 = 16;
847
848/// Maximum line drift tolerated by the name-fuzzy and anonymous fallbacks.
849/// Both reject an alias further than this from the target, which is what lets
850/// a lookup binary-search a window of `IstanbulFileCoverage::alias_lines`
851/// instead of scanning every record in the file.
852const ALIAS_FUZZ_MAX_LINE_DRIFT: u32 = 2;
853
854#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
855struct IstanbulPosition {
856    line: u32,
857    col: u32,
858}
859
860impl IstanbulPosition {
861    const fn new(line: u32, col: u32) -> Self {
862        Self { line, col }
863    }
864
865    const fn distance_from(self, target: Self) -> (u32, u32) {
866        (
867            self.line.abs_diff(target.line),
868            self.col.abs_diff(target.col),
869        )
870    }
871}
872
873#[derive(Clone, Copy, Debug, Eq, PartialEq)]
874struct IstanbulSpan {
875    start: IstanbulPosition,
876    end: IstanbulPosition,
877}
878
879impl IstanbulSpan {
880    fn from_entry(
881        fn_entry: &oxc_coverage_instrument::FnEntry,
882        source_index: Option<&IstanbulSourceIndex<'_>>,
883    ) -> Option<Self> {
884        let start = normalized_istanbul_position(
885            fn_entry.loc.start.line,
886            fn_entry.loc.start.column,
887            source_index,
888        )?;
889        let end = normalized_istanbul_position(
890            fn_entry.loc.end.line,
891            fn_entry.loc.end.column,
892            source_index,
893        )?;
894        (start.line > 0 && end.line > 0 && start < end).then_some(Self { start, end })
895    }
896
897    fn header_from_entry(
898        fn_entry: &oxc_coverage_instrument::FnEntry,
899        source_index: Option<&IstanbulSourceIndex<'_>>,
900    ) -> Option<Self> {
901        let start = normalized_istanbul_position(
902            fn_entry.decl.start.line,
903            fn_entry.decl.start.column,
904            source_index,
905        )?;
906        let end = normalized_istanbul_position(
907            fn_entry.loc.start.line,
908            fn_entry.loc.start.column,
909            source_index,
910        )?;
911        (start.line > 0 && end.line > 0 && start < end).then_some(Self { start, end })
912    }
913
914    /// Half-open containment: `end` is the position just past the body.
915    fn contains(self, position: IstanbulPosition) -> bool {
916        self.start <= position && position < self.end
917    }
918
919    fn strictly_contains(self, other: Self) -> bool {
920        self != other && self.start <= other.start && other.end <= self.end
921    }
922}
923
924/// A position under which an Istanbul function record can be found.
925///
926/// The producer's effective position and `decl.start` are primary: they
927/// identify the function itself. The body start (`loc.start`) is secondary.
928/// istanbul-lib-instrument records an expression-bodied arrow's `loc` as the
929/// body expression, so for curried arrows the outer entry's body start is the
930/// inner entry's declaration start. A secondary alias therefore yields to a
931/// primary alias at the same position instead of making it ambiguous.
932#[derive(Clone, Copy, Debug, Eq, PartialEq)]
933struct IstanbulAlias {
934    position: IstanbulPosition,
935    primary: bool,
936}
937
938/// How many primary and secondary aliases share one position within a
939/// collision namespace (per name, or across all anonymous records).
940#[derive(Clone, Copy, Debug, Default)]
941struct IstanbulAliasCounts {
942    primary: usize,
943    secondary: usize,
944}
945
946impl IstanbulAliasCounts {
947    fn add(&mut self, alias: IstanbulAlias) {
948        if alias.primary {
949            self.primary += 1;
950        } else {
951            self.secondary += 1;
952        }
953    }
954
955    /// A primary alias is unique when no other primary shares its position;
956    /// a secondary alias is unique only when nothing else does.
957    const fn is_unique(self, alias: IstanbulAlias) -> bool {
958        if alias.primary {
959            self.primary == 1
960        } else {
961            self.primary == 0 && self.secondary == 1
962        }
963    }
964
965    const fn has_secondary_only_collision(self) -> bool {
966        self.primary == 0 && self.secondary > 1
967    }
968}
969
970fn is_anonymous_istanbul_name(name: &str) -> bool {
971    name.starts_with("(anonymous_")
972}
973
974struct IstanbulFunctionCoverage {
975    name: String,
976    coverage_pct: f64,
977    aliases: Vec<IstanbulAlias>,
978    /// Where the producer says the function is written. Unlike the alias set
979    /// this is never a synthesized position, so it answers "is another
980    /// function declared here" without false positives.
981    decl_start: IstanbulPosition,
982    /// Whether another function is declared inside this record's header span.
983    /// Computed once per file, because the header fallback needs it on every
984    /// unmatched lookup and recomputing it there is quadratic.
985    header_holds_other_fn: bool,
986    header_span: Option<IstanbulSpan>,
987    body_span: Option<IstanbulSpan>,
988}
989
990impl IstanbulFunctionCoverage {
991    /// Whether this record answers to `name`, either as recorded or as the
992    /// property behind an accessor keyword the producer kept.
993    fn answers_to(&self, name: &str) -> bool {
994        if self.name == name {
995            return true;
996        }
997        accessor_property_name(&self.name) == Some(name)
998    }
999
1000    fn nearest_alias(
1001        &self,
1002        target: IstanbulPosition,
1003        max_column_drift: Option<u32>,
1004    ) -> Option<(u32, u32)> {
1005        self.aliases
1006            .iter()
1007            .filter_map(|alias| {
1008                let distance = alias.position.distance_from(target);
1009                if distance.0 > ALIAS_FUZZ_MAX_LINE_DRIFT {
1010                    return None;
1011                }
1012                if distance.0 > 0 && max_column_drift.is_some_and(|maximum| distance.1 > maximum) {
1013                    return None;
1014                }
1015                Some(distance)
1016            })
1017            .min()
1018    }
1019}
1020
1021/// Pre-processed per-function coverage data for a single file,
1022/// derived from Istanbul `coverage-final.json`.
1023pub struct IstanbulFileCoverage {
1024    /// One record per Istanbul `fnMap` identity. Each record owns its
1025    /// deduplicated producer, declaration, and valid body-start aliases, so an
1026    /// entry cannot tie with itself during anonymous positional matching.
1027    functions: Vec<IstanbulFunctionCoverage>,
1028    /// Exact aliases that belong to one function identity. Primary aliases
1029    /// that collide are removed from this index and recorded in
1030    /// `ambiguous_aliases`. A secondary alias yields to a primary collision,
1031    /// while secondary-only collisions are also recorded as ambiguous.
1032    alias_index: rustc_hash::FxHashMap<(String, u32, u32), usize>,
1033    /// Aliases shared by multiple function identities without a unique
1034    /// primary owner. Exact queries at these positions abstain instead of
1035    /// falling through to a fuzzy attribution.
1036    ambiguous_aliases: rustc_hash::FxHashSet<(String, u32, u32)>,
1037    /// Positions shared by multiple anonymous identities without a unique
1038    /// primary owner. Anonymous fallback abstains at these targets even when
1039    /// each identity has other aliases.
1040    ambiguous_anonymous_aliases: rustc_hash::FxHashSet<IstanbulPosition>,
1041    /// `(alias line, function index)` for every retained alias, sorted.
1042    /// The fuzzy and anonymous fallbacks reject any alias further than
1043    /// [`ALIAS_FUZZ_MAX_LINE_DRIFT`] lines from the target, so they can search
1044    /// a window of this index instead of every record in the file.
1045    alias_lines: Vec<(u32, usize)>,
1046    /// `(header span start line, function index)` for every record that has a
1047    /// header span, sorted.
1048    header_starts: Vec<(u32, usize)>,
1049    /// Height in lines of the tallest header span in this file. A span reaches
1050    /// no further than this below its own start, which bounds the window
1051    /// searched in `header_starts`.
1052    max_header_height: u32,
1053    /// The coverage map was recorded against a different checkout of the
1054    /// project, so line numbers may have drifted beyond the bounded fuzz.
1055    /// Enables the distance-free unambiguous-name fallback in [`Self::lookup`].
1056    relocated: bool,
1057}
1058
1059/// Records whether each header span has a second function declared inside it,
1060/// which makes the span say nothing about a position it contains.
1061///
1062/// Computed once per file because the header fallback needs the answer on
1063/// every unmatched lookup and recomputing it there would be quadratic.
1064fn mark_headers_holding_other_fns(functions: &mut [IstanbulFunctionCoverage]) {
1065    let mut declarations: Vec<IstanbulPosition> = functions
1066        .iter()
1067        .map(|function| function.decl_start)
1068        .collect();
1069    declarations.sort_unstable();
1070    for function in functions {
1071        let Some(span) = function.header_span else {
1072            continue;
1073        };
1074        // The record's own declaration opens its header span, so it is always
1075        // in range: a second hit is what marks a foreign function.
1076        let first = declarations.partition_point(|position| *position < span.start);
1077        let past = declarations.partition_point(|position| *position < span.end);
1078        function.header_holds_other_fn = past - first > 1;
1079    }
1080}
1081
1082/// Line-keyed indexes over one file's records, built once per file so the
1083/// fuzzy, anonymous, and header fallbacks can binary-search a bounded window
1084/// instead of rescanning every record on every unmatched lookup.
1085struct IstanbulLineIndexes {
1086    alias_lines: Vec<(u32, usize)>,
1087    header_starts: Vec<(u32, usize)>,
1088    max_header_height: u32,
1089}
1090
1091impl IstanbulLineIndexes {
1092    fn build(functions: &[IstanbulFunctionCoverage]) -> Self {
1093        let mut alias_lines: Vec<(u32, usize)> = functions
1094            .iter()
1095            .enumerate()
1096            .flat_map(|(function_index, function)| {
1097                function
1098                    .aliases
1099                    .iter()
1100                    .map(move |alias| (alias.position.line, function_index))
1101            })
1102            .collect();
1103        alias_lines.sort_unstable();
1104
1105        let mut header_starts: Vec<(u32, usize)> = Vec::new();
1106        let mut max_header_height = 0;
1107        for (function_index, function) in functions.iter().enumerate() {
1108            if let Some(span) = function.header_span {
1109                header_starts.push((span.start.line, function_index));
1110                // `IstanbulSpan` construction requires `start < end`, so the
1111                // end line is never above the start line.
1112                max_header_height = max_header_height.max(span.end.line - span.start.line);
1113            }
1114        }
1115        header_starts.sort_unstable();
1116
1117        Self {
1118            alias_lines,
1119            header_starts,
1120            max_header_height,
1121        }
1122    }
1123}
1124
1125impl IstanbulFileCoverage {
1126    /// Coverage for an extracted unit.
1127    ///
1128    /// The entry point callers outside this module get, because the
1129    /// private-member rule has to hold for every consumer: gating it at one
1130    /// call site leaves the next one free to reintroduce the bug.
1131    pub fn lookup_function(
1132        &self,
1133        function: &fallow_types::extract::FunctionComplexity,
1134    ) -> Option<f64> {
1135        if function.is_private_member {
1136            return self.lookup_private(&function.name, function.line, function.col);
1137        }
1138        // A context name (`Command.make("setup")`, the name of the function
1139        // that returns `Effect.gen(...)`) is not the name that a coverage
1140        // producer records. It could match the record of the wrapper function
1141        // on the same line, so the lookup uses the placeholder.
1142        self.lookup(function.identity_name(), function.line, function.col)
1143    }
1144
1145    fn new(mut functions: Vec<IstanbulFunctionCoverage>, relocated: bool) -> Self {
1146        let mut named_alias_counts: rustc_hash::FxHashMap<
1147            (String, IstanbulPosition),
1148            IstanbulAliasCounts,
1149        > = rustc_hash::FxHashMap::default();
1150        let mut anonymous_alias_counts: rustc_hash::FxHashMap<
1151            IstanbulPosition,
1152            IstanbulAliasCounts,
1153        > = rustc_hash::FxHashMap::default();
1154        for function in &functions {
1155            let is_anonymous = is_anonymous_istanbul_name(&function.name);
1156            for alias in &function.aliases {
1157                named_alias_counts
1158                    .entry((function.name.clone(), alias.position))
1159                    .or_default()
1160                    .add(*alias);
1161                if is_anonymous {
1162                    anonymous_alias_counts
1163                        .entry(alias.position)
1164                        .or_default()
1165                        .add(*alias);
1166                }
1167            }
1168        }
1169
1170        // A secondary alias that collides with a primary is dropped, which
1171        // leaves the primary owner of that position unique. Primary/primary
1172        // and secondary-only collisions remain ambiguous so fuzzy fallback
1173        // cannot attribute the shared position to an arbitrary record.
1174        let mut ambiguous_aliases = rustc_hash::FxHashSet::default();
1175        let mut ambiguous_anonymous_aliases = rustc_hash::FxHashSet::default();
1176        for function in &mut functions {
1177            let name = function.name.clone();
1178            let is_anonymous = is_anonymous_istanbul_name(&name);
1179            function.aliases.retain(|alias| {
1180                let named = named_alias_counts
1181                    .get(&(name.clone(), alias.position))
1182                    .copied()
1183                    .unwrap_or_default();
1184                let anonymous = is_anonymous
1185                    .then(|| anonymous_alias_counts.get(&alias.position).copied())
1186                    .flatten();
1187                let unique = named.is_unique(*alias)
1188                    && anonymous.is_none_or(|counts| counts.is_unique(*alias));
1189                if unique {
1190                    return true;
1191                }
1192                if alias.primary {
1193                    ambiguous_aliases.insert((
1194                        name.clone(),
1195                        alias.position.line,
1196                        alias.position.col,
1197                    ));
1198                    if anonymous.is_some_and(|counts| counts.primary > 1) {
1199                        ambiguous_anonymous_aliases.insert(alias.position);
1200                    }
1201                } else {
1202                    if named.has_secondary_only_collision() {
1203                        ambiguous_aliases.insert((
1204                            name.clone(),
1205                            alias.position.line,
1206                            alias.position.col,
1207                        ));
1208                    }
1209                    if anonymous.is_some_and(IstanbulAliasCounts::has_secondary_only_collision) {
1210                        ambiguous_anonymous_aliases.insert(alias.position);
1211                    }
1212                }
1213                false
1214            });
1215        }
1216
1217        let mut alias_index = rustc_hash::FxHashMap::default();
1218        for (function_index, function) in functions.iter().enumerate() {
1219            for alias in &function.aliases {
1220                alias_index.insert(
1221                    (
1222                        function.name.clone(),
1223                        alias.position.line,
1224                        alias.position.col,
1225                    ),
1226                    function_index,
1227                );
1228                // An accessor answers to its property name as well, without
1229                // giving up the spelling the producer recorded.
1230                if let Some(property) = accessor_property_name(&function.name) {
1231                    alias_index
1232                        .entry((
1233                            property.to_string(),
1234                            alias.position.line,
1235                            alias.position.col,
1236                        ))
1237                        .or_insert(function_index);
1238                }
1239            }
1240        }
1241
1242        mark_headers_holding_other_fns(&mut functions);
1243        let indexes = IstanbulLineIndexes::build(&functions);
1244
1245        Self {
1246            functions,
1247            alias_index,
1248            ambiguous_aliases,
1249            ambiguous_anonymous_aliases,
1250            alias_lines: indexes.alias_lines,
1251            header_starts: indexes.header_starts,
1252            max_header_height: indexes.max_header_height,
1253            relocated,
1254        }
1255    }
1256
1257    /// Indices of the records with an alias within
1258    /// [`ALIAS_FUZZ_MAX_LINE_DRIFT`] lines of `target`, ascending and
1259    /// deduplicated.
1260    ///
1261    /// This is exactly the candidate set of the fuzzy and anonymous fallbacks:
1262    /// `nearest_alias` yields `None` for a record whose every alias is further
1263    /// away, so a record outside the window cannot produce a distance and
1264    /// cannot win either fallback. Ascending order reproduces the order of a
1265    /// full `self.functions` scan, which both fallbacks' tie-breaks depend on:
1266    /// `min_by_key` keeps the first minimum, and the anonymous scan appends
1267    /// equal-distance records in encounter order.
1268    fn fuzz_window(&self, target: IstanbulPosition) -> Vec<usize> {
1269        let low = target.line.saturating_sub(ALIAS_FUZZ_MAX_LINE_DRIFT);
1270        let high = target.line.saturating_add(ALIAS_FUZZ_MAX_LINE_DRIFT);
1271        let first = self.alias_lines.partition_point(|(line, _)| *line < low);
1272        let past = self.alias_lines.partition_point(|(line, _)| *line <= high);
1273        let mut window: Vec<usize> = self.alias_lines[first..past]
1274            .iter()
1275            .map(|(_, function_index)| *function_index)
1276            .collect();
1277        window.sort_unstable();
1278        window.dedup();
1279        window
1280    }
1281
1282    /// Coverage for a private class member, from a record with its own
1283    /// `#name` only.
1284    ///
1285    /// The anonymous, header-span, and relocated fallbacks of [`Self::lookup`]
1286    /// match on proximity, and the nearest record to a private member is often
1287    /// the enclosing function or a public twin. The named step stays, but it
1288    /// must find exactly one record: two `#name` records near the member (for
1289    /// example a private getter and setter) give no coverage (#3816).
1290    fn lookup_private(&self, name: &str, line: u32, col: u32) -> Option<f64> {
1291        let exact_key = (name.to_string(), line, col);
1292        if self.ambiguous_aliases.contains(&exact_key) {
1293            return None;
1294        }
1295        if let Some(&function_index) = self.alias_index.get(&exact_key) {
1296            return Some(self.functions[function_index].coverage_pct);
1297        }
1298        let target = IstanbulPosition::new(line, col);
1299        let window = self.fuzz_window(target);
1300        let signature_owners = self.header_spans_containing(target);
1301        let mut candidates = self.named_candidates(name, target, &window, &signature_owners);
1302        let (_, function_index) = candidates.next()?;
1303        if candidates.next().is_some() {
1304            return None;
1305        }
1306        Some(self.functions[function_index].coverage_pct)
1307    }
1308
1309    /// Records in `window` named `name`, with their alias distance from
1310    /// `target`.
1311    ///
1312    /// A function written inside another function's signature is a
1313    /// different function from the one the signature belongs to, and both
1314    /// sit within a line or two of the same position. Proximity cannot
1315    /// tell them apart, so `signature_owners` (the records whose signature
1316    /// covers `target`) decide which candidates are eligible at all.
1317    fn named_candidates<'a>(
1318        &'a self,
1319        name: &'a str,
1320        target: IstanbulPosition,
1321        window: &'a [usize],
1322        signature_owners: &'a [usize],
1323    ) -> impl Iterator<Item = ((u32, u32), usize)> + 'a {
1324        window
1325            .iter()
1326            .copied()
1327            .filter(move |function_index| self.functions[*function_index].answers_to(name))
1328            .filter_map(move |function_index| {
1329                self.functions[function_index]
1330                    .nearest_alias(target, None)
1331                    .map(|distance| (distance, function_index))
1332            })
1333            .filter(move |(distance, function_index)| {
1334                *distance == (0, 0)
1335                    || !self.foreign_signature_blocks(signature_owners, *function_index, target)
1336            })
1337    }
1338
1339    /// Look up coverage for a function by name, start line, and start column.
1340    ///
1341    /// Resolution order:
1342    /// 1. Exact `(name, line, col)` match.
1343    /// 2. Name-only fuzzy match within ±2 lines (tolerates formatter drift),
1344    ///    tie-broken by smallest `(line, col)` distance from the target.
1345    /// 3. Anonymous fallback: among Istanbul `(anonymous_N)` records with an
1346    ///    alias within ±2 lines, pick the record whose closest alias has the
1347    ///    smallest `(line, col)` distance from the target. A distance tie is
1348    ///    resolved only when one valid body span contains the target and is
1349    ///    strictly inside every other tied span.
1350    /// 4. Unique anonymous header-span fallback between `decl.start` and
1351    ///    `loc.start`.
1352    ///
1353    /// Step 3 covers arrow-function exports where fallow extracts the binding
1354    /// identifier
1355    /// (`const myHandler = () => {...}` yields `myHandler`) while Istanbul
1356    /// records the function as anonymous. `load_istanbul_coverage` indexes
1357    /// declaration aliases so standard Istanbul producers still participate
1358    /// in this fallback. Step 4 covers multi-line callback arguments whose
1359    /// extracted start falls between Istanbul's declaration and body anchors,
1360    /// but only after the established anonymous resolution cannot decide. See
1361    /// issues #155, #166, #181, and #370.
1362    ///
1363    /// When the map is `relocated` (recorded against a different checkout of
1364    /// the project, as in the audit base-worktree pass), a distance-free
1365    /// name match runs between steps 2 and 3: if every entry named `name`
1366    /// carries the same coverage value, that value is returned regardless of
1367    /// line drift. Unrelated edits can shift a function arbitrarily far
1368    /// between the two checkouts, and when all same-named candidates agree
1369    /// the choice among them cannot matter (#2347). Same-checkout lookups
1370    /// keep the bounded fuzz, which protects against stale coverage data.
1371    pub(crate) fn lookup(&self, name: &str, line: u32, col: u32) -> Option<f64> {
1372        let exact_key = (name.to_string(), line, col);
1373        if self.ambiguous_aliases.contains(&exact_key) {
1374            return None;
1375        }
1376        if let Some(&function_index) = self.alias_index.get(&exact_key) {
1377            return Some(self.functions[function_index].coverage_pct);
1378        }
1379
1380        let target = IstanbulPosition::new(line, col);
1381        let window = self.fuzz_window(target);
1382        let signature_owners = self.header_spans_containing(target);
1383        if let Some(function) = self
1384            .named_candidates(name, target, &window, &signature_owners)
1385            .min_by_key(|(distance, _)| *distance)
1386            .map(|(_, function_index)| &self.functions[function_index])
1387        {
1388            return Some(function.coverage_pct);
1389        }
1390        if self.relocated
1391            && let Some(pct) = self.unambiguous_named_pct(name)
1392        {
1393            return Some(pct);
1394        }
1395        if self.ambiguous_anonymous_aliases.contains(&target) {
1396            return self.unique_anonymous_header_match(&signature_owners);
1397        }
1398
1399        let mut nearest_distance: Option<(u32, u32)> = None;
1400        let mut nearest_functions = Vec::new();
1401        for function_index in window {
1402            let function = &self.functions[function_index];
1403            if !is_anonymous_istanbul_name(&function.name) {
1404                continue;
1405            }
1406            let Some(distance) =
1407                function.nearest_alias(target, Some(ANONYMOUS_FALLBACK_MAX_COLUMN_DRIFT))
1408            else {
1409                continue;
1410            };
1411            // Inside a signature, proximity alone cannot tell a member from
1412            // the function written in its parameter list. A candidate that
1413            // neither sits on the target nor contains it is the wrong one.
1414            if distance != (0, 0)
1415                && self.foreign_signature_blocks(&signature_owners, function_index, target)
1416            {
1417                continue;
1418            }
1419            match nearest_distance {
1420                None => {
1421                    nearest_distance = Some(distance);
1422                    nearest_functions.push(function_index);
1423                }
1424                Some(previous) if distance < previous => {
1425                    nearest_distance = Some(distance);
1426                    nearest_functions.clear();
1427                    nearest_functions.push(function_index);
1428                }
1429                Some(previous) if distance == previous => {
1430                    nearest_functions.push(function_index);
1431                }
1432                Some(_) => {}
1433            }
1434        }
1435        let established_match = match nearest_functions.as_slice() {
1436            [] => None,
1437            [function_index] => Some(self.functions[*function_index].coverage_pct),
1438            tied => self.innermost_anonymous_match(tied, target),
1439        };
1440        if established_match.is_some() {
1441            return established_match;
1442        }
1443
1444        self.unique_anonymous_header_match(&signature_owners)
1445    }
1446
1447    /// Indices of the records whose header span contains `target`, ascending.
1448    ///
1449    /// A span reaches `target` from no further than `max_header_height` lines
1450    /// above it, so every containing span starts inside that window.
1451    fn header_spans_containing(&self, target: IstanbulPosition) -> Vec<usize> {
1452        let low = target.line.saturating_sub(self.max_header_height);
1453        let first = self.header_starts.partition_point(|(line, _)| *line < low);
1454        let past = self
1455            .header_starts
1456            .partition_point(|(line, _)| *line <= target.line);
1457        self.header_starts[first..past]
1458            .iter()
1459            .filter(|(_, function_index)| {
1460                self.functions[*function_index]
1461                    .header_span
1462                    .is_some_and(|span| span.contains(target))
1463            })
1464            .map(|(_, function_index)| *function_index)
1465            .collect()
1466    }
1467
1468    /// Whether `candidate` is the wrong record for a target inside a
1469    /// signature it does not own.
1470    ///
1471    /// A default parameter value, a decorator argument, and a class
1472    /// expression in a signature are functions of their own, written a line
1473    /// or two from the member whose signature holds them. Crediting one by
1474    /// proximity reports its coverage for a function that never shared its
1475    /// fate. A candidate that contains the target in its own signature or
1476    /// body is not that case: the target is its code, however the enclosing
1477    /// signature encloses both.
1478    fn foreign_signature_blocks(
1479        &self,
1480        owners: &[usize],
1481        candidate: usize,
1482        target: IstanbulPosition,
1483    ) -> bool {
1484        let function = &self.functions[candidate];
1485        if function
1486            .header_span
1487            .is_some_and(|span| span.contains(target))
1488            || function.body_span.is_some_and(|span| span.contains(target))
1489        {
1490            return false;
1491        }
1492        owners.iter().any(|&owner| {
1493            owner != candidate
1494                && self.functions[owner]
1495                    .header_span
1496                    .is_some_and(|span| span.contains(function.decl_start))
1497        })
1498    }
1499
1500    /// Coverage of the single anonymous record whose signature owns the
1501    /// target, given every record whose header span covers it.
1502    ///
1503    /// A header span runs from `decl.start` to `loc.start`, so it covers the
1504    /// signature: the parameter list, its default values, and any decorators.
1505    /// A function literal written there is a different function from the one
1506    /// that owns the span, and crediting it with the owner's coverage reports
1507    /// never-executed code as covered. Two containing spans therefore abstain,
1508    /// as does a span with a second function declared inside it. Only an
1509    /// anonymous record can win, because a named record is already reachable
1510    /// through the exact and fuzzy name paths.
1511    fn unique_anonymous_header_match(&self, signature_owners: &[usize]) -> Option<f64> {
1512        let [function_index] = signature_owners else {
1513            return None;
1514        };
1515        let function = &self.functions[*function_index];
1516        if !is_anonymous_istanbul_name(&function.name) || function.header_holds_other_fn {
1517            return None;
1518        }
1519        Some(function.coverage_pct)
1520    }
1521
1522    fn innermost_anonymous_match(&self, tied: &[usize], target: IstanbulPosition) -> Option<f64> {
1523        let containing: Option<Vec<_>> = tied
1524            .iter()
1525            .map(|&function_index| {
1526                self.functions[function_index]
1527                    .body_span
1528                    .filter(|span| span.contains(target))
1529                    .map(|span| (function_index, span))
1530            })
1531            .collect();
1532        let containing = containing?;
1533
1534        let mut winner = None;
1535        for &(function_index, candidate_span) in &containing {
1536            let is_strictly_innermost = containing.iter().all(|&(other_index, other_span)| {
1537                other_index == function_index || other_span.strictly_contains(candidate_span)
1538            });
1539            if !is_strictly_innermost {
1540                continue;
1541            }
1542            if winner.replace(function_index).is_some() {
1543                return None;
1544            }
1545        }
1546        winner.map(|function_index| self.functions[function_index].coverage_pct)
1547    }
1548
1549    /// The single coverage value shared by every entry named `name`, or
1550    /// `None` when the name is absent or its records disagree. Bit-exact
1551    /// comparison: distinct functions whose values coincide cannot change the
1552    /// result regardless of which record matched.
1553    fn unambiguous_named_pct(&self, name: &str) -> Option<f64> {
1554        let mut found: Option<f64> = None;
1555        for function in &self.functions {
1556            if !function.answers_to(name) {
1557                continue;
1558            }
1559            match found {
1560                None => found = Some(function.coverage_pct),
1561                Some(previous) if previous.to_bits() == function.coverage_pct.to_bits() => {}
1562                Some(_) => return None,
1563            }
1564        }
1565        found
1566    }
1567}
1568
1569/// Loaded Istanbul coverage data, keyed by canonical file path.
1570pub struct IstanbulCoverage {
1571    files: rustc_hash::FxHashMap<std::path::PathBuf, IstanbulFileCoverage>,
1572    format: fallow_output::CoverageInputFormat,
1573}
1574
1575impl IstanbulCoverage {
1576    /// Get coverage data for a file path.
1577    pub fn get(&self, path: &std::path::Path) -> Option<&IstanbulFileCoverage> {
1578        self.files.get(path)
1579    }
1580
1581    /// How many files the coverage map describes, joined or not.
1582    pub fn file_count(&self) -> usize {
1583        self.files.len()
1584    }
1585
1586    /// The input format the coverage was read from.
1587    pub const fn format(&self) -> fallow_output::CoverageInputFormat {
1588        self.format
1589    }
1590}
1591
1592/// Precedence decision for per-function CRAP coverage inputs.
1593///
1594/// Template inheritance wins first so Angular `.html` template findings can
1595/// use the owning `.component.ts` reachability context. Istanbul wins next,
1596/// even when the current file is missing from the coverage map, because that
1597/// path still records unmatched functions in the run-level match counters.
1598/// Plain graph-estimated coverage is the final fallback.
1599enum CrapCoverageResolution<'a> {
1600    TemplateInherited(&'a TemplateInheritContext),
1601    Istanbul {
1602        file_coverage: Option<&'a IstanbulFileCoverage>,
1603    },
1604    StaticEstimated,
1605}
1606
1607fn resolve_crap_coverage<'a>(
1608    template_inherit: Option<&'a TemplateInheritContext>,
1609    istanbul_coverage: Option<&'a IstanbulCoverage>,
1610    path: &std::path::Path,
1611) -> CrapCoverageResolution<'a> {
1612    if let Some(inherit_ctx) = template_inherit {
1613        CrapCoverageResolution::TemplateInherited(inherit_ctx)
1614    } else if let Some(istanbul) = istanbul_coverage {
1615        let canonical = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
1616        CrapCoverageResolution::Istanbul {
1617            file_coverage: istanbul.get(&canonical),
1618        }
1619    } else {
1620        CrapCoverageResolution::StaticEstimated
1621    }
1622}
1623
1624/// Auto-detect a `coverage-final.json` file in common locations relative to the project root.
1625///
1626/// Checks (in order): `coverage/coverage-final.json`, `.nyc_output/coverage-final.json`.
1627/// Returns the first path found, or `None` if no coverage file exists.
1628/// The audit base-worktree pass uses the same detection against the head
1629/// project root, so auto-detected coverage scores both attribution sides
1630/// (#2347).
1631pub fn auto_detect_coverage(root: &std::path::Path) -> Option<std::path::PathBuf> {
1632    let candidates = [
1633        root.join("coverage/coverage-final.json"),
1634        root.join(".nyc_output/coverage-final.json"),
1635    ];
1636    candidates.into_iter().find(|p| p.is_file())
1637}
1638
1639/// Resolve a relative path against the fallow project root. Returns `path`
1640/// unchanged when it is absolute or `project_root` is `None`. Matches the
1641/// convention every other path-shaped CLI input uses, so a monorepo CI run
1642/// invoked from the workspace root with `--root sub-project` finds
1643/// `sub-project/relative/path.json` instead of `cwd/relative/path.json`.
1644pub fn resolve_relative_to_root(
1645    path: &std::path::Path,
1646    project_root: Option<&std::path::Path>,
1647) -> std::path::PathBuf {
1648    if fallow_types::path_util::is_absolute_path_any_platform(path) {
1649        return path.to_path_buf();
1650    }
1651    match project_root {
1652        Some(root) => root.join(path),
1653        None => path.to_path_buf(),
1654    }
1655}
1656
1657/// If `path` is a directory, looks for `coverage-final.json` inside it.
1658/// Parses the Istanbul JSON format and pre-computes per-function statement
1659/// coverage percentages for efficient lookup during CRAP scoring.
1660///
1661/// When `coverage_root` is provided, file paths in the Istanbul data are rebased:
1662/// the `coverage_root` prefix is stripped and `project_root` is prepended, enabling
1663/// cross-environment matching (e.g., coverage from CI used on a local checkout).
1664///
1665/// `path` itself is resolved against `project_root` when relative, so callers
1666/// can pass `--coverage coverage/foo.json` from a parent directory and have it
1667/// land under the `--root` they configured.
1668///
1669/// `relocated` marks a map recorded against a different checkout of the
1670/// project; see [`IstanbulFileCoverage::lookup`].
1671#[cfg(test)]
1672fn load_istanbul_coverage(
1673    path: &std::path::Path,
1674    coverage_root: Option<&std::path::Path>,
1675    project_root: Option<&std::path::Path>,
1676    relocated: bool,
1677) -> Result<IstanbulCoverage, String> {
1678    load_istanbul_coverage_for_sources(path, coverage_root, project_root, None, relocated)
1679}
1680
1681pub(super) fn load_istanbul_coverage_for_sources(
1682    path: &std::path::Path,
1683    coverage_root: Option<&std::path::Path>,
1684    project_root: Option<&std::path::Path>,
1685    discovered_sources: Option<&rustc_hash::FxHashSet<std::path::PathBuf>>,
1686    relocated: bool,
1687) -> Result<IstanbulCoverage, String> {
1688    super::validate_coverage_root_absolute(coverage_root)?;
1689    let resolved = resolve_relative_to_root(path, project_root);
1690    match read_coverage_input(&resolved)? {
1691        CoverageInput::Istanbul { file_path, json } => {
1692            let raw = parse_coverage_map_tolerantly(&json).map_err(|e| {
1693                format!(
1694                    "failed to parse coverage data from {}: {e}",
1695                    file_path.display()
1696                )
1697            })?;
1698            let sources = CoverageMapSources {
1699                coverage_root,
1700                project_root,
1701                discovered_sources,
1702                relocated,
1703            };
1704            Ok(build_istanbul_coverage(
1705                &raw,
1706                &sources,
1707                fallow_output::CoverageInputFormat::Istanbul,
1708            ))
1709        }
1710        CoverageInput::V8 { dump_files } => {
1711            let scope = super::coverage_v8::V8ScriptScope {
1712                coverage_root,
1713                project_root,
1714                discovered_sources,
1715            };
1716            let raw = super::coverage_v8::load_v8_coverage_map(&dump_files, &scope)?;
1717            // The V8 records already carry rebased canonical paths.
1718            let sources = CoverageMapSources {
1719                coverage_root: None,
1720                project_root,
1721                discovered_sources,
1722                relocated,
1723            };
1724            Ok(build_istanbul_coverage(
1725                &raw,
1726                &sources,
1727                fallow_output::CoverageInputFormat::V8,
1728            ))
1729        }
1730    }
1731}
1732
1733/// How the file paths of a coverage map relate to the analyzed project.
1734#[derive(Clone, Copy)]
1735struct CoverageMapSources<'a> {
1736    coverage_root: Option<&'a std::path::Path>,
1737    project_root: Option<&'a std::path::Path>,
1738    discovered_sources: Option<&'a rustc_hash::FxHashSet<std::path::PathBuf>>,
1739    relocated: bool,
1740}
1741
1742fn build_istanbul_coverage(
1743    raw: &std::collections::BTreeMap<String, oxc_coverage_instrument::FileCoverage>,
1744    sources: &CoverageMapSources<'_>,
1745    format: fallow_output::CoverageInputFormat,
1746) -> IstanbulCoverage {
1747    let CoverageMapSources {
1748        coverage_root,
1749        project_root,
1750        discovered_sources,
1751        relocated,
1752    } = *sources;
1753    let mut files = rustc_hash::FxHashMap::default();
1754    for file_cov in raw.values() {
1755        // A producer may record project-relative keys. They are relative to
1756        // the project, not to wherever the process happens to run, and
1757        // resolving them against the current directory fails the whole map at
1758        // once with every unit silently falling back to its estimate.
1759        let raw_path = resolve_relative_to_root(std::path::Path::new(&file_cov.path), project_root);
1760        let file_path = if let (Some(cov_root), Some(proj_root)) = (coverage_root, project_root) {
1761            rebase_coverage_path(raw_path, cov_root, proj_root)
1762        } else {
1763            raw_path
1764        };
1765        let canonical = dunce::canonicalize(&file_path).unwrap_or(file_path);
1766        let source = read_discovered_source(&canonical, discovered_sources, relocated);
1767        let source_index = source
1768            .as_deref()
1769            .map(|source| IstanbulSourceIndex::new(source, &canonical));
1770
1771        let statement_owners = tally_statements_by_owner(file_cov);
1772        let mut functions = Vec::with_capacity(file_cov.fn_map.len());
1773        for (fn_id, fn_entry) in &file_cov.fn_map {
1774            let coverage_pct = compute_function_statement_coverage(
1775                file_cov,
1776                fn_id,
1777                statement_owners.get(fn_id.as_str()),
1778            );
1779            if let Some(function) =
1780                istanbul_function_coverage(fn_entry, coverage_pct, source_index.as_ref())
1781            {
1782                functions.push(function);
1783            }
1784        }
1785
1786        files.insert(canonical, IstanbulFileCoverage::new(functions, relocated));
1787    }
1788
1789    IstanbulCoverage { files, format }
1790}
1791
1792#[expect(
1793    clippy::filetype_is_file,
1794    reason = "coverage provenance must admit regular files and reject every special file type"
1795)]
1796fn read_discovered_source(
1797    path: &std::path::Path,
1798    discovered_sources: Option<&rustc_hash::FxHashSet<std::path::PathBuf>>,
1799    relocated: bool,
1800) -> Option<String> {
1801    if relocated || !discovered_sources.is_some_and(|sources| sources.contains(path)) {
1802        return None;
1803    }
1804    if std::fs::symlink_metadata(path).ok()?.file_type().is_file() {
1805        std::fs::read_to_string(path).ok()
1806    } else {
1807        None
1808    }
1809}
1810
1811/// Parse a coverage map, retrying once with negative values clamped.
1812///
1813/// A producer can emit a negative coordinate for a position it could not
1814/// place: `v8-to-istanbul`, which is what c8 and nyc write, records
1815/// `column: -1` on the implicit else of a bare `if`. Vitest `coverage-v8`
1816/// (through ast-v8-to-istanbul) records a negative hit count for that same
1817/// implicit else in `b`. Positions and counts are unsigned, so one such value
1818/// rejects the entire map. The retry costs a second parse and only runs after
1819/// the strict one has already failed.
1820fn parse_coverage_map_tolerantly(
1821    json: &str,
1822) -> Result<std::collections::BTreeMap<String, oxc_coverage_instrument::FileCoverage>, String> {
1823    match oxc_coverage_instrument::parse_coverage_map(json) {
1824        Ok(raw) => Ok(raw),
1825        Err(strict_error) => {
1826            let mut value: serde_json::Value =
1827                serde_json::from_str(json).map_err(|_| strict_error.to_string())?;
1828            let positions = clamp_negative_positions(&mut value);
1829            let counts = clamp_negative_counts(&mut value);
1830            if !positions && !counts {
1831                return Err(strict_error.to_string());
1832            }
1833            serde_json::from_value(value).map_err(|_| strict_error.to_string())
1834        }
1835    }
1836}
1837
1838/// Clamp every negative `line` or `column` in the tree to zero, reporting
1839/// whether anything changed. Zero is what the shared position type already
1840/// uses for a coordinate a producer left null or absent.
1841fn clamp_negative_positions(value: &mut serde_json::Value) -> bool {
1842    match value {
1843        serde_json::Value::Object(entries) => {
1844            let mut clamped = false;
1845            for (key, child) in entries.iter_mut() {
1846                if matches!(key.as_str(), "line" | "column")
1847                    && child.as_i64().is_some_and(|number| number < 0)
1848                {
1849                    *child = serde_json::Value::from(0);
1850                    clamped = true;
1851                    continue;
1852                }
1853                clamped |= clamp_negative_positions(child);
1854            }
1855            clamped
1856        }
1857        serde_json::Value::Array(items) => items.iter_mut().fold(false, |clamped, item| {
1858            clamped | clamp_negative_positions(item)
1859        }),
1860        _ => false,
1861    }
1862}
1863
1864/// The hit-count sections of an Istanbul file record.
1865const COVERAGE_COUNT_KEYS: [&str; 4] = ["s", "f", "b", "b_T"];
1866
1867/// Clamp every negative hit count in the map to zero, reporting whether
1868/// anything changed. A negative count is a miss: the coverage test here is
1869/// `count > 0`, so zero gives the same answer the signed value would.
1870fn clamp_negative_counts(value: &mut serde_json::Value) -> bool {
1871    let serde_json::Value::Object(files) = value else {
1872        return false;
1873    };
1874    let mut clamped = false;
1875    for file in files.values_mut() {
1876        let serde_json::Value::Object(sections) = file else {
1877            continue;
1878        };
1879        for key in COVERAGE_COUNT_KEYS {
1880            if let Some(counts) = sections.get_mut(key) {
1881                clamped |= clamp_negative_numbers(counts);
1882            }
1883        }
1884    }
1885    clamped
1886}
1887
1888/// Clamp every negative number in the tree to zero, reporting whether
1889/// anything changed.
1890fn clamp_negative_numbers(value: &mut serde_json::Value) -> bool {
1891    match value {
1892        serde_json::Value::Number(number) if number.as_f64().is_some_and(|n| n < 0.0) => {
1893            *value = serde_json::Value::from(0);
1894            true
1895        }
1896        serde_json::Value::Object(entries) => entries.values_mut().fold(false, |clamped, child| {
1897            clamped | clamp_negative_numbers(child)
1898        }),
1899        serde_json::Value::Array(items) => items.iter_mut().fold(false, |clamped, item| {
1900            clamped | clamp_negative_numbers(item)
1901        }),
1902        _ => false,
1903    }
1904}
1905
1906/// The property name behind an accessor record, when a producer prefixed it.
1907///
1908/// istanbul-lib-instrument leaves a class accessor anonymous, but raw V8
1909/// coverage and `oxc-coverage-instrument` record `get area` and `set area`,
1910/// while fallow extracts the unit as `area`. The prefix is the whole
1911/// difference, so a record keeps its own spelling and answers to the bare
1912/// property name as well.
1913fn accessor_property_name(name: &str) -> Option<&str> {
1914    let property = name
1915        .strip_prefix("get ")
1916        .or_else(|| name.strip_prefix("set "))?;
1917    (!property.is_empty() && !property.contains(' ')).then_some(property)
1918}
1919
1920/// Rebase one Istanbul file path from `coverage_root` onto `project_root`.
1921///
1922/// When the recorded path does not start with `coverage_root` verbatim, retry
1923/// with its canonicalized form: coverage generated inside a symlinked
1924/// directory (macOS `/var` vs `/private/var`) records the symlinked spelling
1925/// while the rebase prefix is typically canonical. Paths under neither
1926/// spelling are kept as-is.
1927fn rebase_coverage_path(
1928    raw_path: std::path::PathBuf,
1929    coverage_root: &std::path::Path,
1930    project_root: &std::path::Path,
1931) -> std::path::PathBuf {
1932    if let Ok(rel) = raw_path.strip_prefix(coverage_root) {
1933        return project_root.join(rel);
1934    }
1935    if let Ok(canonical) = dunce::canonicalize(&raw_path)
1936        && let Ok(rel) = canonical.strip_prefix(coverage_root)
1937    {
1938        return project_root.join(rel);
1939    }
1940    raw_path
1941}
1942
1943fn istanbul_function_coverage(
1944    fn_entry: &oxc_coverage_instrument::FnEntry,
1945    coverage_pct: f64,
1946    source_index: Option<&IstanbulSourceIndex<'_>>,
1947) -> Option<IstanbulFunctionCoverage> {
1948    let body_span = IstanbulSpan::from_entry(fn_entry, source_index);
1949    let header_span = IstanbulSpan::header_from_entry(fn_entry, source_index);
1950    let decl_start = normalized_istanbul_position(
1951        fn_entry.decl.start.line,
1952        fn_entry.decl.start.column,
1953        source_index,
1954    )?;
1955    let effective_position = normalized_istanbul_position(
1956        effective_istanbul_fn_line(fn_entry),
1957        fn_entry.decl.start.column,
1958        source_index,
1959    );
1960    let candidates = [
1961        effective_position.map(|position| IstanbulAlias {
1962            position,
1963            primary: true,
1964        }),
1965        Some(IstanbulAlias {
1966            position: decl_start,
1967            primary: true,
1968        }),
1969        body_span.map(|span| IstanbulAlias {
1970            position: span.start,
1971            primary: false,
1972        }),
1973        named_function_syntax_alias(fn_entry, source_index),
1974    ];
1975    let mut aliases: Vec<IstanbulAlias> = Vec::with_capacity(candidates.len());
1976    for candidate in candidates.into_iter().flatten() {
1977        if !aliases
1978            .iter()
1979            .any(|alias| alias.position == candidate.position)
1980        {
1981            aliases.push(candidate);
1982        }
1983    }
1984
1985    Some(IstanbulFunctionCoverage {
1986        name: fn_entry.name.clone(),
1987        coverage_pct,
1988        aliases,
1989        decl_start,
1990        header_holds_other_fn: false,
1991        header_span,
1992        body_span,
1993    })
1994}
1995
1996/// Source index used to reconcile Istanbul's UTF-16 columns with Fallow's
1997/// UTF-8 byte columns and recover exact named-function syntax starts.
1998struct IstanbulSourceIndex<'a> {
1999    source: &'a str,
2000    line_starts: Vec<usize>,
2001    non_ascii_lines: rustc_hash::FxHashMap<usize, Utf16LineIndex>,
2002    named_function_starts: rustc_hash::FxHashMap<usize, usize>,
2003}
2004
2005struct Utf16LineIndex {
2006    utf16_len: u32,
2007    byte_len: usize,
2008    checkpoints: Vec<Utf16Checkpoint>,
2009}
2010
2011struct Utf16Checkpoint {
2012    utf16_start: u32,
2013    utf16_end: u32,
2014    byte_end: usize,
2015}
2016
2017impl<'a> IstanbulSourceIndex<'a> {
2018    fn new(source: &'a str, path: &std::path::Path) -> Self {
2019        let mut line_starts = vec![0];
2020        line_starts.extend(
2021            source
2022                .bytes()
2023                .enumerate()
2024                .filter_map(|(index, byte)| (byte == b'\n').then_some(index + 1)),
2025        );
2026        let non_ascii_lines = utf16_line_indexes(source, &line_starts);
2027
2028        let named_function_starts = named_function_starts_from_clean_parse(source, path);
2029
2030        Self {
2031            source,
2032            line_starts,
2033            non_ascii_lines,
2034            named_function_starts,
2035        }
2036    }
2037
2038    fn byte_position(&self, line: u32, utf16_column: u32) -> Option<IstanbulPosition> {
2039        let line_index = usize::try_from(line.checked_sub(1)?).ok()?;
2040        let line_start = *self.line_starts.get(line_index)?;
2041        let line_end = self
2042            .line_starts
2043            .get(line_index + 1)
2044            .copied()
2045            .map_or(self.source.len(), |next_start| next_start - 1);
2046        let line_source = self.source.get(line_start..line_end)?;
2047        let byte_column = if let Some(index) = self.non_ascii_lines.get(&line_index) {
2048            index.byte_column(utf16_column)?
2049        } else {
2050            let byte_column = usize::try_from(utf16_column).ok()?;
2051            (byte_column <= line_source.len()).then_some(byte_column)?
2052        };
2053        Some(IstanbulPosition::new(
2054            line,
2055            u32::try_from(byte_column).ok()?,
2056        ))
2057    }
2058
2059    fn absolute_offset(&self, line: u32, utf16_column: u32) -> Option<usize> {
2060        let position = self.byte_position(line, utf16_column)?;
2061        let line_index = usize::try_from(position.line.checked_sub(1)?).ok()?;
2062        self.line_starts
2063            .get(line_index)?
2064            .checked_add(position.col as usize)
2065    }
2066
2067    fn position_at_offset(&self, offset: usize) -> Option<IstanbulPosition> {
2068        if offset > self.source.len() {
2069            return None;
2070        }
2071        let line_index = self.line_starts.partition_point(|start| *start <= offset) - 1;
2072        Some(IstanbulPosition::new(
2073            u32::try_from(line_index + 1).ok()?,
2074            u32::try_from(offset.checked_sub(self.line_starts[line_index])?).ok()?,
2075        ))
2076    }
2077
2078    fn named_function_start(
2079        &self,
2080        fn_entry: &oxc_coverage_instrument::FnEntry,
2081    ) -> Option<IstanbulPosition> {
2082        let declaration_offset =
2083            self.absolute_offset(fn_entry.decl.start.line, fn_entry.decl.start.column)?;
2084        let syntax_offset = *self.named_function_starts.get(&declaration_offset)?;
2085        self.position_at_offset(syntax_offset)
2086    }
2087}
2088
2089impl Utf16LineIndex {
2090    fn byte_column(&self, utf16_column: u32) -> Option<usize> {
2091        if utf16_column > self.utf16_len {
2092            return None;
2093        }
2094        let completed = self
2095            .checkpoints
2096            .partition_point(|checkpoint| checkpoint.utf16_end <= utf16_column);
2097        if let Some(next) = self.checkpoints.get(completed)
2098            && utf16_column > next.utf16_start
2099        {
2100            return None;
2101        }
2102        let (utf16_base, byte_base) = completed
2103            .checked_sub(1)
2104            .and_then(|index| self.checkpoints.get(index))
2105            .map_or((0, 0), |checkpoint| {
2106                (checkpoint.utf16_end, checkpoint.byte_end)
2107            });
2108        let ascii_width = usize::try_from(utf16_column.checked_sub(utf16_base)?).ok()?;
2109        let byte_column = byte_base.checked_add(ascii_width)?;
2110        (byte_column <= self.byte_len).then_some(byte_column)
2111    }
2112}
2113
2114fn utf16_line_indexes(
2115    source: &str,
2116    line_starts: &[usize],
2117) -> rustc_hash::FxHashMap<usize, Utf16LineIndex> {
2118    let mut indexes = rustc_hash::FxHashMap::default();
2119    for (line_index, &line_start) in line_starts.iter().enumerate() {
2120        let line_end = line_starts
2121            .get(line_index + 1)
2122            .copied()
2123            .map_or(source.len(), |next_start| next_start - 1);
2124        let Some(line) = source.get(line_start..line_end) else {
2125            continue;
2126        };
2127        if line.is_ascii() {
2128            continue;
2129        }
2130        let mut utf16_column = 0_u32;
2131        let mut checkpoints = Vec::new();
2132        for (byte_column, character) in line.char_indices() {
2133            let utf16_width = character.len_utf16() as u32;
2134            if !character.is_ascii() {
2135                checkpoints.push(Utf16Checkpoint {
2136                    utf16_start: utf16_column,
2137                    utf16_end: utf16_column.saturating_add(utf16_width),
2138                    byte_end: byte_column.saturating_add(character.len_utf8()),
2139                });
2140            }
2141            utf16_column = utf16_column.saturating_add(utf16_width);
2142        }
2143        indexes.insert(
2144            line_index,
2145            Utf16LineIndex {
2146                utf16_len: utf16_column,
2147                byte_len: line.len(),
2148                checkpoints,
2149            },
2150        );
2151    }
2152    indexes
2153}
2154
2155fn named_function_starts_from_clean_parse(
2156    source: &str,
2157    path: &std::path::Path,
2158) -> rustc_hash::FxHashMap<usize, usize> {
2159    let source_type = match path.extension().and_then(|extension| extension.to_str()) {
2160        Some("gts") => oxc_span::SourceType::ts(),
2161        Some("gjs") => oxc_span::SourceType::mjs(),
2162        _ => oxc_span::SourceType::from_path(path).unwrap_or_default(),
2163    };
2164    if let Some(starts) = collect_named_function_starts(source, source_type) {
2165        return starts;
2166    }
2167    if source_type.is_jsx() {
2168        return rustc_hash::FxHashMap::default();
2169    }
2170    let jsx_source_type = if source_type.is_typescript() {
2171        oxc_span::SourceType::tsx()
2172    } else {
2173        oxc_span::SourceType::jsx()
2174    };
2175    collect_named_function_starts(source, jsx_source_type).unwrap_or_default()
2176}
2177
2178fn collect_named_function_starts(
2179    source: &str,
2180    source_type: oxc_span::SourceType,
2181) -> Option<rustc_hash::FxHashMap<usize, usize>> {
2182    fallow_extract::parse_bounded_or_default(source, source_type, |parsed| {
2183        if parsed.fatal_error || !parsed.diagnostics.is_empty() {
2184            return None;
2185        }
2186        let mut starts = rustc_hash::FxHashMap::default();
2187        let mut collector = NamedFunctionSyntaxCollector {
2188            starts: &mut starts,
2189        };
2190        oxc_ast_visit::Visit::visit_program(&mut collector, &parsed.program);
2191        Some(starts)
2192    })
2193}
2194
2195struct NamedFunctionSyntaxCollector<'a> {
2196    starts: &'a mut rustc_hash::FxHashMap<usize, usize>,
2197}
2198
2199impl<'ast> oxc_ast_visit::Visit<'ast> for NamedFunctionSyntaxCollector<'_> {
2200    fn visit_function(
2201        &mut self,
2202        function: &oxc_ast::ast::Function<'ast>,
2203        flags: oxc_syntax::scope::ScopeFlags,
2204    ) {
2205        if let Some(identifier) = &function.id
2206            && let (Ok(identifier_start), Ok(syntax_start)) = (
2207                usize::try_from(identifier.span.start),
2208                usize::try_from(function.span.start),
2209            )
2210        {
2211            self.starts.insert(identifier_start, syntax_start);
2212        }
2213        oxc_ast_visit::walk::walk_function(self, function, flags);
2214    }
2215}
2216
2217fn normalized_istanbul_position(
2218    line: u32,
2219    column: u32,
2220    source_index: Option<&IstanbulSourceIndex<'_>>,
2221) -> Option<IstanbulPosition> {
2222    match source_index {
2223        Some(index) => index.byte_position(line, column),
2224        None => Some(IstanbulPosition::new(line, column)),
2225    }
2226}
2227
2228/// Exact syntax-backed alias for a named function's source start.
2229///
2230/// Istanbul declares a named function at its identifier, while Fallow records
2231/// the containing `function` or `async` keyword. Parser tokens distinguish
2232/// that real syntax across legal trivia from unrelated same-width text.
2233fn named_function_syntax_alias(
2234    fn_entry: &oxc_coverage_instrument::FnEntry,
2235    source_index: Option<&IstanbulSourceIndex<'_>>,
2236) -> Option<IstanbulAlias> {
2237    if is_anonymous_istanbul_name(&fn_entry.name) {
2238        return None;
2239    }
2240    Some(IstanbulAlias {
2241        position: source_index?.named_function_start(fn_entry)?,
2242        primary: true,
2243    })
2244}
2245
2246fn effective_istanbul_fn_line(fn_entry: &oxc_coverage_instrument::FnEntry) -> u32 {
2247    if fn_entry.line > 0 {
2248        fn_entry.line
2249    } else {
2250        fn_entry.decl.start.line
2251    }
2252}
2253
2254/// Statements owned by a single `fnMap` record.
2255#[derive(Default)]
2256struct StatementTally {
2257    covered: u32,
2258    total: u32,
2259}
2260
2261/// Whether `outer` encloses `inner`, with both bounds inclusive.
2262///
2263/// These are the bounds the per-function statement scan has always used, so
2264/// which statements a function can claim is unchanged; only how a contested
2265/// statement is awarded moved.
2266fn istanbul_range_contains(
2267    outer: &oxc_coverage_instrument::Location,
2268    inner: &oxc_coverage_instrument::Location,
2269) -> bool {
2270    let after_start = inner.start.line > outer.start.line
2271        || (inner.start.line == outer.start.line && inner.start.column >= outer.start.column);
2272    let before_end = inner.end.line < outer.end.line
2273        || (inner.end.line == outer.end.line && inner.end.column <= outer.end.column);
2274    after_start && before_end
2275}
2276
2277/// Assign every statement to the innermost `fnMap` record that encloses it.
2278///
2279/// A nested function body lies inside the enclosing function's `loc`, so a
2280/// bare containment test charges a closure's statements to the function that
2281/// returns it as well, and an outer function that ran every statement of its
2282/// own is scored down for code it does not own. Ownership here is exclusive:
2283/// a statement counts for exactly one record, or for none at all when no
2284/// record encloses it, which keeps module-scope statements out of every
2285/// function as before.
2286///
2287/// Innermost is the record with the greatest `loc` start. A tie breaks on the
2288/// smallest `loc` end, and a remaining tie between two byte-identical ranges
2289/// keeps the first record in `fnMap` key order, which is stable because the
2290/// map is a `BTreeMap`. Identical ranges are pathological and any winner is
2291/// arbitrary, so determinism is the property that matters.
2292///
2293/// Computed once per file for the same reason as
2294/// [`mark_headers_holding_other_fns`]: every record needs the answer, and the
2295/// alternative rescans the whole statement map once per record.
2296fn tally_statements_by_owner(
2297    file_cov: &oxc_coverage_instrument::FileCoverage,
2298) -> rustc_hash::FxHashMap<&str, StatementTally> {
2299    let mut owners: rustc_hash::FxHashMap<&str, StatementTally> = rustc_hash::FxHashMap::default();
2300
2301    for (stmt_id, stmt_loc) in &file_cov.statement_map {
2302        let mut owner: Option<(&str, &oxc_coverage_instrument::Location)> = None;
2303
2304        for (fn_id, fn_entry) in &file_cov.fn_map {
2305            if !istanbul_range_contains(&fn_entry.loc, stmt_loc) {
2306                continue;
2307            }
2308            let inner_than_current = owner.is_none_or(|(_, best)| {
2309                let candidate = (
2310                    (fn_entry.loc.start.line, fn_entry.loc.start.column),
2311                    std::cmp::Reverse((fn_entry.loc.end.line, fn_entry.loc.end.column)),
2312                );
2313                let incumbent = (
2314                    (best.start.line, best.start.column),
2315                    std::cmp::Reverse((best.end.line, best.end.column)),
2316                );
2317                candidate > incumbent
2318            });
2319            if inner_than_current {
2320                owner = Some((fn_id.as_str(), &fn_entry.loc));
2321            }
2322        }
2323
2324        let Some((fn_id, _)) = owner else {
2325            continue;
2326        };
2327        let tally = owners.entry(fn_id).or_default();
2328        tally.total += 1;
2329        if file_cov.s.get(stmt_id).copied().unwrap_or(0) > 0 {
2330            tally.covered += 1;
2331        }
2332    }
2333
2334    owners
2335}
2336
2337/// Compute statement-level coverage percentage for a single function.
2338///
2339/// Takes the fraction of the statements the function owns that have non-zero
2340/// hit counts, where ownership comes from [`tally_statements_by_owner`] and a
2341/// statement belongs only to the innermost function that encloses it. When the
2342/// function owns no statements (a one-liner arrow, a getter, an outer function
2343/// whose whole body is a nested declaration, or a producer that emits an empty
2344/// `statementMap`), falls back to the function hit count as a binary signal.
2345fn compute_function_statement_coverage(
2346    file_cov: &oxc_coverage_instrument::FileCoverage,
2347    fn_id: &str,
2348    owned: Option<&StatementTally>,
2349) -> f64 {
2350    match owned {
2351        Some(tally) if tally.total > 0 => f64::from(tally.covered) / f64::from(tally.total) * 100.0,
2352        _ => {
2353            let hit = file_cov.f.get(fn_id).copied().unwrap_or(0);
2354            if hit > 0 { 100.0 } else { 0.0 }
2355        }
2356    }
2357}
2358
2359/// Count unused VALUE exports per file path for O(1) lookup.
2360///
2361/// Type-only exports (interfaces, type aliases) are intentionally excluded ---
2362/// they are a different concern than unused functions/components.
2363fn count_unused_exports_by_path(
2364    unused_exports: &[crate::results::UnusedExportFinding],
2365) -> rustc_hash::FxHashMap<&std::path::Path, usize> {
2366    let mut map: rustc_hash::FxHashMap<&std::path::Path, usize> = rustc_hash::FxHashMap::default();
2367    for exp in unused_exports {
2368        *map.entry(exp.export.path.as_path()).or_default() += 1;
2369    }
2370    map
2371}
2372
2373/// Compute the maintainability index for a single file.
2374///
2375/// Formula:
2376/// ```text
2377/// dampening = min(lines / 50, 1.0)
2378/// fan_out_penalty = min(ln(fan_out + 1) * 4, 15)
2379/// MI = 100 - (complexity_density * 30 * dampening) - (dead_code_ratio * 20) - fan_out_penalty
2380/// ```
2381///
2382/// The dampening factor prevents complexity density from dominating the score
2383/// on small files. A 5-line utility with CC=2 has density 0.40, but is trivially
2384/// readable; without dampening it scores worse than a 192-line function with CC=57
2385/// (density 0.30). Files under 50 lines get proportionally reduced density weight.
2386///
2387/// Fan-out uses logarithmic scaling capped at 15 points to reflect diminishing
2388/// marginal risk (the 30th import is less concerning than the 5th) and prevent
2389/// composition-root files from being unfairly penalized.
2390///
2391/// Clamped to \[0, 100\]. Higher is better.
2392fn compute_maintainability_index(
2393    complexity_density: f64,
2394    dead_code_ratio: f64,
2395    fan_out: usize,
2396    lines: u32,
2397) -> f64 {
2398    let dampening = (f64::from(lines) / fallow_output::MI_DENSITY_MIN_LINES).min(1.0);
2399    let fan_out_penalty = ((fan_out as f64).ln_1p() * 4.0).min(15.0);
2400    #[expect(
2401        clippy::suboptimal_flops,
2402        reason = "formula matches documented specification"
2403    )]
2404    let score = 100.0
2405        - (complexity_density * 30.0 * dampening)
2406        - (dead_code_ratio * 20.0)
2407        - fan_out_penalty;
2408    score.clamp(0.0, 100.0)
2409}
2410
2411fn file_score_structural_concern(score: &FileHealthScore) -> f64 {
2412    (100.0 - score.maintainability_index).clamp(0.0, 100.0)
2413}
2414
2415/// True when the file's CRAP signal is fully covered by configuration: nothing
2416/// meets its effective ceiling while something would have been flagged at the
2417/// canonical 30.0 baseline, or CRAP enforcement is disabled entirely
2418/// (`max_crap_threshold <= 0`). Mirrors the findings pipeline, which emits no
2419/// CRAP finding in exactly these states, so the row must not read `risk`.
2420#[must_use]
2421pub fn file_score_fully_crap_exempt(score: &FileHealthScore, max_crap_threshold: f64) -> bool {
2422    let signal = file_score_crap_signal(score, max_crap_threshold);
2423    max_crap_threshold <= 0.0
2424        || (score.crap_above_threshold == 0
2425            && if signal.suppression_aware {
2426                signal.maximum >= CRAP_THRESHOLD
2427            } else {
2428                score.crap_exempted > 0
2429            })
2430}
2431
2432/// The complete CRAP metric/ceiling pair used for triage and remediation.
2433pub struct FileScoreCrapSignal {
2434    /// Maximum remaining score, or the raw maximum for legacy rows.
2435    pub maximum: f64,
2436    /// Effective ceiling belonging to the same population as the maximum.
2437    pub threshold: f64,
2438    suppression_aware: bool,
2439}
2440
2441impl FileScoreCrapSignal {
2442    /// JSON metric whose value the signal carries.
2443    pub const fn metric(&self) -> &'static str {
2444        if self.suppression_aware {
2445            "crap_unsuppressed_max"
2446        } else {
2447            "crap_max"
2448        }
2449    }
2450}
2451
2452/// Select the unsuppressed pair only when complete. Absent or partial external
2453/// metadata uses the complete legacy pair, never a mixture of populations.
2454pub fn file_score_crap_signal(score: &FileHealthScore, global: f64) -> FileScoreCrapSignal {
2455    match (
2456        score.crap_unsuppressed_max,
2457        score.crap_unsuppressed_effective_threshold,
2458    ) {
2459        (Some(maximum), Some(threshold)) => FileScoreCrapSignal {
2460            maximum,
2461            threshold,
2462            suppression_aware: true,
2463        },
2464        _ => FileScoreCrapSignal {
2465            maximum: score.crap_max,
2466            threshold: score.crap_effective_threshold.unwrap_or(global),
2467            suppression_aware: false,
2468        },
2469    }
2470}
2471
2472/// CRAP concern bands generalized over the selected metric pair's ceiling `t`.
2473/// The complete unsuppressed pair takes precedence over legacy metrics. At `t = 30`
2474/// the breakpoints are the historical (15, 30, 100). A fully exempt file
2475/// scores `0.0`: band generalization alone cannot drop an exempted file below
2476/// its structural concern, so the tag would keep reading `risk` against a run
2477/// with zero findings.
2478fn file_score_crap_concern(score: &FileHealthScore, max_crap_threshold: f64) -> f64 {
2479    if file_score_fully_crap_exempt(score, max_crap_threshold) {
2480        return 0.0;
2481    }
2482    let signal = file_score_crap_signal(score, max_crap_threshold);
2483    let crap_max = signal.maximum;
2484    let t = signal.threshold;
2485    let half = t / 2.0;
2486    let saturation = t * 10.0 / 3.0;
2487    if crap_max <= 0.0 {
2488        0.0
2489    } else if crap_max < half {
2490        (crap_max / half) * 45.0
2491    } else if crap_max < t {
2492        ((crap_max - half) / half).mul_add(30.0, 45.0)
2493    } else if crap_max < saturation {
2494        ((crap_max - t) / (saturation - t)).mul_add(25.0, 75.0)
2495    } else {
2496        100.0
2497    }
2498}
2499
2500fn file_score_triage_concern(score: &FileHealthScore, max_crap_threshold: f64) -> f64 {
2501    file_score_structural_concern(score).max(file_score_crap_concern(score, max_crap_threshold))
2502}
2503
2504/// Which signal places a file at its triage rank: its structural quality (low
2505/// maintainability index) or its untested complexity (CRAP risk). Surfaced per
2506/// row so the human file-scores table can label why a file sits where it does
2507/// when the two axes disagree (e.g. a low-CRAP file outranking a higher-CRAP
2508/// one because its MI is the worse signal).
2509#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2510pub enum FileScoreConcern {
2511    /// Ranked by structural quality: a low maintainability index.
2512    Structural,
2513    /// Ranked by untested complexity: a high CRAP score.
2514    Risk,
2515}
2516
2517impl FileScoreConcern {
2518    /// Short lowercase label for the human file-scores table.
2519    pub const fn label(self) -> &'static str {
2520        match self {
2521            Self::Structural => "structure",
2522            Self::Risk => "risk",
2523        }
2524    }
2525}
2526
2527/// Classify which concern drove `score` to its rank. A file with no CRAP
2528/// concern (no CRAP risk at all, or every breaching function exempted by its
2529/// effective ceiling) is always `Structural`; otherwise the larger concern
2530/// wins, with ties (and the boundary where the two are equal) resolving to
2531/// `Risk` because untested complexity is the more urgent signal to act on.
2532///
2533/// `max_crap_threshold` is the run global (`summary.max_crap_threshold`), the
2534/// fallback ceiling for rows without a `crap_effective_threshold` of their own.
2535pub fn file_score_concern_axis(
2536    score: &FileHealthScore,
2537    max_crap_threshold: f64,
2538) -> FileScoreConcern {
2539    let crap_concern = file_score_crap_concern(score, max_crap_threshold);
2540    if crap_concern <= 0.0 {
2541        FileScoreConcern::Structural
2542    } else if crap_concern >= file_score_structural_concern(score) {
2543        FileScoreConcern::Risk
2544    } else {
2545        FileScoreConcern::Structural
2546    }
2547}
2548
2549fn compare_file_score_triage(
2550    a: &FileHealthScore,
2551    b: &FileHealthScore,
2552    max_crap_threshold: f64,
2553) -> std::cmp::Ordering {
2554    file_score_triage_concern(b, max_crap_threshold)
2555        .total_cmp(&file_score_triage_concern(a, max_crap_threshold))
2556        .then_with(|| {
2557            file_score_crap_signal(b, max_crap_threshold)
2558                .maximum
2559                .total_cmp(&file_score_crap_signal(a, max_crap_threshold).maximum)
2560        })
2561        .then_with(|| a.maintainability_index.total_cmp(&b.maintainability_index))
2562        .then_with(|| a.path.cmp(&b.path))
2563}
2564
2565/// Inputs for [`compute_file_scores`], bundled so the analysis artifacts stay
2566/// a separate owned argument.
2567#[derive(Clone, Copy)]
2568pub(super) struct FileScoreComputeInput<'a> {
2569    pub(super) modules: &'a [crate::source::ModuleInfo],
2570    pub(super) file_paths:
2571        &'a rustc_hash::FxHashMap<crate::discover::FileId, &'a std::path::PathBuf>,
2572    pub(super) changed_files: Option<&'a rustc_hash::FxHashSet<std::path::PathBuf>>,
2573    pub(super) istanbul_coverage: Option<&'a IstanbulCoverage>,
2574    pub(super) root: &'a std::path::Path,
2575    pub(super) crap_thresholds: CrapScoreThresholds<'a>,
2576    /// Build the static edge index for change coupling. Only a run that reads
2577    /// the commit history needs it, so other runs skip the graph walk.
2578    pub(super) with_static_links: bool,
2579    /// Graph of the full project that supplies test reachability when the
2580    /// analysis graph has no test files (production mode).
2581    pub(super) test_reach: Option<&'a super::test_reach::TestReachGraph>,
2582}
2583
2584/// Compute per-file health scores using a pre-computed analysis output.
2585///
2586/// The caller provides an `AnalysisOutput` (with graph and dead code results)
2587/// so this function does not need to re-run the analysis pipeline. Complexity
2588/// density is derived from the already-parsed modules.
2589pub(super) fn compute_file_scores(
2590    input: FileScoreComputeInput<'_>,
2591    analysis_output: crate::results::DeadCodeAnalysisArtifacts,
2592) -> Result<FileScoreOutput, String> {
2593    let FileScoreComputeInput {
2594        modules,
2595        file_paths,
2596        changed_files,
2597        istanbul_coverage,
2598        root,
2599        crap_thresholds,
2600        with_static_links,
2601        test_reach,
2602    } = input;
2603    let retained_graph = analysis_output.graph.ok_or("graph not available")?;
2604    let test_coverage = test_reach.map_or_else(
2605        || retained_graph.static_test_coverage(),
2606        super::test_reach::TestReachGraph::static_test_coverage,
2607    );
2608    let graph = retained_graph.as_graph();
2609    let results = &analysis_output.results;
2610
2611    let circular_files = collect_circular_files(results);
2612    let top_complex_fns = collect_top_complex_fns(modules, file_paths);
2613    let cycle_members = collect_cycle_members(results);
2614    let direct_callers = collect_direct_callers(graph, file_paths);
2615    let unused_export_names = collect_unused_export_names(results);
2616
2617    let unused_files: rustc_hash::FxHashSet<&std::path::Path> = results
2618        .unused_files
2619        .iter()
2620        .map(|f| f.file.path.as_path())
2621        .collect();
2622
2623    let unused_exports_by_path = count_unused_exports_by_path(&results.unused_exports);
2624
2625    let FileScoreCoverageSetup {
2626        module_by_id,
2627        coverage,
2628    } = prepare_file_score_coverage_setup(modules, file_paths, results, graph, test_coverage, root);
2629
2630    let template_inherit =
2631        build_template_inherit_contexts(graph, test_coverage, &module_by_id, file_paths);
2632
2633    let mut acc = accumulate_file_scores(
2634        unused_export_names,
2635        &FileScoreLoopCtx {
2636            graph,
2637            test_coverage,
2638            file_paths,
2639            module_by_id: &module_by_id,
2640            unused_files: &unused_files,
2641            unused_exports_by_path: &unused_exports_by_path,
2642            template_inherit: &template_inherit,
2643            istanbul_coverage,
2644            root,
2645            crap_thresholds,
2646        },
2647    );
2648    acc.scores = finalize_file_score_list(
2649        acc.scores,
2650        changed_files,
2651        crap_thresholds.resolver.global.crap,
2652    );
2653
2654    Ok(build_file_score_output(FileScoreOutputParts {
2655        graph,
2656        with_static_links,
2657        file_paths,
2658        results,
2659        scores: acc.scores,
2660        coverage,
2661        circular_files,
2662        top_complex_fns,
2663        crap_target_fns: acc.crap_target_fns,
2664        entry_points: acc.entry_points,
2665        value_export_counts: acc.value_export_counts,
2666        unused_export_names: acc.unused_export_names,
2667        cycle_members,
2668        direct_callers,
2669        istanbul_matched: acc.istanbul_matched,
2670        istanbul_total: acc.istanbul_total,
2671        istanbul_files_joined: acc.istanbul_files_joined,
2672        istanbul_files_total: acc.istanbul_files_total,
2673        coverage_input_format: istanbul_coverage.map(IstanbulCoverage::format),
2674        per_function_crap: acc.per_function_crap,
2675        template_inherit,
2676    }))
2677}
2678
2679/// Read-only inputs threaded into the per-node file-score loop.
2680struct FileScoreLoopCtx<'a> {
2681    graph: &'a fallow_graph::graph::ModuleGraph,
2682    test_coverage: StaticTestCoverage<'a>,
2683    file_paths: &'a rustc_hash::FxHashMap<crate::discover::FileId, &'a std::path::PathBuf>,
2684    module_by_id: &'a rustc_hash::FxHashMap<crate::discover::FileId, &'a crate::source::ModuleInfo>,
2685    unused_files: &'a rustc_hash::FxHashSet<&'a std::path::Path>,
2686    unused_exports_by_path: &'a rustc_hash::FxHashMap<&'a std::path::Path, usize>,
2687    template_inherit: &'a rustc_hash::FxHashMap<crate::discover::FileId, TemplateInheritContext>,
2688    istanbul_coverage: Option<&'a IstanbulCoverage>,
2689    /// Project root used to relativize paths into the override resolver's glob
2690    /// space, matching the findings pipeline's `strip_prefix` on the same root.
2691    root: &'a std::path::Path,
2692    crap_thresholds: CrapScoreThresholds<'a>,
2693}
2694
2695/// Mutable accumulators populated by the per-node file-score loop.
2696struct FileScoreAccumulator {
2697    scores: Vec<FileHealthScore>,
2698    entry_points: rustc_hash::FxHashSet<std::path::PathBuf>,
2699    value_export_counts: rustc_hash::FxHashMap<std::path::PathBuf, usize>,
2700    unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
2701    crap_target_fns: rustc_hash::FxHashMap<std::path::PathBuf, Vec<(String, u32, u16)>>,
2702    per_function_crap: rustc_hash::FxHashMap<std::path::PathBuf, Vec<PerFunctionCrap>>,
2703    istanbul_matched: usize,
2704    istanbul_files_joined: usize,
2705    istanbul_files_total: usize,
2706    istanbul_total: usize,
2707}
2708
2709impl FileScoreAccumulator {
2710    /// Empty accumulator with the score vector pre-sized to the module count.
2711    fn with_capacity(modules: usize) -> Self {
2712        FileScoreAccumulator {
2713            scores: Vec::with_capacity(modules),
2714            entry_points: rustc_hash::FxHashSet::default(),
2715            value_export_counts: rustc_hash::FxHashMap::default(),
2716            unused_export_names: rustc_hash::FxHashMap::default(),
2717            crap_target_fns: rustc_hash::FxHashMap::default(),
2718            per_function_crap: rustc_hash::FxHashMap::default(),
2719            istanbul_matched: 0,
2720            istanbul_total: 0,
2721            istanbul_files_joined: 0,
2722            istanbul_files_total: 0,
2723        }
2724    }
2725}
2726
2727/// Drive the per-node loop, returning an accumulator with one score per
2728/// analyzable file. `unused_export_names` seeds the accumulator's same field.
2729fn accumulate_file_scores(
2730    unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
2731    ctx: &FileScoreLoopCtx<'_>,
2732) -> FileScoreAccumulator {
2733    let mut acc = FileScoreAccumulator {
2734        unused_export_names,
2735        istanbul_files_total: ctx
2736            .istanbul_coverage
2737            .map_or(0, IstanbulCoverage::file_count),
2738        ..FileScoreAccumulator::with_capacity(ctx.graph.modules.len())
2739    };
2740    for node in &ctx.graph.modules {
2741        let Some(path) = ctx.file_paths.get(&node.file_id) else {
2742            continue;
2743        };
2744        record_entry_point(&mut acc.entry_points, node, path);
2745        let score = compute_one_file_score(&mut acc, ctx, node, path);
2746        acc.scores.push(score);
2747    }
2748    acc
2749}
2750
2751/// Apply the changed-file scope filter, drop zero-function barrels, and sort by
2752/// risk-aware triage concern.
2753fn finalize_file_score_list(
2754    mut scores: Vec<FileHealthScore>,
2755    changed_files: Option<&rustc_hash::FxHashSet<std::path::PathBuf>>,
2756    max_crap_threshold: f64,
2757) -> Vec<FileHealthScore> {
2758    if let Some(changed) = changed_files {
2759        scores.retain(|s| changed.contains(&s.path));
2760    }
2761    scores.retain(|s| s.function_count > 0);
2762    scores.sort_by(|a, b| compare_file_score_triage(a, b, max_crap_threshold));
2763    scores
2764}
2765
2766/// Compute the `FileHealthScore` for one node and fold its side data into `acc`.
2767fn compute_one_file_score(
2768    acc: &mut FileScoreAccumulator,
2769    ctx: &FileScoreLoopCtx<'_>,
2770    node: &fallow_graph::graph::ModuleNode,
2771    path: &std::path::Path,
2772) -> FileHealthScore {
2773    let fan_in = ctx
2774        .graph
2775        .reverse_deps
2776        .get(node.file_id.0 as usize)
2777        .map_or(0, Vec::len);
2778    let fan_out = node.edge_range.len();
2779
2780    let (total_cyclomatic, total_cognitive, function_count, lines) = ctx
2781        .module_by_id
2782        .get(&node.file_id)
2783        .map_or((0, 0, 0, 0), |module| aggregate_complexity(module));
2784
2785    let value_exports = node.exports.iter().filter(|e| !e.is_type_only).count();
2786    let path_owned = path.to_path_buf();
2787    acc.value_export_counts
2788        .insert(path_owned.clone(), value_exports);
2789    record_unused_file_export_names(
2790        path_owned.as_path(),
2791        &node.exports,
2792        ctx.unused_files,
2793        &mut acc.unused_export_names,
2794    );
2795
2796    let (dead_code_ratio_rounded, complexity_density_rounded, maintainability_index_rounded) =
2797        compute_file_score_metrics(node, &path_owned, ctx, total_cyclomatic, lines, fan_out);
2798
2799    let relative = path_owned.strip_prefix(ctx.root).unwrap_or(&path_owned);
2800    let suppressions = ctx
2801        .module_by_id
2802        .get(&node.file_id)
2803        .map_or(&[][..], |module| module.suppressions.as_slice());
2804    let ceilings = CrapCeilingLookup::new(ctx.crap_thresholds, relative, suppressions);
2805    let crap = compute_file_score_crap(node, ctx, &path_owned, &ceilings);
2806    acc.istanbul_matched += crap.istanbul_matched;
2807    acc.istanbul_total += crap.istanbul_total;
2808    acc.istanbul_files_joined += usize::from(crap.coverage_file_joined);
2809    record_per_function_crap(&mut acc.per_function_crap, &path_owned, crap.per_function);
2810    let mut eligible_functions = crap.signals.eligible_functions;
2811    if !eligible_functions.is_empty() {
2812        eligible_functions.sort_by_key(|function| std::cmp::Reverse(function.2));
2813        eligible_functions.truncate(MAX_FUNCTION_EVIDENCE);
2814        acc.crap_target_fns
2815            .insert(path_owned.clone(), eligible_functions);
2816    }
2817
2818    // `crap_effective_threshold` is the file's lowest effective ceiling, on the
2819    // wire only when it differs from the run global. Both sides come from the
2820    // same resolved configuration values, so any difference beyond epsilon is a
2821    // real override, never rounding noise.
2822    let global_crap = ctx.crap_thresholds.resolver.global.crap;
2823    let crap_effective_threshold = crap
2824        .signals
2825        .min_ceiling
2826        .filter(|ceiling| (*ceiling - global_crap).abs() > f64::EPSILON);
2827
2828    FileHealthScore {
2829        path: path_owned,
2830        fan_in,
2831        fan_out,
2832        dead_code_ratio: dead_code_ratio_rounded,
2833        complexity_density: complexity_density_rounded,
2834        maintainability_index: maintainability_index_rounded,
2835        total_cyclomatic,
2836        total_cognitive,
2837        function_count,
2838        lines,
2839        crap_max: crap.max,
2840        crap_above_threshold: crap.signals.above,
2841        crap_exempted: crap.signals.exempted,
2842        crap_suppressed: crap.signals.suppressed,
2843        crap_unsuppressed_max: (crap.signals.suppressed > 0)
2844            .then_some(crap.signals.unsuppressed_max),
2845        crap_unsuppressed_effective_threshold: (crap.signals.suppressed > 0)
2846            .then_some(crap.signals.unsuppressed_min_ceiling.unwrap_or(global_crap)),
2847        crap_effective_threshold,
2848    }
2849}
2850
2851/// Compute the rounded dead-code-ratio, complexity-density, and
2852/// maintainability-index metrics for one file.
2853fn compute_file_score_metrics(
2854    node: &fallow_graph::graph::ModuleNode,
2855    path: &std::path::Path,
2856    ctx: &FileScoreLoopCtx<'_>,
2857    total_cyclomatic: u32,
2858    lines: u32,
2859    fan_out: usize,
2860) -> (f64, f64, f64) {
2861    let dead_code_ratio = compute_dead_code_ratio(
2862        path,
2863        &node.exports,
2864        ctx.unused_files,
2865        ctx.unused_exports_by_path,
2866    );
2867    let complexity_density = compute_complexity_density(total_cyclomatic, lines);
2868
2869    let dead_code_ratio_rounded = (dead_code_ratio * 100.0).round() / 100.0;
2870    let complexity_density_rounded = (complexity_density * 100.0).round() / 100.0;
2871
2872    let maintainability_index = compute_maintainability_index(
2873        complexity_density_rounded,
2874        dead_code_ratio_rounded,
2875        fan_out,
2876        lines,
2877    );
2878    (
2879        dead_code_ratio_rounded,
2880        complexity_density_rounded,
2881        (maintainability_index * 10.0).round() / 10.0,
2882    )
2883}
2884
2885fn build_file_score_output(parts: FileScoreOutputParts<'_>) -> FileScoreOutput {
2886    let total_exports: usize = parts.graph.modules.iter().map(|m| m.exports.len()).sum();
2887    let unused_deps = parts.results.unused_dependencies.len()
2888        + parts.results.unused_dev_dependencies.len()
2889        + parts.results.unused_optional_dependencies.len();
2890    let analysis_snapshot =
2891        build_analysis_counts_snapshot(parts.graph, parts.file_paths, parts.results, unused_deps);
2892    let analysis_counts =
2893        build_file_score_analysis_counts(parts.results, total_exports, unused_deps);
2894    let template_inherit_provenance =
2895        build_template_inherit_provenance(parts.template_inherit, parts.file_paths);
2896
2897    FileScoreOutput {
2898        scores: parts.scores,
2899        coverage: parts.coverage,
2900        circular_files: parts.circular_files,
2901        top_complex_fns: parts.top_complex_fns,
2902        crap_target_fns: parts.crap_target_fns,
2903        entry_points: parts.entry_points,
2904        value_export_counts: parts.value_export_counts,
2905        unused_export_names: parts.unused_export_names,
2906        cycle_members: parts.cycle_members,
2907        direct_callers: parts.direct_callers,
2908        analysis_counts,
2909        prop_drilling_chains: parts.results.prop_drilling_chains.clone(),
2910        render_fan_in: parts.results.render_fan_in.clone(),
2911        analysis_snapshot,
2912        istanbul_matched: parts.istanbul_matched,
2913        istanbul_total: parts.istanbul_total,
2914        istanbul_files_joined: parts.istanbul_files_joined,
2915        istanbul_files_total: parts.istanbul_files_total,
2916        coverage_input_format: parts.coverage_input_format,
2917        per_function_crap: parts.per_function_crap,
2918        template_inherit_provenance,
2919        static_links: parts
2920            .with_static_links
2921            .then(|| crate::change_coupling::StaticLinkIndex::from_graph(parts.graph)),
2922    }
2923}
2924
2925fn build_file_score_analysis_counts(
2926    results: &crate::results::AnalysisResults,
2927    total_exports: usize,
2928    unused_deps: usize,
2929) -> crate::vital_signs::AnalysisCounts {
2930    crate::vital_signs::AnalysisCounts {
2931        total_exports,
2932        dead_files: results.unused_files.len(),
2933        dead_exports: results.unused_exports.len() + results.unused_types.len(),
2934        unused_deps,
2935        circular_deps: results.circular_dependencies.len(),
2936        total_deps: 0usize,
2937    }
2938}
2939
2940fn build_template_inherit_provenance(
2941    template_inherit: rustc_hash::FxHashMap<crate::discover::FileId, TemplateInheritContext>,
2942    file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
2943) -> rustc_hash::FxHashMap<std::path::PathBuf, std::path::PathBuf> {
2944    template_inherit
2945        .into_iter()
2946        .filter_map(|(file_id, ctx)| {
2947            file_paths
2948                .get(&file_id)
2949                .map(|path| ((**path).clone(), ctx.provenance_owner))
2950        })
2951        .collect()
2952}
2953
2954fn record_entry_point(
2955    entry_points: &mut rustc_hash::FxHashSet<std::path::PathBuf>,
2956    node: &fallow_graph::graph::ModuleNode,
2957    path: &std::path::Path,
2958) {
2959    if node.is_entry_point() {
2960        entry_points.insert(path.to_path_buf());
2961    }
2962}
2963
2964fn record_unused_file_export_names(
2965    path: &std::path::Path,
2966    exports: &[fallow_graph::graph::ExportSymbol],
2967    unused_files: &rustc_hash::FxHashSet<&std::path::Path>,
2968    unused_export_names: &mut rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>>,
2969) {
2970    if !unused_files.contains(path) || unused_export_names.contains_key(path) {
2971        return;
2972    }
2973
2974    let names: Vec<String> = exports
2975        .iter()
2976        .filter(|export| !export.is_type_only)
2977        .map(|export| export.name.to_string())
2978        .collect();
2979    if !names.is_empty() {
2980        unused_export_names.insert(path.to_path_buf(), names);
2981    }
2982}
2983
2984struct FileScoreCrap {
2985    max: f64,
2986    signals: CrapThresholdSignals,
2987    per_function: Vec<PerFunctionCrap>,
2988    istanbul_matched: usize,
2989    istanbul_total: usize,
2990    /// The coverage map carried an entry for this file. Distinguishes a map
2991    /// that did not join from code the map genuinely says nothing ran in.
2992    coverage_file_joined: bool,
2993}
2994
2995impl FileScoreCrap {
2996    fn empty() -> Self {
2997        Self {
2998            max: 0.0,
2999            signals: CrapThresholdSignals::default(),
3000            per_function: Vec::new(),
3001            istanbul_matched: 0,
3002            istanbul_total: 0,
3003            coverage_file_joined: false,
3004        }
3005    }
3006
3007    fn estimated(result: EstimatedCrapResult) -> Self {
3008        Self {
3009            max: result.max_crap,
3010            signals: result.signals,
3011            per_function: result.per_function,
3012            istanbul_matched: 0,
3013            istanbul_total: 0,
3014            coverage_file_joined: false,
3015        }
3016    }
3017
3018    fn istanbul(result: IstanbulCrapResult, coverage_file_joined: bool) -> Self {
3019        Self {
3020            max: result.max_crap,
3021            signals: result.signals,
3022            per_function: result.per_function,
3023            istanbul_matched: result.matched,
3024            istanbul_total: result.total,
3025            coverage_file_joined,
3026        }
3027    }
3028}
3029
3030fn compute_file_score_crap(
3031    node: &fallow_graph::graph::ModuleNode,
3032    ctx: &FileScoreLoopCtx<'_>,
3033    path: &std::path::Path,
3034    ceilings: &CrapCeilingLookup<'_>,
3035) -> FileScoreCrap {
3036    let Some(module) = ctx.module_by_id.get(&node.file_id).copied() else {
3037        return FileScoreCrap::empty();
3038    };
3039
3040    let is_coverage_suppressed = crate::suppress::is_file_suppressed(
3041        &module.suppressions,
3042        fallow_types::suppress::IssueKind::CoverageGaps,
3043    );
3044    let is_test_reachable = ctx.test_coverage.covers_file(node.file_id) || is_coverage_suppressed;
3045    let resolution = resolve_crap_coverage(
3046        ctx.template_inherit.get(&node.file_id),
3047        ctx.istanbul_coverage,
3048        path,
3049    );
3050    match resolution {
3051        CrapCoverageResolution::TemplateInherited(inherit_ctx) => {
3052            compute_template_inherited_crap(module, inherit_ctx, ceilings)
3053        }
3054        CrapCoverageResolution::Istanbul { file_coverage } => {
3055            compute_istanbul_file_crap(module, file_coverage, is_test_reachable, ceilings)
3056        }
3057        CrapCoverageResolution::StaticEstimated => {
3058            compute_static_file_crap(module, node, ctx.test_coverage, is_test_reachable, ceilings)
3059        }
3060    }
3061}
3062
3063fn compute_template_inherited_crap(
3064    module: &crate::source::ModuleInfo,
3065    inherit_ctx: &TemplateInheritContext,
3066    ceilings: &CrapCeilingLookup<'_>,
3067) -> FileScoreCrap {
3068    FileScoreCrap::estimated(compute_crap_scores_estimated(
3069        &module.complexity,
3070        &inherit_ctx.test_referenced_exports,
3071        inherit_ctx.is_test_reachable,
3072        fallow_output::CoverageSource::EstimatedComponentInherited,
3073        ceilings,
3074    ))
3075}
3076
3077fn compute_istanbul_file_crap(
3078    module: &crate::source::ModuleInfo,
3079    file_coverage: Option<&IstanbulFileCoverage>,
3080    is_test_reachable: bool,
3081    ceilings: &CrapCeilingLookup<'_>,
3082) -> FileScoreCrap {
3083    FileScoreCrap::istanbul(
3084        compute_crap_scores_istanbul(
3085            &module.complexity,
3086            file_coverage,
3087            is_test_reachable,
3088            ceilings,
3089        ),
3090        file_coverage.is_some(),
3091    )
3092}
3093
3094fn compute_static_file_crap(
3095    module: &crate::source::ModuleInfo,
3096    node: &fallow_graph::graph::ModuleNode,
3097    test_coverage: StaticTestCoverage<'_>,
3098    is_test_reachable: bool,
3099    ceilings: &CrapCeilingLookup<'_>,
3100) -> FileScoreCrap {
3101    let test_refs = build_test_referenced_exports(node.file_id, &node.exports, test_coverage);
3102    FileScoreCrap::estimated(compute_crap_scores_estimated(
3103        &module.complexity,
3104        &test_refs,
3105        is_test_reachable,
3106        fallow_output::CoverageSource::Estimated,
3107        ceilings,
3108    ))
3109}
3110
3111fn record_per_function_crap(
3112    per_function_crap: &mut rustc_hash::FxHashMap<std::path::PathBuf, Vec<PerFunctionCrap>>,
3113    path: &std::path::Path,
3114    per_function: Vec<PerFunctionCrap>,
3115) {
3116    if !per_function.is_empty() {
3117        per_function_crap.insert(path.to_path_buf(), per_function);
3118    }
3119}
3120
3121struct FileScoreCoverageSetup<'a> {
3122    module_by_id: rustc_hash::FxHashMap<crate::discover::FileId, &'a crate::source::ModuleInfo>,
3123    coverage: CoverageGapData,
3124}
3125
3126fn prepare_file_score_coverage_setup<'a>(
3127    modules: &'a [crate::source::ModuleInfo],
3128    file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
3129    results: &crate::results::AnalysisResults,
3130    graph: &fallow_graph::graph::ModuleGraph,
3131    test_coverage: StaticTestCoverage<'_>,
3132    root: &std::path::Path,
3133) -> FileScoreCoverageSetup<'a> {
3134    let module_by_id: rustc_hash::FxHashMap<_, _> =
3135        modules.iter().map(|m| (m.file_id, m)).collect();
3136    let unused_exports: rustc_hash::FxHashSet<(&std::path::Path, String)> = results
3137        .unused_exports
3138        .iter()
3139        .map(|export| {
3140            (
3141                export.export.path.as_path(),
3142                export.export.export_name.clone(),
3143            )
3144        })
3145        .collect();
3146    let coverage = compute_coverage_gaps(
3147        graph,
3148        test_coverage,
3149        file_paths,
3150        &module_by_id,
3151        &unused_exports,
3152        root,
3153    );
3154    FileScoreCoverageSetup {
3155        module_by_id,
3156        coverage,
3157    }
3158}
3159
3160fn collect_circular_files(
3161    results: &crate::results::AnalysisResults,
3162) -> rustc_hash::FxHashSet<std::path::PathBuf> {
3163    results
3164        .circular_dependencies
3165        .iter()
3166        .flat_map(|c| c.cycle.files.iter().cloned())
3167        .collect()
3168}
3169
3170fn collect_top_complex_fns(
3171    modules: &[crate::source::ModuleInfo],
3172    file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
3173) -> rustc_hash::FxHashMap<std::path::PathBuf, Vec<(String, u32, u16)>> {
3174    let mut top_complex_fns = rustc_hash::FxHashMap::default();
3175    for module in modules {
3176        if module.complexity.is_empty() {
3177            continue;
3178        }
3179        let Some(path) = file_paths.get(&module.file_id) else {
3180            continue;
3181        };
3182        // The module-scope unit is excluded: this list feeds the refactoring
3183        // target's evidence copy, which would otherwise render
3184        // "<module> has cognitive complexity 12" next to advice about
3185        // extracting helpers.
3186        let mut funcs: Vec<(String, u32, u16)> = module
3187            .complexity
3188            .iter()
3189            .filter(|f| !fallow_types::extract::is_synthetic_module_unit(&f.name))
3190            .map(|f| (f.name.clone(), f.line, f.cognitive))
3191            .collect();
3192        funcs.sort_by_key(|f| std::cmp::Reverse(f.2));
3193        funcs.truncate(MAX_FUNCTION_EVIDENCE);
3194        if funcs.first().is_some_and(|worst| worst.2 > 0) {
3195            top_complex_fns.insert((*path).clone(), funcs);
3196        }
3197    }
3198    top_complex_fns
3199}
3200
3201fn collect_cycle_members(
3202    results: &crate::results::AnalysisResults,
3203) -> rustc_hash::FxHashMap<std::path::PathBuf, Vec<std::path::PathBuf>> {
3204    let mut cycle_members: rustc_hash::FxHashMap<std::path::PathBuf, Vec<std::path::PathBuf>> =
3205        rustc_hash::FxHashMap::default();
3206    for cycle in &results.circular_dependencies {
3207        for file in &cycle.cycle.files {
3208            let others: Vec<std::path::PathBuf> = cycle
3209                .cycle
3210                .files
3211                .iter()
3212                .filter(|f| *f != file)
3213                .cloned()
3214                .collect();
3215            cycle_members
3216                .entry(file.clone())
3217                .or_default()
3218                .extend(others);
3219        }
3220    }
3221    for members in cycle_members.values_mut() {
3222        members.sort();
3223        members.dedup();
3224    }
3225    cycle_members
3226}
3227
3228fn collect_unused_export_names(
3229    results: &crate::results::AnalysisResults,
3230) -> rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>> {
3231    let mut unused_export_names: rustc_hash::FxHashMap<std::path::PathBuf, Vec<String>> =
3232        rustc_hash::FxHashMap::default();
3233    for exp in &results.unused_exports {
3234        unused_export_names
3235            .entry(exp.export.path.clone())
3236            .or_default()
3237            .push(exp.export.export_name.clone());
3238    }
3239    unused_export_names
3240}
3241
3242fn build_analysis_counts_snapshot(
3243    graph: &fallow_graph::graph::ModuleGraph,
3244    file_paths: &rustc_hash::FxHashMap<crate::discover::FileId, &std::path::PathBuf>,
3245    results: &crate::results::AnalysisResults,
3246    unused_deps: usize,
3247) -> AnalysisCountsSnapshot {
3248    let mut module_export_counts = rustc_hash::FxHashMap::with_capacity_and_hasher(
3249        graph.modules.len(),
3250        rustc_hash::FxBuildHasher,
3251    );
3252    for module in &graph.modules {
3253        if let Some(path) = file_paths.get(&module.file_id) {
3254            module_export_counts.insert((*path).clone(), module.exports.len());
3255        }
3256    }
3257
3258    let mut unused_export_paths =
3259        Vec::with_capacity(results.unused_exports.len() + results.unused_types.len());
3260    unused_export_paths.extend(results.unused_exports.iter().map(|e| e.export.path.clone()));
3261    unused_export_paths.extend(results.unused_types.iter().map(|e| e.export.path.clone()));
3262
3263    let mut unused_dep_package_paths = Vec::with_capacity(unused_deps);
3264    unused_dep_package_paths.extend(
3265        results
3266            .unused_dependencies
3267            .iter()
3268            .map(|d| d.dep.path.clone()),
3269    );
3270    unused_dep_package_paths.extend(
3271        results
3272            .unused_dev_dependencies
3273            .iter()
3274            .map(|d| d.dep.path.clone()),
3275    );
3276    unused_dep_package_paths.extend(
3277        results
3278            .unused_optional_dependencies
3279            .iter()
3280            .map(|d| d.dep.path.clone()),
3281    );
3282
3283    AnalysisCountsSnapshot {
3284        unused_file_paths: results
3285            .unused_files
3286            .iter()
3287            .map(|f| f.file.path.clone())
3288            .collect(),
3289        unused_export_paths,
3290        unused_dep_package_paths,
3291        circular_dep_groups: results
3292            .circular_dependencies
3293            .iter()
3294            .map(|c| c.cycle.files.clone())
3295            .collect(),
3296        module_export_counts,
3297    }
3298}
3299
3300#[cfg(test)]
3301#[path = "scoring_private_member_tests.rs"]
3302mod private_member_tests;
3303
3304#[cfg(test)]
3305#[path = "scoring_tests.rs"]
3306mod tests;