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/// Top-level JSON/JSONL schema version emitted by `tmt`.
11pub const SCHEMA_VERSION: u32 = 1;
12
13#[derive(Clone, Debug, Default, PartialEq, Serialize)]
14pub struct Location {
15    pub file: String,
16    pub line: usize,
17    pub column: usize,
18    pub code: String,
19    /// The function or constant the code is in (`Store::commit`); empty where unknown.
20    #[serde(skip_serializing_if = "String::is_empty")]
21    pub item: String,
22    /// What the finding at this place is known by across runs: see [`finding_id`].
23    #[serde(skip_serializing_if = "String::is_empty")]
24    pub id: String,
25}
26
27/// The name a finding keeps from run to run: its kind, its file, the item it is in, its
28/// code, and which of the places with that code in that item it is (0 for the first).
29/// Lines are not in it, so code that moves keeps its name, and neither are the words
30/// that describe the surviving mutants, so those can be improved.
31pub fn finding_id(kind: &str, at: &Location, nth: usize) -> String {
32    format!("{kind}|{}|{}|{}|{nth}", at.file, at.item, at.code)
33}
34
35#[derive(Clone, Debug, PartialEq, Serialize)]
36#[serde(rename_all = "snake_case", tag = "kind")]
37pub enum Finding {
38    /// No test input can tell these mutants from the original.
39    InputGap {
40        #[serde(flatten)]
41        at: Location,
42        /// Source-level form of mutants that pass every test.
43        survivors: Vec<String>,
44        /// How many mutants the gap lets through in total.
45        survivor_count: u128,
46        /// Inputs to add, in words.
47        add_tests: Vec<String>,
48        /// What the tests did feed the comparison.
49        observed: Option<String>,
50        /// Whether the tests were re-run against a survivor to confirm.
51        verified: bool,
52    },
53    /// Tests execute the changed behaviour, and still pass.
54    AssertionGap {
55        #[serde(flatten)]
56        at: Location,
57        survivors: Vec<String>,
58        /// Tests whose execution changed under the mutants but did not fail.
59        tests: Vec<String>,
60        /// What one surviving mutant changes later in those tests: the places an
61        /// assertion could catch it. Empty when that was not looked into.
62        effects: Vec<String>,
63        /// The mutant whose effects those are, as it is written in `survivors`.
64        effects_of: Option<String>,
65        #[serde(skip_serializing_if = "Option::is_none")]
66        witness: Option<VerifiedWitness>,
67    },
68    /// A mutant that was built on its own passes every test, and nothing was recorded
69    /// that says why: whether no test runs the code (nothing can be recorded in a
70    /// `const fn`), or one does and does not look at the result.
71    Survivor {
72        #[serde(flatten)]
73        at: Location,
74        survivors: Vec<String>,
75        #[serde(skip_serializing_if = "Option::is_none")]
76        witness: Option<VerifiedWitness>,
77        /// Set when the mutant is a change undone (`--since`): the revision whose code
78        /// was put back.
79        #[serde(skip_serializing_if = "Option::is_none")]
80        change_since: Option<String>,
81        /// What to add, when the kind of mutant says it and nothing was verified.
82        #[serde(skip_serializing_if = "Option::is_none")]
83        advice: Option<String>,
84    },
85}
86
87#[derive(Clone, Debug, PartialEq, Serialize)]
88pub struct VerifiedWitness {
89    pub call: String,
90    pub original: String,
91    pub mutant: String,
92    pub assertion: String,
93    /// When the original and mutant returned the same multi-field struct differing on one
94    /// field (recursively), the narrowed dotted field path (e.g. `"fee"` or `"inner.fee"`).
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub field: Option<String>,
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub guidance: Option<String>,
99    #[serde(skip_serializing_if = "Option::is_none")]
100    pub individually_killed: Option<usize>,
101    /// The test that makes the call, where the values are those the call has there:
102    /// after what that test does before it. In a test of its own it may return another.
103    #[serde(skip_serializing_if = "Option::is_none")]
104    pub in_test: Option<String>,
105    /// The line of the finding's file on which that test makes the call.
106    #[serde(skip_serializing_if = "Option::is_none")]
107    pub in_test_line: Option<usize>,
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub in_test_column: Option<usize>,
110}
111
112impl Finding {
113    pub fn at(&self) -> &Location {
114        let (Finding::InputGap { at, .. }
115        | Finding::AssertionGap { at, .. }
116        | Finding::Survivor { at, .. }) = self;
117        at
118    }
119
120    pub fn at_mut(&mut self) -> &mut Location {
121        let (Finding::InputGap { at, .. }
122        | Finding::AssertionGap { at, .. }
123        | Finding::Survivor { at, .. }) = self;
124        at
125    }
126
127    pub fn survivors(&self) -> &[String] {
128        let (Finding::InputGap { survivors, .. }
129        | Finding::AssertionGap { survivors, .. }
130        | Finding::Survivor { survivors, .. }) = self;
131        survivors
132    }
133
134    pub(crate) fn set_witness(&mut self, evidence: VerifiedWitness) {
135        match self {
136            Self::AssertionGap { witness, .. } | Self::Survivor { witness, .. } => {
137                if witness.is_none() {
138                    *witness = Some(evidence);
139                }
140            }
141            Self::InputGap { .. } => {}
142        }
143    }
144
145    /// The kind as the JSON report and the names of findings spell it.
146    pub fn kind(&self) -> &'static str {
147        match self {
148            Finding::InputGap { .. } => "input_gap",
149            Finding::AssertionGap { .. } => "assertion_gap",
150            Finding::Survivor { .. } => "survivor",
151        }
152    }
153}
154
155/// What decides which code cargo compiles, as given on the command line.
156#[derive(Clone, Debug, Default, PartialEq, Serialize)]
157pub struct CargoConfig {
158    pub features: Vec<String>,
159    pub all_features: bool,
160    pub no_default_features: bool,
161    pub locked: bool,
162}
163
164/// What a run looked at and how: a report says nothing about what is outside of it.
165#[derive(Clone, Debug, Default, PartialEq, Serialize)]
166pub struct Nextest {
167    #[serde(skip_serializing_if = "Option::is_none")]
168    pub profile: Option<String>,
169}
170
171#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
172pub struct Shard {
173    pub index: usize,
174    pub count: usize,
175    pub round_robin: bool,
176}
177
178#[derive(Clone, Debug, Default, PartialEq, Serialize)]
179pub struct Analysis {
180    /// The package's directory in its git repository (`crates/core/`; empty at the top).
181    pub package_path: String,
182    /// Only the code changed since this revision.
183    pub since: Option<String>,
184    /// Only these lines.
185    pub lines: Vec<String>,
186    /// The packages whose tests were run.
187    pub tests_of: Vec<String>,
188    pub cargo: CargoConfig,
189    pub opt_level: Option<u8>,
190    #[serde(skip_serializing_if = "Option::is_none")]
191    pub timeout_seconds: Option<u64>,
192    #[serde(skip_serializing_if = "Option::is_none")]
193    pub baseline_jobs: Option<usize>,
194    pub timeout_recheck: &'static str,
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub wrapper_grace_seconds: Option<u64>,
197    /// Mutants that need a build of their own were run.
198    pub rebuild: bool,
199    /// Predicted survivors were re-run.
200    pub verified: bool,
201    pub doc_tests: bool,
202    #[serde(skip_serializing_if = "std::ops::Not::not")]
203    pub source_only: bool,
204    #[serde(skip_serializing_if = "std::ops::Not::not")]
205    pub literal_operators: bool,
206    #[serde(skip_serializing_if = "Option::is_none")]
207    pub shard: Option<Shard>,
208    #[serde(skip_serializing_if = "Option::is_none")]
209    pub nextest: Option<Nextest>,
210    #[serde(skip_serializing_if = "Vec::is_empty")]
211    pub error_values: Vec<String>,
212    #[serde(skip_serializing_if = "Option::is_none")]
213    pub test_selection: Option<TestSelection>,
214    #[serde(skip_serializing_if = "std::ops::Not::not")]
215    pub git_index: bool,
216    #[serde(skip_serializing_if = "Vec::is_empty")]
217    pub copy_fixtures: Vec<PathBuf>,
218    #[serde(skip_serializing_if = "Vec::is_empty")]
219    pub copy_fixture_excludes: Vec<PathBuf>,
220    #[serde(skip_serializing_if = "Vec::is_empty")]
221    pub output_fixtures: Vec<crate::output_fixture::Fixture>,
222    #[serde(skip_serializing_if = "Vec::is_empty")]
223    pub stage_external: Vec<crate::driver::StageExternal>,
224    #[serde(skip_serializing_if = "Option::is_none")]
225    pub checkpoint: Option<PathBuf>,
226}
227
228#[derive(Clone, Debug, Default, PartialEq, Serialize)]
229pub struct TestSelection {
230    pub build_scope: TestBuildScope,
231    pub wrapper: Option<String>,
232    pub tests: Vec<String>,
233}
234
235#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
236#[serde(rename_all = "snake_case")]
237pub enum TestBuildScope {
238    #[default]
239    PackageWide,
240    SelectedTargets,
241}
242
243#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
244#[serde(rename_all = "snake_case")]
245pub enum Evaluation {
246    NoSites,
247    NoMutantsExecuted,
248    /// At least one mutant ran, but other mutants were left unbuilt (`--rebuild`),
249    /// could not be evaluated, had skipped probes, or had unconfirmed timeouts.
250    Partial,
251}
252
253/// Partition of [`Report::mutants_survived`] by what happened to each surviving mutant.
254///
255/// The fields are mutually exclusive and exhaustive:
256/// `reported + suppressed + redundant_constant + preexisting_unchanged + unchanged_not_compared + unconfirmed_gap == mutants_survived`.
257#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
258pub struct SurvivorBreakdown {
259    /// Surviving mutants emitted in [`Report::findings`] (after suppressions).
260    /// Note that one finding can group multiple surviving mutants at the same site.
261    pub reported: usize,
262    /// Surviving mutants whose finding was suppressed by `// tmt:ignore` or `--baseline`.
263    pub suppressed: usize,
264    /// Surviving mutants omitted because an enclosing or sole expression was already
265    /// classified as constant in the tests.
266    pub redundant_constant: usize,
267    /// Surviving mutants in unchanged code (reached by changed tests under `--since`)
268    /// confirmed to have also survived the earlier tests, so they are not regressions.
269    pub preexisting_unchanged: usize,
270    /// Surviving mutants in unchanged code (under `--since`) whose status against the
271    /// earlier tests could not be evaluated (earlier tests failed to build/pass or the
272    /// mutant run was unable/unconfirmed).
273    pub unchanged_not_compared: usize,
274    /// Surviving confirmation mutants whose predicted gap was not confirmed
275    /// (another confirmation mutant for the same gap was refuted or not evaluated).
276    pub unconfirmed_gap: usize,
277}
278
279impl SurvivorBreakdown {
280    /// Total surviving mutants accounted for across all categories, returning `None` on overflow.
281    pub fn checked_total(&self) -> Option<usize> {
282        self.reported
283            .checked_add(self.suppressed)?
284            .checked_add(self.redundant_constant)?
285            .checked_add(self.preexisting_unchanged)?
286            .checked_add(self.unchanged_not_compared)?
287            .checked_add(self.unconfirmed_gap)
288    }
289
290    /// Total surviving mutants accounted for across all categories.
291    pub fn total(&self) -> usize {
292        self.reported
293            + self.suppressed
294            + self.redundant_constant
295            + self.preexisting_unchanged
296            + self.unchanged_not_compared
297            + self.unconfirmed_gap
298    }
299
300    /// Surviving mutants intentionally not emitted as findings (excluding suppressions).
301    pub fn unreported(&self) -> usize {
302        self.redundant_constant
303            + self.preexisting_unchanged
304            + self.unchanged_not_compared
305            + self.unconfirmed_gap
306    }
307}
308
309#[derive(Clone, Debug, Default, PartialEq, Serialize)]
310pub struct TimeoutRechecks {
311    pub first_pass: usize,
312    pub confirmed: usize,
313    pub recovered: usize,
314    pub unconfirmed: usize,
315}
316
317impl TimeoutRechecks {
318    fn is_empty(&self) -> bool {
319        self.first_pass == 0
320    }
321}
322
323#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
324#[serde(rename_all = "snake_case")]
325pub enum SkipReason {
326    ProbeCompileError,
327    ProbeReplacedBySourceRebuild,
328    RequiresSourceRebuild,
329    SourceNotBuilt,
330    UnparseableSource,
331}
332
333#[derive(Clone, Debug, PartialEq, Serialize)]
334pub struct SkippedSite {
335    #[serde(flatten)]
336    pub at: Location,
337    pub end_line: usize,
338    pub end_column: usize,
339    pub reason: SkipReason,
340    #[serde(skip_serializing_if = "Option::is_none")]
341    pub diagnostic: Option<String>,
342}
343
344impl SkippedSite {
345    pub(crate) fn new(
346        at: Location,
347        (end_line, end_column): (usize, usize),
348        reason: SkipReason,
349        diagnostic: Option<String>,
350    ) -> Self {
351        Self {
352            at,
353            end_line,
354            end_column,
355            reason,
356            diagnostic,
357        }
358    }
359}
360
361fn is_zero_usize(value: &usize) -> bool {
362    *value == 0
363}
364
365/// What a run that was asked to check itself found (`--audit`).
366#[derive(Clone, Debug, Default, PartialEq, Serialize)]
367pub struct Audit {
368    /// Surviving mutants that were run once more, against every test of every binary.
369    pub sampled: usize,
370    /// How many surviving mutants there were to choose from.
371    pub survivors: usize,
372    /// Sampled survivors whose all-tests re-run could not be judged (`Unable` or unconfirmed timeout).
373    #[serde(skip_serializing_if = "is_zero_usize")]
374    pub not_audited: usize,
375    /// Where one of those failed a test it had not been run against: the tests were not
376    /// chosen as they should have been, or do not always do the same.
377    pub disagreements: Vec<Location>,
378    /// Test binaries whose second recorded run was not like the first, with the number
379    /// of records (what one test saw at one site) that differ.
380    pub trace_differences: Vec<TraceDifference>,
381    /// Mutants that were run as probes and chosen to be built from the source as well.
382    pub rebuilt: usize,
383    /// Of those, the ones that built and whose two results could be compared.
384    pub compared: usize,
385    /// And the ones that did not build (or whose probe run could not be evaluated):
386    /// nothing is known about them.
387    pub not_compared: usize,
388    /// Where the two did not agree on whether the tests pass.
389    pub source_disagreements: Vec<SourceDisagreement>,
390}
391
392/// A mutant on which its probe and its source form do not agree.
393#[derive(Clone, Debug, Default, PartialEq, Serialize)]
394pub struct SourceDisagreement {
395    #[serde(flatten)]
396    pub at: Location,
397    pub mutant: String,
398    /// `passes` or `fails`: what the tests did with the probe, and with the source.
399    pub as_probe: String,
400    pub built: String,
401}
402
403#[derive(Clone, Debug, Default, PartialEq, Serialize)]
404pub struct TraceDifference {
405    pub binary: String,
406    pub records: usize,
407    #[serde(skip_serializing_if = "std::ops::Not::not")]
408    pub rerun_failed: bool,
409}
410
411/// A source edit in the candidate catalogue. Byte offsets refer to the original file.
412#[derive(Clone, Debug, PartialEq, Serialize)]
413pub struct CandidateEdit {
414    pub file: String,
415    pub line: usize,
416    pub column: usize,
417    pub start: usize,
418    pub end: usize,
419    pub before: String,
420    pub replacement: String,
421}
422
423#[derive(Clone, Debug, PartialEq, Serialize)]
424pub struct Candidate {
425    pub what: String,
426    pub into: String,
427    pub requires_rebuild: bool,
428    pub edits: Vec<CandidateEdit>,
429}
430
431#[derive(Clone, Debug, PartialEq, Serialize)]
432pub struct Report {
433    pub schema_version: u32,
434    pub package: String,
435    #[serde(skip_serializing_if = "Option::is_none")]
436    pub mutants: Option<Vec<Candidate>>,
437    pub analysis: Analysis,
438    /// Present when the run was asked to check itself.
439    #[serde(skip_serializing_if = "Option::is_none")]
440    pub audit: Option<Audit>,
441    #[serde(skip_serializing_if = "Option::is_none")]
442    pub evaluation: Option<Evaluation>,
443    pub sites: usize,
444    /// Sites that could not be instrumented (the probe did not compile there).
445    pub skipped_sites: usize,
446    #[serde(skip_serializing_if = "Vec::is_empty")]
447    pub skipped: Vec<SkippedSite>,
448    /// Values a function's body was to be replaced by that do not have its type
449    /// (`Default::default()` for a type without a default): those mutants do not exist.
450    pub unviable_mutants: usize,
451    /// Mutants that need a build of their own and were not asked for (`--rebuild`).
452    pub mutants_not_built: usize,
453    /// Mutants that could not be run as what they are (a range that ends at the largest
454    /// value of its type cannot be made to include it): neither killed nor survivors.
455    pub mutants_not_evaluated: usize,
456    /// Of those, the mutants of code that is not part of this build (another target's
457    /// file, or a `cfg` the features turn off).
458    pub mutants_not_compiled: usize,
459    pub mutants_run: usize,
460    pub mutants_killed: usize,
461    /// Killed mutants that were stopped by the timeout (typically an endless loop).
462    /// This is a subset of `mutants_killed`.
463    pub mutants_timed_out: usize,
464    /// Evaluated mutants that passed the tests (`mutants_run - mutants_killed`).
465    pub mutants_survived: usize,
466    /// Complete accounting of `mutants_survived` by disposition.
467    pub survivor_breakdown: SurvivorBreakdown,
468    #[serde(skip_serializing_if = "TimeoutRechecks::is_empty")]
469    pub timeout_rechecks: TimeoutRechecks,
470    pub findings: Vec<Finding>,
471    /// Findings left out because of a `// tmt:ignore` comment or the baseline.
472    pub suppressed: usize,
473    /// Code no test executes.
474    pub unreached: Vec<Location>,
475    /// Survivors predicted from the trace that a re-run killed: the tests are not deterministic.
476    pub unstable: Vec<Location>,
477    /// Findings in code that did not change, of a file whose tests did (`--since`): the
478    /// tests as they were at the revision found these mutants out.
479    #[serde(skip_serializing_if = "Vec::is_empty")]
480    pub weakened: Vec<Location>,
481}
482
483impl Default for Report {
484    fn default() -> Self {
485        Self {
486            schema_version: SCHEMA_VERSION,
487            package: String::new(),
488            mutants: None,
489            analysis: Analysis::default(),
490            audit: None,
491            evaluation: None,
492            sites: 0,
493            skipped_sites: 0,
494            skipped: Vec::new(),
495            unviable_mutants: 0,
496            mutants_not_built: 0,
497            mutants_not_evaluated: 0,
498            mutants_not_compiled: 0,
499            mutants_run: 0,
500            mutants_killed: 0,
501            mutants_timed_out: 0,
502            mutants_survived: 0,
503            survivor_breakdown: SurvivorBreakdown::default(),
504            timeout_rechecks: TimeoutRechecks::default(),
505            findings: Vec::new(),
506            suppressed: 0,
507            unreached: Vec::new(),
508            unstable: Vec::new(),
509            weakened: Vec::new(),
510        }
511    }
512}
513
514impl Report {
515    pub(crate) fn record_evaluation(&mut self) {
516        self.evaluation = if self.mutants_run == 0 {
517            if self.sites == 0
518                && self.skipped.is_empty()
519                && self.mutants_not_built == 0
520                && self.mutants_not_evaluated == 0
521            {
522                Some(Evaluation::NoSites)
523            } else {
524                Some(Evaluation::NoMutantsExecuted)
525            }
526        } else if self.mutants_not_built > 0
527            || self.mutants_not_evaluated > 0
528            || self.skipped_sites > 0
529            || self.timeout_rechecks.unconfirmed > 0
530            || self.survivor_breakdown.unchanged_not_compared > 0
531            || (self.analysis.source_only && self.mutants_timed_out > 0)
532            || self
533                .skipped
534                .iter()
535                .any(|entry| entry.reason == SkipReason::UnparseableSource)
536        {
537            Some(Evaluation::Partial)
538        } else {
539            None
540        };
541    }
542
543    /// Whether the mutant counts are internally consistent:
544    /// - `mutants_run == mutants_killed + mutants_survived`
545    /// - `mutants_timed_out <= mutants_killed`
546    /// - `mutants_survived == survivor_breakdown.checked_total()`
547    pub fn counts_reconcile(&self) -> bool {
548        self.mutants_killed.checked_add(self.mutants_survived) == Some(self.mutants_run)
549            && self.mutants_timed_out <= self.mutants_killed
550            && self.survivor_breakdown.checked_total() == Some(self.mutants_survived)
551    }
552
553    /// Puts the findings in reading order. Sites are numbered as they are discovered, and
554    /// a statement is discovered before the expressions of the statements above it.
555    pub fn sort_findings(&mut self) {
556        self.findings.sort_by(|a, b| {
557            let (a, b) = (a.at(), b.at());
558            (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column))
559        });
560    }
561
562    /// Whether the run found something to act on: a gap, an unstable prediction, or an
563    /// audit discrepancy (which means the report cannot be trusted as it stands).
564    pub fn has_gaps(&self) -> bool {
565        !self.findings.is_empty()
566            || !self.unstable.is_empty()
567            || self.audit.as_ref().is_some_and(|audit| {
568                !audit.disagreements.is_empty()
569                    || !audit.source_disagreements.is_empty()
570                    || !audit.trace_differences.is_empty()
571            })
572    }
573}
574
575pub fn location(file: &str, site: &Site) -> Location {
576    Location {
577        file: file.to_string(),
578        line: site.line,
579        column: site.column,
580        code: one_line(&site.text),
581        ..Location::default()
582    }
583}
584
585/// A revision as a reader wants it: a full object name cut to its first twelve digits.
586pub(crate) fn short_revision(revision: &str) -> &str {
587    let full = revision.len() >= 40 && revision.bytes().all(|byte| byte.is_ascii_hexdigit());
588    if full { &revision[..12] } else { revision }
589}
590
591pub(crate) fn one_line(code: &str) -> String {
592    const LIMIT: usize = 100;
593    const ELLIPSIS: &str = "...";
594    const PREFIX: usize = LIMIT - ELLIPSIS.len();
595
596    // A code preview can contain four bytes per displayed character.
597    // tmt:ignore performance only: the loop below gives the same text for code of any length
598    if code.len() <= 4 * LIMIT {
599        let mut words = code.split_whitespace();
600        let Some(first) = words.next() else {
601            return String::new();
602        };
603        let mut output = String::with_capacity(code.len());
604        output.push_str(first);
605        for word in words {
606            output.push(' ');
607            output.push_str(word);
608        }
609        // tmt:ignore performance only: text of more than LIMIT characters has more than LIMIT bytes, the first test only saves counting
610        if output.len() > LIMIT && output.chars().count() > LIMIT {
611            let cut = output.char_indices().nth(PREFIX).unwrap().0;
612            output.truncate(cut);
613            output.push_str(ELLIPSIS);
614        }
615        return output;
616    }
617
618    let mut output = String::with_capacity(LIMIT);
619    let mut width = 0;
620    let mut shortened_at = 0;
621    let mut separated = false;
622    for ch in code.chars() {
623        if ch.is_whitespace() {
624            separated = width != 0;
625            continue;
626        }
627        for ch in [separated.then_some(' '), Some(ch)].into_iter().flatten() {
628            if width == LIMIT {
629                output.truncate(shortened_at);
630                output.push_str(ELLIPSIS);
631                return output;
632            }
633            output.push(ch);
634            width += 1;
635            if width == PREFIX {
636                shortened_at = output.len();
637            }
638        }
639        separated = false;
640    }
641    output
642}
643
644/// Value of a float literal such as `30.5`, `1e3` or `2.5_f32`.
645fn float_literal(text: &str) -> Option<f64> {
646    let text = text.trim().replace('_', "");
647    let text = text
648        .strip_suffix("f32")
649        .or(text.strip_suffix("f64"))
650        .unwrap_or(&text);
651    let looks_numeric = text.starts_with(|c: char| c.is_ascii_digit() || c == '-')
652        && text
653            .chars()
654            .all(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E'));
655    if looks_numeric {
656        text.parse().ok()
657    } else {
658        None
659    }
660}
661
662/// Floats in reports: the shortest text that reads back as the same value, so nothing is
663/// rounded away.
664fn show_float(v: f64) -> String {
665    format!("{v:?}")
666}
667
668/// Source-level form of a mutant.
669pub fn describe(site: &Site, m: Mutation) -> String {
670    match &site.kind {
671        SiteKind::Stmt => format!("delete `{}`", one_line(&site.text)),
672        SiteKind::Neg { operand, .. } => format!("`{}`", one_line(operand)),
673        SiteKind::Guard { .. } => match m {
674            Mutation::Const(value) => {
675                format!("the guard `{}` replaced by `{value}`", one_line(&site.text))
676            }
677            _ => format!("another guard than `{}`", one_line(&site.text)),
678        },
679        SiteKind::Field {
680            from_base: Some(from_base),
681            ..
682        } => format!(
683            "without the field `{}` (it is then `{from_base}`)",
684            one_line(&site.text)
685        ),
686        SiteKind::Field {
687            from_base: None, ..
688        } => format!("without the field `{}`", one_line(&site.text)),
689        SiteKind::Body { name, value, .. } => format!("the body of `{name}` replaced by `{value}`"),
690        SiteKind::Not { operand, .. } => format!("`{}`", one_line(operand)),
691        SiteKind::Return { name, option, .. } => match (m, option) {
692            (Mutation::Const(false), Some(_)) => format!("`{name}` returning `None`"),
693            (Mutation::Const(value), _) => format!("`{name}` returning `{value}`"),
694            _ => format!("`{name}` returning something else"),
695        },
696        SiteKind::Range {
697            inclusive,
698            lhs,
699            rhs,
700            ..
701        } => {
702            let dots = if *inclusive { ".." } else { "..=" };
703            format!("`{}{dots}{}`", one_line(lhs), one_line(rhs))
704        }
705        SiteKind::Arm { pattern, .. } => format!("remove the arm `{} => ..`", one_line(pattern)),
706        SiteKind::MinMax {
707            max,
708            receiver,
709            argument,
710            ..
711        } => {
712            let other = if *max { "min" } else { "max" };
713            format!("`{}.{other}({})`", one_line(receiver), one_line(argument))
714        }
715        SiteKind::SliceEnd {
716            first, receiver, ..
717        } => {
718            let other = if *first { "last" } else { "first" };
719            format!("`{}.{other}()`", one_line(receiver))
720        }
721        SiteKind::StrAffix {
722            receiver, pattern, ..
723        } => format!("`{}.contains({})`", one_line(receiver), one_line(pattern)),
724        SiteKind::StrReplace {
725            replace_all,
726            receiver,
727            from,
728            to,
729            ..
730        } => {
731            let (r, f, t) = (one_line(receiver), one_line(from), one_line(to));
732            if *replace_all {
733                format!("`{r}.replacen({f}, {t}, 1)`")
734            } else {
735                format!("`{r}.replace({f}, {t})`")
736            }
737        }
738        SiteKind::Clamp {
739            receiver,
740            low,
741            high,
742            ..
743        } => match m {
744            Mutation::ClampDropLower => format!("`{}.min({})`", one_line(receiver), one_line(high)),
745            _ => format!("`{}.max({})`", one_line(receiver), one_line(low)),
746        },
747        SiteKind::Rounding { op, receiver, .. } => {
748            let alt = match m {
749                Mutation::RoundAlt2 => op.alt2(),
750                _ => op.alt1(),
751            };
752            format!("`{}.{}()`", one_line(receiver), alt.name())
753        }
754        SiteKind::Quantifier {
755            all,
756            receiver,
757            predicate,
758            ..
759        } => {
760            let other = if *all { "any" } else { "all" };
761            format!("`{}.{other}({})`", one_line(receiver), one_line(predicate))
762        }
763        SiteKind::LiteralSet {
764            receiver, argument, ..
765        } => format!(
766            "without a literal element in `{}.contains({})`",
767            one_line(receiver),
768            one_line(argument)
769        ),
770        SiteKind::Logic { and, lhs, rhs, .. } => {
771            let (lhs, rhs) = (one_line(lhs), one_line(rhs));
772            match m {
773                // Both operands are still evaluated whenever the original evaluates them;
774                // only the value of one is ignored. The forms below say exactly that.
775                Mutation::LogicDropRhs if *and => format!("`{lhs} && {{ {rhs}; true }}`"),
776                Mutation::LogicDropRhs => format!("`{lhs} || {{ {rhs}; false }}`"),
777                Mutation::LogicDropLhs => format!("`{{ {lhs}; {rhs} }}`"),
778                _ => format!("`{lhs} {} {rhs}`", if *and { "||" } else { "&&" }),
779            }
780        }
781        SiteKind::Arith {
782            op,
783            assign,
784            lhs,
785            rhs,
786            ..
787        } => {
788            let eq = if *assign { "=" } else { "" };
789            let other = match m {
790                Mutation::ArithSwap2 => op.swapped2().unwrap_or(op.swapped()),
791                _ => op.swapped(),
792            };
793            format!(
794                "`{} {}{eq} {}`",
795                one_line(lhs),
796                other.symbol(),
797                one_line(rhs)
798            )
799        }
800        SiteKind::Cmp {
801            op,
802            lhs,
803            rhs,
804            literal,
805            ..
806        } => {
807            let (lhs, rhs) = (one_line(lhs), one_line(rhs));
808            let sym = op.symbol();
809            match m {
810                Mutation::Const(c) => format!("`{c}`"),
811                Mutation::Op(op2) => format!("`{lhs} {} {rhs}`", op2.symbol()),
812                Mutation::Shift(d) => {
813                    let display = literal_display_kind(&lhs, &rhs, *literal);
814                    match literal {
815                        LiteralSide::Rhs(k) => {
816                            format!("`{lhs} {sym} {}`", format_shifted_literal(k + d, display))
817                        }
818                        // k op rhs + d  <=>  k - d op rhs
819                        LiteralSide::Lhs(k) => {
820                            format!("`{} {sym} {rhs}`", format_shifted_literal(k - d, display))
821                        }
822                        LiteralSide::None => match (op, d) {
823                            (CmpOp::Ge, 1) => format!("`{lhs} > {rhs}`"),
824                            (CmpOp::Gt, -1) => format!("`{lhs} >= {rhs}`"),
825                            (CmpOp::Le, -1) => format!("`{lhs} < {rhs}`"),
826                            (CmpOp::Lt, 1) => format!("`{lhs} <= {rhs}`"),
827                            // Meant as arithmetic on whole numbers: in the operands' own
828                            // type the addition could overflow, the mutant that was run cannot.
829                            // tmt:ignore a shift of 0 is never planned, so `>=` is the same
830                            (_, d) if d > 0 => {
831                                format!("`{lhs} {sym} {rhs} + {d}` (without overflow)")
832                            }
833                            (_, d) => format!("`{lhs} {sym} {rhs} - {}` (without overflow)", -d),
834                        },
835                    }
836                }
837                Mutation::ShiftF(d) => match (float_literal(&lhs), float_literal(&rhs)) {
838                    (None, Some(k)) => format!("`{lhs} {sym} {}`", show_float(k + d)),
839                    (Some(k), None) => format!("`{} {sym} {rhs}`", show_float(k - d)),
840                    // tmt:ignore a shift of 0 is never planned, so any threshold near it is the same
841                    _ if d > 0.0 => format!("`{lhs} {sym} {rhs} + {}`", show_float(d)),
842                    _ => format!("`{lhs} {sym} {rhs} - {}`", show_float(-d)),
843                },
844                _ => format!("`!({lhs} {sym} {rhs})`"),
845            }
846        }
847    }
848}
849
850#[derive(Clone, Copy, PartialEq, Eq, Debug)]
851enum LiteralDisplay {
852    Int,
853    Byte,
854    Char,
855}
856
857fn literal_display_kind(lhs: &str, rhs: &str, literal: LiteralSide) -> LiteralDisplay {
858    let text = match literal {
859        LiteralSide::Rhs(_) => rhs,
860        LiteralSide::Lhs(_) => lhs,
861        LiteralSide::None => return LiteralDisplay::Int,
862    };
863    let Ok(mut expr) = syn::parse_str::<syn::Expr>(text) else {
864        return LiteralDisplay::Int;
865    };
866    loop {
867        match expr {
868            syn::Expr::Paren(inner) => expr = *inner.expr,
869            syn::Expr::Group(inner) => expr = *inner.expr,
870            _ => break,
871        }
872    }
873    match expr {
874        syn::Expr::Lit(syn::ExprLit {
875            lit: syn::Lit::Byte(_),
876            ..
877        }) => LiteralDisplay::Byte,
878        syn::Expr::Lit(syn::ExprLit {
879            lit: syn::Lit::Char(_),
880            ..
881        }) => LiteralDisplay::Char,
882        _ => LiteralDisplay::Int,
883    }
884}
885
886fn format_byte_lit(b: u8) -> String {
887    match b {
888        b'\'' => "b'\\''".to_string(),
889        b'\\' => "b'\\\\'".to_string(),
890        b'\n' => "b'\\n'".to_string(),
891        b'\r' => "b'\\r'".to_string(),
892        b'\t' => "b'\\t'".to_string(),
893        b'\0' => "b'\\0'".to_string(),
894        0x20..=0x7e => format!("b'{}'", b as char),
895        _ => format!("b'\\x{b:02x}'"),
896    }
897}
898
899fn ord_to_char(ord: i128) -> Option<char> {
900    let u = u32::try_from(ord).ok()?;
901    let scalar = if u < 0xD800 {
902        u
903    } else if u <= 0x10_D7FF {
904        u + 0x800
905    } else {
906        return None;
907    };
908    char::from_u32(scalar)
909}
910
911fn format_shifted_literal(v: i128, display: LiteralDisplay) -> String {
912    match display {
913        LiteralDisplay::Byte => u8::try_from(v)
914            .map(format_byte_lit)
915            .unwrap_or_else(|_| v.to_string()),
916        LiteralDisplay::Char => ord_to_char(v)
917            .map(|c| format!("{c:?}"))
918            .unwrap_or_else(|| v.to_string()),
919        LiteralDisplay::Int => v.to_string(),
920    }
921}
922
923fn format_literal_value(v: i128, display: LiteralDisplay) -> String {
924    match display {
925        LiteralDisplay::Byte => u8::try_from(v)
926            .map(|b| format!("{} ({b})", format_byte_lit(b)))
927            .unwrap_or_else(|_| v.to_string()),
928        LiteralDisplay::Char => ord_to_char(v)
929            .map(|c| format!("{c:?} ({})", c as u32))
930            .unwrap_or_else(|| v.to_string()),
931        LiteralDisplay::Int => v.to_string(),
932    }
933}
934
935/// The operand values that give `lhs - rhs = d`, in words.
936fn input_for(lhs: &str, rhs: &str, literal: LiteralSide, d: i128) -> String {
937    let display = literal_display_kind(lhs, rhs, literal);
938    match (literal, d) {
939        (LiteralSide::Rhs(k), d) => {
940            format!("`{lhs}` = {}", format_literal_value(k + d, display))
941        }
942        (LiteralSide::Lhs(k), d) => {
943            format!("`{rhs}` = {}", format_literal_value(k - d, display))
944        }
945        (LiteralSide::None, 0) => format!("`{lhs}` equal to `{rhs}`"),
946        // tmt:ignore 0 is taken by the arm above, so `>=` is the same
947        (LiteralSide::None, d) if d > 0 => format!("`{lhs}` = `{rhs}` + {d}"),
948        (LiteralSide::None, d) => format!("`{lhs}` = `{rhs}` - {}", -d),
949    }
950}
951
952fn observed_values(lhs: &str, rhs: &str, literal: LiteralSide, obs: &Obs) -> Option<String> {
953    if !obs.valued() {
954        return None;
955    }
956    let display = literal_display_kind(lhs, rhs, literal);
957    let ds: Vec<i128> = [obs.max_neg, obs.eq.then_some(0), obs.min_pos]
958        .into_iter()
959        .flatten()
960        .collect();
961    let text = match literal {
962        LiteralSide::Rhs(k) => {
963            let values: Vec<String> = ds
964                .iter()
965                .map(|d| format_literal_value(k + d, display))
966                .collect();
967            format!("`{lhs}` = {}", values.join(", "))
968        }
969        LiteralSide::Lhs(k) => {
970            let mut values: Vec<i128> = ds.iter().map(|d| k - d).collect();
971            values.sort();
972            let values: Vec<String> = values
973                .iter()
974                .map(|v| format_literal_value(*v, display))
975                .collect();
976            format!("`{rhs}` = {}", values.join(", "))
977        }
978        LiteralSide::None => {
979            let values: Vec<String> = ds.iter().map(i128::to_string).collect();
980            format!("`{lhs}` - `{rhs}` = {}", values.join(", "))
981        }
982    };
983    Some(format!("nearest values the tests passed: {text}"))
984}
985
986/// Builds the input-gap finding for a comparison site. `None` for gaps that are reported
987/// elsewhere (unreached code).
988pub fn input_gap_finding(
989    file: &str,
990    site: &Site,
991    gap: &InputGap,
992    obs: &Obs,
993    verified: bool,
994) -> Option<Finding> {
995    let SiteKind::Cmp {
996        op,
997        lhs,
998        rhs,
999        literal,
1000        ..
1001    } = &site.kind
1002    else {
1003        return None;
1004    };
1005    let (lhs_text, rhs_text) = (one_line(lhs), one_line(rhs));
1006    // A float shift too small to move the literal is not a different program. The
1007    // literal moves the way `describe` writes it.
1008    let moves = |d: f64| match (float_literal(&lhs_text), float_literal(&rhs_text)) {
1009        (None, Some(k)) => k + d != k,
1010        (Some(k), None) => k - d != k,
1011        _ => true,
1012    };
1013    let survivors: Vec<String> = gap
1014        .survivors()
1015        .into_iter()
1016        .filter(|m| !matches!(m, Mutation::ShiftF(d) if !moves(*d)))
1017        .map(|m| describe(site, m))
1018        .collect();
1019    let mut observed = observed_values(&lhs_text, &rhs_text, *literal, obs);
1020    let (survivor_count, add_tests) = match gap {
1021        InputGap::Unreached => return None,
1022        InputGap::OneSided { always } => (
1023            1,
1024            vec![format!(
1025                "an input that makes `{}` {}",
1026                one_line(&site.text),
1027                !always
1028            )],
1029        ),
1030        InputGap::EqualNeverObserved { flipped, float_gap } => {
1031            if let Some((lo, hi)) = float_gap {
1032                observed = Some(match (float_literal(&lhs_text), float_literal(&rhs_text)) {
1033                    (None, Some(k)) => format!(
1034                        "nearest values the tests passed: `{lhs_text}` = {}, {}; any threshold between them passes",
1035                        show_float(k + lo),
1036                        show_float(k + hi)
1037                    ),
1038                    (Some(k), None) => format!(
1039                        "nearest values the tests passed: `{rhs_text}` = {}, {}; any threshold between them passes",
1040                        show_float(k - hi),
1041                        show_float(k - lo)
1042                    ),
1043                    _ => format!(
1044                        "nearest values the tests passed: `{lhs_text}` - `{rhs_text}` = {}, {}",
1045                        show_float(*lo),
1046                        show_float(*hi)
1047                    ),
1048                });
1049            }
1050            (
1051                survivors.len() as u128,
1052                vec![format!(
1053                    "`{lhs_text}` equal to `{rhs_text}` (the original gives {}, the mutant {})",
1054                    op.eval_d(0),
1055                    flipped.eval_d(0)
1056                )],
1057            )
1058        }
1059        InputGap::Boundary {
1060            min_shift,
1061            max_shift,
1062            missing,
1063            same,
1064        } => {
1065            let add = missing
1066                .iter()
1067                .map(|d| {
1068                    format!(
1069                        "{} (the original gives {})",
1070                        input_for(&lhs_text, &rhs_text, *literal, *d),
1071                        op.eval_d(*d)
1072                    )
1073                })
1074                .collect();
1075            // Without the shifts that are no mutants: the expression cannot be a
1076            // value that tells them from the original.
1077            (((max_shift - min_shift) - (same.1 - same.0)) as u128, add)
1078        }
1079    };
1080    Some(Finding::InputGap {
1081        at: location(file, site),
1082        survivors,
1083        survivor_count,
1084        add_tests,
1085        observed,
1086        verified,
1087    })
1088}
1089
1090/// Input gap at `a && b` / `a || b`: one operand never decides the result in any test.
1091pub fn logic_gap_finding(
1092    file: &str,
1093    site: &Site,
1094    gap: LogicGap,
1095    verified: bool,
1096) -> Option<Finding> {
1097    let SiteKind::Logic { and, lhs, rhs, .. } = &site.kind else {
1098        return None;
1099    };
1100    let (lhs, rhs) = (one_line(lhs), one_line(rhs));
1101    let (mutation, add) = match (gap, and) {
1102        (LogicGap::Unreached, _) => return None,
1103        (LogicGap::RhsNeverDecides, true) => (
1104            Mutation::LogicDropRhs,
1105            format!("a case where `{lhs}` is true and `{rhs}` is false"),
1106        ),
1107        (LogicGap::RhsNeverDecides, false) => (
1108            Mutation::LogicDropRhs,
1109            format!("a case where `{lhs}` is false and `{rhs}` is true"),
1110        ),
1111        (LogicGap::LhsNeverDecides, true) => (
1112            Mutation::LogicDropLhs,
1113            format!("a case where `{lhs}` is false"),
1114        ),
1115        (LogicGap::LhsNeverDecides, false) => (
1116            Mutation::LogicDropLhs,
1117            format!("a case where `{lhs}` is true"),
1118        ),
1119    };
1120    Some(Finding::InputGap {
1121        at: location(file, site),
1122        survivors: vec![describe(site, mutation)],
1123        survivor_count: 1,
1124        add_tests: vec![add],
1125        observed: None,
1126        verified,
1127    })
1128}
1129
1130/// Input gap at `v.first()` / `v.last()`: no test gave more than one element.
1131pub fn slice_end_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
1132    let SiteKind::SliceEnd { receiver, .. } = &site.kind else {
1133        return None;
1134    };
1135    Some(Finding::InputGap {
1136        at: location(file, site),
1137        survivors: vec![describe(site, Mutation::OtherEnd)],
1138        survivor_count: 1,
1139        add_tests: vec![format!(
1140            "`{}` with two or more elements, the first different from the last",
1141            one_line(receiver)
1142        )],
1143        observed: None,
1144        verified,
1145    })
1146}
1147
1148/// Input gap at `a.max(b)` / `a.min(b)`: the two operands were equal in every test.
1149pub fn min_max_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
1150    let SiteKind::MinMax {
1151        receiver, argument, ..
1152    } = &site.kind
1153    else {
1154        return None;
1155    };
1156    Some(Finding::InputGap {
1157        at: location(file, site),
1158        survivors: vec![describe(site, Mutation::MinMax)],
1159        survivor_count: 1,
1160        add_tests: vec![format!(
1161            "`{}` different from `{}`",
1162            one_line(receiver),
1163            one_line(argument)
1164        )],
1165        observed: None,
1166        verified,
1167    })
1168}
1169
1170/// Input gap at `s.starts_with(p)` / `s.ends_with(p)`: no test passed a string containing `p`
1171/// away from the prefix/suffix position.
1172pub fn str_affix_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
1173    let SiteKind::StrAffix {
1174        starts,
1175        receiver,
1176        pattern,
1177        ..
1178    } = &site.kind
1179    else {
1180        return None;
1181    };
1182    let where_else = if *starts { "start" } else { "end" };
1183    Some(Finding::InputGap {
1184        at: location(file, site),
1185        survivors: vec![describe(site, Mutation::StrContains)],
1186        survivor_count: 1,
1187        add_tests: vec![format!(
1188            "`{}` containing `{}` somewhere other than the {where_else}",
1189            one_line(receiver),
1190            one_line(pattern)
1191        )],
1192        observed: None,
1193        verified,
1194    })
1195}
1196
1197/// Input gap at `s.replace(a, b)` / `s.replacen(a, b, 1)`: no test had `a` occur more than once.
1198pub fn str_replace_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
1199    let SiteKind::StrReplace { receiver, from, .. } = &site.kind else {
1200        return None;
1201    };
1202    Some(Finding::InputGap {
1203        at: location(file, site),
1204        survivors: vec![describe(site, Mutation::StrReplaceMultiplicity)],
1205        survivor_count: 1,
1206        add_tests: vec![format!(
1207            "`{}` containing `{}` more than once",
1208            one_line(receiver),
1209            one_line(from)
1210        )],
1211        observed: None,
1212        verified,
1213    })
1214}
1215
1216/// Input gap at `x.clamp(lo, hi)`: no test crossed the dropped bound.
1217pub fn clamp_gap_finding(
1218    file: &str,
1219    site: &Site,
1220    mutation: Mutation,
1221    verified: bool,
1222) -> Option<Finding> {
1223    let SiteKind::Clamp {
1224        receiver,
1225        low,
1226        high,
1227        ..
1228    } = &site.kind
1229    else {
1230        return None;
1231    };
1232    let advice = if mutation == Mutation::ClampDropLower {
1233        format!(
1234            "`{}` below the lower clamp bound `{}`",
1235            one_line(receiver),
1236            one_line(low)
1237        )
1238    } else {
1239        format!(
1240            "`{}` above the upper clamp bound `{}`",
1241            one_line(receiver),
1242            one_line(high)
1243        )
1244    };
1245    Some(Finding::InputGap {
1246        at: location(file, site),
1247        survivors: vec![describe(site, mutation)],
1248        survivor_count: 1,
1249        add_tests: vec![advice],
1250        observed: None,
1251        verified,
1252    })
1253}
1254
1255/// Input gap at `x.floor()` / `.ceil()` / `.round()` / `.trunc()`: no test distinguished the rounding mode.
1256pub fn rounding_gap_finding(
1257    file: &str,
1258    site: &Site,
1259    mutation: Mutation,
1260    verified: bool,
1261) -> Option<Finding> {
1262    let SiteKind::Rounding { op, receiver, .. } = &site.kind else {
1263        return None;
1264    };
1265    let alt = if mutation == Mutation::RoundAlt2 {
1266        op.alt2()
1267    } else {
1268        op.alt1()
1269    };
1270    Some(Finding::InputGap {
1271        at: location(file, site),
1272        survivors: vec![describe(site, mutation)],
1273        survivor_count: 1,
1274        add_tests: vec![format!(
1275            "`{}` that is {}",
1276            one_line(receiver),
1277            op.differs_for(alt)
1278        )],
1279        observed: None,
1280        verified,
1281    })
1282}
1283
1284/// Input gap at a `-> bool` function that returned the same value in every test.
1285pub fn return_gap_finding(
1286    file: &str,
1287    site: &Site,
1288    always: bool,
1289    verified: bool,
1290) -> Option<Finding> {
1291    let SiteKind::Return { name, option, .. } = &site.kind else {
1292        return None;
1293    };
1294    let other = match (option, always) {
1295        (None, always) => format!("{}", !always),
1296        (Some(_), false) => "`Some`".to_string(),
1297        (Some(_), true) => "`None`".to_string(),
1298    };
1299    Some(Finding::InputGap {
1300        at: location(file, site),
1301        survivors: vec![describe(site, Mutation::Const(always))],
1302        survivor_count: 1,
1303        add_tests: vec![format!("a case where `{name}` returns {other}")],
1304        observed: None,
1305        verified,
1306    })
1307}
1308
1309/// Input gap at the guard of a match arm that had the same value in every test.
1310pub fn guard_gap_finding(file: &str, site: &Site, always: bool, verified: bool) -> Finding {
1311    Finding::InputGap {
1312        at: location(file, site),
1313        survivors: vec![describe(site, Mutation::Const(always))],
1314        survivor_count: 1,
1315        add_tests: vec![format!(
1316            "a case where the guard `{}` is {}",
1317            one_line(&site.text),
1318            !always
1319        )],
1320        observed: None,
1321        verified,
1322    }
1323}
1324
1325/// Input gap at an arithmetic operator: the swapped operator computes the same value on
1326/// every pair of operands the tests pass.
1327pub fn arith_gap_finding(
1328    file: &str,
1329    site: &Site,
1330    mutation: Mutation,
1331    verified: bool,
1332) -> Option<Finding> {
1333    let SiteKind::Arith {
1334        op,
1335        assign,
1336        lhs,
1337        rhs,
1338        ..
1339    } = &site.kind
1340    else {
1341        return None;
1342    };
1343    let (lhs, rhs) = (one_line(lhs), one_line(rhs));
1344    let eq = if *assign { "=" } else { "" };
1345    let other = match mutation {
1346        Mutation::ArithSwap2 => op.second(*assign)?,
1347        _ => op.swapped(),
1348    };
1349    let add = match (op, other) {
1350        (ArithOp::Add, ArithOp::Sub) | (ArithOp::Sub, ArithOp::Add) => {
1351            format!("`{rhs}` other than 0")
1352        }
1353        (ArithOp::BitOr, ArithOp::BitXor) | (ArithOp::BitXor, ArithOp::BitOr) => format!(
1354            "operands where `{lhs}` and `{rhs}` share at least one set bit (if their bits are disjoint by construction, `{}` and `{}` are equivalent)",
1355            op.symbol(),
1356            other.symbol()
1357        ),
1358        _ => format!(
1359            "operands for which `{lhs} {}{eq} {rhs}` and `{lhs} {}{eq} {rhs}` differ",
1360            op.symbol(),
1361            other.symbol()
1362        ),
1363    };
1364    Some(Finding::InputGap {
1365        at: location(file, site),
1366        survivors: vec![describe(site, mutation)],
1367        survivor_count: 1,
1368        add_tests: vec![add],
1369        observed: None,
1370        verified,
1371    })
1372}
1373
1374/// The report as SARIF 2.1.0, with file names relative to the repository root.
1375pub fn render_sarif(report: &Report) -> String {
1376    serde_json::to_string_pretty(&sarif_document(vec![sarif_run(report)]))
1377        .expect("JSON values serialise")
1378}
1379
1380/// The CLI's workspace SARIF has one run per member, the analysed ones in report order
1381/// and then those whose analysis could not run (`failed`: package and what went wrong).
1382/// A member that failed is a run that says so: a document without it would read as a
1383/// package with nothing to report. Each run has an id of its own, by which a service
1384/// that takes several runs of one tool keeps them apart.
1385#[doc(hidden)]
1386pub fn workspace_sarif(reports: &[Report], failed: &[(String, String)]) -> impl std::fmt::Display {
1387    let category = |package: &str| serde_json::json!({ "id": format!("tmt/{package}/") });
1388    let mut runs: Vec<serde_json::Value> = reports
1389        .iter()
1390        .map(|report| {
1391            let mut run = sarif_run(report);
1392            run["properties"]["package"] = serde_json::json!(report.package);
1393            run["automationDetails"] = category(&report.package);
1394            run["invocations"] = serde_json::json!([{ "executionSuccessful": true }]);
1395            run
1396        })
1397        .collect();
1398    for (package, error) in failed {
1399        runs.push(serde_json::json!({
1400            "tool": sarif_tool(),
1401            "automationDetails": category(package),
1402            "invocations": [{
1403                "executionSuccessful": false,
1404                "toolExecutionNotifications": [{
1405                    "level": "error",
1406                    "message": { "text": error },
1407                }],
1408            }],
1409            "properties": { "package": package },
1410            "results": [],
1411        }));
1412    }
1413    sarif_document(runs)
1414}
1415
1416/// A path as the URI reference SARIF wants: `/` between its parts, and in the parts
1417/// every byte that is not plainly allowed in one (a space, `#`, `%`, what is not ASCII)
1418/// written as `%XX`.
1419fn sarif_uri(prefix: &str, file: &str) -> String {
1420    sarif_uri_for(prefix, file, cfg!(windows))
1421}
1422
1423fn sarif_uri_for(prefix: &str, file: &str, backslash_is_separator: bool) -> String {
1424    let mut uri = String::new();
1425    for byte in prefix.bytes().chain(file.bytes()) {
1426        let byte = if backslash_is_separator && byte == b'\\' {
1427            b'/'
1428        } else {
1429            byte
1430        };
1431        match byte {
1432            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
1433                uri.push(byte as char)
1434            }
1435            _ => uri.push_str(&format!("%{byte:02X}")),
1436        }
1437    }
1438    uri
1439}
1440
1441fn sarif_tool() -> serde_json::Value {
1442    serde_json::json!({ "driver": {
1443        "name": "tmt",
1444        "rules": [
1445            { "id": "input-gap", "shortDescription": { "text": "No test input tells this mutant from the original" } },
1446            { "id": "assertion-gap", "shortDescription": { "text": "Tests run the mutated code and still pass" } },
1447            { "id": "survivor", "shortDescription": { "text": "A mutant built on its own passes every test; why is not known" } },
1448            { "id": "unstable-prediction", "shortDescription": { "text": "A predicted survivor failed when re-run; tests may be non-deterministic" } },
1449            { "id": "weakened-test", "shortDescription": { "text": "Tests since the base revision stopped catching a mutant in unchanged code" } },
1450            { "id": "audit-disagreement", "shortDescription": { "text": "Audit found a mismatch between selective/probe results and full/source execution" } }
1451        ]
1452    } })
1453}
1454
1455fn sarif_document(runs: Vec<serde_json::Value>) -> serde_json::Value {
1456    let mut document = serde_json::json!({
1457        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
1458        "version": "2.1.0",
1459    });
1460    document["runs"] = serde_json::Value::Array(runs);
1461    document
1462}
1463
1464fn sarif_run(report: &Report) -> serde_json::Value {
1465    let prefix = report.analysis.package_path.as_str();
1466    let mut results: Vec<serde_json::Value> = report
1467        .findings
1468        .iter()
1469        .map(|finding| {
1470            let (kind, at) = finding_parts(finding);
1471            let rule = match kind {
1472                "INPUT GAP" => "input-gap",
1473                "ASSERTION GAP" => "assertion-gap",
1474                _ => "survivor",
1475            };
1476            let text = format!("`{}`: {}", at.code, finding_body(finding, false).join("; "));
1477            serde_json::json!({
1478                "ruleId": rule,
1479                "level": "warning",
1480                "message": { "text": text },
1481                // What the service tells a finding of one run from that of another by.
1482                "partialFingerprints": { "tmtFindingId/v2": at.id },
1483                "locations": [{
1484                    "physicalLocation": {
1485                        "artifactLocation": { "uri": sarif_uri(prefix, &at.file) },
1486                        "region": { "startLine": at.line, "startColumn": at.column }
1487                    }
1488                }]
1489            })
1490        })
1491        .collect();
1492    for at in &report.unstable {
1493        results.push(serde_json::json!({
1494            "ruleId": "unstable-prediction",
1495            "level": "error",
1496            "message": {
1497                "text": format!(
1498                    "`{}`: trace predicted a survivor, but the re-run failed (tests may not be deterministic)",
1499                    at.code
1500                )
1501            },
1502            "locations": [{
1503                "physicalLocation": {
1504                    "artifactLocation": { "uri": sarif_uri(prefix, &at.file) },
1505                    "region": { "startLine": at.line, "startColumn": at.column }
1506                }
1507            }]
1508        }));
1509    }
1510    for at in &report.weakened {
1511        results.push(serde_json::json!({
1512            "ruleId": "weakened-test",
1513            "level": "warning",
1514            "message": {
1515                "text": format!(
1516                    "`{}`: mutant in unchanged code now survives after test changes",
1517                    at.code
1518                )
1519            },
1520            "locations": [{
1521                "physicalLocation": {
1522                    "artifactLocation": { "uri": sarif_uri(prefix, &at.file) },
1523                    "region": { "startLine": at.line, "startColumn": at.column }
1524                }
1525            }]
1526        }));
1527    }
1528    if let Some(audit) = &report.audit {
1529        for at in &audit.disagreements {
1530            results.push(serde_json::json!({
1531                "ruleId": "audit-disagreement",
1532                "level": "error",
1533                "message": {
1534                    "text": format!(
1535                        "`{}`: survived selective tests, but failed when audited against all tests",
1536                        at.code
1537                    )
1538                },
1539                "locations": [{
1540                    "physicalLocation": {
1541                        "artifactLocation": { "uri": sarif_uri(prefix, &at.file) },
1542                        "region": { "startLine": at.line, "startColumn": at.column }
1543                    }
1544                }]
1545            }));
1546        }
1547        for diff in &audit.source_disagreements {
1548            results.push(serde_json::json!({
1549                "ruleId": "audit-disagreement",
1550                "level": "error",
1551                "message": {
1552                    "text": format!(
1553                        "`{}` ({}): {} as a probe, {} built from source",
1554                        diff.at.code, diff.mutant, diff.as_probe, diff.built
1555                    )
1556                },
1557                "locations": [{
1558                    "physicalLocation": {
1559                        "artifactLocation": { "uri": sarif_uri(prefix, &diff.at.file) },
1560                        "region": { "startLine": diff.at.line, "startColumn": diff.at.column }
1561                    }
1562                }]
1563            }));
1564        }
1565        for diff in &audit.trace_differences {
1566            let text = if diff.rerun_failed && diff.records == 0 {
1567                format!(
1568                    "audit trace re-run for `{}` did not pass (tests may not be deterministic)",
1569                    diff.binary
1570                )
1571            } else if diff.rerun_failed {
1572                format!(
1573                    "audit trace re-run for `{}` did not pass and differed in {} records",
1574                    diff.binary, diff.records
1575                )
1576            } else {
1577                format!(
1578                    "audit trace for `{}` differed between two runs ({} records)",
1579                    diff.binary, diff.records
1580                )
1581            };
1582            results.push(serde_json::json!({
1583                "ruleId": "audit-disagreement",
1584                "level": "error",
1585                "message": { "text": text }
1586            }));
1587        }
1588    }
1589    let mut properties = serde_json::json!({
1590        "analysis": report.analysis,
1591        "evaluation": report.evaluation,
1592        "skipped": report.skipped,
1593    });
1594    if let Some(audit) = &report.audit {
1595        properties["audit"] = serde_json::json!(audit);
1596    }
1597    let mut run = serde_json::json!({
1598        "tool": sarif_tool(),
1599        // What was looked at: a run of a part says nothing about the rest.
1600        "properties": properties,
1601    });
1602    run["results"] = serde_json::Value::Array(results);
1603    run
1604}
1605
1606fn list(items: &[String], limit: usize) -> String {
1607    let shown: Vec<&str> = items.iter().take(limit).map(String::as_str).collect();
1608    let more = items.len().saturating_sub(limit);
1609    if more > 0 {
1610        format!("{} (+{more} more)", shown.join(", "))
1611    } else {
1612        shown.join(", ")
1613    }
1614}
1615
1616/// The lines of one finding, without its header. When `sanitize` is true, each untrusted
1617/// field is sanitized before being joined so an incomplete escape sequence in one field
1618/// cannot swallow later fields on the same line.
1619fn finding_body(finding: &Finding, sanitize: bool) -> Vec<String> {
1620    let clean = |s: &str| {
1621        if sanitize {
1622            sanitize_inline(s)
1623        } else {
1624            s.to_string()
1625        }
1626    };
1627    let clean_list = |items: &[String]| {
1628        if sanitize {
1629            items
1630                .iter()
1631                .map(|s| sanitize_inline(s))
1632                .collect::<Vec<_>>()
1633                .join(", ")
1634        } else {
1635            items.join(", ")
1636        }
1637    };
1638    let mut lines = vec![];
1639    match finding {
1640        Finding::InputGap {
1641            survivors,
1642            survivor_count,
1643            add_tests,
1644            observed,
1645            verified,
1646            ..
1647        } => {
1648            let more = survivor_count.saturating_sub(survivors.len() as u128);
1649            let more = if more > 0 {
1650                format!(" (+{more} more)")
1651            } else {
1652                String::new()
1653            };
1654            let note = if *verified {
1655                "re-run: tests pass"
1656            } else {
1657                "from the trace, not re-run"
1658            };
1659            lines.push(format!(
1660                "passes every test as: {}{more}  [{note}]",
1661                clean_list(survivors)
1662            ));
1663            lines.extend(observed.iter().map(|s| clean(s)));
1664            lines.extend(
1665                add_tests
1666                    .iter()
1667                    .map(|test| format!("add a test with {}", clean(test))),
1668            );
1669        }
1670        Finding::AssertionGap {
1671            survivors,
1672            tests,
1673            effects,
1674            effects_of,
1675            witness,
1676            ..
1677        } => {
1678            lines.push(format!("passes every test as: {}", clean_list(survivors)));
1679            let shown_tests: Vec<String> = tests.iter().map(|t| clean(t)).collect();
1680            lines.push(format!(
1681                "these tests run the changed code and still pass: {}",
1682                list(&shown_tests, 5)
1683            ));
1684            if effects.is_empty() {
1685                lines.push("add an assertion on what this code is responsible for".to_string());
1686            } else {
1687                // Which of several mutants was followed, so that what is said of "the
1688                // mutant" below can be tried.
1689                if let (Some(followed), true) = (effects_of, survivors.len() > 1) {
1690                    lines.push(format!(
1691                        "followed one of them through the tests: {}",
1692                        clean(followed)
1693                    ));
1694                }
1695                lines.extend(effects.iter().map(|s| clean(s)));
1696            }
1697            if let Some(witness) = witness {
1698                lines.extend(witness_lines(witness, sanitize));
1699            }
1700        }
1701        Finding::Survivor {
1702            survivors,
1703            change_since: Some(revision),
1704            ..
1705        } => {
1706            lines.push(format!("passes every test {}", clean_list(survivors)));
1707            lines.push(format!(
1708                "no test tells this change from the code as it was at {}: add one that fails without it",
1709                clean(short_revision(revision))
1710            ));
1711        }
1712        Finding::Survivor {
1713            survivors,
1714            witness,
1715            advice,
1716            ..
1717        } => {
1718            lines.push(format!("passes every test as: {}", clean_list(survivors)));
1719            if let Some(witness) = witness {
1720                lines.extend(witness_lines(witness, sanitize));
1721            } else if let Some(advice) = advice {
1722                lines.push(clean(advice));
1723            } else {
1724                lines.push(
1725                    "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"
1726                        .to_string(),
1727                );
1728            }
1729        }
1730    }
1731    lines
1732}
1733
1734fn witness_lines(witness: &VerifiedWitness, sanitize: bool) -> Vec<String> {
1735    let clean = |s: &str| {
1736        if sanitize {
1737            sanitize_inline(s)
1738        } else {
1739            s.to_string()
1740        }
1741    };
1742    let call = clean(&witness.call);
1743    let orig = clean(&witness.original);
1744    let mut_val = clean(&witness.mutant);
1745    let assertion = clean(&witness.assertion);
1746    if let Some(test) = &witness.in_test {
1747        let test = clean(test);
1748        // The test may make the call more than once, with another result each time.
1749        let place = witness
1750            .in_test_line
1751            .zip(witness.in_test_column)
1752            .map(|(line, column)| format!("line {line}, column {column}"));
1753        let (on, of) = place.map_or_else(
1754            || (String::new(), "that call".to_string()),
1755            |place| (format!(" at {place}"), format!("the call at {place}")),
1756        );
1757        return vec![
1758            format!(
1759                "verified on `{call}` where `{test}` calls it{on}: original returned {orig}, mutant returned {mut_val}",
1760            ),
1761            format!("in `{test}`, compare the result of {of} with this value: `{assertion}`"),
1762        ];
1763    }
1764    let mut lines = vec![format!(
1765        "verified on `{call}`: original returned {orig}, mutant returned {mut_val}",
1766    )];
1767    if let Some(killed) = witness.individually_killed {
1768        lines.push(format!(
1769            "the selected tests detected all {killed} component changes in isolation"
1770        ));
1771    }
1772    lines.extend(witness.guidance.iter().map(|s| clean(s)));
1773    lines.push(format!("add a test with `{assertion}`"));
1774    lines
1775}
1776
1777fn finding_parts(finding: &Finding) -> (&'static str, &Location) {
1778    match finding {
1779        Finding::InputGap { at, .. } => ("INPUT GAP", at),
1780        Finding::AssertionGap { at, .. } => ("ASSERTION GAP", at),
1781        Finding::Survivor {
1782            at,
1783            change_since: Some(_),
1784            ..
1785        } => ("UNTESTED CHANGE", at),
1786        Finding::Survivor { at, .. } => ("SURVIVOR", at),
1787    }
1788}
1789
1790/// Strips 7-bit and 8-bit ANSI/VT terminal escape sequences (CSI, OSC, DCS, SOS, PM, APC,
1791/// and nF/Fp/Fe ESC sequences), C0/C1/DEL control characters, and Unicode bidirectional
1792/// override/isolate controls from untrusted project text before writing to a terminal.
1793/// When `preserve_newlines` is false, `\n`, `\r`, and `\t` are collapsed to spaces so
1794/// untrusted fields cannot forge new lines in text reports.
1795fn sanitize_terminal_text(text: &str, preserve_newlines: bool) -> String {
1796    fn consume_csi(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) {
1797        while let Some(&next) = chars.peek() {
1798            if (' '..='?').contains(&next) {
1799                chars.next();
1800            } else if ('@'..='~').contains(&next) {
1801                chars.next();
1802                break;
1803            } else {
1804                // Incomplete/malformed CSI: stop before consuming unrelated text or newlines.
1805                break;
1806            }
1807        }
1808    }
1809    fn consume_st_terminated(
1810        chars: &mut std::iter::Peekable<std::str::Chars<'_>>,
1811        allow_bel: bool,
1812    ) {
1813        while let Some(next) = chars.next() {
1814            if (allow_bel && next == '\x07') || next == '\u{009c}' {
1815                break;
1816            }
1817            if next == '\x1b' && chars.peek() == Some(&'\\') {
1818                chars.next();
1819                break;
1820            }
1821        }
1822    }
1823    let mut out = String::with_capacity(text.len());
1824    let mut chars = text.chars().peekable();
1825    while let Some(ch) = chars.next() {
1826        if ch == '\x1b' {
1827            match chars.peek().copied() {
1828                // 7-bit CSI: ESC [ <param/interm 0x20-0x3F>* <final 0x40-0x7E>
1829                Some('[') => {
1830                    chars.next();
1831                    consume_csi(&mut chars);
1832                }
1833                // 7-bit OSC: ESC ] ... (BEL | ESC \ | C1 ST)
1834                Some(']') => {
1835                    chars.next();
1836                    consume_st_terminated(&mut chars, true);
1837                }
1838                // 7-bit DCS / SOS / PM / APC: ESC (P | X | ^ | _) ... (ESC \ | C1 ST)
1839                Some('P' | 'X' | '^' | '_') => {
1840                    chars.next();
1841                    consume_st_terminated(&mut chars, false);
1842                }
1843                // nF sequences (e.g., ESC ( B charset designation): 0x20-0x2F intermediates + 0x30-0x7E final.
1844                Some(next) if (' '..='/').contains(&next) => {
1845                    while let Some(&c) = chars.peek() {
1846                        if (' '..='/').contains(&c) {
1847                            chars.next();
1848                        } else if ('0'..='~').contains(&c) {
1849                            chars.next();
1850                            break;
1851                        } else {
1852                            break;
1853                        }
1854                    }
1855                }
1856                // Single-final ESC sequence (e.g., ESC c, ESC 7, ESC =).
1857                Some(next) if ('0'..='~').contains(&next) => {
1858                    chars.next();
1859                }
1860                _ => {}
1861            }
1862            continue;
1863        }
1864        // 8-bit C1 CSI (\u{009B}), OSC (\u{009D}), DCS (\u{0090}), SOS (\u{0098}), PM (\u{009E}), APC (\u{009F}).
1865        if ch == '\u{009b}' {
1866            consume_csi(&mut chars);
1867            continue;
1868        }
1869        if ch == '\u{009d}' {
1870            consume_st_terminated(&mut chars, true);
1871            continue;
1872        }
1873        if matches!(ch, '\u{0090}' | '\u{0098}' | '\u{009e}' | '\u{009f}') {
1874            consume_st_terminated(&mut chars, false);
1875            continue;
1876        }
1877        // Unicode BiDi override/isolate controls (Trojan Source / terminal spoofing).
1878        if matches!(
1879            ch,
1880            '\u{061c}'
1881                | '\u{200e}'
1882                | '\u{200f}'
1883                | '\u{202a}'..='\u{202e}'
1884                | '\u{2066}'..='\u{2069}'
1885        ) {
1886            continue;
1887        }
1888        if ch == '\n' && preserve_newlines {
1889            out.push('\n');
1890            continue;
1891        }
1892        if matches!(ch, '\n' | '\r' | '\t') {
1893            out.push(' ');
1894            continue;
1895        }
1896        if ch.is_control() {
1897            continue;
1898        }
1899        out.push(ch);
1900    }
1901    out
1902}
1903
1904/// Sanitizes an untrusted single-line string for terminal output (no escape sequences, no
1905/// control characters, no injected line breaks).
1906#[doc(hidden)]
1907pub fn sanitize_inline(text: &str) -> String {
1908    sanitize_terminal_text(text, false)
1909}
1910
1911/// Sanitizes multi-line terminal output while preserving intentional `\n` line breaks.
1912#[doc(hidden)]
1913pub fn sanitize_terminal(text: &str) -> String {
1914    sanitize_terminal_text(text, true)
1915}
1916
1917pub fn render_text(report: &Report, show_unreached: bool) -> String {
1918    let mut out = String::new();
1919    let mut previous: Option<(&str, usize)> = None;
1920    for finding in &report.findings {
1921        let (kind, at) = finding_parts(finding);
1922        // Findings on one line are usually one thought (a chain of conditions): they are
1923        // printed as one block.
1924        let same_line = previous == Some((at.file.as_str(), at.line));
1925        if same_line {
1926            out.push_str(&format!(
1927                "  + {kind}  column {}\n    {}\n",
1928                at.column,
1929                sanitize_inline(&at.code)
1930            ));
1931        } else {
1932            if previous.is_some() {
1933                out.push('\n');
1934            }
1935            out.push_str(&format!(
1936                "{kind}  {}:{}:{}\n    {}\n",
1937                sanitize_inline(&at.file),
1938                at.line,
1939                at.column,
1940                sanitize_inline(&at.code)
1941            ));
1942        }
1943        for line in finding_body(finding, true) {
1944            out.push_str(&format!("  {line}\n"));
1945        }
1946        if report.weakened.iter().any(|before| {
1947            (before.file.as_str(), before.line, before.column)
1948                == (at.file.as_str(), at.line, at.column)
1949        }) {
1950            out.push_str(&format!(
1951                "  the tests as they were at {} found this out: a change to the tests lets it through\n",
1952                sanitize_inline(short_revision(
1953                    report.analysis.since.as_deref().unwrap_or("the revision")
1954                ))
1955            ));
1956        }
1957        previous = Some((at.file.as_str(), at.line));
1958    }
1959    if previous.is_some() {
1960        out.push('\n');
1961    }
1962    if show_unreached {
1963        for at in &report.unreached {
1964            out.push_str(&format!(
1965                "UNREACHED  {}:{}:{}\n    {}\n\n",
1966                sanitize_inline(&at.file),
1967                at.line,
1968                at.column,
1969                sanitize_inline(&at.code)
1970            ));
1971        }
1972    }
1973    for at in &report.unstable {
1974        out.push_str(&format!(
1975            "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",
1976            sanitize_inline(&at.file),
1977            at.line,
1978            at.column,
1979            sanitize_inline(&at.code)
1980        ));
1981    }
1982    let input = report
1983        .findings
1984        .iter()
1985        .filter(|f| matches!(f, Finding::InputGap { .. }))
1986        .count();
1987    let assertion = report
1988        .findings
1989        .iter()
1990        .filter(|f| matches!(f, Finding::AssertionGap { .. }))
1991        .count();
1992    let unexplained = report.findings.len() - input - assertion;
1993    // A mutant stopped by the time limit costs the limit: worth knowing when a run is slow.
1994    let by_time_limit = if report.mutants_timed_out > 0 {
1995        format!(", {} of them by the time limit", report.mutants_timed_out)
1996    } else {
1997        String::new()
1998    };
1999    out.push_str(&format!(
2000        "{}: {} sites, {} input gaps, {} assertion gaps, {} mutants run ({} killed{by_time_limit}), {} sites unreached",
2001        sanitize_inline(&report.package),
2002        report.sites,
2003        input,
2004        assertion,
2005        report.mutants_run,
2006        report.mutants_killed,
2007        report.unreached.len()
2008    ));
2009    if unexplained > 0 {
2010        out.push_str(&format!(
2011            ", {unexplained} survivors of mutants built on their own"
2012        ));
2013    }
2014    if !report.timeout_rechecks.is_empty() {
2015        let rechecks = &report.timeout_rechecks;
2016        out.push_str(&format!(
2017            ", {} parallel timeouts ({} confirmed, {} recovered, {} unconfirmed)",
2018            rechecks.first_pass, rechecks.confirmed, rechecks.recovered, rechecks.unconfirmed
2019        ));
2020    }
2021    if report.suppressed > 0 {
2022        out.push_str(&format!(", {} findings suppressed", report.suppressed));
2023    }
2024    if report.skipped_sites > 0 {
2025        out.push_str(&format!(
2026            ", {} sites skipped (probe did not compile)",
2027            report.skipped_sites
2028        ));
2029    }
2030    if report.unviable_mutants > 0 {
2031        out.push_str(&format!(
2032            ", {} mutants left out (they do not compile)",
2033            report.unviable_mutants
2034        ));
2035    }
2036    out.push('\n');
2037    if let Some(audit) = &report.audit {
2038        out.push_str(&format!(
2039            "audit: {} of {} surviving mutants run against all tests, {} failed one they had not been run against",
2040            audit.sampled,
2041            audit.survivors,
2042            audit.disagreements.len()
2043        ));
2044        if audit.not_audited > 0 {
2045            out.push_str(&format!(", {} could not be judged", audit.not_audited));
2046        }
2047        out.push('\n');
2048        for at in &audit.disagreements {
2049            out.push_str(&format!(
2050                "  {}:{}:{}  {}\n",
2051                sanitize_inline(&at.file),
2052                at.line,
2053                at.column,
2054                sanitize_inline(&at.code)
2055            ));
2056        }
2057        if audit.rebuilt > 0 {
2058            out.push_str(&format!(
2059                "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",
2060                audit.rebuilt,
2061                audit.compared,
2062                audit.source_disagreements.len(),
2063                audit.not_compared
2064            ));
2065        }
2066        for differs in &audit.source_disagreements {
2067            out.push_str(&format!(
2068                "  {}:{}:{}  {}: {} as a probe, {} built\n",
2069                sanitize_inline(&differs.at.file),
2070                differs.at.line,
2071                differs.at.column,
2072                sanitize_inline(&differs.mutant),
2073                sanitize_inline(&differs.as_probe),
2074                sanitize_inline(&differs.built)
2075            ));
2076        }
2077        if audit.trace_differences.is_empty() {
2078            out.push_str("audit: recorded once more, the tests did the same\n");
2079        }
2080        for binary in &audit.trace_differences {
2081            let name = sanitize_inline(&binary.binary);
2082            if binary.rerun_failed && binary.records == 0 {
2083                out.push_str(&format!(
2084                    "audit: recorded once more, `{name}` did not pass: its tests do not always do the same\n"
2085                ));
2086            } else if binary.rerun_failed {
2087                out.push_str(&format!(
2088                    "audit: recorded once more, `{name}` did not pass and differs in {} records: its tests do not always do the same\n",
2089                    binary.records
2090                ));
2091            } else {
2092                out.push_str(&format!(
2093                    "audit: recorded once more, `{name}` differs in {} records: its tests do not always do the same\n",
2094                    binary.records
2095                ));
2096            }
2097        }
2098    }
2099    if report.mutants_not_compiled > 0 {
2100        out.push_str(&format!(
2101            "({} 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",
2102            report.mutants_not_compiled
2103        ));
2104    }
2105    let not_evaluated = report
2106        .mutants_not_evaluated
2107        .saturating_sub(report.mutants_not_compiled);
2108    if not_evaluated > 0 {
2109        out.push_str(&format!(
2110            "({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"
2111        ));
2112    }
2113    if report.mutants_not_built > 0 {
2114        out.push_str(&format!(
2115            "({} more mutants need a build of their own: --rebuild runs them)\n",
2116            report.mutants_not_built
2117        ));
2118    }
2119    if !report.skipped.is_empty() {
2120        out.push_str(&format!(
2121            "({} skipped entries with locations and reasons in --json)\n",
2122            report.skipped.len()
2123        ));
2124    }
2125    if report.survivor_breakdown.unreported() > 0 {
2126        let breakdown = &report.survivor_breakdown;
2127        let mut parts = vec![];
2128        if breakdown.redundant_constant > 0 {
2129            parts.push(format!(
2130                "{} redundant constant",
2131                breakdown.redundant_constant
2132            ));
2133        }
2134        if breakdown.preexisting_unchanged > 0 {
2135            parts.push(format!(
2136                "{} preexisting in unchanged code",
2137                breakdown.preexisting_unchanged
2138            ));
2139        }
2140        if breakdown.unchanged_not_compared > 0 {
2141            parts.push(format!(
2142                "{} in unchanged code (earlier tests could not be evaluated)",
2143                breakdown.unchanged_not_compared
2144            ));
2145        }
2146        if breakdown.unconfirmed_gap > 0 {
2147            parts.push(format!(
2148                "{} from unconfirmed gaps",
2149                breakdown.unconfirmed_gap
2150            ));
2151        }
2152        out.push_str(&format!(
2153            "({} surviving mutants not reported as findings: {})\n",
2154            breakdown.unreported(),
2155            parts.join(", ")
2156        ));
2157    }
2158    if report.evaluation == Some(Evaluation::Partial) {
2159        out.push_str("(partial evaluation: some mutants were not built or evaluated)\n");
2160    }
2161    if report.evaluation == Some(Evaluation::NoMutantsExecuted) {
2162        if report.unreached.is_empty()
2163            && report.mutants_not_evaluated == 0
2164            && report.mutants_not_built == 0
2165            && (report.unviable_mutants > 0 || report.skipped_sites > 0)
2166        {
2167            out.push_str("No mutants executed. See any skipped entries in --json.\n");
2168        } else {
2169            out.push_str("No mutants executed. See any skipped entries in --json. For a subprocess that clears the probe environment, try --source-only.\n");
2170        }
2171    }
2172    if !show_unreached && !report.unreached.is_empty() {
2173        out.push_str("(--show-unreached lists the code no test executes)\n");
2174    }
2175    sanitize_terminal(&out)
2176}
2177
2178#[cfg(test)]
2179mod tests {
2180    use super::*;
2181    use crate::instrument::discover;
2182
2183    #[test]
2184    fn evaluation_distinguishes_no_sites_no_mutants_partial_and_completed_work() {
2185        let mut report = Report::default();
2186        report.record_evaluation();
2187        assert_eq!(report.evaluation, Some(Evaluation::NoSites));
2188        report.sites = 1;
2189        report.record_evaluation();
2190        assert_eq!(report.evaluation, Some(Evaluation::NoMutantsExecuted));
2191        assert!(render_text(&report, false).contains("No mutants executed."));
2192        assert!(render_text(&report, false).contains("--source-only"));
2193        // When every candidate was skipped as unviable/uncompilable with no unreached,
2194        // unbuilt, or unevaluated sites, suggesting --source-only would not help.
2195        report.unviable_mutants = 1;
2196        let unbuildable_text = render_text(&report, false);
2197        assert!(unbuildable_text.contains("No mutants executed."));
2198        assert!(
2199            !unbuildable_text.contains("--source-only"),
2200            "{unbuildable_text}"
2201        );
2202        // Mixed with unevaluated or unbuilt candidates keeps the --source-only hint.
2203        report.mutants_not_evaluated = 1;
2204        assert!(render_text(&report, false).contains("--source-only"));
2205        report.mutants_not_evaluated = 0;
2206        report.mutants_not_built = 1;
2207        assert!(render_text(&report, false).contains("--source-only"));
2208        report.mutants_not_built = 0;
2209        report.unviable_mutants = 0;
2210        report.mutants_run = 1;
2211        report.mutants_killed = 1;
2212        report.record_evaluation();
2213        assert_eq!(report.evaluation, None);
2214        assert!(report.counts_reconcile());
2215        assert!(!render_text(&report, false).contains("No mutants executed."));
2216        assert!(!render_text(&report, false).contains("partial evaluation"));
2217
2218        report.mutants_not_built = 3;
2219        report.record_evaluation();
2220        assert_eq!(report.evaluation, Some(Evaluation::Partial));
2221        assert!(render_text(&report, false).contains("partial evaluation"));
2222    }
2223
2224    #[test]
2225    fn evaluation_pict_table() {
2226        let table = include_str!("../tests/data/report_evaluation.pict.tsv");
2227        let mut lines = table.lines();
2228        let header = lines.next().expect("header");
2229        assert_eq!(
2230            header,
2231            "sites\tmutants_run\tskipped_entries\tskipped_sites\tunparseable_source\tmutants_not_built\tmutants_not_evaluated\tunconfirmed_timeouts\tsource_only_timeout\thas_gaps\tsource_only"
2232        );
2233        let dummy = || Location {
2234            file: "src/lib.rs".into(),
2235            line: 1,
2236            column: 1,
2237            code: "x".into(),
2238            ..Location::default()
2239        };
2240        let mut rows = 0;
2241        for line in lines.filter(|line| !line.trim().is_empty()) {
2242            rows += 1;
2243            let cols: Vec<&str> = line.split('\t').collect();
2244            assert_eq!(cols.len(), 11, "row: {line}");
2245            let skipped = if cols[4] == "true" {
2246                vec![SkippedSite::new(
2247                    dummy(),
2248                    (1, 2),
2249                    SkipReason::UnparseableSource,
2250                    Some("parse error".into()),
2251                )]
2252            } else if cols[2] == "nonempty" {
2253                vec![SkippedSite::new(
2254                    dummy(),
2255                    (1, 2),
2256                    SkipReason::ProbeReplacedBySourceRebuild,
2257                    None,
2258                )]
2259            } else {
2260                vec![]
2261            };
2262            let source_only_timeout = cols[8] == "true";
2263            let mut report = Report {
2264                sites: usize::from(cols[0] == "nonzero"),
2265                mutants_run: usize::from(cols[1] == "nonzero"),
2266                mutants_killed: usize::from(cols[1] == "nonzero"),
2267                mutants_timed_out: usize::from(source_only_timeout),
2268                skipped,
2269                skipped_sites: usize::from(cols[3] == "nonzero"),
2270                mutants_not_built: usize::from(cols[5] == "nonzero"),
2271                mutants_not_evaluated: usize::from(cols[6] == "nonzero"),
2272                timeout_rechecks: TimeoutRechecks {
2273                    first_pass: usize::from(cols[7] == "nonzero"),
2274                    unconfirmed: usize::from(cols[7] == "nonzero"),
2275                    ..TimeoutRechecks::default()
2276                },
2277                analysis: Analysis {
2278                    source_only: cols[10] == "true",
2279                    ..Analysis::default()
2280                },
2281                ..Report::default()
2282            };
2283            report.record_evaluation();
2284            let expected = match cols[1] {
2285                "zero" => {
2286                    if cols[0] == "zero"
2287                        && cols[2] == "empty"
2288                        && cols[5] == "zero"
2289                        && cols[6] == "zero"
2290                    {
2291                        Some(Evaluation::NoSites)
2292                    } else {
2293                        Some(Evaluation::NoMutantsExecuted)
2294                    }
2295                }
2296                "nonzero" => {
2297                    if cols[3] == "nonzero"
2298                        || cols[4] == "true"
2299                        || cols[5] == "nonzero"
2300                        || cols[6] == "nonzero"
2301                        || cols[7] == "nonzero"
2302                        || source_only_timeout
2303                    {
2304                        Some(Evaluation::Partial)
2305                    } else {
2306                        None
2307                    }
2308                }
2309                other => panic!("unexpected mutants_run value: {other}"),
2310            };
2311            assert_eq!(report.evaluation, expected, "row: {line}");
2312            assert!(report.counts_reconcile(), "row: {line}");
2313            let text = render_text(&report, false);
2314            assert_eq!(
2315                text.contains("partial evaluation"),
2316                expected == Some(Evaluation::Partial),
2317                "row: {line}\n{text}"
2318            );
2319        }
2320        assert!(rows >= 11, "expected PICT table rows, got {rows}");
2321    }
2322
2323    #[test]
2324    fn survivor_breakdown_reconciles_and_renders_unreported_reasons() {
2325        let mut report = Report {
2326            package: "demo".into(),
2327            sites: 5,
2328            mutants_run: 11,
2329            mutants_killed: 4,
2330            mutants_timed_out: 1,
2331            mutants_survived: 7,
2332            survivor_breakdown: SurvivorBreakdown {
2333                reported: 1,
2334                suppressed: 1,
2335                redundant_constant: 2,
2336                preexisting_unchanged: 1,
2337                unchanged_not_compared: 1,
2338                unconfirmed_gap: 1,
2339            },
2340            ..Report::default()
2341        };
2342        assert!(report.counts_reconcile());
2343        report.record_evaluation();
2344        assert_eq!(report.evaluation, Some(Evaluation::Partial));
2345        let text = render_text(&report, false);
2346        assert!(
2347            text.contains(
2348                "(5 surviving mutants not reported as findings: 2 redundant constant, 1 preexisting in unchanged code, 1 in unchanged code (earlier tests could not be evaluated), 1 from unconfirmed gaps)"
2349            ),
2350            "{text}"
2351        );
2352
2353        report.survivor_breakdown.reported = 0;
2354        assert!(!report.counts_reconcile());
2355        report.survivor_breakdown.reported = 1;
2356        report.mutants_timed_out = 5;
2357        assert!(!report.counts_reconcile());
2358
2359        // Overflow in breakdown addition must not panic or wrap to a false match.
2360        let overflow = Report {
2361            mutants_run: 0,
2362            mutants_killed: 0,
2363            mutants_survived: 0,
2364            survivor_breakdown: SurvivorBreakdown {
2365                reported: usize::MAX,
2366                suppressed: 1,
2367                ..SurvivorBreakdown::default()
2368            },
2369            ..Report::default()
2370        };
2371        assert!(!overflow.counts_reconcile());
2372    }
2373
2374    fn results_of(sarif: &serde_json::Value) -> &Vec<serde_json::Value> {
2375        sarif["runs"][0]["results"].as_array().unwrap()
2376    }
2377
2378    fn or_site() -> Site {
2379        site_of("fn f(a: bool, b: bool) -> bool { a || b }")
2380    }
2381
2382    fn assign_kind() -> SiteKind {
2383        SiteKind::Arith {
2384            op: ArithOp::Add,
2385            assign: true,
2386            lhs: "*total".into(),
2387            rhs: "fee".into(),
2388            gap: (0, 0),
2389            local_types: vec![],
2390            shadowed_prims: vec![],
2391            cast_probes: vec![],
2392        }
2393    }
2394
2395    fn site_of(src: &str) -> Site {
2396        discover(src, 0)
2397            .unwrap()
2398            .sites
2399            .into_iter()
2400            .find(|s| !matches!(s.kind, SiteKind::Return { .. } | SiteKind::Body { .. }))
2401            .unwrap()
2402    }
2403
2404    #[test]
2405    fn describes_mutants_at_source_level() {
2406        let rhs = site_of("fn f(age: u32) -> bool { age >= 18 }");
2407        assert_eq!(describe(&rhs, Mutation::Shift(1)), "`age >= 19`");
2408        assert_eq!(describe(&rhs, Mutation::Shift(-2)), "`age >= 16`");
2409        assert_eq!(describe(&rhs, Mutation::Negate), "`!(age >= 18)`");
2410        assert_eq!(describe(&rhs, Mutation::Const(false)), "`false`");
2411        assert_eq!(describe(&rhs, Mutation::Op(CmpOp::Gt)), "`age > 18`");
2412
2413        // 18 <= age shifted by +1 is 18 <= age + 1, i.e. 17 <= age.
2414        let lhs = site_of("fn f(age: i32) -> bool { 18 <= age }");
2415        assert_eq!(describe(&lhs, Mutation::Shift(1)), "`17 <= age`");
2416
2417        let none = site_of("fn f(a: u32, b: u32) -> bool { a >= b }");
2418        assert_eq!(describe(&none, Mutation::Shift(1)), "`a > b`");
2419        assert_eq!(
2420            describe(&none, Mutation::Shift(2)),
2421            "`a >= b + 2` (without overflow)"
2422        );
2423        assert_eq!(
2424            describe(&none, Mutation::Shift(-1)),
2425            "`a >= b - 1` (without overflow)"
2426        );
2427        let lt = site_of("fn f(a: u32, b: u32) -> bool { a < b }");
2428        assert_eq!(describe(&lt, Mutation::Shift(1)), "`a <= b`");
2429
2430        let stmt = site_of("fn f(s: &mut S) { s.check(\n  1,\n  2); }");
2431        assert_eq!(
2432            describe(&stmt, Mutation::Delete),
2433            "delete `s.check( 1, 2);`"
2434        );
2435    }
2436
2437    /// The source-level form must mean the same as the planner's `Shift`.
2438    #[test]
2439    fn literal_shift_rendering_matches_shift_semantics() {
2440        use crate::plan::eval_mutated_d;
2441        for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
2442            for shift in [-2, -1, 1, 2] {
2443                for other in -5..=5i128 {
2444                    let k = 1i128;
2445                    // literal on the right: `x op k+shift`
2446                    assert_eq!(
2447                        op.eval_d(other - (k + shift)),
2448                        eval_mutated_d(op, Mutation::Shift(shift), other - k)
2449                    );
2450                    // literal on the left: `k-shift op x`
2451                    assert_eq!(
2452                        op.eval_d((k - shift) - other),
2453                        eval_mutated_d(op, Mutation::Shift(shift), k - other)
2454                    );
2455                }
2456            }
2457        }
2458        // And the operator flips used when neither side is a literal.
2459        for (op, shift, flipped) in [
2460            (CmpOp::Ge, 1, CmpOp::Gt),
2461            (CmpOp::Gt, -1, CmpOp::Ge),
2462            (CmpOp::Le, -1, CmpOp::Lt),
2463            (CmpOp::Lt, 1, CmpOp::Le),
2464        ] {
2465            for d in -3..=3 {
2466                assert_eq!(
2467                    flipped.eval_d(d),
2468                    eval_mutated_d(op, Mutation::Shift(shift), d)
2469                );
2470            }
2471        }
2472    }
2473
2474    #[test]
2475    fn boundary_finding_for_the_age_check() {
2476        let site = site_of("fn f(age: u32) -> bool { age >= 18 }");
2477        let mut obs = Obs::of_d(-1);
2478        obs.merge(&Obs::of_d(2));
2479        let gap = InputGap::Boundary {
2480            min_shift: 0,
2481            max_shift: 2,
2482            missing: vec![0],
2483            same: (0, 0),
2484        };
2485        let finding = input_gap_finding("src/lib.rs", &site, &gap, &obs, true).unwrap();
2486        assert_eq!(
2487            finding,
2488            Finding::InputGap {
2489                at: Location {
2490                    file: "src/lib.rs".into(),
2491                    line: 1,
2492                    column: 26,
2493                    code: "age >= 18".into(),
2494                    ..Location::default()
2495                },
2496                survivors: vec!["`age >= 19`".into(), "`age >= 20`".into()],
2497                survivor_count: 2,
2498                add_tests: vec!["`age` = 18 (the original gives true)".into()],
2499                observed: Some("nearest values the tests passed: `age` = 17, 20".into()),
2500                verified: true,
2501            }
2502        );
2503        let report = Report {
2504            package: "p".into(),
2505            sites: 1,
2506            findings: vec![finding],
2507            ..Report::default()
2508        };
2509        let text = render_text(&report, false);
2510        assert!(text.contains("INPUT GAP  src/lib.rs:1:26"), "{text}");
2511        assert!(
2512            text.contains("passes every test as: `age >= 19`, `age >= 20`  [re-run: tests pass]"),
2513            "{text}"
2514        );
2515        assert!(
2516            text.contains("add a test with `age` = 18 (the original gives true)"),
2517            "{text}"
2518        );
2519        assert!(
2520            text.contains("p: 1 sites, 1 input gaps, 0 assertion gaps"),
2521            "{text}"
2522        );
2523        assert!(report.has_gaps());
2524    }
2525
2526    #[test]
2527    fn other_gap_kinds() {
2528        let site = site_of("fn f(a: f64, b: f64) -> bool { a < b }");
2529        let mut obs = Obs::of_rel(crate::plan::Rel::Less);
2530        obs.merge(&Obs::of_rel(crate::plan::Rel::Greater));
2531        let gap = InputGap::EqualNeverObserved {
2532            flipped: CmpOp::Le,
2533            float_gap: None,
2534        };
2535        let Some(Finding::InputGap {
2536            survivors,
2537            add_tests,
2538            observed,
2539            ..
2540        }) = input_gap_finding("f.rs", &site, &gap, &obs, false)
2541        else {
2542            panic!()
2543        };
2544        assert_eq!(survivors, ["`a <= b`"]);
2545        assert_eq!(
2546            add_tests,
2547            ["`a` equal to `b` (the original gives false, the mutant true)"]
2548        );
2549        assert_eq!(observed, None);
2550
2551        let Some(Finding::InputGap {
2552            survivors,
2553            add_tests,
2554            ..
2555        }) = input_gap_finding(
2556            "f.rs",
2557            &site,
2558            &InputGap::OneSided { always: true },
2559            &obs,
2560            false,
2561        )
2562        else {
2563            panic!()
2564        };
2565        assert_eq!(survivors, ["`true`"]);
2566        assert_eq!(add_tests, ["an input that makes `a < b` false"]);
2567
2568        assert_eq!(
2569            input_gap_finding("f.rs", &site, &InputGap::Unreached, &obs, false),
2570            None
2571        );
2572    }
2573
2574    #[test]
2575    fn float_gap_finding() {
2576        let site = site_of("fn f(celsius: f64) -> bool { celsius > 30.5 }");
2577        let mut obs = Obs::of_f(-20.5);
2578        obs.merge(&Obs::of_f(9.5));
2579        let gap = InputGap::EqualNeverObserved {
2580            flipped: CmpOp::Ge,
2581            float_gap: obs.float_gap(),
2582        };
2583        let Some(Finding::InputGap {
2584            survivors,
2585            add_tests,
2586            observed,
2587            survivor_count,
2588            ..
2589        }) = input_gap_finding("f.rs", &site, &gap, &obs, true)
2590        else {
2591            panic!()
2592        };
2593        assert_eq!(
2594            survivors,
2595            [
2596                "`celsius >= 30.5`",
2597                "`celsius > 35.25`",
2598                "`celsius > 20.25`"
2599            ]
2600        );
2601        assert_eq!(survivor_count, 3);
2602        assert_eq!(
2603            add_tests,
2604            ["`celsius` equal to `30.5` (the original gives false, the mutant true)"]
2605        );
2606        assert_eq!(
2607            observed.as_deref(),
2608            Some(
2609                "nearest values the tests passed: `celsius` = 10.0, 40.0; any threshold between them passes"
2610            )
2611        );
2612
2613        let lhs = site_of("fn f(x: f32) -> bool { 1.5_f32 <= x }");
2614        assert_eq!(describe(&lhs, Mutation::ShiftF(0.25)), "`1.25 <= x`");
2615        let none = site_of("fn f(x: f64, y: f64) -> bool { x < y }");
2616        assert_eq!(describe(&none, Mutation::ShiftF(0.5)), "`x < y + 0.5`");
2617        assert_eq!(describe(&none, Mutation::ShiftF(-0.5)), "`x < y - 0.5`");
2618        let finding = input_gap_finding(
2619            "f.rs",
2620            &none,
2621            &InputGap::EqualNeverObserved {
2622                flipped: CmpOp::Le,
2623                float_gap: Some((-1.0, 2.0)),
2624            },
2625            &obs,
2626            false,
2627        );
2628        let Some(Finding::InputGap { observed, .. }) = finding else {
2629            panic!()
2630        };
2631        assert_eq!(
2632            observed.as_deref(),
2633            Some("nearest values the tests passed: `x` - `y` = -1.0, 2.0")
2634        );
2635
2636        assert_eq!(float_literal("30.5"), Some(30.5));
2637        assert_eq!(float_literal("-1e3"), Some(-1000.0));
2638        assert_eq!(float_literal("1_000.5f64"), Some(1000.5));
2639        assert_eq!(float_literal("limit"), None);
2640        assert_eq!(float_literal("x1"), None);
2641        assert_eq!(float_literal("1x"), None);
2642        assert_eq!(float_literal("-x"), None);
2643        assert_eq!(float_literal("-2.5"), Some(-2.5));
2644        assert_eq!(float_literal("e"), None);
2645        // Nothing is rounded away: a tiny shift stays visible.
2646        assert_eq!(show_float(0.1 + 0.2), "0.30000000000000004");
2647        assert_eq!(show_float(1e-10), "1e-10");
2648        assert_eq!(show_float(10.0), "10.0");
2649        assert_eq!(show_float(35.25), "35.25");
2650        // A shift that does not change the literal is not listed as a mutant.
2651        let big = site_of("fn f(x: f64) -> bool { x > 1e300 }");
2652        let tiny = InputGap::EqualNeverObserved {
2653            flipped: CmpOp::Ge,
2654            float_gap: Some((-2e-300, 2e-300)),
2655        };
2656        let Some(Finding::InputGap { survivors, .. }) =
2657            input_gap_finding("f.rs", &big, &tiny, &obs, true)
2658        else {
2659            panic!()
2660        };
2661        assert_eq!(survivors, ["`x >= 1e300`"]);
2662    }
2663
2664    #[test]
2665    fn logic_and_arithmetic_findings() {
2666        let and = site_of("fn f(a: bool, b: bool) -> bool { a && b }");
2667        assert_eq!(describe(&and, Mutation::LogicSwap), "`a || b`");
2668        assert_eq!(describe(&and, Mutation::LogicDropRhs), "`a && { b; true }`");
2669        assert_eq!(
2670            describe(&or_site(), Mutation::LogicDropRhs),
2671            "`a || { b; false }`"
2672        );
2673        assert_eq!(describe(&and, Mutation::LogicDropLhs), "`{ a; b }`");
2674        let or = site_of("fn f(a: bool, b: bool) -> bool { a || b }");
2675        assert_eq!(describe(&or, Mutation::LogicSwap), "`a && b`");
2676        let advice = |site: &Site, gap| match logic_gap_finding("f.rs", site, gap, true) {
2677            Some(Finding::InputGap {
2678                survivors,
2679                add_tests,
2680                ..
2681            }) => (survivors[0].clone(), add_tests[0].clone()),
2682            _ => panic!(),
2683        };
2684        assert_eq!(
2685            advice(&and, LogicGap::RhsNeverDecides),
2686            (
2687                "`a && { b; true }`".into(),
2688                "a case where `a` is true and `b` is false".into()
2689            )
2690        );
2691        assert_eq!(
2692            advice(&and, LogicGap::LhsNeverDecides),
2693            ("`{ a; b }`".into(), "a case where `a` is false".into())
2694        );
2695        assert_eq!(
2696            advice(&or, LogicGap::RhsNeverDecides),
2697            (
2698                "`a || { b; false }`".into(),
2699                "a case where `a` is false and `b` is true".into()
2700            )
2701        );
2702        assert_eq!(
2703            advice(&or, LogicGap::LhsNeverDecides),
2704            ("`{ a; b }`".into(), "a case where `a` is true".into())
2705        );
2706        assert_eq!(
2707            logic_gap_finding("f.rs", &and, LogicGap::Unreached, true),
2708            None
2709        );
2710        assert_eq!(
2711            arith_gap_finding("f.rs", &and, Mutation::ArithSwap, true),
2712            None
2713        );
2714
2715        let add = site_of("fn f(total: u32, fee: u32) -> u32 { total + fee }");
2716        assert_eq!(describe(&add, Mutation::ArithSwap), "`total - fee`");
2717        let Some(Finding::InputGap {
2718            survivors,
2719            add_tests,
2720            ..
2721        }) = arith_gap_finding("f.rs", &add, Mutation::ArithSwap, true)
2722        else {
2723            panic!()
2724        };
2725        assert_eq!(
2726            (survivors[0].as_str(), add_tests[0].as_str()),
2727            ("`total - fee`", "`fee` other than 0")
2728        );
2729        let mul = site_of("fn f(n: u32, scale: u32) -> u32 { n * scale }");
2730        let Some(Finding::InputGap {
2731            survivors,
2732            add_tests,
2733            ..
2734        }) = arith_gap_finding("f.rs", &mul, Mutation::ArithSwap, true)
2735        else {
2736            panic!()
2737        };
2738        assert_eq!(survivors[0], "`n / scale`");
2739        assert_eq!(
2740            add_tests[0],
2741            "operands for which `n * scale` and `n / scale` differ"
2742        );
2743        let assign = Site {
2744            kind: assign_kind(),
2745            ..add.clone()
2746        };
2747        assert_eq!(describe(&assign, Mutation::ArithSwap), "`*total -= fee`");
2748        let Some(Finding::InputGap { add_tests, .. }) =
2749            arith_gap_finding("f.rs", &assign, Mutation::ArithSwap, true)
2750        else {
2751            panic!()
2752        };
2753        assert_eq!(add_tests[0], "`fee` other than 0");
2754        let shift = Site {
2755            kind: SiteKind::Arith {
2756                op: ArithOp::Shl,
2757                assign: true,
2758                lhs: "bits".into(),
2759                rhs: "n".into(),
2760                gap: (0, 0),
2761                local_types: vec![],
2762                shadowed_prims: vec![],
2763                cast_probes: vec![],
2764            },
2765            ..assign.clone()
2766        };
2767        assert_eq!(describe(&shift, Mutation::ArithSwap), "`bits >>= n`");
2768        let Some(Finding::InputGap { add_tests, .. }) =
2769            arith_gap_finding("f.rs", &shift, Mutation::ArithSwap, true)
2770        else {
2771            panic!()
2772        };
2773        assert_eq!(
2774            add_tests[0],
2775            "operands for which `bits <<= n` and `bits >>= n` differ"
2776        );
2777
2778        let not = Site {
2779            kind: SiteKind::Not {
2780                bang: (0, 1),
2781                operand: "is_ready(x)".into(),
2782                needs_space: false,
2783            },
2784            ..assign.clone()
2785        };
2786        assert_eq!(describe(&not, Mutation::DropNot), "`is_ready(x)`");
2787        let ret = Site {
2788            kind: SiteKind::Return {
2789                name: "is_ready".into(),
2790                option: None,
2791                sole_expr: None,
2792            },
2793            ..assign.clone()
2794        };
2795        assert_eq!(
2796            describe(&ret, Mutation::Const(true)),
2797            "`is_ready` returning `true`"
2798        );
2799        let Some(Finding::InputGap {
2800            survivors,
2801            add_tests,
2802            ..
2803        }) = return_gap_finding("f.rs", &ret, false, true)
2804        else {
2805            panic!()
2806        };
2807        assert_eq!(survivors[0], "`is_ready` returning `false`");
2808        assert_eq!(add_tests[0], "a case where `is_ready` returns true");
2809        assert_eq!(return_gap_finding("f.rs", &not, false, true), None);
2810
2811        let find = Site {
2812            kind: SiteKind::Return {
2813                name: "find".into(),
2814                option: Some("Option<&str>".into()),
2815                sole_expr: None,
2816            },
2817            ..assign.clone()
2818        };
2819        assert_eq!(
2820            describe(&find, Mutation::Const(false)),
2821            "`find` returning `None`"
2822        );
2823        let Some(Finding::InputGap { add_tests, .. }) =
2824            return_gap_finding("f.rs", &find, false, true)
2825        else {
2826            panic!()
2827        };
2828        assert_eq!(add_tests[0], "a case where `find` returns `Some`");
2829        let range = Site {
2830            kind: SiteKind::Range {
2831                inclusive: false,
2832                lhs: "0".into(),
2833                rhs: "n".into(),
2834                gap: (0, 0),
2835            },
2836            ..assign.clone()
2837        };
2838        assert_eq!(describe(&range, Mutation::RangeEnd), "`0..=n`");
2839        let closed = Site {
2840            kind: SiteKind::Range {
2841                inclusive: true,
2842                lhs: "1".into(),
2843                rhs: "n".into(),
2844                gap: (0, 0),
2845            },
2846            ..assign.clone()
2847        };
2848        assert_eq!(describe(&closed, Mutation::RangeEnd), "`1..n`");
2849        let arm = Site {
2850            kind: SiteKind::Arm {
2851                pattern: "Kind::Update { key, .. }".into(),
2852                guard: crate::instrument::ArmGuard::None(0),
2853                removal: (0, 0),
2854            },
2855            ..assign.clone()
2856        };
2857        assert_eq!(
2858            describe(&arm, Mutation::Delete),
2859            "remove the arm `Kind::Update { key, .. } => ..`"
2860        );
2861
2862        let clamp = Site {
2863            kind: SiteKind::MinMax {
2864                max: true,
2865                receiver: "drift".into(),
2866                argument: "peak.get()".into(),
2867                call: (0, 0),
2868                close: (0, 0),
2869            },
2870            ..assign.clone()
2871        };
2872        assert_eq!(
2873            describe(&clamp, Mutation::MinMax),
2874            "`drift.min(peak.get())`"
2875        );
2876        let Some(Finding::InputGap { add_tests, .. }) = min_max_gap_finding("f.rs", &clamp, true)
2877        else {
2878            panic!()
2879        };
2880        assert_eq!(add_tests[0], "`drift` different from `peak.get()`");
2881        assert_eq!(min_max_gap_finding("f.rs", &assign, true), None);
2882
2883        let end = Site {
2884            kind: SiteKind::SliceEnd {
2885                first: false,
2886                receiver: "self.items".into(),
2887                call: (0, 0),
2888                method: (0, 0),
2889            },
2890            ..assign.clone()
2891        };
2892        assert_eq!(describe(&end, Mutation::OtherEnd), "`self.items.first()`");
2893        let Some(Finding::InputGap { add_tests, .. }) = slice_end_gap_finding("f.rs", &end, true)
2894        else {
2895            panic!()
2896        };
2897        assert_eq!(
2898            add_tests[0],
2899            "`self.items` with two or more elements, the first different from the last"
2900        );
2901        assert_eq!(slice_end_gap_finding("f.rs", &clamp, true), None);
2902
2903        let rem = site_of("fn f(n: u32, k: u32) -> u32 { n % k }");
2904        assert_eq!(describe(&rem, Mutation::ArithSwap), "`n / k`");
2905        assert_eq!(
2906            logic_gap_finding("f.rs", &add, LogicGap::RhsNeverDecides, true),
2907            None
2908        );
2909    }
2910
2911    #[test]
2912    fn workspace_sarif_matches_the_individual_runs() {
2913        use serde_json::{Value, json};
2914
2915        let report = Report {
2916            package: "zebra".into(),
2917            analysis: Analysis {
2918                package_path: "crates/zebra/".into(),
2919                ..Analysis::default()
2920            },
2921            findings: vec![Finding::Survivor {
2922                at: Location {
2923                    file: r#"src/"é".rs"#.into(),
2924                    line: 4,
2925                    column: 1,
2926                    id: "zebra|4".into(),
2927                    ..Location::default()
2928                },
2929                survivors: vec!["delete".into()],
2930                witness: None,
2931                change_since: None,
2932                advice: None,
2933            }],
2934            ..Report::default()
2935        };
2936        let empty = Report {
2937            package: "ant".into(),
2938            ..Report::default()
2939        };
2940        for reports in [
2941            &[][..],
2942            std::slice::from_ref(&report),
2943            &[report.clone(), empty],
2944        ] {
2945            let runs: Vec<_> = reports
2946                .iter()
2947                .map(|report| {
2948                    let mut single: Value = serde_json::from_str(&render_sarif(report)).unwrap();
2949                    let mut run = single["runs"][0].take();
2950                    assert!(run["properties"].get("package").is_none());
2951                    run["properties"]["package"] = json!(report.package);
2952                    // What a run of a workspace has beside that of a package alone.
2953                    run["automationDetails"] = json!({ "id": format!("tmt/{}/", report.package) });
2954                    run["invocations"] = json!([{ "executionSuccessful": true }]);
2955                    run
2956                })
2957                .collect();
2958            let old = json!({
2959                "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
2960                "version": "2.1.0",
2961                "runs": runs,
2962            });
2963            let workspace: Value =
2964                serde_json::from_str(&format!("{:#}", workspace_sarif(reports, &[]))).unwrap();
2965            assert_eq!(workspace, old);
2966        }
2967    }
2968
2969    #[test]
2970    fn a_package_that_could_not_be_analysed_is_a_run_that_says_so() {
2971        use serde_json::Value;
2972
2973        let analysed = Report {
2974            package: "ant".into(),
2975            ..Report::default()
2976        };
2977        let failed = [(
2978            "bee".to_string(),
2979            "the tests of `bee` fail: \"quoted\"\n".to_string(),
2980        )];
2981        let document: Value = serde_json::from_str(&format!(
2982            "{:#}",
2983            workspace_sarif(std::slice::from_ref(&analysed), &failed)
2984        ))
2985        .unwrap();
2986        let runs = document["runs"].as_array().unwrap();
2987        assert_eq!(runs.len(), 2);
2988        // Each run is told from the others, and the one that failed is not a clean one.
2989        assert_eq!(runs[0]["automationDetails"]["id"], "tmt/ant/");
2990        assert_eq!(runs[0]["invocations"][0]["executionSuccessful"], true);
2991        assert_eq!(runs[1]["automationDetails"]["id"], "tmt/bee/");
2992        assert_eq!(runs[1]["invocations"][0]["executionSuccessful"], false);
2993        assert_eq!(
2994            runs[1]["invocations"][0]["toolExecutionNotifications"][0]["message"]["text"],
2995            failed[0].1
2996        );
2997        assert_eq!(runs[1]["results"].as_array().unwrap().len(), 0);
2998        assert_eq!(runs[1]["tool"], runs[0]["tool"]);
2999        assert_eq!(runs[1]["properties"]["package"], "bee");
3000        // Only failures: still a document, with nothing passed off as analysed.
3001        let document: Value =
3002            serde_json::from_str(&format!("{:#}", workspace_sarif(&[], &failed))).unwrap();
3003        assert_eq!(document["runs"].as_array().unwrap().len(), 1);
3004    }
3005
3006    #[test]
3007    fn a_path_is_written_as_a_uri() {
3008        assert_eq!(sarif_uri("", "src/lib.rs"), "src/lib.rs");
3009        assert_eq!(
3010            sarif_uri("crates/a-b_c/", "src/x~1.rs"),
3011            "crates/a-b_c/src/x~1.rs"
3012        );
3013        // What a URI gives a meaning of its own, or does not allow, is written as bytes.
3014        assert_eq!(
3015            sarif_uri("my crate/", "a#b%c?.rs"),
3016            "my%20crate/a%23b%25c%3F.rs"
3017        );
3018        assert_eq!(sarif_uri("", "src/é.rs"), "src/%C3%A9.rs");
3019        assert_eq!(sarif_uri("", r#"a\b"c.rs"#), "a%5Cb%22c.rs");
3020        let report = Report {
3021            analysis: Analysis {
3022                package_path: "my crate/".into(),
3023                ..Analysis::default()
3024            },
3025            findings: vec![Finding::Survivor {
3026                at: Location {
3027                    file: "src/a b.rs".into(),
3028                    line: 1,
3029                    column: 1,
3030                    ..Location::default()
3031                },
3032                survivors: vec![],
3033                witness: None,
3034                change_since: None,
3035                advice: None,
3036            }],
3037            ..Report::default()
3038        };
3039        let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
3040        assert_eq!(
3041            sarif["runs"][0]["results"][0]["locations"][0]["physicalLocation"]["artifactLocation"]
3042                ["uri"],
3043            "my%20crate/src/a%20b.rs"
3044        );
3045        assert_eq!(sarif_uri_for("", r#"a\b"c.rs"#, false), "a%5Cb%22c.rs");
3046        assert_eq!(
3047            sarif_uri_for(r"crates\core\", r"src\lib.rs", true),
3048            "crates/core/src/lib.rs"
3049        );
3050    }
3051
3052    #[test]
3053    fn findings_sort_by_path_and_position_in_input_order_for_ties() {
3054        let mut report = Report {
3055            findings: [
3056                ("z.rs", 1, 1, "1"),
3057                ("é.rs", 1, 1, "2"),
3058                ("a.rs", 2, 1, "3"),
3059                ("a.rs", 1, 3, "4"),
3060                ("a.rs", 1, 3, "5"),
3061                ("a.rs", 1, 1, "6"),
3062            ]
3063            .into_iter()
3064            .map(|(file, line, column, id)| Finding::Survivor {
3065                at: Location {
3066                    file: file.into(),
3067                    line,
3068                    column,
3069                    id: id.into(),
3070                    ..Location::default()
3071                },
3072                survivors: vec![],
3073                witness: None,
3074                change_since: None,
3075                advice: None,
3076            })
3077            .collect(),
3078            ..Report::default()
3079        };
3080        report.sort_findings();
3081        let ids: Vec<_> = report
3082            .findings
3083            .iter()
3084            .map(|finding| finding.at().id.as_str())
3085            .collect();
3086        assert_eq!(ids, ["6", "4", "5", "3", "1", "2"]);
3087    }
3088
3089    #[test]
3090    fn collapsed_code_matches_the_previous_format() {
3091        // Pairwise combinations of character set, whitespace and normalized width.
3092        for (charset, spacing, width) in [
3093            ("ascii", "none", 17),
3094            ("ascii", "split", 100),
3095            ("ascii", "surrounded", 101),
3096            ("multibyte", "split", 101),
3097            ("ascii", "none", 4096),
3098            ("multibyte", "none", 97),
3099            ("multibyte", "surrounded", 0),
3100            ("multibyte", "surrounded", 17),
3101            ("multibyte", "surrounded", 4096),
3102            ("ascii", "split", 17),
3103            ("multibyte", "none", 100),
3104            ("multibyte", "none", 101),
3105            ("ascii", "surrounded", 97),
3106            ("ascii", "surrounded", 100),
3107            ("multibyte", "split", 97),
3108            ("ascii", "none", 0),
3109            ("multibyte", "split", 4096),
3110        ] {
3111            let glyph = if charset == "ascii" { "x" } else { "🦀" };
3112            let code = match spacing {
3113                "none" => glyph.repeat(width),
3114                "surrounded" => format!("\t{}\u{2003}\r\n", glyph.repeat(width)),
3115                _ => format!(
3116                    "{}\u{2003}\r\n {}",
3117                    glyph.repeat(width / 2),
3118                    glyph.repeat(width - width / 2 - 1),
3119                ),
3120            };
3121            let normalized = code.split_whitespace().collect::<Vec<_>>().join(" ");
3122            let expected = if normalized.chars().count() > 100 {
3123                format!("{}...", normalized.chars().take(97).collect::<String>())
3124            } else {
3125                normalized
3126            };
3127            assert_eq!(one_line(&code), expected, "{charset} {spacing} {width}");
3128        }
3129
3130        // The last visible character can itself be the space between two words.
3131        let code = format!("{}\n{}", "x".repeat(96), "y".repeat(4096));
3132        assert_eq!(one_line(&code), format!("{} ...", "x".repeat(96)));
3133        let code = format!("{}\n{}", "x".repeat(100), " ".repeat(4096));
3134        assert_eq!(one_line(&code), "x".repeat(100));
3135    }
3136
3137    #[test]
3138    fn long_code_is_shortened() {
3139        let exactly_100 = "x".repeat(100);
3140        assert_eq!(one_line(&exactly_100), exactly_100);
3141        let shortened = one_line(&"x".repeat(101));
3142        assert_eq!(shortened, format!("{}...", "x".repeat(97)));
3143        assert_eq!(one_line("a\n   b"), "a b");
3144    }
3145
3146    #[test]
3147    fn timeout_rechecks_are_in_the_json_only_when_there_were_any() {
3148        let none = serde_json::to_value(Report::default()).unwrap();
3149        assert!(none.get("timeout_rechecks").is_none(), "{none}");
3150        let report = Report {
3151            timeout_rechecks: TimeoutRechecks {
3152                first_pass: 3,
3153                confirmed: 1,
3154                recovered: 2,
3155                unconfirmed: 0,
3156            },
3157            ..Report::default()
3158        };
3159        assert_eq!(
3160            serde_json::to_value(&report).unwrap()["timeout_rechecks"],
3161            serde_json::json!({"first_pass": 3, "confirmed": 1, "recovered": 2, "unconfirmed": 0})
3162        );
3163    }
3164
3165    #[test]
3166    fn at_most_three_survivors_are_listed_nearest_first() {
3167        let site = site_of("fn f(a: i64) -> bool { a >= 10 }");
3168        let obs = Obs::default();
3169        let survivors = |min_shift, max_shift| {
3170            let gap = InputGap::Boundary {
3171                min_shift,
3172                max_shift,
3173                missing: vec![0],
3174                same: (0, 0),
3175            };
3176            match input_gap_finding("f.rs", &site, &gap, &obs, false) {
3177                Some(Finding::InputGap {
3178                    survivors,
3179                    survivor_count,
3180                    ..
3181                }) => (survivors, survivor_count),
3182                _ => panic!(),
3183            }
3184        };
3185        assert_eq!(
3186            survivors(-9, 9),
3187            (
3188                vec!["`a >= 11`".into(), "`a >= 9`".into(), "`a >= 12`".into()],
3189                18
3190            )
3191        );
3192        assert_eq!(survivors(-1, 0), (vec!["`a >= 9`".into()], 1));
3193        assert_eq!(survivors(0, 1), (vec!["`a >= 11`".into()], 1));
3194        assert_eq!(
3195            survivors(-2, 0),
3196            (vec!["`a >= 9`".into(), "`a >= 8`".into()], 2)
3197        );
3198    }
3199
3200    #[test]
3201    fn text_report_is_exact() {
3202        let at = Location {
3203            file: "src/lib.rs".into(),
3204            line: 3,
3205            column: 9,
3206            code: "a >= b".into(),
3207            ..Location::default()
3208        };
3209        let below = Location {
3210            file: "src/lib.rs".into(),
3211            line: 7,
3212            column: 5,
3213            code: "s.reset();".into(),
3214            ..Location::default()
3215        };
3216        let report = Report {
3217            package: "p".into(),
3218            sites: 2,
3219            mutants_run: 1,
3220            suppressed: 2,
3221            findings: vec![
3222                Finding::InputGap {
3223                    at: at.clone(),
3224                    survivors: vec!["`a > b`".into()],
3225                    survivor_count: 4,
3226                    add_tests: vec!["`a` equal to `b` (the original gives true)".into()],
3227                    observed: Some("nearest values the tests passed: `a` - `b` = -1, 4".into()),
3228                    verified: false,
3229                },
3230                Finding::InputGap {
3231                    at: at.clone(),
3232                    survivors: vec!["`true`".into()],
3233                    survivor_count: 1,
3234                    add_tests: vec![],
3235                    observed: None,
3236                    verified: true,
3237                },
3238                Finding::AssertionGap {
3239                    at: Location { column: 4, ..at },
3240                    survivors: vec!["`!(a >= b)`".into()],
3241                    tests: vec!["t".into()],
3242                    effects: vec![],
3243                    effects_of: None,
3244                    witness: None,
3245                },
3246                Finding::AssertionGap {
3247                    at: below,
3248                    survivors: vec!["delete `s.reset();`".into()],
3249                    tests: vec!["t".into()],
3250                    effects: vec![
3251                        "with the mutant, `t` no longer runs `s.count = 0;` (src/lib.rs:12)".into(),
3252                    ],
3253                    effects_of: None,
3254                    witness: None,
3255                },
3256            ],
3257            ..Report::default()
3258        };
3259        // Findings on one line form one block; a new line starts a new block.
3260        assert_eq!(
3261            render_text(&report, false),
3262            "INPUT GAP  src/lib.rs:3:9\n    a >= b\n\
3263             \x20 passes every test as: `a > b` (+3 more)  [from the trace, not re-run]\n\
3264             \x20 nearest values the tests passed: `a` - `b` = -1, 4\n\
3265             \x20 add a test with `a` equal to `b` (the original gives true)\n\
3266             \x20 + INPUT GAP  column 9\n    a >= b\n\
3267             \x20 passes every test as: `true`  [re-run: tests pass]\n\
3268             \x20 + ASSERTION GAP  column 4\n    a >= b\n\
3269             \x20 passes every test as: `!(a >= b)`\n\
3270             \x20 these tests run the changed code and still pass: t\n\
3271             \x20 add an assertion on what this code is responsible for\n\
3272             \n\
3273             ASSERTION GAP  src/lib.rs:7:5\n    s.reset();\n\
3274             \x20 passes every test as: delete `s.reset();`\n\
3275             \x20 these tests run the changed code and still pass: t\n\
3276             \x20 with the mutant, `t` no longer runs `s.count = 0;` (src/lib.rs:12)\n\
3277             \n\
3278             p: 2 sites, 2 input gaps, 2 assertion gaps, 1 mutants run (0 killed), 0 sites unreached, 2 findings suppressed\n"
3279        );
3280        assert_eq!(
3281            render_text(
3282                &Report {
3283                    package: "q".into(),
3284                    ..Report::default()
3285                },
3286                false
3287            ),
3288            "q: 0 sites, 0 input gaps, 0 assertion gaps, 0 mutants run (0 killed), 0 sites unreached\n"
3289        );
3290
3291        let mut in_repository = report.clone();
3292        in_repository.analysis.package_path = "crates/p/".into();
3293        in_repository.analysis.since = Some("abc".into());
3294        if let Finding::AssertionGap { at, .. } = &mut in_repository.findings[3] {
3295            at.id = "assertion_gap|src/lib.rs|f|s.reset();|0".into();
3296        }
3297        let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&in_repository)).unwrap();
3298        assert_eq!(
3299            results_of(&sarif)[3]["partialFingerprints"]["tmtFindingId/v2"],
3300            "assertion_gap|src/lib.rs|f|s.reset();|0"
3301        );
3302        assert_eq!(sarif["runs"][0]["properties"]["analysis"]["since"], "abc");
3303        assert_eq!(sarif["version"], "2.1.0");
3304        let results = sarif["runs"][0]["results"].as_array().unwrap();
3305        assert_eq!(results.len(), 4);
3306        assert_eq!(results[0]["ruleId"], "input-gap");
3307        assert_eq!(results[3]["ruleId"], "assertion-gap");
3308        let location = &results[3]["locations"][0]["physicalLocation"];
3309        assert_eq!(location["artifactLocation"]["uri"], "crates/p/src/lib.rs");
3310        assert_eq!(
3311            (
3312                &location["region"]["startLine"],
3313                &location["region"]["startColumn"]
3314            ),
3315            (&serde_json::json!(7), &serde_json::json!(5))
3316        );
3317        assert!(
3318            results[3]["message"]["text"]
3319                .as_str()
3320                .unwrap()
3321                .starts_with("`s.reset();`: passes every test as: delete `s.reset();`; ")
3322        );
3323        let rules = sarif["runs"][0]["tool"]["driver"]["rules"]
3324            .as_array()
3325            .unwrap();
3326        assert_eq!(rules.len(), 6);
3327    }
3328
3329    #[test]
3330    fn a_mutant_built_on_its_own_is_a_survivor_without_a_cause() {
3331        let survivor = Finding::Survivor {
3332            at: Location {
3333                file: "src/lib.rs".into(),
3334                line: 2,
3335                column: 1,
3336                code: "const fn limit() -> u8".into(),
3337                ..Location::default()
3338            },
3339            survivors: vec!["the body of `limit` replaced by `0`".into()],
3340            witness: None,
3341            change_since: None,
3342            advice: None,
3343        };
3344        assert_eq!(survivor.kind(), "survivor");
3345        assert_eq!(survivor.at().line, 2);
3346        assert_eq!(survivor.survivors().len(), 1);
3347        let report = Report {
3348            package: "p".into(),
3349            findings: vec![survivor],
3350            ..Report::default()
3351        };
3352        // Neither of the two gaps: it is counted and named as what it is.
3353        assert_eq!(
3354            render_text(&report, false),
3355            "SURVIVOR  src/lib.rs:2:1\n    const fn limit() -> u8\n\
3356             \x20 passes every test as: the body of `limit` replaced by `0`\n\
3357             \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\
3358             \n\
3359             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"
3360        );
3361        let json = serde_json::to_value(&report).unwrap();
3362        assert_eq!(json["findings"][0]["kind"], "survivor");
3363        let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
3364        assert_eq!(results_of(&sarif)[0]["ruleId"], "survivor");
3365        assert!(report.has_gaps());
3366    }
3367
3368    #[test]
3369    fn non_literal_inputs_in_words() {
3370        assert_eq!(
3371            input_for("a", "b", LiteralSide::None, 0),
3372            "`a` equal to `b`"
3373        );
3374        assert_eq!(input_for("a", "b", LiteralSide::None, 1), "`a` = `b` + 1");
3375        assert_eq!(input_for("a", "b", LiteralSide::None, -1), "`a` = `b` - 1");
3376        assert_eq!(
3377            input_for("18", "age", LiteralSide::Lhs(18), -1),
3378            "`age` = 19"
3379        );
3380    }
3381
3382    #[test]
3383    fn text_report_sections() {
3384        let at = Location {
3385            file: "src/lib.rs".into(),
3386            line: 3,
3387            column: 9,
3388            code: "s.check()?;".into(),
3389            ..Location::default()
3390        };
3391        let report = Report {
3392            schema_version: SCHEMA_VERSION,
3393            mutants: None,
3394            package: "p".into(),
3395            analysis: Analysis::default(),
3396            audit: None,
3397            evaluation: None,
3398            sites: 4,
3399            skipped_sites: 1,
3400            skipped: vec![],
3401            unviable_mutants: 2,
3402            mutants_not_built: 0,
3403            mutants_not_evaluated: 0,
3404            mutants_not_compiled: 0,
3405            mutants_run: 3,
3406            mutants_killed: 2,
3407            mutants_timed_out: 0,
3408            mutants_survived: 1,
3409            survivor_breakdown: SurvivorBreakdown {
3410                reported: 1,
3411                ..SurvivorBreakdown::default()
3412            },
3413            timeout_rechecks: TimeoutRechecks::default(),
3414            suppressed: 0,
3415            findings: vec![Finding::AssertionGap {
3416                at: at.clone(),
3417                survivors: vec!["delete `s.check()?;`".into()],
3418                tests: (0..7).map(|i| format!("tests::t{i}")).collect(),
3419                effects: vec![],
3420                effects_of: None,
3421                witness: None,
3422            }],
3423            unreached: vec![at.clone()],
3424            unstable: vec![at],
3425            weakened: vec![],
3426        };
3427        let text = render_text(&report, false);
3428        assert!(
3429            text.contains("ASSERTION GAP  src/lib.rs:3:9\n    s.check()?;"),
3430            "{text}"
3431        );
3432        assert!(text.contains("tests::t4 (+2 more)"), "{text}");
3433        assert!(text.contains("UNSTABLE  src/lib.rs:3:9"), "{text}");
3434        assert!(!text.contains("UNREACHED"), "{text}");
3435        assert!(
3436            text.contains("3 mutants run (2 killed), 1 sites unreached, 1 sites skipped"),
3437            "{text}"
3438        );
3439        assert!(
3440            text.contains(", 2 mutants left out (they do not compile)\n"),
3441            "{text}"
3442        );
3443        assert!(text.contains("--show-unreached"), "{text}");
3444        let listed = render_text(&report, true);
3445        assert!(listed.contains("UNREACHED  src/lib.rs:3:9"));
3446        assert!(!listed.contains("--show-unreached"), "{listed}");
3447        let one_more = Report {
3448            findings: vec![Finding::InputGap {
3449                at: report.unreached[0].clone(),
3450                survivors: vec!["`a`".into()],
3451                survivor_count: 2,
3452                add_tests: vec![],
3453                observed: None,
3454                verified: true,
3455            }],
3456            ..report.clone()
3457        };
3458        assert!(render_text(&one_more, false).contains("`a` (+1 more)"));
3459        let nothing_unreached = Report {
3460            unreached: vec![],
3461            ..report.clone()
3462        };
3463        assert!(!render_text(&nothing_unreached, false).contains("--show-unreached"));
3464        assert!(!Report::default().has_gaps());
3465    }
3466    #[test]
3467    fn unstable_predictions_alone_are_something_to_act_on() {
3468        let at = Location {
3469            file: "src/lib.rs".into(),
3470            line: 1,
3471            column: 1,
3472            code: "a > b".into(),
3473            ..Location::default()
3474        };
3475        assert!(!Report::default().has_gaps());
3476        assert!(
3477            Report {
3478                unstable: vec![at],
3479                ..Report::default()
3480            }
3481            .has_gaps()
3482        );
3483    }
3484
3485    #[test]
3486    fn what_counts_as_a_float_literal() {
3487        assert_eq!(float_literal("30.5"), Some(30.5));
3488        assert_eq!(float_literal(" 2.5_f32 "), Some(2.5));
3489        assert_eq!(float_literal("-1e3"), Some(-1000.0));
3490        // These parse as floats too, and are not literals: a variable called `inf`, and
3491        // forms Rust does not accept.
3492        for text in ["inf", "nan", "-inf", ".5", "+5", "e5", "limit", ""] {
3493            assert_eq!(float_literal(text), None, "{text}");
3494        }
3495    }
3496
3497    #[test]
3498    fn a_float_shift_that_does_not_move_the_literal_is_dropped() {
3499        // At 2^53 the next float below is 1 away and the next above 2 away.
3500        let survivors_of = |source: &str| {
3501            let site = site_of(source);
3502            let mut obs = Obs::of_f(-4.0);
3503            obs.merge(&Obs::of_f(4.0));
3504            let gap = InputGap::EqualNeverObserved {
3505                flipped: CmpOp::Ge,
3506                float_gap: obs.float_gap(),
3507            };
3508            match input_gap_finding("f.rs", &site, &gap, &obs, true) {
3509                Some(Finding::InputGap {
3510                    survivors,
3511                    survivor_count,
3512                    ..
3513                }) => (survivors, survivor_count),
3514                _ => panic!(),
3515            }
3516        };
3517        // Shifts of +2 and -2 are proposed. Both move the literal.
3518        assert_eq!(
3519            survivors_of("fn f(x: f64) -> bool { x > 9007199254740992.0 }"),
3520            (
3521                vec![
3522                    "`x >= 9007199254740992.0`".to_string(),
3523                    "`x > 9007199254740994.0`".to_string(),
3524                    "`x > 9007199254740990.0`".to_string(),
3525                ],
3526                3
3527            )
3528        );
3529        // At 2^54 only the step down is a different number, and on the left of the
3530        // comparison the literal moves the other way.
3531        assert_eq!(
3532            survivors_of("fn f(x: f64) -> bool { x > 18014398509481984.0 }"),
3533            (
3534                vec![
3535                    "`x >= 18014398509481984.0`".to_string(),
3536                    "`x > 1.8014398509481982e16`".to_string(),
3537                ],
3538                2
3539            )
3540        );
3541        assert_eq!(
3542            survivors_of("fn f(x: f64) -> bool { 18014398509481984.0 > x }"),
3543            (
3544                vec![
3545                    "`18014398509481984.0 >= x`".to_string(),
3546                    "`1.8014398509481982e16 > x`".to_string(),
3547                ],
3548                2
3549            )
3550        );
3551        // With the literal on the left, the nearest values are those of the other side.
3552        let site = site_of("fn f(x: f64) -> bool { 1.5 > x }");
3553        let mut obs = Obs::of_f(-1.0);
3554        obs.merge(&Obs::of_f(2.0));
3555        let gap = InputGap::EqualNeverObserved {
3556            flipped: CmpOp::Ge,
3557            float_gap: obs.float_gap(),
3558        };
3559        let Some(Finding::InputGap { observed, .. }) =
3560            input_gap_finding("f.rs", &site, &gap, &obs, true)
3561        else {
3562            panic!()
3563        };
3564        assert_eq!(
3565            observed.as_deref(),
3566            Some(
3567                "nearest values the tests passed: `x` = -0.5, 2.5; any threshold between them passes"
3568            )
3569        );
3570        // Far above, neither does.
3571        assert_eq!(
3572            survivors_of("fn f(x: f64) -> bool { x > 1e30 }"),
3573            (vec!["`x >= 1e30`".to_string()], 1)
3574        );
3575    }
3576
3577    #[test]
3578    fn the_effects_are_said_of_the_mutant_they_were_seen_with() {
3579        let gap = |survivors: &[&str], effects_of: Option<&str>| Finding::AssertionGap {
3580            at: Location {
3581                file: "src/lib.rs".into(),
3582                line: 1,
3583                column: 1,
3584                code: "a < b".into(),
3585                ..Location::default()
3586            },
3587            survivors: survivors.iter().map(|s| s.to_string()).collect(),
3588            tests: vec!["tests::t".into()],
3589            effects: vec!["with the mutant, `tests::t` now runs `x;` (src/lib.rs:2)".into()],
3590            effects_of: effects_of.map(str::to_string),
3591            witness: None,
3592        };
3593        // Of several mutants one was followed: the report says which.
3594        let body = finding_body(&gap(&["`a <= b`", "`a == b`"], Some("`a <= b`")), false);
3595        assert_eq!(
3596            body[2..],
3597            [
3598                "followed one of them through the tests: `a <= b`",
3599                "with the mutant, `tests::t` now runs `x;` (src/lib.rs:2)"
3600            ]
3601        );
3602        // A single mutant needs no saying, and nothing is said where nothing is known.
3603        for single in [
3604            gap(&["`a <= b`"], Some("`a <= b`")),
3605            gap(&["`a <= b`", "`a == b`"], None),
3606        ] {
3607            let body = finding_body(&single, false);
3608            assert_eq!(body.len(), 3, "{body:?}");
3609            assert!(body[2].starts_with("with the mutant"), "{body:?}");
3610        }
3611    }
3612
3613    #[test]
3614    fn an_audit_is_said_in_the_summary() {
3615        let mut report = Report {
3616            package: "p".into(),
3617            audit: Some(Audit {
3618                sampled: 2,
3619                survivors: 7,
3620                ..Audit::default()
3621            }),
3622            ..Report::default()
3623        };
3624        let text = render_text(&report, false);
3625        assert!(
3626            text.ends_with(
3627                "\naudit: 2 of 7 surviving mutants run against all tests, 0 failed one they had not been run against\n\
3628                 audit: recorded once more, the tests did the same\n"
3629            ),
3630            "{text}"
3631        );
3632        let audit = report.audit.as_mut().unwrap();
3633        audit.disagreements.push(Location {
3634            file: "src/lib.rs".into(),
3635            line: 3,
3636            column: 5,
3637            code: "x > 5".into(),
3638            ..Location::default()
3639        });
3640        audit.trace_differences.push(TraceDifference {
3641            binary: "p".into(),
3642            records: 4,
3643            rerun_failed: false,
3644        });
3645        let text = render_text(&report, false);
3646        assert!(
3647            text.ends_with(
3648                "all tests, 1 failed one they had not been run against\n\
3649                 \x20 src/lib.rs:3:5  x > 5\n\
3650                 audit: recorded once more, `p` differs in 4 records: its tests do not always do the same\n"
3651            ),
3652            "{text}"
3653        );
3654        // Mutants built from the source are said only where some were, with what differs.
3655        assert!(!text.contains("built from the source"), "{text}");
3656        let audit = report.audit.as_mut().unwrap();
3657        audit.rebuilt = 1;
3658        audit.not_compared = 1;
3659        let text = render_text(&report, false);
3660        assert!(
3661            text.contains(
3662                "\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"
3663            ),
3664            "{text}"
3665        );
3666        let audit = report.audit.as_mut().unwrap();
3667        audit.rebuilt = 5;
3668        audit.compared = 4;
3669        audit.source_disagreements.push(SourceDisagreement {
3670            at: Location {
3671                file: "src/lib.rs".into(),
3672                line: 9,
3673                column: 14,
3674                code: "note(asked)".into(),
3675                ..Location::default()
3676            },
3677            mutant: "the guard `note(asked)` replaced by `true`".into(),
3678            as_probe: "passes".into(),
3679            built: "fails".into(),
3680        });
3681        let text = render_text(&report, false);
3682        assert!(
3683            text.contains(
3684                "\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\
3685                 \x20 src/lib.rs:9:14  the guard `note(asked)` replaced by `true`: passes as a probe, fails built\n"
3686            ),
3687            "{text}"
3688        );
3689        assert!(!render_text(&Report::default(), false).contains("audit"));
3690    }
3691
3692    #[test]
3693    fn lists_and_counts_at_their_limits() {
3694        let items: Vec<String> = ["a", "b", "c"].iter().map(|s| s.to_string()).collect();
3695        assert_eq!(list(&items, 3), "a, b, c");
3696        assert_eq!(list(&items, 2), "a, b (+1 more)");
3697        assert_eq!(list(&items, 1), "a (+2 more)");
3698        let one = Report {
3699            package: "p".into(),
3700            suppressed: 1,
3701            unviable_mutants: 1,
3702            ..Report::default()
3703        };
3704        assert!(
3705            render_text(&one, false).contains(", 1 mutants left out (they do not compile)"),
3706            "{}",
3707            render_text(&one, false)
3708        );
3709        assert!(!render_text(&Report::default(), false).contains("left out"));
3710        assert!(!render_text(&one, false).contains("--rebuild"));
3711        assert!(!render_text(&one, false).contains("not evaluated"));
3712        let at_top = Report {
3713            mutants_not_evaluated: 1,
3714            ..Report::default()
3715        };
3716        assert!(
3717            render_text(&at_top, false).ends_with(
3718                "\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"
3719            ),
3720            "{}",
3721            render_text(&at_top, false)
3722        );
3723        // Each reason is said for the mutants it holds for, and only when it holds for some.
3724        let not_built = Report {
3725            mutants_not_evaluated: 5,
3726            mutants_not_compiled: 5,
3727            ..Report::default()
3728        };
3729        let text = render_text(&not_built, false);
3730        assert!(
3731            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"),
3732            "{text}"
3733        );
3734        assert!(!text.contains("largest value"), "{text}");
3735        let both = Report {
3736            mutants_not_evaluated: 7,
3737            mutants_not_compiled: 5,
3738            ..Report::default()
3739        };
3740        let text = render_text(&both, false);
3741        assert!(
3742            text.contains("(5 mutants not evaluated: their code"),
3743            "{text}"
3744        );
3745        assert!(
3746            text.contains("\n(2 mutants not evaluated: a range"),
3747            "{text}"
3748        );
3749        let quick = Report {
3750            mutants_not_built: 1,
3751            ..Report::default()
3752        };
3753        assert!(
3754            render_text(&quick, false)
3755                .ends_with("\n(1 more mutants need a build of their own: --rebuild runs them)\n"),
3756            "{}",
3757            render_text(&quick, false)
3758        );
3759        let slow = Report {
3760            mutants_run: 5,
3761            mutants_killed: 4,
3762            mutants_timed_out: 2,
3763            ..Report::default()
3764        };
3765        assert!(
3766            render_text(&slow, false)
3767                .contains("5 mutants run (4 killed, 2 of them by the time limit), 0 sites"),
3768            "{}",
3769            render_text(&slow, false)
3770        );
3771        assert!(!render_text(&one, false).contains("time limit"));
3772        let once = Report {
3773            mutants_timed_out: 1,
3774            ..slow.clone()
3775        };
3776        assert!(
3777            render_text(&once, false).contains("(4 killed, 1 of them by the time limit)"),
3778            "{}",
3779            render_text(&once, false)
3780        );
3781        assert!(
3782            render_text(&one, false).contains(", 1 findings suppressed"),
3783            "{}",
3784            render_text(&one, false)
3785        );
3786        assert!(!render_text(&Report::default(), false).contains("suppressed"));
3787    }
3788
3789    #[test]
3790    fn findings_are_put_in_reading_order() {
3791        let gap = |file: &str, line: usize, column: usize, survivor: &str| Finding::AssertionGap {
3792            at: Location {
3793                file: file.into(),
3794                line,
3795                column,
3796                code: "x".into(),
3797                ..Location::default()
3798            },
3799            survivors: vec![survivor.into()],
3800            tests: vec![],
3801            effects: vec![],
3802            effects_of: None,
3803            witness: None,
3804        };
3805        let mut report = Report {
3806            findings: vec![
3807                gap("src/b.rs", 1, 1, "b"),
3808                gap("src/a.rs", 9, 5, "statement"),
3809                gap("src/a.rs", 7, 2, "above it"),
3810                gap("src/a.rs", 9, 5, "its operator"),
3811                gap("src/a.rs", 9, 3, "left of both"),
3812            ],
3813            ..Report::default()
3814        };
3815        report.sort_findings();
3816        let order: Vec<&str> = report
3817            .findings
3818            .iter()
3819            .map(|f| match f {
3820                Finding::AssertionGap { survivors, .. } => survivors[0].as_str(),
3821                _ => panic!(),
3822            })
3823            .collect();
3824        // Findings at one position keep the order they were made in.
3825        assert_eq!(
3826            order,
3827            ["above it", "left of both", "statement", "its operator", "b"]
3828        );
3829    }
3830    #[test]
3831    fn second_replacements_guards_fields_and_bodies_in_words() {
3832        let all = |src: &str| discover(src, 0).unwrap().sites;
3833        let add = site_of("fn f(total: u32, fee: u32) -> u32 { total + fee }");
3834        assert_eq!(describe(&add, Mutation::ArithSwap2), "`total * fee`");
3835        let Some(Finding::InputGap {
3836            survivors,
3837            add_tests,
3838            ..
3839        }) = arith_gap_finding("f.rs", &add, Mutation::ArithSwap2, true)
3840        else {
3841            panic!()
3842        };
3843        assert_eq!(survivors, ["`total * fee`"]);
3844        assert_eq!(
3845            add_tests,
3846            ["operands for which `total + fee` and `total * fee` differ"]
3847        );
3848        let sites = all("fn f(bits: &mut u8, mask: u8) { *bits ^= mask; *bits <<= 1 }");
3849        let arith: Vec<&Site> = sites
3850            .iter()
3851            .filter(|s| matches!(s.kind, SiteKind::Arith { .. }))
3852            .collect();
3853        assert_eq!(describe(arith[0], Mutation::ArithSwap), "`*bits &= mask`");
3854        assert_eq!(describe(arith[0], Mutation::ArithSwap2), "`*bits |= mask`");
3855        let collect = site_of("fn f(bits: &mut u8, mask: u8) { *bits |= mask }");
3856        assert_eq!(
3857            arith_gap_finding("f.rs", &collect, Mutation::ArithSwap2, true),
3858            None
3859        );
3860        // A shift has one replacement: no second finding.
3861        assert_eq!(
3862            arith_gap_finding("f.rs", arith[1], Mutation::ArithSwap2, true),
3863            None
3864        );
3865
3866        let sites = all("fn f(k: Option<i32>, base: O) -> O { \
3867             let d = match k { Some(n) if n > 1 => -n, _ => 0 }; O { depth: d, ..base } }");
3868        let of = |pick: &dyn Fn(&SiteKind) -> bool| sites.iter().find(|s| pick(&s.kind)).unwrap();
3869        let guard = of(&|k| matches!(k, SiteKind::Guard { .. }));
3870        assert_eq!(
3871            describe(guard, Mutation::Const(true)),
3872            "the guard `n > 1` replaced by `true`"
3873        );
3874        assert_eq!(
3875            guard_gap_finding("f.rs", guard, false, true),
3876            Finding::InputGap {
3877                at: location("f.rs", guard),
3878                survivors: vec!["the guard `n > 1` replaced by `false`".into()],
3879                survivor_count: 1,
3880                add_tests: vec!["a case where the guard `n > 1` is true".into()],
3881                observed: None,
3882                verified: true,
3883            }
3884        );
3885        let neg = of(&|k| matches!(k, SiteKind::Neg { .. }));
3886        assert_eq!(describe(neg, Mutation::Delete), "`n`");
3887        let field = of(&|k| matches!(k, SiteKind::Field { .. }));
3888        assert_eq!(
3889            describe(field, Mutation::Delete),
3890            "without the field `depth: d` (it is then `(base).depth`)"
3891        );
3892        let body = of(&|k| matches!(k, SiteKind::Body { .. }));
3893        assert_eq!(
3894            describe(body, Mutation::Delete),
3895            "the body of `f` replaced by `Default::default()`"
3896        );
3897        assert_eq!(
3898            location("f.rs", body).code,
3899            "fn f(k: Option<i32>, base: O) -> O"
3900        );
3901    }
3902
3903    #[test]
3904    fn audit_reports_unjudged_all_tests_reruns_in_text_and_json() {
3905        let mut report = Report {
3906            package: "demo".into(),
3907            audit: Some(Audit {
3908                sampled: 3,
3909                survivors: 3,
3910                not_audited: 2,
3911                ..Audit::default()
3912            }),
3913            ..Report::default()
3914        };
3915        let text = render_text(&report, false);
3916        assert!(
3917            text.contains(
3918                "audit: 3 of 3 surviving mutants run against all tests, 0 failed one they had not been run against, 2 could not be judged\n"
3919            ),
3920            "{text}"
3921        );
3922        let value = serde_json::to_value(&report).unwrap();
3923        assert_eq!(value["audit"]["not_audited"], 2);
3924
3925        report.audit.as_mut().unwrap().not_audited = 0;
3926        let clean_text = render_text(&report, false);
3927        assert!(!clean_text.contains("could not be judged"), "{clean_text}");
3928        let clean_value = serde_json::to_value(&report).unwrap();
3929        assert!(clean_value["audit"].get("not_audited").is_none());
3930    }
3931
3932    #[test]
3933    fn sarif_emits_unstable_predictions() {
3934        let report = Report {
3935            package: "demo".into(),
3936            unstable: vec![Location {
3937                file: "src/lib.rs".into(),
3938                line: 12,
3939                column: 5,
3940                code: "age >= 18".into(),
3941                ..Location::default()
3942            }],
3943            ..Report::default()
3944        };
3945        let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
3946        let results = sarif["runs"][0]["results"].as_array().unwrap();
3947        assert_eq!(results.len(), 1);
3948        assert_eq!(results[0]["ruleId"], "unstable-prediction");
3949        assert_eq!(results[0]["level"], "error");
3950        assert_eq!(
3951            results[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
3952            "src/lib.rs"
3953        );
3954    }
3955
3956    #[test]
3957    fn sarif_emits_weakened_and_audit_disagreements_and_has_gaps() {
3958        let loc = Location {
3959            file: "src/lib.rs".into(),
3960            line: 20,
3961            column: 9,
3962            code: "x > 0".into(),
3963            ..Location::default()
3964        };
3965        let report = Report {
3966            package: "demo".into(),
3967            weakened: vec![loc.clone()],
3968            audit: Some(Audit {
3969                survivors: 1,
3970                sampled: 1,
3971                disagreements: vec![loc.clone()],
3972                not_audited: 0,
3973                rebuilt: 1,
3974                compared: 1,
3975                not_compared: 0,
3976                source_disagreements: vec![SourceDisagreement {
3977                    at: loc,
3978                    mutant: "`x >= 0`".into(),
3979                    as_probe: "passes".into(),
3980                    built: "fails".into(),
3981                }],
3982                trace_differences: vec![
3983                    TraceDifference {
3984                        binary: "unit".into(),
3985                        records: 3,
3986                        rerun_failed: false,
3987                    },
3988                    TraceDifference {
3989                        binary: "flaky".into(),
3990                        records: 0,
3991                        rerun_failed: true,
3992                    },
3993                    TraceDifference {
3994                        binary: "flaky-diff".into(),
3995                        records: 2,
3996                        rerun_failed: true,
3997                    },
3998                ],
3999            }),
4000            ..Report::default()
4001        };
4002        assert!(report.has_gaps());
4003        let text = render_text(&report, false);
4004        assert!(
4005            text.contains("`flaky` did not pass: its tests do not always do the same"),
4006            "{text}"
4007        );
4008        assert!(
4009            text.contains(
4010                "`flaky-diff` did not pass and differs in 2 records: its tests do not always do the same"
4011            ),
4012            "{text}"
4013        );
4014        let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
4015        let results = sarif["runs"][0]["results"].as_array().unwrap();
4016        let rules: Vec<_> = results
4017            .iter()
4018            .map(|r| (r["ruleId"].as_str().unwrap(), r["level"].as_str().unwrap()))
4019            .collect();
4020        assert_eq!(
4021            rules,
4022            [
4023                ("weakened-test", "warning"),
4024                ("audit-disagreement", "error"),
4025                ("audit-disagreement", "error"),
4026                ("audit-disagreement", "error"),
4027                ("audit-disagreement", "error"),
4028                ("audit-disagreement", "error"),
4029            ]
4030        );
4031        assert!(
4032            results[4]["message"]["text"]
4033                .as_str()
4034                .unwrap()
4035                .contains("did not pass"),
4036            "{}",
4037            results[4]
4038        );
4039        assert!(
4040            results[5]["message"]["text"]
4041                .as_str()
4042                .unwrap()
4043                .contains("did not pass and differed in 2 records"),
4044            "{}",
4045            results[5]
4046        );
4047        assert!(sarif["runs"][0]["properties"].get("audit").is_some());
4048    }
4049
4050    #[test]
4051    fn render_text_sanitizes_terminal_escape_sequences_bidi_and_injected_newlines() {
4052        let report = Report {
4053            package: "pkg\x1b[31mred\x1b[0m\nFAKE".into(),
4054            sites: 1,
4055            findings: vec![Finding::AssertionGap {
4056                at: Location {
4057                    file: "src/\x1b]52;c;evil\x07lib.rs".into(),
4058                    line: 10,
4059                    column: 5,
4060                    code: "x\u{202e} == 1\r\nFAKE LINE".into(),
4061                    ..Location::default()
4062                },
4063                survivors: vec!["`x \x1b[2J!= 1`".into()],
4064                tests: vec!["tests::\u{009b}31mspoof".into()],
4065                effects: vec![],
4066                effects_of: None,
4067                witness: None,
4068            }],
4069            ..Report::default()
4070        };
4071        assert_eq!(report.schema_version, SCHEMA_VERSION);
4072        let json: serde_json::Value = serde_json::to_value(&report).unwrap();
4073        assert_eq!(json["schema_version"], SCHEMA_VERSION);
4074        // JSON remains lossless.
4075        assert!(json["package"].as_str().unwrap().contains('\x1b'));
4076
4077        let text = render_text(&report, false);
4078        assert!(!text.contains('\x1b'), "{text:?}");
4079        assert!(!text.contains('\x07'), "{text:?}");
4080        assert!(!text.contains('\u{009b}'), "{text:?}");
4081        assert!(!text.contains('\u{202e}'), "{text:?}");
4082        assert!(!text.contains('\r'), "{text:?}");
4083        // Injected newlines in untrusted fields cannot start a forged line.
4084        assert!(!text.lines().any(|l| l.starts_with("FAKE")), "{text:?}");
4085        assert!(text.contains("src/lib.rs:10:5"), "{text:?}");
4086        assert!(text.contains("pkgred FAKE:"), "{text:?}");
4087
4088        // C1 OSC/DCS, C1 ST terminator, nF ESC ( B, and incomplete OSC do not leak payloads
4089        // or swallow subsequent fields on the same line.
4090        assert_eq!(sanitize_inline("a\u{009d}0;title\u{009c}b"), "ab");
4091        assert_eq!(sanitize_inline("a\u{0090}dcs-payload\u{009c}b"), "ab");
4092        assert_eq!(sanitize_inline("a\x1b]0;title\u{009c}b"), "ab");
4093        assert_eq!(sanitize_inline("a\x1b(Bb"), "ab");
4094        let report_unclosed = Report {
4095            package: "p".into(),
4096            sites: 1,
4097            findings: vec![Finding::AssertionGap {
4098                at: Location {
4099                    file: "src/lib.rs".into(),
4100                    line: 1,
4101                    column: 1,
4102                    code: "x == 1".into(),
4103                    ..Location::default()
4104                },
4105                survivors: vec!["`a\x1b]0;unterminated".into(), "`b`".into()],
4106                tests: vec!["t".into()],
4107                effects: vec![],
4108                effects_of: None,
4109                witness: None,
4110            }],
4111            ..Report::default()
4112        };
4113        let unclosed_text = render_text(&report_unclosed, false);
4114        assert!(unclosed_text.contains("`a, `b`"), "{unclosed_text:?}");
4115    }
4116
4117    #[test]
4118    fn bitor_bitxor_input_gap_advice_mentions_shared_bits_and_disjoint_equivalence() {
4119        let found = crate::instrument::discover("fn f(a: u8, b: u8) -> u8 { a | b }", 0).unwrap();
4120        let site = found
4121            .sites
4122            .iter()
4123            .find(|s| matches!(s.kind, SiteKind::Arith { .. }))
4124            .expect("arith site");
4125        let Some(Finding::InputGap { add_tests, .. }) =
4126            arith_gap_finding("src/lib.rs", site, Mutation::ArithSwap2, true)
4127        else {
4128            panic!("expected InputGap for | -> ^");
4129        };
4130        assert_eq!(add_tests.len(), 1);
4131        assert!(
4132            add_tests[0].contains("share at least one set bit")
4133                && add_tests[0].contains("disjoint by construction"),
4134            "{add_tests:?}"
4135        );
4136    }
4137
4138    #[test]
4139    fn byte_and_char_literal_nearest_values_match_pict_table() {
4140        let table = include_str!("../tests/data/literal-nearest.pict.tsv");
4141        let mut rows = 0;
4142        for line in table.lines().skip(1).filter(|l| !l.trim().is_empty()) {
4143            let cols: Vec<&str> = line.split('\t').collect();
4144            assert_eq!(cols.len(), 4, "unexpected row: {line}");
4145            let (lit_kind, lit_side, cmp_op, obs_kind) = (cols[0], cols[1], cols[2], cols[3]);
4146            let (lit_text, lit_val): (&str, Option<i128>) = match lit_kind {
4147                "byte_ascii" => ("b'A'", Some(65)),
4148                "byte_escape" => ("b'\\n'", Some(10)),
4149                "byte_non_ascii" => ("b'\\xfe'", Some(254)),
4150                "char_ascii" => ("'A'", Some(65)),
4151                "char_unicode" => ("'あ'", Some('あ' as u32 as i128)),
4152                "int" => ("65", Some(65)),
4153                "none" => ("other", None),
4154                other => panic!("unexpected LitKind: {other}"),
4155            };
4156            let (lhs, rhs, literal) = match (lit_val, lit_side) {
4157                (Some(k), "rhs") => ("tag", lit_text, LiteralSide::Rhs(k)),
4158                (Some(k), "lhs") => (lit_text, "tag", LiteralSide::Lhs(k)),
4159                (None, _) => ("tag", "other", LiteralSide::None),
4160                other => panic!("unexpected LitSide: {other:?}"),
4161            };
4162            let obs = match obs_kind {
4163                "pos_only" => Obs::of_d(46),
4164                "neg_only" => Obs::of_d(-1),
4165                "both_sides" => {
4166                    let mut o = Obs::of_d(-2);
4167                    o.merge(&Obs::of_d(1));
4168                    o
4169                }
4170                "eq_only" => Obs::of_d(0),
4171                other => panic!("unexpected ObsKind: {other}"),
4172            };
4173            let observed = observed_values(lhs, rhs, literal, &obs).expect("valued obs");
4174            match lit_kind {
4175                "byte_ascii" => {
4176                    if lit_side == "rhs" && obs_kind == "pos_only" {
4177                        assert_eq!(
4178                            observed,
4179                            "nearest values the tests passed: `tag` = b'o' (111)"
4180                        );
4181                    } else {
4182                        assert!(
4183                            observed.contains("b'") && observed.contains('('),
4184                            "{observed}"
4185                        );
4186                    }
4187                }
4188                "byte_escape" => {
4189                    if lit_side == "rhs" && obs_kind == "eq_only" {
4190                        assert_eq!(
4191                            observed,
4192                            "nearest values the tests passed: `tag` = b'\\n' (10)"
4193                        );
4194                    } else {
4195                        assert!(
4196                            observed.contains("b'") && observed.contains('('),
4197                            "{observed}"
4198                        );
4199                    }
4200                }
4201                "byte_non_ascii" => {
4202                    if lit_side == "rhs" && obs_kind == "pos_only" {
4203                        // 254 + 46 = 300 > u8::MAX: falls back cleanly to plain integer.
4204                        assert_eq!(observed, "nearest values the tests passed: `tag` = 300");
4205                    } else {
4206                        assert!(observed.contains("b'\\x"), "{observed}");
4207                    }
4208                }
4209                "char_ascii" => {
4210                    if lit_side == "rhs" && obs_kind == "pos_only" {
4211                        assert_eq!(
4212                            observed,
4213                            "nearest values the tests passed: `tag` = 'o' (111)"
4214                        );
4215                    } else {
4216                        assert!(
4217                            observed.contains('\'') && !observed.contains("b'"),
4218                            "{observed}"
4219                        );
4220                    }
4221                }
4222                "char_unicode" => {
4223                    assert!(
4224                        observed.contains('\'') && !observed.contains("b'"),
4225                        "{observed}"
4226                    );
4227                }
4228                "int" => {
4229                    assert!(!observed.contains('\''), "{observed}");
4230                }
4231                "none" => {
4232                    assert!(observed.contains("`tag` - `other` = "), "{observed}");
4233                }
4234                _ => unreachable!(),
4235            }
4236
4237            // Also check input_for and Shift description for ordering ops on both literal sides.
4238            if lit_kind == "byte_ascii" {
4239                let expected_input = "`tag` = b'A' (65)";
4240                assert_eq!(input_for(lhs, rhs, literal, 0), expected_input);
4241                if cmp_op != "eq" {
4242                    let op_sym = if cmp_op == "ge" { ">=" } else { "<" };
4243                    let expr = if lit_side == "rhs" {
4244                        format!("tag {op_sym} b'A'")
4245                    } else {
4246                        format!("b'A' {op_sym} tag")
4247                    };
4248                    let site = site_of(&format!("fn f(tag: u8) -> bool {{ {expr} }}"));
4249                    let expected = if lit_side == "rhs" {
4250                        format!("`tag {op_sym} b'B'`")
4251                    } else {
4252                        format!("`b'@' {op_sym} tag`")
4253                    };
4254                    assert_eq!(describe(&site, Mutation::Shift(1)), expected);
4255                }
4256            }
4257            if lit_kind == "char_ascii" {
4258                let expected_input = "`tag` = 'A' (65)";
4259                assert_eq!(input_for(lhs, rhs, literal, 0), expected_input);
4260                if cmp_op != "eq" {
4261                    let op_sym = if cmp_op == "ge" { ">=" } else { "<" };
4262                    let expr = if lit_side == "rhs" {
4263                        format!("tag {op_sym} 'A'")
4264                    } else {
4265                        format!("'A' {op_sym} tag")
4266                    };
4267                    let site = site_of(&format!("fn f(tag: char) -> bool {{ {expr} }}"));
4268                    let expected = if lit_side == "rhs" {
4269                        format!("`tag {op_sym} 'B'`")
4270                    } else {
4271                        format!("`'@' {op_sym} tag`")
4272                    };
4273                    assert_eq!(describe(&site, Mutation::Shift(1)), expected);
4274                }
4275            }
4276            rows += 1;
4277        }
4278        assert!(rows >= 25, "expected full PICT table, got {rows} rows");
4279
4280        // Ordinal 0xD800 maps cleanly to '\u{e000}' (57344), skipping surrogates;
4281        // out-of-range ordinals fall back to plain integers without panicking.
4282        assert_eq!(
4283            format_literal_value(0xd800, LiteralDisplay::Char),
4284            "'\\u{e000}' (57344)"
4285        );
4286        assert_eq!(
4287            format_literal_value(0x10_d800, LiteralDisplay::Char),
4288            "1103872"
4289        );
4290    }
4291}