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