fallow-api 3.47.0

Programmatic API contract types for fallow
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! Comparison of the head run with the base snapshot, and the verdict.

use std::path::{Path, PathBuf};

use fallow_config::{AuditGate, AuditWorsened, ResolvedConfig, RulesConfig, Severity};

use fallow_engine::changed_files::RenamedFile;
use fallow_engine::module_graph::relative_key_path;
use fallow_types::duplicates::CloneGroup;
use rustc_hash::FxHashSet;

use super::clone_regions::{
    CloneRegionBase, CloneRegionHead, grade_clone_regions, has_unmatched_group,
};
use super::{AuditAnalysesView, AuditKeySnapshot};
use crate::audit_keys::{
    AuditComparison, AuditDomainLedger, ChangedPaths, DeadCodeAuditLedger,
    classify_complexity_attribution_against_all_with_moves, complexity_ledger_keys,
    dead_code_audit_ledger, dupe_group_key, styling_ledger_keys, styling_ledger_keys_with_diff,
};
use crate::audit_moved::{MovedDeadCode, moved_dead_code_keys};
use crate::diff_risk::clones::{AcceptedCloneGroup, BaseCloneGroup};
use crate::{AuditAttribution, AuditSummary, AuditVerdict};

/// Which diff decided the new-only duplication demotion, so output can name
/// where a demotion came from (issue #2220).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DupeDemotionDiffSource {
    /// The opt-in shared diff index decided. Carries the user-facing source
    /// label (`--diff-file <path>`, `--diff-stdin`, or
    /// `$FALLOW_DIFF_FILE <path>`).
    Shared(String),
    /// The merge-base worktree diff against the resolved base ref decided.
    Worktree,
    /// No diff was available. The demotion check did not run, and every
    /// introduced clone group kept its gate.
    Skipped,
}

impl DupeDemotionDiffSource {
    /// User-facing label for the diff that decided the demotion.
    #[must_use]
    pub fn label(&self, base_ref: &str) -> String {
        match self {
            Self::Shared(label) => label.clone(),
            Self::Worktree => format!("merge-base worktree diff vs {base_ref}"),
            Self::Skipped => "skipped: no diff available".to_string(),
        }
    }
}

/// An opt-in shared diff that the run already applied, with its source label.
#[derive(Clone, Copy)]
pub struct SharedDiff<'a> {
    /// The parsed diff.
    pub index: &'a fallow_output::DiffIndex,
    /// The user-facing source label, for example `--diff-file <path>`.
    pub label: &'a str,
}

/// The change of one audit run: its files, and the inputs of its diff.
pub struct RunChange<'a> {
    /// Head analysis root.
    pub root: &'a Path,
    /// Resolved base ref, for the merge-base worktree diff.
    pub base_ref: &'a str,
    /// The opt-in shared diff of the run.
    pub shared: Option<SharedDiff<'a>>,
    /// The files that the change touched or deleted.
    pub changed_files: &'a FxHashSet<PathBuf>,
    /// The merge-base worktree diff, read by the first phase that needs it.
    /// The inner `None` records that git gave no diff.
    worktree: std::cell::OnceCell<Option<fallow_output::DiffIndex>>,
}

impl<'a> RunChange<'a> {
    /// The change of one run.
    #[must_use]
    pub const fn new(
        root: &'a Path,
        base_ref: &'a str,
        shared: Option<SharedDiff<'a>>,
        changed_files: &'a FxHashSet<PathBuf>,
    ) -> Self {
        Self {
            root,
            base_ref,
            shared,
            changed_files,
            worktree: std::cell::OnceCell::new(),
        }
    }

    /// The diff of the run: the shared diff when one is active, else the
    /// merge-base worktree diff. One run reads the worktree diff at most one
    /// time, and it does not read again after a failed read. `None` when git
    /// gives no diff.
    pub(super) fn diff_index(&self) -> Option<&fallow_output::DiffIndex> {
        if let Some(shared) = self.shared {
            return Some(shared.index);
        }
        self.worktree
            .get_or_init(|| {
                fallow_engine::changed_files::try_get_changed_diff(self.root, self.base_ref)
                    .ok()
                    .map(|diff| fallow_output::DiffIndex::from_unified_diff(&diff))
            })
            .as_ref()
    }
}

