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