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