/// Whether the diff added a line with `symbol` to the head file `path`, a
/// root-relative key path.
fn added_line_names(
    diff: &fallow_output::DiffIndex,
    root: &Path,
    path: &str,
    symbol: &str,
) -> bool {
    let file = root.join(path);
    let Some(added) = diff
        .key_for(&file, root)
        .and_then(|key| diff.added_lines_in(&key))
    else {
        return false;
    };
    let Ok(source) = std::fs::read_to_string(&file) else {
        return false;
    };
    source
        .lines()
        .zip(1_u64..)
        .any(|(line, number)| added.contains(&number) && line.contains(symbol))
}

/// Classify every head finding once against the base snapshot.
///
/// With `syntactic_fallback` set (the degraded type-aware path), dead code
/// compares against the syntactic keys of the base, and a head finding that
/// only semantic evidence produced stays advisory: it has no syntactic base
/// counterpart to compare with.
///
/// `change` holds the files that the change touched or deleted, and its
/// diff. A complexity finding of a function that the change moved between
/// two of those files compares with its base finding (see
/// [`classify_complexity_attribution_against_all_with_moves`]). An unused
/// symbol that the change moved is inherited (see `audit_moved.rs`). The
/// clone groups compare by key here, and [`attribute_clone_regions`] grades
/// them as regions.
#[must_use]
pub fn compare(
    view: &AuditAnalysesView<'_>,
    base: Option<&AuditKeySnapshot>,
    syntactic_fallback: bool,
    change: &RunChange<'_>,
) -> AuditComparison {
    let dead_code =
        view.dead_code
            .as_ref()
            .map_or_else(DeadCodeAuditLedger::default, |dead_code| {
                // A base that ran without type-aware analysis is already
                // syntactic, so its refined set is also its fallback set.
                let base_keys = base.map(|snapshot| {
                    if syntactic_fallback {
                        snapshot
                            .syntactic_dead_code
                            .as_ref()
                            .unwrap_or(&snapshot.dead_code)
                    } else {
                        &snapshot.dead_code
                    }
                });
                let mut ledger = dead_code_audit_ledger(
                    dead_code.results,
                    dead_code.root,
                    dead_code.config,
                    base_keys,
                );
                if syntactic_fallback && let Some(head_syntactic) = dead_code.syntactic_keys {
                    ledger.demote_unattributable_introductions(head_syntactic);
                }
                if let Some(base_keys) = base_keys {
                    let moved = moved_dead_code_keys(
                        &ledger,
                        &MovedDeadCode {
                            base: base_keys,
                            changed: &changed_paths_of(change.changed_files, dead_code.root),
                            also_reported: dead_code.syntactic_keys.filter(|_| syntactic_fallback),
                            added_line_names: &|path, symbol| {
                                change.diff_index().is_some_and(|index| {
                                    added_line_names(index, dead_code.root, path, symbol)
                                })
                            },
                        },
                    );
                    ledger.inherit_introductions(&moved);
                }
                ledger
            });
    let health_classes =
        view.health
            .as_ref()
            .zip(base)
            .map_or_else(Vec::new, |(health, snapshot)| {
                let changed_paths = changed_paths_of(change.changed_files, health.root);
                classify_complexity_attribution_against_all_with_moves(
                    &health.report.findings,
                    health.root,
                    std::iter::once(&snapshot.health).chain(&snapshot.inherited_health),
                    &changed_paths,
                )
            });
    let health = view
        .health
        .as_ref()
        .map_or_else(AuditDomainLedger::default, |health| {
            let findings = &health.report.findings;
            let keys = complexity_ledger_keys(findings, health.root);
            let introduced = (0..findings.len()).map(|index| {
                health_classes
                    .get(index)
                    .is_some_and(|class| class.introduced)
            });
            AuditDomainLedger::from_classified(keys.into_iter().zip(introduced), base.is_some())
        });
    // The key compare is the attribution until `attribute_clone_regions`
    // grades the regions with the diff.
    let dupes = AuditDomainLedger::compare(
        view.duplication.iter().flat_map(|duplication| {
            duplication
                .clone_groups
                .iter()
                .map(|group| dupe_group_key(group, duplication.root))
        }),
        base.map(|snapshot| &snapshot.dupes),
    );
    let styling = AuditDomainLedger::compare(
        view.health
            .iter()
            .flat_map(|health| styling_ledger_keys(&health.report.styling_findings, health.root)),
        base.map(|snapshot| &snapshot.styling),
    );
    AuditComparison {
        dead_code,
        health,
        health_classes,
        dupes,
        dupe_regions: super::clone_regions::CloneRegions::default(),
        styling,
    }
}

