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