Skip to main content

fallow_engine/baseline/prune/
mod.rs

1//! Prune a saved baseline to the entries that still match a current finding.
2//!
3//! Each function keeps exactly the entries that `--baseline` matches for the
4//! same findings, in the old file order. A pruned file therefore hides the same
5//! findings as before, and `--fail-on-stale-baseline` finds no stale entry in
6//! it. Prune never adds an entry: a new finding stays outside the baseline, and
7//! the normal gates report it.
8
9use rustc_hash::FxHashMap;
10use std::path::Path;
11
12use fallow_output::BaselineMode;
13use fallow_types::identity::IdentityPaths;
14
15use super::{
16    BASELINE_KEY_SCHEME, BaselineData, BaselineFileKind, BaselineKind, DuplicationBaselineData,
17    HEALTH_FINDING_DIMENSIONS, HealthBaselineCount, HealthBaselineData, HealthBaselineMode,
18    HealthFindingCategory, HealthFindingCountMap, HealthMatch, canonical_keys,
19    classify_baseline_value, clone_group_fingerprint_key, consume_baseline_key,
20    health_finding_counts, match_health_baseline, severity_counts_for_dimension, severity_index,
21};
22use crate::duplicates::{CloneFingerprintSet, DuplicationReport};
23
24/// One baseline entry that matched no current finding.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct PrunedEntry {
27    /// The baseline field that held the entry, for example `unused_exports`.
28    /// A health count names the bucket field and the category, for example
29    /// `finding_counts.complexity_high`.
30    pub category: String,
31    /// The entry key as the file stores it.
32    pub key: String,
33    /// The number of occurrences removed under this key.
34    pub count: usize,
35}
36
37/// The result of pruning one baseline file.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct BaselinePrune {
40    /// Entries in the file before the prune, counted as `--baseline` counts
41    /// them for the stale-baseline check.
42    pub entries_before: usize,
43    /// Entries left after the prune.
44    pub entries_after: usize,
45    /// The removed entries, in file order.
46    pub removed: Vec<PrunedEntry>,
47    /// The new file content. `None` when nothing was removed, so the caller
48    /// leaves the file as it is.
49    pub content: Option<String>,
50}
51
52/// Why a baseline file cannot be pruned. The file stays as it is.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub enum BaselinePruneRefusal {
55    /// The file is not valid JSON or not a valid baseline of this kind.
56    Parse(String),
57    /// Another command saved the file, or nothing in it names this kind.
58    NotThisKind {
59        /// The command that saved the file, when the file names one.
60        saved_by: Option<BaselineKind>,
61    },
62    /// The file uses a key form from an older version, which prune cannot
63    /// match entry by entry.
64    LegacyKeys,
65    /// The file uses a key scheme that this version does not know.
66    UnknownKeyScheme(String),
67    /// The file was saved with another analysis identity, for example a
68    /// type-aware run. The fields that differ are listed.
69    IncompatibleIdentity(Vec<&'static str>),
70    /// The duplication baseline holds clone keys that older versions shared
71    /// between unrelated groups (issue #3290).
72    SharedCloneKeys,
73    /// The file has fields that this version does not know, probably from a
74    /// newer version. A rewrite would drop them.
75    UnknownFields(Vec<String>),
76    /// The file and the run differ in a mode that decides which findings exist.
77    /// A prune would remove entries that are valid in the mode of the file.
78    ScopeMismatch {
79        /// The channels the file records and this run does not use.
80        saved_only: BaselineMode,
81        /// The channels this run uses and the file does not record. A file
82        /// saved before the file recorded its scope reads the same as a file
83        /// saved without the channel.
84        run_only: BaselineMode,
85    },
86}
87
88impl BaselinePruneRefusal {
89    /// A stable token for machine output.
90    #[must_use]
91    pub const fn code(&self) -> &'static str {
92        match self {
93            Self::Parse(_) => "parse-error",
94            Self::NotThisKind { .. } => "not-this-kind",
95            Self::LegacyKeys => "legacy-keys",
96            Self::UnknownKeyScheme(_) => "unknown-key-scheme",
97            Self::IncompatibleIdentity(_) => "incompatible-identity",
98            Self::SharedCloneKeys => "shared-clone-keys",
99            Self::UnknownFields(_) => "unknown-fields",
100            Self::ScopeMismatch { .. } => "scope-mismatch",
101        }
102    }
103
104    /// A one-sentence reason for people.
105    #[must_use]
106    pub fn reason(&self) -> String {
107        match self {
108            Self::Parse(error) => format!("the file is not a valid baseline: {error}"),
109            Self::NotThisKind {
110                saved_by: Some(kind),
111            } => format!("`fallow {}` saved this file", kind.as_str()),
112            Self::NotThisKind { saved_by: None } => {
113                "nothing in the file names this baseline kind".to_owned()
114            }
115            Self::LegacyKeys => {
116                "the file uses an older key form that prune cannot match".to_owned()
117            }
118            Self::UnknownKeyScheme(scheme) => {
119                format!("the file uses the key scheme `{scheme}`, which this version does not know")
120            }
121            Self::IncompatibleIdentity(fields) => format!(
122                "the file was saved with another analysis mode ({})",
123                fields.join(", ")
124            ),
125            Self::SharedCloneKeys => {
126                "the file has clone keys that older versions shared between unrelated groups"
127                    .to_owned()
128            }
129            Self::UnknownFields(fields) => format!(
130                "the file has fields that this version does not know ({}); a newer fallow version probably saved it",
131                fields.join(", ")
132            ),
133            Self::ScopeMismatch {
134                saved_only,
135                run_only,
136            } => {
137                let mut facts = Vec::new();
138                if !saved_only.is_empty() {
139                    facts.push(format!(
140                        "the file was saved with {} and this run does not use it",
141                        saved_only.flags_prose()
142                    ));
143                }
144                if !run_only.is_empty() {
145                    facts.push(format!(
146                        "the file does not record {} and this run uses it",
147                        run_only.unrecorded_prose()
148                    ));
149                }
150                format!(
151                    "{}, so a prune would remove valid entries",
152                    facts.join(", and ")
153                )
154            }
155        }
156    }
157}
158
159/// Refuse a file with entries when the file and the run differ in a mode. A file
160/// with no entries has nothing to lose.
161fn check_saved_mode(
162    content: &str,
163    entries: usize,
164    run: BaselineMode,
165) -> Result<(), BaselinePruneRefusal> {
166    if entries == 0 {
167        return Ok(());
168    }
169    let saved = BaselineMode::from_saved_names(&super::saved_scope_reasons(content));
170    if saved == run {
171        return Ok(());
172    }
173    Err(BaselinePruneRefusal::ScopeMismatch {
174        saved_only: saved.minus(run),
175        run_only: run.minus(saved),
176    })
177}
178
179fn parse_own_kind(
180    content: &str,
181    kind: BaselineKind,
182) -> Result<serde_json::Value, BaselinePruneRefusal> {
183    let parsed = serde_json::from_str::<serde_json::Value>(content)
184        .map_err(|error| BaselinePruneRefusal::Parse(error.to_string()))?;
185    match classify_baseline_value(&parsed, kind) {
186        BaselineFileKind::Own | BaselineFileKind::NotAnObject => Ok(parsed),
187        other @ (BaselineFileKind::Foreign(_) | BaselineFileKind::Unrecognised) => {
188            Err(BaselinePruneRefusal::NotThisKind {
189                saved_by: other.saved_by(),
190            })
191        }
192    }
193}
194
195/// Parse the file and refuse it when a rewrite would drop a field with data.
196///
197/// The structs skip empty fields on save, so a field that is absent from the
198/// round trip is unknown only when the file holds data in it.
199fn parse_value<T: serde::de::DeserializeOwned + serde::Serialize>(
200    value: &serde_json::Value,
201) -> Result<T, BaselinePruneRefusal> {
202    let parsed =
203        T::deserialize(value).map_err(|error| BaselinePruneRefusal::Parse(error.to_string()))?;
204    let round_trip = serde_json::to_value(&parsed)
205        .map_err(|error| BaselinePruneRefusal::Parse(error.to_string()))?;
206    if let (Some(original), Some(known)) = (value.as_object(), round_trip.as_object()) {
207        let unknown: Vec<String> = original
208            .iter()
209            .filter(|(key, field)| {
210                key.as_str() != "kind" && !known.contains_key(key.as_str()) && !is_empty_json(field)
211            })
212            .map(|(key, _)| key.clone())
213            .collect();
214        if !unknown.is_empty() {
215            return Err(BaselinePruneRefusal::UnknownFields(unknown));
216        }
217    }
218    Ok(parsed)
219}
220
221fn is_empty_json(value: &serde_json::Value) -> bool {
222    match value {
223        serde_json::Value::Null => true,
224        serde_json::Value::Array(items) => items.is_empty(),
225        serde_json::Value::Object(fields) => fields.is_empty(),
226        serde_json::Value::String(text) => text.is_empty(),
227        serde_json::Value::Bool(_) | serde_json::Value::Number(_) => false,
228    }
229}
230
231fn serialize<T: serde::Serialize>(
232    baseline: &T,
233    trailing_newline: bool,
234) -> Result<String, BaselinePruneRefusal> {
235    let mut json = serde_json::to_string_pretty(baseline)
236        .map_err(|error| BaselinePruneRefusal::Parse(error.to_string()))?;
237    if trailing_newline {
238        json.push('\n');
239    }
240    Ok(json)
241}
242
243/// Keep the saved keys that a current key matches, one saved occurrence for
244/// each current occurrence, and record the rest.
245fn retain_matched(
246    saved: &mut Vec<String>,
247    current: &[String],
248    category: &str,
249    removed: &mut Vec<PrunedEntry>,
250) {
251    let mut remaining: FxHashMap<&str, usize> = FxHashMap::default();
252    for key in current {
253        *remaining.entry(key.as_str()).or_default() += 1;
254    }
255    saved.retain(|key| {
256        if consume_baseline_key(&mut remaining, key) {
257            return true;
258        }
259        removed.push(PrunedEntry {
260            category: category.to_owned(),
261            key: key.clone(),
262            count: 1,
263        });
264        false
265    });
266}
267
268/// Prune a dead-code baseline (the format `fallow dead-code --save-baseline`
269/// writes) against the results of a whole-project run.
270///
271/// # Errors
272///
273/// Returns [`BaselinePruneRefusal`] when the file is not a canonical dead-code
274/// baseline of the same analysis identity, or when `mode` differs from the mode
275/// the file records.
276pub fn prune_dead_code_baseline(
277    content: &str,
278    results: &crate::results::AnalysisResults,
279    root: &Path,
280    identity: &fallow_types::semantic::SemanticAnalysisIdentity,
281    mode: BaselineMode,
282) -> Result<BaselinePrune, BaselinePruneRefusal> {
283    let mut baseline: BaselineData =
284        parse_value(&parse_own_kind(content, BaselineKind::DeadCode)?)?;
285    match baseline.identity.as_deref() {
286        None => return Err(BaselinePruneRefusal::LegacyKeys),
287        Some(scheme) if scheme != BASELINE_KEY_SCHEME => {
288            return Err(BaselinePruneRefusal::UnknownKeyScheme(scheme.to_owned()));
289        }
290        Some(_) => {}
291    }
292    let incompatible = baseline.analysis_identity().incompatible_fields(identity);
293    if !incompatible.is_empty() {
294        return Err(BaselinePruneRefusal::IncompatibleIdentity(incompatible));
295    }
296
297    let entries_before = baseline.total_entries();
298    check_saved_mode(content, entries_before, mode)?;
299    let paths = IdentityPaths::new(root);
300    // A finding that the cascade filter hid still exists, so its entry stays.
301    let hidden = results.cascade.hidden.to_results();
302    let mut removed = Vec::new();
303    macro_rules! prune {
304        ($($field:ident),* $(,)?) => {
305            $({
306                let mut current = canonical_keys(&results.$field, &paths);
307                current.extend(canonical_keys(&hidden.$field, &paths));
308                retain_matched(
309                    &mut baseline.$field,
310                    &current,
311                    stringify!($field),
312                    &mut removed,
313                );
314            })*
315        };
316    }
317    with_baseline_fields!(prune);
318
319    let content = if removed.is_empty() {
320        None
321    } else {
322        baseline.kind = Some(BaselineKind::DeadCode);
323        Some(serialize(&baseline, true)?)
324    };
325    Ok(BaselinePrune {
326        entries_before,
327        entries_after: baseline.total_entries(),
328        removed,
329        content,
330    })
331}
332
333/// Prune a duplication baseline against the report of a whole-project run.
334///
335/// The three key arrays of the format hold one row for each clone group. A row
336/// stays when its normalized key matches a current group, and the older arrays
337/// lose the same rows so they stay aligned.
338///
339/// # Errors
340///
341/// Returns [`BaselinePruneRefusal`] when the file is not a duplication baseline
342/// with normalized keys, when it holds the shared clone keys of issue #3290, or
343/// when `production` differs from the mode the file records.
344pub fn prune_dupes_baseline(
345    content: &str,
346    report: &DuplicationReport,
347    production: bool,
348) -> Result<BaselinePrune, BaselinePruneRefusal> {
349    let mut baseline: DuplicationBaselineData =
350        parse_value(&parse_own_kind(content, BaselineKind::Dupes)?)?;
351    if baseline.has_unparsed_collision_keys() {
352        return Err(BaselinePruneRefusal::SharedCloneKeys);
353    }
354    let entries_before = baseline.entry_count();
355    if baseline.normalized_clone_fingerprints.is_empty() {
356        if entries_before == 0 {
357            return Ok(BaselinePrune {
358                entries_before,
359                entries_after: 0,
360                removed: Vec::new(),
361                content: None,
362            });
363        }
364        return Err(BaselinePruneRefusal::LegacyKeys);
365    }
366    check_saved_mode(
367        content,
368        entries_before,
369        BaselineMode {
370            production,
371            include_entry_exports: false,
372        },
373    )?;
374
375    let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
376    let current: Vec<String> = report
377        .clone_groups
378        .iter()
379        .map(|group| clone_group_fingerprint_key(group, &fingerprints))
380        .collect();
381    let mut remaining: FxHashMap<&str, usize> = FxHashMap::default();
382    for key in &current {
383        *remaining.entry(key.as_str()).or_default() += 1;
384    }
385    let keep: Vec<bool> = baseline
386        .normalized_clone_fingerprints
387        .iter()
388        .map(|key| consume_baseline_key(&mut remaining, key))
389        .collect();
390    let removed: Vec<PrunedEntry> = baseline
391        .normalized_clone_fingerprints
392        .iter()
393        .zip(&keep)
394        .filter(|(_, kept)| !**kept)
395        .map(|(key, _)| PrunedEntry {
396            category: "normalized_clone_fingerprints".to_owned(),
397            key: key.clone(),
398            count: 1,
399        })
400        .collect();
401    if removed.is_empty() {
402        return Ok(BaselinePrune {
403            entries_before,
404            entries_after: entries_before,
405            removed,
406            content: None,
407        });
408    }
409
410    let rows = keep.len();
411    retain_rows(&mut baseline.normalized_clone_fingerprints, &keep);
412    // A hand-edited file can break the row alignment. Older binaries read the
413    // older arrays only, so leave a misaligned array as it is.
414    if baseline.clone_groups.len() == rows {
415        retain_rows(&mut baseline.clone_groups, &keep);
416    }
417    if baseline.clone_fingerprints.len() == rows {
418        retain_rows(&mut baseline.clone_fingerprints, &keep);
419    }
420    baseline.kind = Some(BaselineKind::Dupes);
421    Ok(BaselinePrune {
422        entries_before,
423        entries_after: baseline.entry_count(),
424        removed,
425        content: Some(serialize(&baseline, false)?),
426    })
427}
428
429fn retain_rows(rows: &mut Vec<String>, keep: &[bool]) {
430    let mut index = 0;
431    rows.retain(|_| {
432        let kept = keep[index];
433        index += 1;
434        kept
435    });
436}
437
438/// Prune a health baseline against the findings of a whole-project run.
439///
440/// `finding_counts` and `identity_finding_counts` lose the slots that matched
441/// no current finding. Identity buckets follow a moved file as `--baseline`
442/// does and keep their saved key. A placeholder bucket keeps a slot that
443/// covers a named function of its file. An emptied identity bucket stays as an
444/// empty map when the run reports its key, so the move matching does not
445/// change. The runtime-coverage keys and the refactoring target keys stay as
446/// they are, because this run does not compute them.
447///
448/// # Errors
449///
450/// Returns [`BaselinePruneRefusal`] when the file is not a health baseline with
451/// count buckets.
452pub fn prune_health_baseline(
453    content: &str,
454    findings: &[fallow_output::ComplexityViolation],
455    root: &Path,
456    production: bool,
457) -> Result<BaselinePrune, BaselinePruneRefusal> {
458    let mut baseline: HealthBaselineData =
459        parse_value(&parse_own_kind(content, BaselineKind::Health)?)?;
460    if baseline.finding_counts.is_empty() && !baseline.findings.is_empty() {
461        return Err(BaselinePruneRefusal::LegacyKeys);
462    }
463    let entries_before = baseline.finding_entry_count();
464    check_saved_mode(
465        content,
466        entries_before,
467        BaselineMode {
468            production,
469            include_entry_exports: false,
470        },
471    )?;
472
473    let mut removed = Vec::new();
474    let counting = baseline.file_length_counting();
475    let current_counts = health_finding_counts(findings, root, HealthBaselineMode::Count, counting);
476    let matched = match_health_baseline(
477        &baseline.finding_counts,
478        &current_counts,
479        HealthBaselineMode::Count,
480        root,
481    );
482    prune_count_buckets(
483        &mut baseline.finding_counts,
484        &matched,
485        "finding_counts",
486        &mut removed,
487    );
488    baseline
489        .finding_counts
490        .retain(|_, counts| !counts.is_empty());
491    if !baseline.identity_finding_counts.is_empty() {
492        let current_identity =
493            health_finding_counts(findings, root, HealthBaselineMode::Identity, counting);
494        let matched = match_health_baseline(
495            &baseline.identity_finding_counts,
496            &current_identity,
497            HealthBaselineMode::Identity,
498            root,
499        );
500        prune_count_buckets(
501            &mut baseline.identity_finding_counts,
502            &matched,
503            "identity_finding_counts",
504            &mut removed,
505        );
506        // A saved identity key that the run also reports is never a move
507        // candidate. Dropping its emptied bucket would make it one, and a
508        // second candidate with the same function name stops another bucket
509        // from following its move. So the key stays, with no slots.
510        baseline
511            .identity_finding_counts
512            .retain(|key, counts| !counts.is_empty() || current_identity.contains_key(key));
513    }
514
515    let content = if removed.is_empty() {
516        None
517    } else {
518        baseline.kind = Some(BaselineKind::Health);
519        Some(serialize(&baseline, false)?)
520    };
521    Ok(BaselinePrune {
522        entries_before,
523        entries_after: baseline.finding_entry_count(),
524        removed,
525        content,
526    })
527}
528
529/// Reduce each saved bucket to the slots that the `--baseline` match uses.
530fn prune_count_buckets(
531    saved: &mut HealthFindingCountMap,
532    matched: &HealthMatch,
533    field: &str,
534    removed: &mut Vec<PrunedEntry>,
535) {
536    for (bucket, saved_counts) in saved.iter_mut() {
537        for dimension in HEALTH_FINDING_DIMENSIONS {
538            let baseline = severity_counts_for_dimension(Some(saved_counts), dimension);
539            for severity in [
540                fallow_output::FindingSeverity::Moderate,
541                fallow_output::FindingSeverity::High,
542                fallow_output::FindingSeverity::Critical,
543            ] {
544                let index = severity_index(severity);
545                let category = HealthFindingCategory {
546                    dimension,
547                    severity,
548                }
549                .key();
550                let used = matched.used_slots(bucket, category);
551                if used == baseline[index] {
552                    continue;
553                }
554                removed.push(PrunedEntry {
555                    category: format!("{field}.{category}"),
556                    key: bucket.clone(),
557                    count: baseline[index] - used,
558                });
559                if used == 0 {
560                    saved_counts.remove(category);
561                } else {
562                    saved_counts.insert(category.to_owned(), HealthBaselineCount { count: used });
563                }
564            }
565        }
566    }
567}
568
569#[cfg(test)]
570mod tests;