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