/// The changed files as key paths, with the files that the head does not have.
fn changed_paths_of(changed_files: &FxHashSet<PathBuf>, root: &Path) -> ChangedPaths {
    let mut paths = ChangedPaths::default();
    for path in changed_files {
        let key = relative_key_path(path, root);
        if !path.exists() {
            paths.deleted.insert(key.clone());
        }
        paths.changed.insert(key);
    }
    paths
}

/// The base data that the clone regions compare with.
#[derive(Clone, Copy)]
pub struct DupeBase<'a> {
    /// Attribution keys of the base clone groups, at head paths.
    pub keys: &'a FxHashSet<String>,
    /// Instance locations of the base clone groups, at base paths.
    pub groups: &'a [BaseCloneGroup],
    /// Base clone groups that `duplicates.ignoredClones` hid, at base paths.
    pub accepted: &'a [AcceptedCloneGroup],
    /// The renamed files of the change.
    pub renames: &'a [RenamedFile],
}

/// Grade the head clone groups as regions, and set the introduced flag of
/// each group from the grade of its region (see the `clone_regions` module
/// of `audit_run`).
///
/// The opt-in shared diff decides when it is present; the merge-base worktree
/// diff decides in the other cases. The diff is read only when a head group
/// has a key that the base does not hold. `base` is `None` when the run has
/// no base snapshot.
pub fn attribute_clone_regions(
    comparison: &mut AuditComparison,
    view: &AuditAnalysesView<'_>,
    change: &RunChange<'_>,
    base: Option<DupeBase<'_>>,
) -> Option<DupeDemotionDiffSource> {
    let (Some(duplication), Some(base)) = (view.duplication.as_ref(), base) else {
        return None;
    };
    let head = CloneRegionHead {
        groups: &duplication.clone_groups,
        ignored: duplication.ignored_groups,
        root: duplication.root,
        min_lines: duplication.config.duplicates.min_lines,
    };
    let changed = changed_paths_of(change.changed_files, duplication.root);
    let region_base = CloneRegionBase {
        keys: base.keys,
        groups: base.groups,
        accepted: base.accepted,
        renames: base.renames,
        changed: &changed,
    };
    let (diff, source) = if has_unmatched_group(&head, base.keys) {
        match change.diff_index() {
            Some(index) => (
                Some(index),
                Some(
                    change
                        .shared
                        .map_or(DupeDemotionDiffSource::Worktree, |shared| {
                            DupeDemotionDiffSource::Shared(shared.label.to_owned())
                        }),
                ),
            ),
            None => (None, Some(DupeDemotionDiffSource::Skipped)),
        }
    } else {
        (None, None)
    };
    let regions = grade_clone_regions(&head, &region_base, diff);
    let keys: Vec<String> = duplication
        .clone_groups
        .iter()
        .map(|group| dupe_group_key(group, duplication.root))
        .collect();
    let demoted: FxHashSet<String> = keys
        .iter()
        .enumerate()
        .filter(|(index, _)| regions.group_demoted(*index))
        .map(|(_, key)| key.clone())
        .collect();
    let mut ledger = AuditDomainLedger::from_classified(
        keys.into_iter().enumerate().map(|(index, key)| {
            let flagged = regions.group_introduced(index) || regions.group_demoted(index);
            (key, flagged)
        }),
        true,
    );
    ledger.demote_introductions(&demoted);
    comparison.dupes = ledger;
    comparison.dupe_regions = regions;
    source
}

/// Compare the styling findings again with the run's diff, so the finding
/// that the change wrote is the introduced one.
///
/// Equal styling findings share one identity key, and their occurrence
/// suffix follows source order. A new equal finding above an unchanged one
/// would take the occurrence of the unchanged finding. With the diff, the
/// findings on added lines get the last occurrences (issue #3956). The step
/// runs only when a styling finding is introduced, and it changes no count.
pub fn realign_styling_introductions(
    comparison: &mut AuditComparison,
    view: &AuditAnalysesView<'_>,
    base: Option<&AuditKeySnapshot>,
    change: &RunChange<'_>,
) {
    let (Some(base), Some(health)) = (base, view.health.as_ref()) else {
        return;
    };
    if comparison.styling.introduced_count() == 0 {
        return;
    }
    let Some(index) = change.diff_index() else {
        return;
    };
    comparison.styling = AuditDomainLedger::compare(
        styling_ledger_keys_with_diff(&health.report.styling_findings, health.root, Some(index)),
        Some(&base.styling),
    );
}

