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            override_comment_line: None,
868            max_file_lines: None,
869        })
870    }
871
872    fn baseline(findings: Vec<HealthFinding>) -> ComplexityBaseline {
873        complexity_baseline(
874            &HealthReport {
875                findings,
876                ..HealthReport::default()
877            },
878            &root(),
879        )
880    }
881
882    fn classify(base: Vec<HealthFinding>, head: &[HealthFinding]) -> Vec<bool> {
883        classify_complexity_findings(head, &root(), &baseline(base))
884    }
885
886    #[test]
887    fn identity_key_excludes_category_and_line() {
888        let key = health_finding_key(&finding("hotspot", 4, 17, 16), &root());
889        assert_eq!(key, "complexity:src/index.js:hotspot");
890    }
891
892    #[test]
893    fn issue_cases() {
894        // Unchanged.
895        assert_eq!(
896            classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 17, 16)]),
897            [false]
898        );
899        // Increased in the same severity tier: worsened, not introduced.
900        assert_eq!(
901            classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 18, 17)]),
902            [false]
903        );
904        // Decreased, same category.
905        assert_eq!(
906            classify(vec![finding("f", 1, 18, 17)], &[finding("f", 1, 17, 16)]),
907            [false]
908        );
909        // Decreased, category change from both to cyclomatic.
910        assert_eq!(
911            classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 16, 15)]),
912            [false]
913        );
914        // New threshold crossing.
915        assert_eq!(classify(vec![], &[finding("f", 1, 17, 16)]), [true]);
916    }
917
918    #[test]
919    fn only_exceeded_metrics_can_introduce() {
920        // Cognitive grows but stays under the limit: only cyclomatic is
921        // exceeded, and it did not grow.
922        assert_eq!(
923            classify(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]),
924            [false]
925        );
926        // A category change to a newly exceeded metric that grew.
927        assert_eq!(
928            classify(vec![finding("f", 1, 20, 14)], &[finding("f", 1, 19, 16)]),
929            [true]
930        );
931    }
932
933    #[test]
934    fn a_finding_that_any_base_has_is_inherited() {
935        let primary = baseline(vec![]);
936        let merged = baseline(vec![finding("f", 1, 17, 16)]);
937        let head = [finding("f", 1, 17, 16), finding("g", 9, 17, 16)];
938        assert_eq!(
939            classify_complexity_findings_against_all(&head, &root(), [&primary, &merged]),
940            [false, true]
941        );
942        // A finding that moved to a higher tier against every base stays
943        // introduced.
944        assert_eq!(
945            classify_complexity_findings_against_all(
946                &[finding("f", 1, 31, 17)],
947                &root(),
948                [&baseline(vec![finding("f", 1, 17, 16)]), &merged]
949            ),
950            [true]
951        );
952    }
953
954    fn finding_in(path: &str, name: &str, cyclomatic: u16, cognitive: u16) -> HealthFinding {
955        let mut finding = finding(name, 1, cyclomatic, cognitive);
956        finding.violation.path = root().join(path);
957        finding
958    }
959
960    /// Changed paths where `src/old.js`, `src/a.js` and `src/b.js` are the
961    /// deleted files.
962    fn changed(paths: &[&str]) -> ChangedPaths {
963        let changed: FxHashSet<String> = paths.iter().map(|path| (*path).to_string()).collect();
964        let deleted = ["src/old.js", "src/a.js", "src/b.js"]
965            .into_iter()
966            .filter(|path| changed.contains(*path))
967            .map(str::to_string)
968            .collect();
969        ChangedPaths { changed, deleted }
970    }
971
972    fn classify_moves(
973        base: Vec<HealthFinding>,
974        head: &[HealthFinding],
975        changed_paths: &[&str],
976    ) -> Vec<AuditFindingAttribution> {
977        classify_complexity_attribution_with_moves(
978            head,
979            &root(),
980            &baseline(base),
981            &changed(changed_paths),
982        )
983        .iter()
984        .map(ComplexityClass::attribution)
985        .collect()
986    }
987
988    #[test]
989    fn moved_function_compares_with_its_base_finding() {
990        use AuditFindingAttribution::{Inherited, Introduced, Worsened};
991        let base = || vec![finding_in("src/old.js", "f", 17, 16)];
992        let both = ["src/old.js", "src/new.js"];
993
994        assert_eq!(
995            classify_moves(base(), &[finding_in("src/new.js", "f", 17, 16)], &both),
996            [Inherited]
997        );
998        assert_eq!(
999            classify_moves(base(), &[finding_in("src/new.js", "f", 18, 17)], &both),
1000            [Worsened]
1001        );
1002        // Without the changed paths, the path is part of the identity.
1003        assert_eq!(
1004            classify(base(), &[finding_in("src/new.js", "f", 17, 16)]),
1005            [true]
1006        );
1007        // The base function is in a file that the change did not touch, so it
1008        // still exists.
1009        assert_eq!(
1010            classify_moves(
1011                base(),
1012                &[finding_in("src/new.js", "f", 17, 16)],
1013                &["src/new.js"]
1014            ),
1015            [Introduced]
1016        );
1017    }
1018
1019    #[test]
1020    fn grown_function_does_not_take_the_base_finding_of_a_kept_file() {
1021        use AuditFindingAttribution::{Inherited, Introduced};
1022        let base = || vec![finding_in("src/kept.js", "f", 17, 16)];
1023        let both = ["src/kept.js", "src/new.js"];
1024        // `src/kept.js` has no head finding: the change made `f` simpler, or
1025        // removed it. A different `f` in a new file is new.
1026        assert_eq!(
1027            classify_moves(base(), &[finding_in("src/new.js", "f", 16, 16)], &both),
1028            [Introduced]
1029        );
1030        // Equal values still match.
1031        assert_eq!(
1032            classify_moves(base(), &[finding_in("src/new.js", "f", 17, 16)], &both),
1033            [Inherited]
1034        );
1035    }
1036
1037    #[test]
1038    fn one_of_two_same_named_functions_moves() {
1039        use AuditFindingAttribution::Inherited;
1040        let mut second = finding_in("src/kept.js", "run", 21, 20);
1041        second.violation.line = 40;
1042        let base = vec![finding_in("src/kept.js", "run", 17, 16), second];
1043        let head = [
1044            finding_in("src/kept.js", "run", 17, 16),
1045            finding_in("src/new.js", "run", 21, 20),
1046        ];
1047        assert_eq!(
1048            classify_moves(base, &head, &["src/kept.js", "src/new.js"]),
1049            [Inherited, Inherited]
1050        );
1051    }
1052
1053    #[test]
1054    fn moved_function_does_not_take_a_base_finding_that_is_in_use() {
1055        use AuditFindingAttribution::{Inherited, Introduced};
1056        let head = [
1057            finding_in("src/old.js", "f", 17, 16),
1058            finding_in("src/new.js", "f", 17, 16),
1059        ];
1060        assert_eq!(
1061            classify_moves(
1062                vec![finding_in("src/old.js", "f", 17, 16)],
1063                &head,
1064                &["src/old.js", "src/new.js"]
1065            ),
1066            [Inherited, Introduced]
1067        );
1068    }
1069
1070    #[test]
1071    fn same_named_moved_functions_pair_by_values_only() {
1072        use AuditFindingAttribution::{Inherited, Introduced};
1073        let base = || {
1074            vec![
1075                finding_in("src/a.js", "run", 17, 16),
1076                finding_in("src/b.js", "run", 21, 20),
1077            ]
1078        };
1079        let paths = ["src/a.js", "src/b.js", "src/c.js", "src/d.js"];
1080        // Each function keeps its values, in the opposite path order.
1081        assert_eq!(
1082            classify_moves(
1083                base(),
1084                &[
1085                    finding_in("src/c.js", "run", 21, 20),
1086                    finding_in("src/d.js", "run", 17, 16),
1087                ],
1088                &paths
1089            ),
1090            [Inherited, Inherited]
1091        );
1092        // Both functions changed: the name does not tell which is which.
1093        assert_eq!(
1094            classify_moves(
1095                base(),
1096                &[
1097                    finding_in("src/c.js", "run", 22, 21),
1098                    finding_in("src/d.js", "run", 18, 17),
1099                ],
1100                &paths
1101            ),
1102            [Introduced, Introduced]
1103        );
1104    }
1105
1106    #[test]
1107    fn moved_placeholder_name_needs_equal_values_and_lines() {
1108        use AuditFindingAttribution::{Inherited, Introduced};
1109        let base = || vec![finding_in("src/old.js", "<arrow>", 17, 16)];
1110        let both = ["src/old.js", "src/new.js"];
1111        assert_eq!(
1112            classify_moves(
1113                base(),
1114                &[finding_in("src/new.js", "<arrow>", 17, 16)],
1115                &both
1116            ),
1117            [Inherited]
1118        );
1119        assert_eq!(
1120            classify_moves(
1121                base(),
1122                &[finding_in("src/new.js", "<arrow>", 18, 17)],
1123                &both
1124            ),
1125            [Introduced]
1126        );
1127    }
1128
1129    #[test]
1130    fn moved_function_name_can_contain_a_colon() {
1131        assert_eq!(
1132            classify_moves(
1133                vec![finding_in("src/old.js", "it: parses", 17, 16)],
1134                &[finding_in("src/new.js", "it: parses", 17, 16)],
1135                &["src/old.js", "src/new.js"]
1136            ),
1137            [AuditFindingAttribution::Inherited]
1138        );
1139    }
1140
1141    #[test]
1142    fn line_shift_keeps_the_match() {
1143        assert_eq!(
1144            classify(vec![finding("f", 1, 17, 16)], &[finding("f", 40, 17, 16)]),
1145            [false]
1146        );
1147    }
1148
1149    fn crap_finding(crap: Option<f64>, source: Option<CoverageSource>) -> HealthFinding {
1150        let mut finding = finding("f", 1, 16, 5);
1151        finding.violation.exceeded = ExceededThreshold::Crap;
1152        finding.violation.crap = crap;
1153        finding.violation.coverage_source = source;
1154        finding.violation.effective_severity = Some(EffectiveSeverity::Error);
1155        finding
1156    }
1157
1158    #[test]
1159    fn crap_without_base_value_is_not_an_increase() {
1160        // A base without a CRAP score ran without that coverage input. The
1161        // code did not grow.
1162        let head = crap_finding(Some(50.0), Some(CoverageSource::Istanbul));
1163        assert_eq!(
1164            classify(vec![crap_finding(None, None)], std::slice::from_ref(&head)),
1165            [false]
1166        );
1167        // Measured CRAP growth in the same tier is worsened.
1168        assert_eq!(
1169            classify(
1170                vec![crap_finding(Some(40.0), Some(CoverageSource::Istanbul))],
1171                std::slice::from_ref(&head)
1172            ),
1173            [false]
1174        );
1175        assert_eq!(
1176            classify(
1177                vec![crap_finding(Some(60.0), Some(CoverageSource::Istanbul))],
1178                &[head]
1179            ),
1180            [false]
1181        );
1182    }
1183
1184    #[test]
1185    fn estimated_crap_growth_is_worsened_not_introduced() {
1186        let estimated = Some(CoverageSource::Estimated);
1187        let classes = attribution(
1188            vec![crap_finding(Some(40.0), estimated)],
1189            &[crap_finding(Some(50.0), estimated)],
1190        );
1191        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1192        assert_eq!(
1193            classes[0].worsened_metrics,
1194            [metric(WorsenedMetricKind::Crap, 40.0, 50.0)]
1195        );
1196        // A grown cognitive value that the base already exceeds is worsened.
1197        let mut base = crap_finding(Some(40.0), estimated);
1198        base.violation.exceeded = ExceededThreshold::CognitiveCrap;
1199        base.violation.cognitive = 20;
1200        let mut head = base.clone();
1201        head.violation.cognitive = 21;
1202        head.violation.crap = Some(50.0);
1203        assert_eq!(classify(vec![base.clone()], &[head.clone()]), [false]);
1204        // A grown cognitive value that reaches the next tier is introduced.
1205        head.violation.cognitive = 25;
1206        assert_eq!(classify(vec![base], &[head]), [true]);
1207    }
1208
1209    #[test]
1210    fn test_file_findings_get_warn_gate_severity_and_the_exemption() {
1211        // The project itself lives below a `tests` directory. Only the path
1212        // below the project root decides.
1213        let project = root().join("tests").join("project");
1214        let at = |relative: &str| {
1215            let mut finding = finding("f", 1, 16, 5);
1216            finding.violation.path = project.join(relative);
1217            finding.violation.effective_severity = Some(EffectiveSeverity::Error);
1218            finding
1219        };
1220        let mut findings = [
1221            at("src/__tests__/app.js"),
1222            at("src/app.spec.ts"),
1223            at("src/app.test.tsx"),
1224            at("src/__mocks__/api.js"),
1225            at("src/app.js"),
1226            at("src/latest.js"),
1227        ];
1228        exempt_test_file_gates(&mut findings, &project);
1229        let marks: Vec<_> = findings
1230            .iter()
1231            .map(|finding| (finding.effective_severity, finding.gate_exemption))
1232            .collect();
1233        let exempt = (
1234            Some(EffectiveSeverity::Warn),
1235            Some(AuditGateExemption::TestFile),
1236        );
1237        let gated = (Some(EffectiveSeverity::Error), None);
1238        assert_eq!(marks, [exempt, exempt, exempt, exempt, gated, gated]);
1239    }
1240
1241    #[test]
1242    fn estimated_crap_only_findings_get_warn_gate_severity() {
1243        let mut both = crap_finding(Some(50.0), Some(CoverageSource::Estimated));
1244        both.violation.exceeded = ExceededThreshold::CognitiveCrap;
1245        let mut warn_rule = crap_finding(Some(50.0), Some(CoverageSource::Estimated));
1246        warn_rule.violation.effective_severity = Some(EffectiveSeverity::Warn);
1247        let mut findings = [
1248            crap_finding(Some(50.0), Some(CoverageSource::Estimated)),
1249            crap_finding(
1250                Some(50.0),
1251                Some(CoverageSource::EstimatedComponentInherited),
1252            ),
1253            crap_finding(Some(50.0), Some(CoverageSource::Istanbul)),
1254            both,
1255            warn_rule,
1256        ];
1257        demote_estimated_crap_gates(&mut findings);
1258        let severities: Vec<_> = findings
1259            .iter()
1260            .map(|finding| finding.effective_severity)
1261            .collect();
1262        assert_eq!(
1263            severities,
1264            [
1265                Some(EffectiveSeverity::Warn),
1266                Some(EffectiveSeverity::Warn),
1267                Some(EffectiveSeverity::Error),
1268                Some(EffectiveSeverity::Error),
1269                Some(EffectiveSeverity::Warn),
1270            ]
1271        );
1272    }
1273
1274    #[test]
1275    fn same_named_findings_match_unchanged_values_first() {
1276        let base = vec![finding("run", 1, 17, 16), finding("run", 30, 21, 20)];
1277        // Unchanged.
1278        assert_eq!(
1279            classify(
1280                base.clone(),
1281                &[finding("run", 1, 17, 16), finding("run", 30, 21, 20)]
1282            ),
1283            [false, false]
1284        );
1285        // The second function moves to the first function's line but keeps its own base finding.
1286        assert_eq!(
1287            classify(base.clone(), &[finding("run", 1, 21, 20)]),
1288            [false]
1289        );
1290        // A new one added before both.
1291        assert_eq!(
1292            classify(
1293                base.clone(),
1294                &[
1295                    finding("run", 1, 30, 30),
1296                    finding("run", 20, 17, 16),
1297                    finding("run", 50, 21, 20)
1298                ]
1299            ),
1300            [true, false, false]
1301        );
1302        // The first one worsened, the second one unchanged.
1303        assert_eq!(
1304            classify(
1305                base.clone(),
1306                &[finding("run", 1, 18, 17), finding("run", 30, 21, 20)]
1307            ),
1308            [false, false]
1309        );
1310        // The first one moved to a higher tier, the second one unchanged.
1311        assert_eq!(
1312            classify(
1313                base,
1314                &[finding("run", 1, 30, 17), finding("run", 30, 21, 20)]
1315            ),
1316            [true, false]
1317        );
1318    }
1319
1320    /// An anonymous finding with a CRAP score from the given coverage source.
1321    fn arrow(
1322        line: u32,
1323        cyclomatic: u16,
1324        cognitive: u16,
1325        crap: Option<f64>,
1326        source: CoverageSource,
1327    ) -> HealthFinding {
1328        let mut finding = finding("<arrow>", line, MAX + 1, MAX + 1);
1329        finding.violation.cyclomatic = cyclomatic;
1330        finding.violation.cognitive = cognitive;
1331        finding.violation.crap = crap;
1332        finding.violation.coverage_source = crap.map(|_| source);
1333        finding.violation.exceeded = ExceededThreshold::from_bools(
1334            cyclomatic > MAX,
1335            cognitive > MAX,
1336            crap.is_some_and(|crap| crap >= 30.0),
1337        );
1338        finding
1339    }
1340
1341    #[test]
1342    fn unchanged_arrow_keeps_its_base_when_only_crap_changes() {
1343        // Issue #3815: the CRAP score of an unchanged arrow went from an
1344        // estimated score to a measured score. Its cyclomatic and cognitive
1345        // values did not change, so it must keep its own base finding, not the
1346        // first remaining base finding in line order.
1347        let estimated = CoverageSource::Estimated;
1348        let measured = CoverageSource::Istanbul;
1349        let base = [
1350            (122, 36, 37, 1332.0),
1351            (284, 26, 28, 702.0),
1352            (352, 9, 6, 90.0),
1353            (560, 7, 6, 56.0),
1354            (637, 30, 42, 930.0),
1355            (732, 13, 5, 182.0),
1356            (872, 13, 12, 182.0),
1357            (889, 6, 2, 42.0),
1358            (945, 5, 3, 30.0),
1359            (972, 16, 4, 272.0),
1360            (1017, 11, 13, 132.0),
1361            (1184, 14, 15, 210.0),
1362            (1202, 12, 5, 156.0),
1363        ]
1364        .into_iter()
1365        .map(|(line, cyclomatic, cognitive, crap)| {
1366            arrow(line, cyclomatic, cognitive, Some(crap), estimated)
1367        })
1368        .collect();
1369        let head = [
1370            arrow(128, 36, 37, Some(36.0), measured),
1371            arrow(294, 27, 29, None, measured),
1372            arrow(663, 30, 42, Some(30.0), measured),
1373        ];
1374        let classes = attribution(base, &head);
1375        assert!(!classes[0].introduced);
1376        assert!(!classes[2].introduced, "{:?}", classes[2]);
1377        assert!(classes[2].worsened_metrics.is_empty());
1378    }
1379
1380    #[test]
1381    fn crap_growth_of_an_unchanged_arrow_still_compares() {
1382        let measured = CoverageSource::Istanbul;
1383        let classes = attribution(
1384            vec![
1385                arrow(10, 9, 6, Some(40.0), measured),
1386                arrow(40, 30, 42, Some(30.0), measured),
1387            ],
1388            &[arrow(40, 30, 42, Some(60.0), measured)],
1389        );
1390        assert_eq!(
1391            classes[0].worsened_metrics,
1392            [metric(WorsenedMetricKind::Crap, 30.0, 60.0)]
1393        );
1394    }
1395
1396    fn with_lines(mut finding: HealthFinding, line_count: u32) -> HealthFinding {
1397        finding.violation.line_count = line_count;
1398        finding
1399    }
1400
1401    fn attribution(base: Vec<HealthFinding>, head: &[HealthFinding]) -> Vec<ComplexityClass> {
1402        classify_complexity_attribution(head, &root(), &baseline(base))
1403    }
1404
1405    fn metric(kind: WorsenedMetricKind, base: f64, head: f64) -> WorsenedMetric {
1406        WorsenedMetric {
1407            metric: kind,
1408            base,
1409            head,
1410        }
1411    }
1412
1413    #[test]
1414    fn grown_line_count_is_worsened_not_introduced() {
1415        let classes = attribution(
1416            vec![with_lines(finding("f", 1, 17, 16), 80)],
1417            &[with_lines(finding("f", 1, 17, 16), 300)],
1418        );
1419        assert!(!classes[0].introduced);
1420        assert!(classes[0].is_worsened());
1421        assert_eq!(
1422            classes[0].worsened_metrics,
1423            [metric(WorsenedMetricKind::LineCount, 80.0, 300.0)]
1424        );
1425        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1426    }
1427
1428    #[test]
1429    fn grown_metric_that_the_finding_does_not_exceed_is_worsened() {
1430        // Only cyclomatic is exceeded; cognitive grows below the limit.
1431        let classes = attribution(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]);
1432        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1433        assert_eq!(
1434            classes[0].worsened_metrics,
1435            [metric(WorsenedMetricKind::Cognitive, 5.0, 9.0)]
1436        );
1437    }
1438
1439    #[test]
1440    fn grown_exceeded_metric_in_the_same_tier_is_worsened() {
1441        // Cyclomatic 100 to 103 stays in the critical tier.
1442        let classes = attribution(vec![finding("f", 1, 100, 16)], &[finding("f", 1, 103, 16)]);
1443        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1444        assert!(classes[0].exceeded_metric_grew);
1445        assert_eq!(
1446            classes[0].worsened_metrics,
1447            [metric(WorsenedMetricKind::Cyclomatic, 100.0, 103.0)]
1448        );
1449        // Growth only in a metric that the finding does not exceed.
1450        let below = attribution(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]);
1451        assert!(!below[0].exceeded_metric_grew);
1452    }
1453
1454    #[test]
1455    fn severity_tier_uses_the_base_values_not_todays_thresholds() {
1456        // The base finding exceeded only cyclomatic. A threshold override in
1457        // the same change lowers the cognitive limit, so the head finding
1458        // exceeds cognitive too, without cognitive growth.
1459        let mut head = finding("f", 1, 18, 10);
1460        head.violation.exceeded = ExceededThreshold::Both;
1461        assert_eq!(
1462            classify(vec![finding("f", 1, 17, 10)], &[head.clone()]),
1463            [false]
1464        );
1465        // Cognitive grew and the base did not exceed it: newly exceeded.
1466        head.violation.cognitive = 11;
1467        assert_eq!(classify(vec![finding("f", 1, 17, 10)], &[head]), [true]);
1468    }
1469
1470    #[test]
1471    fn measured_crap_tier_crossing_is_introduced() {
1472        let istanbul = Some(CoverageSource::Istanbul);
1473        let mut base = crap_finding(Some(40.0), istanbul);
1474        base.violation.severity = FindingSeverity::Moderate;
1475        let mut head = crap_finding(Some(120.0), istanbul);
1476        head.violation.severity = FindingSeverity::Critical;
1477        assert_eq!(classify(vec![base.clone()], &[head.clone()]), [true]);
1478        // The same values from estimated coverage do not cross a tier.
1479        let estimated = Some(CoverageSource::Estimated);
1480        base.violation.coverage_source = estimated;
1481        head.violation.coverage_source = estimated;
1482        assert_eq!(classify(vec![base], &[head]), [false]);
1483    }
1484
1485    #[test]
1486    fn grown_exceeded_metric_is_introduced_with_values() {
1487        let classes = attribution(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 40, 16)]);
1488        assert_eq!(
1489            classes[0].attribution(),
1490            AuditFindingAttribution::Introduced
1491        );
1492        assert_eq!(
1493            classes[0].worsened_metrics,
1494            [metric(WorsenedMetricKind::Cyclomatic, 17.0, 40.0)]
1495        );
1496        assert!(!classes[0].is_worsened());
1497    }
1498
1499    #[test]
1500    fn improved_and_moved_functions_are_inherited() {
1501        let improved = attribution(
1502            vec![with_lines(finding("f", 1, 30, 30), 90)],
1503            &[with_lines(finding("f", 1, 20, 18), 60)],
1504        );
1505        assert_eq!(
1506            improved[0].attribution(),
1507            AuditFindingAttribution::Inherited
1508        );
1509        assert!(improved[0].worsened_metrics.is_empty());
1510        let moved = attribution(vec![finding("f", 1, 17, 16)], &[finding("f", 400, 17, 16)]);
1511        assert_eq!(moved[0].attribution(), AuditFindingAttribution::Inherited);
1512    }
1513
1514    #[test]
1515    fn new_function_is_introduced_without_values() {
1516        let classes = attribution(vec![finding("f", 1, 17, 16)], &[finding("g", 1, 17, 16)]);
1517        assert_eq!(
1518            classes[0].attribution(),
1519            AuditFindingAttribution::Introduced
1520        );
1521        assert!(classes[0].worsened_metrics.is_empty());
1522    }
1523
1524    #[test]
1525    fn crap_compares_only_when_both_sides_have_a_score() {
1526        let mut head = finding("f", 1, 20, 5);
1527        head.violation.crap = Some(50.0);
1528        let classes = attribution(vec![finding("f", 1, 20, 5)], std::slice::from_ref(&head));
1529        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1530        let mut base = finding("f", 1, 20, 5);
1531        base.violation.crap = Some(40.0);
1532        let classes = attribution(vec![base], &[head]);
1533        assert_eq!(
1534            classes[0].worsened_metrics,
1535            [metric(WorsenedMetricKind::Crap, 40.0, 50.0)]
1536        );
1537    }
1538
1539    #[test]
1540    fn same_named_findings_prefer_the_base_with_equal_line_count() {
1541        // Two same-valued findings; the second one grew in lines.
1542        let base = vec![
1543            with_lines(finding("run", 1, 17, 16), 10),
1544            with_lines(finding("run", 30, 17, 16), 40),
1545        ];
1546        let head = [
1547            with_lines(finding("run", 1, 17, 16), 40),
1548            with_lines(finding("run", 50, 17, 16), 25),
1549        ];
1550        let classes = attribution(base, &head);
1551        // The first head finding takes the 40-line base finding; the second one
1552        // takes the 10-line base finding and grew.
1553        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1554        assert_eq!(classes[1].attribution(), AuditFindingAttribution::Worsened);
1555    }
1556
1557    #[test]
1558    fn an_exact_match_of_a_later_head_is_not_taken_by_an_earlier_head() {
1559        // The 10-line function moved up and grew to 30 lines. The 40-line
1560        // function did not change, but it now comes later in line order.
1561        let base = vec![
1562            with_lines(finding("run", 1, 17, 16), 40),
1563            with_lines(finding("run", 50, 17, 16), 10),
1564        ];
1565        let head = [
1566            with_lines(finding("run", 1, 17, 16), 30),
1567            with_lines(finding("run", 20, 17, 16), 40),
1568        ];
1569        let classes = attribution(base, &head);
1570        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1571        assert_eq!(
1572            classes[0].worsened_metrics,
1573            [metric(WorsenedMetricKind::LineCount, 10.0, 30.0)]
1574        );
1575        assert_eq!(classes[1].attribution(), AuditFindingAttribution::Inherited);
1576        assert!(classes[1].worsened_metrics.is_empty());
1577    }
1578
1579    #[test]
1580    fn small_line_growth_is_not_worsened() {
1581        // A comment line or a formatter rewrap adds a few physical lines.
1582        let classes = attribution(
1583            vec![with_lines(finding("f", 1, 17, 16), 80)],
1584            &[with_lines(finding("f", 1, 17, 16), 84)],
1585        );
1586        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1587        assert!(classes[0].worsened_metrics.is_empty());
1588    }
1589
1590    #[test]
1591    fn line_growth_needs_five_lines_at_any_function_size() {
1592        // 4 lines are below the floor, also on a short function.
1593        let short = attribution(
1594            vec![with_lines(finding("f", 1, 17, 16), 20)],
1595            &[with_lines(finding("f", 1, 17, 16), 24)],
1596        );
1597        assert_eq!(short[0].attribution(), AuditFindingAttribution::Inherited);
1598        let grown = attribution(
1599            vec![with_lines(finding("f", 1, 17, 16), 20)],
1600            &[with_lines(finding("f", 1, 17, 16), 25)],
1601        );
1602        assert_eq!(grown[0].attribution(), AuditFindingAttribution::Worsened);
1603        // The floor does not scale: 9 lines on a 300-line function count.
1604        let long = attribution(
1605            vec![with_lines(finding("f", 1, 17, 16), 300)],
1606            &[with_lines(finding("f", 1, 17, 16), 309)],
1607        );
1608        assert_eq!(long[0].attribution(), AuditFindingAttribution::Worsened);
1609    }
1610
1611    #[test]
1612    fn a_base_with_the_same_values_keeps_the_finding_inherited() {
1613        let primary = baseline(vec![with_lines(finding("f", 1, 17, 16), 20)]);
1614        let merged = baseline(vec![with_lines(finding("f", 1, 17, 16), 60)]);
1615        let head = [with_lines(finding("f", 1, 17, 16), 60)];
1616        let classes =
1617            classify_complexity_attribution_against_all(&head, &root(), [&primary, &merged]);
1618        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1619        let classes = classify_complexity_attribution_against_all(&head, &root(), [&primary]);
1620        assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1621    }
1622
1623    #[test]
1624    fn rename_moves_the_base_findings() {
1625        let base = baseline(vec![finding("f", 1, 17, 16)]);
1626        let renames =
1627            FxHashMap::from_iter([("src/index.js".to_string(), "src/moved.js".to_string())]);
1628        let remapped = remap_complexity_baseline_for_renames(base, &renames);
1629        assert!(remapped.contains_key("complexity:src/moved.js:f"));
1630        assert!(!remapped.contains_key("complexity:src/index.js:f"));
1631    }
1632
1633    #[test]
1634    fn ledger_keys_count_same_named_findings_separately() {
1635        let keys = complexity_ledger_keys(
1636            &[finding("run", 1, 17, 16), finding("run", 30, 17, 16)],
1637            &root(),
1638        );
1639        assert_eq!(
1640            keys,
1641            [
1642                "complexity:src/index.js:run",
1643                "complexity:src/index.js:run#2"
1644            ]
1645        );
1646    }
1647}