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