Skip to main content

targeted_mutation/
report.rs

1//! Turns planner results into findings a person can act on: which wrong implementation
2//! survives, and which input or assertion would catch it.
3
4use serde::Serialize;
5use std::path::PathBuf;
6
7use crate::instrument::{ArithOp, LiteralSide, Site, SiteKind};
8use crate::plan::{CmpOp, InputGap, LogicGap, Mutation, Obs};
9
10/// Top-level JSON/JSONL schema version emitted by `tmt`.
11pub const SCHEMA_VERSION: u32 = 1;
12
13#[derive(Clone, Debug, Default, PartialEq, Serialize)]
14pub struct Location {
15    pub file: String,
16    pub line: usize,
17    pub column: usize,
18    pub code: String,
19    /// The function or constant the code is in (`Store::commit`); empty where unknown.
20    #[serde(skip_serializing_if = "String::is_empty")]
21    pub item: String,
22    /// What the finding at this place is known by across runs: see [`finding_id`].
23    #[serde(skip_serializing_if = "String::is_empty")]
24    pub id: String,
25}
26
27/// The name a finding keeps from run to run: its kind, its file, the item it is in, its
28/// code, and which of the places with that code in that item it is (0 for the first).
29/// Lines are not in it, so code that moves keeps its name, and neither are the words
30/// that describe the surviving mutants, so those can be improved.
31pub fn finding_id(kind: &str, at: &Location, nth: usize) -> String {
32    format!("{kind}|{}|{}|{}|{nth}", at.file, at.item, at.code)
33}
34
35#[derive(Clone, Debug, PartialEq, Serialize)]
36#[serde(rename_all = "snake_case", tag = "kind")]
37pub enum Finding {
38    /// No test input can tell these mutants from the original.
39    InputGap {
40        #[serde(flatten)]
41        at: Location,
42        /// Source-level form of mutants that pass every test.
43        survivors: Vec<String>,
44        /// How many mutants the gap lets through in total.
45        survivor_count: u128,
46        /// Inputs to add, in words.
47        add_tests: Vec<String>,
48        /// What the tests did feed the comparison.
49        observed: Option<String>,
50        /// Whether the tests were re-run against a survivor to confirm.
51        verified: bool,
52    },
53    /// Tests execute the changed behaviour, and still pass.
54    AssertionGap {
55        #[serde(flatten)]
56        at: Location,
57        survivors: Vec<String>,
58        /// Tests whose execution changed under the mutants but did not fail.
59        tests: Vec<String>,
60        /// What one surviving mutant changes later in those tests: the places an
61        /// assertion could catch it. Empty when that was not looked into.
62        effects: Vec<String>,
63        /// The mutant whose effects those are, as it is written in `survivors`.
64        effects_of: Option<String>,
65        #[serde(skip_serializing_if = "Option::is_none")]
66        witness: Option<VerifiedWitness>,
67    },
68    /// A mutant that was built on its own passes every test, and nothing was recorded
69    /// that says why: whether no test runs the code (nothing can be recorded in a
70    /// `const fn`), or one does and does not look at the result.
71    Survivor {
72        #[serde(flatten)]
73        at: Location,
74        survivors: Vec<String>,
75        #[serde(skip_serializing_if = "Option::is_none")]
76        witness: Option<VerifiedWitness>,
77        /// Set when the mutant is a change undone (`--since`): the revision whose code
78        /// was put back.
79        #[serde(skip_serializing_if = "Option::is_none")]
80        change_since: Option<String>,
81        /// What to add, when the kind of mutant says it and nothing was verified.
82        #[serde(skip_serializing_if = "Option::is_none")]
83        advice: Option<String>,
84    },
85}
86
87#[derive(Clone, Debug, PartialEq, Serialize)]
88pub struct VerifiedWitness {
89    pub call: String,
90    pub original: String,
91    pub mutant: String,
92    pub assertion: String,
93    /// When the original and mutant returned the same multi-field struct differing on one
94    /// field (recursively), the narrowed dotted field path (e.g. `"fee"` or `"inner.fee"`).
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub field: Option<String>,
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub guidance: Option<String>,
99    #[serde(skip_serializing_if = "Option::is_none")]
100    pub individually_killed: Option<usize>,
101    /// The test that makes the call, where the values are those the call has there:
102    /// after what that test does before it. In a test of its own it may return another.
103    #[serde(skip_serializing_if = "Option::is_none")]
104    pub in_test: Option<String>,
105    /// The line of the finding's file on which that test makes the call.
106    #[serde(skip_serializing_if = "Option::is_none")]
107    pub in_test_line: Option<usize>,
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub in_test_column: Option<usize>,
110}
111
112impl Finding {
113    pub fn at(&self) -> &Location {
114        let (Finding::InputGap { at, .. }
115        | Finding::AssertionGap { at, .. }
116        | Finding::Survivor { at, .. }) = self;
117        at
118    }
119
120    pub fn at_mut(&mut self) -> &mut Location {
121        let (Finding::InputGap { at, .. }
122        | Finding::AssertionGap { at, .. }
123        | Finding::Survivor { at, .. }) = self;
124        at
125    }
126
127    pub fn survivors(&self) -> &[String] {
128        let (Finding::InputGap { survivors, .. }
129        | Finding::AssertionGap { survivors, .. }
130        | Finding::Survivor { survivors, .. }) = self;
131        survivors
132    }
133
134    pub(crate) fn set_witness(&mut self, evidence: VerifiedWitness) {
135        match self {
136            Self::AssertionGap { witness, .. } | Self::Survivor { witness, .. } => {
137                if witness.is_none() {
138                    *witness = Some(evidence);
139                }
140            }
141            Self::InputGap { .. } => {}
142        }
143    }
144
145    /// The kind as the JSON report and the names of findings spell it.
146    pub fn kind(&self) -> &'static str {
147        match self {
148            Finding::InputGap { .. } => "input_gap",
149            Finding::AssertionGap { .. } => "assertion_gap",
150            Finding::Survivor { .. } => "survivor",
151        }
152    }
153}
154
155/// What decides which code cargo compiles, as given on the command line.
156#[derive(Clone, Debug, Default, PartialEq, Serialize)]
157pub struct CargoConfig {
158    pub features: Vec<String>,
159    pub all_features: bool,
160    pub no_default_features: bool,
161    pub locked: bool,
162}
163
164/// What a run looked at and how: a report says nothing about what is outside of it.
165#[derive(Clone, Debug, Default, PartialEq, Serialize)]
166pub struct Nextest {
167    #[serde(skip_serializing_if = "Option::is_none")]
168    pub profile: Option<String>,
169}
170
171#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
172pub struct Shard {
173    pub index: usize,
174    pub count: usize,
175    pub round_robin: bool,
176}
177
178#[derive(Clone, Debug, Default, PartialEq, Serialize)]
179pub struct Analysis {
180    /// The package's directory in its git repository (`crates/core/`; empty at the top).
181    pub package_path: String,
182    /// Only the code changed since this revision.
183    pub since: Option<String>,
184    /// Only these lines.
185    pub lines: Vec<String>,
186    /// The packages whose tests were run.
187    pub tests_of: Vec<String>,
188    pub cargo: CargoConfig,
189    pub opt_level: Option<u8>,
190    #[serde(skip_serializing_if = "Option::is_none")]
191    pub timeout_seconds: Option<u64>,
192    #[serde(skip_serializing_if = "Option::is_none")]
193    pub baseline_jobs: Option<usize>,
194    pub timeout_recheck: &'static str,
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub wrapper_grace_seconds: Option<u64>,
197    /// Mutants that need a build of their own were run.
198    pub rebuild: bool,
199    /// Predicted survivors were re-run.
200    pub verified: bool,
201    pub doc_tests: bool,
202    #[serde(skip_serializing_if = "std::ops::Not::not")]
203    pub source_only: bool,
204    #[serde(skip_serializing_if = "std::ops::Not::not")]
205    pub literal_operators: bool,
206    #[serde(skip_serializing_if = "Option::is_none")]
207    pub shard: Option<Shard>,
208    #[serde(skip_serializing_if = "Option::is_none")]
209    pub nextest: Option<Nextest>,
210    #[serde(skip_serializing_if = "Vec::is_empty")]
211    pub error_values: Vec<String>,
212    #[serde(skip_serializing_if = "Option::is_none")]
213    pub test_selection: Option<TestSelection>,
214    #[serde(skip_serializing_if = "std::ops::Not::not")]
215    pub git_index: bool,
216    #[serde(skip_serializing_if = "Vec::is_empty")]
217    pub copy_fixtures: Vec<PathBuf>,
218    #[serde(skip_serializing_if = "Vec::is_empty")]
219    pub copy_fixture_excludes: Vec<PathBuf>,
220    #[serde(skip_serializing_if = "Vec::is_empty")]
221    pub output_fixtures: Vec<crate::output_fixture::Fixture>,
222    #[serde(skip_serializing_if = "Option::is_none")]
223    pub checkpoint: Option<PathBuf>,
224}
225
226#[derive(Clone, Debug, Default, PartialEq, Serialize)]
227pub struct TestSelection {
228    pub build_scope: TestBuildScope,
229    pub wrapper: Option<String>,
230    pub tests: Vec<String>,
231}
232
233#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
234#[serde(rename_all = "snake_case")]
235pub enum TestBuildScope {
236    #[default]
237    PackageWide,
238    SelectedTargets,
239}
240
241#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
242#[serde(rename_all = "snake_case")]
243pub enum Evaluation {
244    NoSites,
245    NoMutantsExecuted,
246}
247
248#[derive(Clone, Debug, Default, PartialEq, Serialize)]
249pub struct TimeoutRechecks {
250    pub first_pass: usize,
251    pub confirmed: usize,
252    pub recovered: usize,
253    pub unconfirmed: usize,
254}
255
256impl TimeoutRechecks {
257    fn is_empty(&self) -> bool {
258        self.first_pass == 0
259    }
260}
261
262#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
263#[serde(rename_all = "snake_case")]
264pub enum SkipReason {
265    ProbeCompileError,
266    ProbeReplacedBySourceRebuild,
267    RequiresSourceRebuild,
268    SourceNotBuilt,
269    UnparseableSource,
270}
271
272#[derive(Clone, Debug, PartialEq, Serialize)]
273pub struct SkippedSite {
274    #[serde(flatten)]
275    pub at: Location,
276    pub end_line: usize,
277    pub end_column: usize,
278    pub reason: SkipReason,
279    #[serde(skip_serializing_if = "Option::is_none")]
280    pub diagnostic: Option<String>,
281}
282
283impl SkippedSite {
284    pub(crate) fn new(
285        at: Location,
286        (end_line, end_column): (usize, usize),
287        reason: SkipReason,
288        diagnostic: Option<String>,
289    ) -> Self {
290        Self {
291            at,
292            end_line,
293            end_column,
294            reason,
295            diagnostic,
296        }
297    }
298}
299
300fn is_zero_usize(value: &usize) -> bool {
301    *value == 0
302}
303
304/// What a run that was asked to check itself found (`--audit`).
305#[derive(Clone, Debug, Default, PartialEq, Serialize)]
306pub struct Audit {
307    /// Surviving mutants that were run once more, against every test of every binary.
308    pub sampled: usize,
309    /// How many surviving mutants there were to choose from.
310    pub survivors: usize,
311    /// Sampled survivors whose all-tests re-run could not be judged (`Unable` or unconfirmed timeout).
312    #[serde(skip_serializing_if = "is_zero_usize")]
313    pub not_audited: usize,
314    /// Where one of those failed a test it had not been run against: the tests were not
315    /// chosen as they should have been, or do not always do the same.
316    pub disagreements: Vec<Location>,
317    /// Test binaries whose second recorded run was not like the first, with the number
318    /// of records (what one test saw at one site) that differ.
319    pub trace_differences: Vec<TraceDifference>,
320    /// Mutants that were run as probes and chosen to be built from the source as well.
321    pub rebuilt: usize,
322    /// Of those, the ones that built and whose two results could be compared.
323    pub compared: usize,
324    /// And the ones that did not build (or whose probe run could not be evaluated):
325    /// nothing is known about them.
326    pub not_compared: usize,
327    /// Where the two did not agree on whether the tests pass.
328    pub source_disagreements: Vec<SourceDisagreement>,
329}
330
331/// A mutant on which its probe and its source form do not agree.
332#[derive(Clone, Debug, Default, PartialEq, Serialize)]
333pub struct SourceDisagreement {
334    #[serde(flatten)]
335    pub at: Location,
336    pub mutant: String,
337    /// `passes` or `fails`: what the tests did with the probe, and with the source.
338    pub as_probe: String,
339    pub built: String,
340}
341
342#[derive(Clone, Debug, Default, PartialEq, Serialize)]
343pub struct TraceDifference {
344    pub binary: String,
345    pub records: usize,
346    #[serde(skip_serializing_if = "std::ops::Not::not")]
347    pub rerun_failed: bool,
348}
349
350/// A source edit in the candidate catalogue. Byte offsets refer to the original file.
351#[derive(Clone, Debug, PartialEq, Serialize)]
352pub struct CandidateEdit {
353    pub file: String,
354    pub line: usize,
355    pub column: usize,
356    pub start: usize,
357    pub end: usize,
358    pub before: String,
359    pub replacement: String,
360}
361
362#[derive(Clone, Debug, PartialEq, Serialize)]
363pub struct Candidate {
364    pub what: String,
365    pub into: String,
366    pub requires_rebuild: bool,
367    pub edits: Vec<CandidateEdit>,
368}
369
370#[derive(Clone, Debug, PartialEq, Serialize)]
371pub struct Report {
372    pub schema_version: u32,
373    pub package: String,
374    #[serde(skip_serializing_if = "Option::is_none")]
375    pub mutants: Option<Vec<Candidate>>,
376    pub analysis: Analysis,
377    /// Present when the run was asked to check itself.
378    #[serde(skip_serializing_if = "Option::is_none")]
379    pub audit: Option<Audit>,
380    #[serde(skip_serializing_if = "Option::is_none")]
381    pub evaluation: Option<Evaluation>,
382    pub sites: usize,
383    /// Sites that could not be instrumented (the probe did not compile there).
384    pub skipped_sites: usize,
385    #[serde(skip_serializing_if = "Vec::is_empty")]
386    pub skipped: Vec<SkippedSite>,
387    /// Values a function's body was to be replaced by that do not have its type
388    /// (`Default::default()` for a type without a default): those mutants do not exist.
389    pub unviable_mutants: usize,
390    /// Mutants that need a build of their own and were not asked for (`--rebuild`).
391    pub mutants_not_built: usize,
392    /// Mutants that could not be run as what they are (a range that ends at the largest
393    /// value of its type cannot be made to include it): neither killed nor survivors.
394    pub mutants_not_evaluated: usize,
395    /// Of those, the mutants of code that is not part of this build (another target's
396    /// file, or a `cfg` the features turn off).
397    pub mutants_not_compiled: usize,
398    pub mutants_run: usize,
399    pub mutants_killed: usize,
400    /// Killed mutants that were stopped by the timeout (typically an endless loop).
401    pub mutants_timed_out: usize,
402    #[serde(skip_serializing_if = "TimeoutRechecks::is_empty")]
403    pub timeout_rechecks: TimeoutRechecks,
404    pub findings: Vec<Finding>,
405    /// Findings left out because of a `// tmt:ignore` comment or the baseline.
406    pub suppressed: usize,
407    /// Code no test executes.
408    pub unreached: Vec<Location>,
409    /// Survivors predicted from the trace that a re-run killed: the tests are not deterministic.
410    pub unstable: Vec<Location>,
411    /// Findings in code that did not change, of a file whose tests did (`--since`): the
412    /// tests as they were at the revision found these mutants out.
413    #[serde(skip_serializing_if = "Vec::is_empty")]
414    pub weakened: Vec<Location>,
415}
416
417impl Default for Report {
418    fn default() -> Self {
419        Self {
420            schema_version: SCHEMA_VERSION,
421            package: String::new(),
422            mutants: None,
423            analysis: Analysis::default(),
424            audit: None,
425            evaluation: None,
426            sites: 0,
427            skipped_sites: 0,
428            skipped: Vec::new(),
429            unviable_mutants: 0,
430            mutants_not_built: 0,
431            mutants_not_evaluated: 0,
432            mutants_not_compiled: 0,
433            mutants_run: 0,
434            mutants_killed: 0,
435            mutants_timed_out: 0,
436            timeout_rechecks: TimeoutRechecks::default(),
437            findings: Vec::new(),
438            suppressed: 0,
439            unreached: Vec::new(),
440            unstable: Vec::new(),
441            weakened: Vec::new(),
442        }
443    }
444}
445
446impl Report {
447    pub(crate) fn record_evaluation(&mut self) {
448        self.evaluation = match (self.sites, self.mutants_run, self.skipped.is_empty()) {
449            (_, 1.., _) => None,
450            (0, 0, true) => Some(Evaluation::NoSites),
451            _ => Some(Evaluation::NoMutantsExecuted),
452        };
453    }
454
455    /// Puts the findings in reading order. Sites are numbered as they are discovered, and
456    /// a statement is discovered before the expressions of the statements above it.
457    pub fn sort_findings(&mut self) {
458        self.findings.sort_by(|a, b| {
459            let (a, b) = (a.at(), b.at());
460            (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column))
461        });
462    }
463
464    /// Whether the run found something to act on: a gap, an unstable prediction, or an
465    /// audit discrepancy (which means the report cannot be trusted as it stands).
466    pub fn has_gaps(&self) -> bool {
467        !self.findings.is_empty()
468            || !self.unstable.is_empty()
469            || self.audit.as_ref().is_some_and(|audit| {
470                !audit.disagreements.is_empty()
471                    || !audit.source_disagreements.is_empty()
472                    || !audit.trace_differences.is_empty()
473            })
474    }
475}
476
477pub fn location(file: &str, site: &Site) -> Location {
478    Location {
479        file: file.to_string(),
480        line: site.line,
481        column: site.column,
482        code: one_line(&site.text),
483        ..Location::default()
484    }
485}
486
487/// A revision as a reader wants it: a full object name cut to its first twelve digits.
488pub(crate) fn short_revision(revision: &str) -> &str {
489    let full = revision.len() >= 40 && revision.bytes().all(|byte| byte.is_ascii_hexdigit());
490    if full { &revision[..12] } else { revision }
491}
492
493pub(crate) fn one_line(code: &str) -> String {
494    const LIMIT: usize = 100;
495    const ELLIPSIS: &str = "...";
496    const PREFIX: usize = LIMIT - ELLIPSIS.len();
497
498    // A code preview can contain four bytes per displayed character.
499    // tmt:ignore performance only: the loop below gives the same text for code of any length
500    if code.len() <= 4 * LIMIT {
501        let mut words = code.split_whitespace();
502        let Some(first) = words.next() else {
503            return String::new();
504        };
505        let mut output = String::with_capacity(code.len());
506        output.push_str(first);
507        for word in words {
508            output.push(' ');
509            output.push_str(word);
510        }
511        // tmt:ignore performance only: text of more than LIMIT characters has more than LIMIT bytes, the first test only saves counting
512        if output.len() > LIMIT && output.chars().count() > LIMIT {
513            let cut = output.char_indices().nth(PREFIX).unwrap().0;
514            output.truncate(cut);
515            output.push_str(ELLIPSIS);
516        }
517        return output;
518    }
519
520    let mut output = String::with_capacity(LIMIT);
521    let mut width = 0;
522    let mut shortened_at = 0;
523    let mut separated = false;
524    for ch in code.chars() {
525        if ch.is_whitespace() {
526            separated = width != 0;
527            continue;
528        }
529        for ch in [separated.then_some(' '), Some(ch)].into_iter().flatten() {
530            if width == LIMIT {
531                output.truncate(shortened_at);
532                output.push_str(ELLIPSIS);
533                return output;
534            }
535            output.push(ch);
536            width += 1;
537            if width == PREFIX {
538                shortened_at = output.len();
539            }
540        }
541        separated = false;
542    }
543    output
544}
545
546/// Value of a float literal such as `30.5`, `1e3` or `2.5_f32`.
547fn float_literal(text: &str) -> Option<f64> {
548    let text = text.trim().replace('_', "");
549    let text = text
550        .strip_suffix("f32")
551        .or(text.strip_suffix("f64"))
552        .unwrap_or(&text);
553    let looks_numeric = text.starts_with(|c: char| c.is_ascii_digit() || c == '-')
554        && text
555            .chars()
556            .all(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E'));
557    if looks_numeric {
558        text.parse().ok()
559    } else {
560        None
561    }
562}
563
564/// Floats in reports: the shortest text that reads back as the same value, so nothing is
565/// rounded away.
566fn show_float(v: f64) -> String {
567    format!("{v:?}")
568}
569
570/// Source-level form of a mutant.
571pub fn describe(site: &Site, m: Mutation) -> String {
572    match &site.kind {
573        SiteKind::Stmt => format!("delete `{}`", one_line(&site.text)),
574        SiteKind::Neg { operand, .. } => format!("`{}`", one_line(operand)),
575        SiteKind::Guard { .. } => match m {
576            Mutation::Const(value) => {
577                format!("the guard `{}` replaced by `{value}`", one_line(&site.text))
578            }
579            _ => format!("another guard than `{}`", one_line(&site.text)),
580        },
581        SiteKind::Field {
582            from_base: Some(from_base),
583            ..
584        } => format!(
585            "without the field `{}` (it is then `{from_base}`)",
586            one_line(&site.text)
587        ),
588        SiteKind::Field {
589            from_base: None, ..
590        } => format!("without the field `{}`", one_line(&site.text)),
591        SiteKind::Body { name, value, .. } => format!("the body of `{name}` replaced by `{value}`"),
592        SiteKind::Not { operand, .. } => format!("`{}`", one_line(operand)),
593        SiteKind::Return { name, option, .. } => match (m, option) {
594            (Mutation::Const(false), Some(_)) => format!("`{name}` returning `None`"),
595            (Mutation::Const(value), _) => format!("`{name}` returning `{value}`"),
596            _ => format!("`{name}` returning something else"),
597        },
598        SiteKind::Range {
599            inclusive,
600            lhs,
601            rhs,
602            ..
603        } => {
604            let dots = if *inclusive { ".." } else { "..=" };
605            format!("`{}{dots}{}`", one_line(lhs), one_line(rhs))
606        }
607        SiteKind::Arm { pattern, .. } => format!("remove the arm `{} => ..`", one_line(pattern)),
608        SiteKind::MinMax {
609            max,
610            receiver,
611            argument,
612            ..
613        } => {
614            let other = if *max { "min" } else { "max" };
615            format!("`{}.{other}({})`", one_line(receiver), one_line(argument))
616        }
617        SiteKind::SliceEnd {
618            first, receiver, ..
619        } => {
620            let other = if *first { "last" } else { "first" };
621            format!("`{}.{other}()`", one_line(receiver))
622        }
623        SiteKind::StrAffix {
624            receiver, pattern, ..
625        } => format!("`{}.contains({})`", one_line(receiver), one_line(pattern)),
626        SiteKind::StrReplace {
627            replace_all,
628            receiver,
629            from,
630            to,
631            ..
632        } => {
633            let (r, f, t) = (one_line(receiver), one_line(from), one_line(to));
634            if *replace_all {
635                format!("`{r}.replacen({f}, {t}, 1)`")
636            } else {
637                format!("`{r}.replace({f}, {t})`")
638            }
639        }
640        SiteKind::Clamp {
641            receiver,
642            low,
643            high,
644            ..
645        } => match m {
646            Mutation::ClampDropLower => format!("`{}.min({})`", one_line(receiver), one_line(high)),
647            _ => format!("`{}.max({})`", one_line(receiver), one_line(low)),
648        },
649        SiteKind::Rounding { op, receiver, .. } => {
650            let alt = match m {
651                Mutation::RoundAlt2 => op.alt2(),
652                _ => op.alt1(),
653            };
654            format!("`{}.{}()`", one_line(receiver), alt.name())
655        }
656        SiteKind::Quantifier {
657            all,
658            receiver,
659            predicate,
660            ..
661        } => {
662            let other = if *all { "any" } else { "all" };
663            format!("`{}.{other}({})`", one_line(receiver), one_line(predicate))
664        }
665        SiteKind::LiteralSet {
666            receiver, argument, ..
667        } => format!(
668            "without a literal element in `{}.contains({})`",
669            one_line(receiver),
670            one_line(argument)
671        ),
672        SiteKind::Logic { and, lhs, rhs, .. } => {
673            let (lhs, rhs) = (one_line(lhs), one_line(rhs));
674            match m {
675                // Both operands are still evaluated whenever the original evaluates them;
676                // only the value of one is ignored. The forms below say exactly that.
677                Mutation::LogicDropRhs if *and => format!("`{lhs} && {{ {rhs}; true }}`"),
678                Mutation::LogicDropRhs => format!("`{lhs} || {{ {rhs}; false }}`"),
679                Mutation::LogicDropLhs => format!("`{{ {lhs}; {rhs} }}`"),
680                _ => format!("`{lhs} {} {rhs}`", if *and { "||" } else { "&&" }),
681            }
682        }
683        SiteKind::Arith {
684            op,
685            assign,
686            lhs,
687            rhs,
688            ..
689        } => {
690            let eq = if *assign { "=" } else { "" };
691            let other = match m {
692                Mutation::ArithSwap2 => op.swapped2().unwrap_or(op.swapped()),
693                _ => op.swapped(),
694            };
695            format!(
696                "`{} {}{eq} {}`",
697                one_line(lhs),
698                other.symbol(),
699                one_line(rhs)
700            )
701        }
702        SiteKind::Cmp {
703            op,
704            lhs,
705            rhs,
706            literal,
707            ..
708        } => {
709            let (lhs, rhs) = (one_line(lhs), one_line(rhs));
710            let sym = op.symbol();
711            match m {
712                Mutation::Const(c) => format!("`{c}`"),
713                Mutation::Op(op2) => format!("`{lhs} {} {rhs}`", op2.symbol()),
714                Mutation::Shift(d) => match literal {
715                    LiteralSide::Rhs(k) => format!("`{lhs} {sym} {}`", k + d),
716                    // k op rhs + d  <=>  k - d op rhs
717                    LiteralSide::Lhs(k) => format!("`{} {sym} {rhs}`", k - d),
718                    LiteralSide::None => match (op, d) {
719                        (CmpOp::Ge, 1) => format!("`{lhs} > {rhs}`"),
720                        (CmpOp::Gt, -1) => format!("`{lhs} >= {rhs}`"),
721                        (CmpOp::Le, -1) => format!("`{lhs} < {rhs}`"),
722                        (CmpOp::Lt, 1) => format!("`{lhs} <= {rhs}`"),
723                        // Meant as arithmetic on whole numbers: in the operands' own
724                        // type the addition could overflow, the mutant that was run cannot.
725                        // tmt:ignore a shift of 0 is never planned, so `>=` is the same
726                        (_, d) if d > 0 => format!("`{lhs} {sym} {rhs} + {d}` (without overflow)"),
727                        (_, d) => format!("`{lhs} {sym} {rhs} - {}` (without overflow)", -d),
728                    },
729                },
730                Mutation::ShiftF(d) => match (float_literal(&lhs), float_literal(&rhs)) {
731                    (None, Some(k)) => format!("`{lhs} {sym} {}`", show_float(k + d)),
732                    (Some(k), None) => format!("`{} {sym} {rhs}`", show_float(k - d)),
733                    // tmt:ignore a shift of 0 is never planned, so any threshold near it is the same
734                    _ if d > 0.0 => format!("`{lhs} {sym} {rhs} + {}`", show_float(d)),
735                    _ => format!("`{lhs} {sym} {rhs} - {}`", show_float(-d)),
736                },
737                _ => format!("`!({lhs} {sym} {rhs})`"),
738            }
739        }
740    }
741}
742
743/// The operand values that give `lhs - rhs = d`, in words.
744fn input_for(lhs: &str, rhs: &str, literal: LiteralSide, d: i128) -> String {
745    match (literal, d) {
746        (LiteralSide::Rhs(k), d) => format!("`{lhs}` = {}", k + d),
747        (LiteralSide::Lhs(k), d) => format!("`{rhs}` = {}", k - d),
748        (LiteralSide::None, 0) => format!("`{lhs}` equal to `{rhs}`"),
749        // tmt:ignore 0 is taken by the arm above, so `>=` is the same
750        (LiteralSide::None, d) if d > 0 => format!("`{lhs}` = `{rhs}` + {d}"),
751        (LiteralSide::None, d) => format!("`{lhs}` = `{rhs}` - {}", -d),
752    }
753}
754
755fn observed_values(lhs: &str, rhs: &str, literal: LiteralSide, obs: &Obs) -> Option<String> {
756    if !obs.valued() {
757        return None;
758    }
759    let ds: Vec<i128> = [obs.max_neg, obs.eq.then_some(0), obs.min_pos]
760        .into_iter()
761        .flatten()
762        .collect();
763    let text = match literal {
764        LiteralSide::Rhs(k) => {
765            let values: Vec<String> = ds.iter().map(|d| (k + d).to_string()).collect();
766            format!("`{lhs}` = {}", values.join(", "))
767        }
768        LiteralSide::Lhs(k) => {
769            let mut values: Vec<i128> = ds.iter().map(|d| k - d).collect();
770            values.sort();
771            let values: Vec<String> = values.iter().map(i128::to_string).collect();
772            format!("`{rhs}` = {}", values.join(", "))
773        }
774        LiteralSide::None => {
775            let values: Vec<String> = ds.iter().map(i128::to_string).collect();
776            format!("`{lhs}` - `{rhs}` = {}", values.join(", "))
777        }
778    };
779    Some(format!("nearest values the tests passed: {text}"))
780}
781
782/// Builds the input-gap finding for a comparison site. `None` for gaps that are reported
783/// elsewhere (unreached code).
784pub fn input_gap_finding(
785    file: &str,
786    site: &Site,
787    gap: &InputGap,
788    obs: &Obs,
789    verified: bool,
790) -> Option<Finding> {
791    let SiteKind::Cmp {
792        op,
793        lhs,
794        rhs,
795        literal,
796        ..
797    } = &site.kind
798    else {
799        return None;
800    };
801    let (lhs_text, rhs_text) = (one_line(lhs), one_line(rhs));
802    // A float shift too small to move the literal is not a different program. The
803    // literal moves the way `describe` writes it.
804    let moves = |d: f64| match (float_literal(&lhs_text), float_literal(&rhs_text)) {
805        (None, Some(k)) => k + d != k,
806        (Some(k), None) => k - d != k,
807        _ => true,
808    };
809    let survivors: Vec<String> = gap
810        .survivors()
811        .into_iter()
812        .filter(|m| !matches!(m, Mutation::ShiftF(d) if !moves(*d)))
813        .map(|m| describe(site, m))
814        .collect();
815    let mut observed = observed_values(&lhs_text, &rhs_text, *literal, obs);
816    let (survivor_count, add_tests) = match gap {
817        InputGap::Unreached => return None,
818        InputGap::OneSided { always } => (
819            1,
820            vec![format!(
821                "an input that makes `{}` {}",
822                one_line(&site.text),
823                !always
824            )],
825        ),
826        InputGap::EqualNeverObserved { flipped, float_gap } => {
827            if let Some((lo, hi)) = float_gap {
828                observed = Some(match (float_literal(&lhs_text), float_literal(&rhs_text)) {
829                    (None, Some(k)) => format!(
830                        "nearest values the tests passed: `{lhs_text}` = {}, {}; any threshold between them passes",
831                        show_float(k + lo),
832                        show_float(k + hi)
833                    ),
834                    (Some(k), None) => format!(
835                        "nearest values the tests passed: `{rhs_text}` = {}, {}; any threshold between them passes",
836                        show_float(k - hi),
837                        show_float(k - lo)
838                    ),
839                    _ => format!(
840                        "nearest values the tests passed: `{lhs_text}` - `{rhs_text}` = {}, {}",
841                        show_float(*lo),
842                        show_float(*hi)
843                    ),
844                });
845            }
846            (
847                survivors.len() as u128,
848                vec![format!(
849                    "`{lhs_text}` equal to `{rhs_text}` (the original gives {}, the mutant {})",
850                    op.eval_d(0),
851                    flipped.eval_d(0)
852                )],
853            )
854        }
855        InputGap::Boundary {
856            min_shift,
857            max_shift,
858            missing,
859            same,
860        } => {
861            let add = missing
862                .iter()
863                .map(|d| {
864                    format!(
865                        "{} (the original gives {})",
866                        input_for(&lhs_text, &rhs_text, *literal, *d),
867                        op.eval_d(*d)
868                    )
869                })
870                .collect();
871            // Without the shifts that are no mutants: the expression cannot be a
872            // value that tells them from the original.
873            (((max_shift - min_shift) - (same.1 - same.0)) as u128, add)
874        }
875    };
876    Some(Finding::InputGap {
877        at: location(file, site),
878        survivors,
879        survivor_count,
880        add_tests,
881        observed,
882        verified,
883    })
884}
885
886/// Input gap at `a && b` / `a || b`: one operand never decides the result in any test.
887pub fn logic_gap_finding(
888    file: &str,
889    site: &Site,
890    gap: LogicGap,
891    verified: bool,
892) -> Option<Finding> {
893    let SiteKind::Logic { and, lhs, rhs, .. } = &site.kind else {
894        return None;
895    };
896    let (lhs, rhs) = (one_line(lhs), one_line(rhs));
897    let (mutation, add) = match (gap, and) {
898        (LogicGap::Unreached, _) => return None,
899        (LogicGap::RhsNeverDecides, true) => (
900            Mutation::LogicDropRhs,
901            format!("a case where `{lhs}` is true and `{rhs}` is false"),
902        ),
903        (LogicGap::RhsNeverDecides, false) => (
904            Mutation::LogicDropRhs,
905            format!("a case where `{lhs}` is false and `{rhs}` is true"),
906        ),
907        (LogicGap::LhsNeverDecides, true) => (
908            Mutation::LogicDropLhs,
909            format!("a case where `{lhs}` is false"),
910        ),
911        (LogicGap::LhsNeverDecides, false) => (
912            Mutation::LogicDropLhs,
913            format!("a case where `{lhs}` is true"),
914        ),
915    };
916    Some(Finding::InputGap {
917        at: location(file, site),
918        survivors: vec![describe(site, mutation)],
919        survivor_count: 1,
920        add_tests: vec![add],
921        observed: None,
922        verified,
923    })
924}
925
926/// Input gap at `v.first()` / `v.last()`: no test gave more than one element.
927pub fn slice_end_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
928    let SiteKind::SliceEnd { receiver, .. } = &site.kind else {
929        return None;
930    };
931    Some(Finding::InputGap {
932        at: location(file, site),
933        survivors: vec![describe(site, Mutation::OtherEnd)],
934        survivor_count: 1,
935        add_tests: vec![format!(
936            "`{}` with two or more elements, the first different from the last",
937            one_line(receiver)
938        )],
939        observed: None,
940        verified,
941    })
942}
943
944/// Input gap at `a.max(b)` / `a.min(b)`: the two operands were equal in every test.
945pub fn min_max_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
946    let SiteKind::MinMax {
947        receiver, argument, ..
948    } = &site.kind
949    else {
950        return None;
951    };
952    Some(Finding::InputGap {
953        at: location(file, site),
954        survivors: vec![describe(site, Mutation::MinMax)],
955        survivor_count: 1,
956        add_tests: vec![format!(
957            "`{}` different from `{}`",
958            one_line(receiver),
959            one_line(argument)
960        )],
961        observed: None,
962        verified,
963    })
964}
965
966/// Input gap at `s.starts_with(p)` / `s.ends_with(p)`: no test passed a string containing `p`
967/// away from the prefix/suffix position.
968pub fn str_affix_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
969    let SiteKind::StrAffix {
970        starts,
971        receiver,
972        pattern,
973        ..
974    } = &site.kind
975    else {
976        return None;
977    };
978    let where_else = if *starts { "start" } else { "end" };
979    Some(Finding::InputGap {
980        at: location(file, site),
981        survivors: vec![describe(site, Mutation::StrContains)],
982        survivor_count: 1,
983        add_tests: vec![format!(
984            "`{}` containing `{}` somewhere other than the {where_else}",
985            one_line(receiver),
986            one_line(pattern)
987        )],
988        observed: None,
989        verified,
990    })
991}
992
993/// Input gap at `s.replace(a, b)` / `s.replacen(a, b, 1)`: no test had `a` occur more than once.
994pub fn str_replace_gap_finding(file: &str, site: &Site, verified: bool) -> Option<Finding> {
995    let SiteKind::StrReplace { receiver, from, .. } = &site.kind else {
996        return None;
997    };
998    Some(Finding::InputGap {
999        at: location(file, site),
1000        survivors: vec![describe(site, Mutation::StrReplaceMultiplicity)],
1001        survivor_count: 1,
1002        add_tests: vec![format!(
1003            "`{}` containing `{}` more than once",
1004            one_line(receiver),
1005            one_line(from)
1006        )],
1007        observed: None,
1008        verified,
1009    })
1010}
1011
1012/// Input gap at `x.clamp(lo, hi)`: no test crossed the dropped bound.
1013pub fn clamp_gap_finding(
1014    file: &str,
1015    site: &Site,
1016    mutation: Mutation,
1017    verified: bool,
1018) -> Option<Finding> {
1019    let SiteKind::Clamp {
1020        receiver,
1021        low,
1022        high,
1023        ..
1024    } = &site.kind
1025    else {
1026        return None;
1027    };
1028    let advice = if mutation == Mutation::ClampDropLower {
1029        format!(
1030            "`{}` below the lower clamp bound `{}`",
1031            one_line(receiver),
1032            one_line(low)
1033        )
1034    } else {
1035        format!(
1036            "`{}` above the upper clamp bound `{}`",
1037            one_line(receiver),
1038            one_line(high)
1039        )
1040    };
1041    Some(Finding::InputGap {
1042        at: location(file, site),
1043        survivors: vec![describe(site, mutation)],
1044        survivor_count: 1,
1045        add_tests: vec![advice],
1046        observed: None,
1047        verified,
1048    })
1049}
1050
1051/// Input gap at `x.floor()` / `.ceil()` / `.round()` / `.trunc()`: no test distinguished the rounding mode.
1052pub fn rounding_gap_finding(
1053    file: &str,
1054    site: &Site,
1055    mutation: Mutation,
1056    verified: bool,
1057) -> Option<Finding> {
1058    let SiteKind::Rounding { op, receiver, .. } = &site.kind else {
1059        return None;
1060    };
1061    let alt = if mutation == Mutation::RoundAlt2 {
1062        op.alt2()
1063    } else {
1064        op.alt1()
1065    };
1066    Some(Finding::InputGap {
1067        at: location(file, site),
1068        survivors: vec![describe(site, mutation)],
1069        survivor_count: 1,
1070        add_tests: vec![format!(
1071            "`{}` that is {}",
1072            one_line(receiver),
1073            op.differs_for(alt)
1074        )],
1075        observed: None,
1076        verified,
1077    })
1078}
1079
1080/// Input gap at a `-> bool` function that returned the same value in every test.
1081pub fn return_gap_finding(
1082    file: &str,
1083    site: &Site,
1084    always: bool,
1085    verified: bool,
1086) -> Option<Finding> {
1087    let SiteKind::Return { name, option, .. } = &site.kind else {
1088        return None;
1089    };
1090    let other = match (option, always) {
1091        (None, always) => format!("{}", !always),
1092        (Some(_), false) => "`Some`".to_string(),
1093        (Some(_), true) => "`None`".to_string(),
1094    };
1095    Some(Finding::InputGap {
1096        at: location(file, site),
1097        survivors: vec![describe(site, Mutation::Const(always))],
1098        survivor_count: 1,
1099        add_tests: vec![format!("a case where `{name}` returns {other}")],
1100        observed: None,
1101        verified,
1102    })
1103}
1104
1105/// Input gap at the guard of a match arm that had the same value in every test.
1106pub fn guard_gap_finding(file: &str, site: &Site, always: bool, verified: bool) -> Finding {
1107    Finding::InputGap {
1108        at: location(file, site),
1109        survivors: vec![describe(site, Mutation::Const(always))],
1110        survivor_count: 1,
1111        add_tests: vec![format!(
1112            "a case where the guard `{}` is {}",
1113            one_line(&site.text),
1114            !always
1115        )],
1116        observed: None,
1117        verified,
1118    }
1119}
1120
1121/// Input gap at an arithmetic operator: the swapped operator computes the same value on
1122/// every pair of operands the tests pass.
1123pub fn arith_gap_finding(
1124    file: &str,
1125    site: &Site,
1126    mutation: Mutation,
1127    verified: bool,
1128) -> Option<Finding> {
1129    let SiteKind::Arith {
1130        op,
1131        assign,
1132        lhs,
1133        rhs,
1134        ..
1135    } = &site.kind
1136    else {
1137        return None;
1138    };
1139    let (lhs, rhs) = (one_line(lhs), one_line(rhs));
1140    let eq = if *assign { "=" } else { "" };
1141    let other = match mutation {
1142        Mutation::ArithSwap2 => op.second(*assign)?,
1143        _ => op.swapped(),
1144    };
1145    let add = match (op, other) {
1146        (ArithOp::Add, ArithOp::Sub) | (ArithOp::Sub, ArithOp::Add) => {
1147            format!("`{rhs}` other than 0")
1148        }
1149        _ => format!(
1150            "operands for which `{lhs} {}{eq} {rhs}` and `{lhs} {}{eq} {rhs}` differ",
1151            op.symbol(),
1152            other.symbol()
1153        ),
1154    };
1155    Some(Finding::InputGap {
1156        at: location(file, site),
1157        survivors: vec![describe(site, mutation)],
1158        survivor_count: 1,
1159        add_tests: vec![add],
1160        observed: None,
1161        verified,
1162    })
1163}
1164
1165/// The report as SARIF 2.1.0, with file names relative to the repository root.
1166pub fn render_sarif(report: &Report) -> String {
1167    serde_json::to_string_pretty(&sarif_document(vec![sarif_run(report)]))
1168        .expect("JSON values serialise")
1169}
1170
1171/// The CLI's workspace SARIF has one run per member, the analysed ones in report order
1172/// and then those whose analysis could not run (`failed`: package and what went wrong).
1173/// A member that failed is a run that says so: a document without it would read as a
1174/// package with nothing to report. Each run has an id of its own, by which a service
1175/// that takes several runs of one tool keeps them apart.
1176#[doc(hidden)]
1177pub fn workspace_sarif(reports: &[Report], failed: &[(String, String)]) -> impl std::fmt::Display {
1178    let category = |package: &str| serde_json::json!({ "id": format!("tmt/{package}/") });
1179    let mut runs: Vec<serde_json::Value> = reports
1180        .iter()
1181        .map(|report| {
1182            let mut run = sarif_run(report);
1183            run["properties"]["package"] = serde_json::json!(report.package);
1184            run["automationDetails"] = category(&report.package);
1185            run["invocations"] = serde_json::json!([{ "executionSuccessful": true }]);
1186            run
1187        })
1188        .collect();
1189    for (package, error) in failed {
1190        runs.push(serde_json::json!({
1191            "tool": sarif_tool(),
1192            "automationDetails": category(package),
1193            "invocations": [{
1194                "executionSuccessful": false,
1195                "toolExecutionNotifications": [{
1196                    "level": "error",
1197                    "message": { "text": error },
1198                }],
1199            }],
1200            "properties": { "package": package },
1201            "results": [],
1202        }));
1203    }
1204    sarif_document(runs)
1205}
1206
1207/// A path as the URI reference SARIF wants: `/` between its parts, and in the parts
1208/// every byte that is not plainly allowed in one (a space, `#`, `%`, what is not ASCII)
1209/// written as `%XX`.
1210fn sarif_uri(prefix: &str, file: &str) -> String {
1211    sarif_uri_for(prefix, file, cfg!(windows))
1212}
1213
1214fn sarif_uri_for(prefix: &str, file: &str, backslash_is_separator: bool) -> String {
1215    let mut uri = String::new();
1216    for byte in prefix.bytes().chain(file.bytes()) {
1217        let byte = if backslash_is_separator && byte == b'\\' {
1218            b'/'
1219        } else {
1220            byte
1221        };
1222        match byte {
1223            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
1224                uri.push(byte as char)
1225            }
1226            _ => uri.push_str(&format!("%{byte:02X}")),
1227        }
1228    }
1229    uri
1230}
1231
1232fn sarif_tool() -> serde_json::Value {
1233    serde_json::json!({ "driver": {
1234        "name": "tmt",
1235        "rules": [
1236            { "id": "input-gap", "shortDescription": { "text": "No test input tells this mutant from the original" } },
1237            { "id": "assertion-gap", "shortDescription": { "text": "Tests run the mutated code and still pass" } },
1238            { "id": "survivor", "shortDescription": { "text": "A mutant built on its own passes every test; why is not known" } },
1239            { "id": "unstable-prediction", "shortDescription": { "text": "A predicted survivor failed when re-run; tests may be non-deterministic" } },
1240            { "id": "weakened-test", "shortDescription": { "text": "Tests since the base revision stopped catching a mutant in unchanged code" } },
1241            { "id": "audit-disagreement", "shortDescription": { "text": "Audit found a mismatch between selective/probe results and full/source execution" } }
1242        ]
1243    } })
1244}
1245
1246fn sarif_document(runs: Vec<serde_json::Value>) -> serde_json::Value {
1247    let mut document = serde_json::json!({
1248        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
1249        "version": "2.1.0",
1250    });
1251    document["runs"] = serde_json::Value::Array(runs);
1252    document
1253}
1254
1255fn sarif_run(report: &Report) -> serde_json::Value {
1256    let prefix = report.analysis.package_path.as_str();
1257    let mut results: Vec<serde_json::Value> = report
1258        .findings
1259        .iter()
1260        .map(|finding| {
1261            let (kind, at) = finding_parts(finding);
1262            let rule = match kind {
1263                "INPUT GAP" => "input-gap",
1264                "ASSERTION GAP" => "assertion-gap",
1265                _ => "survivor",
1266            };
1267            let text = format!("`{}`: {}", at.code, finding_body(finding, false).join("; "));
1268            serde_json::json!({
1269                "ruleId": rule,
1270                "level": "warning",
1271                "message": { "text": text },
1272                // What the service tells a finding of one run from that of another by.
1273                "partialFingerprints": { "tmtFindingId/v2": at.id },
1274                "locations": [{
1275                    "physicalLocation": {
1276                        "artifactLocation": { "uri": sarif_uri(prefix, &at.file) },
1277                        "region": { "startLine": at.line, "startColumn": at.column }
1278                    }
1279                }]
1280            })
1281        })
1282        .collect();
1283    for at in &report.unstable {
1284        results.push(serde_json::json!({
1285            "ruleId": "unstable-prediction",
1286            "level": "error",
1287            "message": {
1288                "text": format!(
1289                    "`{}`: trace predicted a survivor, but the re-run failed (tests may not be deterministic)",
1290                    at.code
1291                )
1292            },
1293            "locations": [{
1294                "physicalLocation": {
1295                    "artifactLocation": { "uri": sarif_uri(prefix, &at.file) },
1296                    "region": { "startLine": at.line, "startColumn": at.column }
1297                }
1298            }]
1299        }));
1300    }
1301    for at in &report.weakened {
1302        results.push(serde_json::json!({
1303            "ruleId": "weakened-test",
1304            "level": "warning",
1305            "message": {
1306                "text": format!(
1307                    "`{}`: mutant in unchanged code now survives after test changes",
1308                    at.code
1309                )
1310            },
1311            "locations": [{
1312                "physicalLocation": {
1313                    "artifactLocation": { "uri": sarif_uri(prefix, &at.file) },
1314                    "region": { "startLine": at.line, "startColumn": at.column }
1315                }
1316            }]
1317        }));
1318    }
1319    if let Some(audit) = &report.audit {
1320        for at in &audit.disagreements {
1321            results.push(serde_json::json!({
1322                "ruleId": "audit-disagreement",
1323                "level": "error",
1324                "message": {
1325                    "text": format!(
1326                        "`{}`: survived selective tests, but failed when audited against all tests",
1327                        at.code
1328                    )
1329                },
1330                "locations": [{
1331                    "physicalLocation": {
1332                        "artifactLocation": { "uri": sarif_uri(prefix, &at.file) },
1333                        "region": { "startLine": at.line, "startColumn": at.column }
1334                    }
1335                }]
1336            }));
1337        }
1338        for diff in &audit.source_disagreements {
1339            results.push(serde_json::json!({
1340                "ruleId": "audit-disagreement",
1341                "level": "error",
1342                "message": {
1343                    "text": format!(
1344                        "`{}` ({}): {} as a probe, {} built from source",
1345                        diff.at.code, diff.mutant, diff.as_probe, diff.built
1346                    )
1347                },
1348                "locations": [{
1349                    "physicalLocation": {
1350                        "artifactLocation": { "uri": sarif_uri(prefix, &diff.at.file) },
1351                        "region": { "startLine": diff.at.line, "startColumn": diff.at.column }
1352                    }
1353                }]
1354            }));
1355        }
1356        for diff in &audit.trace_differences {
1357            let text = if diff.rerun_failed && diff.records == 0 {
1358                format!(
1359                    "audit trace re-run for `{}` did not pass (tests may not be deterministic)",
1360                    diff.binary
1361                )
1362            } else if diff.rerun_failed {
1363                format!(
1364                    "audit trace re-run for `{}` did not pass and differed in {} records",
1365                    diff.binary, diff.records
1366                )
1367            } else {
1368                format!(
1369                    "audit trace for `{}` differed between two runs ({} records)",
1370                    diff.binary, diff.records
1371                )
1372            };
1373            results.push(serde_json::json!({
1374                "ruleId": "audit-disagreement",
1375                "level": "error",
1376                "message": { "text": text }
1377            }));
1378        }
1379    }
1380    let mut properties = serde_json::json!({
1381        "analysis": report.analysis,
1382        "evaluation": report.evaluation,
1383        "skipped": report.skipped,
1384    });
1385    if let Some(audit) = &report.audit {
1386        properties["audit"] = serde_json::json!(audit);
1387    }
1388    let mut run = serde_json::json!({
1389        "tool": sarif_tool(),
1390        // What was looked at: a run of a part says nothing about the rest.
1391        "properties": properties,
1392    });
1393    run["results"] = serde_json::Value::Array(results);
1394    run
1395}
1396
1397fn list(items: &[String], limit: usize) -> String {
1398    let shown: Vec<&str> = items.iter().take(limit).map(String::as_str).collect();
1399    let more = items.len().saturating_sub(limit);
1400    if more > 0 {
1401        format!("{} (+{more} more)", shown.join(", "))
1402    } else {
1403        shown.join(", ")
1404    }
1405}
1406
1407/// The lines of one finding, without its header. When `sanitize` is true, each untrusted
1408/// field is sanitized before being joined so an incomplete escape sequence in one field
1409/// cannot swallow later fields on the same line.
1410fn finding_body(finding: &Finding, sanitize: bool) -> Vec<String> {
1411    let clean = |s: &str| {
1412        if sanitize {
1413            sanitize_inline(s)
1414        } else {
1415            s.to_string()
1416        }
1417    };
1418    let clean_list = |items: &[String]| {
1419        if sanitize {
1420            items
1421                .iter()
1422                .map(|s| sanitize_inline(s))
1423                .collect::<Vec<_>>()
1424                .join(", ")
1425        } else {
1426            items.join(", ")
1427        }
1428    };
1429    let mut lines = vec![];
1430    match finding {
1431        Finding::InputGap {
1432            survivors,
1433            survivor_count,
1434            add_tests,
1435            observed,
1436            verified,
1437            ..
1438        } => {
1439            let more = survivor_count.saturating_sub(survivors.len() as u128);
1440            let more = if more > 0 {
1441                format!(" (+{more} more)")
1442            } else {
1443                String::new()
1444            };
1445            let note = if *verified {
1446                "re-run: tests pass"
1447            } else {
1448                "from the trace, not re-run"
1449            };
1450            lines.push(format!(
1451                "passes every test as: {}{more}  [{note}]",
1452                clean_list(survivors)
1453            ));
1454            lines.extend(observed.iter().map(|s| clean(s)));
1455            lines.extend(
1456                add_tests
1457                    .iter()
1458                    .map(|test| format!("add a test with {}", clean(test))),
1459            );
1460        }
1461        Finding::AssertionGap {
1462            survivors,
1463            tests,
1464            effects,
1465            effects_of,
1466            witness,
1467            ..
1468        } => {
1469            lines.push(format!("passes every test as: {}", clean_list(survivors)));
1470            let shown_tests: Vec<String> = tests.iter().map(|t| clean(t)).collect();
1471            lines.push(format!(
1472                "these tests run the changed code and still pass: {}",
1473                list(&shown_tests, 5)
1474            ));
1475            if effects.is_empty() {
1476                lines.push("add an assertion on what this code is responsible for".to_string());
1477            } else {
1478                // Which of several mutants was followed, so that what is said of "the
1479                // mutant" below can be tried.
1480                if let (Some(followed), true) = (effects_of, survivors.len() > 1) {
1481                    lines.push(format!(
1482                        "followed one of them through the tests: {}",
1483                        clean(followed)
1484                    ));
1485                }
1486                lines.extend(effects.iter().map(|s| clean(s)));
1487            }
1488            if let Some(witness) = witness {
1489                lines.extend(witness_lines(witness, sanitize));
1490            }
1491        }
1492        Finding::Survivor {
1493            survivors,
1494            change_since: Some(revision),
1495            ..
1496        } => {
1497            lines.push(format!("passes every test {}", clean_list(survivors)));
1498            lines.push(format!(
1499                "no test tells this change from the code as it was at {}: add one that fails without it",
1500                clean(short_revision(revision))
1501            ));
1502        }
1503        Finding::Survivor {
1504            survivors,
1505            witness,
1506            advice,
1507            ..
1508        } => {
1509            lines.push(format!("passes every test as: {}", clean_list(survivors)));
1510            if let Some(witness) = witness {
1511                lines.extend(witness_lines(witness, sanitize));
1512            } else if let Some(advice) = advice {
1513                lines.push(clean(advice));
1514            } else {
1515                lines.push(
1516                    "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"
1517                        .to_string(),
1518                );
1519            }
1520        }
1521    }
1522    lines
1523}
1524
1525fn witness_lines(witness: &VerifiedWitness, sanitize: bool) -> Vec<String> {
1526    let clean = |s: &str| {
1527        if sanitize {
1528            sanitize_inline(s)
1529        } else {
1530            s.to_string()
1531        }
1532    };
1533    let call = clean(&witness.call);
1534    let orig = clean(&witness.original);
1535    let mut_val = clean(&witness.mutant);
1536    let assertion = clean(&witness.assertion);
1537    if let Some(test) = &witness.in_test {
1538        let test = clean(test);
1539        // The test may make the call more than once, with another result each time.
1540        let place = witness
1541            .in_test_line
1542            .zip(witness.in_test_column)
1543            .map(|(line, column)| format!("line {line}, column {column}"));
1544        let (on, of) = place.map_or_else(
1545            || (String::new(), "that call".to_string()),
1546            |place| (format!(" at {place}"), format!("the call at {place}")),
1547        );
1548        return vec![
1549            format!(
1550                "verified on `{call}` where `{test}` calls it{on}: original returned {orig}, mutant returned {mut_val}",
1551            ),
1552            format!("in `{test}`, compare the result of {of} with this value: `{assertion}`"),
1553        ];
1554    }
1555    let mut lines = vec![format!(
1556        "verified on `{call}`: original returned {orig}, mutant returned {mut_val}",
1557    )];
1558    if let Some(killed) = witness.individually_killed {
1559        lines.push(format!(
1560            "the selected tests detected all {killed} component changes in isolation"
1561        ));
1562    }
1563    lines.extend(witness.guidance.iter().map(|s| clean(s)));
1564    lines.push(format!("add a test with `{assertion}`"));
1565    lines
1566}
1567
1568fn finding_parts(finding: &Finding) -> (&'static str, &Location) {
1569    match finding {
1570        Finding::InputGap { at, .. } => ("INPUT GAP", at),
1571        Finding::AssertionGap { at, .. } => ("ASSERTION GAP", at),
1572        Finding::Survivor {
1573            at,
1574            change_since: Some(_),
1575            ..
1576        } => ("UNTESTED CHANGE", at),
1577        Finding::Survivor { at, .. } => ("SURVIVOR", at),
1578    }
1579}
1580
1581/// Strips 7-bit and 8-bit ANSI/VT terminal escape sequences (CSI, OSC, DCS, SOS, PM, APC,
1582/// and nF/Fp/Fe ESC sequences), C0/C1/DEL control characters, and Unicode bidirectional
1583/// override/isolate controls from untrusted project text before writing to a terminal.
1584/// When `preserve_newlines` is false, `\n`, `\r`, and `\t` are collapsed to spaces so
1585/// untrusted fields cannot forge new lines in text reports.
1586fn sanitize_terminal_text(text: &str, preserve_newlines: bool) -> String {
1587    fn consume_csi(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) {
1588        while let Some(&next) = chars.peek() {
1589            if (' '..='?').contains(&next) {
1590                chars.next();
1591            } else if ('@'..='~').contains(&next) {
1592                chars.next();
1593                break;
1594            } else {
1595                // Incomplete/malformed CSI: stop before consuming unrelated text or newlines.
1596                break;
1597            }
1598        }
1599    }
1600    fn consume_st_terminated(
1601        chars: &mut std::iter::Peekable<std::str::Chars<'_>>,
1602        allow_bel: bool,
1603    ) {
1604        while let Some(next) = chars.next() {
1605            if (allow_bel && next == '\x07') || next == '\u{009c}' {
1606                break;
1607            }
1608            if next == '\x1b' && chars.peek() == Some(&'\\') {
1609                chars.next();
1610                break;
1611            }
1612        }
1613    }
1614    let mut out = String::with_capacity(text.len());
1615    let mut chars = text.chars().peekable();
1616    while let Some(ch) = chars.next() {
1617        if ch == '\x1b' {
1618            match chars.peek().copied() {
1619                // 7-bit CSI: ESC [ <param/interm 0x20-0x3F>* <final 0x40-0x7E>
1620                Some('[') => {
1621                    chars.next();
1622                    consume_csi(&mut chars);
1623                }
1624                // 7-bit OSC: ESC ] ... (BEL | ESC \ | C1 ST)
1625                Some(']') => {
1626                    chars.next();
1627                    consume_st_terminated(&mut chars, true);
1628                }
1629                // 7-bit DCS / SOS / PM / APC: ESC (P | X | ^ | _) ... (ESC \ | C1 ST)
1630                Some('P' | 'X' | '^' | '_') => {
1631                    chars.next();
1632                    consume_st_terminated(&mut chars, false);
1633                }
1634                // nF sequences (e.g., ESC ( B charset designation): 0x20-0x2F intermediates + 0x30-0x7E final.
1635                Some(next) if (' '..='/').contains(&next) => {
1636                    while let Some(&c) = chars.peek() {
1637                        if (' '..='/').contains(&c) {
1638                            chars.next();
1639                        } else if ('0'..='~').contains(&c) {
1640                            chars.next();
1641                            break;
1642                        } else {
1643                            break;
1644                        }
1645                    }
1646                }
1647                // Single-final ESC sequence (e.g., ESC c, ESC 7, ESC =).
1648                Some(next) if ('0'..='~').contains(&next) => {
1649                    chars.next();
1650                }
1651                _ => {}
1652            }
1653            continue;
1654        }
1655        // 8-bit C1 CSI (\u{009B}), OSC (\u{009D}), DCS (\u{0090}), SOS (\u{0098}), PM (\u{009E}), APC (\u{009F}).
1656        if ch == '\u{009b}' {
1657            consume_csi(&mut chars);
1658            continue;
1659        }
1660        if ch == '\u{009d}' {
1661            consume_st_terminated(&mut chars, true);
1662            continue;
1663        }
1664        if matches!(ch, '\u{0090}' | '\u{0098}' | '\u{009e}' | '\u{009f}') {
1665            consume_st_terminated(&mut chars, false);
1666            continue;
1667        }
1668        // Unicode BiDi override/isolate controls (Trojan Source / terminal spoofing).
1669        if matches!(
1670            ch,
1671            '\u{061c}'
1672                | '\u{200e}'
1673                | '\u{200f}'
1674                | '\u{202a}'..='\u{202e}'
1675                | '\u{2066}'..='\u{2069}'
1676        ) {
1677            continue;
1678        }
1679        if ch == '\n' && preserve_newlines {
1680            out.push('\n');
1681            continue;
1682        }
1683        if matches!(ch, '\n' | '\r' | '\t') {
1684            out.push(' ');
1685            continue;
1686        }
1687        if ch.is_control() {
1688            continue;
1689        }
1690        out.push(ch);
1691    }
1692    out
1693}
1694
1695/// Sanitizes an untrusted single-line string for terminal output (no escape sequences, no
1696/// control characters, no injected line breaks).
1697#[doc(hidden)]
1698pub fn sanitize_inline(text: &str) -> String {
1699    sanitize_terminal_text(text, false)
1700}
1701
1702/// Sanitizes multi-line terminal output while preserving intentional `\n` line breaks.
1703#[doc(hidden)]
1704pub fn sanitize_terminal(text: &str) -> String {
1705    sanitize_terminal_text(text, true)
1706}
1707
1708pub fn render_text(report: &Report, show_unreached: bool) -> String {
1709    let mut out = String::new();
1710    let mut previous: Option<(&str, usize)> = None;
1711    for finding in &report.findings {
1712        let (kind, at) = finding_parts(finding);
1713        // Findings on one line are usually one thought (a chain of conditions): they are
1714        // printed as one block.
1715        let same_line = previous == Some((at.file.as_str(), at.line));
1716        if same_line {
1717            out.push_str(&format!(
1718                "  + {kind}  column {}\n    {}\n",
1719                at.column,
1720                sanitize_inline(&at.code)
1721            ));
1722        } else {
1723            if previous.is_some() {
1724                out.push('\n');
1725            }
1726            out.push_str(&format!(
1727                "{kind}  {}:{}:{}\n    {}\n",
1728                sanitize_inline(&at.file),
1729                at.line,
1730                at.column,
1731                sanitize_inline(&at.code)
1732            ));
1733        }
1734        for line in finding_body(finding, true) {
1735            out.push_str(&format!("  {line}\n"));
1736        }
1737        if report.weakened.iter().any(|before| {
1738            (before.file.as_str(), before.line, before.column)
1739                == (at.file.as_str(), at.line, at.column)
1740        }) {
1741            out.push_str(&format!(
1742                "  the tests as they were at {} found this out: a change to the tests lets it through\n",
1743                sanitize_inline(short_revision(
1744                    report.analysis.since.as_deref().unwrap_or("the revision")
1745                ))
1746            ));
1747        }
1748        previous = Some((at.file.as_str(), at.line));
1749    }
1750    if previous.is_some() {
1751        out.push('\n');
1752    }
1753    if show_unreached {
1754        for at in &report.unreached {
1755            out.push_str(&format!(
1756                "UNREACHED  {}:{}:{}\n    {}\n\n",
1757                sanitize_inline(&at.file),
1758                at.line,
1759                at.column,
1760                sanitize_inline(&at.code)
1761            ));
1762        }
1763    }
1764    for at in &report.unstable {
1765        out.push_str(&format!(
1766            "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",
1767            sanitize_inline(&at.file),
1768            at.line,
1769            at.column,
1770            sanitize_inline(&at.code)
1771        ));
1772    }
1773    let input = report
1774        .findings
1775        .iter()
1776        .filter(|f| matches!(f, Finding::InputGap { .. }))
1777        .count();
1778    let assertion = report
1779        .findings
1780        .iter()
1781        .filter(|f| matches!(f, Finding::AssertionGap { .. }))
1782        .count();
1783    let unexplained = report.findings.len() - input - assertion;
1784    // A mutant stopped by the time limit costs the limit: worth knowing when a run is slow.
1785    let by_time_limit = if report.mutants_timed_out > 0 {
1786        format!(", {} of them by the time limit", report.mutants_timed_out)
1787    } else {
1788        String::new()
1789    };
1790    out.push_str(&format!(
1791        "{}: {} sites, {} input gaps, {} assertion gaps, {} mutants run ({} killed{by_time_limit}), {} sites unreached",
1792        sanitize_inline(&report.package),
1793        report.sites,
1794        input,
1795        assertion,
1796        report.mutants_run,
1797        report.mutants_killed,
1798        report.unreached.len()
1799    ));
1800    if unexplained > 0 {
1801        out.push_str(&format!(
1802            ", {unexplained} survivors of mutants built on their own"
1803        ));
1804    }
1805    if !report.timeout_rechecks.is_empty() {
1806        let rechecks = &report.timeout_rechecks;
1807        out.push_str(&format!(
1808            ", {} parallel timeouts ({} confirmed, {} recovered, {} unconfirmed)",
1809            rechecks.first_pass, rechecks.confirmed, rechecks.recovered, rechecks.unconfirmed
1810        ));
1811    }
1812    if report.suppressed > 0 {
1813        out.push_str(&format!(", {} findings suppressed", report.suppressed));
1814    }
1815    if report.skipped_sites > 0 {
1816        out.push_str(&format!(
1817            ", {} sites skipped (probe did not compile)",
1818            report.skipped_sites
1819        ));
1820    }
1821    if report.unviable_mutants > 0 {
1822        out.push_str(&format!(
1823            ", {} mutants left out (they do not compile)",
1824            report.unviable_mutants
1825        ));
1826    }
1827    out.push('\n');
1828    if let Some(audit) = &report.audit {
1829        out.push_str(&format!(
1830            "audit: {} of {} surviving mutants run against all tests, {} failed one they had not been run against",
1831            audit.sampled,
1832            audit.survivors,
1833            audit.disagreements.len()
1834        ));
1835        if audit.not_audited > 0 {
1836            out.push_str(&format!(", {} could not be judged", audit.not_audited));
1837        }
1838        out.push('\n');
1839        for at in &audit.disagreements {
1840            out.push_str(&format!(
1841                "  {}:{}:{}  {}\n",
1842                sanitize_inline(&at.file),
1843                at.line,
1844                at.column,
1845                sanitize_inline(&at.code)
1846            ));
1847        }
1848        if audit.rebuilt > 0 {
1849            out.push_str(&format!(
1850                "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",
1851                audit.rebuilt,
1852                audit.compared,
1853                audit.source_disagreements.len(),
1854                audit.not_compared
1855            ));
1856        }
1857        for differs in &audit.source_disagreements {
1858            out.push_str(&format!(
1859                "  {}:{}:{}  {}: {} as a probe, {} built\n",
1860                sanitize_inline(&differs.at.file),
1861                differs.at.line,
1862                differs.at.column,
1863                sanitize_inline(&differs.mutant),
1864                sanitize_inline(&differs.as_probe),
1865                sanitize_inline(&differs.built)
1866            ));
1867        }
1868        if audit.trace_differences.is_empty() {
1869            out.push_str("audit: recorded once more, the tests did the same\n");
1870        }
1871        for binary in &audit.trace_differences {
1872            let name = sanitize_inline(&binary.binary);
1873            if binary.rerun_failed && binary.records == 0 {
1874                out.push_str(&format!(
1875                    "audit: recorded once more, `{name}` did not pass: its tests do not always do the same\n"
1876                ));
1877            } else if binary.rerun_failed {
1878                out.push_str(&format!(
1879                    "audit: recorded once more, `{name}` did not pass and differs in {} records: its tests do not always do the same\n",
1880                    binary.records
1881                ));
1882            } else {
1883                out.push_str(&format!(
1884                    "audit: recorded once more, `{name}` differs in {} records: its tests do not always do the same\n",
1885                    binary.records
1886                ));
1887            }
1888        }
1889    }
1890    if report.mutants_not_compiled > 0 {
1891        out.push_str(&format!(
1892            "({} 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",
1893            report.mutants_not_compiled
1894        ));
1895    }
1896    let not_evaluated = report
1897        .mutants_not_evaluated
1898        .saturating_sub(report.mutants_not_compiled);
1899    if not_evaluated > 0 {
1900        out.push_str(&format!(
1901            "({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"
1902        ));
1903    }
1904    if report.mutants_not_built > 0 {
1905        out.push_str(&format!(
1906            "({} more mutants need a build of their own: --rebuild runs them)\n",
1907            report.mutants_not_built
1908        ));
1909    }
1910    if !report.skipped.is_empty() {
1911        out.push_str(&format!(
1912            "({} skipped entries with locations and reasons in --json)\n",
1913            report.skipped.len()
1914        ));
1915    }
1916    if report.evaluation == Some(Evaluation::NoMutantsExecuted) {
1917        out.push_str("No mutants executed. See any skipped entries in --json. For a subprocess that clears the probe environment, try --source-only.\n");
1918    }
1919    if !show_unreached && !report.unreached.is_empty() {
1920        out.push_str("(--show-unreached lists the code no test executes)\n");
1921    }
1922    sanitize_terminal(&out)
1923}
1924
1925#[cfg(test)]
1926mod tests {
1927    use super::*;
1928    use crate::instrument::discover;
1929
1930    #[test]
1931    fn evaluation_distinguishes_no_sites_no_mutants_and_completed_work() {
1932        let mut report = Report::default();
1933        report.record_evaluation();
1934        assert_eq!(report.evaluation, Some(Evaluation::NoSites));
1935        report.sites = 1;
1936        report.record_evaluation();
1937        assert_eq!(report.evaluation, Some(Evaluation::NoMutantsExecuted));
1938        assert!(render_text(&report, false).contains("No mutants executed."));
1939        report.mutants_run = 1;
1940        report.record_evaluation();
1941        assert_eq!(report.evaluation, None);
1942        assert!(!render_text(&report, false).contains("No mutants executed."));
1943    }
1944
1945    fn results_of(sarif: &serde_json::Value) -> &Vec<serde_json::Value> {
1946        sarif["runs"][0]["results"].as_array().unwrap()
1947    }
1948
1949    fn or_site() -> Site {
1950        site_of("fn f(a: bool, b: bool) -> bool { a || b }")
1951    }
1952
1953    fn assign_kind() -> SiteKind {
1954        SiteKind::Arith {
1955            op: ArithOp::Add,
1956            assign: true,
1957            lhs: "*total".into(),
1958            rhs: "fee".into(),
1959            gap: (0, 0),
1960        }
1961    }
1962
1963    fn site_of(src: &str) -> Site {
1964        discover(src, 0)
1965            .unwrap()
1966            .sites
1967            .into_iter()
1968            .find(|s| !matches!(s.kind, SiteKind::Return { .. } | SiteKind::Body { .. }))
1969            .unwrap()
1970    }
1971
1972    #[test]
1973    fn describes_mutants_at_source_level() {
1974        let rhs = site_of("fn f(age: u32) -> bool { age >= 18 }");
1975        assert_eq!(describe(&rhs, Mutation::Shift(1)), "`age >= 19`");
1976        assert_eq!(describe(&rhs, Mutation::Shift(-2)), "`age >= 16`");
1977        assert_eq!(describe(&rhs, Mutation::Negate), "`!(age >= 18)`");
1978        assert_eq!(describe(&rhs, Mutation::Const(false)), "`false`");
1979        assert_eq!(describe(&rhs, Mutation::Op(CmpOp::Gt)), "`age > 18`");
1980
1981        // 18 <= age shifted by +1 is 18 <= age + 1, i.e. 17 <= age.
1982        let lhs = site_of("fn f(age: i32) -> bool { 18 <= age }");
1983        assert_eq!(describe(&lhs, Mutation::Shift(1)), "`17 <= age`");
1984
1985        let none = site_of("fn f(a: u32, b: u32) -> bool { a >= b }");
1986        assert_eq!(describe(&none, Mutation::Shift(1)), "`a > b`");
1987        assert_eq!(
1988            describe(&none, Mutation::Shift(2)),
1989            "`a >= b + 2` (without overflow)"
1990        );
1991        assert_eq!(
1992            describe(&none, Mutation::Shift(-1)),
1993            "`a >= b - 1` (without overflow)"
1994        );
1995        let lt = site_of("fn f(a: u32, b: u32) -> bool { a < b }");
1996        assert_eq!(describe(&lt, Mutation::Shift(1)), "`a <= b`");
1997
1998        let stmt = site_of("fn f(s: &mut S) { s.check(\n  1,\n  2); }");
1999        assert_eq!(
2000            describe(&stmt, Mutation::Delete),
2001            "delete `s.check( 1, 2);`"
2002        );
2003    }
2004
2005    /// The source-level form must mean the same as the planner's `Shift`.
2006    #[test]
2007    fn literal_shift_rendering_matches_shift_semantics() {
2008        use crate::plan::eval_mutated_d;
2009        for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
2010            for shift in [-2, -1, 1, 2] {
2011                for other in -5..=5i128 {
2012                    let k = 1i128;
2013                    // literal on the right: `x op k+shift`
2014                    assert_eq!(
2015                        op.eval_d(other - (k + shift)),
2016                        eval_mutated_d(op, Mutation::Shift(shift), other - k)
2017                    );
2018                    // literal on the left: `k-shift op x`
2019                    assert_eq!(
2020                        op.eval_d((k - shift) - other),
2021                        eval_mutated_d(op, Mutation::Shift(shift), k - other)
2022                    );
2023                }
2024            }
2025        }
2026        // And the operator flips used when neither side is a literal.
2027        for (op, shift, flipped) in [
2028            (CmpOp::Ge, 1, CmpOp::Gt),
2029            (CmpOp::Gt, -1, CmpOp::Ge),
2030            (CmpOp::Le, -1, CmpOp::Lt),
2031            (CmpOp::Lt, 1, CmpOp::Le),
2032        ] {
2033            for d in -3..=3 {
2034                assert_eq!(
2035                    flipped.eval_d(d),
2036                    eval_mutated_d(op, Mutation::Shift(shift), d)
2037                );
2038            }
2039        }
2040    }
2041
2042    #[test]
2043    fn boundary_finding_for_the_age_check() {
2044        let site = site_of("fn f(age: u32) -> bool { age >= 18 }");
2045        let mut obs = Obs::of_d(-1);
2046        obs.merge(&Obs::of_d(2));
2047        let gap = InputGap::Boundary {
2048            min_shift: 0,
2049            max_shift: 2,
2050            missing: vec![0],
2051            same: (0, 0),
2052        };
2053        let finding = input_gap_finding("src/lib.rs", &site, &gap, &obs, true).unwrap();
2054        assert_eq!(
2055            finding,
2056            Finding::InputGap {
2057                at: Location {
2058                    file: "src/lib.rs".into(),
2059                    line: 1,
2060                    column: 26,
2061                    code: "age >= 18".into(),
2062                    ..Location::default()
2063                },
2064                survivors: vec!["`age >= 19`".into(), "`age >= 20`".into()],
2065                survivor_count: 2,
2066                add_tests: vec!["`age` = 18 (the original gives true)".into()],
2067                observed: Some("nearest values the tests passed: `age` = 17, 20".into()),
2068                verified: true,
2069            }
2070        );
2071        let report = Report {
2072            package: "p".into(),
2073            sites: 1,
2074            findings: vec![finding],
2075            ..Report::default()
2076        };
2077        let text = render_text(&report, false);
2078        assert!(text.contains("INPUT GAP  src/lib.rs:1:26"), "{text}");
2079        assert!(
2080            text.contains("passes every test as: `age >= 19`, `age >= 20`  [re-run: tests pass]"),
2081            "{text}"
2082        );
2083        assert!(
2084            text.contains("add a test with `age` = 18 (the original gives true)"),
2085            "{text}"
2086        );
2087        assert!(
2088            text.contains("p: 1 sites, 1 input gaps, 0 assertion gaps"),
2089            "{text}"
2090        );
2091        assert!(report.has_gaps());
2092    }
2093
2094    #[test]
2095    fn other_gap_kinds() {
2096        let site = site_of("fn f(a: f64, b: f64) -> bool { a < b }");
2097        let mut obs = Obs::of_rel(crate::plan::Rel::Less);
2098        obs.merge(&Obs::of_rel(crate::plan::Rel::Greater));
2099        let gap = InputGap::EqualNeverObserved {
2100            flipped: CmpOp::Le,
2101            float_gap: None,
2102        };
2103        let Some(Finding::InputGap {
2104            survivors,
2105            add_tests,
2106            observed,
2107            ..
2108        }) = input_gap_finding("f.rs", &site, &gap, &obs, false)
2109        else {
2110            panic!()
2111        };
2112        assert_eq!(survivors, ["`a <= b`"]);
2113        assert_eq!(
2114            add_tests,
2115            ["`a` equal to `b` (the original gives false, the mutant true)"]
2116        );
2117        assert_eq!(observed, None);
2118
2119        let Some(Finding::InputGap {
2120            survivors,
2121            add_tests,
2122            ..
2123        }) = input_gap_finding(
2124            "f.rs",
2125            &site,
2126            &InputGap::OneSided { always: true },
2127            &obs,
2128            false,
2129        )
2130        else {
2131            panic!()
2132        };
2133        assert_eq!(survivors, ["`true`"]);
2134        assert_eq!(add_tests, ["an input that makes `a < b` false"]);
2135
2136        assert_eq!(
2137            input_gap_finding("f.rs", &site, &InputGap::Unreached, &obs, false),
2138            None
2139        );
2140    }
2141
2142    #[test]
2143    fn float_gap_finding() {
2144        let site = site_of("fn f(celsius: f64) -> bool { celsius > 30.5 }");
2145        let mut obs = Obs::of_f(-20.5);
2146        obs.merge(&Obs::of_f(9.5));
2147        let gap = InputGap::EqualNeverObserved {
2148            flipped: CmpOp::Ge,
2149            float_gap: obs.float_gap(),
2150        };
2151        let Some(Finding::InputGap {
2152            survivors,
2153            add_tests,
2154            observed,
2155            survivor_count,
2156            ..
2157        }) = input_gap_finding("f.rs", &site, &gap, &obs, true)
2158        else {
2159            panic!()
2160        };
2161        assert_eq!(
2162            survivors,
2163            [
2164                "`celsius >= 30.5`",
2165                "`celsius > 35.25`",
2166                "`celsius > 20.25`"
2167            ]
2168        );
2169        assert_eq!(survivor_count, 3);
2170        assert_eq!(
2171            add_tests,
2172            ["`celsius` equal to `30.5` (the original gives false, the mutant true)"]
2173        );
2174        assert_eq!(
2175            observed.as_deref(),
2176            Some(
2177                "nearest values the tests passed: `celsius` = 10.0, 40.0; any threshold between them passes"
2178            )
2179        );
2180
2181        let lhs = site_of("fn f(x: f32) -> bool { 1.5_f32 <= x }");
2182        assert_eq!(describe(&lhs, Mutation::ShiftF(0.25)), "`1.25 <= x`");
2183        let none = site_of("fn f(x: f64, y: f64) -> bool { x < y }");
2184        assert_eq!(describe(&none, Mutation::ShiftF(0.5)), "`x < y + 0.5`");
2185        assert_eq!(describe(&none, Mutation::ShiftF(-0.5)), "`x < y - 0.5`");
2186        let finding = input_gap_finding(
2187            "f.rs",
2188            &none,
2189            &InputGap::EqualNeverObserved {
2190                flipped: CmpOp::Le,
2191                float_gap: Some((-1.0, 2.0)),
2192            },
2193            &obs,
2194            false,
2195        );
2196        let Some(Finding::InputGap { observed, .. }) = finding else {
2197            panic!()
2198        };
2199        assert_eq!(
2200            observed.as_deref(),
2201            Some("nearest values the tests passed: `x` - `y` = -1.0, 2.0")
2202        );
2203
2204        assert_eq!(float_literal("30.5"), Some(30.5));
2205        assert_eq!(float_literal("-1e3"), Some(-1000.0));
2206        assert_eq!(float_literal("1_000.5f64"), Some(1000.5));
2207        assert_eq!(float_literal("limit"), None);
2208        assert_eq!(float_literal("x1"), None);
2209        assert_eq!(float_literal("1x"), None);
2210        assert_eq!(float_literal("-x"), None);
2211        assert_eq!(float_literal("-2.5"), Some(-2.5));
2212        assert_eq!(float_literal("e"), None);
2213        // Nothing is rounded away: a tiny shift stays visible.
2214        assert_eq!(show_float(0.1 + 0.2), "0.30000000000000004");
2215        assert_eq!(show_float(1e-10), "1e-10");
2216        assert_eq!(show_float(10.0), "10.0");
2217        assert_eq!(show_float(35.25), "35.25");
2218        // A shift that does not change the literal is not listed as a mutant.
2219        let big = site_of("fn f(x: f64) -> bool { x > 1e300 }");
2220        let tiny = InputGap::EqualNeverObserved {
2221            flipped: CmpOp::Ge,
2222            float_gap: Some((-2e-300, 2e-300)),
2223        };
2224        let Some(Finding::InputGap { survivors, .. }) =
2225            input_gap_finding("f.rs", &big, &tiny, &obs, true)
2226        else {
2227            panic!()
2228        };
2229        assert_eq!(survivors, ["`x >= 1e300`"]);
2230    }
2231
2232    #[test]
2233    fn logic_and_arithmetic_findings() {
2234        let and = site_of("fn f(a: bool, b: bool) -> bool { a && b }");
2235        assert_eq!(describe(&and, Mutation::LogicSwap), "`a || b`");
2236        assert_eq!(describe(&and, Mutation::LogicDropRhs), "`a && { b; true }`");
2237        assert_eq!(
2238            describe(&or_site(), Mutation::LogicDropRhs),
2239            "`a || { b; false }`"
2240        );
2241        assert_eq!(describe(&and, Mutation::LogicDropLhs), "`{ a; b }`");
2242        let or = site_of("fn f(a: bool, b: bool) -> bool { a || b }");
2243        assert_eq!(describe(&or, Mutation::LogicSwap), "`a && b`");
2244        let advice = |site: &Site, gap| match logic_gap_finding("f.rs", site, gap, true) {
2245            Some(Finding::InputGap {
2246                survivors,
2247                add_tests,
2248                ..
2249            }) => (survivors[0].clone(), add_tests[0].clone()),
2250            _ => panic!(),
2251        };
2252        assert_eq!(
2253            advice(&and, LogicGap::RhsNeverDecides),
2254            (
2255                "`a && { b; true }`".into(),
2256                "a case where `a` is true and `b` is false".into()
2257            )
2258        );
2259        assert_eq!(
2260            advice(&and, LogicGap::LhsNeverDecides),
2261            ("`{ a; b }`".into(), "a case where `a` is false".into())
2262        );
2263        assert_eq!(
2264            advice(&or, LogicGap::RhsNeverDecides),
2265            (
2266                "`a || { b; false }`".into(),
2267                "a case where `a` is false and `b` is true".into()
2268            )
2269        );
2270        assert_eq!(
2271            advice(&or, LogicGap::LhsNeverDecides),
2272            ("`{ a; b }`".into(), "a case where `a` is true".into())
2273        );
2274        assert_eq!(
2275            logic_gap_finding("f.rs", &and, LogicGap::Unreached, true),
2276            None
2277        );
2278        assert_eq!(
2279            arith_gap_finding("f.rs", &and, Mutation::ArithSwap, true),
2280            None
2281        );
2282
2283        let add = site_of("fn f(total: u32, fee: u32) -> u32 { total + fee }");
2284        assert_eq!(describe(&add, Mutation::ArithSwap), "`total - fee`");
2285        let Some(Finding::InputGap {
2286            survivors,
2287            add_tests,
2288            ..
2289        }) = arith_gap_finding("f.rs", &add, Mutation::ArithSwap, true)
2290        else {
2291            panic!()
2292        };
2293        assert_eq!(
2294            (survivors[0].as_str(), add_tests[0].as_str()),
2295            ("`total - fee`", "`fee` other than 0")
2296        );
2297        let mul = site_of("fn f(n: u32, scale: u32) -> u32 { n * scale }");
2298        let Some(Finding::InputGap {
2299            survivors,
2300            add_tests,
2301            ..
2302        }) = arith_gap_finding("f.rs", &mul, Mutation::ArithSwap, true)
2303        else {
2304            panic!()
2305        };
2306        assert_eq!(survivors[0], "`n / scale`");
2307        assert_eq!(
2308            add_tests[0],
2309            "operands for which `n * scale` and `n / scale` differ"
2310        );
2311        let assign = Site {
2312            kind: assign_kind(),
2313            ..add.clone()
2314        };
2315        assert_eq!(describe(&assign, Mutation::ArithSwap), "`*total -= fee`");
2316        let Some(Finding::InputGap { add_tests, .. }) =
2317            arith_gap_finding("f.rs", &assign, Mutation::ArithSwap, true)
2318        else {
2319            panic!()
2320        };
2321        assert_eq!(add_tests[0], "`fee` other than 0");
2322        let shift = Site {
2323            kind: SiteKind::Arith {
2324                op: ArithOp::Shl,
2325                assign: true,
2326                lhs: "bits".into(),
2327                rhs: "n".into(),
2328                gap: (0, 0),
2329            },
2330            ..assign.clone()
2331        };
2332        assert_eq!(describe(&shift, Mutation::ArithSwap), "`bits >>= n`");
2333        let Some(Finding::InputGap { add_tests, .. }) =
2334            arith_gap_finding("f.rs", &shift, Mutation::ArithSwap, true)
2335        else {
2336            panic!()
2337        };
2338        assert_eq!(
2339            add_tests[0],
2340            "operands for which `bits <<= n` and `bits >>= n` differ"
2341        );
2342
2343        let not = Site {
2344            kind: SiteKind::Not {
2345                bang: (0, 1),
2346                operand: "is_ready(x)".into(),
2347                needs_space: false,
2348            },
2349            ..assign.clone()
2350        };
2351        assert_eq!(describe(&not, Mutation::DropNot), "`is_ready(x)`");
2352        let ret = Site {
2353            kind: SiteKind::Return {
2354                name: "is_ready".into(),
2355                option: None,
2356                sole_expr: None,
2357            },
2358            ..assign.clone()
2359        };
2360        assert_eq!(
2361            describe(&ret, Mutation::Const(true)),
2362            "`is_ready` returning `true`"
2363        );
2364        let Some(Finding::InputGap {
2365            survivors,
2366            add_tests,
2367            ..
2368        }) = return_gap_finding("f.rs", &ret, false, true)
2369        else {
2370            panic!()
2371        };
2372        assert_eq!(survivors[0], "`is_ready` returning `false`");
2373        assert_eq!(add_tests[0], "a case where `is_ready` returns true");
2374        assert_eq!(return_gap_finding("f.rs", &not, false, true), None);
2375
2376        let find = Site {
2377            kind: SiteKind::Return {
2378                name: "find".into(),
2379                option: Some("Option<&str>".into()),
2380                sole_expr: None,
2381            },
2382            ..assign.clone()
2383        };
2384        assert_eq!(
2385            describe(&find, Mutation::Const(false)),
2386            "`find` returning `None`"
2387        );
2388        let Some(Finding::InputGap { add_tests, .. }) =
2389            return_gap_finding("f.rs", &find, false, true)
2390        else {
2391            panic!()
2392        };
2393        assert_eq!(add_tests[0], "a case where `find` returns `Some`");
2394        let range = Site {
2395            kind: SiteKind::Range {
2396                inclusive: false,
2397                lhs: "0".into(),
2398                rhs: "n".into(),
2399                gap: (0, 0),
2400            },
2401            ..assign.clone()
2402        };
2403        assert_eq!(describe(&range, Mutation::RangeEnd), "`0..=n`");
2404        let closed = Site {
2405            kind: SiteKind::Range {
2406                inclusive: true,
2407                lhs: "1".into(),
2408                rhs: "n".into(),
2409                gap: (0, 0),
2410            },
2411            ..assign.clone()
2412        };
2413        assert_eq!(describe(&closed, Mutation::RangeEnd), "`1..n`");
2414        let arm = Site {
2415            kind: SiteKind::Arm {
2416                pattern: "Kind::Update { key, .. }".into(),
2417                guard: crate::instrument::ArmGuard::None(0),
2418                removal: (0, 0),
2419            },
2420            ..assign.clone()
2421        };
2422        assert_eq!(
2423            describe(&arm, Mutation::Delete),
2424            "remove the arm `Kind::Update { key, .. } => ..`"
2425        );
2426
2427        let clamp = Site {
2428            kind: SiteKind::MinMax {
2429                max: true,
2430                receiver: "drift".into(),
2431                argument: "peak.get()".into(),
2432                call: (0, 0),
2433                close: (0, 0),
2434            },
2435            ..assign.clone()
2436        };
2437        assert_eq!(
2438            describe(&clamp, Mutation::MinMax),
2439            "`drift.min(peak.get())`"
2440        );
2441        let Some(Finding::InputGap { add_tests, .. }) = min_max_gap_finding("f.rs", &clamp, true)
2442        else {
2443            panic!()
2444        };
2445        assert_eq!(add_tests[0], "`drift` different from `peak.get()`");
2446        assert_eq!(min_max_gap_finding("f.rs", &assign, true), None);
2447
2448        let end = Site {
2449            kind: SiteKind::SliceEnd {
2450                first: false,
2451                receiver: "self.items".into(),
2452                call: (0, 0),
2453                method: (0, 0),
2454            },
2455            ..assign.clone()
2456        };
2457        assert_eq!(describe(&end, Mutation::OtherEnd), "`self.items.first()`");
2458        let Some(Finding::InputGap { add_tests, .. }) = slice_end_gap_finding("f.rs", &end, true)
2459        else {
2460            panic!()
2461        };
2462        assert_eq!(
2463            add_tests[0],
2464            "`self.items` with two or more elements, the first different from the last"
2465        );
2466        assert_eq!(slice_end_gap_finding("f.rs", &clamp, true), None);
2467
2468        let rem = site_of("fn f(n: u32, k: u32) -> u32 { n % k }");
2469        assert_eq!(describe(&rem, Mutation::ArithSwap), "`n / k`");
2470        assert_eq!(
2471            logic_gap_finding("f.rs", &add, LogicGap::RhsNeverDecides, true),
2472            None
2473        );
2474    }
2475
2476    #[test]
2477    fn workspace_sarif_matches_the_individual_runs() {
2478        use serde_json::{Value, json};
2479
2480        let report = Report {
2481            package: "zebra".into(),
2482            analysis: Analysis {
2483                package_path: "crates/zebra/".into(),
2484                ..Analysis::default()
2485            },
2486            findings: vec![Finding::Survivor {
2487                at: Location {
2488                    file: r#"src/"é".rs"#.into(),
2489                    line: 4,
2490                    column: 1,
2491                    id: "zebra|4".into(),
2492                    ..Location::default()
2493                },
2494                survivors: vec!["delete".into()],
2495                witness: None,
2496                change_since: None,
2497                advice: None,
2498            }],
2499            ..Report::default()
2500        };
2501        let empty = Report {
2502            package: "ant".into(),
2503            ..Report::default()
2504        };
2505        for reports in [
2506            &[][..],
2507            std::slice::from_ref(&report),
2508            &[report.clone(), empty],
2509        ] {
2510            let runs: Vec<_> = reports
2511                .iter()
2512                .map(|report| {
2513                    let mut single: Value = serde_json::from_str(&render_sarif(report)).unwrap();
2514                    let mut run = single["runs"][0].take();
2515                    assert!(run["properties"].get("package").is_none());
2516                    run["properties"]["package"] = json!(report.package);
2517                    // What a run of a workspace has beside that of a package alone.
2518                    run["automationDetails"] = json!({ "id": format!("tmt/{}/", report.package) });
2519                    run["invocations"] = json!([{ "executionSuccessful": true }]);
2520                    run
2521                })
2522                .collect();
2523            let old = json!({
2524                "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
2525                "version": "2.1.0",
2526                "runs": runs,
2527            });
2528            let workspace: Value =
2529                serde_json::from_str(&format!("{:#}", workspace_sarif(reports, &[]))).unwrap();
2530            assert_eq!(workspace, old);
2531        }
2532    }
2533
2534    #[test]
2535    fn a_package_that_could_not_be_analysed_is_a_run_that_says_so() {
2536        use serde_json::Value;
2537
2538        let analysed = Report {
2539            package: "ant".into(),
2540            ..Report::default()
2541        };
2542        let failed = [(
2543            "bee".to_string(),
2544            "the tests of `bee` fail: \"quoted\"\n".to_string(),
2545        )];
2546        let document: Value = serde_json::from_str(&format!(
2547            "{:#}",
2548            workspace_sarif(std::slice::from_ref(&analysed), &failed)
2549        ))
2550        .unwrap();
2551        let runs = document["runs"].as_array().unwrap();
2552        assert_eq!(runs.len(), 2);
2553        // Each run is told from the others, and the one that failed is not a clean one.
2554        assert_eq!(runs[0]["automationDetails"]["id"], "tmt/ant/");
2555        assert_eq!(runs[0]["invocations"][0]["executionSuccessful"], true);
2556        assert_eq!(runs[1]["automationDetails"]["id"], "tmt/bee/");
2557        assert_eq!(runs[1]["invocations"][0]["executionSuccessful"], false);
2558        assert_eq!(
2559            runs[1]["invocations"][0]["toolExecutionNotifications"][0]["message"]["text"],
2560            failed[0].1
2561        );
2562        assert_eq!(runs[1]["results"].as_array().unwrap().len(), 0);
2563        assert_eq!(runs[1]["tool"], runs[0]["tool"]);
2564        assert_eq!(runs[1]["properties"]["package"], "bee");
2565        // Only failures: still a document, with nothing passed off as analysed.
2566        let document: Value =
2567            serde_json::from_str(&format!("{:#}", workspace_sarif(&[], &failed))).unwrap();
2568        assert_eq!(document["runs"].as_array().unwrap().len(), 1);
2569    }
2570
2571    #[test]
2572    fn a_path_is_written_as_a_uri() {
2573        assert_eq!(sarif_uri("", "src/lib.rs"), "src/lib.rs");
2574        assert_eq!(
2575            sarif_uri("crates/a-b_c/", "src/x~1.rs"),
2576            "crates/a-b_c/src/x~1.rs"
2577        );
2578        // What a URI gives a meaning of its own, or does not allow, is written as bytes.
2579        assert_eq!(
2580            sarif_uri("my crate/", "a#b%c?.rs"),
2581            "my%20crate/a%23b%25c%3F.rs"
2582        );
2583        assert_eq!(sarif_uri("", "src/é.rs"), "src/%C3%A9.rs");
2584        assert_eq!(sarif_uri("", r#"a\b"c.rs"#), "a%5Cb%22c.rs");
2585        let report = Report {
2586            analysis: Analysis {
2587                package_path: "my crate/".into(),
2588                ..Analysis::default()
2589            },
2590            findings: vec![Finding::Survivor {
2591                at: Location {
2592                    file: "src/a b.rs".into(),
2593                    line: 1,
2594                    column: 1,
2595                    ..Location::default()
2596                },
2597                survivors: vec![],
2598                witness: None,
2599                change_since: None,
2600                advice: None,
2601            }],
2602            ..Report::default()
2603        };
2604        let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
2605        assert_eq!(
2606            sarif["runs"][0]["results"][0]["locations"][0]["physicalLocation"]["artifactLocation"]
2607                ["uri"],
2608            "my%20crate/src/a%20b.rs"
2609        );
2610        assert_eq!(sarif_uri_for("", r#"a\b"c.rs"#, false), "a%5Cb%22c.rs");
2611        assert_eq!(
2612            sarif_uri_for(r"crates\core\", r"src\lib.rs", true),
2613            "crates/core/src/lib.rs"
2614        );
2615    }
2616
2617    #[test]
2618    fn findings_sort_by_path_and_position_in_input_order_for_ties() {
2619        let mut report = Report {
2620            findings: [
2621                ("z.rs", 1, 1, "1"),
2622                ("é.rs", 1, 1, "2"),
2623                ("a.rs", 2, 1, "3"),
2624                ("a.rs", 1, 3, "4"),
2625                ("a.rs", 1, 3, "5"),
2626                ("a.rs", 1, 1, "6"),
2627            ]
2628            .into_iter()
2629            .map(|(file, line, column, id)| Finding::Survivor {
2630                at: Location {
2631                    file: file.into(),
2632                    line,
2633                    column,
2634                    id: id.into(),
2635                    ..Location::default()
2636                },
2637                survivors: vec![],
2638                witness: None,
2639                change_since: None,
2640                advice: None,
2641            })
2642            .collect(),
2643            ..Report::default()
2644        };
2645        report.sort_findings();
2646        let ids: Vec<_> = report
2647            .findings
2648            .iter()
2649            .map(|finding| finding.at().id.as_str())
2650            .collect();
2651        assert_eq!(ids, ["6", "4", "5", "3", "1", "2"]);
2652    }
2653
2654    #[test]
2655    fn collapsed_code_matches_the_previous_format() {
2656        // Pairwise combinations of character set, whitespace and normalized width.
2657        for (charset, spacing, width) in [
2658            ("ascii", "none", 17),
2659            ("ascii", "split", 100),
2660            ("ascii", "surrounded", 101),
2661            ("multibyte", "split", 101),
2662            ("ascii", "none", 4096),
2663            ("multibyte", "none", 97),
2664            ("multibyte", "surrounded", 0),
2665            ("multibyte", "surrounded", 17),
2666            ("multibyte", "surrounded", 4096),
2667            ("ascii", "split", 17),
2668            ("multibyte", "none", 100),
2669            ("multibyte", "none", 101),
2670            ("ascii", "surrounded", 97),
2671            ("ascii", "surrounded", 100),
2672            ("multibyte", "split", 97),
2673            ("ascii", "none", 0),
2674            ("multibyte", "split", 4096),
2675        ] {
2676            let glyph = if charset == "ascii" { "x" } else { "🦀" };
2677            let code = match spacing {
2678                "none" => glyph.repeat(width),
2679                "surrounded" => format!("\t{}\u{2003}\r\n", glyph.repeat(width)),
2680                _ => format!(
2681                    "{}\u{2003}\r\n {}",
2682                    glyph.repeat(width / 2),
2683                    glyph.repeat(width - width / 2 - 1),
2684                ),
2685            };
2686            let normalized = code.split_whitespace().collect::<Vec<_>>().join(" ");
2687            let expected = if normalized.chars().count() > 100 {
2688                format!("{}...", normalized.chars().take(97).collect::<String>())
2689            } else {
2690                normalized
2691            };
2692            assert_eq!(one_line(&code), expected, "{charset} {spacing} {width}");
2693        }
2694
2695        // The last visible character can itself be the space between two words.
2696        let code = format!("{}\n{}", "x".repeat(96), "y".repeat(4096));
2697        assert_eq!(one_line(&code), format!("{} ...", "x".repeat(96)));
2698        let code = format!("{}\n{}", "x".repeat(100), " ".repeat(4096));
2699        assert_eq!(one_line(&code), "x".repeat(100));
2700    }
2701
2702    #[test]
2703    fn long_code_is_shortened() {
2704        let exactly_100 = "x".repeat(100);
2705        assert_eq!(one_line(&exactly_100), exactly_100);
2706        let shortened = one_line(&"x".repeat(101));
2707        assert_eq!(shortened, format!("{}...", "x".repeat(97)));
2708        assert_eq!(one_line("a\n   b"), "a b");
2709    }
2710
2711    #[test]
2712    fn timeout_rechecks_are_in_the_json_only_when_there_were_any() {
2713        let none = serde_json::to_value(Report::default()).unwrap();
2714        assert!(none.get("timeout_rechecks").is_none(), "{none}");
2715        let report = Report {
2716            timeout_rechecks: TimeoutRechecks {
2717                first_pass: 3,
2718                confirmed: 1,
2719                recovered: 2,
2720                unconfirmed: 0,
2721            },
2722            ..Report::default()
2723        };
2724        assert_eq!(
2725            serde_json::to_value(&report).unwrap()["timeout_rechecks"],
2726            serde_json::json!({"first_pass": 3, "confirmed": 1, "recovered": 2, "unconfirmed": 0})
2727        );
2728    }
2729
2730    #[test]
2731    fn at_most_three_survivors_are_listed_nearest_first() {
2732        let site = site_of("fn f(a: i64) -> bool { a >= 10 }");
2733        let obs = Obs::default();
2734        let survivors = |min_shift, max_shift| {
2735            let gap = InputGap::Boundary {
2736                min_shift,
2737                max_shift,
2738                missing: vec![0],
2739                same: (0, 0),
2740            };
2741            match input_gap_finding("f.rs", &site, &gap, &obs, false) {
2742                Some(Finding::InputGap {
2743                    survivors,
2744                    survivor_count,
2745                    ..
2746                }) => (survivors, survivor_count),
2747                _ => panic!(),
2748            }
2749        };
2750        assert_eq!(
2751            survivors(-9, 9),
2752            (
2753                vec!["`a >= 11`".into(), "`a >= 9`".into(), "`a >= 12`".into()],
2754                18
2755            )
2756        );
2757        assert_eq!(survivors(-1, 0), (vec!["`a >= 9`".into()], 1));
2758        assert_eq!(survivors(0, 1), (vec!["`a >= 11`".into()], 1));
2759        assert_eq!(
2760            survivors(-2, 0),
2761            (vec!["`a >= 9`".into(), "`a >= 8`".into()], 2)
2762        );
2763    }
2764
2765    #[test]
2766    fn text_report_is_exact() {
2767        let at = Location {
2768            file: "src/lib.rs".into(),
2769            line: 3,
2770            column: 9,
2771            code: "a >= b".into(),
2772            ..Location::default()
2773        };
2774        let below = Location {
2775            file: "src/lib.rs".into(),
2776            line: 7,
2777            column: 5,
2778            code: "s.reset();".into(),
2779            ..Location::default()
2780        };
2781        let report = Report {
2782            package: "p".into(),
2783            sites: 2,
2784            mutants_run: 1,
2785            suppressed: 2,
2786            findings: vec![
2787                Finding::InputGap {
2788                    at: at.clone(),
2789                    survivors: vec!["`a > b`".into()],
2790                    survivor_count: 4,
2791                    add_tests: vec!["`a` equal to `b` (the original gives true)".into()],
2792                    observed: Some("nearest values the tests passed: `a` - `b` = -1, 4".into()),
2793                    verified: false,
2794                },
2795                Finding::InputGap {
2796                    at: at.clone(),
2797                    survivors: vec!["`true`".into()],
2798                    survivor_count: 1,
2799                    add_tests: vec![],
2800                    observed: None,
2801                    verified: true,
2802                },
2803                Finding::AssertionGap {
2804                    at: Location { column: 4, ..at },
2805                    survivors: vec!["`!(a >= b)`".into()],
2806                    tests: vec!["t".into()],
2807                    effects: vec![],
2808                    effects_of: None,
2809                    witness: None,
2810                },
2811                Finding::AssertionGap {
2812                    at: below,
2813                    survivors: vec!["delete `s.reset();`".into()],
2814                    tests: vec!["t".into()],
2815                    effects: vec![
2816                        "with the mutant, `t` no longer runs `s.count = 0;` (src/lib.rs:12)".into(),
2817                    ],
2818                    effects_of: None,
2819                    witness: None,
2820                },
2821            ],
2822            ..Report::default()
2823        };
2824        // Findings on one line form one block; a new line starts a new block.
2825        assert_eq!(
2826            render_text(&report, false),
2827            "INPUT GAP  src/lib.rs:3:9\n    a >= b\n\
2828             \x20 passes every test as: `a > b` (+3 more)  [from the trace, not re-run]\n\
2829             \x20 nearest values the tests passed: `a` - `b` = -1, 4\n\
2830             \x20 add a test with `a` equal to `b` (the original gives true)\n\
2831             \x20 + INPUT GAP  column 9\n    a >= b\n\
2832             \x20 passes every test as: `true`  [re-run: tests pass]\n\
2833             \x20 + ASSERTION GAP  column 4\n    a >= b\n\
2834             \x20 passes every test as: `!(a >= b)`\n\
2835             \x20 these tests run the changed code and still pass: t\n\
2836             \x20 add an assertion on what this code is responsible for\n\
2837             \n\
2838             ASSERTION GAP  src/lib.rs:7:5\n    s.reset();\n\
2839             \x20 passes every test as: delete `s.reset();`\n\
2840             \x20 these tests run the changed code and still pass: t\n\
2841             \x20 with the mutant, `t` no longer runs `s.count = 0;` (src/lib.rs:12)\n\
2842             \n\
2843             p: 2 sites, 2 input gaps, 2 assertion gaps, 1 mutants run (0 killed), 0 sites unreached, 2 findings suppressed\n"
2844        );
2845        assert_eq!(
2846            render_text(
2847                &Report {
2848                    package: "q".into(),
2849                    ..Report::default()
2850                },
2851                false
2852            ),
2853            "q: 0 sites, 0 input gaps, 0 assertion gaps, 0 mutants run (0 killed), 0 sites unreached\n"
2854        );
2855
2856        let mut in_repository = report.clone();
2857        in_repository.analysis.package_path = "crates/p/".into();
2858        in_repository.analysis.since = Some("abc".into());
2859        if let Finding::AssertionGap { at, .. } = &mut in_repository.findings[3] {
2860            at.id = "assertion_gap|src/lib.rs|f|s.reset();|0".into();
2861        }
2862        let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&in_repository)).unwrap();
2863        assert_eq!(
2864            results_of(&sarif)[3]["partialFingerprints"]["tmtFindingId/v2"],
2865            "assertion_gap|src/lib.rs|f|s.reset();|0"
2866        );
2867        assert_eq!(sarif["runs"][0]["properties"]["analysis"]["since"], "abc");
2868        assert_eq!(sarif["version"], "2.1.0");
2869        let results = sarif["runs"][0]["results"].as_array().unwrap();
2870        assert_eq!(results.len(), 4);
2871        assert_eq!(results[0]["ruleId"], "input-gap");
2872        assert_eq!(results[3]["ruleId"], "assertion-gap");
2873        let location = &results[3]["locations"][0]["physicalLocation"];
2874        assert_eq!(location["artifactLocation"]["uri"], "crates/p/src/lib.rs");
2875        assert_eq!(
2876            (
2877                &location["region"]["startLine"],
2878                &location["region"]["startColumn"]
2879            ),
2880            (&serde_json::json!(7), &serde_json::json!(5))
2881        );
2882        assert!(
2883            results[3]["message"]["text"]
2884                .as_str()
2885                .unwrap()
2886                .starts_with("`s.reset();`: passes every test as: delete `s.reset();`; ")
2887        );
2888        let rules = sarif["runs"][0]["tool"]["driver"]["rules"]
2889            .as_array()
2890            .unwrap();
2891        assert_eq!(rules.len(), 6);
2892    }
2893
2894    #[test]
2895    fn a_mutant_built_on_its_own_is_a_survivor_without_a_cause() {
2896        let survivor = Finding::Survivor {
2897            at: Location {
2898                file: "src/lib.rs".into(),
2899                line: 2,
2900                column: 1,
2901                code: "const fn limit() -> u8".into(),
2902                ..Location::default()
2903            },
2904            survivors: vec!["the body of `limit` replaced by `0`".into()],
2905            witness: None,
2906            change_since: None,
2907            advice: None,
2908        };
2909        assert_eq!(survivor.kind(), "survivor");
2910        assert_eq!(survivor.at().line, 2);
2911        assert_eq!(survivor.survivors().len(), 1);
2912        let report = Report {
2913            package: "p".into(),
2914            findings: vec![survivor],
2915            ..Report::default()
2916        };
2917        // Neither of the two gaps: it is counted and named as what it is.
2918        assert_eq!(
2919            render_text(&report, false),
2920            "SURVIVOR  src/lib.rs:2:1\n    const fn limit() -> u8\n\
2921             \x20 passes every test as: the body of `limit` replaced by `0`\n\
2922             \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\
2923             \n\
2924             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"
2925        );
2926        let json = serde_json::to_value(&report).unwrap();
2927        assert_eq!(json["findings"][0]["kind"], "survivor");
2928        let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
2929        assert_eq!(results_of(&sarif)[0]["ruleId"], "survivor");
2930        assert!(report.has_gaps());
2931    }
2932
2933    #[test]
2934    fn non_literal_inputs_in_words() {
2935        assert_eq!(
2936            input_for("a", "b", LiteralSide::None, 0),
2937            "`a` equal to `b`"
2938        );
2939        assert_eq!(input_for("a", "b", LiteralSide::None, 1), "`a` = `b` + 1");
2940        assert_eq!(input_for("a", "b", LiteralSide::None, -1), "`a` = `b` - 1");
2941        assert_eq!(
2942            input_for("18", "age", LiteralSide::Lhs(18), -1),
2943            "`age` = 19"
2944        );
2945    }
2946
2947    #[test]
2948    fn text_report_sections() {
2949        let at = Location {
2950            file: "src/lib.rs".into(),
2951            line: 3,
2952            column: 9,
2953            code: "s.check()?;".into(),
2954            ..Location::default()
2955        };
2956        let report = Report {
2957            schema_version: SCHEMA_VERSION,
2958            mutants: None,
2959            package: "p".into(),
2960            analysis: Analysis::default(),
2961            audit: None,
2962            evaluation: None,
2963            sites: 4,
2964            skipped_sites: 1,
2965            skipped: vec![],
2966            unviable_mutants: 2,
2967            mutants_not_built: 0,
2968            mutants_not_evaluated: 0,
2969            mutants_not_compiled: 0,
2970            mutants_run: 3,
2971            mutants_killed: 2,
2972            mutants_timed_out: 0,
2973            timeout_rechecks: TimeoutRechecks::default(),
2974            suppressed: 0,
2975            findings: vec![Finding::AssertionGap {
2976                at: at.clone(),
2977                survivors: vec!["delete `s.check()?;`".into()],
2978                tests: (0..7).map(|i| format!("tests::t{i}")).collect(),
2979                effects: vec![],
2980                effects_of: None,
2981                witness: None,
2982            }],
2983            unreached: vec![at.clone()],
2984            unstable: vec![at],
2985            weakened: vec![],
2986        };
2987        let text = render_text(&report, false);
2988        assert!(
2989            text.contains("ASSERTION GAP  src/lib.rs:3:9\n    s.check()?;"),
2990            "{text}"
2991        );
2992        assert!(text.contains("tests::t4 (+2 more)"), "{text}");
2993        assert!(text.contains("UNSTABLE  src/lib.rs:3:9"), "{text}");
2994        assert!(!text.contains("UNREACHED"), "{text}");
2995        assert!(
2996            text.contains("3 mutants run (2 killed), 1 sites unreached, 1 sites skipped"),
2997            "{text}"
2998        );
2999        assert!(
3000            text.contains(", 2 mutants left out (they do not compile)\n"),
3001            "{text}"
3002        );
3003        assert!(text.contains("--show-unreached"), "{text}");
3004        let listed = render_text(&report, true);
3005        assert!(listed.contains("UNREACHED  src/lib.rs:3:9"));
3006        assert!(!listed.contains("--show-unreached"), "{listed}");
3007        let one_more = Report {
3008            findings: vec![Finding::InputGap {
3009                at: report.unreached[0].clone(),
3010                survivors: vec!["`a`".into()],
3011                survivor_count: 2,
3012                add_tests: vec![],
3013                observed: None,
3014                verified: true,
3015            }],
3016            ..report.clone()
3017        };
3018        assert!(render_text(&one_more, false).contains("`a` (+1 more)"));
3019        let nothing_unreached = Report {
3020            unreached: vec![],
3021            ..report.clone()
3022        };
3023        assert!(!render_text(&nothing_unreached, false).contains("--show-unreached"));
3024        assert!(!Report::default().has_gaps());
3025    }
3026    #[test]
3027    fn unstable_predictions_alone_are_something_to_act_on() {
3028        let at = Location {
3029            file: "src/lib.rs".into(),
3030            line: 1,
3031            column: 1,
3032            code: "a > b".into(),
3033            ..Location::default()
3034        };
3035        assert!(!Report::default().has_gaps());
3036        assert!(
3037            Report {
3038                unstable: vec![at],
3039                ..Report::default()
3040            }
3041            .has_gaps()
3042        );
3043    }
3044
3045    #[test]
3046    fn what_counts_as_a_float_literal() {
3047        assert_eq!(float_literal("30.5"), Some(30.5));
3048        assert_eq!(float_literal(" 2.5_f32 "), Some(2.5));
3049        assert_eq!(float_literal("-1e3"), Some(-1000.0));
3050        // These parse as floats too, and are not literals: a variable called `inf`, and
3051        // forms Rust does not accept.
3052        for text in ["inf", "nan", "-inf", ".5", "+5", "e5", "limit", ""] {
3053            assert_eq!(float_literal(text), None, "{text}");
3054        }
3055    }
3056
3057    #[test]
3058    fn a_float_shift_that_does_not_move_the_literal_is_dropped() {
3059        // At 2^53 the next float below is 1 away and the next above 2 away.
3060        let survivors_of = |source: &str| {
3061            let site = site_of(source);
3062            let mut obs = Obs::of_f(-4.0);
3063            obs.merge(&Obs::of_f(4.0));
3064            let gap = InputGap::EqualNeverObserved {
3065                flipped: CmpOp::Ge,
3066                float_gap: obs.float_gap(),
3067            };
3068            match input_gap_finding("f.rs", &site, &gap, &obs, true) {
3069                Some(Finding::InputGap {
3070                    survivors,
3071                    survivor_count,
3072                    ..
3073                }) => (survivors, survivor_count),
3074                _ => panic!(),
3075            }
3076        };
3077        // Shifts of +2 and -2 are proposed. Both move the literal.
3078        assert_eq!(
3079            survivors_of("fn f(x: f64) -> bool { x > 9007199254740992.0 }"),
3080            (
3081                vec![
3082                    "`x >= 9007199254740992.0`".to_string(),
3083                    "`x > 9007199254740994.0`".to_string(),
3084                    "`x > 9007199254740990.0`".to_string(),
3085                ],
3086                3
3087            )
3088        );
3089        // At 2^54 only the step down is a different number, and on the left of the
3090        // comparison the literal moves the other way.
3091        assert_eq!(
3092            survivors_of("fn f(x: f64) -> bool { x > 18014398509481984.0 }"),
3093            (
3094                vec![
3095                    "`x >= 18014398509481984.0`".to_string(),
3096                    "`x > 1.8014398509481982e16`".to_string(),
3097                ],
3098                2
3099            )
3100        );
3101        assert_eq!(
3102            survivors_of("fn f(x: f64) -> bool { 18014398509481984.0 > x }"),
3103            (
3104                vec![
3105                    "`18014398509481984.0 >= x`".to_string(),
3106                    "`1.8014398509481982e16 > x`".to_string(),
3107                ],
3108                2
3109            )
3110        );
3111        // With the literal on the left, the nearest values are those of the other side.
3112        let site = site_of("fn f(x: f64) -> bool { 1.5 > x }");
3113        let mut obs = Obs::of_f(-1.0);
3114        obs.merge(&Obs::of_f(2.0));
3115        let gap = InputGap::EqualNeverObserved {
3116            flipped: CmpOp::Ge,
3117            float_gap: obs.float_gap(),
3118        };
3119        let Some(Finding::InputGap { observed, .. }) =
3120            input_gap_finding("f.rs", &site, &gap, &obs, true)
3121        else {
3122            panic!()
3123        };
3124        assert_eq!(
3125            observed.as_deref(),
3126            Some(
3127                "nearest values the tests passed: `x` = -0.5, 2.5; any threshold between them passes"
3128            )
3129        );
3130        // Far above, neither does.
3131        assert_eq!(
3132            survivors_of("fn f(x: f64) -> bool { x > 1e30 }"),
3133            (vec!["`x >= 1e30`".to_string()], 1)
3134        );
3135    }
3136
3137    #[test]
3138    fn the_effects_are_said_of_the_mutant_they_were_seen_with() {
3139        let gap = |survivors: &[&str], effects_of: Option<&str>| Finding::AssertionGap {
3140            at: Location {
3141                file: "src/lib.rs".into(),
3142                line: 1,
3143                column: 1,
3144                code: "a < b".into(),
3145                ..Location::default()
3146            },
3147            survivors: survivors.iter().map(|s| s.to_string()).collect(),
3148            tests: vec!["tests::t".into()],
3149            effects: vec!["with the mutant, `tests::t` now runs `x;` (src/lib.rs:2)".into()],
3150            effects_of: effects_of.map(str::to_string),
3151            witness: None,
3152        };
3153        // Of several mutants one was followed: the report says which.
3154        let body = finding_body(&gap(&["`a <= b`", "`a == b`"], Some("`a <= b`")), false);
3155        assert_eq!(
3156            body[2..],
3157            [
3158                "followed one of them through the tests: `a <= b`",
3159                "with the mutant, `tests::t` now runs `x;` (src/lib.rs:2)"
3160            ]
3161        );
3162        // A single mutant needs no saying, and nothing is said where nothing is known.
3163        for single in [
3164            gap(&["`a <= b`"], Some("`a <= b`")),
3165            gap(&["`a <= b`", "`a == b`"], None),
3166        ] {
3167            let body = finding_body(&single, false);
3168            assert_eq!(body.len(), 3, "{body:?}");
3169            assert!(body[2].starts_with("with the mutant"), "{body:?}");
3170        }
3171    }
3172
3173    #[test]
3174    fn an_audit_is_said_in_the_summary() {
3175        let mut report = Report {
3176            package: "p".into(),
3177            audit: Some(Audit {
3178                sampled: 2,
3179                survivors: 7,
3180                ..Audit::default()
3181            }),
3182            ..Report::default()
3183        };
3184        let text = render_text(&report, false);
3185        assert!(
3186            text.ends_with(
3187                "\naudit: 2 of 7 surviving mutants run against all tests, 0 failed one they had not been run against\n\
3188                 audit: recorded once more, the tests did the same\n"
3189            ),
3190            "{text}"
3191        );
3192        let audit = report.audit.as_mut().unwrap();
3193        audit.disagreements.push(Location {
3194            file: "src/lib.rs".into(),
3195            line: 3,
3196            column: 5,
3197            code: "x > 5".into(),
3198            ..Location::default()
3199        });
3200        audit.trace_differences.push(TraceDifference {
3201            binary: "p".into(),
3202            records: 4,
3203            rerun_failed: false,
3204        });
3205        let text = render_text(&report, false);
3206        assert!(
3207            text.ends_with(
3208                "all tests, 1 failed one they had not been run against\n\
3209                 \x20 src/lib.rs:3:5  x > 5\n\
3210                 audit: recorded once more, `p` differs in 4 records: its tests do not always do the same\n"
3211            ),
3212            "{text}"
3213        );
3214        // Mutants built from the source are said only where some were, with what differs.
3215        assert!(!text.contains("built from the source"), "{text}");
3216        let audit = report.audit.as_mut().unwrap();
3217        audit.rebuilt = 1;
3218        audit.not_compared = 1;
3219        let text = render_text(&report, false);
3220        assert!(
3221            text.contains(
3222                "\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"
3223            ),
3224            "{text}"
3225        );
3226        let audit = report.audit.as_mut().unwrap();
3227        audit.rebuilt = 5;
3228        audit.compared = 4;
3229        audit.source_disagreements.push(SourceDisagreement {
3230            at: Location {
3231                file: "src/lib.rs".into(),
3232                line: 9,
3233                column: 14,
3234                code: "note(asked)".into(),
3235                ..Location::default()
3236            },
3237            mutant: "the guard `note(asked)` replaced by `true`".into(),
3238            as_probe: "passes".into(),
3239            built: "fails".into(),
3240        });
3241        let text = render_text(&report, false);
3242        assert!(
3243            text.contains(
3244                "\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\
3245                 \x20 src/lib.rs:9:14  the guard `note(asked)` replaced by `true`: passes as a probe, fails built\n"
3246            ),
3247            "{text}"
3248        );
3249        assert!(!render_text(&Report::default(), false).contains("audit"));
3250    }
3251
3252    #[test]
3253    fn lists_and_counts_at_their_limits() {
3254        let items: Vec<String> = ["a", "b", "c"].iter().map(|s| s.to_string()).collect();
3255        assert_eq!(list(&items, 3), "a, b, c");
3256        assert_eq!(list(&items, 2), "a, b (+1 more)");
3257        assert_eq!(list(&items, 1), "a (+2 more)");
3258        let one = Report {
3259            package: "p".into(),
3260            suppressed: 1,
3261            unviable_mutants: 1,
3262            ..Report::default()
3263        };
3264        assert!(
3265            render_text(&one, false).contains(", 1 mutants left out (they do not compile)"),
3266            "{}",
3267            render_text(&one, false)
3268        );
3269        assert!(!render_text(&Report::default(), false).contains("left out"));
3270        assert!(!render_text(&one, false).contains("--rebuild"));
3271        assert!(!render_text(&one, false).contains("not evaluated"));
3272        let at_top = Report {
3273            mutants_not_evaluated: 1,
3274            ..Report::default()
3275        };
3276        assert!(
3277            render_text(&at_top, false).ends_with(
3278                "\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"
3279            ),
3280            "{}",
3281            render_text(&at_top, false)
3282        );
3283        // Each reason is said for the mutants it holds for, and only when it holds for some.
3284        let not_built = Report {
3285            mutants_not_evaluated: 5,
3286            mutants_not_compiled: 5,
3287            ..Report::default()
3288        };
3289        let text = render_text(&not_built, false);
3290        assert!(
3291            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"),
3292            "{text}"
3293        );
3294        assert!(!text.contains("largest value"), "{text}");
3295        let both = Report {
3296            mutants_not_evaluated: 7,
3297            mutants_not_compiled: 5,
3298            ..Report::default()
3299        };
3300        let text = render_text(&both, false);
3301        assert!(
3302            text.contains("(5 mutants not evaluated: their code"),
3303            "{text}"
3304        );
3305        assert!(
3306            text.contains("\n(2 mutants not evaluated: a range"),
3307            "{text}"
3308        );
3309        let quick = Report {
3310            mutants_not_built: 1,
3311            ..Report::default()
3312        };
3313        assert!(
3314            render_text(&quick, false)
3315                .ends_with("\n(1 more mutants need a build of their own: --rebuild runs them)\n"),
3316            "{}",
3317            render_text(&quick, false)
3318        );
3319        let slow = Report {
3320            mutants_run: 5,
3321            mutants_killed: 4,
3322            mutants_timed_out: 2,
3323            ..Report::default()
3324        };
3325        assert!(
3326            render_text(&slow, false)
3327                .contains("5 mutants run (4 killed, 2 of them by the time limit), 0 sites"),
3328            "{}",
3329            render_text(&slow, false)
3330        );
3331        assert!(!render_text(&one, false).contains("time limit"));
3332        let once = Report {
3333            mutants_timed_out: 1,
3334            ..slow.clone()
3335        };
3336        assert!(
3337            render_text(&once, false).contains("(4 killed, 1 of them by the time limit)"),
3338            "{}",
3339            render_text(&once, false)
3340        );
3341        assert!(
3342            render_text(&one, false).contains(", 1 findings suppressed"),
3343            "{}",
3344            render_text(&one, false)
3345        );
3346        assert!(!render_text(&Report::default(), false).contains("suppressed"));
3347    }
3348
3349    #[test]
3350    fn findings_are_put_in_reading_order() {
3351        let gap = |file: &str, line: usize, column: usize, survivor: &str| Finding::AssertionGap {
3352            at: Location {
3353                file: file.into(),
3354                line,
3355                column,
3356                code: "x".into(),
3357                ..Location::default()
3358            },
3359            survivors: vec![survivor.into()],
3360            tests: vec![],
3361            effects: vec![],
3362            effects_of: None,
3363            witness: None,
3364        };
3365        let mut report = Report {
3366            findings: vec![
3367                gap("src/b.rs", 1, 1, "b"),
3368                gap("src/a.rs", 9, 5, "statement"),
3369                gap("src/a.rs", 7, 2, "above it"),
3370                gap("src/a.rs", 9, 5, "its operator"),
3371                gap("src/a.rs", 9, 3, "left of both"),
3372            ],
3373            ..Report::default()
3374        };
3375        report.sort_findings();
3376        let order: Vec<&str> = report
3377            .findings
3378            .iter()
3379            .map(|f| match f {
3380                Finding::AssertionGap { survivors, .. } => survivors[0].as_str(),
3381                _ => panic!(),
3382            })
3383            .collect();
3384        // Findings at one position keep the order they were made in.
3385        assert_eq!(
3386            order,
3387            ["above it", "left of both", "statement", "its operator", "b"]
3388        );
3389    }
3390    #[test]
3391    fn second_replacements_guards_fields_and_bodies_in_words() {
3392        let all = |src: &str| discover(src, 0).unwrap().sites;
3393        let add = site_of("fn f(total: u32, fee: u32) -> u32 { total + fee }");
3394        assert_eq!(describe(&add, Mutation::ArithSwap2), "`total * fee`");
3395        let Some(Finding::InputGap {
3396            survivors,
3397            add_tests,
3398            ..
3399        }) = arith_gap_finding("f.rs", &add, Mutation::ArithSwap2, true)
3400        else {
3401            panic!()
3402        };
3403        assert_eq!(survivors, ["`total * fee`"]);
3404        assert_eq!(
3405            add_tests,
3406            ["operands for which `total + fee` and `total * fee` differ"]
3407        );
3408        let sites = all("fn f(bits: &mut u8, mask: u8) { *bits ^= mask; *bits <<= 1 }");
3409        let arith: Vec<&Site> = sites
3410            .iter()
3411            .filter(|s| matches!(s.kind, SiteKind::Arith { .. }))
3412            .collect();
3413        assert_eq!(describe(arith[0], Mutation::ArithSwap), "`*bits &= mask`");
3414        assert_eq!(describe(arith[0], Mutation::ArithSwap2), "`*bits |= mask`");
3415        let collect = site_of("fn f(bits: &mut u8, mask: u8) { *bits |= mask }");
3416        assert_eq!(
3417            arith_gap_finding("f.rs", &collect, Mutation::ArithSwap2, true),
3418            None
3419        );
3420        // A shift has one replacement: no second finding.
3421        assert_eq!(
3422            arith_gap_finding("f.rs", arith[1], Mutation::ArithSwap2, true),
3423            None
3424        );
3425
3426        let sites = all("fn f(k: Option<i32>, base: O) -> O { \
3427             let d = match k { Some(n) if n > 1 => -n, _ => 0 }; O { depth: d, ..base } }");
3428        let of = |pick: &dyn Fn(&SiteKind) -> bool| sites.iter().find(|s| pick(&s.kind)).unwrap();
3429        let guard = of(&|k| matches!(k, SiteKind::Guard { .. }));
3430        assert_eq!(
3431            describe(guard, Mutation::Const(true)),
3432            "the guard `n > 1` replaced by `true`"
3433        );
3434        assert_eq!(
3435            guard_gap_finding("f.rs", guard, false, true),
3436            Finding::InputGap {
3437                at: location("f.rs", guard),
3438                survivors: vec!["the guard `n > 1` replaced by `false`".into()],
3439                survivor_count: 1,
3440                add_tests: vec!["a case where the guard `n > 1` is true".into()],
3441                observed: None,
3442                verified: true,
3443            }
3444        );
3445        let neg = of(&|k| matches!(k, SiteKind::Neg { .. }));
3446        assert_eq!(describe(neg, Mutation::Delete), "`n`");
3447        let field = of(&|k| matches!(k, SiteKind::Field { .. }));
3448        assert_eq!(
3449            describe(field, Mutation::Delete),
3450            "without the field `depth: d` (it is then `(base).depth`)"
3451        );
3452        let body = of(&|k| matches!(k, SiteKind::Body { .. }));
3453        assert_eq!(
3454            describe(body, Mutation::Delete),
3455            "the body of `f` replaced by `Default::default()`"
3456        );
3457        assert_eq!(
3458            location("f.rs", body).code,
3459            "fn f(k: Option<i32>, base: O) -> O"
3460        );
3461    }
3462
3463    #[test]
3464    fn audit_reports_unjudged_all_tests_reruns_in_text_and_json() {
3465        let mut report = Report {
3466            package: "demo".into(),
3467            audit: Some(Audit {
3468                sampled: 3,
3469                survivors: 3,
3470                not_audited: 2,
3471                ..Audit::default()
3472            }),
3473            ..Report::default()
3474        };
3475        let text = render_text(&report, false);
3476        assert!(
3477            text.contains(
3478                "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"
3479            ),
3480            "{text}"
3481        );
3482        let value = serde_json::to_value(&report).unwrap();
3483        assert_eq!(value["audit"]["not_audited"], 2);
3484
3485        report.audit.as_mut().unwrap().not_audited = 0;
3486        let clean_text = render_text(&report, false);
3487        assert!(!clean_text.contains("could not be judged"), "{clean_text}");
3488        let clean_value = serde_json::to_value(&report).unwrap();
3489        assert!(clean_value["audit"].get("not_audited").is_none());
3490    }
3491
3492    #[test]
3493    fn sarif_emits_unstable_predictions() {
3494        let report = Report {
3495            package: "demo".into(),
3496            unstable: vec![Location {
3497                file: "src/lib.rs".into(),
3498                line: 12,
3499                column: 5,
3500                code: "age >= 18".into(),
3501                ..Location::default()
3502            }],
3503            ..Report::default()
3504        };
3505        let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
3506        let results = sarif["runs"][0]["results"].as_array().unwrap();
3507        assert_eq!(results.len(), 1);
3508        assert_eq!(results[0]["ruleId"], "unstable-prediction");
3509        assert_eq!(results[0]["level"], "error");
3510        assert_eq!(
3511            results[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
3512            "src/lib.rs"
3513        );
3514    }
3515
3516    #[test]
3517    fn sarif_emits_weakened_and_audit_disagreements_and_has_gaps() {
3518        let loc = Location {
3519            file: "src/lib.rs".into(),
3520            line: 20,
3521            column: 9,
3522            code: "x > 0".into(),
3523            ..Location::default()
3524        };
3525        let report = Report {
3526            package: "demo".into(),
3527            weakened: vec![loc.clone()],
3528            audit: Some(Audit {
3529                survivors: 1,
3530                sampled: 1,
3531                disagreements: vec![loc.clone()],
3532                not_audited: 0,
3533                rebuilt: 1,
3534                compared: 1,
3535                not_compared: 0,
3536                source_disagreements: vec![SourceDisagreement {
3537                    at: loc,
3538                    mutant: "`x >= 0`".into(),
3539                    as_probe: "passes".into(),
3540                    built: "fails".into(),
3541                }],
3542                trace_differences: vec![
3543                    TraceDifference {
3544                        binary: "unit".into(),
3545                        records: 3,
3546                        rerun_failed: false,
3547                    },
3548                    TraceDifference {
3549                        binary: "flaky".into(),
3550                        records: 0,
3551                        rerun_failed: true,
3552                    },
3553                    TraceDifference {
3554                        binary: "flaky-diff".into(),
3555                        records: 2,
3556                        rerun_failed: true,
3557                    },
3558                ],
3559            }),
3560            ..Report::default()
3561        };
3562        assert!(report.has_gaps());
3563        let text = render_text(&report, false);
3564        assert!(
3565            text.contains("`flaky` did not pass: its tests do not always do the same"),
3566            "{text}"
3567        );
3568        assert!(
3569            text.contains(
3570                "`flaky-diff` did not pass and differs in 2 records: its tests do not always do the same"
3571            ),
3572            "{text}"
3573        );
3574        let sarif: serde_json::Value = serde_json::from_str(&render_sarif(&report)).unwrap();
3575        let results = sarif["runs"][0]["results"].as_array().unwrap();
3576        let rules: Vec<_> = results
3577            .iter()
3578            .map(|r| (r["ruleId"].as_str().unwrap(), r["level"].as_str().unwrap()))
3579            .collect();
3580        assert_eq!(
3581            rules,
3582            [
3583                ("weakened-test", "warning"),
3584                ("audit-disagreement", "error"),
3585                ("audit-disagreement", "error"),
3586                ("audit-disagreement", "error"),
3587                ("audit-disagreement", "error"),
3588                ("audit-disagreement", "error"),
3589            ]
3590        );
3591        assert!(
3592            results[4]["message"]["text"]
3593                .as_str()
3594                .unwrap()
3595                .contains("did not pass"),
3596            "{}",
3597            results[4]
3598        );
3599        assert!(
3600            results[5]["message"]["text"]
3601                .as_str()
3602                .unwrap()
3603                .contains("did not pass and differed in 2 records"),
3604            "{}",
3605            results[5]
3606        );
3607        assert!(sarif["runs"][0]["properties"].get("audit").is_some());
3608    }
3609
3610    #[test]
3611    fn render_text_sanitizes_terminal_escape_sequences_bidi_and_injected_newlines() {
3612        let report = Report {
3613            package: "pkg\x1b[31mred\x1b[0m\nFAKE".into(),
3614            sites: 1,
3615            findings: vec![Finding::AssertionGap {
3616                at: Location {
3617                    file: "src/\x1b]52;c;evil\x07lib.rs".into(),
3618                    line: 10,
3619                    column: 5,
3620                    code: "x\u{202e} == 1\r\nFAKE LINE".into(),
3621                    ..Location::default()
3622                },
3623                survivors: vec!["`x \x1b[2J!= 1`".into()],
3624                tests: vec!["tests::\u{009b}31mspoof".into()],
3625                effects: vec![],
3626                effects_of: None,
3627                witness: None,
3628            }],
3629            ..Report::default()
3630        };
3631        assert_eq!(report.schema_version, SCHEMA_VERSION);
3632        let json: serde_json::Value = serde_json::to_value(&report).unwrap();
3633        assert_eq!(json["schema_version"], SCHEMA_VERSION);
3634        // JSON remains lossless.
3635        assert!(json["package"].as_str().unwrap().contains('\x1b'));
3636
3637        let text = render_text(&report, false);
3638        assert!(!text.contains('\x1b'), "{text:?}");
3639        assert!(!text.contains('\x07'), "{text:?}");
3640        assert!(!text.contains('\u{009b}'), "{text:?}");
3641        assert!(!text.contains('\u{202e}'), "{text:?}");
3642        assert!(!text.contains('\r'), "{text:?}");
3643        // Injected newlines in untrusted fields cannot start a forged line.
3644        assert!(!text.lines().any(|l| l.starts_with("FAKE")), "{text:?}");
3645        assert!(text.contains("src/lib.rs:10:5"), "{text:?}");
3646        assert!(text.contains("pkgred FAKE:"), "{text:?}");
3647
3648        // C1 OSC/DCS, C1 ST terminator, nF ESC ( B, and incomplete OSC do not leak payloads
3649        // or swallow subsequent fields on the same line.
3650        assert_eq!(sanitize_inline("a\u{009d}0;title\u{009c}b"), "ab");
3651        assert_eq!(sanitize_inline("a\u{0090}dcs-payload\u{009c}b"), "ab");
3652        assert_eq!(sanitize_inline("a\x1b]0;title\u{009c}b"), "ab");
3653        assert_eq!(sanitize_inline("a\x1b(Bb"), "ab");
3654        let report_unclosed = Report {
3655            package: "p".into(),
3656            sites: 1,
3657            findings: vec![Finding::AssertionGap {
3658                at: Location {
3659                    file: "src/lib.rs".into(),
3660                    line: 1,
3661                    column: 1,
3662                    code: "x == 1".into(),
3663                    ..Location::default()
3664                },
3665                survivors: vec!["`a\x1b]0;unterminated".into(), "`b`".into()],
3666                tests: vec!["t".into()],
3667                effects: vec![],
3668                effects_of: None,
3669                witness: None,
3670            }],
3671            ..Report::default()
3672        };
3673        let unclosed_text = render_text(&report_unclosed, false);
3674        assert!(unclosed_text.contains("`a, `b`"), "{unclosed_text:?}");
3675    }
3676}