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