/// The severity of the rule that owns a styling finding `code`. Styling is
/// verdict-neutral by default (rule `warn`).
#[must_use]
pub fn styling_rule_severity(rules: &RulesConfig, code: &str) -> Severity {
    match code {
        "css-token-drift" => rules.css_token_drift,
        "css-duplicate-block" => rules.css_duplicate_block,
        "css-selector-complexity" => rules.css_selector_complexity,
        "css-dead-surface" => rules.css_dead_surface,
        "css-broken-reference" => rules.css_broken_reference,
        _ => Severity::Warn,
    }
}

/// Whether a styling finding escalates to `error` and so gates the verdict.
#[must_use]
pub fn styling_finding_gates(rules: &RulesConfig, code: &str) -> bool {
    styling_rule_severity(rules, code) == Severity::Error
}

/// The `introduced-clone-group` severity of one clone group.
///
/// With `overrides`, the rule resolves for the file of each instance, and
/// the most severe result applies. So an override that raises the rule for
/// one copy gates the group, and `off` applies only when it matches every
/// copy.
fn clone_group_severity(config: &ResolvedConfig, group: &CloneGroup) -> Severity {
    if config.overrides.is_empty() {
        return config.rules.introduced_clone_group;
    }
    group
        .instances
        .iter()
        .map(|instance| {
            config
                .resolve_rules_for_path(&instance.file)
                .introduced_clone_group
        })
        .max_by_key(|severity| match severity {
            Severity::Error => 2,
            Severity::Warn => 1,
            Severity::Off => 0,
        })
        .unwrap_or(config.rules.introduced_clone_group)
}

/// Attribution counts, verdict and summary of one comparison.
#[must_use]
pub fn outcome(
    gate: AuditGate,
    worsened: AuditWorsened,
    view: &AuditAnalysesView<'_>,
    comparison: &AuditComparison,
    has_base: bool,
) -> (AuditAttribution, AuditVerdict, AuditSummary) {
    let summary = summary(view, comparison);
    (
        attribution(gate, worsened, comparison, has_base),
        verdict(gate, worsened, view, comparison, &summary),
        summary,
    )
}

/// How each complexity finding takes part in the verdict: `(gates, warns)`.
///
/// Under `new-only`, an introduced finding gates. A worsened finding gates
/// under `audit.worsened: error`, and gives at least `warn` under `warn`.
fn complexity_verdict_flags(
    gate: AuditGate,
    worsened: AuditWorsened,
    view: &AuditAnalysesView<'_>,
    comparison: &AuditComparison,
) -> (bool, bool) {
    let new_only = matches!(gate, AuditGate::NewOnly);
    let Some(health) = view.health.as_ref() else {
        return (false, false);
    };
    let mut errors = false;
    let mut warnings = false;
    for (index, (finding, introduced)) in health
        .report
        .findings
        .iter()
        .zip(comparison.health.introduced())
        .enumerate()
    {
        let is_worsened = comparison
            .health_classes
            .get(index)
            .is_some_and(crate::audit_keys::ComplexityClass::is_worsened);
        let counts = !new_only || introduced || (is_worsened && worsened == AuditWorsened::Error);
        if counts {
            if finding.blocks() {
                errors = true;
            } else {
                warnings = true;
            }
        } else if is_worsened {
            warnings = true;
        }
    }
    (errors, warnings)
}

/// How the clone groups take part in the verdict: `(gates, warns)`.
///
/// Under `new-only`, only an introduced group counts. The attribution counts
/// regions, so the groups of one paste are one finding there. Under `all`, every
/// group counts. The `introduced-clone-group` rule gives the severity of a
/// group that counts.
fn duplication_verdict_flags(
    new_only: bool,
    view: &AuditAnalysesView<'_>,
    comparison: &AuditComparison,
) -> (bool, bool) {
    let Some(duplication) = view.duplication.as_ref() else {
        return (false, false);
    };
    let introduced: Vec<bool> = comparison.dupes.introduced().collect();
    let mut errors = false;
    let mut warnings = false;
    for (index, group) in duplication.clone_groups.iter().enumerate() {
        if new_only && !introduced.get(index).copied().unwrap_or(false) {
            continue;
        }
        match clone_group_severity(duplication.config, group) {
            Severity::Error => errors = true,
            Severity::Warn => warnings = true,
            Severity::Off => {}
        }
    }
    (errors, warnings)
}

