Skip to main content

fallow_api/audit_run/
outcome.rs

1//! Comparison of the head run with the base snapshot, and the verdict.
2
3use std::path::{Path, PathBuf};
4
5use fallow_config::{AuditGate, AuditWorsened, ResolvedConfig, RulesConfig, Severity};
6
7use fallow_engine::changed_files::RenamedFile;
8use fallow_engine::module_graph::relative_key_path;
9use fallow_types::duplicates::CloneGroup;
10use rustc_hash::FxHashSet;
11
12use super::clone_regions::{
13    CloneRegionBase, CloneRegionHead, grade_clone_regions, has_unmatched_group,
14};
15use super::{AuditAnalysesView, AuditKeySnapshot};
16use crate::audit_keys::{
17    AuditComparison, AuditDomainLedger, ChangedPaths, DeadCodeAuditLedger,
18    classify_complexity_attribution_against_all_with_moves, complexity_ledger_keys,
19    dead_code_audit_ledger, dupe_group_key, styling_ledger_keys, styling_ledger_keys_with_diff,
20};
21use crate::audit_moved::{MovedDeadCode, moved_dead_code_keys};
22use crate::diff_risk::clones::{AcceptedCloneGroup, BaseCloneGroup};
23use crate::{AuditAttribution, AuditSummary, AuditVerdict};
24
25/// Which diff decided the new-only duplication demotion, so output can name
26/// where a demotion came from (issue #2220).
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum DupeDemotionDiffSource {
29    /// The opt-in shared diff index decided. Carries the user-facing source
30    /// label (`--diff-file <path>`, `--diff-stdin`, or
31    /// `$FALLOW_DIFF_FILE <path>`).
32    Shared(String),
33    /// The merge-base worktree diff against the resolved base ref decided.
34    Worktree,
35    /// No diff was available. The demotion check did not run, and every
36    /// introduced clone group kept its gate.
37    Skipped,
38}
39
40impl DupeDemotionDiffSource {
41    /// User-facing label for the diff that decided the demotion.
42    #[must_use]
43    pub fn label(&self, base_ref: &str) -> String {
44        match self {
45            Self::Shared(label) => label.clone(),
46            Self::Worktree => format!("merge-base worktree diff vs {base_ref}"),
47            Self::Skipped => "skipped: no diff available".to_string(),
48        }
49    }
50}
51
52/// An opt-in shared diff that the run already applied, with its source label.
53#[derive(Clone, Copy)]
54pub struct SharedDiff<'a> {
55    /// The parsed diff.
56    pub index: &'a fallow_output::DiffIndex,
57    /// The user-facing source label, for example `--diff-file <path>`.
58    pub label: &'a str,
59}
60
61/// The change of one audit run: its files, and the inputs of its diff.
62pub struct RunChange<'a> {
63    /// Head analysis root.
64    pub root: &'a Path,
65    /// Resolved base ref, for the merge-base worktree diff.
66    pub base_ref: &'a str,
67    /// The opt-in shared diff of the run.
68    pub shared: Option<SharedDiff<'a>>,
69    /// The files that the change touched or deleted.
70    pub changed_files: &'a FxHashSet<PathBuf>,
71    /// The merge-base worktree diff, read by the first phase that needs it.
72    /// The inner `None` records that git gave no diff.
73    worktree: std::cell::OnceCell<Option<fallow_output::DiffIndex>>,
74}
75
76impl<'a> RunChange<'a> {
77    /// The change of one run.
78    #[must_use]
79    pub const fn new(
80        root: &'a Path,
81        base_ref: &'a str,
82        shared: Option<SharedDiff<'a>>,
83        changed_files: &'a FxHashSet<PathBuf>,
84    ) -> Self {
85        Self {
86            root,
87            base_ref,
88            shared,
89            changed_files,
90            worktree: std::cell::OnceCell::new(),
91        }
92    }
93
94    /// The diff of the run: the shared diff when one is active, else the
95    /// merge-base worktree diff. One run reads the worktree diff at most one
96    /// time, and it does not read again after a failed read. `None` when git
97    /// gives no diff.
98    pub(super) fn diff_index(&self) -> Option<&fallow_output::DiffIndex> {
99        if let Some(shared) = self.shared {
100            return Some(shared.index);
101        }
102        self.worktree
103            .get_or_init(|| {
104                fallow_engine::changed_files::try_get_changed_diff(self.root, self.base_ref)
105                    .ok()
106                    .map(|diff| fallow_output::DiffIndex::from_unified_diff(&diff))
107            })
108            .as_ref()
109    }
110}
111
112/// Whether the diff added a line with `symbol` to the head file `path`, a
113/// root-relative key path.
114fn added_line_names(
115    diff: &fallow_output::DiffIndex,
116    root: &Path,
117    path: &str,
118    symbol: &str,
119) -> bool {
120    let file = root.join(path);
121    let Some(added) = diff
122        .key_for(&file, root)
123        .and_then(|key| diff.added_lines_in(&key))
124    else {
125        return false;
126    };
127    let Ok(source) = std::fs::read_to_string(&file) else {
128        return false;
129    };
130    source
131        .lines()
132        .zip(1_u64..)
133        .any(|(line, number)| added.contains(&number) && line.contains(symbol))
134}
135
136/// Classify every head finding once against the base snapshot.
137///
138/// With `syntactic_fallback` set (the degraded type-aware path), dead code
139/// compares against the syntactic keys of the base, and a head finding that
140/// only semantic evidence produced stays advisory: it has no syntactic base
141/// counterpart to compare with.
142///
143/// `change` holds the files that the change touched or deleted, and its
144/// diff. A complexity finding of a function that the change moved between
145/// two of those files compares with its base finding (see
146/// [`classify_complexity_attribution_against_all_with_moves`]). An unused
147/// symbol that the change moved is inherited (see `audit_moved.rs`). The
148/// clone groups compare by key here, and [`attribute_clone_regions`] grades
149/// them as regions.
150#[must_use]
151pub fn compare(
152    view: &AuditAnalysesView<'_>,
153    base: Option<&AuditKeySnapshot>,
154    syntactic_fallback: bool,
155    change: &RunChange<'_>,
156) -> AuditComparison {
157    let dead_code =
158        view.dead_code
159            .as_ref()
160            .map_or_else(DeadCodeAuditLedger::default, |dead_code| {
161                // A base that ran without type-aware analysis is already
162                // syntactic, so its refined set is also its fallback set.
163                let base_keys = base.map(|snapshot| {
164                    if syntactic_fallback {
165                        snapshot
166                            .syntactic_dead_code
167                            .as_ref()
168                            .unwrap_or(&snapshot.dead_code)
169                    } else {
170                        &snapshot.dead_code
171                    }
172                });
173                let mut ledger = dead_code_audit_ledger(
174                    dead_code.results,
175                    dead_code.root,
176                    dead_code.config,
177                    base_keys,
178                );
179                if syntactic_fallback && let Some(head_syntactic) = dead_code.syntactic_keys {
180                    ledger.demote_unattributable_introductions(head_syntactic);
181                }
182                if let Some(base_keys) = base_keys {
183                    let moved = moved_dead_code_keys(
184                        &ledger,
185                        &MovedDeadCode {
186                            base: base_keys,
187                            changed: &changed_paths_of(change.changed_files, dead_code.root),
188                            also_reported: dead_code.syntactic_keys.filter(|_| syntactic_fallback),
189                            added_line_names: &|path, symbol| {
190                                change.diff_index().is_some_and(|index| {
191                                    added_line_names(index, dead_code.root, path, symbol)
192                                })
193                            },
194                        },
195                    );
196                    ledger.inherit_introductions(&moved);
197                }
198                ledger
199            });
200    let health_classes =
201        view.health
202            .as_ref()
203            .zip(base)
204            .map_or_else(Vec::new, |(health, snapshot)| {
205                let changed_paths = changed_paths_of(change.changed_files, health.root);
206                classify_complexity_attribution_against_all_with_moves(
207                    &health.report.findings,
208                    health.root,
209                    std::iter::once(&snapshot.health).chain(&snapshot.inherited_health),
210                    &changed_paths,
211                )
212            });
213    let health = view
214        .health
215        .as_ref()
216        .map_or_else(AuditDomainLedger::default, |health| {
217            let findings = &health.report.findings;
218            let keys = complexity_ledger_keys(findings, health.root);
219            let introduced = (0..findings.len()).map(|index| {
220                health_classes
221                    .get(index)
222                    .is_some_and(|class| class.introduced)
223            });
224            AuditDomainLedger::from_classified(keys.into_iter().zip(introduced), base.is_some())
225        });
226    // The key compare is the attribution until `attribute_clone_regions`
227    // grades the regions with the diff.
228    let dupes = AuditDomainLedger::compare(
229        view.duplication.iter().flat_map(|duplication| {
230            duplication
231                .clone_groups
232                .iter()
233                .map(|group| dupe_group_key(group, duplication.root))
234        }),
235        base.map(|snapshot| &snapshot.dupes),
236    );
237    let styling = AuditDomainLedger::compare(
238        view.health
239            .iter()
240            .flat_map(|health| styling_ledger_keys(&health.report.styling_findings, health.root)),
241        base.map(|snapshot| &snapshot.styling),
242    );
243    AuditComparison {
244        dead_code,
245        health,
246        health_classes,
247        dupes,
248        dupe_regions: super::clone_regions::CloneRegions::default(),
249        styling,
250    }
251}
252
253/// The changed files as key paths, with the files that the head does not have.
254fn changed_paths_of(changed_files: &FxHashSet<PathBuf>, root: &Path) -> ChangedPaths {
255    let mut paths = ChangedPaths::default();
256    for path in changed_files {
257        let key = relative_key_path(path, root);
258        if !path.exists() {
259            paths.deleted.insert(key.clone());
260        }
261        paths.changed.insert(key);
262    }
263    paths
264}
265
266/// The base data that the clone regions compare with.
267#[derive(Clone, Copy)]
268pub struct DupeBase<'a> {
269    /// Attribution keys of the base clone groups, at head paths.
270    pub keys: &'a FxHashSet<String>,
271    /// Instance locations of the base clone groups, at base paths.
272    pub groups: &'a [BaseCloneGroup],
273    /// Base clone groups that `duplicates.ignoredClones` hid, at base paths.
274    pub accepted: &'a [AcceptedCloneGroup],
275    /// The renamed files of the change.
276    pub renames: &'a [RenamedFile],
277}
278
279/// Grade the head clone groups as regions, and set the introduced flag of
280/// each group from the grade of its region (see the `clone_regions` module
281/// of `audit_run`).
282///
283/// The opt-in shared diff decides when it is present; the merge-base worktree
284/// diff decides in the other cases. The diff is read only when a head group
285/// has a key that the base does not hold. `base` is `None` when the run has
286/// no base snapshot.
287pub fn attribute_clone_regions(
288    comparison: &mut AuditComparison,
289    view: &AuditAnalysesView<'_>,
290    change: &RunChange<'_>,
291    base: Option<DupeBase<'_>>,
292) -> Option<DupeDemotionDiffSource> {
293    let (Some(duplication), Some(base)) = (view.duplication.as_ref(), base) else {
294        return None;
295    };
296    let head = CloneRegionHead {
297        groups: &duplication.clone_groups,
298        ignored: duplication.ignored_groups,
299        root: duplication.root,
300        min_lines: duplication.config.duplicates.min_lines,
301    };
302    let changed = changed_paths_of(change.changed_files, duplication.root);
303    let region_base = CloneRegionBase {
304        keys: base.keys,
305        groups: base.groups,
306        accepted: base.accepted,
307        renames: base.renames,
308        changed: &changed,
309    };
310    let (diff, source) = if has_unmatched_group(&head, base.keys) {
311        match change.diff_index() {
312            Some(index) => (
313                Some(index),
314                Some(
315                    change
316                        .shared
317                        .map_or(DupeDemotionDiffSource::Worktree, |shared| {
318                            DupeDemotionDiffSource::Shared(shared.label.to_owned())
319                        }),
320                ),
321            ),
322            None => (None, Some(DupeDemotionDiffSource::Skipped)),
323        }
324    } else {
325        (None, None)
326    };
327    let regions = grade_clone_regions(&head, &region_base, diff);
328    let keys: Vec<String> = duplication
329        .clone_groups
330        .iter()
331        .map(|group| dupe_group_key(group, duplication.root))
332        .collect();
333    let demoted: FxHashSet<String> = keys
334        .iter()
335        .enumerate()
336        .filter(|(index, _)| regions.group_demoted(*index))
337        .map(|(_, key)| key.clone())
338        .collect();
339    let mut ledger = AuditDomainLedger::from_classified(
340        keys.into_iter().enumerate().map(|(index, key)| {
341            let flagged = regions.group_introduced(index) || regions.group_demoted(index);
342            (key, flagged)
343        }),
344        true,
345    );
346    ledger.demote_introductions(&demoted);
347    comparison.dupes = ledger;
348    comparison.dupe_regions = regions;
349    source
350}
351
352/// Compare the styling findings again with the run's diff, so the finding
353/// that the change wrote is the introduced one.
354///
355/// Equal styling findings share one identity key, and their occurrence
356/// suffix follows source order. A new equal finding above an unchanged one
357/// would take the occurrence of the unchanged finding. With the diff, the
358/// findings on added lines get the last occurrences (issue #3956). The step
359/// runs only when a styling finding is introduced, and it changes no count.
360pub fn realign_styling_introductions(
361    comparison: &mut AuditComparison,
362    view: &AuditAnalysesView<'_>,
363    base: Option<&AuditKeySnapshot>,
364    change: &RunChange<'_>,
365) {
366    let (Some(base), Some(health)) = (base, view.health.as_ref()) else {
367        return;
368    };
369    if comparison.styling.introduced_count() == 0 {
370        return;
371    }
372    let Some(index) = change.diff_index() else {
373        return;
374    };
375    comparison.styling = AuditDomainLedger::compare(
376        styling_ledger_keys_with_diff(&health.report.styling_findings, health.root, Some(index)),
377        Some(&base.styling),
378    );
379}
380
381/// The severity of the rule that owns a styling finding `code`. Styling is
382/// verdict-neutral by default (rule `warn`).
383#[must_use]
384pub fn styling_rule_severity(rules: &RulesConfig, code: &str) -> Severity {
385    match code {
386        "css-token-drift" => rules.css_token_drift,
387        "css-duplicate-block" => rules.css_duplicate_block,
388        "css-selector-complexity" => rules.css_selector_complexity,
389        "css-dead-surface" => rules.css_dead_surface,
390        "css-broken-reference" => rules.css_broken_reference,
391        _ => Severity::Warn,
392    }
393}
394
395/// Whether a styling finding escalates to `error` and so gates the verdict.
396#[must_use]
397pub fn styling_finding_gates(rules: &RulesConfig, code: &str) -> bool {
398    styling_rule_severity(rules, code) == Severity::Error
399}
400
401/// The `introduced-clone-group` severity of one clone group.
402///
403/// With `overrides`, the rule resolves for the file of each instance, and
404/// the most severe result applies. So an override that raises the rule for
405/// one copy gates the group, and `off` applies only when it matches every
406/// copy.
407fn clone_group_severity(config: &ResolvedConfig, group: &CloneGroup) -> Severity {
408    if config.overrides.is_empty() {
409        return config.rules.introduced_clone_group;
410    }
411    group
412        .instances
413        .iter()
414        .map(|instance| {
415            config
416                .resolve_rules_for_path(&instance.file)
417                .introduced_clone_group
418        })
419        .max_by_key(|severity| match severity {
420            Severity::Error => 2,
421            Severity::Warn => 1,
422            Severity::Off => 0,
423        })
424        .unwrap_or(config.rules.introduced_clone_group)
425}
426
427/// Attribution counts, verdict and summary of one comparison.
428#[must_use]
429pub fn outcome(
430    gate: AuditGate,
431    worsened: AuditWorsened,
432    view: &AuditAnalysesView<'_>,
433    comparison: &AuditComparison,
434    has_base: bool,
435) -> (AuditAttribution, AuditVerdict, AuditSummary) {
436    let summary = summary(view, comparison);
437    (
438        attribution(gate, worsened, comparison, has_base),
439        verdict(gate, worsened, view, comparison, &summary),
440        summary,
441    )
442}
443
444/// How each complexity finding takes part in the verdict: `(gates, warns)`.
445///
446/// Under `new-only`, an introduced finding gates. A worsened finding gates
447/// under `audit.worsened: error`, and gives at least `warn` under `warn`.
448fn complexity_verdict_flags(
449    gate: AuditGate,
450    worsened: AuditWorsened,
451    view: &AuditAnalysesView<'_>,
452    comparison: &AuditComparison,
453) -> (bool, bool) {
454    let new_only = matches!(gate, AuditGate::NewOnly);
455    let Some(health) = view.health.as_ref() else {
456        return (false, false);
457    };
458    let mut errors = false;
459    let mut warnings = false;
460    for (index, (finding, introduced)) in health
461        .report
462        .findings
463        .iter()
464        .zip(comparison.health.introduced())
465        .enumerate()
466    {
467        let is_worsened = comparison
468            .health_classes
469            .get(index)
470            .is_some_and(crate::audit_keys::ComplexityClass::is_worsened);
471        let counts = !new_only || introduced || (is_worsened && worsened == AuditWorsened::Error);
472        if counts {
473            if finding.blocks() {
474                errors = true;
475            } else {
476                warnings = true;
477            }
478        } else if is_worsened {
479            warnings = true;
480        }
481    }
482    (errors, warnings)
483}
484
485/// How the clone groups take part in the verdict: `(gates, warns)`.
486///
487/// Under `new-only`, only an introduced group counts. The attribution counts
488/// regions, so the groups of one paste are one finding there. Under `all`, every
489/// group counts. The `introduced-clone-group` rule gives the severity of a
490/// group that counts.
491fn duplication_verdict_flags(
492    new_only: bool,
493    view: &AuditAnalysesView<'_>,
494    comparison: &AuditComparison,
495) -> (bool, bool) {
496    let Some(duplication) = view.duplication.as_ref() else {
497        return (false, false);
498    };
499    let introduced: Vec<bool> = comparison.dupes.introduced().collect();
500    let mut errors = false;
501    let mut warnings = false;
502    for (index, group) in duplication.clone_groups.iter().enumerate() {
503        if new_only && !introduced.get(index).copied().unwrap_or(false) {
504            continue;
505        }
506        match clone_group_severity(duplication.config, group) {
507            Severity::Error => errors = true,
508            Severity::Warn => warnings = true,
509            Severity::Off => {}
510        }
511    }
512    (errors, warnings)
513}
514
515fn verdict(
516    gate: AuditGate,
517    worsened: AuditWorsened,
518    view: &AuditAnalysesView<'_>,
519    comparison: &AuditComparison,
520    summary: &AuditSummary,
521) -> AuditVerdict {
522    let new_only = matches!(gate, AuditGate::NewOnly);
523    let dead_code_errors = if new_only {
524        comparison.dead_code.has_introduced_errors()
525    } else {
526        dead_code_has_errors(view)
527    };
528    let dead_code_warnings = if new_only {
529        comparison.dead_code.has_introduced_warnings()
530    } else {
531        comparison
532            .dead_code
533            .records()
534            .iter()
535            .any(|record| record.effective_severity == Severity::Warn)
536    };
537    // The `complexity-*` rules decide if a finding blocks: `error` fails the
538    // verdict and `warn` gives `warn`. The `new-only` gate reads only the
539    // introduced findings.
540    let (complexity_errors, complexity_warnings) =
541        complexity_verdict_flags(gate, worsened, view, comparison);
542    let styling_errors = view.health.as_ref().is_some_and(|health| {
543        health
544            .report
545            .styling_findings
546            .iter()
547            .zip(comparison.styling.introduced())
548            .any(|(finding, introduced)| {
549                (!new_only || introduced) && styling_finding_gates(health.rules, &finding.code)
550            })
551    });
552    let (clone_errors, clone_warnings) = duplication_verdict_flags(new_only, view, comparison);
553    // The threshold reads every counted group, also a group that the
554    // `introduced-clone-group` rule turns off: the two gates are independent.
555    let duplication_findings = if new_only {
556        comparison.duplication_introduced_count()
557    } else {
558        summary.duplication_clone_groups
559    };
560    let duplication_errors = view.duplication.as_ref().is_some_and(|duplication| {
561        duplication_findings > 0
562            && duplication.threshold > 0.0
563            && duplication.duplication_percentage > duplication.threshold
564    });
565    if dead_code_errors || complexity_errors || styling_errors || duplication_errors || clone_errors
566    {
567        AuditVerdict::Fail
568    } else if dead_code_warnings || complexity_warnings || clone_warnings {
569        AuditVerdict::Warn
570    } else {
571        AuditVerdict::Pass
572    }
573}
574
575/// Whether the head dead-code findings hold an error-severity finding, by the
576/// same rule that decides the exit code of `fallow dead-code`.
577fn dead_code_has_errors(view: &AuditAnalysesView<'_>) -> bool {
578    view.dead_code.as_ref().is_some_and(|dead_code| {
579        fallow_engine::error_severity::has_error_severity_issues(
580            dead_code.results,
581            &dead_code.config.rules,
582            Some(dead_code.config),
583            false,
584        )
585    })
586}
587
588fn attribution(
589    gate: AuditGate,
590    worsened: AuditWorsened,
591    comparison: &AuditComparison,
592    has_base: bool,
593) -> AuditAttribution {
594    if !has_base {
595        return AuditAttribution {
596            gate,
597            worsened,
598            ..AuditAttribution::default()
599        };
600    }
601    AuditAttribution {
602        gate,
603        worsened,
604        complexity_worsened: comparison.complexity_worsened_count(),
605        dead_code_introduced: comparison.dead_code.introduced_count(),
606        dead_code_inherited: comparison.dead_code.inherited_count(),
607        complexity_introduced: comparison.health.introduced_count(),
608        complexity_inherited: comparison.health.inherited_count(),
609        duplication_introduced: comparison.duplication_introduced_count(),
610        duplication_inherited: comparison.duplication_inherited_count(),
611    }
612}
613
614fn summary(view: &AuditAnalysesView<'_>, comparison: &AuditComparison) -> AuditSummary {
615    AuditSummary {
616        dead_code_issues: comparison.dead_code.visible_count(),
617        dead_code_has_errors: dead_code_has_errors(view),
618        dead_code_skipped: view.dead_code.is_none(),
619        complexity_skipped: view.health.is_none(),
620        duplication_skipped: view.duplication.is_none(),
621        complexity_findings: view
622            .health
623            .as_ref()
624            .map_or(0, |health| health.report.findings.len()),
625        max_cyclomatic: view.health.as_ref().and_then(|health| {
626            health
627                .report
628                .findings
629                .iter()
630                .map(|finding| finding.cyclomatic)
631                .max()
632        }),
633        duplication_clone_groups: view
634            .duplication
635            .as_ref()
636            .map_or(0, |duplication| duplication.clone_groups.len()),
637    }
638}