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