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