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