Skip to main content

targeted_mutation/
report.rs

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