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