Skip to main content

targeted_mutation/
report.rs

1//! Turns planner results into findings a person can act on: which wrong implementation
2//! survives, and which input or assertion would catch it.
3
4use serde::Serialize;
5use std::path::PathBuf;
6
7use crate::instrument::{ArithOp, LiteralSide, Site, SiteKind};
8use crate::plan::{CmpOp, InputGap, LogicGap, Mutation, Obs};
9
10#[derive(Clone, Debug, Default, PartialEq, Serialize)]
11pub struct Location {
12    pub file: String,
13    pub line: usize,
14    pub column: usize,
15    pub code: String,
16    /// The function or constant the code is in (`Store::commit`); empty where unknown.
17    #[serde(skip_serializing_if = "String::is_empty")]
18    pub item: String,
19    /// What the finding at this place is known by across runs: see [`finding_id`].
20    #[serde(skip_serializing_if = "String::is_empty")]
21    pub id: String,
22}
23
24/// The name a finding keeps from run to run: its kind, its file, the item it is in, its
25/// code, and which of the places with that code in that item it is (0 for the first).
26/// Lines are not in it, so code that moves keeps its name, and neither are the words
27/// that describe the surviving mutants, so those can be improved.
28pub fn finding_id(kind: &str, at: &Location, nth: usize) -> String {
29    format!("{kind}|{}|{}|{}|{nth}", at.file, at.item, at.code)
30}
31
32#[derive(Clone, Debug, PartialEq, Serialize)]
33#[serde(rename_all = "snake_case", tag = "kind")]
34pub enum Finding {
35    /// No test input can tell these mutants from the original.
36    InputGap {
37        #[serde(flatten)]
38        at: Location,
39        /// Source-level form of mutants that pass every test.
40        survivors: Vec<String>,
41        /// How many mutants the gap lets through in total.
42        survivor_count: u128,
43        /// Inputs to add, in words.
44        add_tests: Vec<String>,
45        /// What the tests did feed the comparison.
46        observed: Option<String>,
47        /// Whether the tests were re-run against a survivor to confirm.
48        verified: bool,
49    },
50    /// Tests execute the changed behaviour, and still pass.
51    AssertionGap {
52        #[serde(flatten)]
53        at: Location,
54        survivors: Vec<String>,
55        /// Tests whose execution changed under the mutants but did not fail.
56        tests: Vec<String>,
57        /// What one surviving mutant changes later in those tests: the places an
58        /// assertion could catch it. Empty when that was not looked into.
59        effects: Vec<String>,
60        /// The mutant whose effects those are, as it is written in `survivors`.
61        effects_of: Option<String>,
62    },
63    /// A mutant that was built on its own passes every test, and nothing was recorded
64    /// that says why: whether no test runs the code (nothing can be recorded in a
65    /// `const fn`), or one does and does not look at the result.
66    Survivor {
67        #[serde(flatten)]
68        at: Location,
69        survivors: Vec<String>,
70    },
71}
72
73impl Finding {
74    pub fn at(&self) -> &Location {
75        let (Finding::InputGap { at, .. }
76        | Finding::AssertionGap { at, .. }
77        | Finding::Survivor { at, .. }) = self;
78        at
79    }
80
81    pub fn at_mut(&mut self) -> &mut Location {
82        let (Finding::InputGap { at, .. }
83        | Finding::AssertionGap { at, .. }
84        | Finding::Survivor { at, .. }) = self;
85        at
86    }
87
88    pub fn survivors(&self) -> &[String] {
89        let (Finding::InputGap { survivors, .. }
90        | Finding::AssertionGap { survivors, .. }
91        | Finding::Survivor { survivors, .. }) = self;
92        survivors
93    }
94
95    /// The kind as the JSON report and the names of findings spell it.
96    pub fn kind(&self) -> &'static str {
97        match self {
98            Finding::InputGap { .. } => "input_gap",
99            Finding::AssertionGap { .. } => "assertion_gap",
100            Finding::Survivor { .. } => "survivor",
101        }
102    }
103}
104
105/// What decides which code cargo compiles, as given on the command line.
106#[derive(Clone, Debug, Default, PartialEq, Serialize)]
107pub struct CargoConfig {
108    pub features: Vec<String>,
109    pub all_features: bool,
110    pub no_default_features: bool,
111    pub locked: bool,
112}
113
114/// What a run looked at and how: a report says nothing about what is outside of it.
115#[derive(Clone, Debug, Default, PartialEq, Serialize)]
116pub struct Analysis {
117    /// The package's directory in its git repository (`crates/core/`; empty at the top).
118    pub package_path: String,
119    /// Only the code changed since this revision.
120    pub since: Option<String>,
121    /// Only these lines.
122    pub lines: Vec<String>,
123    /// The packages whose tests were run.
124    pub tests_of: Vec<String>,
125    pub cargo: CargoConfig,
126    pub opt_level: Option<u8>,
127    /// Mutants that need a build of their own were run.
128    pub rebuild: bool,
129    /// Predicted survivors were re-run.
130    pub verified: bool,
131    pub doc_tests: bool,
132    #[serde(skip_serializing_if = "std::ops::Not::not")]
133    pub source_only: bool,
134    #[serde(skip_serializing_if = "Option::is_none")]
135    pub test_selection: Option<TestSelection>,
136    #[serde(skip_serializing_if = "std::ops::Not::not")]
137    pub git_index: bool,
138    #[serde(skip_serializing_if = "Vec::is_empty")]
139    pub copy_fixtures: Vec<PathBuf>,
140}
141
142#[derive(Clone, Debug, Default, PartialEq, Serialize)]
143pub struct TestSelection {
144    pub build_scope: TestBuildScope,
145    pub wrapper: Option<String>,
146    pub tests: Vec<String>,
147}
148
149#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
150#[serde(rename_all = "snake_case")]
151pub enum TestBuildScope {
152    #[default]
153    PackageWide,
154    SelectedTargets,
155}
156
157#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
158#[serde(rename_all = "snake_case")]
159pub enum Evaluation {
160    NoSites,
161    NoMutantsExecuted,
162}
163
164#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
165#[serde(rename_all = "snake_case")]
166pub enum SkipReason {
167    ProbeCompileError,
168    ProbeReplacedBySourceRebuild,
169    RequiresSourceRebuild,
170    UnparseableSource,
171}
172
173#[derive(Clone, Debug, PartialEq, Serialize)]
174pub struct SkippedSite {
175    #[serde(flatten)]
176    pub at: Location,
177    pub end_line: usize,
178    pub end_column: usize,
179    pub reason: SkipReason,
180    #[serde(skip_serializing_if = "Option::is_none")]
181    pub diagnostic: Option<String>,
182}
183
184impl SkippedSite {
185    pub(crate) fn new(
186        at: Location,
187        source: &str,
188        end: usize,
189        reason: SkipReason,
190        diagnostic: Option<String>,
191    ) -> Self {
192        let before = source.get(..end).unwrap_or(source);
193        let end_line = crate::scope::line_of(before, before.len());
194        let end_column = before.rsplit('\n').next().unwrap_or("").chars().count() + 1;
195        Self {
196            at,
197            end_line,
198            end_column,
199            reason,
200            diagnostic,
201        }
202    }
203}
204
205/// What a run that was asked to check itself found (`--audit`).
206#[derive(Clone, Debug, Default, PartialEq, Serialize)]
207pub struct Audit {
208    /// Surviving mutants that were run once more, against every test of every binary.
209    pub sampled: usize,
210    /// How many surviving mutants there were to choose from.
211    pub survivors: usize,
212    /// Where one of those failed a test it had not been run against: the tests were not
213    /// chosen as they should have been, or do not always do the same.
214    pub disagreements: Vec<Location>,
215    /// Test binaries whose second recorded run was not like the first, with the number
216    /// of records (what one test saw at one site) that differ.
217    pub trace_differences: Vec<TraceDifference>,
218    /// Mutants that were run as probes and chosen to be built from the source as well.
219    pub rebuilt: usize,
220    /// Of those, the ones that built and whose two results could be compared.
221    pub compared: usize,
222    /// And the ones that did not build (or whose probe run could not be evaluated):
223    /// nothing is known about them.
224    pub not_compared: usize,
225    /// Where the two did not agree on whether the tests pass.
226    pub source_disagreements: Vec<SourceDisagreement>,
227}
228
229/// A mutant on which its probe and its source form do not agree.
230#[derive(Clone, Debug, Default, PartialEq, Serialize)]
231pub struct SourceDisagreement {
232    #[serde(flatten)]
233    pub at: Location,
234    pub mutant: String,
235    /// `passes` or `fails`: what the tests did with the probe, and with the source.
236    pub as_probe: String,
237    pub built: String,
238}
239
240#[derive(Clone, Debug, Default, PartialEq, Serialize)]
241pub struct TraceDifference {
242    pub binary: String,
243    pub records: usize,
244}
245
246#[derive(Clone, Debug, Default, PartialEq, Serialize)]
247pub struct Report {
248    pub package: String,
249    pub analysis: Analysis,
250    /// Present when the run was asked to check itself.
251    #[serde(skip_serializing_if = "Option::is_none")]
252    pub audit: Option<Audit>,
253    #[serde(skip_serializing_if = "Option::is_none")]
254    pub evaluation: Option<Evaluation>,
255    pub sites: usize,
256    /// Sites that could not be instrumented (the probe did not compile there).
257    pub skipped_sites: usize,
258    #[serde(skip_serializing_if = "Vec::is_empty")]
259    pub skipped: Vec<SkippedSite>,
260    /// Values a function's body was to be replaced by that do not have its type
261    /// (`Default::default()` for a type without a default): those mutants do not exist.
262    pub unviable_mutants: usize,
263    /// Mutants that need a build of their own and were not asked for (`--rebuild`).
264    pub mutants_not_built: usize,
265    /// Mutants that could not be run as what they are (a range that ends at the largest
266    /// value of its type cannot be made to include it): neither killed nor survivors.
267    pub mutants_not_evaluated: usize,
268    pub mutants_run: usize,
269    pub mutants_killed: usize,
270    /// Killed mutants that were stopped by the timeout (typically an endless loop).
271    pub mutants_timed_out: usize,
272    pub findings: Vec<Finding>,
273    /// Findings left out because of a `// tmt:ignore` comment or the baseline.
274    pub suppressed: usize,
275    /// Code no test executes.
276    pub unreached: Vec<Location>,
277    /// Survivors predicted from the trace that a re-run killed: the tests are not deterministic.
278    pub unstable: Vec<Location>,
279}
280
281impl Report {
282    pub(crate) fn record_evaluation(&mut self) {
283        self.evaluation = match (self.sites, self.mutants_run, self.skipped.is_empty()) {
284            (_, 1.., _) => None,
285            (0, 0, true) => Some(Evaluation::NoSites),
286            _ => Some(Evaluation::NoMutantsExecuted),
287        };
288    }
289
290    /// Puts the findings in reading order. Sites are numbered as they are discovered, and
291    /// a statement is discovered before the expressions of the statements above it.
292    pub fn sort_findings(&mut self) {
293        self.findings.sort_by(|a, b| {
294            let key = |finding: &Finding| {
295                let at = finding.at();
296                (at.file.clone(), at.line, at.column)
297            };
298            key(a).cmp(&key(b))
299        });
300    }
301
302    /// Whether the run found something to act on: a gap, or a prediction that did not
303    /// hold (which means the report cannot be trusted as it stands).
304    pub fn has_gaps(&self) -> bool {
305        !self.findings.is_empty() || !self.unstable.is_empty()
306    }
307}
308
309pub fn location(file: &str, site: &Site) -> Location {
310    Location {
311        file: file.to_string(),
312        line: site.line,
313        column: site.column,
314        code: one_line(&site.text),
315        ..Location::default()
316    }
317}
318
319fn one_line(code: &str) -> String {
320    let joined = code.split_whitespace().collect::<Vec<_>>().join(" ");
321    if joined.chars().count() > 100 {
322        format!("{}...", joined.chars().take(97).collect::<String>())
323    } else {
324        joined
325    }
326}
327
328/// Value of a float literal such as `30.5`, `1e3` or `2.5_f32`.
329fn float_literal(text: &str) -> Option<f64> {
330    let text = text.trim().replace('_', "");
331    let text = text
332        .strip_suffix("f32")
333        .or(text.strip_suffix("f64"))
334        .unwrap_or(&text);
335    let looks_numeric = text.starts_with(|c: char| c.is_ascii_digit() || c == '-')
336        && text
337            .chars()
338            .all(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E'));
339    if looks_numeric {
340        text.parse().ok()
341    } else {
342        None
343    }
344}
345
346/// Floats in reports: the shortest text that reads back as the same value, so nothing is
347/// rounded away.
348fn show_float(v: f64) -> String {
349    format!("{v:?}")
350}
351
352/// Source-level form of a mutant.
353pub fn describe(site: &Site, m: Mutation) -> String {
354    match &site.kind {
355        SiteKind::Stmt => format!("delete `{}`", one_line(&site.text)),
356        SiteKind::Neg { operand, .. } => format!("`{}`", one_line(operand)),
357        SiteKind::Guard { .. } => match m {
358            Mutation::Const(value) => {
359                format!("the guard `{}` replaced by `{value}`", one_line(&site.text))
360            }
361            _ => format!("another guard than `{}`", one_line(&site.text)),
362        },
363        SiteKind::Field { from_base, .. } => format!(
364            "without the field `{}` (it is then `{from_base}`)",
365            one_line(&site.text)
366        ),
367        SiteKind::Body { name, value, .. } => format!("the body of `{name}` replaced by `{value}`"),
368        SiteKind::Not { operand, .. } => format!("`{}`", one_line(operand)),
369        SiteKind::Return { name, option, .. } => match (m, option) {
370            (Mutation::Const(false), Some(_)) => format!("`{name}` returning `None`"),
371            (Mutation::Const(value), _) => format!("`{name}` returning `{value}`"),
372            _ => format!("`{name}` returning something else"),
373        },
374        SiteKind::Range {
375            inclusive,
376            lhs,
377            rhs,
378            ..
379        } => {
380            let dots = if *inclusive { ".." } else { "..=" };
381            format!("`{}{dots}{}`", one_line(lhs), one_line(rhs))
382        }
383        SiteKind::Arm { pattern, .. } => format!("remove the arm `{} => ..`", one_line(pattern)),
384        SiteKind::MinMax {
385            max,
386            receiver,
387            argument,
388            ..
389        } => {
390            let other = if *max { "min" } else { "max" };
391            format!("`{}.{other}({})`", one_line(receiver), one_line(argument))
392        }
393        SiteKind::Logic { and, lhs, rhs, .. } => {
394            let (lhs, rhs) = (one_line(lhs), one_line(rhs));
395            match m {
396                // Both operands are still evaluated whenever the original evaluates them;
397                // only the value of one is ignored. The forms below say exactly that.
398                Mutation::LogicDropRhs if *and => format!("`{lhs} && {{ {rhs}; true }}`"),
399                Mutation::LogicDropRhs => format!("`{lhs} || {{ {rhs}; false }}`"),
400                Mutation::LogicDropLhs => format!("`{{ {lhs}; {rhs} }}`"),
401                _ => format!("`{lhs} {} {rhs}`", if *and { "||" } else { "&&" }),
402            }
403        }
404        SiteKind::Arith {
405            op,
406            assign,
407            lhs,
408            rhs,
409            ..
410        } => {
411            let eq = if *assign { "=" } else { "" };
412            let other = match m {
413                Mutation::ArithSwap2 => op.swapped2().unwrap_or(op.swapped()),
414                _ => op.swapped(),
415            };
416            format!(
417                "`{} {}{eq} {}`",
418                one_line(lhs),
419                other.symbol(),
420                one_line(rhs)
421            )
422        }
423        SiteKind::Cmp {
424            op,
425            lhs,
426            rhs,
427            literal,
428            ..
429        } => {
430            let (lhs, rhs) = (one_line(lhs), one_line(rhs));
431            let sym = op.symbol();
432            match m {
433                Mutation::Const(c) => format!("`{c}`"),
434                Mutation::Op(op2) => format!("`{lhs} {} {rhs}`", op2.symbol()),
435                Mutation::Shift(d) => match literal {
436                    LiteralSide::Rhs(k) => format!("`{lhs} {sym} {}`", k + d),
437                    // k op rhs + d  <=>  k - d op rhs
438                    LiteralSide::Lhs(k) => format!("`{} {sym} {rhs}`", k - d),
439                    LiteralSide::None => match (op, d) {
440                        (CmpOp::Ge, 1) => format!("`{lhs} > {rhs}`"),
441                        (CmpOp::Gt, -1) => format!("`{lhs} >= {rhs}`"),
442                        (CmpOp::Le, -1) => format!("`{lhs} < {rhs}`"),
443                        (CmpOp::Lt, 1) => format!("`{lhs} <= {rhs}`"),
444                        // Meant as arithmetic on whole numbers: in the operands' own
445                        // type the addition could overflow, the mutant that was run cannot.
446                        // tmt:ignore a shift of 0 is never planned, so `>=` is the same
447                        (_, d) if d > 0 => format!("`{lhs} {sym} {rhs} + {d}` (without overflow)"),
448                        (_, d) => format!("`{lhs} {sym} {rhs} - {}` (without overflow)", -d),
449                    },
450                },
451                Mutation::ShiftF(d) => match (float_literal(&lhs), float_literal(&rhs)) {
452                    (None, Some(k)) => format!("`{lhs} {sym} {}`", show_float(k + d)),
453                    (Some(k), None) => format!("`{} {sym} {rhs}`", show_float(k - d)),
454                    // tmt:ignore a shift of 0 is never planned, so any threshold near it is the same
455                    _ if d > 0.0 => format!("`{lhs} {sym} {rhs} + {}`", show_float(d)),
456                    _ => format!("`{lhs} {sym} {rhs} - {}`", show_float(-d)),
457                },
458                _ => format!("`!({lhs} {sym} {rhs})`"),
459            }
460        }
461    }
462}
463
464/// The operand values that give `lhs - rhs = d`, in words.
465fn input_for(lhs: &str, rhs: &str, literal: LiteralSide, d: i128) -> String {
466    match (literal, d) {
467        (LiteralSide::Rhs(k), d) => format!("`{lhs}` = {}", k + d),
468        (LiteralSide::Lhs(k), d) => format!("`{rhs}` = {}", k - d),
469        (LiteralSide::None, 0) => format!("`{lhs}` equal to `{rhs}`"),
470        // tmt:ignore 0 is taken by the arm above, so `>=` is the same
471        (LiteralSide::None, d) if d > 0 => format!("`{lhs}` = `{rhs}` + {d}"),
472        (LiteralSide::None, d) => format!("`{lhs}` = `{rhs}` - {}", -d),
473    }
474}
475
476fn observed_values(lhs: &str, rhs: &str, literal: LiteralSide, obs: &Obs) -> Option<String> {
477    if !obs.valued() {
478        return None;
479    }
480    let ds: Vec<i128> = [obs.max_neg, obs.eq.then_some(0), obs.min_pos]
481        .into_iter()
482        .flatten()
483        .collect();
484    let text = match literal {
485        LiteralSide::Rhs(k) => {
486            let values: Vec<String> = ds.iter().map(|d| (k + d).to_string()).collect();
487            format!("`{lhs}` = {}", values.join(", "))
488        }
489        LiteralSide::Lhs(k) => {
490            let mut values: Vec<i128> = ds.iter().map(|d| k - d).collect();
491            values.sort();
492            let values: Vec<String> = values.iter().map(i128::to_string).collect();
493            format!("`{rhs}` = {}", values.join(", "))
494        }
495        LiteralSide::None => {
496            let values: Vec<String> = ds.iter().map(i128::to_string).collect();
497            format!("`{lhs}` - `{rhs}` = {}", values.join(", "))
498        }
499    };
500    Some(format!("nearest values the tests passed: {text}"))
501}
502
503/// Builds the input-gap finding for a comparison site. `None` for gaps that are reported
504/// elsewhere (unreached code).
505pub fn input_gap_finding(
506    file: &str,
507    site: &Site,
508    gap: &InputGap,
509    obs: &Obs,
510    verified: bool,
511) -> Option<Finding> {
512    let SiteKind::Cmp {
513        op,
514        lhs,
515        rhs,
516        literal,
517        ..
518    } = &site.kind
519    else {
520        return None;
521    };
522    let (lhs_text, rhs_text) = (one_line(lhs), one_line(rhs));
523    // A float shift too small to move the literal is not a different program. The
524    // literal moves the way `describe` writes it.
525    let moves = |d: f64| match (float_literal(&lhs_text), float_literal(&rhs_text)) {
526        (None, Some(k)) => k + d != k,
527        (Some(k), None) => k - d != k,
528        _ => true,
529    };
530    let survivors: Vec<String> = gap
531        .survivors()
532        .into_iter()
533        .filter(|m| !matches!(m, Mutation::ShiftF(d) if !moves(*d)))
534        .map(|m| describe(site, m))
535        .collect();
536    let mut observed = observed_values(&lhs_text, &rhs_text, *literal, obs);
537    let (survivor_count, add_tests) = match gap {
538        InputGap::Unreached => return None,
539        InputGap::OneSided { always } => (
540            1,
541            vec![format!(
542                "an input that makes `{}` {}",
543                one_line(&site.text),
544                !always
545            )],
546        ),
547        InputGap::EqualNeverObserved { flipped, float_gap } => {
548            if let Some((lo, hi)) = float_gap {
549                observed = Some(match (float_literal(&lhs_text), float_literal(&rhs_text)) {
550                    (None, Some(k)) => format!(
551                        "nearest values the tests passed: `{lhs_text}` = {}, {}; any threshold between them passes",
552                        show_float(k + lo),
553                        show_float(k + hi)
554                    ),
555                    (Some(k), None) => format!(
556                        "nearest values the tests passed: `{rhs_text}` = {}, {}; any threshold between them passes",
557                        show_float(k - hi),
558                        show_float(k - lo)
559                    ),
560                    _ => format!(
561                        "nearest values the tests passed: `{lhs_text}` - `{rhs_text}` = {}, {}",
562                        show_float(*lo),
563                        show_float(*hi)
564                    ),
565                });
566            }
567            (
568                survivors.len() as u128,
569                vec![format!(
570                    "`{lhs_text}` equal to `{rhs_text}` (the original gives {}, the mutant {})",
571                    op.eval_d(0),
572                    flipped.eval_d(0)
573                )],
574            )
575        }
576        InputGap::Boundary {
577            min_shift,
578            max_shift,
579            missing,
580        } => {
581            let add = missing
582                .iter()
583                .map(|d| {
584                    format!(
585                        "{} (the original gives {})",
586                        input_for(&lhs_text, &rhs_text, *literal, *d),
587                        op.eval_d(*d)
588                    )
589                })
590                .collect();
591            ((max_shift - min_shift) as u128, add)
592        }
593    };
594    Some(Finding::InputGap {
595        at: location(file, site),
596        survivors,
597        survivor_count,
598        add_tests,
599        observed,
600        verified,
601    })
602}
603
604/// Input gap at `a && b` / `a || b`: one operand never decides the result in any test.
605pub fn logic_gap_finding(
606    file: &str,
607    site: &Site,
608    gap: LogicGap,
609    verified: bool,
610) -> Option<Finding> {
611    let SiteKind::Logic { and, lhs, rhs, .. } = &site.kind else {
612        return None;
613    };
614    let (lhs, rhs) = (one_line(lhs), one_line(rhs));
615    let (mutation, add) = match (gap, and) {
616        (LogicGap::Unreached, _) => return None,
617        (LogicGap::RhsNeverDecides, true) => (
618            Mutation::LogicDropRhs,
619            format!("a case where `{lhs}` is true and `{rhs}` is false"),
620        ),
621        (LogicGap::RhsNeverDecides, false) => (
622            Mutation::LogicDropRhs,
623            format!("a case where `{lhs}` is false and `{rhs}` is true"),
624        ),
625        (LogicGap::LhsNeverDecides, true) => (
626            Mutation::LogicDropLhs,
627            format!("a case where `{lhs}` is false"),
628        ),
629        (LogicGap::LhsNeverDecides, false) => (
630            Mutation::LogicDropLhs,
631            format!("a case where `{lhs}` is true"),
632        ),
633    };
634    Some(Finding::InputGap {
635        at: location(file, site),
636        survivors: vec![describe(site, mutation)],
637        survivor_count: 1,
638        add_tests: vec![add],
639        observed: None,
640        verified,
641    })
642}
643
644/// Input gap at `a.max(b)` / `a.min(b)`: the two operands were equal in every test.
645pub fn min_max_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
646    let SiteKind::MinMax {
647        receiver, argument, ..
648    } = &site.kind
649    else {
650        return None;
651    };
652    Some(Finding::InputGap {
653        at: location(file, site),
654        survivors: vec![describe(site, Mutation::MinMax)],
655        survivor_count: 1,
656        add_tests: vec![format!(
657            "`{}` different from `{}`",
658            one_line(receiver),
659            one_line(argument)
660        )],
661        observed: None,
662        verified,
663    })
664}
665
666/// Input gap at a `-> bool` function that returned the same value in every test.
667pub fn return_gap_finding(
668    file: &str,
669    site: &Site,
670    always: bool,
671    verified: bool,
672) -> Option<Finding> {
673    let SiteKind::Return { name, option, .. } = &site.kind else {
674        return None;
675    };
676    let other = match (option, always) {
677        (None, always) => format!("{}", !always),
678        (Some(_), false) => "`Some`".to_string(),
679        (Some(_), true) => "`None`".to_string(),
680    };
681    Some(Finding::InputGap {
682        at: location(file, site),
683        survivors: vec![describe(site, Mutation::Const(always))],
684        survivor_count: 1,
685        add_tests: vec![format!("a case where `{name}` returns {other}")],
686        observed: None,
687        verified,
688    })
689}
690
691/// Input gap at the guard of a match arm that had the same value in every test.
692pub fn guard_gap_finding(file: &str, site: &Site, always: bool, verified: bool) -> Finding {
693    Finding::InputGap {
694        at: location(file, site),
695        survivors: vec![describe(site, Mutation::Const(always))],
696        survivor_count: 1,
697        add_tests: vec![format!(
698            "a case where the guard `{}` is {}",
699            one_line(&site.text),
700            !always
701        )],
702        observed: None,
703        verified,
704    }
705}
706
707/// Input gap at an arithmetic operator: the swapped operator computes the same value on
708/// every pair of operands the tests pass.
709pub fn arith_gap_finding(
710    file: &str,
711    site: &Site,
712    mutation: Mutation,
713    verified: bool,
714) -> Option<Finding> {
715    let SiteKind::Arith {
716        op,
717        assign,
718        lhs,
719        rhs,
720        ..
721    } = &site.kind
722    else {
723        return None;
724    };
725    let (lhs, rhs) = (one_line(lhs), one_line(rhs));
726    let eq = if *assign { "=" } else { "" };
727    let other = match mutation {
728        Mutation::ArithSwap2 => op.second(*assign)?,
729        _ => op.swapped(),
730    };
731    let add = match (op, other) {
732        (ArithOp::Add, ArithOp::Sub) | (ArithOp::Sub, ArithOp::Add) => {
733            format!("`{rhs}` other than 0")
734        }
735        _ => format!(
736            "operands for which `{lhs} {}{eq} {rhs}` and `{lhs} {}{eq} {rhs}` differ",
737            op.symbol(),
738            other.symbol()
739        ),
740    };
741    Some(Finding::InputGap {
742        at: location(file, site),
743        survivors: vec![describe(site, mutation)],
744        survivor_count: 1,
745        add_tests: vec![add],
746        observed: None,
747        verified,
748    })
749}
750
751/// The report as SARIF 2.1.0, for code scanning UIs. `prefix` is put in front of the file
752/// names (the package's path inside the repository).
753/// SARIF with the files named from the top of the repository.
754pub fn render_sarif(report: &Report) -> String {
755    let prefix = report.analysis.package_path.as_str();
756    let results: Vec<serde_json::Value> = report
757        .findings
758        .iter()
759        .map(|finding| {
760            let (kind, at) = finding_parts(finding);
761            let rule = match kind {
762                "INPUT GAP" => "input-gap",
763                "ASSERTION GAP" => "assertion-gap",
764                _ => "survivor",
765            };
766            let text = format!("`{}`: {}", at.code, finding_body(finding).join("; "));
767            serde_json::json!({
768                "ruleId": rule,
769                "level": "warning",
770                "message": { "text": text },
771                // What the service tells a finding of one run from that of another by.
772                "partialFingerprints": { "tmtFindingId/v2": at.id },
773                "locations": [{
774                    "physicalLocation": {
775                        "artifactLocation": { "uri": format!("{prefix}{}", at.file) },
776                        "region": { "startLine": at.line, "startColumn": at.column }
777                    }
778                }]
779            })
780        })
781        .collect();
782    let sarif = serde_json::json!({
783        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
784        "version": "2.1.0",
785        "runs": [{
786            "tool": { "driver": {
787                "name": "tmt",
788                "rules": [
789                    { "id": "input-gap", "shortDescription": { "text": "No test input tells this mutant from the original" } },
790                    { "id": "assertion-gap", "shortDescription": { "text": "Tests run the mutated code and still pass" } },
791                    { "id": "survivor", "shortDescription": { "text": "A mutant built on its own passes every test; why is not known" } }
792                ]
793            } },
794            // What was looked at: a run of a part says nothing about the rest.
795            "properties": { "analysis": report.analysis, "evaluation": report.evaluation, "skipped": report.skipped },
796            "results": results
797        }]
798    });
799    serde_json::to_string_pretty(&sarif).expect("JSON values serialise")
800}
801
802fn list(items: &[String], limit: usize) -> String {
803    let shown: Vec<&str> = items.iter().take(limit).map(String::as_str).collect();
804    let more = items.len().saturating_sub(limit);
805    if more > 0 {
806        format!("{} (+{more} more)", shown.join(", "))
807    } else {
808        shown.join(", ")
809    }
810}
811
812/// The lines of one finding, without its header.
813fn finding_body(finding: &Finding) -> Vec<String> {
814    let mut lines = vec![];
815    match finding {
816        Finding::InputGap {
817            survivors,
818            survivor_count,
819            add_tests,
820            observed,
821            verified,
822            ..
823        } => {
824            let more = survivor_count.saturating_sub(survivors.len() as u128);
825            let more = if more > 0 {
826                format!(" (+{more} more)")
827            } else {
828                String::new()
829            };
830            let note = if *verified {
831                "re-run: tests pass"
832            } else {
833                "from the trace, not re-run"
834            };
835            lines.push(format!(
836                "passes every test as: {}{more}  [{note}]",
837                survivors.join(", ")
838            ));
839            lines.extend(observed.iter().cloned());
840            lines.extend(
841                add_tests
842                    .iter()
843                    .map(|test| format!("add a test with {test}")),
844            );
845        }
846        Finding::AssertionGap {
847            survivors,
848            tests,
849            effects,
850            effects_of,
851            ..
852        } => {
853            lines.push(format!("passes every test as: {}", survivors.join(", ")));
854            lines.push(format!(
855                "these tests run the changed code and still pass: {}",
856                list(tests, 5)
857            ));
858            if effects.is_empty() {
859                lines.push("add an assertion on what this code is responsible for".to_string());
860            } else {
861                // Which of several mutants was followed, so that what is said of "the
862                // mutant" below can be tried.
863                if let (Some(followed), true) = (effects_of, survivors.len() > 1) {
864                    lines.push(format!(
865                        "followed one of them through the tests: {followed}"
866                    ));
867                }
868                lines.extend(effects.iter().cloned());
869            }
870        }
871        Finding::Survivor { survivors, .. } => {
872            lines.push(format!("passes every test as: {}", survivors.join(", ")));
873            lines.push(
874                "built on its own, where nothing can be recorded: either no test runs this code, or one does and does not check what it gives"
875                    .to_string(),
876            );
877        }
878    }
879    lines
880}
881
882fn finding_parts(finding: &Finding) -> (&'static str, &Location) {
883    match finding {
884        Finding::InputGap { at, .. } => ("INPUT GAP", at),
885        Finding::AssertionGap { at, .. } => ("ASSERTION GAP", at),
886        Finding::Survivor { at, .. } => ("SURVIVOR", at),
887    }
888}
889
890pub fn render_text(report: &Report, show_unreached: bool) -> String {
891    let mut out = String::new();
892    let mut previous: Option<(&str, usize)> = None;
893    for finding in &report.findings {
894        let (kind, at) = finding_parts(finding);
895        // Findings on one line are usually one thought (a chain of conditions): they are
896        // printed as one block.
897        let same_line = previous == Some((at.file.as_str(), at.line));
898        if same_line {
899            out.push_str(&format!(
900                "  + {kind}  column {}\n    {}\n",
901                at.column, at.code
902            ));
903        } else {
904            if previous.is_some() {
905                out.push('\n');
906            }
907            out.push_str(&format!(
908                "{kind}  {}:{}:{}\n    {}\n",
909                at.file, at.line, at.column, at.code
910            ));
911        }
912        for line in finding_body(finding) {
913            out.push_str(&format!("  {line}\n"));
914        }
915        previous = Some((at.file.as_str(), at.line));
916    }
917    if previous.is_some() {
918        out.push('\n');
919    }
920    if show_unreached {
921        for at in &report.unreached {
922            out.push_str(&format!(
923                "UNREACHED  {}:{}:{}\n    {}\n\n",
924                at.file, at.line, at.column, at.code
925            ));
926        }
927    }
928    for at in &report.unstable {
929        out.push_str(&format!(
930            "UNSTABLE  {}:{}:{}\n    {}\n  the trace predicted a survivor but the re-run failed: the tests are not deterministic, or do something the trace cannot see\n\n",
931            at.file, at.line, at.column, at.code
932        ));
933    }
934    let input = report
935        .findings
936        .iter()
937        .filter(|f| matches!(f, Finding::InputGap { .. }))
938        .count();
939    let assertion = report
940        .findings
941        .iter()
942        .filter(|f| matches!(f, Finding::AssertionGap { .. }))
943        .count();
944    let unexplained = report.findings.len() - input - assertion;
945    // A mutant stopped by the time limit costs the limit: worth knowing when a run is slow.
946    let by_time_limit = if report.mutants_timed_out > 0 {
947        format!(", {} of them by the time limit", report.mutants_timed_out)
948    } else {
949        String::new()
950    };
951    out.push_str(&format!(
952        "{}: {} sites, {} input gaps, {} assertion gaps, {} mutants run ({} killed{by_time_limit}), {} sites unreached",
953        report.package,
954        report.sites,
955        input,
956        assertion,
957        report.mutants_run,
958        report.mutants_killed,
959        report.unreached.len()
960    ));
961    if unexplained > 0 {
962        out.push_str(&format!(
963            ", {unexplained} survivors of mutants built on their own"
964        ));
965    }
966    if report.suppressed > 0 {
967        out.push_str(&format!(", {} findings suppressed", report.suppressed));
968    }
969    if report.skipped_sites > 0 {
970        out.push_str(&format!(
971            ", {} sites skipped (probe did not compile)",
972            report.skipped_sites
973        ));
974    }
975    if report.unviable_mutants > 0 {
976        out.push_str(&format!(
977            ", {} mutants left out (they do not compile)",
978            report.unviable_mutants
979        ));
980    }
981    out.push('\n');
982    if let Some(audit) = &report.audit {
983        out.push_str(&format!(
984            "audit: {} of {} surviving mutants run against all tests, {} failed one they had not been run against\n",
985            audit.sampled,
986            audit.survivors,
987            audit.disagreements.len()
988        ));
989        for at in &audit.disagreements {
990            out.push_str(&format!(
991                "  {}:{}:{}  {}\n",
992                at.file, at.line, at.column, at.code
993            ));
994        }
995        if audit.rebuilt > 0 {
996            out.push_str(&format!(
997                "audit: {} mutants chosen to be built from the source as well: {} compared, {} with another result than as a probe, {} that could not be compared\n",
998                audit.rebuilt,
999                audit.compared,
1000                audit.source_disagreements.len(),
1001                audit.not_compared
1002            ));
1003        }
1004        for differs in &audit.source_disagreements {
1005            out.push_str(&format!(
1006                "  {}:{}:{}  {}: {} as a probe, {} built\n",
1007                differs.at.file,
1008                differs.at.line,
1009                differs.at.column,
1010                differs.mutant,
1011                differs.as_probe,
1012                differs.built
1013            ));
1014        }
1015        if audit.trace_differences.is_empty() {
1016            out.push_str("audit: recorded once more, the tests did the same\n");
1017        }
1018        for binary in &audit.trace_differences {
1019            out.push_str(&format!(
1020                "audit: recorded once more, `{}` differs in {} records: its tests do not always do the same\n",
1021                binary.binary, binary.records
1022            ));
1023        }
1024    }
1025    if report.mutants_not_evaluated > 0 {
1026        out.push_str(&format!(
1027            "({} mutants not evaluated: a range that ends at the largest value of its type cannot be made to include it)\n",
1028            report.mutants_not_evaluated
1029        ));
1030    }
1031    if report.mutants_not_built > 0 {
1032        out.push_str(&format!(
1033            "({} more mutants need a build of their own: --rebuild runs them)\n",
1034            report.mutants_not_built
1035        ));
1036    }
1037    if !report.skipped.is_empty() {
1038        out.push_str(&format!(
1039            "({} skipped entries with locations and reasons in --json)\n",
1040            report.skipped.len()
1041        ));
1042    }
1043    if report.evaluation == Some(Evaluation::NoMutantsExecuted) {
1044        out.push_str("No mutants executed. See any skipped entries in --json. For a subprocess that clears the probe environment, try --source-only.\n");
1045    }
1046    if !show_unreached && !report.unreached.is_empty() {
1047        out.push_str("(--show-unreached lists the code no test executes)\n");
1048    }
1049    out
1050}
1051
1052#[cfg(test)]
1053mod tests {
1054    use super::*;
1055    use crate::instrument::discover;
1056
1057    #[test]
1058    fn evaluation_distinguishes_no_sites_no_mutants_and_completed_work() {
1059        let mut report = Report::default();
1060        report.record_evaluation();
1061        assert_eq!(report.evaluation, Some(Evaluation::NoSites));
1062        report.sites = 1;
1063        report.record_evaluation();
1064        assert_eq!(report.evaluation, Some(Evaluation::NoMutantsExecuted));
1065        assert!(render_text(&report, false).contains("No mutants executed."));
1066        report.mutants_run = 1;
1067        report.record_evaluation();
1068        assert_eq!(report.evaluation, None);
1069        assert!(!render_text(&report, false).contains("No mutants executed."));
1070    }
1071
1072    fn results_of(sarif: &serde_json::Value) -> &Vec<serde_json::Value> {
1073        sarif["runs"][0]["results"].as_array().unwrap()
1074    }
1075
1076    fn or_site() -> Site {
1077        site_of("fn f(a: bool, b: bool) -> bool { a || b }")
1078    }
1079
1080    fn assign_kind() -> SiteKind {
1081        SiteKind::Arith {
1082            op: ArithOp::Add,
1083            assign: true,
1084            lhs: "*total".into(),
1085            rhs: "fee".into(),
1086            gap: (0, 0),
1087        }
1088    }
1089
1090    fn site_of(src: &str) -> Site {
1091        discover(src, 0)
1092            .unwrap()
1093            .sites
1094            .into_iter()
1095            .find(|s| !matches!(s.kind, SiteKind::Return { .. } | SiteKind::Body { .. }))
1096            .unwrap()
1097    }
1098
1099    #[test]
1100    fn describes_mutants_at_source_level() {
1101        let rhs = site_of("fn f(age: u32) -> bool { age >= 18 }");
1102        assert_eq!(describe(&rhs, Mutation::Shift(1)), "`age >= 19`");
1103        assert_eq!(describe(&rhs, Mutation::Shift(-2)), "`age >= 16`");
1104        assert_eq!(describe(&rhs, Mutation::Negate), "`!(age >= 18)`");
1105        assert_eq!(describe(&rhs, Mutation::Const(false)), "`false`");
1106        assert_eq!(describe(&rhs, Mutation::Op(CmpOp::Gt)), "`age > 18`");
1107
1108        // 18 <= age shifted by +1 is 18 <= age + 1, i.e. 17 <= age.
1109        let lhs = site_of("fn f(age: i32) -> bool { 18 <= age }");
1110        assert_eq!(describe(&lhs, Mutation::Shift(1)), "`17 <= age`");
1111
1112        let none = site_of("fn f(a: u32, b: u32) -> bool { a >= b }");
1113        assert_eq!(describe(&none, Mutation::Shift(1)), "`a > b`");
1114        assert_eq!(
1115            describe(&none, Mutation::Shift(2)),
1116            "`a >= b + 2` (without overflow)"
1117        );
1118        assert_eq!(
1119            describe(&none, Mutation::Shift(-1)),
1120            "`a >= b - 1` (without overflow)"
1121        );
1122        let lt = site_of("fn f(a: u32, b: u32) -> bool { a < b }");
1123        assert_eq!(describe(&lt, Mutation::Shift(1)), "`a <= b`");
1124
1125        let stmt = site_of("fn f(s: &mut S) { s.check(\n  1,\n  2); }");
1126        assert_eq!(
1127            describe(&stmt, Mutation::Delete),
1128            "delete `s.check( 1, 2);`"
1129        );
1130    }
1131
1132    /// The source-level form must mean the same as the planner's `Shift`.
1133    #[test]
1134    fn literal_shift_rendering_matches_shift_semantics() {
1135        use crate::plan::eval_mutated_d;
1136        for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
1137            for shift in [-2, -1, 1, 2] {
1138                for other in -5..=5i128 {
1139                    let k = 1i128;
1140                    // literal on the right: `x op k+shift`
1141                    assert_eq!(
1142                        op.eval_d(other - (k + shift)),
1143                        eval_mutated_d(op, Mutation::Shift(shift), other - k)
1144                    );
1145                    // literal on the left: `k-shift op x`
1146                    assert_eq!(
1147                        op.eval_d((k - shift) - other),
1148                        eval_mutated_d(op, Mutation::Shift(shift), k - other)
1149                    );
1150                }
1151            }
1152        }
1153        // And the operator flips used when neither side is a literal.
1154        for (op, shift, flipped) in [
1155            (CmpOp::Ge, 1, CmpOp::Gt),
1156            (CmpOp::Gt, -1, CmpOp::Ge),
1157            (CmpOp::Le, -1, CmpOp::Lt),
1158            (CmpOp::Lt, 1, CmpOp::Le),
1159        ] {
1160            for d in -3..=3 {
1161                assert_eq!(
1162                    flipped.eval_d(d),
1163                    eval_mutated_d(op, Mutation::Shift(shift), d)
1164                );
1165            }
1166        }
1167    }
1168
1169    #[test]
1170    fn boundary_finding_for_the_age_check() {
1171        let site = site_of("fn f(age: u32) -> bool { age >= 18 }");
1172        let mut obs = Obs::of_d(-1);
1173        obs.merge(&Obs::of_d(2));
1174        let gap = InputGap::Boundary {
1175            min_shift: 0,
1176            max_shift: 2,
1177            missing: vec![0],
1178        };
1179        let finding = input_gap_finding("src/lib.rs", &site, &gap, &obs, true).unwrap();
1180        assert_eq!(
1181            finding,
1182            Finding::InputGap {
1183                at: Location {
1184                    file: "src/lib.rs".into(),
1185                    line: 1,
1186                    column: 26,
1187                    code: "age >= 18".into(),
1188                    ..Location::default()
1189                },
1190                survivors: vec!["`age >= 19`".into(), "`age >= 20`".into()],
1191                survivor_count: 2,
1192                add_tests: vec!["`age` = 18 (the original gives true)".into()],
1193                observed: Some("nearest values the tests passed: `age` = 17, 20".into()),
1194                verified: true,
1195            }
1196        );
1197        let report = Report {
1198            package: "p".into(),
1199            sites: 1,
1200            findings: vec![finding],
1201            ..Report::default()
1202        };
1203        let text = render_text(&report, false);
1204        assert!(text.contains("INPUT GAP  src/lib.rs:1:26"), "{text}");
1205        assert!(
1206            text.contains("passes every test as: `age >= 19`, `age >= 20`  [re-run: tests pass]"),
1207            "{text}"
1208        );
1209        assert!(
1210            text.contains("add a test with `age` = 18 (the original gives true)"),
1211            "{text}"
1212        );
1213        assert!(
1214            text.contains("p: 1 sites, 1 input gaps, 0 assertion gaps"),
1215            "{text}"
1216        );
1217        assert!(report.has_gaps());
1218    }
1219
1220    #[test]
1221    fn other_gap_kinds() {
1222        let site = site_of("fn f(a: f64, b: f64) -> bool { a < b }");
1223        let mut obs = Obs::of_rel(crate::plan::Rel::Less);
1224        obs.merge(&Obs::of_rel(crate::plan::Rel::Greater));
1225        let gap = InputGap::EqualNeverObserved {
1226            flipped: CmpOp::Le,
1227            float_gap: None,
1228        };
1229        let Some(Finding::InputGap {
1230            survivors,
1231            add_tests,
1232            observed,
1233            ..
1234        }) = input_gap_finding("f.rs", &site, &gap, &obs, false)
1235        else {
1236            panic!()
1237        };
1238        assert_eq!(survivors, ["`a <= b`"]);
1239        assert_eq!(
1240            add_tests,
1241            ["`a` equal to `b` (the original gives false, the mutant true)"]
1242        );
1243        assert_eq!(observed, None);
1244
1245        let Some(Finding::InputGap {
1246            survivors,
1247            add_tests,
1248            ..
1249        }) = input_gap_finding(
1250            "f.rs",
1251            &site,
1252            &InputGap::OneSided { always: true },
1253            &obs,
1254            false,
1255        )
1256        else {
1257            panic!()
1258        };
1259        assert_eq!(survivors, ["`true`"]);
1260        assert_eq!(add_tests, ["an input that makes `a < b` false"]);
1261
1262        assert_eq!(
1263            input_gap_finding("f.rs", &site, &InputGap::Unreached, &obs, false),
1264            None
1265        );
1266    }
1267
1268    #[test]
1269    fn float_gap_finding() {
1270        let site = site_of("fn f(celsius: f64) -> bool { celsius > 30.5 }");
1271        let mut obs = Obs::of_f(-20.5);
1272        obs.merge(&Obs::of_f(9.5));
1273        let gap = InputGap::EqualNeverObserved {
1274            flipped: CmpOp::Ge,
1275            float_gap: obs.float_gap(),
1276        };
1277        let Some(Finding::InputGap {
1278            survivors,
1279            add_tests,
1280            observed,
1281            survivor_count,
1282            ..
1283        }) = input_gap_finding("f.rs", &site, &gap, &obs, true)
1284        else {
1285            panic!()
1286        };
1287        assert_eq!(
1288            survivors,
1289            [
1290                "`celsius >= 30.5`",
1291                "`celsius > 35.25`",
1292                "`celsius > 20.25`"
1293            ]
1294        );
1295        assert_eq!(survivor_count, 3);
1296        assert_eq!(
1297            add_tests,
1298            ["`celsius` equal to `30.5` (the original gives false, the mutant true)"]
1299        );
1300        assert_eq!(
1301            observed.as_deref(),
1302            Some(
1303                "nearest values the tests passed: `celsius` = 10.0, 40.0; any threshold between them passes"
1304            )
1305        );
1306
1307        let lhs = site_of("fn f(x: f32) -> bool { 1.5_f32 <= x }");
1308        assert_eq!(describe(&lhs, Mutation::ShiftF(0.25)), "`1.25 <= x`");
1309        let none = site_of("fn f(x: f64, y: f64) -> bool { x < y }");
1310        assert_eq!(describe(&none, Mutation::ShiftF(0.5)), "`x < y + 0.5`");
1311        assert_eq!(describe(&none, Mutation::ShiftF(-0.5)), "`x < y - 0.5`");
1312        let finding = input_gap_finding(
1313            "f.rs",
1314            &none,
1315            &InputGap::EqualNeverObserved {
1316                flipped: CmpOp::Le,
1317                float_gap: Some((-1.0, 2.0)),
1318            },
1319            &obs,
1320            false,
1321        );
1322        let Some(Finding::InputGap { observed, .. }) = finding else {
1323            panic!()
1324        };
1325        assert_eq!(
1326            observed.as_deref(),
1327            Some("nearest values the tests passed: `x` - `y` = -1.0, 2.0")
1328        );
1329
1330        assert_eq!(float_literal("30.5"), Some(30.5));
1331        assert_eq!(float_literal("-1e3"), Some(-1000.0));
1332        assert_eq!(float_literal("1_000.5f64"), Some(1000.5));
1333        assert_eq!(float_literal("limit"), None);
1334        assert_eq!(float_literal("x1"), None);
1335        assert_eq!(float_literal("1x"), None);
1336        assert_eq!(float_literal("-x"), None);
1337        assert_eq!(float_literal("-2.5"), Some(-2.5));
1338        assert_eq!(float_literal("e"), None);
1339        // Nothing is rounded away: a tiny shift stays visible.
1340        assert_eq!(show_float(0.1 + 0.2), "0.30000000000000004");
1341        assert_eq!(show_float(1e-10), "1e-10");
1342        assert_eq!(show_float(10.0), "10.0");
1343        assert_eq!(show_float(35.25), "35.25");
1344        // A shift that does not change the literal is not listed as a mutant.
1345        let big = site_of("fn f(x: f64) -> bool { x > 1e300 }");
1346        let tiny = InputGap::EqualNeverObserved {
1347            flipped: CmpOp::Ge,
1348            float_gap: Some((-2e-300, 2e-300)),
1349        };
1350        let Some(Finding::InputGap { survivors, .. }) =
1351            input_gap_finding("f.rs", &big, &tiny, &obs, true)
1352        else {
1353            panic!()
1354        };
1355        assert_eq!(survivors, ["`x >= 1e300`"]);
1356    }
1357
1358    #[test]
1359    fn logic_and_arithmetic_findings() {
1360        let and = site_of("fn f(a: bool, b: bool) -> bool { a && b }");
1361        assert_eq!(describe(&and, Mutation::LogicSwap), "`a || b`");
1362        assert_eq!(describe(&and, Mutation::LogicDropRhs), "`a && { b; true }`");
1363        assert_eq!(
1364            describe(&or_site(), Mutation::LogicDropRhs),
1365            "`a || { b; false }`"
1366        );
1367        assert_eq!(describe(&and, Mutation::LogicDropLhs), "`{ a; b }`");
1368        let or = site_of("fn f(a: bool, b: bool) -> bool { a || b }");
1369        assert_eq!(describe(&or, Mutation::LogicSwap), "`a && b`");
1370        let advice = |site: &Site, gap| match logic_gap_finding("f.rs", site, gap, true) {
1371            Some(Finding::InputGap {
1372                survivors,
1373                add_tests,
1374                ..
1375            }) => (survivors[0].clone(), add_tests[0].clone()),
1376            _ => panic!(),
1377        };
1378        assert_eq!(
1379            advice(&and, LogicGap::RhsNeverDecides),
1380            (
1381                "`a && { b; true }`".into(),
1382                "a case where `a` is true and `b` is false".into()
1383            )
1384        );
1385        assert_eq!(
1386            advice(&and, LogicGap::LhsNeverDecides),
1387            ("`{ a; b }`".into(), "a case where `a` is false".into())
1388        );
1389        assert_eq!(
1390            advice(&or, LogicGap::RhsNeverDecides),
1391            (
1392                "`a || { b; false }`".into(),
1393                "a case where `a` is false and `b` is true".into()
1394            )
1395        );
1396        assert_eq!(
1397            advice(&or, LogicGap::LhsNeverDecides),
1398            ("`{ a; b }`".into(), "a case where `a` is true".into())
1399        );
1400        assert_eq!(
1401            logic_gap_finding("f.rs", &and, LogicGap::Unreached, true),
1402            None
1403        );
1404        assert_eq!(
1405            arith_gap_finding("f.rs", &and, Mutation::ArithSwap, true),
1406            None
1407        );
1408
1409        let add = site_of("fn f(total: u32, fee: u32) -> u32 { total + fee }");
1410        assert_eq!(describe(&add, Mutation::ArithSwap), "`total - fee`");
1411        let Some(Finding::InputGap {
1412            survivors,
1413            add_tests,
1414            ..
1415        }) = arith_gap_finding("f.rs", &add, Mutation::ArithSwap, true)
1416        else {
1417            panic!()
1418        };
1419        assert_eq!(
1420            (survivors[0].as_str(), add_tests[0].as_str()),
1421            ("`total - fee`", "`fee` other than 0")
1422        );
1423        let mul = site_of("fn f(n: u32, scale: u32) -> u32 { n * scale }");
1424        let Some(Finding::InputGap {
1425            survivors,
1426            add_tests,
1427            ..
1428        }) = arith_gap_finding("f.rs", &mul, Mutation::ArithSwap, true)
1429        else {
1430            panic!()
1431        };
1432        assert_eq!(survivors[0], "`n / scale`");
1433        assert_eq!(
1434            add_tests[0],
1435            "operands for which `n * scale` and `n / scale` differ"
1436        );
1437        let assign = Site {
1438            kind: assign_kind(),
1439            ..add.clone()
1440        };
1441        assert_eq!(describe(&assign, Mutation::ArithSwap), "`*total -= fee`");
1442        let Some(Finding::InputGap { add_tests, .. }) =
1443            arith_gap_finding("f.rs", &assign, Mutation::ArithSwap, true)
1444        else {
1445            panic!()
1446        };
1447        assert_eq!(add_tests[0], "`fee` other than 0");
1448        let shift = Site {
1449            kind: SiteKind::Arith {
1450                op: ArithOp::Shl,
1451                assign: true,
1452                lhs: "bits".into(),
1453                rhs: "n".into(),
1454                gap: (0, 0),
1455            },
1456            ..assign.clone()
1457        };
1458        assert_eq!(describe(&shift, Mutation::ArithSwap), "`bits >>= n`");
1459        let Some(Finding::InputGap { add_tests, .. }) =
1460            arith_gap_finding("f.rs", &shift, Mutation::ArithSwap, true)
1461        else {
1462            panic!()
1463        };
1464        assert_eq!(
1465            add_tests[0],
1466            "operands for which `bits <<= n` and `bits >>= n` differ"
1467        );
1468
1469        let not = Site {
1470            kind: SiteKind::Not {
1471                bang: (0, 1),
1472                operand: "is_ready(x)".into(),
1473            },
1474            ..assign.clone()
1475        };
1476        assert_eq!(describe(&not, Mutation::DropNot), "`is_ready(x)`");
1477        let ret = Site {
1478            kind: SiteKind::Return {
1479                name: "is_ready".into(),
1480                option: None,
1481                sole_expr: None,
1482            },
1483            ..assign.clone()
1484        };
1485        assert_eq!(
1486            describe(&ret, Mutation::Const(true)),
1487            "`is_ready` returning `true`"
1488        );
1489        let Some(Finding::InputGap {
1490            survivors,
1491            add_tests,
1492            ..
1493        }) = return_gap_finding("f.rs", &ret, false, true)
1494        else {
1495            panic!()
1496        };
1497        assert_eq!(survivors[0], "`is_ready` returning `false`");
1498        assert_eq!(add_tests[0], "a case where `is_ready` returns true");
1499        assert_eq!(return_gap_finding("f.rs", &not, false, true), None);
1500
1501        let find = Site {
1502            kind: SiteKind::Return {
1503                name: "find".into(),
1504                option: Some("Option<&str>".into()),
1505                sole_expr: None,
1506            },
1507            ..assign.clone()
1508        };
1509        assert_eq!(
1510            describe(&find, Mutation::Const(false)),
1511            "`find` returning `None`"
1512        );
1513        let Some(Finding::InputGap { add_tests, .. }) =
1514            return_gap_finding("f.rs", &find, false, true)
1515        else {
1516            panic!()
1517        };
1518        assert_eq!(add_tests[0], "a case where `find` returns `Some`");
1519        let range = Site {
1520            kind: SiteKind::Range {
1521                inclusive: false,
1522                lhs: "0".into(),
1523                rhs: "n".into(),
1524                gap: (0, 0),
1525            },
1526            ..assign.clone()
1527        };
1528        assert_eq!(describe(&range, Mutation::RangeEnd), "`0..=n`");
1529        let closed = Site {
1530            kind: SiteKind::Range {
1531                inclusive: true,
1532                lhs: "1".into(),
1533                rhs: "n".into(),
1534                gap: (0, 0),
1535            },
1536            ..assign.clone()
1537        };
1538        assert_eq!(describe(&closed, Mutation::RangeEnd), "`1..n`");
1539        let arm = Site {
1540            kind: SiteKind::Arm {
1541                pattern: "Kind::Update { key, .. }".into(),
1542                guard: crate::instrument::ArmGuard::None(0),
1543            },
1544            ..assign.clone()
1545        };
1546        assert_eq!(
1547            describe(&arm, Mutation::Delete),
1548            "remove the arm `Kind::Update { key, .. } => ..`"
1549        );
1550
1551        let clamp = Site {
1552            kind: SiteKind::MinMax {
1553                max: true,
1554                receiver: "drift".into(),
1555                argument: "peak.get()".into(),
1556                call: (0, 0),
1557                close: (0, 0),
1558            },
1559            ..assign.clone()
1560        };
1561        assert_eq!(
1562            describe(&clamp, Mutation::MinMax),
1563            "`drift.min(peak.get())`"
1564        );
1565        let Some(Finding::InputGap { add_tests, .. }) = min_max_gap_finding("f.rs", &clamp, true)
1566        else {
1567            panic!()
1568        };
1569        assert_eq!(add_tests[0], "`drift` different from `peak.get()`");
1570        assert_eq!(min_max_gap_finding("f.rs", &assign, true), None);
1571
1572        let rem = site_of("fn f(n: u32, k: u32) -> u32 { n % k }");
1573        assert_eq!(describe(&rem, Mutation::ArithSwap), "`n / k`");
1574        assert_eq!(
1575            logic_gap_finding("f.rs", &add, LogicGap::RhsNeverDecides, true),
1576            None
1577        );
1578    }
1579
1580    #[test]
1581    fn long_code_is_shortened() {
1582        let exactly_100 = "x".repeat(100);
1583        assert_eq!(one_line(&exactly_100), exactly_100);
1584        let shortened = one_line(&"x".repeat(101));
1585        assert_eq!(shortened, format!("{}...", "x".repeat(97)));
1586        assert_eq!(one_line("a\n   b"), "a b");
1587    }
1588
1589    #[test]
1590    fn at_most_three_survivors_are_listed_nearest_first() {
1591        let site = site_of("fn f(a: i64) -> bool { a >= 10 }");
1592        let obs = Obs::default();
1593        let survivors = |min_shift, max_shift| {
1594            let gap = InputGap::Boundary {
1595                min_shift,
1596                max_shift,
1597                missing: vec![0],
1598            };
1599            match input_gap_finding("f.rs", &site, &gap, &obs, false) {
1600                Some(Finding::InputGap {
1601                    survivors,
1602                    survivor_count,
1603                    ..
1604                }) => (survivors, survivor_count),
1605                _ => panic!(),
1606            }
1607        };
1608        assert_eq!(
1609            survivors(-9, 9),
1610            (
1611                vec!["`a >= 11`".into(), "`a >= 9`".into(), "`a >= 12`".into()],
1612                18
1613            )
1614        );
1615        assert_eq!(survivors(-1, 0), (vec!["`a >= 9`".into()], 1));
1616        assert_eq!(survivors(0, 1), (vec!["`a >= 11`".into()], 1));
1617        assert_eq!(
1618            survivors(-2, 0),
1619            (vec!["`a >= 9`".into(), "`a >= 8`".into()], 2)
1620        );
1621    }
1622
1623    #[test]
1624    fn text_report_is_exact() {
1625        let at = Location {
1626            file: "src/lib.rs".into(),
1627            line: 3,
1628            column: 9,
1629            code: "a >= b".into(),
1630            ..Location::default()
1631        };
1632        let below = Location {
1633            file: "src/lib.rs".into(),
1634            line: 7,
1635            column: 5,
1636            code: "s.reset();".into(),
1637            ..Location::default()
1638        };
1639        let report = Report {
1640            package: "p".into(),
1641            sites: 2,
1642            mutants_run: 1,
1643            suppressed: 2,
1644            findings: vec![
1645                Finding::InputGap {
1646                    at: at.clone(),
1647                    survivors: vec!["`a > b`".into()],
1648                    survivor_count: 4,
1649                    add_tests: vec!["`a` equal to `b` (the original gives true)".into()],
1650                    observed: Some("nearest values the tests passed: `a` - `b` = -1, 4".into()),
1651                    verified: false,
1652                },
1653                Finding::InputGap {
1654                    at: at.clone(),
1655                    survivors: vec!["`true`".into()],
1656                    survivor_count: 1,
1657                    add_tests: vec![],
1658                    observed: None,
1659                    verified: true,
1660                },
1661                Finding::AssertionGap {
1662                    at: Location { column: 4, ..at },
1663                    survivors: vec!["`!(a >= b)`".into()],
1664                    tests: vec!["t".into()],
1665                    effects: vec![],
1666                    effects_of: None,
1667                },
1668                Finding::AssertionGap {
1669                    at: below,
1670                    survivors: vec!["delete `s.reset();`".into()],
1671                    tests: vec!["t".into()],
1672                    effects: vec![
1673                        "with the mutant, `t` no longer runs `s.count = 0;` (src/lib.rs:12)".into(),
1674                    ],
1675                    effects_of: None,
1676                },
1677            ],
1678            ..Report::default()
1679        };
1680        // Findings on one line form one block; a new line starts a new block.
1681        assert_eq!(
1682            render_text(&report, false),
1683            "INPUT GAP  src/lib.rs:3:9\n    a >= b\n\
1684             \x20 passes every test as: `a > b` (+3 more)  [from the trace, not re-run]\n\
1685             \x20 nearest values the tests passed: `a` - `b` = -1, 4\n\
1686             \x20 add a test with `a` equal to `b` (the original gives true)\n\
1687             \x20 + INPUT GAP  column 9\n    a >= b\n\
1688             \x20 passes every test as: `true`  [re-run: tests pass]\n\
1689             \x20 + ASSERTION GAP  column 4\n    a >= b\n\
1690             \x20 passes every test as: `!(a >= b)`\n\
1691             \x20 these tests run the changed code and still pass: t\n\
1692             \x20 add an assertion on what this code is responsible for\n\
1693             \n\
1694             ASSERTION GAP  src/lib.rs:7:5\n    s.reset();\n\
1695             \x20 passes every test as: delete `s.reset();`\n\
1696             \x20 these tests run the changed code and still pass: t\n\
1697             \x20 with the mutant, `t` no longer runs `s.count = 0;` (src/lib.rs:12)\n\
1698             \n\
1699             p: 2 sites, 2 input gaps, 2 assertion gaps, 1 mutants run (0 killed), 0 sites unreached, 2 findings suppressed\n"
1700        );
1701        assert_eq!(
1702            render_text(
1703                &Report {
1704                    package: "q".into(),
1705                    ..Report::default()
1706                },
1707                false
1708            ),
1709            "q: 0 sites, 0 input gaps, 0 assertion gaps, 0 mutants run (0 killed), 0 sites unreached\n"
1710        );
1711
1712        let mut in_repository = report.clone();
1713        in_repository.analysis.package_path = "crates/p/".into();
1714        in_repository.analysis.since = Some("abc".into());
1715        if let Finding::AssertionGap { at, .. } = &mut in_repository.findings[3] {
1716            at.id = "assertion_gap|src/lib.rs|f|s.reset();|0".into();
1717        }
1718        let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&in_repository)).unwrap();
1719        assert_eq!(
1720            results_of(&sarif)[3]["partialFingerprints"]["tmtFindingId/v2"],
1721            "assertion_gap|src/lib.rs|f|s.reset();|0"
1722        );
1723        assert_eq!(sarif["runs"][0]["properties"]["analysis"]["since"], "abc");
1724        assert_eq!(sarif["version"], "2.1.0");
1725        let results = sarif["runs"][0]["results"].as_array().unwrap();
1726        assert_eq!(results.len(), 4);
1727        assert_eq!(results[0]["ruleId"], "input-gap");
1728        assert_eq!(results[3]["ruleId"], "assertion-gap");
1729        let location = &results[3]["locations"][0]["physicalLocation"];
1730        assert_eq!(location["artifactLocation"]["uri"], "crates/p/src/lib.rs");
1731        assert_eq!(
1732            (
1733                &location["region"]["startLine"],
1734                &location["region"]["startColumn"]
1735            ),
1736            (&serde_json::json!(7), &serde_json::json!(5))
1737        );
1738        assert!(
1739            results[3]["message"]["text"]
1740                .as_str()
1741                .unwrap()
1742                .starts_with("`s.reset();`: passes every test as: delete `s.reset();`; ")
1743        );
1744        let rules = sarif["runs"][0]["tool"]["driver"]["rules"]
1745            .as_array()
1746            .unwrap();
1747        assert_eq!(rules.len(), 3);
1748    }
1749
1750    #[test]
1751    fn a_mutant_built_on_its_own_is_a_survivor_without_a_cause() {
1752        let survivor = Finding::Survivor {
1753            at: Location {
1754                file: "src/lib.rs".into(),
1755                line: 2,
1756                column: 1,
1757                code: "const fn limit() -> u8".into(),
1758                ..Location::default()
1759            },
1760            survivors: vec!["the body of `limit` replaced by `0`".into()],
1761        };
1762        assert_eq!(survivor.kind(), "survivor");
1763        assert_eq!(survivor.at().line, 2);
1764        assert_eq!(survivor.survivors().len(), 1);
1765        let report = Report {
1766            package: "p".into(),
1767            findings: vec![survivor],
1768            ..Report::default()
1769        };
1770        // Neither of the two gaps: it is counted and named as what it is.
1771        assert_eq!(
1772            render_text(&report, false),
1773            "SURVIVOR  src/lib.rs:2:1\n    const fn limit() -> u8\n\
1774             \x20 passes every test as: the body of `limit` replaced by `0`\n\
1775             \x20 built on its own, where nothing can be recorded: either no test runs this code, or one does and does not check what it gives\n\
1776             \n\
1777             p: 0 sites, 0 input gaps, 0 assertion gaps, 0 mutants run (0 killed), 0 sites unreached, 1 survivors of mutants built on their own\n"
1778        );
1779        let json = serde_json::to_value(&report).unwrap();
1780        assert_eq!(json["findings"][0]["kind"], "survivor");
1781        let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
1782        assert_eq!(results_of(&sarif)[0]["ruleId"], "survivor");
1783        assert!(report.has_gaps());
1784    }
1785
1786    #[test]
1787    fn non_literal_inputs_in_words() {
1788        assert_eq!(
1789            input_for("a", "b", LiteralSide::None, 0),
1790            "`a` equal to `b`"
1791        );
1792        assert_eq!(input_for("a", "b", LiteralSide::None, 1), "`a` = `b` + 1");
1793        assert_eq!(input_for("a", "b", LiteralSide::None, -1), "`a` = `b` - 1");
1794        assert_eq!(
1795            input_for("18", "age", LiteralSide::Lhs(18), -1),
1796            "`age` = 19"
1797        );
1798    }
1799
1800    #[test]
1801    fn text_report_sections() {
1802        let at = Location {
1803            file: "src/lib.rs".into(),
1804            line: 3,
1805            column: 9,
1806            code: "s.check()?;".into(),
1807            ..Location::default()
1808        };
1809        let report = Report {
1810            package: "p".into(),
1811            analysis: Analysis::default(),
1812            audit: None,
1813            evaluation: None,
1814            sites: 4,
1815            skipped_sites: 1,
1816            skipped: vec![],
1817            unviable_mutants: 2,
1818            mutants_not_built: 0,
1819            mutants_not_evaluated: 0,
1820            mutants_run: 3,
1821            mutants_killed: 2,
1822            mutants_timed_out: 0,
1823            suppressed: 0,
1824            findings: vec![Finding::AssertionGap {
1825                at: at.clone(),
1826                survivors: vec!["delete `s.check()?;`".into()],
1827                tests: (0..7).map(|i| format!("tests::t{i}")).collect(),
1828                effects: vec![],
1829                effects_of: None,
1830            }],
1831            unreached: vec![at.clone()],
1832            unstable: vec![at],
1833        };
1834        let text = render_text(&report, false);
1835        assert!(
1836            text.contains("ASSERTION GAP  src/lib.rs:3:9\n    s.check()?;"),
1837            "{text}"
1838        );
1839        assert!(text.contains("tests::t4 (+2 more)"), "{text}");
1840        assert!(text.contains("UNSTABLE  src/lib.rs:3:9"), "{text}");
1841        assert!(!text.contains("UNREACHED"), "{text}");
1842        assert!(
1843            text.contains("3 mutants run (2 killed), 1 sites unreached, 1 sites skipped"),
1844            "{text}"
1845        );
1846        assert!(
1847            text.contains(", 2 mutants left out (they do not compile)\n"),
1848            "{text}"
1849        );
1850        assert!(text.contains("--show-unreached"), "{text}");
1851        let listed = render_text(&report, true);
1852        assert!(listed.contains("UNREACHED  src/lib.rs:3:9"));
1853        assert!(!listed.contains("--show-unreached"), "{listed}");
1854        let one_more = Report {
1855            findings: vec![Finding::InputGap {
1856                at: report.unreached[0].clone(),
1857                survivors: vec!["`a`".into()],
1858                survivor_count: 2,
1859                add_tests: vec![],
1860                observed: None,
1861                verified: true,
1862            }],
1863            ..report.clone()
1864        };
1865        assert!(render_text(&one_more, false).contains("`a` (+1 more)"));
1866        let nothing_unreached = Report {
1867            unreached: vec![],
1868            ..report.clone()
1869        };
1870        assert!(!render_text(&nothing_unreached, false).contains("--show-unreached"));
1871        assert!(!Report::default().has_gaps());
1872    }
1873    #[test]
1874    fn unstable_predictions_alone_are_something_to_act_on() {
1875        let at = Location {
1876            file: "src/lib.rs".into(),
1877            line: 1,
1878            column: 1,
1879            code: "a > b".into(),
1880            ..Location::default()
1881        };
1882        assert!(!Report::default().has_gaps());
1883        assert!(
1884            Report {
1885                unstable: vec![at],
1886                ..Report::default()
1887            }
1888            .has_gaps()
1889        );
1890    }
1891
1892    #[test]
1893    fn what_counts_as_a_float_literal() {
1894        assert_eq!(float_literal("30.5"), Some(30.5));
1895        assert_eq!(float_literal(" 2.5_f32 "), Some(2.5));
1896        assert_eq!(float_literal("-1e3"), Some(-1000.0));
1897        // These parse as floats too, and are not literals: a variable called `inf`, and
1898        // forms Rust does not accept.
1899        for text in ["inf", "nan", "-inf", ".5", "+5", "e5", "limit", ""] {
1900            assert_eq!(float_literal(text), None, "{text}");
1901        }
1902    }
1903
1904    #[test]
1905    fn a_float_shift_that_does_not_move_the_literal_is_dropped() {
1906        // At 2^53 the next float below is 1 away and the next above 2 away.
1907        let survivors_of = |source: &str| {
1908            let site = site_of(source);
1909            let mut obs = Obs::of_f(-4.0);
1910            obs.merge(&Obs::of_f(4.0));
1911            let gap = InputGap::EqualNeverObserved {
1912                flipped: CmpOp::Ge,
1913                float_gap: obs.float_gap(),
1914            };
1915            match input_gap_finding("f.rs", &site, &gap, &obs, true) {
1916                Some(Finding::InputGap {
1917                    survivors,
1918                    survivor_count,
1919                    ..
1920                }) => (survivors, survivor_count),
1921                _ => panic!(),
1922            }
1923        };
1924        // Shifts of +2 and -2 are proposed. Both move the literal.
1925        assert_eq!(
1926            survivors_of("fn f(x: f64) -> bool { x > 9007199254740992.0 }"),
1927            (
1928                vec![
1929                    "`x >= 9007199254740992.0`".to_string(),
1930                    "`x > 9007199254740994.0`".to_string(),
1931                    "`x > 9007199254740990.0`".to_string(),
1932                ],
1933                3
1934            )
1935        );
1936        // At 2^54 only the step down is a different number, and on the left of the
1937        // comparison the literal moves the other way.
1938        assert_eq!(
1939            survivors_of("fn f(x: f64) -> bool { x > 18014398509481984.0 }"),
1940            (
1941                vec![
1942                    "`x >= 18014398509481984.0`".to_string(),
1943                    "`x > 1.8014398509481982e16`".to_string(),
1944                ],
1945                2
1946            )
1947        );
1948        assert_eq!(
1949            survivors_of("fn f(x: f64) -> bool { 18014398509481984.0 > x }"),
1950            (
1951                vec![
1952                    "`18014398509481984.0 >= x`".to_string(),
1953                    "`1.8014398509481982e16 > x`".to_string(),
1954                ],
1955                2
1956            )
1957        );
1958        // With the literal on the left, the nearest values are those of the other side.
1959        let site = site_of("fn f(x: f64) -> bool { 1.5 > x }");
1960        let mut obs = Obs::of_f(-1.0);
1961        obs.merge(&Obs::of_f(2.0));
1962        let gap = InputGap::EqualNeverObserved {
1963            flipped: CmpOp::Ge,
1964            float_gap: obs.float_gap(),
1965        };
1966        let Some(Finding::InputGap { observed, .. }) =
1967            input_gap_finding("f.rs", &site, &gap, &obs, true)
1968        else {
1969            panic!()
1970        };
1971        assert_eq!(
1972            observed.as_deref(),
1973            Some(
1974                "nearest values the tests passed: `x` = -0.5, 2.5; any threshold between them passes"
1975            )
1976        );
1977        // Far above, neither does.
1978        assert_eq!(
1979            survivors_of("fn f(x: f64) -> bool { x > 1e30 }"),
1980            (vec!["`x >= 1e30`".to_string()], 1)
1981        );
1982    }
1983
1984    #[test]
1985    fn the_effects_are_said_of_the_mutant_they_were_seen_with() {
1986        let gap = |survivors: &[&str], effects_of: Option<&str>| Finding::AssertionGap {
1987            at: Location {
1988                file: "src/lib.rs".into(),
1989                line: 1,
1990                column: 1,
1991                code: "a < b".into(),
1992                ..Location::default()
1993            },
1994            survivors: survivors.iter().map(|s| s.to_string()).collect(),
1995            tests: vec!["tests::t".into()],
1996            effects: vec!["with the mutant, `tests::t` now runs `x;` (src/lib.rs:2)".into()],
1997            effects_of: effects_of.map(str::to_string),
1998        };
1999        // Of several mutants one was followed: the report says which.
2000        let body = finding_body(&gap(&["`a <= b`", "`a == b`"], Some("`a <= b`")));
2001        assert_eq!(
2002            body[2..],
2003            [
2004                "followed one of them through the tests: `a <= b`",
2005                "with the mutant, `tests::t` now runs `x;` (src/lib.rs:2)"
2006            ]
2007        );
2008        // A single mutant needs no saying, and nothing is said where nothing is known.
2009        for single in [
2010            gap(&["`a <= b`"], Some("`a <= b`")),
2011            gap(&["`a <= b`", "`a == b`"], None),
2012        ] {
2013            let body = finding_body(&single);
2014            assert_eq!(body.len(), 3, "{body:?}");
2015            assert!(body[2].starts_with("with the mutant"), "{body:?}");
2016        }
2017    }
2018
2019    #[test]
2020    fn an_audit_is_said_in_the_summary() {
2021        let mut report = Report {
2022            package: "p".into(),
2023            audit: Some(Audit {
2024                sampled: 2,
2025                survivors: 7,
2026                ..Audit::default()
2027            }),
2028            ..Report::default()
2029        };
2030        let text = render_text(&report, false);
2031        assert!(
2032            text.ends_with(
2033                "\naudit: 2 of 7 surviving mutants run against all tests, 0 failed one they had not been run against\n\
2034                 audit: recorded once more, the tests did the same\n"
2035            ),
2036            "{text}"
2037        );
2038        let audit = report.audit.as_mut().unwrap();
2039        audit.disagreements.push(Location {
2040            file: "src/lib.rs".into(),
2041            line: 3,
2042            column: 5,
2043            code: "x > 5".into(),
2044            ..Location::default()
2045        });
2046        audit.trace_differences.push(TraceDifference {
2047            binary: "p".into(),
2048            records: 4,
2049        });
2050        let text = render_text(&report, false);
2051        assert!(
2052            text.ends_with(
2053                "all tests, 1 failed one they had not been run against\n\
2054                 \x20 src/lib.rs:3:5  x > 5\n\
2055                 audit: recorded once more, `p` differs in 4 records: its tests do not always do the same\n"
2056            ),
2057            "{text}"
2058        );
2059        // Mutants built from the source are said only where some were, with what differs.
2060        assert!(!text.contains("built from the source"), "{text}");
2061        let audit = report.audit.as_mut().unwrap();
2062        audit.rebuilt = 1;
2063        audit.not_compared = 1;
2064        let text = render_text(&report, false);
2065        assert!(
2066            text.contains(
2067                "\naudit: 1 mutants chosen to be built from the source as well: 0 compared, 0 with another result than as a probe, 1 that could not be compared\n"
2068            ),
2069            "{text}"
2070        );
2071        let audit = report.audit.as_mut().unwrap();
2072        audit.rebuilt = 5;
2073        audit.compared = 4;
2074        audit.source_disagreements.push(SourceDisagreement {
2075            at: Location {
2076                file: "src/lib.rs".into(),
2077                line: 9,
2078                column: 14,
2079                code: "note(asked)".into(),
2080                ..Location::default()
2081            },
2082            mutant: "the guard `note(asked)` replaced by `true`".into(),
2083            as_probe: "passes".into(),
2084            built: "fails".into(),
2085        });
2086        let text = render_text(&report, false);
2087        assert!(
2088            text.contains(
2089                "\naudit: 5 mutants chosen to be built from the source as well: 4 compared, 1 with another result than as a probe, 1 that could not be compared\n\
2090                 \x20 src/lib.rs:9:14  the guard `note(asked)` replaced by `true`: passes as a probe, fails built\n"
2091            ),
2092            "{text}"
2093        );
2094        assert!(!render_text(&Report::default(), false).contains("audit"));
2095    }
2096
2097    #[test]
2098    fn lists_and_counts_at_their_limits() {
2099        let items: Vec<String> = ["a", "b", "c"].iter().map(|s| s.to_string()).collect();
2100        assert_eq!(list(&items, 3), "a, b, c");
2101        assert_eq!(list(&items, 2), "a, b (+1 more)");
2102        assert_eq!(list(&items, 1), "a (+2 more)");
2103        let one = Report {
2104            package: "p".into(),
2105            suppressed: 1,
2106            unviable_mutants: 1,
2107            ..Report::default()
2108        };
2109        assert!(
2110            render_text(&one, false).contains(", 1 mutants left out (they do not compile)"),
2111            "{}",
2112            render_text(&one, false)
2113        );
2114        assert!(!render_text(&Report::default(), false).contains("left out"));
2115        assert!(!render_text(&one, false).contains("--rebuild"));
2116        assert!(!render_text(&one, false).contains("not evaluated"));
2117        let at_top = Report {
2118            mutants_not_evaluated: 1,
2119            ..Report::default()
2120        };
2121        assert!(
2122            render_text(&at_top, false).ends_with(
2123                "\n(1 mutants not evaluated: a range that ends at the largest value of its type cannot be made to include it)\n"
2124            ),
2125            "{}",
2126            render_text(&at_top, false)
2127        );
2128        let quick = Report {
2129            mutants_not_built: 1,
2130            ..Report::default()
2131        };
2132        assert!(
2133            render_text(&quick, false)
2134                .ends_with("\n(1 more mutants need a build of their own: --rebuild runs them)\n"),
2135            "{}",
2136            render_text(&quick, false)
2137        );
2138        let slow = Report {
2139            mutants_run: 5,
2140            mutants_killed: 4,
2141            mutants_timed_out: 2,
2142            ..Report::default()
2143        };
2144        assert!(
2145            render_text(&slow, false)
2146                .contains("5 mutants run (4 killed, 2 of them by the time limit), 0 sites"),
2147            "{}",
2148            render_text(&slow, false)
2149        );
2150        assert!(!render_text(&one, false).contains("time limit"));
2151        let once = Report {
2152            mutants_timed_out: 1,
2153            ..slow.clone()
2154        };
2155        assert!(
2156            render_text(&once, false).contains("(4 killed, 1 of them by the time limit)"),
2157            "{}",
2158            render_text(&once, false)
2159        );
2160        assert!(
2161            render_text(&one, false).contains(", 1 findings suppressed"),
2162            "{}",
2163            render_text(&one, false)
2164        );
2165        assert!(!render_text(&Report::default(), false).contains("suppressed"));
2166    }
2167
2168    #[test]
2169    fn findings_are_put_in_reading_order() {
2170        let gap = |file: &str, line: usize, column: usize, survivor: &str| Finding::AssertionGap {
2171            at: Location {
2172                file: file.into(),
2173                line,
2174                column,
2175                code: "x".into(),
2176                ..Location::default()
2177            },
2178            survivors: vec![survivor.into()],
2179            tests: vec![],
2180            effects: vec![],
2181            effects_of: None,
2182        };
2183        let mut report = Report {
2184            findings: vec![
2185                gap("src/b.rs", 1, 1, "b"),
2186                gap("src/a.rs", 9, 5, "statement"),
2187                gap("src/a.rs", 7, 2, "above it"),
2188                gap("src/a.rs", 9, 5, "its operator"),
2189                gap("src/a.rs", 9, 3, "left of both"),
2190            ],
2191            ..Report::default()
2192        };
2193        report.sort_findings();
2194        let order: Vec<&str> = report
2195            .findings
2196            .iter()
2197            .map(|f| match f {
2198                Finding::AssertionGap { survivors, .. } => survivors[0].as_str(),
2199                _ => panic!(),
2200            })
2201            .collect();
2202        // Findings at one position keep the order they were made in.
2203        assert_eq!(
2204            order,
2205            ["above it", "left of both", "statement", "its operator", "b"]
2206        );
2207    }
2208    #[test]
2209    fn second_replacements_guards_fields_and_bodies_in_words() {
2210        let all = |src: &str| discover(src, 0).unwrap().sites;
2211        let add = site_of("fn f(total: u32, fee: u32) -> u32 { total + fee }");
2212        assert_eq!(describe(&add, Mutation::ArithSwap2), "`total * fee`");
2213        let Some(Finding::InputGap {
2214            survivors,
2215            add_tests,
2216            ..
2217        }) = arith_gap_finding("f.rs", &add, Mutation::ArithSwap2, true)
2218        else {
2219            panic!()
2220        };
2221        assert_eq!(survivors, ["`total * fee`"]);
2222        assert_eq!(
2223            add_tests,
2224            ["operands for which `total + fee` and `total * fee` differ"]
2225        );
2226        let sites = all("fn f(bits: &mut u8, mask: u8) { *bits ^= mask; *bits <<= 1 }");
2227        let arith: Vec<&Site> = sites
2228            .iter()
2229            .filter(|s| matches!(s.kind, SiteKind::Arith { .. }))
2230            .collect();
2231        assert_eq!(describe(arith[0], Mutation::ArithSwap), "`*bits &= mask`");
2232        assert_eq!(describe(arith[0], Mutation::ArithSwap2), "`*bits |= mask`");
2233        let collect = site_of("fn f(bits: &mut u8, mask: u8) { *bits |= mask }");
2234        assert_eq!(
2235            arith_gap_finding("f.rs", &collect, Mutation::ArithSwap2, true),
2236            None
2237        );
2238        // A shift has one replacement: no second finding.
2239        assert_eq!(
2240            arith_gap_finding("f.rs", arith[1], Mutation::ArithSwap2, true),
2241            None
2242        );
2243
2244        let sites = all("fn f(k: Option<i32>, base: O) -> O { \
2245             let d = match k { Some(n) if n > 1 => -n, _ => 0 }; O { depth: d, ..base } }");
2246        let of = |pick: &dyn Fn(&SiteKind) -> bool| sites.iter().find(|s| pick(&s.kind)).unwrap();
2247        let guard = of(&|k| matches!(k, SiteKind::Guard { .. }));
2248        assert_eq!(
2249            describe(guard, Mutation::Const(true)),
2250            "the guard `n > 1` replaced by `true`"
2251        );
2252        assert_eq!(
2253            guard_gap_finding("f.rs", guard, false, true),
2254            Finding::InputGap {
2255                at: location("f.rs", guard),
2256                survivors: vec!["the guard `n > 1` replaced by `false`".into()],
2257                survivor_count: 1,
2258                add_tests: vec!["a case where the guard `n > 1` is true".into()],
2259                observed: None,
2260                verified: true,
2261            }
2262        );
2263        let neg = of(&|k| matches!(k, SiteKind::Neg { .. }));
2264        assert_eq!(describe(neg, Mutation::Delete), "`n`");
2265        let field = of(&|k| matches!(k, SiteKind::Field { .. }));
2266        assert_eq!(
2267            describe(field, Mutation::Delete),
2268            "without the field `depth: d` (it is then `(base).depth`)"
2269        );
2270        let body = of(&|k| matches!(k, SiteKind::Body { .. }));
2271        assert_eq!(
2272            describe(body, Mutation::Delete),
2273            "the body of `f` replaced by `Default::default()`"
2274        );
2275        assert_eq!(
2276            location("f.rs", body).code,
2277            "fn f(k: Option<i32>, base: O) -> O"
2278        );
2279    }
2280}