Skip to main content

fallow_api/
audit_complexity.rs

1//! New-only attribution of complexity findings.
2//!
3//! A complexity finding is identified by its path and function name. The
4//! exceeded category and the line are not part of the identity, so a line
5//! shift or a category change keeps the match with the base finding. The
6//! metric values then decide the attribution. A head finding is introduced
7//! when:
8//!
9//! - no base finding matches it,
10//! - it exceeds a metric that the base finding did not exceed, and that metric
11//!   grew (see [`newly_exceeded_metric_grew`]), or
12//! - a metric that it exceeds grew, and its severity tier is higher than the
13//!   tier of the base finding (see [`severity_tier_rose`]).
14//!
15//! A function that the change moved to another file has a new path, so its
16//! identity key has no base finding. Such a finding takes the base finding of
17//! the same function name from another changed file (see
18//! [`classify_complexity_attribution_with_moves`]).
19//!
20//! The exceeded flags and the tier of the base finding come from the base run,
21//! so a threshold override in the same change cannot make an old finding
22//! introduced. Unchanged and decreased metrics stay inherited, also when the
23//! exceeded category changes (#3277).
24//!
25//! A matched finding that is not introduced is worsened when its cyclomatic,
26//! cognitive or CRAP value is higher than in its matched base finding. Growth
27//! of a metric that the base finding already exceeded, in the same tier, is
28//! worsened too. A line count must grow by a minimum (see
29//! [`line_count_grew`]). The `audit.worsened` setting decides how a worsened
30//! finding affects the verdict.
31//!
32//! A CRAP score from estimated coverage does not make a finding introduced.
33//! Under the `new-only` gate, a finding that exceeds only that CRAP score gets
34//! the gate severity `warn` (see [`demote_estimated_crap_gates`]).
35//!
36//! Under every gate, a finding in a test file gets the gate severity `warn`
37//! and the gate exemption `test-file` (see [`exempt_test_file_gates`]). The
38//! attribution of the finding does not change.
39
40use std::path::Path;
41
42use fallow_output::{
43    AuditFindingAttribution, AuditGateExemption, CoverageSource, DEFAULT_COGNITIVE_CRITICAL,
44    DEFAULT_COGNITIVE_HIGH, DEFAULT_CYCLOMATIC_CRITICAL, DEFAULT_CYCLOMATIC_HIGH,
45    ExceededThreshold, FindingSeverity, WorsenedMetric, WorsenedMetricKind,
46    compute_finding_severity,
47};
48use fallow_types::output_dead_code::EffectiveSeverity;
49use rustc_hash::{FxHashMap, FxHashSet};
50
51use crate::audit_keys::{health_finding_key, remap_key_for_renames};
52
53/// Metric values of one base complexity finding.
54#[derive(Debug, Clone, Copy, PartialEq)]
55pub struct ComplexityMetrics {
56    /// 1-based line of the function. Only orders same-named findings.
57    pub line: u32,
58    /// Cyclomatic complexity.
59    pub cyclomatic: u16,
60    /// Cognitive complexity.
61    pub cognitive: u16,
62    /// CRAP score, when coverage data exists.
63    pub crap: Option<f64>,
64    /// Lines of code in the function body.
65    pub line_count: u32,
66    /// The thresholds that the finding exceeded in its own run.
67    pub exceeded: ExceededThreshold,
68    /// The severity tier of the finding in its own run.
69    pub severity: FindingSeverity,
70    /// Whether the CRAP score comes from estimated coverage.
71    pub crap_estimated: bool,
72}
73
74impl ComplexityMetrics {
75    /// The metric values of one finding.
76    #[must_use]
77    pub const fn of(finding: &fallow_output::ComplexityViolation) -> Self {
78        Self {
79            line: finding.line,
80            cyclomatic: finding.cyclomatic,
81            cognitive: finding.cognitive,
82            crap: finding.crap,
83            line_count: finding.line_count,
84            exceeded: finding.exceeded,
85            severity: finding.severity,
86            crap_estimated: crap_is_estimated(finding),
87        }
88    }
89
90    /// The metric values that a review comment shows for an inherited
91    /// finding.
92    const fn base_metrics(&self) -> fallow_output::AuditBaseMetrics {
93        fallow_output::AuditBaseMetrics {
94            cyclomatic: self.cyclomatic,
95            cognitive: self.cognitive,
96            crap: self.crap,
97            line_count: self.line_count,
98        }
99    }
100
101    /// Whether both findings have the same complexity values. The line and
102    /// the line count are not compared.
103    fn same_values(&self, other: &Self) -> bool {
104        self.cyclomatic == other.cyclomatic
105            && self.cognitive == other.cognitive
106            && self.crap.map(f64::to_bits) == other.crap.map(f64::to_bits)
107    }
108
109    /// Whether both findings have the same complexity values and the same
110    /// line count.
111    fn same_values_and_lines(&self, other: &Self) -> bool {
112        self.same_values(other) && self.line_count == other.line_count
113    }
114
115    /// Whether both findings have the same cyclomatic and cognitive values.
116    /// The CRAP score is not compared, because it also changes when only the
117    /// coverage input changes (#3815).
118    const fn same_structure(&self, other: &Self) -> bool {
119        self.cyclomatic == other.cyclomatic && self.cognitive == other.cognitive
120    }
121
122    /// Whether both findings have the same cyclomatic and cognitive values and
123    /// the same line count.
124    const fn same_structure_and_lines(&self, other: &Self) -> bool {
125        self.same_structure(other) && self.line_count == other.line_count
126    }
127}
128
129/// Attribution of one head complexity finding against the base findings.
130#[derive(Debug, Clone, PartialEq, Default)]
131pub struct ComplexityClass {
132    /// `true` when no base finding matches, when a newly exceeded metric
133    /// grew, or when growth moved the finding to a higher severity tier.
134    pub introduced: bool,
135    /// The measured metrics that are higher than in the matched base finding.
136    /// Empty when no base finding matches or when no metric grew.
137    pub worsened_metrics: Vec<WorsenedMetric>,
138    /// `true` when a metric that the finding exceeds grew. Before this rule,
139    /// that growth made the finding introduced, so `audit.worsened: off`
140    /// keeps it worsened (see [`Self::clear_worsened_for_off`]).
141    pub exceeded_metric_grew: bool,
142    /// The metric values of the matched base finding. `None` when no base
143    /// finding matches.
144    pub base: Option<fallow_output::AuditBaseMetrics>,
145}
146
147impl ComplexityClass {
148    /// `true` when a base finding matches, the finding is not introduced, and
149    /// a measured metric grew.
150    #[must_use]
151    pub fn is_worsened(&self) -> bool {
152        !self.introduced && !self.worsened_metrics.is_empty()
153    }
154
155    /// The audit-mode class of the finding.
156    #[must_use]
157    pub fn attribution(&self) -> AuditFindingAttribution {
158        if self.introduced {
159            AuditFindingAttribution::Introduced
160        } else if self.worsened_metrics.is_empty() {
161            AuditFindingAttribution::Inherited
162        } else {
163            AuditFindingAttribution::Worsened
164        }
165    }
166
167    /// Clear the grown metrics for `audit.worsened: off`. Growth only in
168    /// metrics that the finding does not exceed then stays inherited. Growth
169    /// of an exceeded metric stays worsened, so it gives at least `warn` and
170    /// does not disappear from the report.
171    pub fn clear_worsened_for_off(&mut self) {
172        if !self.introduced && !self.exceeded_metric_grew {
173            self.worsened_metrics.clear();
174        }
175    }
176
177    fn of_match(
178        head: &fallow_output::ComplexityViolation,
179        base: Option<&ComplexityMetrics>,
180    ) -> Self {
181        base.map_or(
182            Self {
183                introduced: true,
184                worsened_metrics: Vec::new(),
185                exceeded_metric_grew: false,
186                base: None,
187            },
188            |base| {
189                let exceeded_metric_grew = exceeded_metric_increased(head, base);
190                Self {
191                    introduced: newly_exceeded_metric_grew(head, base)
192                        || (exceeded_metric_grew && severity_tier_rose(head, base)),
193                    worsened_metrics: grown_metrics(head, base),
194                    exceeded_metric_grew,
195                    base: Some(base.base_metrics()),
196                }
197            },
198        )
199    }
200}
201
202/// The measured metrics of `head` that are higher than in `base`.
203///
204/// The line count must grow by a minimum, see [`line_count_grew`]. CRAP
205/// compares only when both sides have a score, because a score that
206/// only one side has reflects the coverage input, not the code.
207fn grown_metrics(
208    head: &fallow_output::ComplexityViolation,
209    base: &ComplexityMetrics,
210) -> Vec<WorsenedMetric> {
211    let mut grown = Vec::new();
212    let mut push = |metric, base: f64, head: f64| {
213        if head > base {
214            grown.push(WorsenedMetric { metric, base, head });
215        }
216    };
217    push(
218        WorsenedMetricKind::Cyclomatic,
219        f64::from(base.cyclomatic),
220        f64::from(head.cyclomatic),
221    );
222    push(
223        WorsenedMetricKind::Cognitive,
224        f64::from(base.cognitive),
225        f64::from(head.cognitive),
226    );
227    if let (Some(base_crap), Some(head_crap)) = (base.crap, head.crap) {
228        push(WorsenedMetricKind::Crap, base_crap, head_crap);
229    }
230    if line_count_grew(base.line_count, head.line_count) {
231        grown.push(WorsenedMetric {
232            metric: WorsenedMetricKind::LineCount,
233            base: f64::from(base.line_count),
234            head: f64::from(head.line_count),
235        });
236    }
237    grown
238}
239
240/// The smallest line count growth, in lines, that makes a finding worsened.
241const LINE_COUNT_MIN_GROWTH_LINES: u32 = 5;
242
243/// Whether the line count grew by at least [`LINE_COUNT_MIN_GROWTH_LINES`]
244/// lines. The floor is fixed and does not scale with the function size, so
245/// growth in a large function is not hidden.
246///
247/// The line count is the physical span of the function, so comments and blank
248/// lines in the body count. The minimum keeps a comment or a formatter rewrap
249/// from making a finding worsened.
250fn line_count_grew(base: u32, head: u32) -> bool {
251    head.saturating_sub(base) >= LINE_COUNT_MIN_GROWTH_LINES
252}
253
254/// Base complexity findings by identity key (`complexity:<path>:<function>`),
255/// each list sorted by line.
256pub type ComplexityBaseline = FxHashMap<String, Vec<ComplexityMetrics>>;
257
258/// The base complexity findings of a health report, by identity key.
259#[must_use]
260pub fn complexity_baseline(
261    report: &fallow_output::HealthReport,
262    root: &Path,
263) -> ComplexityBaseline {
264    let mut baseline = ComplexityBaseline::default();
265    for finding in &report.findings {
266        baseline
267            .entry(health_finding_key(finding, root))
268            .or_default()
269            .push(ComplexityMetrics::of(finding));
270    }
271    sort_by_line(&mut baseline);
272    baseline
273}
274
275/// The identity keys of a complexity baseline.
276#[must_use]
277pub fn complexity_baseline_keys(baseline: &ComplexityBaseline) -> FxHashSet<String> {
278    baseline.keys().cloned().collect()
279}
280
281/// Relocate the base findings of renamed files onto their head paths.
282///
283/// `renames` maps base-relative old paths to head-relative new paths, as in
284/// [`crate::audit_keys::remap_keys_for_renames`]. When two keys merge, their findings join
285/// one list, sorted by line.
286#[must_use]
287#[expect(
288    clippy::implicit_hasher,
289    reason = "fallow standardizes on FxHashMap across audit attribution keys"
290)]
291pub fn remap_complexity_baseline_for_renames(
292    baseline: ComplexityBaseline,
293    renames: &FxHashMap<String, String>,
294) -> ComplexityBaseline {
295    let mut remapped = ComplexityBaseline::default();
296    for (key, findings) in baseline {
297        remapped
298            .entry(remap_key_for_renames(&key, renames))
299            .or_default()
300            .extend(findings);
301    }
302    sort_by_line(&mut remapped);
303    remapped
304}
305
306fn sort_by_line(baseline: &mut ComplexityBaseline) {
307    for findings in baseline.values_mut() {
308        findings.sort_by_key(|metrics| metrics.line);
309    }
310}
311
312/// Whether `head` is worse than `base` in a metric that `head` exceeds.
313///
314/// CRAP counts only when both sides have a measured score (see
315/// [`measured_crap_grew`]).
316fn exceeded_metric_increased(
317    head: &fallow_output::ComplexityViolation,
318    base: &ComplexityMetrics,
319) -> bool {
320    let exceeded = head.exceeded;
321    (exceeded.includes_cyclomatic() && head.cyclomatic > base.cyclomatic)
322        || (exceeded.includes_cognitive() && head.cognitive > base.cognitive)
323        || (exceeded.includes_crap() && measured_crap_grew(head, base))
324        || (exceeded.is_file_lines() && line_count_grew(base.line_count, head.line_count))
325}
326
327/// Whether `head` exceeds a metric that `base` did not exceed in its own run,
328/// and that metric grew. A metric that crosses its limit only because a
329/// threshold changed does not grow, so it stays inherited.
330fn newly_exceeded_metric_grew(
331    head: &fallow_output::ComplexityViolation,
332    base: &ComplexityMetrics,
333) -> bool {
334    let (now, before) = (head.exceeded, base.exceeded);
335    (now.includes_cyclomatic()
336        && !before.includes_cyclomatic()
337        && head.cyclomatic > base.cyclomatic)
338        || (now.includes_cognitive()
339            && !before.includes_cognitive()
340            && head.cognitive > base.cognitive)
341        || (now.includes_crap() && !before.includes_crap() && measured_crap_grew(head, base))
342}
343
344/// Whether both sides have a CRAP score from measured coverage and the head
345/// score is higher. A score that only one side has, or a score from estimated
346/// coverage, reflects the coverage input, not the code.
347fn measured_crap_grew(head: &fallow_output::ComplexityViolation, base: &ComplexityMetrics) -> bool {
348    crap_is_comparable(head, base)
349        && matches!((head.crap, base.crap), (Some(head), Some(base)) if head > base)
350}
351
352fn crap_is_comparable(head: &fallow_output::ComplexityViolation, base: &ComplexityMetrics) -> bool {
353    head.crap.is_some() && base.crap.is_some() && !crap_is_estimated(head) && !base.crap_estimated
354}
355
356/// Whether the severity tier of `head` is higher than the tier of `base`.
357///
358/// The tiers use fixed limits, not the configured thresholds. The CRAP score
359/// takes part only when both sides have a measured score; else both tiers come
360/// from cyclomatic and cognitive complexity only.
361fn severity_tier_rose(head: &fallow_output::ComplexityViolation, base: &ComplexityMetrics) -> bool {
362    if crap_is_comparable(head, base) {
363        return head.severity > base.severity;
364    }
365    complexity_tier(head.cognitive, head.cyclomatic)
366        > complexity_tier(base.cognitive, base.cyclomatic)
367}
368
369fn complexity_tier(cognitive: u16, cyclomatic: u16) -> FindingSeverity {
370    compute_finding_severity(
371        cognitive,
372        cyclomatic,
373        None,
374        DEFAULT_COGNITIVE_HIGH,
375        DEFAULT_COGNITIVE_CRITICAL,
376        DEFAULT_CYCLOMATIC_HIGH,
377        DEFAULT_CYCLOMATIC_CRITICAL,
378    )
379}
380
381/// Whether the CRAP score of the finding comes from estimated coverage, not
382/// from a measured coverage map (`--coverage` or runtime coverage).
383#[must_use]
384pub const fn crap_is_estimated(finding: &fallow_output::ComplexityViolation) -> bool {
385    matches!(
386        finding.coverage_source,
387        Some(CoverageSource::Estimated | CoverageSource::EstimatedComponentInherited)
388    )
389}
390
391/// Whether CRAP from estimated coverage is the only threshold that the
392/// finding exceeds.
393#[must_use]
394pub const fn exceeds_only_estimated_crap(finding: &fallow_output::ComplexityViolation) -> bool {
395    matches!(finding.exceeded, ExceededThreshold::Crap) && crap_is_estimated(finding)
396}
397
398/// Give the gate severity `warn` to each finding that exceeds only CRAP from
399/// estimated coverage, for the `new-only` gate.
400///
401/// The estimate comes from static test reachability, so it does not measure
402/// the change. The finding stays in the report, and the verdict reads `warn`
403/// for it. A finding that also exceeds cyclomatic or cognitive complexity
404/// keeps its gate severity. Measured coverage keeps the gate severity too.
405pub fn demote_estimated_crap_gates(findings: &mut [fallow_output::HealthFinding]) {
406    for finding in findings {
407        if exceeds_only_estimated_crap(finding)
408            && finding.effective_severity == Some(EffectiveSeverity::Error)
409        {
410            finding.violation.effective_severity = Some(EffectiveSeverity::Warn);
411        }
412    }
413}
414
415/// Give the gate severity `warn` to each finding in a test file, and mark it
416/// with [`AuditGateExemption::TestFile`].
417///
418/// The shared test-path classifier ([`fallow_engine::test_paths::is_test_path`])
419/// decides what a test file is: specs, test directories, end-to-end suites,
420/// mocks and fixtures. The finding stays in the report. `fallow health` does
421/// not call this, so it keeps the rule severity there.
422pub fn exempt_test_file_gates(findings: &mut [fallow_output::HealthFinding], root: &Path) {
423    for finding in findings {
424        let relative = finding.path.strip_prefix(root).unwrap_or(&finding.path);
425        if fallow_engine::test_paths::is_test_path(root, relative) {
426            finding.violation.effective_severity = Some(EffectiveSeverity::Warn);
427            finding.gate_exemption = Some(AuditGateExemption::TestFile);
428        }
429    }
430}
431
432/// Classify each head complexity finding as introduced (`true`) or inherited
433/// (`false`), in report order. See [`classify_complexity_attribution`].
434#[must_use]
435pub fn classify_complexity_findings(
436    findings: &[fallow_output::HealthFinding],
437    root: &Path,
438    base: &ComplexityBaseline,
439) -> Vec<bool> {
440    classify_complexity_attribution(findings, root, base)
441        .into_iter()
442        .map(|class| class.introduced)
443        .collect()
444}
445
446/// Classify each head complexity finding against one base, in report order.
447///
448/// Head and base findings match by identity key. When one key holds several
449/// findings on one side (same-named class methods or anonymous functions in
450/// one file), the match is ambiguous. This conservative rule then applies, per
451/// key:
452///
453/// 1. Each head finding, in line order, takes an unmatched base finding with
454///    the same complexity values and the same line count.
455/// 2. Each remaining head finding, in line order, takes an unmatched base
456///    finding with the same complexity values. Rules 1 and 2 keep unchanged
457///    findings inherited when a same-named finding is added, removed or
458///    edited. Rule 1 runs for all head findings first, so an earlier head
459///    finding cannot take the exact match of a later one.
460/// 3. Each remaining head finding, in line order, takes an unmatched base
461///    finding with the same cyclomatic and cognitive values and the same line
462///    count, and then one with the same cyclomatic and cognitive values. The
463///    CRAP score is not compared in this rule, because a change of the
464///    coverage input changes the CRAP score of an unchanged function (#3815).
465///    The pair still compares the CRAP score, so CRAP growth stays visible.
466/// 4. The remaining head findings, in line order, take the remaining base
467///    findings, in line order. Each pair compares the exceeded metrics.
468/// 5. A head finding without a base finding is introduced.
469///
470/// Every base finding matches at most one head finding, so a new same-named
471/// finding cannot hide behind an existing one. The rule does not identify
472/// functions beyond path and name (see #2010). Two same-named findings that
473/// swap their metric values in one change stay inherited.
474///
475/// Each matched pair also lists the measured metrics that grew, so an
476/// inherited finding that got worse is visible.
477#[must_use]
478pub fn classify_complexity_attribution(
479    findings: &[fallow_output::HealthFinding],
480    root: &Path,
481    base: &ComplexityBaseline,
482) -> Vec<ComplexityClass> {
483    classify_with_moves(findings, root, base, None)
484}
485
486/// Classify each head complexity finding against one base, as
487/// [`classify_complexity_attribution`] does, and then match the functions
488/// that the change moved to another file.
489///
490/// A head finding without a base finding takes a base finding of the same
491/// function name that no head finding took, from another file of
492/// `changed_paths`. Without this step, a refactor that splits a file reports
493/// each moved function as introduced, because the path is part of the
494/// identity key and git reports no rename for a split.
495///
496/// The candidates of one function name match by these rules, in path and line
497/// order:
498///
499/// 1. The four value rules of [`classify_complexity_attribution`] run first,
500///    so an unchanged function finds its own base finding.
501/// 2. When one head finding remains, and one base finding of a deleted file
502///    remains, they pair, and the pair compares the metrics. A moved function
503///    that grew is worsened.
504/// 3. The other remaining head findings are introduced. With more candidates
505///    on either side, the name does not tell which function is which.
506///
507/// Rule 2 needs a deleted file, because the function of a deleted file is
508/// gone. In a file that still exists, a base finding without a head finding
509/// can be a function that the change made simpler. A new function of the
510/// same name in another file must not take that base finding, so only equal
511/// values match there.
512///
513/// A placeholder name (`<anonymous>`, `<arrow>`) identifies no function, so
514/// such a finding matches only a base finding with the same cyclomatic and
515/// cognitive values and the same line count.
516///
517/// A base finding outside `changed_paths` is no candidate. The head report
518/// holds only the changed files, so a function in an unchanged file still
519/// exists and a new function of the same name is new.
520#[must_use]
521pub fn classify_complexity_attribution_with_moves(
522    findings: &[fallow_output::HealthFinding],
523    root: &Path,
524    base: &ComplexityBaseline,
525    changed_paths: &ChangedPaths,
526) -> Vec<ComplexityClass> {
527    classify_with_moves(findings, root, base, Some(changed_paths))
528}
529
530/// The files of a change, as root-relative paths in the form of the identity
531/// keys.
532#[derive(Debug, Clone, Default)]
533pub struct ChangedPaths {
534    /// Each file that the change touched, added or deleted.
535    pub changed: FxHashSet<String>,
536    /// The files of `changed` that do not exist on the head.
537    pub deleted: FxHashSet<String>,
538}
539
540/// The four value rules that pair findings of one identity, most exact first.
541const VALUE_RULES: [fn(&ComplexityMetrics, &ComplexityMetrics) -> bool; 4] = [
542    ComplexityMetrics::same_values_and_lines,
543    ComplexityMetrics::same_values,
544    ComplexityMetrics::same_structure_and_lines,
545    ComplexityMetrics::same_structure,
546];
547
548/// The value rules for a placeholder function name. Both compare the line
549/// count, because the name identifies no function.
550const PLACEHOLDER_RULES: [fn(&ComplexityMetrics, &ComplexityMetrics) -> bool; 2] = [
551    ComplexityMetrics::same_values_and_lines,
552    ComplexityMetrics::same_structure_and_lines,
553];
554
555fn classify_with_moves(
556    findings: &[fallow_output::HealthFinding],
557    root: &Path,
558    base: &ComplexityBaseline,
559    changed_paths: Option<&ChangedPaths>,
560) -> Vec<ComplexityClass> {
561    let mut groups: FxHashMap<String, Vec<usize>> = FxHashMap::default();
562    for (index, finding) in findings.iter().enumerate() {
563        groups
564            .entry(health_finding_key(finding, root))
565            .or_default()
566            .push(index);
567    }
568    let mut matches: Vec<Option<&ComplexityMetrics>> = vec![None; findings.len()];
569    let mut unused_bases: FxHashMap<&str, Vec<&ComplexityMetrics>> = FxHashMap::default();
570    for (key, mut heads) in groups {
571        let Some((base_key, bases)) = base.get_key_value(&key) else {
572            continue;
573        };
574        heads.sort_by_key(|&index| (findings[index].line, findings[index].col));
575        let mut unmatched_bases: Vec<Option<&ComplexityMetrics>> = bases.iter().map(Some).collect();
576        match_by_rules(
577            findings,
578            &heads,
579            &mut unmatched_bases,
580            &mut matches,
581            &VALUE_RULES,
582        );
583        let mut remaining_bases = unmatched_bases.into_iter().flatten();
584        for &index in &heads {
585            if matches[index].is_none() {
586                matches[index] = remaining_bases.next();
587            }
588        }
589        unused_bases.insert(base_key.as_str(), remaining_bases.collect());
590    }
591    if let Some(changed_paths) = changed_paths {
592        match_moved_functions(findings, base, changed_paths, &unused_bases, &mut matches);
593    }
594    findings
595        .iter()
596        .zip(matches)
597        .map(|(finding, base)| ComplexityClass::of_match(finding, base))
598        .collect()
599}
600
601/// Give each unmatched head finding of `heads` an unmatched base finding that
602/// a rule of `rules` accepts. Each rule runs for all head findings before the
603/// next rule, so an earlier head finding cannot take the exact match of a
604/// later one.
605fn match_by_rules<'a>(
606    findings: &[fallow_output::HealthFinding],
607    heads: &[usize],
608    unmatched_bases: &mut [Option<&'a ComplexityMetrics>],
609    matches: &mut [Option<&'a ComplexityMetrics>],
610    rules: &[fn(&ComplexityMetrics, &ComplexityMetrics) -> bool],
611) {
612    for rule in rules {
613        for &index in heads {
614            if matches[index].is_some() {
615                continue;
616            }
617            let head = ComplexityMetrics::of(&findings[index]);
618            if let Some(slot) = unmatched_bases
619                .iter_mut()
620                .find(|slot| slot.is_some_and(|base| rule(base, &head)))
621            {
622                matches[index] = slot.take();
623            }
624        }
625    }
626}
627
628/// Match the head findings that have no base finding with the base findings
629/// of the same function name in another changed file. See
630/// [`classify_complexity_attribution_with_moves`].
631///
632/// `unused_bases` holds, for each base key that the head also has, the base
633/// findings that no head finding of that key took. A base key that the head
634/// does not have keeps all its findings.
635fn match_moved_functions<'a>(
636    findings: &[fallow_output::HealthFinding],
637    base: &'a ComplexityBaseline,
638    changed_paths: &ChangedPaths,
639    unused_bases: &FxHashMap<&str, Vec<&'a ComplexityMetrics>>,
640    matches: &mut [Option<&'a ComplexityMetrics>],
641) {
642    let mut heads_by_name: FxHashMap<&str, Vec<usize>> = FxHashMap::default();
643    for (index, finding) in findings.iter().enumerate() {
644        if matches[index].is_none() {
645            heads_by_name
646                .entry(finding.name.as_str())
647                .or_default()
648                .push(index);
649        }
650    }
651    if heads_by_name.is_empty() {
652        return;
653    }
654    let mut bases_by_name: FxHashMap<&str, Vec<(&str, &ComplexityMetrics)>> = FxHashMap::default();
655    for (key, bases) in base {
656        let Some((path, name)) = changed_path_and_name(key, &changed_paths.changed) else {
657            continue;
658        };
659        if !heads_by_name.contains_key(name) {
660            continue;
661        }
662        let candidates = bases_by_name.entry(name).or_default();
663        match unused_bases.get(key.as_str()) {
664            Some(unused) => candidates.extend(unused.iter().map(|metrics| (path, *metrics))),
665            None => candidates.extend(bases.iter().map(|metrics| (path, metrics))),
666        }
667    }
668    for (name, mut heads) in heads_by_name {
669        let Some(mut bases) = bases_by_name.remove(name) else {
670            continue;
671        };
672        heads.sort_by(|&left, &right| {
673            let (left, right) = (&findings[left], &findings[right]);
674            (&left.path, left.line, left.col).cmp(&(&right.path, right.line, right.col))
675        });
676        bases.sort_by_key(|(path, metrics)| (*path, metrics.line));
677        let mut unmatched_bases: Vec<Option<&ComplexityMetrics>> =
678            bases.iter().map(|(_, metrics)| Some(*metrics)).collect();
679        let placeholder = name.starts_with('<');
680        let rules: &[fn(&ComplexityMetrics, &ComplexityMetrics) -> bool] = if placeholder {
681            &PLACEHOLDER_RULES
682        } else {
683            &VALUE_RULES
684        };
685        match_by_rules(findings, &heads, &mut unmatched_bases, matches, rules);
686        if placeholder {
687            continue;
688        }
689        let mut remaining_heads = heads.iter().filter(|&&index| matches[index].is_none());
690        let mut remaining_bases = unmatched_bases
691            .into_iter()
692            .zip(&bases)
693            .filter(|(_, (path, _))| changed_paths.deleted.contains(*path))
694            .filter_map(|(metrics, _)| metrics);
695        if let (Some(&head), None, Some(base), None) = (
696            remaining_heads.next(),
697            remaining_heads.next(),
698            remaining_bases.next(),
699            remaining_bases.next(),
700        ) {
701            matches[head] = Some(base);
702        }
703    }
704}
705
706/// Split a base identity key (`complexity:<path>:<function>`) into its path
707/// and its function name, when the path is in `changed_paths`. A function
708/// name can contain `:`, so each `:` is tried as the separator.
709fn changed_path_and_name<'a>(
710    key: &'a str,
711    changed_paths: &FxHashSet<String>,
712) -> Option<(&'a str, &'a str)> {
713    let rest = key.strip_prefix("complexity:")?;
714    rest.match_indices(':').find_map(|(at, _)| {
715        let (path, name) = (&rest[..at], &rest[at + 1..]);
716        changed_paths.contains(path).then_some((path, name))
717    })
718}
719
720/// Classify each head complexity finding against several bases, in report
721/// order. A finding is introduced only when it is introduced against every
722/// base, so a finding that one base already has is inherited.
723#[must_use]
724pub fn classify_complexity_findings_against_all<'a>(
725    findings: &[fallow_output::HealthFinding],
726    root: &Path,
727    bases: impl IntoIterator<Item = &'a ComplexityBaseline>,
728) -> Vec<bool> {
729    classify_complexity_attribution_against_all(findings, root, bases)
730        .into_iter()
731        .map(|class| class.introduced)
732        .collect()
733}
734
735/// Classify each head complexity finding against several bases, in report
736/// order.
737///
738/// A finding is introduced only when it is introduced against every base. A
739/// finding that is not introduced takes the smallest list of grown metrics of
740/// the bases that it is not introduced against, so a finding that one base
741/// already has with the same values is inherited, not worsened. An introduced
742/// finding keeps the grown metrics of the first base that matches it.
743#[must_use]
744pub fn classify_complexity_attribution_against_all<'a>(
745    findings: &[fallow_output::HealthFinding],
746    root: &Path,
747    bases: impl IntoIterator<Item = &'a ComplexityBaseline>,
748) -> Vec<ComplexityClass> {
749    classify_against_all(findings, root, bases, None)
750}
751
752/// Classify each head complexity finding against several bases, as
753/// [`classify_complexity_attribution_against_all`] does, and match the
754/// functions that the change moved to another file against each base (see
755/// [`classify_complexity_attribution_with_moves`]).
756#[must_use]
757pub fn classify_complexity_attribution_against_all_with_moves<'a>(
758    findings: &[fallow_output::HealthFinding],
759    root: &Path,
760    bases: impl IntoIterator<Item = &'a ComplexityBaseline>,
761    changed_paths: &ChangedPaths,
762) -> Vec<ComplexityClass> {
763    classify_against_all(findings, root, bases, Some(changed_paths))
764}
765
766fn classify_against_all<'a>(
767    findings: &[fallow_output::HealthFinding],
768    root: &Path,
769    bases: impl IntoIterator<Item = &'a ComplexityBaseline>,
770    changed_paths: Option<&ChangedPaths>,
771) -> Vec<ComplexityClass> {
772    let per_base: Vec<Vec<ComplexityClass>> = bases
773        .into_iter()
774        .map(|base| classify_with_moves(findings, root, base, changed_paths))
775        .collect();
776    (0..findings.len())
777        .map(|index| {
778            let classes = per_base.iter().map(|classes| &classes[index]);
779            let inherited = classes
780                .clone()
781                .filter(|class| !class.introduced)
782                .min_by_key(|class| class.worsened_metrics.len());
783            inherited.cloned().unwrap_or_else(|| ComplexityClass {
784                introduced: true,
785                exceeded_metric_grew: false,
786                base: None,
787                worsened_metrics: classes
788                    .map(|class| &class.worsened_metrics)
789                    .find(|metrics| !metrics.is_empty())
790                    .cloned()
791                    .unwrap_or_default(),
792            })
793        })
794        .collect()
795}
796
797/// The ledger key of each complexity finding, in report order.
798///
799/// A repeated identity key gets an occurrence suffix, so each finding counts
800/// once in the attribution counts. Without the suffix, same-named findings
801/// collapse to one count.
802#[must_use]
803pub fn complexity_ledger_keys(
804    findings: &[fallow_output::HealthFinding],
805    root: &Path,
806) -> Vec<String> {
807    let mut seen: FxHashMap<String, usize> = FxHashMap::default();
808    findings
809        .iter()
810        .map(|finding| {
811            let key = health_finding_key(finding, root);
812            let occurrence = seen.entry(key.clone()).or_default();
813            *occurrence += 1;
814            if *occurrence == 1 {
815                key
816            } else {
817                format!("{key}#{occurrence}")
818            }
819        })
820        .collect()
821}
822
823#[cfg(test)]
824mod tests {
825    use std::path::PathBuf;
826
827    use fallow_output::{
828        ComplexityViolation, ExceededThreshold, FindingSeverity, HealthFinding, HealthReport,
829    };
830
831    use super::*;
832
833    const MAX: u16 = 15;
834
835    fn root() -> PathBuf {
836        PathBuf::from("/project")
837    }
838
839    fn finding(name: &str, line: u32, cyclomatic: u16, cognitive: u16) -> HealthFinding {
840        HealthFinding::from(ComplexityViolation {
841            path: root().join("src/index.js"),
842            name: name.to_string(),
843            line,
844            col: 0,
845            cyclomatic,
846            standard_cyclomatic: None,
847            cognitive,
848            line_count: 30,
849            param_count: 1,
850            react_hook_count: 0,
851            react_jsx_max_depth: 0,
852            react_prop_count: 0,
853            react_hook_profile: None,
854            exceeded: ExceededThreshold::from_bools(cyclomatic > MAX, cognitive > MAX, false),
855            effective_severity: None,
856            severity: FindingSeverity::High,
857            crap: None,
858            mutation: None,
859            coverage_pct: None,
860            coverage_tier: None,
861            coverage_source: None,
862            inherited_from: None,
863            component_rollup: None,
864            contributions: Vec::new(),
865            effective_thresholds: None,
866            threshold_source: None,
867            max_file_lines: None,
868        })
869    }
870
871    fn baseline(findings: Vec<HealthFinding>) -> ComplexityBaseline {
872        complexity_baseline(
873            &HealthReport {
874                findings,
875                ..HealthReport::default()
876            },
877            &root(),
878        )
879    }
880
881    fn classify(base: Vec<HealthFinding>, head: &[HealthFinding]) -> Vec<bool> {
882        classify_complexity_findings(head, &root(), &baseline(base))
883    }
884
885    #[test]
886    fn identity_key_excludes_category_and_line() {
887        let key = health_finding_key(&finding("hotspot", 4, 17, 16), &root());
888        assert_eq!(key, "complexity:src/index.js:hotspot");
889    }
890
891    #[test]
892    fn issue_cases() {
893        // Unchanged.
894        assert_eq!(
895            classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 17, 16)]),
896            [false]
897        );
898        // Increased in the same severity tier: worsened, not introduced.
899        assert_eq!(
900            classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 18, 17)]),
901            [false]
902        );
903        // Decreased, same category.
904        assert_eq!(
905            classify(vec![finding("f", 1, 18, 17)], &[finding("f", 1, 17, 16)]),
906            [false]
907        );
908        // Decreased, category change from both to cyclomatic.
909        assert_eq!(
910            classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 16, 15)]),
911            [false]
912        );
913        // New threshold crossing.
914        assert_eq!(classify(vec![], &[finding("f", 1, 17, 16)]), [true]);
915    }
916
917    #[test]
918    fn only_exceeded_metrics_can_introduce() {
919        // Cognitive grows but stays under the limit: only cyclomatic is
920        // exceeded, and it did not grow.
921        assert_eq!(
922            classify(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]),
923            [false]
924        );
925        // A category change to a newly exceeded metric that grew.
926        assert_eq!(
927            classify(vec![finding("f", 1, 20, 14)], &[finding("f", 1, 19, 16)]),
928            [true]
929        );
930    }
931
932    #[test]
933    fn a_finding_that_any_base_has_is_inherited() {
934        let primary = baseline(vec![]);
935        let merged = baseline(vec![finding("f", 1, 17, 16)]);
936        let head = [finding("f", 1, 17, 16), finding("g", 9, 17, 16)];
937        assert_eq!(
938            classify_complexity_findings_against_all(&head, &root(), [&primary, &merged]),
939            [false, true]
940        );
941        // A finding that moved to a higher tier against every base stays
942        // introduced.
943        assert_eq!(
944            classify_complexity_findings_against_all(
945                &[finding("f", 1, 31, 17)],
946                &root(),
947                [&baseline(vec![finding("f", 1, 17, 16)]), &merged]
948            ),
949            [true]
950        );
951    }
952
953    fn finding_in(path: &str, name: &str, cyclomatic: u16, cognitive: u16) -> HealthFinding {
954        let mut finding = finding(name, 1, cyclomatic, cognitive);
955        finding.violation.path = root().join(path);
956        finding
957    }
958
959    /// Changed paths where `src/old.js`, `src/a.js` and `src/b.js` are the
960    /// deleted files.
961    fn changed(paths: &[&str]) -> ChangedPaths {
962        let changed: FxHashSet<String> = paths.iter().map(|path| (*path).to_string()).collect();
963        let deleted = ["src/old.js", "src/a.js", "src/b.js"]
964            .into_iter()
965            .filter(|path| changed.contains(*path))
966            .map(str::to_string)
967            .collect();
968        ChangedPaths { changed, deleted }
969    }
970
971    fn classify_moves(
972        base: Vec<HealthFinding>,
973        head: &[HealthFinding],
974        changed_paths: &[&str],
975    ) -> Vec<AuditFindingAttribution> {
976        classify_complexity_attribution_with_moves(
977            head,
978            &root(),
979            &baseline(base),
980            &changed(changed_paths),
981        )
982        .iter()
983        .map(ComplexityClass::attribution)
984        .collect()
985    }
986
987    #[test]
988    fn moved_function_compares_with_its_base_finding() {
989        use AuditFindingAttribution::{Inherited, Introduced, Worsened};
990        let base = || vec![finding_in("src/old.js", "f", 17, 16)];
991        let both = ["src/old.js", "src/new.js"];
992
993        assert_eq!(
994            classify_moves(base(), &[finding_in("src/new.js", "f", 17, 16)], &both),
995            [Inherited]
996        );
997        assert_eq!(
998            classify_moves(base(), &[finding_in("src/new.js", "f", 18, 17)], &both),
999            [Worsened]
1000        );
1001        // Without the changed paths, the path is part of the identity.
1002        assert_eq!(
1003            classify(base(), &[finding_in("src/new.js", "f", 17, 16)]),
1004            [true]
1005        );
1006        // The base function is in a file that the change did not touch, so it
1007        // still exists.
1008        assert_eq!(
1009            classify_moves(
1010                base(),
1011                &[finding_in("src/new.js", "f", 17, 16)],
1012                &["src/new.js"]
1013            ),
1014            [Introduced]
1015        );
1016    }
1017
1018    #[test]
1019    fn grown_function_does_not_take_the_base_finding_of_a_kept_file() {
1020        use AuditFindingAttribution::{Inherited, Introduced};
1021        let base = || vec![finding_in("src/kept.js", "f", 17, 16)];
1022        let both = ["src/kept.js", "src/new.js"];
1023        // `src/kept.js` has no head finding: the change made `f` simpler, or
1024        // removed it. A different `f` in a new file is new.
1025        assert_eq!(
1026            classify_moves(base(), &[finding_in("src/new.js", "f", 16, 16)], &both),
1027            [Introduced]
1028        );
1029        // Equal values still match.
1030        assert_eq!(
1031            classify_moves(base(), &[finding_in("src/new.js", "f", 17, 16)], &both),
1032            [Inherited]
1033        );
1034    }
1035
1036    #[test]
1037    fn one_of_two_same_named_functions_moves() {
1038        use AuditFindingAttribution::Inherited;
1039        let mut second = finding_in("src/kept.js", "run", 21, 20);
1040        second.violation.line = 40;
1041        let base = vec![finding_in("src/kept.js", "run", 17, 16), second];
1042        let head = [
1043            finding_in("src/kept.js", "run", 17, 16),
1044            finding_in("src/new.js", "run", 21, 20),
1045        ];
1046        assert_eq!(
1047            classify_moves(base, &head, &["src/kept.js", "src/new.js"]),
1048            [Inherited, Inherited]
1049        );
1050    }
1051
1052    #[test]
1053    fn moved_function_does_not_take_a_base_finding_that_is_in_use() {
1054        use AuditFindingAttribution::{Inherited, Introduced};
1055        let head = [
1056            finding_in("src/old.js", "f", 17, 16),
1057            finding_in("src/new.js", "f", 17, 16),
1058        ];
1059        assert_eq!(
1060            classify_moves(
1061                vec![finding_in("src/old.js", "f", 17, 16)],
1062                &head,
1063                &["src/old.js", "src/new.js"]
1064            ),
1065            [Inherited, Introduced]
1066        );
1067    }
1068
1069    #[test]
1070    fn same_named_moved_functions_pair_by_values_only() {
1071        use AuditFindingAttribution::{Inherited, Introduced};
1072        let base = || {
1073            vec![
1074                finding_in("src/a.js", "run", 17, 16),
1075                finding_in("src/b.js", "run", 21, 20),
1076            ]
1077        };
1078        let paths = ["src/a.js", "src/b.js", "src/c.js", "src/d.js"];
1079        // Each function keeps its values, in the opposite path order.
1080        assert_eq!(
1081            classify_moves(
1082                base(),
1083                &[
1084                    finding_in("src/c.js", "run", 21, 20),
1085                    finding_in("src/d.js", "run", 17, 16),
1086                ],
1087                &paths
1088            ),
1089            [Inherited, Inherited]
1090        );
1091        // Both functions changed: the name does not tell which is which.
1092        assert_eq!(
1093            classify_moves(
1094                base(),
1095                &[
1096                    finding_in("src/c.js", "run", 22, 21),
1097                    finding_in("src/d.js", "run", 18, 17),
1098                ],
1099                &paths
1100            ),
1101            [Introduced, Introduced]
1102        );
1103    }
1104
1105    #[test]
1106    fn moved_placeholder_name_needs_equal_values_and_lines() {
1107        use AuditFindingAttribution::{Inherited, Introduced};
1108        let base = || vec![finding_in("src/old.js", "<arrow>", 17, 16)];
1109        let both = ["src/old.js", "src/new.js"];
1110        assert_eq!(
1111            classify_moves(
1112                base(),
1113                &[finding_in("src/new.js", "<arrow>", 17, 16)],
1114                &both
1115            ),
1116            [Inherited]
1117        );
1118        assert_eq!(
1119            classify_moves(
1120                base(),
1121                &[finding_in("src/new.js", "<arrow>", 18, 17)],
1122                &both
1123            ),
1124            [Introduced]
1125        );
1126    }
1127
1128    #[test]
1129    fn moved_function_name_can_contain_a_colon() {
1130        assert_eq!(
1131            classify_moves(
1132                vec![finding_in("src/old.js", "it: parses", 17, 16)],
1133                &[finding_in("src/new.js", "it: parses", 17, 16)],
1134                &["src/old.js", "src/new.js"]
1135            ),
1136            [AuditFindingAttribution::Inherited]
1137        );
1138    }
1139
1140    #[test]
1141    fn line_shift_keeps_the_match() {
1142        assert_eq!(
1143            classify(vec![finding("f", 1, 17, 16)], &[finding("f", 40, 17, 16)]),
1144            [false]
1145        );
1146    }
1147
1148    fn crap_finding(crap: Option<f64>, source: Option<CoverageSource>) -> HealthFinding {
1149        let mut finding = finding("f", 1, 16, 5);
1150        finding.violation.exceeded = ExceededThreshold::Crap;
1151        finding.violation.crap = crap;
1152        finding.violation.coverage_source = source;
1153        finding.violation.effective_severity = Some(EffectiveSeverity::Error);
1154        finding
1155    }
1156
1157    #[test]
1158    fn crap_without_base_value_is_not_an_increase() {
1159        // A base without a CRAP score ran without that coverage input. The
1160        // code did not grow.
1161        let head = crap_finding(Some(50.0), Some(CoverageSource::Istanbul));
1162        assert_eq!(
1163            classify(vec![crap_finding(None, None)], std::slice::from_ref(&head)),
1164            [false]
1165        );
1166        // Measured CRAP growth in the same tier is worsened.
1167        assert_eq!(
1168            classify(
1169                vec![crap_finding(Some(40.0), Some(CoverageSource::Istanbul))],
1170                std::slice::from_ref(&head)
1171            ),
1172            [false]
1173        );
1174        assert_eq!(
1175            classify(
1176                vec![crap_finding(Some(60.0), Some(CoverageSource::Istanbul))],
1177                &[head]
1178            ),
1179            [false]
1180        );
1181    }
1182
1183    #[test]
1184    fn estimated_crap_growth_is_worsened_not_introduced() {
1185        let estimated = Some(CoverageSource::Estimated);
1186        let classes = attribution(
1187            vec![crap_finding(Some(40.0), estimated)],
1188            &[crap_finding(Some(50.0), estimated)],
1189        );
1190        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1191        assert_eq!(
1192            classes[0].worsened_metrics,
1193            [metric(WorsenedMetricKind::Crap, 40.0, 50.0)]
1194        );
1195        // A grown cognitive value that the base already exceeds is worsened.
1196        let mut base = crap_finding(Some(40.0), estimated);
1197        base.violation.exceeded = ExceededThreshold::CognitiveCrap;
1198        base.violation.cognitive = 20;
1199        let mut head = base.clone();
1200        head.violation.cognitive = 21;
1201        head.violation.crap = Some(50.0);
1202        assert_eq!(classify(vec![base.clone()], &[head.clone()]), [false]);
1203        // A grown cognitive value that reaches the next tier is introduced.
1204        head.violation.cognitive = 25;
1205        assert_eq!(classify(vec![base], &[head]), [true]);
1206    }
1207
1208    #[test]
1209    fn test_file_findings_get_warn_gate_severity_and_the_exemption() {
1210        // The project itself lives below a `tests` directory. Only the path
1211        // below the project root decides.
1212        let project = root().join("tests").join("project");
1213        let at = |relative: &str| {
1214            let mut finding = finding("f", 1, 16, 5);
1215            finding.violation.path = project.join(relative);
1216            finding.violation.effective_severity = Some(EffectiveSeverity::Error);
1217            finding
1218        };
1219        let mut findings = [
1220            at("src/__tests__/app.js"),
1221            at("src/app.spec.ts"),
1222            at("src/app.test.tsx"),
1223            at("src/__mocks__/api.js"),
1224            at("src/app.js"),
1225            at("src/latest.js"),
1226        ];
1227        exempt_test_file_gates(&mut findings, &project);
1228        let marks: Vec<_> = findings
1229            .iter()
1230            .map(|finding| (finding.effective_severity, finding.gate_exemption))
1231            .collect();
1232        let exempt = (
1233            Some(EffectiveSeverity::Warn),
1234            Some(AuditGateExemption::TestFile),
1235        );
1236        let gated = (Some(EffectiveSeverity::Error), None);
1237        assert_eq!(marks, [exempt, exempt, exempt, exempt, gated, gated]);
1238    }
1239
1240    #[test]
1241    fn estimated_crap_only_findings_get_warn_gate_severity() {
1242        let mut both = crap_finding(Some(50.0), Some(CoverageSource::Estimated));
1243        both.violation.exceeded = ExceededThreshold::CognitiveCrap;
1244        let mut warn_rule = crap_finding(Some(50.0), Some(CoverageSource::Estimated));
1245        warn_rule.violation.effective_severity = Some(EffectiveSeverity::Warn);
1246        let mut findings = [
1247            crap_finding(Some(50.0), Some(CoverageSource::Estimated)),
1248            crap_finding(
1249                Some(50.0),
1250                Some(CoverageSource::EstimatedComponentInherited),
1251            ),
1252            crap_finding(Some(50.0), Some(CoverageSource::Istanbul)),
1253            both,
1254            warn_rule,
1255        ];
1256        demote_estimated_crap_gates(&mut findings);
1257        let severities: Vec<_> = findings
1258            .iter()
1259            .map(|finding| finding.effective_severity)
1260            .collect();
1261        assert_eq!(
1262            severities,
1263            [
1264                Some(EffectiveSeverity::Warn),
1265                Some(EffectiveSeverity::Warn),
1266                Some(EffectiveSeverity::Error),
1267                Some(EffectiveSeverity::Error),
1268                Some(EffectiveSeverity::Warn),
1269            ]
1270        );
1271    }
1272
1273    #[test]
1274    fn same_named_findings_match_unchanged_values_first() {
1275        let base = vec![finding("run", 1, 17, 16), finding("run", 30, 21, 20)];
1276        // Unchanged.
1277        assert_eq!(
1278            classify(
1279                base.clone(),
1280                &[finding("run", 1, 17, 16), finding("run", 30, 21, 20)]
1281            ),
1282            [false, false]
1283        );
1284        // The second function moves to the first function's line but keeps its own base finding.
1285        assert_eq!(
1286            classify(base.clone(), &[finding("run", 1, 21, 20)]),
1287            [false]
1288        );
1289        // A new one added before both.
1290        assert_eq!(
1291            classify(
1292                base.clone(),
1293                &[
1294                    finding("run", 1, 30, 30),
1295                    finding("run", 20, 17, 16),
1296                    finding("run", 50, 21, 20)
1297                ]
1298            ),
1299            [true, false, false]
1300        );
1301        // The first one worsened, the second one unchanged.
1302        assert_eq!(
1303            classify(
1304                base.clone(),
1305                &[finding("run", 1, 18, 17), finding("run", 30, 21, 20)]
1306            ),
1307            [false, false]
1308        );
1309        // The first one moved to a higher tier, the second one unchanged.
1310        assert_eq!(
1311            classify(
1312                base,
1313                &[finding("run", 1, 30, 17), finding("run", 30, 21, 20)]
1314            ),
1315            [true, false]
1316        );
1317    }
1318
1319    /// An anonymous finding with a CRAP score from the given coverage source.
1320    fn arrow(
1321        line: u32,
1322        cyclomatic: u16,
1323        cognitive: u16,
1324        crap: Option<f64>,
1325        source: CoverageSource,
1326    ) -> HealthFinding {
1327        let mut finding = finding("<arrow>", line, MAX + 1, MAX + 1);
1328        finding.violation.cyclomatic = cyclomatic;
1329        finding.violation.cognitive = cognitive;
1330        finding.violation.crap = crap;
1331        finding.violation.coverage_source = crap.map(|_| source);
1332        finding.violation.exceeded = ExceededThreshold::from_bools(
1333            cyclomatic > MAX,
1334            cognitive > MAX,
1335            crap.is_some_and(|crap| crap >= 30.0),
1336        );
1337        finding
1338    }
1339
1340    #[test]
1341    fn unchanged_arrow_keeps_its_base_when_only_crap_changes() {
1342        // Issue #3815: the CRAP score of an unchanged arrow went from an
1343        // estimated score to a measured score. Its cyclomatic and cognitive
1344        // values did not change, so it must keep its own base finding, not the
1345        // first remaining base finding in line order.
1346        let estimated = CoverageSource::Estimated;
1347        let measured = CoverageSource::Istanbul;
1348        let base = [
1349            (122, 36, 37, 1332.0),
1350            (284, 26, 28, 702.0),
1351            (352, 9, 6, 90.0),
1352            (560, 7, 6, 56.0),
1353            (637, 30, 42, 930.0),
1354            (732, 13, 5, 182.0),
1355            (872, 13, 12, 182.0),
1356            (889, 6, 2, 42.0),
1357            (945, 5, 3, 30.0),
1358            (972, 16, 4, 272.0),
1359            (1017, 11, 13, 132.0),
1360            (1184, 14, 15, 210.0),
1361            (1202, 12, 5, 156.0),
1362        ]
1363        .into_iter()
1364        .map(|(line, cyclomatic, cognitive, crap)| {
1365            arrow(line, cyclomatic, cognitive, Some(crap), estimated)
1366        })
1367        .collect();
1368        let head = [
1369            arrow(128, 36, 37, Some(36.0), measured),
1370            arrow(294, 27, 29, None, measured),
1371            arrow(663, 30, 42, Some(30.0), measured),
1372        ];
1373        let classes = attribution(base, &head);
1374        assert!(!classes[0].introduced);
1375        assert!(!classes[2].introduced, "{:?}", classes[2]);
1376        assert!(classes[2].worsened_metrics.is_empty());
1377    }
1378
1379    #[test]
1380    fn crap_growth_of_an_unchanged_arrow_still_compares() {
1381        let measured = CoverageSource::Istanbul;
1382        let classes = attribution(
1383            vec![
1384                arrow(10, 9, 6, Some(40.0), measured),
1385                arrow(40, 30, 42, Some(30.0), measured),
1386            ],
1387            &[arrow(40, 30, 42, Some(60.0), measured)],
1388        );
1389        assert_eq!(
1390            classes[0].worsened_metrics,
1391            [metric(WorsenedMetricKind::Crap, 30.0, 60.0)]
1392        );
1393    }
1394
1395    fn with_lines(mut finding: HealthFinding, line_count: u32) -> HealthFinding {
1396        finding.violation.line_count = line_count;
1397        finding
1398    }
1399
1400    fn attribution(base: Vec<HealthFinding>, head: &[HealthFinding]) -> Vec<ComplexityClass> {
1401        classify_complexity_attribution(head, &root(), &baseline(base))
1402    }
1403
1404    fn metric(kind: WorsenedMetricKind, base: f64, head: f64) -> WorsenedMetric {
1405        WorsenedMetric {
1406            metric: kind,
1407            base,
1408            head,
1409        }
1410    }
1411
1412    #[test]
1413    fn grown_line_count_is_worsened_not_introduced() {
1414        let classes = attribution(
1415            vec![with_lines(finding("f", 1, 17, 16), 80)],
1416            &[with_lines(finding("f", 1, 17, 16), 300)],
1417        );
1418        assert!(!classes[0].introduced);
1419        assert!(classes[0].is_worsened());
1420        assert_eq!(
1421            classes[0].worsened_metrics,
1422            [metric(WorsenedMetricKind::LineCount, 80.0, 300.0)]
1423        );
1424        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1425    }
1426
1427    #[test]
1428    fn grown_metric_that_the_finding_does_not_exceed_is_worsened() {
1429        // Only cyclomatic is exceeded; cognitive grows below the limit.
1430        let classes = attribution(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]);
1431        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1432        assert_eq!(
1433            classes[0].worsened_metrics,
1434            [metric(WorsenedMetricKind::Cognitive, 5.0, 9.0)]
1435        );
1436    }
1437
1438    #[test]
1439    fn grown_exceeded_metric_in_the_same_tier_is_worsened() {
1440        // Cyclomatic 100 to 103 stays in the critical tier.
1441        let classes = attribution(vec![finding("f", 1, 100, 16)], &[finding("f", 1, 103, 16)]);
1442        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1443        assert!(classes[0].exceeded_metric_grew);
1444        assert_eq!(
1445            classes[0].worsened_metrics,
1446            [metric(WorsenedMetricKind::Cyclomatic, 100.0, 103.0)]
1447        );
1448        // Growth only in a metric that the finding does not exceed.
1449        let below = attribution(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]);
1450        assert!(!below[0].exceeded_metric_grew);
1451    }
1452
1453    #[test]
1454    fn severity_tier_uses_the_base_values_not_todays_thresholds() {
1455        // The base finding exceeded only cyclomatic. A threshold override in
1456        // the same change lowers the cognitive limit, so the head finding
1457        // exceeds cognitive too, without cognitive growth.
1458        let mut head = finding("f", 1, 18, 10);
1459        head.violation.exceeded = ExceededThreshold::Both;
1460        assert_eq!(
1461            classify(vec![finding("f", 1, 17, 10)], &[head.clone()]),
1462            [false]
1463        );
1464        // Cognitive grew and the base did not exceed it: newly exceeded.
1465        head.violation.cognitive = 11;
1466        assert_eq!(classify(vec![finding("f", 1, 17, 10)], &[head]), [true]);
1467    }
1468
1469    #[test]
1470    fn measured_crap_tier_crossing_is_introduced() {
1471        let istanbul = Some(CoverageSource::Istanbul);
1472        let mut base = crap_finding(Some(40.0), istanbul);
1473        base.violation.severity = FindingSeverity::Moderate;
1474        let mut head = crap_finding(Some(120.0), istanbul);
1475        head.violation.severity = FindingSeverity::Critical;
1476        assert_eq!(classify(vec![base.clone()], &[head.clone()]), [true]);
1477        // The same values from estimated coverage do not cross a tier.
1478        let estimated = Some(CoverageSource::Estimated);
1479        base.violation.coverage_source = estimated;
1480        head.violation.coverage_source = estimated;
1481        assert_eq!(classify(vec![base], &[head]), [false]);
1482    }
1483
1484    #[test]
1485    fn grown_exceeded_metric_is_introduced_with_values() {
1486        let classes = attribution(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 40, 16)]);
1487        assert_eq!(
1488            classes[0].attribution(),
1489            AuditFindingAttribution::Introduced
1490        );
1491        assert_eq!(
1492            classes[0].worsened_metrics,
1493            [metric(WorsenedMetricKind::Cyclomatic, 17.0, 40.0)]
1494        );
1495        assert!(!classes[0].is_worsened());
1496    }
1497
1498    #[test]
1499    fn improved_and_moved_functions_are_inherited() {
1500        let improved = attribution(
1501            vec![with_lines(finding("f", 1, 30, 30), 90)],
1502            &[with_lines(finding("f", 1, 20, 18), 60)],
1503        );
1504        assert_eq!(
1505            improved[0].attribution(),
1506            AuditFindingAttribution::Inherited
1507        );
1508        assert!(improved[0].worsened_metrics.is_empty());
1509        let moved = attribution(vec![finding("f", 1, 17, 16)], &[finding("f", 400, 17, 16)]);
1510        assert_eq!(moved[0].attribution(), AuditFindingAttribution::Inherited);
1511    }
1512
1513    #[test]
1514    fn new_function_is_introduced_without_values() {
1515        let classes = attribution(vec![finding("f", 1, 17, 16)], &[finding("g", 1, 17, 16)]);
1516        assert_eq!(
1517            classes[0].attribution(),
1518            AuditFindingAttribution::Introduced
1519        );
1520        assert!(classes[0].worsened_metrics.is_empty());
1521    }
1522
1523    #[test]
1524    fn crap_compares_only_when_both_sides_have_a_score() {
1525        let mut head = finding("f", 1, 20, 5);
1526        head.violation.crap = Some(50.0);
1527        let classes = attribution(vec![finding("f", 1, 20, 5)], std::slice::from_ref(&head));
1528        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1529        let mut base = finding("f", 1, 20, 5);
1530        base.violation.crap = Some(40.0);
1531        let classes = attribution(vec![base], &[head]);
1532        assert_eq!(
1533            classes[0].worsened_metrics,
1534            [metric(WorsenedMetricKind::Crap, 40.0, 50.0)]
1535        );
1536    }
1537
1538    #[test]
1539    fn same_named_findings_prefer_the_base_with_equal_line_count() {
1540        // Two same-valued findings; the second one grew in lines.
1541        let base = vec![
1542            with_lines(finding("run", 1, 17, 16), 10),
1543            with_lines(finding("run", 30, 17, 16), 40),
1544        ];
1545        let head = [
1546            with_lines(finding("run", 1, 17, 16), 40),
1547            with_lines(finding("run", 50, 17, 16), 25),
1548        ];
1549        let classes = attribution(base, &head);
1550        // The first head finding takes the 40-line base finding; the second one
1551        // takes the 10-line base finding and grew.
1552        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1553        assert_eq!(classes[1].attribution(), AuditFindingAttribution::Worsened);
1554    }
1555
1556    #[test]
1557    fn an_exact_match_of_a_later_head_is_not_taken_by_an_earlier_head() {
1558        // The 10-line function moved up and grew to 30 lines. The 40-line
1559        // function did not change, but it now comes later in line order.
1560        let base = vec![
1561            with_lines(finding("run", 1, 17, 16), 40),
1562            with_lines(finding("run", 50, 17, 16), 10),
1563        ];
1564        let head = [
1565            with_lines(finding("run", 1, 17, 16), 30),
1566            with_lines(finding("run", 20, 17, 16), 40),
1567        ];
1568        let classes = attribution(base, &head);
1569        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1570        assert_eq!(
1571            classes[0].worsened_metrics,
1572            [metric(WorsenedMetricKind::LineCount, 10.0, 30.0)]
1573        );
1574        assert_eq!(classes[1].attribution(), AuditFindingAttribution::Inherited);
1575        assert!(classes[1].worsened_metrics.is_empty());
1576    }
1577
1578    #[test]
1579    fn small_line_growth_is_not_worsened() {
1580        // A comment line or a formatter rewrap adds a few physical lines.
1581        let classes = attribution(
1582            vec![with_lines(finding("f", 1, 17, 16), 80)],
1583            &[with_lines(finding("f", 1, 17, 16), 84)],
1584        );
1585        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1586        assert!(classes[0].worsened_metrics.is_empty());
1587    }
1588
1589    #[test]
1590    fn line_growth_needs_five_lines_at_any_function_size() {
1591        // 4 lines are below the floor, also on a short function.
1592        let short = attribution(
1593            vec![with_lines(finding("f", 1, 17, 16), 20)],
1594            &[with_lines(finding("f", 1, 17, 16), 24)],
1595        );
1596        assert_eq!(short[0].attribution(), AuditFindingAttribution::Inherited);
1597        let grown = attribution(
1598            vec![with_lines(finding("f", 1, 17, 16), 20)],
1599            &[with_lines(finding("f", 1, 17, 16), 25)],
1600        );
1601        assert_eq!(grown[0].attribution(), AuditFindingAttribution::Worsened);
1602        // The floor does not scale: 9 lines on a 300-line function count.
1603        let long = attribution(
1604            vec![with_lines(finding("f", 1, 17, 16), 300)],
1605            &[with_lines(finding("f", 1, 17, 16), 309)],
1606        );
1607        assert_eq!(long[0].attribution(), AuditFindingAttribution::Worsened);
1608    }
1609
1610    #[test]
1611    fn a_base_with_the_same_values_keeps_the_finding_inherited() {
1612        let primary = baseline(vec![with_lines(finding("f", 1, 17, 16), 20)]);
1613        let merged = baseline(vec![with_lines(finding("f", 1, 17, 16), 60)]);
1614        let head = [with_lines(finding("f", 1, 17, 16), 60)];
1615        let classes =
1616            classify_complexity_attribution_against_all(&head, &root(), [&primary, &merged]);
1617        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1618        let classes = classify_complexity_attribution_against_all(&head, &root(), [&primary]);
1619        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1620    }
1621
1622    #[test]
1623    fn rename_moves_the_base_findings() {
1624        let base = baseline(vec![finding("f", 1, 17, 16)]);
1625        let renames =
1626            FxHashMap::from_iter([("src/index.js".to_string(), "src/moved.js".to_string())]);
1627        let remapped = remap_complexity_baseline_for_renames(base, &renames);
1628        assert!(remapped.contains_key("complexity:src/moved.js:f"));
1629        assert!(!remapped.contains_key("complexity:src/index.js:f"));
1630    }
1631
1632    #[test]
1633    fn ledger_keys_count_same_named_findings_separately() {
1634        let keys = complexity_ledger_keys(
1635            &[finding("run", 1, 17, 16), finding("run", 30, 17, 16)],
1636            &root(),
1637        );
1638        assert_eq!(
1639            keys,
1640            [
1641                "complexity:src/index.js:run",
1642                "complexity:src/index.js:run#2"
1643            ]
1644        );
1645    }
1646}