Skip to main content

fallow_engine/health/
scoring.rs

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