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