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