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