fn verdict(
    gate: AuditGate,
    worsened: AuditWorsened,
    view: &AuditAnalysesView<'_>,
    comparison: &AuditComparison,
    summary: &AuditSummary,
) -> AuditVerdict {
    let new_only = matches!(gate, AuditGate::NewOnly);
    let dead_code_errors = if new_only {
        comparison.dead_code.has_introduced_errors()
    } else {
        dead_code_has_errors(view)
    };
    let dead_code_warnings = if new_only {
        comparison.dead_code.has_introduced_warnings()
    } else {
        comparison
            .dead_code
            .records()
            .iter()
            .any(|record| record.effective_severity == Severity::Warn)
    };
    // The `complexity-*` rules decide if a finding blocks: `error` fails the
    // verdict and `warn` gives `warn`. The `new-only` gate reads only the
    // introduced findings.
    let (complexity_errors, complexity_warnings) =
        complexity_verdict_flags(gate, worsened, view, comparison);
    let styling_errors = view.health.as_ref().is_some_and(|health| {
        health
            .report
            .styling_findings
            .iter()
            .zip(comparison.styling.introduced())
            .any(|(finding, introduced)| {
                (!new_only || introduced) && styling_finding_gates(health.rules, &finding.code)
            })
    });
    let (clone_errors, clone_warnings) = duplication_verdict_flags(new_only, view, comparison);
    // The threshold reads every counted group, also a group that the
    // `introduced-clone-group` rule turns off: the two gates are independent.
    let duplication_findings = if new_only {
        comparison.duplication_introduced_count()
    } else {
        summary.duplication_clone_groups
    };
    let duplication_errors = view.duplication.as_ref().is_some_and(|duplication| {
        duplication_findings > 0
            && duplication.threshold > 0.0
            && duplication.duplication_percentage > duplication.threshold
    });
    if dead_code_errors || complexity_errors || styling_errors || duplication_errors || clone_errors
    {
        AuditVerdict::Fail
    } else if dead_code_warnings || complexity_warnings || clone_warnings {
        AuditVerdict::Warn
    } else {
        AuditVerdict::Pass
    }
}

/// Whether the head dead-code findings hold an error-severity finding, by the
/// same rule that decides the exit code of `fallow dead-code`.
fn dead_code_has_errors(view: &AuditAnalysesView<'_>) -> bool {
    view.dead_code.as_ref().is_some_and(|dead_code| {
        fallow_engine::error_severity::has_error_severity_issues(
            dead_code.results,
            &dead_code.config.rules,
            Some(dead_code.config),
            false,
        )
    })
}

fn attribution(
    gate: AuditGate,
    worsened: AuditWorsened,
    comparison: &AuditComparison,
    has_base: bool,
) -> AuditAttribution {
    if !has_base {
        return AuditAttribution {
            gate,
            worsened,
            ..AuditAttribution::default()
        };
    }
    AuditAttribution {
        gate,
        worsened,
        complexity_worsened: comparison.complexity_worsened_count(),
        dead_code_introduced: comparison.dead_code.introduced_count(),
        dead_code_inherited: comparison.dead_code.inherited_count(),
        complexity_introduced: comparison.health.introduced_count(),
        complexity_inherited: comparison.health.inherited_count(),
        duplication_introduced: comparison.duplication_introduced_count(),
        duplication_inherited: comparison.duplication_inherited_count(),
    }
}

fn summary(view: &AuditAnalysesView<'_>, comparison: &AuditComparison) -> AuditSummary {
    AuditSummary {
        dead_code_issues: comparison.dead_code.visible_count(),
        dead_code_has_errors: dead_code_has_errors(view),
        dead_code_skipped: view.dead_code.is_none(),
        complexity_skipped: view.health.is_none(),
        duplication_skipped: view.duplication.is_none(),
        complexity_findings: view
            .health
            .as_ref()
            .map_or(0, |health| health.report.findings.len()),
        max_cyclomatic: view.health.as_ref().and_then(|health| {
            health
                .report
                .findings
                .iter()
                .map(|finding| finding.cyclomatic)
                .max()
        }),
        duplication_clone_groups: view
            .duplication
            .as_ref()
            .map_or(0, |duplication| duplication.clone_groups.len()),
    }
}