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