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