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