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