1use std::cell::RefCell;
8use std::collections::{BTreeMap, BTreeSet, HashSet};
9use std::fs;
10use std::path::{Path, PathBuf};
11use std::process::{Command, Stdio};
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15use anyhow::{Context, Result, anyhow, bail};
16
17use crate::checkpoint::{Checkpoint, Phase};
18use crate::instrument::{self, RUNTIME_MOD, Rendered, Site, SiteKind};
19use crate::output_fixture::{self, Fixture};
20use crate::plan::{self, Mutation};
21use crate::propagation::Change;
22use crate::report::{self, Finding, Report};
23use crate::scope::{self};
24use crate::trace::Trace;
25use crate::work_lock::WorkLock;
26use crate::{git_index, leftovers, progress, reverts, witness};
27
28#[derive(Clone)]
29pub struct Options {
30 pub dir: PathBuf,
32 pub package: Option<String>,
33 pub list: bool,
35 pub test_workspace: bool,
37 pub verify: bool,
39 pub work_dir: Option<PathBuf>,
41 pub progress: bool,
43 pub since: Option<String>,
45 pub lines: Vec<String>,
47 pub baseline: Option<PathBuf>,
49 pub write_baseline: Option<PathBuf>,
51 pub also_test: Vec<String>,
53 pub dependents: bool,
55 pub effects: bool,
57 pub rebuild: bool,
59 pub error_values: Vec<String>,
61 pub source_only: bool,
62 pub literal_operators: bool,
63 pub shard: Option<report::Shard>,
64 pub nextest: Option<report::Nextest>,
65 pub test_selection: TestSelection,
66 pub opt_level: Option<u8>,
68 pub timeout_seconds: Option<u64>,
70 pub baseline_jobs: usize,
71 pub serial_timeout_rechecks: bool,
72 pub wrapper_grace: Duration,
73 pub audit: Option<usize>,
75 pub cargo: CargoConfig,
77 pub jobs: usize,
79 pub all_files: bool,
81 pub git_index: bool,
82 pub copy_fixtures: Vec<PathBuf>,
83 pub copy_fixture_excludes: Vec<PathBuf>,
84 pub output_fixtures: Vec<Fixture>,
85 pub stage_external: Vec<StageExternal>,
86 pub checkpoint: bool,
87 pub doc: bool,
89}
90
91#[derive(Clone, Default)]
92pub struct TestSelection {
93 pub isolate: bool,
94 pub lib: bool,
95 pub bins: bool,
96 pub integration_tests: Vec<String>,
97 pub targets: Vec<String>,
98 pub include: Vec<String>,
99 pub filter: Vec<String>,
100 pub exclude: Vec<String>,
101 pub include_ignored: bool,
102 pub wrapper: Option<PathBuf>,
103}
104
105impl TestSelection {
106 pub(crate) fn has_target_filters(&self) -> bool {
107 self.lib || self.bins || !self.integration_tests.is_empty() || !self.targets.is_empty()
108 }
109
110 fn enabled(&self) -> bool {
111 self.isolate
112 || self.has_target_filters()
113 || !self.include.is_empty()
114 || !self.filter.is_empty()
115 || !self.exclude.is_empty()
116 || self.include_ignored
117 || self.wrapper.is_some()
118 }
119
120 pub(crate) fn matches_test(&self, test: &str, was_ignored: bool) -> bool {
121 if was_ignored && !self.include_ignored {
122 return false;
123 }
124 if self.exclude.iter().any(|name| name == test) {
125 return false;
126 }
127 if !self.include.is_empty() || !self.filter.is_empty() {
128 let exact = self.include.iter().any(|name| name == test);
129 let partial = self.filter.iter().any(|pat| test.contains(pat));
130 if !exact && !partial {
131 return false;
132 }
133 }
134 true
135 }
136}
137
138pub use crate::report::CargoConfig;
139pub use workcopy::StageExternal;
140
141impl CargoConfig {
142 pub fn flags(&self) -> Vec<String> {
144 let mut flags = vec![];
145 if !self.features.is_empty() {
146 flags.extend(["--features".to_string(), self.features.join(",")]);
147 }
148 for (on, flag) in [
149 (self.all_features, "--all-features"),
150 (self.no_default_features, "--no-default-features"),
151 (self.locked, "--locked"),
152 ] {
153 if on {
154 flags.push(flag.to_string());
155 }
156 }
157 flags
158 }
159}
160
161const NEARBY_LINES: usize = 6;
164const WORK_MARKER: &str = ".tmt-work-dir";
166const STD_ALIAS: &str = "__tmt_std";
168const MAX_REPAIR_ROUNDS: usize = 40;
170const MAX_TEST_FILTERS: usize = 200;
172
173mod cargo;
174mod repair_cache;
175mod runner;
176mod scope_blame;
177mod session;
178mod witness_runner;
179mod workcopy;
180
181use cargo::*;
182use runner::*;
183use scope_blame::*;
184use session::*;
185use witness_runner::*;
186use workcopy::*;
187
188struct SourceFile {
189 display: String,
191 path: PathBuf,
193 owners: BTreeSet<PathBuf>,
194 original: String,
195 lines: scope::LineIndex,
196 sites: Vec<Site>,
197 rebuild_sites: Vec<Site>,
199 places: Vec<(usize, usize, String)>,
202 rendered: Option<Rendered>,
203}
204
205fn write_rendered(
206 file: &mut SourceFile,
207 state: &WorkCopy,
208 suffix: &str,
209 disabled: &HashSet<u32>,
210 newly_disabled: &HashSet<u32>,
211) -> Result<()> {
212 if file.rendered.is_none()
213 || file
214 .sites
215 .iter()
216 .any(|site| newly_disabled.contains(&site.id))
217 {
218 file.rendered = Some(instrument::render(&file.original, &file.sites, &|id| {
219 !disabled.contains(&id)
220 }));
221 }
222 let rendered = file.rendered.as_ref().expect("rendered before writing");
223 if suffix.is_empty() {
224 state.write(&file.path, &rendered.text)
225 } else {
226 state.write(&file.path, &format!("{}{suffix}", rendered.text))
227 }
228}
229
230#[derive(Clone, Copy)]
231struct WorkspaceShard {
232 offset: usize,
233 total: usize,
234 member_total: usize,
235}
236
237struct CatalogueSnapshot {
238 path: PathBuf,
239 ready: std::cell::Cell<bool>,
240 _lock: WorkLock,
241}
242
243struct WorkspaceBatch<'a> {
244 metadata: &'a Metadata,
245 work: &'a Path,
246 catalogue: Option<CatalogueSnapshot>,
247}
248
249pub fn run_packages(options: &Options, names: &[String]) -> Result<Vec<(String, Result<Report>)>> {
251 let mut reports = vec![];
252 run_packages_each(options, names, |name, result| {
253 reports.push((name, result));
254 Ok(())
255 })?;
256 Ok(reports)
257}
258
259pub fn run_packages_each(
261 options: &Options,
262 names: &[String],
263 mut completed: impl FnMut(String, Result<Report>) -> Result<()>,
264) -> Result<()> {
265 if options.baseline.is_some() || options.write_baseline.is_some() {
266 bail!("baseline files require a single package");
267 }
268 let metadata = cargo_metadata(&options.dir, &options.cargo)?;
269 let all: BTreeSet<_> = metadata.packages.iter().map(|p| p.name.clone()).collect();
270 let selected = if names.is_empty() {
271 all.clone()
272 } else {
273 names.iter().cloned().collect()
274 };
275 if let Some(unknown) = selected.difference(&all).next() {
276 bail!("no package `{unknown}` in the workspace");
277 }
278 let base = options
279 .work_dir
280 .clone()
281 .unwrap_or_else(|| metadata.target_directory.join("tmt-workspace"));
282 fs::create_dir_all(&base).with_context(|| format!("creating {}", base.display()))?;
283 let base = base.canonicalize()?;
284 if metadata.workspace_root.canonicalize()?.starts_with(&base) {
285 bail!(
286 "the work directory {} contains the workspace",
287 base.display()
288 );
289 }
290 let catalogue = if options.list || options.shard.is_some() {
291 let path = work_directory(&base, ".catalogue")?;
292 Some(CatalogueSnapshot {
293 _lock: WorkLock::take(&path)?,
294 path,
295 ready: std::cell::Cell::new(false),
296 })
297 } else {
298 None
299 };
300 let batch = WorkspaceBatch {
301 metadata: &metadata,
302 work: &base,
303 catalogue,
304 };
305 let member_options = selected.into_iter().map(|name| {
306 let mut member = options.clone();
307 member.package = Some(name.clone());
308 member.work_dir = Some(base.join(&name));
309 (name, member)
310 });
311 let Some(shard) = options.shard else {
312 for (name, member) in member_options {
313 let result = run_package(&member, Some(&batch), None);
314 completed(name, result)?;
315 }
316 return Ok(());
317 };
318 if !options.source_only || shard.index >= shard.count {
319 bail!("shards require --source-only and a valid shard index");
320 }
321 let catalogues: Vec<_> = member_options
324 .map(|(name, member)| {
325 let mut preview = member.clone();
326 preview.list = true;
327 preview.shard = None;
328 preview.progress = false;
329 let catalogue = run_package(&preview, Some(&batch), None).map(|mut report| {
330 let count = report.mutants.as_ref().map_or(0, Vec::len);
331 if !member.list {
332 report.mutants = None;
333 }
334 (count, report)
335 });
336 (name, member, catalogue)
337 })
338 .collect();
339 let total = catalogues
340 .iter()
341 .filter_map(|(_, _, catalogue)| catalogue.as_ref().ok())
342 .map(|(count, _)| count)
343 .sum();
344 let mut offset = 0;
345 for (name, member, catalogue) in catalogues {
346 let result = catalogue.and_then(|(member_total, mut report)| {
347 let range = WorkspaceShard {
348 offset,
349 total,
350 member_total,
351 };
352 offset += member_total;
353 if member.list {
354 report.analysis.shard = Some(shard);
355 let mut index = range.offset;
356 report
357 .mutants
358 .as_mut()
359 .expect("source catalogue")
360 .retain(|_| {
361 let keep = shard.contains(index, total);
362 index += 1;
363 keep
364 });
365 Ok(report)
366 } else {
367 run_package(&member, Some(&batch), Some(range))
368 }
369 });
370 completed(name, result)?;
371 }
372 Ok(())
373}
374
375struct LeftoverNote(bool);
377
378impl Drop for LeftoverNote {
379 fn drop(&mut self) {
380 use std::sync::atomic::Ordering;
381 let stopped = leftovers::STOPPED.swap(0, Ordering::Relaxed);
382 let not_stopped = leftovers::NOT_STOPPED.swap(0, Ordering::Relaxed);
383 if let Some(text) = leftover_note(stopped, not_stopped)
384 && self.0
385 {
386 eprintln!("tmt: {text}");
387 }
388 }
389}
390
391fn leftover_note(stopped: usize, not_stopped: usize) -> Option<String> {
392 let stopped = (stopped > 0).then(|| {
393 format!("stopped {stopped} processes that the tests had left running after their run")
394 });
395 let not_stopped = (not_stopped > 0).then(|| {
396 format!(
397 "after {not_stopped} runs something the tests started may still be running \
398 (it could not be found or stopped)"
399 )
400 });
401 match (stopped, not_stopped) {
402 (None, None) => None,
403 (Some(one), None) | (None, Some(one)) => Some(one),
404 (Some(stopped), Some(not_stopped)) => Some(format!("{stopped}; {not_stopped}")),
405 }
406}
407
408pub fn run(options: &Options) -> Result<Report> {
409 run_package(options, None, None)
410}
411
412fn run_package(
413 options: &Options,
414 batch: Option<&WorkspaceBatch<'_>>,
415 workspace_shard: Option<WorkspaceShard>,
416) -> Result<Report> {
417 let _leftovers = LeftoverNote(options.progress);
418 let error_values = validate_package_options(options)?;
419 let selection = &options.test_selection;
420 let effective_jobs = if options.source_only { 1 } else { options.jobs };
421 let note = |text: &str| {
422 if options.progress {
423 eprintln!("tmt: {}", report::sanitize_inline(text));
424 }
425 };
426 let dir = options
427 .dir
428 .canonicalize()
429 .with_context(|| format!("no such directory: {}", options.dir.display()))?;
430
431 let local_metadata;
432 let metadata = if let Some(batch) = batch {
433 batch.metadata
434 } else {
435 local_metadata = cargo_metadata(&dir, &options.cargo)?;
436 &local_metadata
437 };
438 let catalogue = batch
439 .and_then(|batch| batch.catalogue.as_ref())
440 .filter(|_| options.list);
441 let package = match &options.package {
442 Some(name) => metadata.packages.iter().find(|p| &p.name == name),
443 None => metadata
444 .packages
445 .iter()
446 .find(|p| p.manifest_path.parent() == Some(dir.as_path()))
447 .or(match &metadata.packages[..] {
448 [only] => Some(only),
449 _ => None,
450 }),
451 }
452 .ok_or_else(|| anyhow!("cannot tell which package to analyse; pass --package <name>"))?;
453 let mut test_packages: Vec<&Package> = vec![package];
456 for name in &options.also_test {
457 let other = metadata
458 .packages
459 .iter()
460 .find(|p| &p.name == name)
461 .ok_or_else(|| anyhow!("--also-test: no package `{name}` in the workspace"))?;
462 if !test_packages.iter().any(|p| p.name == other.name) {
463 test_packages.push(other);
464 }
465 }
466 if options.test_workspace {
467 test_packages.extend(
468 metadata
469 .packages
470 .iter()
471 .filter(|other| {
472 !test_packages
473 .iter()
474 .any(|selected| selected.name == other.name)
475 })
476 .collect::<Vec<_>>(),
477 );
478 }
479 if options.dependents {
480 for name in dependents_of(&package.name, &metadata.packages) {
481 if let Some(other) = metadata.packages.iter().find(|p| p.name == name)
482 && !test_packages.iter().any(|p| p.name == other.name)
483 {
484 test_packages.push(other);
485 }
486 }
487 }
488 if !options.list {
489 validate_target_selection(&test_packages, selection)?;
490 }
491 let is_kind = |t: &Target, kinds: &[&str]| t.kind.iter().any(|k| kinds.contains(&k.as_str()));
492 let root_target = package
493 .targets
494 .iter()
495 .find(|t| {
496 is_kind(
497 t,
498 &["lib", "rlib", "cdylib", "staticlib", "dylib", "proc-macro"],
499 )
500 })
501 .or_else(|| package.targets.iter().find(|t| is_kind(t, &["bin"])))
502 .ok_or_else(|| anyhow!("package `{}` has no lib or bin target", package.name))?;
503
504 let PreparedWorkCopy {
506 workspace,
507 work,
508 work_lock,
509 copy,
510 state,
511 external_deps,
512 } = prepare_work_copy(options, metadata, batch, catalogue, ¬e)?;
513
514 let in_copy = |path: &Path| -> Result<PathBuf> {
515 let canonical = path.canonicalize()?;
516 let relative = canonical
517 .strip_prefix(&workspace)
518 .with_context(|| format!("{} is outside the workspace", path.display()))?;
519 Ok(copy.join(relative))
520 };
521 let package_dir = in_copy(
522 package
523 .manifest_path
524 .parent()
525 .expect("manifest has a parent"),
526 )?;
527 let root_file = in_copy(&root_target.src_path)?;
528 let source_dir = root_file
529 .parent()
530 .expect("source file has a parent")
531 .to_path_buf();
532
533 let mut roots = BTreeMap::new();
536 for owner in &metadata.packages {
537 for target in &owner.targets {
538 let production = owner.name == package.name && target.is_production();
539 if let Ok(path) = in_copy(&target.src_path)
540 && path.is_file()
541 {
542 let selected = roots.entry(path).or_insert(false);
543 *selected |= production;
544 }
545 }
546 }
547 let paths = source_graph(roots, ©, |path| state.original(path, &workspace))?;
548 let scope = requested_scope(options, &workspace, &package_dir, ©)?;
549 let mut skipped = vec![];
550 let mut files = vec![];
551 let mut next_id = 0u32;
552 let want_witnesses = (options.list || options.rebuild || options.source_only)
553 && root_target.test_build_arg() == Some(("--lib", None));
554 let mut witness_candidates = vec![];
555 for (path, owners) in paths {
556 let Some(original) = state.original(&path, &workspace)? else {
557 continue; };
559 let selected_file = scope.as_ref().is_none_or(|scope| {
560 let relative = path.strip_prefix(©).unwrap_or(&path).to_string_lossy();
561 scope.touches(&relative, 1, usize::MAX)
562 });
563 if !selected_file && path != root_file {
564 continue;
565 }
566 let display = relative_source(&path, &package_dir).display().to_string();
567 match instrument::parse_source(&original) {
568 Ok(parsed) => {
569 let mut found =
570 instrument::discover_parsed(&original, &parsed, next_id, &error_values);
571 if want_witnesses
573 && selected_file
574 && owners.consumers.len() == 1
575 && owners.consumers.contains(&root_file)
576 {
577 witness_candidates.extend(
578 witness::discover_parsed(&original, &parsed, !options.list)
579 .into_iter()
580 .map(|mut candidate| {
581 candidate.file = path.clone();
582 candidate
583 }),
584 );
585 if !options.list && !options.literal_operators {
588 witness_candidates.extend(
589 stronger_assertions(
592 &original,
593 &parsed,
594 found.sites.iter().chain(&found.rebuild_sites),
595 )
596 .into_iter()
597 .map(|mut candidate| {
598 candidate.file = path.clone();
599 candidate
600 }),
601 );
602 }
603 }
604 next_id += found.sites.len() as u32;
605 if owners.consumers.len() != 1 || !owners.consumers.contains(&root_file) {
606 found.rebuild_sites.append(&mut found.sites);
607 }
608 let places = if options.list {
609 vec![]
610 } else {
611 found
612 .sites
613 .iter()
614 .chain(&found.rebuild_sites)
615 .map(|site| (site.line, site.column, report::one_line(&site.text)))
616 .collect()
617 };
618 files.push(SourceFile {
619 display,
620 path,
621 owners: owners.production,
622 lines: scope::LineIndex::new(&original),
623 original,
624 places,
625 sites: found.sites,
626 rebuild_sites: found.rebuild_sites,
627 rendered: None,
628 });
629 }
630 Err(err) => {
631 if selected_file {
632 let diagnostic = format!("{err:#}");
633 note(&format!("skipping {display}: {diagnostic}"));
634 let end_line = scope::line_of(&original, original.len());
635 let end_column = original.rsplit('\n').next().unwrap_or("").chars().count() + 1;
636 skipped.push(report::SkippedSite::new(
637 report::Location {
638 file: display,
639 line: 1,
640 column: 1,
641 ..Default::default()
642 },
643 (end_line, end_column),
644 report::SkipReason::UnparseableSource,
645 Some(diagnostic),
646 ));
647 }
648 }
649 }
650 }
651
652 let since_hunks = match options.since.as_deref() {
655 Some(revision) if !options.list && options.shard.is_none() => {
656 scope::hunks(&since_diff(&workspace, revision)?)
657 }
658 _ => vec![],
659 };
660 let mut tests_changed: Vec<(PathBuf, Vec<scope::Hunk>)> = vec![];
661 let mut undo_paths: HashSet<PathBuf> = HashSet::new();
663 let mut not_built_reverts: usize = 0;
664 let mut beyond_places: HashSet<(PathBuf, usize, usize)> = HashSet::new();
665 if let Some(scope) = &scope {
667 for file in &mut files {
668 let relative = file
669 .path
670 .strip_prefix(©)
671 .unwrap_or(&file.path)
672 .to_string_lossy()
673 .into_owned();
674 let in_scope = |site: &Site| {
675 scope.touches(&relative, file.lines.line_of(site.start), file.lines.line_of(site.end))
676 || scope.touches(&relative, site.line, site.line)
678 };
679 let of_file: Vec<scope::Hunk> = since_hunks
680 .iter()
681 .filter(|hunk| hunk.file == relative)
682 .cloned()
683 .collect();
684 let changes_count = reverts::changes(&file.original, &of_file).len();
685 if options.rebuild || options.source_only {
686 if changes_count > 0 || reverts::mixed(&file.original, &of_file) > 0 {
687 undo_paths.insert(file.path.clone());
688 }
689 } else {
690 not_built_reverts += changes_count;
691 }
692 let of_tests = reverts::test_hunks(&file.original, &of_file);
693 if of_tests.is_empty() {
694 file.sites.retain(in_scope);
695 } else {
696 beyond_places.extend(
697 file.sites
698 .iter()
699 .filter(|site| !in_scope(site))
700 .map(|site| (file.path.clone(), site.start, site.end)),
701 );
702 tests_changed.push((file.path.clone(), of_tests));
703 }
704 file.rebuild_sites.retain(in_scope);
705 }
706 files.retain(|f| {
707 !f.sites.is_empty()
708 || !f.rebuild_sites.is_empty()
709 || f.path == root_file
710 || witness_candidates.iter().any(|c| c.file == f.path)
711 || undo_paths.contains(&f.path)
712 });
713 }
714 if !options.list {
715 for candidate in witness_candidates.iter().filter(|c| !c.existing) {
716 if let Some(file) = files.iter_mut().find(|file| file.path == candidate.file) {
717 let at = witness_location(file, candidate);
718 file.places.push((at.line, at.column, at.code));
719 }
720 }
721 }
722 witness_candidates.retain(|candidate| {
723 let Some(file) = files.iter().find(|file| file.path == candidate.file) else {
724 return false;
725 };
726 let relative = file
727 .path
728 .strip_prefix(©)
729 .unwrap_or(&file.path)
730 .to_string_lossy();
731 scope.as_ref().is_none_or(|scope| {
732 let site_in_scope = if candidate.edits.len() == 1 {
733 scope.touches(&relative, *candidate.scope.start(), *candidate.scope.end())
734 } else {
735 candidate.edits.iter().any(|edit| {
736 scope.touches(
737 &relative,
738 file.lines.line_of(edit.span.start),
739 file.lines.line_of(edit.span.end),
740 )
741 })
742 };
743 site_in_scope
744 || candidate
745 .signature_lines
746 .iter()
747 .any(|&line| scope.touches(&relative, line, line))
748 })
749 });
750 let total_sites: usize = files
751 .iter()
752 .map(|f| f.sites.len() + f.rebuild_sites.len())
753 .sum::<usize>()
754 + witness_candidates
755 .iter()
756 .filter(|candidate| !candidate.existing)
757 .count();
758 let files_with_sites = files
759 .iter()
760 .filter(|f| {
761 !f.sites.is_empty()
762 || !f.rebuild_sites.is_empty()
763 || witness_candidates
764 .iter()
765 .any(|c| !c.existing && c.file == f.path)
766 })
767 .count();
768 note(&format!(
769 "{total_sites} sites in {files_with_sites} {}",
770 if files_with_sites == 1 {
771 "file"
772 } else {
773 "files"
774 }
775 ));
776 if options.source_only {
777 for file in &mut files {
778 file.rebuild_sites.append(&mut file.sites);
779 }
780 }
781
782 let source_mutants = |file: &SourceFile, site: &Site, include_boundary: bool| {
783 let mut mutants = instrument::source_mutants(site);
784 if include_boundary {
785 mutants.extend(instrument::source_boundary_mutant(site));
786 }
787 if options.literal_operators {
788 instrument::literal_operator_mutants(&file.original, site, &mut mutants);
789 }
790 instrument::keep_line_ends(&file.original, &mut mutants);
791 mutants
792 };
793 let counts = options.shard.map(|_| {
794 let regular: usize = files
795 .iter()
796 .map(|file| {
797 file.rebuild_sites
798 .iter()
799 .map(|site| source_mutants(file, site, true).len())
800 .sum::<usize>()
801 })
802 .sum();
803 let total = regular
804 + witness_candidates
805 .iter()
806 .filter(|candidate| !candidate.existing)
807 .count();
808 (regular, total)
809 });
810 if let (Some(range), Some((_, local_total))) = (workspace_shard, counts)
811 && range.member_total != local_total
812 {
813 bail!("package catalogue changed while preparing its workspace shard");
814 }
815 let in_shard = |index| match (options.shard, counts, workspace_shard) {
816 (Some(shard), _, Some(range)) => shard.contains(range.offset + index, range.total),
817 (Some(shard), Some((_, total)), _) => shard.contains(index, total),
818 _ => true,
819 };
820 if let Some((mut index, _)) = counts {
821 witness_candidates.retain(|candidate| {
822 if candidate.existing {
823 return true;
824 }
825 let selected = in_shard(index);
826 index += 1;
827 selected
828 });
829 }
830 let empty_shard = counts.is_some_and(|(_, total)| !(0..total).any(in_shard));
831
832 let package_path = package.manifest_path.parent().unwrap_or(Path::new("."));
833 let mut report_path = repository_prefix(package_path);
834 if report_path.is_empty()
835 && batch.is_some()
836 && let Ok(relative) = package_path.strip_prefix(&workspace)
837 {
838 report_path = workspace_report_prefix(relative);
839 }
840 let mut report = Report {
841 package: package.name.clone(),
842 sites: if empty_shard { 0 } else { total_sites },
843 analysis: report::Analysis {
844 package_path: report_path,
845 since: options.since.clone(),
846 lines: options.lines.clone(),
847 tests_of: test_packages.iter().map(|p| p.name.clone()).collect(),
848 cargo: options.cargo.clone(),
849 opt_level: options.opt_level,
850 timeout_seconds: options.timeout_seconds,
851 baseline_jobs: (options.baseline_jobs > 1).then_some(options.baseline_jobs),
852 timeout_recheck: if options.serial_timeout_rechecks {
853 "serial"
854 } else {
855 "none"
856 },
857 wrapper_grace_seconds: selection
858 .wrapper
859 .as_ref()
860 .map(|_| options.wrapper_grace.as_secs()),
861 rebuild: options.rebuild || options.source_only,
862 verified: options.verify && !options.source_only,
863 doc_tests: options.doc,
864 source_only: options.source_only,
865 literal_operators: options.literal_operators,
866 shard: options.shard,
867 nextest: options.nextest.clone(),
868 error_values: error_values
869 .iter()
870 .map(|value| (*value).to_owned())
871 .collect(),
872 test_selection: None,
873 git_index: options.git_index,
874 copy_fixtures: options.copy_fixtures.clone(),
875 copy_fixture_excludes: options.copy_fixture_excludes.clone(),
876 output_fixtures: options.output_fixtures.clone(),
877 stage_external: options.stage_external.clone(),
878 checkpoint: (options.checkpoint && !options.list)
879 .then(|| work.join("checkpoint.jsonl")),
880 },
881 skipped,
882 ..Report::default()
883 };
884 if options.list {
885 if catalogue.is_none() {
886 state.settle(&workspace)?;
887 }
888 let mut candidates = vec![];
889 let mut index = 0;
890 for file in &files {
891 let sites = file
892 .sites
893 .iter()
894 .map(|site| (site, false))
895 .chain(file.rebuild_sites.iter().map(|site| (site, true)));
896 for (site, requires_rebuild) in sites {
897 for mutant in source_mutants(file, site, true) {
898 if in_shard(index) {
899 candidates.push(report::Candidate {
900 what: mutant.what,
901 into: mutant.into,
902 requires_rebuild,
903 edits: vec![candidate_edit(
904 file,
905 mutant.start,
906 mutant.end,
907 mutant.replacement,
908 )],
909 });
910 }
911 index += 1;
912 }
913 }
914 }
915 candidates.extend(
916 witness_candidates
917 .iter()
918 .filter(|candidate| !candidate.existing)
919 .filter_map(|candidate| {
920 let file = files.iter().find(|file| file.path == candidate.file)?;
921 Some(report::Candidate {
922 what: "witness".into(),
923 into: candidate.description.clone(),
924 requires_rebuild: true,
925 edits: candidate
926 .edits
927 .iter()
928 .map(|edit| {
929 candidate_edit(
930 file,
931 edit.span.start,
932 edit.span.end,
933 edit.replacement.clone(),
934 )
935 })
936 .collect(),
937 })
938 }),
939 );
940 report.mutants = Some(candidates);
941 return Ok(report);
942 }
943 if empty_shard || (scope.is_some() && total_sites == 0 && undo_paths.is_empty()) {
944 state.settle(&workspace)?;
946 if let Some(path) = &options.baseline {
947 crate::baseline::load(path)?;
948 }
949 if let Some(path) = &options.write_baseline {
950 crate::baseline::write(path, &[])?;
951 }
952 if !empty_shard {
953 report.mutants_not_built += not_built_reverts;
954 }
955 report.record_evaluation();
956 if let Some(path) = report.analysis.checkpoint.as_deref() {
957 let checkpoint = Checkpoint::open(path)?;
958 let settings =
959 serde_json::json!({"analysis": &report.analysis, "package": &package.name});
960 let identity = crate::campaign_identity::compute(©, &settings, [], false)?;
961 checkpoint.start(&identity, settings)?;
962 checkpoint.finish()?;
963 }
964 return Ok(report);
965 }
966
967 for (id, site) in files
970 .iter_mut()
971 .flat_map(|file| &mut file.sites)
972 .enumerate()
973 {
974 site.id = id as u32;
975 }
976 let beyond: HashSet<u32> = files
978 .iter()
979 .flat_map(|file| {
980 file.sites
981 .iter()
982 .filter(|site| beyond_places.contains(&(file.path.clone(), site.start, site.end)))
983 .map(|site| site.id)
984 })
985 .collect();
986
987 let root_source = state
988 .original(&root_file, &workspace)?
989 .with_context(|| format!("{} is missing", root_target.src_path.display()))?;
990 let root_suffix = if options.source_only || files.iter().all(|file| file.sites.is_empty()) {
991 String::new()
992 } else {
993 state.write(
994 &source_dir.join(format!("{RUNTIME_MOD}.rs")),
995 crate::RUNTIME_SOURCE,
996 )?;
997 let std_alias = format!("extern crate std as {STD_ALIAS};");
998 if root_source.contains(&std_alias) {
999 format!("\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
1000 } else {
1001 format!("\n#[doc(hidden)]\n{std_alias}\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
1002 }
1003 };
1004
1005 let mut disabled: HashSet<u32> = HashSet::new();
1007 let mut repairs = BTreeMap::new();
1008 let build_target = work_directory(&work, "target")?;
1009 let target_flags = test_build_flags(&test_packages, selection, &workspace, &options.cargo);
1010 let build_scope = if target_flags.is_some() {
1011 report::TestBuildScope::SelectedTargets
1012 } else {
1013 report::TestBuildScope::PackageWide
1014 };
1015 let build_note = if selection.has_target_filters() && target_flags.is_none() {
1016 "Cargo is using a package-wide build because the selected test targets cannot be expressed exactly.\n"
1017 } else {
1018 ""
1019 };
1020 if !build_note.is_empty() {
1021 note(build_note.trim_end());
1022 }
1023 let can_build_only_observer = !options.doc
1026 && target_flags.is_none()
1027 && test_packages.len() == 1
1028 && package.targets.len() == 1
1029 && root_target.test
1030 && root_target.test_build_arg() == Some(("--lib", None));
1031 let build_test_binaries = |observer: bool| {
1032 let mut command = Command::new("cargo");
1033 isolate_copy_command(&mut command, &work);
1034 if let Some(lock) = &work_lock {
1035 lock.retain_for(&mut command);
1036 }
1037 command
1038 .args(["test", "--no-run", "--message-format=json"])
1039 .args(test_packages.iter().flat_map(|p| ["-p", p.name.as_str()]))
1040 .args(target_flags.as_deref().unwrap_or_default())
1041 .args((observer && can_build_only_observer).then_some("--lib"))
1042 .args(options.cargo.flags())
1043 .current_dir(©)
1044 .env("CARGO_TARGET_DIR", &build_target)
1045 .env("CARGO_BUILD_BUILD_DIR", &build_target)
1046 .envs(profile_env(options.opt_level));
1047 run_cargo_with_progress(&mut command, options.progress && !observer)
1048 };
1049 let cargo_build = || build_test_binaries(false);
1050 let has_probe_sites = !options.source_only && files.iter().any(|f| !f.sites.is_empty());
1051 let repair_fingerprint = has_probe_sites.then(|| {
1052 let test_pkg_names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
1053 repair_cache::compute_fingerprint(
1054 &state.root,
1055 ©,
1056 &workspace,
1057 &state,
1058 &external_deps,
1059 &package.name,
1060 &test_pkg_names,
1061 &options.cargo,
1062 options.opt_level,
1063 target_flags.as_deref(),
1064 &error_values,
1065 options.doc,
1066 &files,
1067 )
1068 });
1069 if let Some(fingerprint) = &repair_fingerprint {
1070 let cached = repair_cache::load(&work, fingerprint);
1071 if !cached.is_empty() {
1072 for entry in cached {
1073 if let Some(file) = files.iter().find(|f| f.display == entry.file)
1074 && let Some(site) = file.sites.get(entry.site_index)
1075 && site.start == entry.start
1076 && site.end == entry.end
1077 && site.text == entry.text
1078 && format!("{:?}", site.kind) == entry.kind
1079 {
1080 disabled.insert(site.id);
1081 repairs.entry(site.id).or_insert(entry.reason);
1082 }
1083 }
1084 if !disabled.is_empty() {
1085 note(&format!(
1086 "reusing {} cached repair exclusion(s)",
1087 disabled.len()
1088 ));
1089 }
1090 }
1091 }
1092 let mut rounds = 0;
1093 let mut newly_disabled = HashSet::new();
1094 let build = loop {
1095 for file in &mut files {
1096 let suffix = if file.path == root_file {
1097 root_suffix.as_str()
1098 } else {
1099 ""
1100 };
1101 write_rendered(file, &state, suffix, &disabled, &newly_disabled)?;
1102 }
1103 if !files.iter().any(|f| f.path == root_file) {
1104 state.write(&root_file, &format!("{root_source}{root_suffix}"))?;
1105 }
1106 if rounds == 0 {
1107 state.settle(&workspace)?;
1108 }
1109 note(if rounds == 0 {
1110 "building the instrumented crate"
1111 } else {
1112 "rebuilding without the sites that failed to compile"
1113 });
1114 let output = cargo_build()?;
1115 let names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
1116 let build = parse_build_output(&String::from_utf8_lossy(&output.stdout), &names);
1117 if output.status.success() {
1118 if let Some(fingerprint) = &repair_fingerprint {
1119 let cached_entries: Vec<repair_cache::CachedSite> = files
1120 .iter()
1121 .flat_map(|file| {
1122 file.sites
1123 .iter()
1124 .enumerate()
1125 .filter(|(_, site)| disabled.contains(&site.id))
1126 .map(|(site_index, site)| repair_cache::CachedSite {
1127 file: file.display.clone(),
1128 site_index,
1129 start: site.start,
1130 end: site.end,
1131 text: site.text.clone(),
1132 kind: format!("{:?}", site.kind),
1133 reason: repairs.get(&site.id).cloned().unwrap_or_default(),
1134 })
1135 })
1136 .collect();
1137 let _ = repair_cache::save(&work, fingerprint, &cached_entries);
1138 }
1139 break build;
1140 }
1141 let diagnostics = || {
1142 [
1143 build.diagnostics.join("\n"),
1144 String::from_utf8_lossy(&output.stderr).into_owned(),
1145 ]
1146 .into_iter()
1147 .filter(|part| !part.trim().is_empty())
1148 .collect::<Vec<_>>()
1149 .join("\n")
1150 };
1151 if build.errors.is_empty() {
1152 bail!("the build failed:\n{build_note}{}", diagnostics());
1153 }
1154 if build
1155 .errors
1156 .iter()
1157 .any(|error| is_non_probe_error(error, &files, ©))
1158 {
1159 bail!(
1160 "the build failed with an error unrelated to instrumentation:\n{build_note}{}",
1161 diagnostics()
1162 );
1163 }
1164 rounds += 1;
1165 let before = disabled.len();
1166 let mut blamed_now: HashSet<u32> = HashSet::new();
1167 for error in &build.errors {
1168 let blamed = blame_error(error, &files, ©, &disabled);
1169 if std::env::var_os("TMT_DEBUG").is_some() {
1170 eprintln!(
1171 "tmt: debug: blaming {blamed:?} for\n{}",
1172 report::sanitize_terminal(&error.rendered)
1173 );
1174 }
1175 for id in blamed {
1176 repairs
1177 .entry(id)
1178 .or_insert_with(|| error.rendered.lines().next().unwrap_or("").to_string());
1179 blamed_now.insert(id);
1180 }
1181 }
1182 disabled.extend(blamed_now.iter().copied());
1183 newly_disabled = blamed_now;
1184 if disabled.len() == before || rounds > MAX_REPAIR_ROUNDS {
1185 bail!(
1186 "the crate does not build after instrumentation.\n\
1187 {build_note}Does `cargo test --no-run` pass on the original for the same targets?\n{}",
1188 diagnostics()
1189 );
1190 }
1191 };
1192 let built_sources = if options.rebuild || options.source_only || options.audit.is_some() {
1193 let behind_cargo = features_from_flags(
1198 std::env::vars_os()
1199 .filter(|(name, _)| name.to_string_lossy().ends_with("RUSTFLAGS"))
1200 .map(|(_, value)| Some(value)),
1201 ) || build.build_scripts.iter().any(|script| {
1202 script["cfgs"].as_array().is_some_and(|cfgs| {
1203 cfgs.iter()
1204 .any(|cfg| cfg.as_str().is_some_and(|cfg| cfg.contains("feature")))
1205 })
1206 }) || configuration_names_a_feature(
1207 ©,
1208 std::env::var_os("CARGO_HOME").map(PathBuf::from),
1209 );
1210 BuiltSources::from_artifacts(&build.artifacts, &build.features, !behind_cargo, ©)
1211 } else {
1212 BuiltSources::default()
1213 };
1214 output_fixture::stage(&workspace, &work, &build_target, &options.output_fixtures)?;
1215 let checkpoint_path = report.analysis.checkpoint.as_deref();
1216 let checkpoint = checkpoint_path.map(Checkpoint::open).transpose()?;
1217 let doc_packages = test_packages
1218 .iter()
1219 .filter(|p| options.doc && p.targets.iter().any(|target| target.doctest));
1220 if build.test_binaries.is_empty() && doc_packages.clone().next().is_none() {
1221 bail!("{build_note}`{}` has no test binaries", package.name);
1222 }
1223
1224 let mut session = Session {
1226 progress: options.progress,
1227 serial_timeout_rechecks: options.serial_timeout_rechecks,
1228 package_dir,
1229 binaries: vec![],
1230 };
1231 let wrapper = selection
1232 .wrapper
1233 .as_ref()
1234 .map(|path| {
1235 let relative = wrapper_relative(path)?;
1236 let copied = copy.join(&relative);
1237 if !copied.is_file() {
1238 bail!(
1239 "test wrapper is missing from the work copy: {}",
1240 copied.display()
1241 );
1242 }
1243 Ok(copied)
1244 })
1245 .transpose()?;
1246 let mut runners: Vec<(String, Runner, PathBuf)> = vec![];
1247 let root_test_exe = |built: &BuildOutput| {
1248 built
1249 .test_binaries
1250 .iter()
1251 .find(|(name, _, owner, kind)| {
1252 *name == root_target.name && *owner == package.name && *kind == root_target.kind
1253 })
1254 .map(|(_, exe, _, _)| exe.clone())
1255 };
1256 let root_exe = (!witness_candidates.is_empty())
1257 .then(|| root_test_exe(&build))
1258 .flatten();
1259 let mut discovered_tests: Vec<String> = vec![];
1260 let mut empty_bin_targets: Vec<(String, String)> = vec![];
1261 if let Some(nextest) = &options.nextest {
1262 let mut flags: Vec<_> = test_packages
1263 .iter()
1264 .flat_map(|p| ["-p".to_owned(), p.name.clone()])
1265 .collect();
1266 flags.extend(options.cargo.flags());
1267 runners.push((
1268 "nextest".to_owned(),
1269 Runner::Nextest {
1270 copy: copy.clone(),
1271 target_dir: build_target.clone(),
1272 profile: nextest.profile.clone(),
1273 opt_level: options.opt_level,
1274 flags,
1275 },
1276 session.package_dir.clone(),
1277 ));
1278 } else {
1279 for (name, exe, owner, kind) in build.test_binaries {
1280 if !artifact_target_selected(&name, &kind, selection) {
1281 continue;
1282 }
1283 let owner_package = test_packages
1284 .iter()
1285 .find(|p| p.name == owner)
1286 .expect("binaries are filtered by these packages");
1287 let cwd = in_copy(
1288 owner_package
1289 .manifest_path
1290 .parent()
1291 .expect("manifest has a parent"),
1292 )?;
1293 if selection.enabled() {
1294 let all = list_tests(&exe, &cwd, &work, false, true, work_lock.as_deref())?;
1295 if all.is_empty() && kind.first().map(String::as_str) == Some("bin") {
1296 empty_bin_targets.push((owner.clone(), name.clone()));
1297 }
1298 let ignored = list_tests(&exe, &cwd, &work, true, true, work_lock.as_deref())?;
1299 for test in all {
1300 let was_ignored = ignored.contains(&test);
1301 if (!was_ignored || selection.include_ignored)
1302 && !selection.exclude.iter().any(|name| name == &test)
1303 {
1304 discovered_tests.push(test.clone());
1305 }
1306 if !selection.matches_test(&test, was_ignored) {
1307 continue;
1308 }
1309 runners.push((
1310 format!("{owner}::{}::{name}::{test}", kind.join("+")),
1311 Runner::Isolated {
1312 exe: exe.clone(),
1313 test,
1314 ignored: was_ignored,
1315 wrapper: wrapper.clone(),
1316 },
1317 cwd.clone(),
1318 ));
1319 }
1320 continue;
1321 }
1322 let name = if owner == package.name {
1324 name
1325 } else {
1326 format!("{owner}::{name}")
1327 };
1328 runners.push((name, Runner::Exe(exe), cwd));
1329 }
1330 }
1331 if selection.enabled() && runners.is_empty() {
1332 let hint = no_tests_matched_hint(
1333 &test_packages,
1334 selection,
1335 &empty_bin_targets,
1336 &discovered_tests,
1337 );
1338 bail!("{build_note}no tests matched the requested selection{hint}");
1339 }
1340 let selected_tests = selection.enabled().then(|| report::TestSelection {
1341 build_scope,
1342 wrapper: selection
1343 .wrapper
1344 .as_ref()
1345 .map(|path| path.display().to_string()),
1346 tests: runners.iter().map(|(name, _, _)| name.clone()).collect(),
1347 });
1348 for owner in doc_packages {
1349 let doc = Runner::Doc {
1350 copy: copy.clone(),
1351 target_dir: build_target.clone(),
1352 package: owner.name.clone(),
1353 opt_level: options.opt_level,
1354 flags: options.cargo.flags(),
1355 };
1356 let name = if owner.name == package.name {
1357 "doc tests".to_owned()
1358 } else {
1359 format!("{}::doc tests", owner.name)
1360 };
1361 let cwd = in_copy(owner.manifest_path.parent().expect("manifest has a parent"))?;
1362 runners.push((name, doc, cwd));
1363 }
1364 report.analysis.test_selection = selected_tests;
1365 let identity = if checkpoint.is_some() {
1366 let mut build_inputs: Vec<_> = build
1367 .build_scripts
1368 .iter()
1369 .map(serde_json::Value::to_string)
1370 .collect();
1371 build_inputs.sort();
1372 let settings = serde_json::json!({
1375 "build_scripts": build_inputs,
1376 "analysis": &report.analysis, "package": &package.name, "jobs": effective_jobs,
1377 "verify": options.verify, "audit": options.audit, "effects": options.effects,
1378 "all_files": options.all_files, "build_scope": build_scope,
1379 "runners": runners.iter().map(|(name, runner, cwd)| (name, runner.executable(), cwd)).collect::<Vec<_>>()
1380 });
1381 let mut inputs = BTreeSet::new();
1382 for (root, artifacts) in &build.artifacts {
1383 inputs.insert(root.clone());
1384 if let Some(dependencies) = artifacts
1385 .iter()
1386 .map(|artifact| artifact_inputs(artifact, root, ©))
1387 .find(|deps| !deps.is_empty())
1388 {
1389 inputs.extend(dependencies);
1390 } else {
1391 inputs.extend(artifacts.iter().cloned());
1394 }
1395 }
1396 inputs.extend(
1397 build
1398 .build_scripts
1399 .iter()
1400 .filter_map(|script| script.get("out_dir")?.as_str().map(PathBuf::from)),
1401 );
1402 inputs.retain(|path| !path.starts_with(©));
1405 inputs.extend(
1406 options
1407 .output_fixtures
1408 .iter()
1409 .map(|fixture| build_target.join(&fixture.to)),
1410 );
1411 inputs.extend(
1412 options
1413 .stage_external
1414 .iter()
1415 .map(|entry| normalize(©.join(&entry.rel))),
1416 );
1417 Some(crate::campaign_identity::compute(
1418 ©,
1419 &settings,
1420 inputs,
1421 options.nextest.is_some(),
1422 )?)
1423 } else {
1424 None
1425 };
1426 let marks = marks_dir(&work)?;
1431 let baseline_jobs = if selection.enabled() {
1432 options.baseline_jobs
1433 } else {
1434 1
1435 };
1436 if options.progress {
1437 eprintln!(
1438 "tmt: baselines: 0/{} completed ({} workers)",
1439 runners.len(),
1440 baseline_jobs
1441 );
1442 }
1443
1444 session.binaries = progress::track_baselines(options.progress, runners.len(), |progress| {
1445 run_pool(runners.len(), baseline_jobs, |slot| {
1446 let index = slot;
1447 let (name, runner, cwd) = runners[index].clone();
1448 let result = (|| {
1449 let trace_path = work.join(format!("trace-{index}.tsv"));
1450 let _ = fs::remove_file(&trace_path);
1451 let mut bin = TestBinary {
1452 name,
1453 cwd,
1454 marks: marks.clone(),
1455 git_ceiling: work.clone(),
1456 work_lock: work_lock.clone(),
1457 tests: BTreeSet::new(),
1458 runner,
1459 baseline: Duration::ZERO,
1460 untraced_baseline: None,
1461 timeout_diagnostic: std::sync::Once::new(),
1462 traced: Duration::ZERO,
1463 timeout: options.timeout_seconds.map(Duration::from_secs),
1464 wrapper_grace: options.wrapper_grace,
1465 report_slow: options.progress,
1466 filtered_timings: Default::default(),
1467 trace: Trace::default(),
1468 effects_baseline: std::sync::OnceLock::new(),
1469 };
1470 session.note(&format!("tracing `{}`", bin.name));
1471 let started = Instant::now();
1472 let trace_env = trace_path.to_string_lossy().into_owned();
1473 let trace = [("TMT_TRACE", trace_env.as_str())];
1474 run_baseline(
1475 &bin,
1476 if options.source_only { &[] } else { &trace },
1477 Duration::from_secs(3600),
1478 &work.join(format!("baseline-{index}.log")),
1479 false,
1480 )?;
1481 bin.traced = started.elapsed();
1482 bin.baseline = bin.traced;
1483 if options.source_only {
1484 bin.untraced_baseline = Some(BaselineTiming::Completed(bin.baseline));
1485 }
1486 if !options.source_only && bin.traced > SLOW_TRACE {
1489 let started = Instant::now();
1490 let passed = run_baseline(
1491 &bin,
1492 &[],
1493 bin.traced,
1494 &work.join(format!("baseline-{index}-untraced.log")),
1495 true,
1496 )?;
1497 let elapsed = started.elapsed();
1498 if passed {
1499 bin.untraced_baseline = Some(BaselineTiming::Completed(elapsed));
1500 bin.baseline = elapsed;
1501 } else {
1502 bin.untraced_baseline = Some(BaselineTiming::StillRunning(bin.traced));
1503 }
1504 }
1505 let text = match fs::read_to_string(&trace_path) {
1508 Ok(text) => text,
1509 Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
1510 Err(err) => bail!("cannot read the trace of `{}`: {err}", bin.name),
1511 };
1512 bin.trace = Trace::parse(&text);
1513 if bin.trace.malformed_lines > 0 {
1514 bail!(
1515 "the trace of `{}` has {} malformed lines; not drawing conclusions from it",
1516 bin.name,
1517 bin.trace.malformed_lines
1518 );
1519 }
1520 if let Runner::Exe(exe) = &bin.runner {
1521 bin.tests =
1522 list_tests(exe, &bin.cwd, &work, false, false, work_lock.as_deref())?;
1523 }
1524 Ok(bin)
1525 })();
1526 progress.complete(if result.is_ok() {
1527 progress::Outcome::Survived
1528 } else {
1529 progress::Outcome::Failed
1530 });
1531 result
1532 })
1533 })?;
1534
1535 for file in &files {
1537 for site in &file.sites {
1538 if disabled.contains(&site.id) {
1539 let fallback = options.rebuild
1540 && !matches!(site.kind, SiteKind::Body { .. })
1541 && !instrument::source_mutants(site).is_empty();
1542 match site.kind {
1543 SiteKind::Body { .. } => report.unviable_mutants += 1,
1544 _ if fallback => {}
1545 _ => report.skipped_sites += 1,
1546 }
1547 report.skipped.push(report::SkippedSite::new(
1548 report::location(&file.display, site),
1549 file.lines.position(&file.original, site.end),
1550 if fallback {
1551 report::SkipReason::ProbeReplacedBySourceRebuild
1552 } else {
1553 report::SkipReason::ProbeCompileError
1554 },
1555 repairs.get(&site.id).cloned(),
1556 ));
1557 }
1558 }
1559 if !options.rebuild && !options.source_only {
1560 report.skipped.extend(file.rebuild_sites.iter().map(|site| {
1561 report::SkippedSite::new(
1562 report::location(&file.display, site),
1563 file.lines.position(&file.original, site.end),
1564 report::SkipReason::RequiresSourceRebuild,
1565 None,
1566 )
1567 }));
1568 }
1569 }
1570 if let (Some(checkpoint), Some(identity)) = (&checkpoint, &identity) {
1571 checkpoint.start(
1572 identity,
1573 serde_json::json!({
1574 "package": &package.name, "analysis": &report.analysis,
1575 "runners": session.binaries.iter().map(|bin| &bin.name).collect::<Vec<_>>(),
1576 "jobs": effective_jobs, "tool_version": env!("CARGO_PKG_VERSION")
1577 }),
1578 )?;
1579 }
1580 let phase = |name: &str, keys: Vec<String>| {
1581 checkpoint
1582 .as_ref()
1583 .zip(identity.as_deref())
1584 .map(|(checkpoint, identity)| checkpoint.begin(name, identity, keys))
1585 .transpose()
1586 };
1587 let probe_phase = |name: &str, jobs: &[Job]| -> Result<Option<Phase<'_>>> {
1588 if checkpoint.is_none() {
1589 return Ok(None);
1590 }
1591 let locations: BTreeMap<_, _> = files
1592 .iter()
1593 .flat_map(|file| {
1594 file.sites
1595 .iter()
1596 .map(|site| (site.id, (&file.display, site.line, site.column, &site.text)))
1597 })
1598 .collect();
1599 let keys = jobs
1600 .iter()
1601 .map(|job| {
1602 let tests = job
1603 .tests
1604 .iter()
1605 .map(|(bin, selected)| (&session.binaries[*bin].name, selected))
1606 .collect::<Vec<_>>();
1607 serde_json::to_string(&(locations.get(&job.site), job.mutation.encode(), tests))
1608 })
1609 .collect::<std::result::Result<Vec<_>, _>>()?;
1610 phase(name, keys)
1611 };
1612 let scratch = work.clone();
1613 let mut jobs: Vec<Job> = vec![];
1614 let mut not_evaluated: HashSet<u32> = HashSet::new();
1617 let mut site_work: Vec<SiteWork> = vec![];
1618 let mut effect_jobs: Vec<(usize, usize)> = vec![];
1620 for file in &files {
1621 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
1622 let primitive = |from: usize, to: usize| {
1625 let Some(mut text) = file.original.get(from..to) else {
1626 return false;
1627 };
1628 let mut start = from;
1629 loop {
1630 let trimmed = text.trim_start();
1631 start += text.len() - trimmed.len();
1632 text = trimmed.trim_end();
1633 if matches!(syn::parse_str::<syn::Expr>(text), Ok(syn::Expr::Paren(_)))
1634 && let Some(inner) = text
1635 .strip_prefix('(')
1636 .and_then(|inner| inner.strip_suffix(')'))
1637 {
1638 start += 1;
1639 text = inner;
1640 } else {
1641 break;
1642 }
1643 }
1644 file.sites.iter().any(|other| {
1645 matches!(other.kind, SiteKind::Arith { .. })
1646 && other.start == start
1647 && other.end == start + text.len()
1648 && !disabled.contains(&other.id)
1649 && {
1650 let seen =
1651 session.merged(|t| t.arith.get(&other.id), plan::ArithObs::merge);
1652 !seen.opaque
1653 && (seen.same || seen.differs || seen.same2 || seen.differs2)
1654 }
1655 })
1656 };
1657 let cast_bounds = |from: usize, to: usize| -> Option<(i128, i128)> {
1658 let (owner_id, slot) = file.sites.iter().find_map(|other| {
1659 if disabled.contains(&other.id) {
1660 return None;
1661 }
1662 let SiteKind::Arith { cast_probes, .. } = &other.kind else {
1663 return None;
1664 };
1665 cast_probes
1666 .iter()
1667 .find(|&&(_, start, end)| start == from && end == to)
1668 .map(|&(slot, _, _)| (other.id, slot))
1669 })?;
1670 let mut recorded = session
1671 .binaries
1672 .iter()
1673 .filter_map(|b| b.trace.cast_bounds.get(&(owner_id, slot)));
1674 let first = recorded.next()?;
1675 if recorded.all(|other| other == first) {
1676 *first
1677 } else {
1678 None
1679 }
1680 };
1681 let plan = match session.plan(
1682 &file.display,
1683 site,
1684 options.verify,
1685 &primitive,
1686 &cast_bounds,
1687 ) {
1688 Planned::Unreached if beyond.contains(&site.id) => continue,
1691 Planned::Unreached => {
1692 let at = report::location(&file.display, site);
1694 if report.unreached.last() != Some(&at) {
1695 report.unreached.push(at);
1696 }
1697 continue;
1698 }
1699 Planned::Nothing => continue,
1700 Planned::NotEvaluated => {
1701 not_evaluated.insert(site.id);
1702 continue;
1703 }
1704 Planned::Plan(plan) => plan,
1705 };
1706 let mut add =
1707 |mutation: Mutation, tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>| {
1708 jobs.push(session.job(site.id, mutation, tests_of));
1709 jobs.len() - 1
1710 };
1711 let gaps = plan
1712 .gaps
1713 .into_iter()
1714 .map(
1715 |PlannedGap {
1716 finding,
1717 survivors,
1718 constant_expr,
1719 }| {
1720 let confirm = if options.verify {
1723 survivors
1724 .into_iter()
1725 .map(|m| add(m, &*plan.reaching))
1726 .collect()
1727 } else {
1728 vec![]
1729 };
1730 (finding, confirm, constant_expr)
1731 },
1732 )
1733 .collect();
1734 let infected = &plan.infected;
1735 let runs = plan
1736 .run
1737 .iter()
1738 .map(|m| (*m, add(*m, &|bin| infected(bin, *m))))
1739 .collect();
1740 site_work.push(SiteWork {
1741 file: &file.display,
1742 site,
1743 gaps,
1744 constant: plan.constant,
1745 cannot_differ: plan.cannot_differ,
1746 redundant_logic_swap: plan.redundant_logic_swap,
1747 runs,
1748 });
1749 }
1750 }
1751 session.note(&format!(
1752 "running {} mutants on {} thread(s)",
1753 jobs.len(),
1754 options.jobs.max(1)
1755 ));
1756 let probe_checkpoint = probe_phase("probe", &jobs)?;
1757 let mut results =
1758 session.run_jobs(&jobs, options.jobs, "mutants", probe_checkpoint.as_ref())?;
1759 for result in &results {
1760 report.timeout_rechecks.include(result);
1761 }
1762
1763 if let Some(wanted) = options.audit {
1766 report.audit = Some(run_audit_phase(
1767 &session,
1768 &files,
1769 &jobs,
1770 &mut results,
1771 &mut report.timeout_rechecks,
1772 &scratch,
1773 wanted,
1774 options.jobs,
1775 &probe_phase,
1776 )?);
1777 }
1778 #[derive(Clone, Copy, PartialEq, Eq)]
1782 enum EarlierVerdict {
1783 Killed,
1784 Survived,
1785 Unknown,
1786 }
1787 let mut earlier_verdict: BTreeMap<usize, EarlierVerdict> = BTreeMap::new();
1788 let asked: Vec<usize> = site_work
1789 .iter()
1790 .filter(|item| beyond.contains(&item.site.id))
1791 .flat_map(|item| {
1792 item.gaps
1793 .iter()
1794 .flat_map(|(_, confirm, _)| confirm.iter().copied())
1795 .chain(
1796 item.runs
1797 .iter()
1798 .filter(|(m, _)| !(*m == Mutation::LogicSwap && item.redundant_logic_swap))
1799 .map(|(_, job)| *job),
1800 )
1801 })
1802 .filter(|job| results[*job].survived.is_some())
1803 .collect();
1804 if !asked.is_empty() {
1805 let revision = report::short_revision(options.since.as_deref().unwrap_or_default());
1806 session.note(&format!(
1807 "running {} surviving mutants against the tests as they were at {revision}",
1808 asked.len()
1809 ));
1810 let suffix = |file: &SourceFile| {
1811 if file.path == root_file {
1812 root_suffix.as_str()
1813 } else {
1814 ""
1815 }
1816 };
1817 let earlier: Option<Vec<(&SourceFile, String)>> = tests_changed
1819 .iter()
1820 .map(|(path, hunks)| {
1821 let file = files.iter().find(|file| file.path == *path)?;
1822 let rendered = file.rendered.as_ref()?;
1823 let mut places = hunks
1824 .iter()
1825 .map(|hunk| {
1826 let (from, to) = scope::range_of(&file.original, hunk);
1827 Some((rendered.copied(from, to)?, hunk.old.as_str()))
1828 })
1829 .collect::<Option<Vec<_>>>()?;
1830 places.sort_by_key(|((from, _), _)| std::cmp::Reverse(*from));
1831 let mut text = rendered.text.clone();
1832 for ((from, to), old) in places {
1833 text.replace_range(from..to, old);
1834 }
1835 Some((file, text))
1836 })
1837 .collect();
1838 let attempted = if let Some(earlier) = earlier {
1839 let attempted = (|| -> Result<Option<Vec<JobResult>>> {
1840 for (file, text) in &earlier {
1841 state.write(&file.path, &format!("{text}{}", suffix(file)))?;
1842 }
1843 if !cargo_build()?.status.success() {
1844 session.note(
1845 "the tests as they were do not build with the code as it is: what they found out is not known",
1846 );
1847 return Ok(None);
1848 }
1849 let all: Vec<&TestBinary> = session.binaries.iter().collect();
1851 if run_source_tests(&all)? != Outcome::Pass {
1852 session.note(
1853 "the tests as they were fail on the code as it is: what they found out is not known",
1854 );
1855 return Ok(None);
1856 }
1857 let against_all: Vec<Job> = asked
1858 .iter()
1859 .map(|job| Job {
1860 site: jobs[*job].site,
1861 mutation: jobs[*job].mutation,
1862 tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
1863 })
1864 .collect();
1865 session
1866 .run_jobs(&against_all, options.jobs, "mutants, earlier tests", None)
1867 .map(Some)
1868 })();
1869 for (file, _) in &earlier {
1871 let rendered = file.rendered.as_ref().expect("rendered before building");
1872 state.write(&file.path, &format!("{}{}", rendered.text, suffix(file)))?;
1873 }
1874 if !cargo_build()?.status.success() {
1875 bail!("the crate does not build once its tests are put back as they are");
1876 }
1877 attempted
1878 } else {
1879 session.note(
1880 "not all changed test files could be restored as they were: what they found out is not known",
1881 );
1882 Ok(None)
1883 };
1884 if let Some(again) = attempted? {
1885 for (job, result) in asked.iter().zip(again) {
1886 let verdict = if result.unable || result.unconfirmed_timeout {
1887 EarlierVerdict::Unknown
1888 } else if result.survived.is_none() {
1889 EarlierVerdict::Killed
1890 } else {
1891 EarlierVerdict::Survived
1892 };
1893 earlier_verdict.insert(*job, verdict);
1894 }
1895 } else {
1896 for job in &asked {
1897 earlier_verdict.insert(*job, EarlierVerdict::Unknown);
1898 }
1899 }
1900 }
1901 let unable = results
1902 .iter()
1903 .filter(|r| r.unable || r.unconfirmed_timeout)
1904 .count();
1905 not_evaluated.extend(
1906 jobs.iter()
1907 .zip(&results)
1908 .filter(|(_, result)| result.unable || result.unconfirmed_timeout)
1909 .map(|(job, _)| job.site),
1910 );
1911 if !options.rebuild {
1912 report.mutants_not_evaluated = not_evaluated.len();
1913 }
1914 report.mutants_run = results.len() - unable;
1915 report.mutants_killed = results.iter().filter(|r| r.survived.is_none()).count() - unable;
1916 report.mutants_survived = report.mutants_run - report.mutants_killed;
1917 report.mutants_timed_out = results
1918 .iter()
1919 .filter(|r| r.timed_out && !r.unconfirmed_timeout)
1920 .count();
1921
1922 let mut finding_run_survivors: Vec<usize> = vec![];
1925
1926 let confirmed = |w: &SiteWork| {
1929 w.gaps
1930 .iter()
1931 .all(|(_, confirm, _)| confirm.iter().all(|j| results[*j].survived.is_some()))
1932 };
1933 let constants: BTreeSet<(&str, usize, usize)> = site_work
1934 .iter()
1935 .filter(|w| w.cannot_differ || (w.constant && confirmed(w)))
1936 .map(|w| (w.file, w.site.start, w.site.end))
1937 .collect();
1938 for item in &site_work {
1939 let at = report::location(item.file, item.site);
1940 for (finding, confirm, constant_expr) in &item.gaps {
1941 let repeats = constant_expr
1944 .is_some_and(|(start, end)| constants.contains(&(item.file, start, end)));
1945 let survived_count = confirm
1946 .iter()
1947 .filter(|j| results[**j].survived.is_some())
1948 .count();
1949 if beyond.contains(&item.site.id) {
1950 let confirmed = confirm.iter().all(|j| results[*j].survived.is_some());
1952 let killed_before = confirm
1953 .iter()
1954 .any(|j| earlier_verdict.get(j) == Some(&EarlierVerdict::Killed));
1955 if confirmed && !repeats && killed_before {
1956 report.weakened.push(finding.at().clone());
1957 report.findings.push(finding.clone());
1958 finding_run_survivors.push(survived_count);
1959 } else if !confirmed {
1960 report.survivor_breakdown.unconfirmed_gap += survived_count;
1961 } else if repeats {
1962 report.survivor_breakdown.redundant_constant += survived_count;
1963 } else {
1964 for job in confirm {
1965 if results[*job].survived.is_some() {
1966 if earlier_verdict.get(job) == Some(&EarlierVerdict::Survived) {
1967 report.survivor_breakdown.preexisting_unchanged += 1;
1968 } else {
1969 report.survivor_breakdown.unchanged_not_compared += 1;
1970 }
1971 }
1972 }
1973 }
1974 continue;
1975 }
1976 match Prediction::of(confirm.iter().map(|j| &results[*j])) {
1977 Prediction::Refuted => {
1978 report.unstable.push(at.clone());
1979 report.survivor_breakdown.unconfirmed_gap += survived_count;
1980 }
1981 Prediction::Confirmed if !repeats => {
1982 report.findings.push(finding.clone());
1983 finding_run_survivors.push(survived_count);
1984 }
1985 Prediction::Confirmed => {
1986 report.survivor_breakdown.redundant_constant += survived_count;
1987 }
1988 Prediction::Unknown => {
1990 report.survivor_breakdown.unconfirmed_gap += survived_count;
1991 }
1992 }
1993 }
1994 if let SiteKind::Body {
1997 sole_expr: Some((start, end)),
1998 ..
1999 } = item.site.kind
2000 && constants.contains(&(item.file, start, end))
2001 {
2002 report.survivor_breakdown.redundant_constant += item
2003 .runs
2004 .iter()
2005 .filter(|(_, job)| results[*job].survived.is_some())
2006 .count();
2007 continue;
2008 }
2009 let mut survivors = vec![];
2010 let mut passing_tests = BTreeSet::new();
2011 for (mutation, job) in &item.runs {
2012 if let Some(tests) = &results[*job].survived {
2013 if *mutation == Mutation::LogicSwap && item.redundant_logic_swap {
2014 report.survivor_breakdown.redundant_constant += 1;
2015 continue;
2016 }
2017 if beyond.contains(&item.site.id) {
2018 match earlier_verdict.get(job) {
2019 Some(EarlierVerdict::Killed) => {}
2020 Some(EarlierVerdict::Survived) => {
2021 report.survivor_breakdown.preexisting_unchanged += 1;
2022 continue;
2023 }
2024 Some(EarlierVerdict::Unknown) | None => {
2025 report.survivor_breakdown.unchanged_not_compared += 1;
2026 continue;
2027 }
2028 }
2029 }
2030 survivors.push(report::describe(item.site, *mutation));
2031 passing_tests.extend(tests.iter().cloned());
2032 }
2033 }
2034 if !survivors.is_empty() {
2035 let first = item.runs.iter().find(|(mutation, job)| {
2037 !(*mutation == Mutation::LogicSwap && item.redundant_logic_swap)
2038 && results[*job].survived.is_some()
2039 && (!beyond.contains(&item.site.id)
2040 || earlier_verdict.get(job) == Some(&EarlierVerdict::Killed))
2041 });
2042 if beyond.contains(&item.site.id) {
2043 report.weakened.push(at.clone());
2044 }
2045 effect_jobs.push((report.findings.len(), first.expect("a survivor").1));
2046 finding_run_survivors.push(survivors.len());
2047 report.findings.push(Finding::AssertionGap {
2048 at,
2049 survivors,
2050 tests: passing_tests.into_iter().collect(),
2051 effects: vec![],
2052 effects_of: None,
2053 witness: None,
2054 });
2055 }
2056 }
2057
2058 if options.effects && !effect_jobs.is_empty() {
2060 run_effects_phase(
2061 &session,
2062 &files,
2063 &jobs,
2064 &effect_jobs,
2065 &scratch,
2066 options.jobs,
2067 &mut report.findings,
2068 )?;
2069 }
2070
2071 let mut built: Vec<(&SourceFile, &Site, instrument::SourceMutant, Option<usize>)> = vec![];
2075 let build_regular_mutants = options.rebuild || options.source_only;
2076 let mut index = 0;
2077 for file in &files {
2078 let retried = file.sites.iter().filter(|site| {
2081 (disabled.contains(&site.id) && !matches!(site.kind, SiteKind::Body { .. }))
2082 || not_evaluated.contains(&site.id)
2083 });
2084 for site in file.rebuild_sites.iter().chain(retried) {
2085 let mutants = source_mutants(file, site, true);
2086 if build_regular_mutants {
2087 built.extend(mutants.into_iter().filter_map(|mutant| {
2088 let selected = in_shard(index);
2089 index += 1;
2090 selected.then_some((file, site, mutant, None))
2091 }));
2092 } else {
2093 report.mutants_not_built += mutants.len();
2094 }
2095 }
2096 }
2097 if let (Some(wanted), Some(audit)) = (options.audit, report.audit.as_mut()) {
2100 let mut twins = vec![];
2101 for file in &files {
2102 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
2103 let integers = session.binaries.iter().all(|bin| {
2105 let seen = bin.trace.merged(site.id);
2106 !seen.reached() || seen.valued()
2107 });
2108 let candidates = jobs_for_site(&jobs, site.id);
2109 let job_of = |mutation: Mutation| {
2110 candidates
2111 .clone()
2112 .find(|&index| jobs[index].mutation == mutation)
2113 };
2114 let mut compared = vec![];
2115 let mut mutants = instrument::source_mutants(site);
2116 instrument::keep_line_ends(&file.original, &mut mutants);
2117 for mutant in mutants {
2118 let job = mutations_like(site, &mutant, integers)
2120 .into_iter()
2121 .find_map(job_of);
2122 if let Some(job) = job {
2123 compared.push(job);
2124 twins.push((file, site, mutant, Some(job)));
2125 }
2126 }
2127 if let (SiteKind::Cmp { op, .. }, Some(job)) =
2130 (&site.kind, job_of(Mutation::Negate))
2131 && !compared.contains(&job)
2132 {
2133 let negated = instrument::SourceMutant {
2134 start: site.start,
2135 end: site.end,
2136 replacement: format!("!({})", site.text),
2137 what: op.symbol().to_string(),
2138 into: "!".to_string(),
2139 };
2140 twins.push((file, site, negated, Some(job)));
2141 }
2142 }
2143 }
2144 let chosen = spread(twins.len(), wanted);
2145 audit.rebuilt = chosen.len();
2146 let mut twins: Vec<Option<_>> = twins.into_iter().map(Some).collect();
2147 built.extend(chosen.into_iter().filter_map(|nth| twins[nth].take()));
2148 }
2149 let mut by_speed: Vec<&TestBinary> = session.binaries.iter().collect();
2150 by_speed.sort_by_key(|bin| bin.baseline);
2151 let root_mutant_suffix = if files.iter().any(|file| {
2153 file.path != root_file
2154 && file
2155 .rendered
2156 .as_ref()
2157 .is_some_and(|rendered| rendered.text != file.original)
2158 }) {
2159 root_suffix.as_str()
2160 } else {
2161 ""
2162 };
2163 if !built.is_empty() {
2164 if options.timeout_seconds.is_some()
2165 && built
2166 .iter()
2167 .any(|(file, _, _, _)| built_sources.contains(file))
2168 {
2169 for bin in &by_speed {
2170 bin.warn_timeout_conflict(None);
2171 }
2172 }
2173 let source_checkpoint = if checkpoint.is_some() {
2174 let keys = built
2175 .iter()
2176 .map(|(file, _, mutation, twin)| {
2177 serde_json::to_string(&(
2178 &file.display,
2179 mutation.start,
2180 mutation.end,
2181 &mutation.replacement,
2182 twin,
2183 ))
2184 })
2185 .collect::<std::result::Result<Vec<_>, _>>()?;
2186 phase("source", keys)?
2187 } else {
2188 None
2189 };
2190 session.note(&format!(
2191 "building {} mutants one by one (code a probe cannot be put in, or to compare with the probe)",
2192 built.len()
2193 ));
2194 let instrumented = |file: &SourceFile, text: &str, suffix: &str| {
2195 if file.path == root_file {
2196 format!("{text}{suffix}")
2197 } else {
2198 text.to_string()
2199 }
2200 };
2201 let mut skipped_targets = BTreeSet::new();
2204 let mut left_out: BTreeMap<&PathBuf, Vec<(usize, usize)>> = BTreeMap::new();
2206 let mut survivors: Vec<(report::Location, Vec<String>)> = vec![];
2207 progress::track(
2208 options.progress,
2209 "source mutants",
2210 built.len(),
2211 |progress| -> Result<()> {
2212 for (index, (file, site, mutant, twin)) in built.iter().enumerate() {
2213 let cached = source_checkpoint
2214 .as_ref()
2215 .map(|phase| phase.get::<Option<Outcome>>(index))
2216 .transpose()?
2217 .flatten();
2218 let left_out = left_out
2219 .entry(&file.path)
2220 .or_insert_with(|| built_sources.left_out(file))
2221 .iter()
2222 .any(|(from, to)| *from <= site.start && site.end <= *to);
2223 if left_out || !built_sources.contains(file) {
2224 if let Some(phase) = source_checkpoint.as_ref().filter(|_| cached.is_none())
2225 {
2226 phase.record(index, &Some(Outcome::Unable))?;
2227 }
2228 if twin.is_none() {
2229 report.mutants_not_evaluated += 1;
2230 report.mutants_not_compiled += 1;
2231 if skipped_targets.insert((&file.path, site.start, site.end)) {
2232 report.skipped.push(report::SkippedSite::new(
2233 report::location(&file.display, site),
2234 file.lines.position(&file.original, site.end),
2235 report::SkipReason::SourceNotBuilt,
2236 left_out.then(|| {
2237 "under a `cfg` that the features of this build turn off"
2238 .to_string()
2239 }),
2240 ));
2241 }
2242 } else if let Some(audit) = report.audit.as_mut() {
2243 audit.not_compared += 1;
2244 }
2245 progress.complete(progress::Outcome::Unable);
2246 continue;
2247 }
2248 let outcome = if let Some(cached) = cached {
2249 cached
2250 } else {
2251 let mutated = format!(
2252 "{}{}{}",
2253 &file.original[..mutant.start],
2254 mutant.replacement,
2255 &file.original[mutant.end..]
2256 );
2257 let attempt = || -> Result<Option<Outcome>> {
2259 state.write(
2260 &file.path,
2261 &instrumented(file, &mutated, root_mutant_suffix),
2262 )?;
2263 match source_build(&cargo_build()?) {
2264 SourceBuild::Built => run_source_tests(&by_speed).map(Some),
2265 SourceBuild::Refused => Ok(None),
2266 SourceBuild::Failed(why) => {
2269 session.note(&format!(
2270 "a build failed without the compiler refusing the code; its mutant is not evaluated: {why}"
2271 ));
2272 Ok(Some(Outcome::Unable))
2273 }
2274 }
2275 };
2276 let attempted = attempt();
2277 let rendered = file.rendered.as_ref().expect("rendered before building");
2279 state.write(
2280 &file.path,
2281 &instrumented(file, &rendered.text, &root_suffix),
2282 )?;
2283 let outcome = attempted?;
2284 if let Some(phase) = &source_checkpoint
2287 && outcome != Some(Outcome::Unable)
2288 {
2289 phase.record(index, &outcome)?;
2290 }
2291 outcome
2292 };
2293 progress.complete(outcome.map_or(progress::Outcome::Unable, Into::into));
2294 if let Some(job) = twin {
2295 let as_probe = results[*job].survived.is_some();
2297 let Some(audit) = report.audit.as_mut() else {
2298 continue;
2299 };
2300 match audit_source_comparison(&results[*job], outcome) {
2303 Some(disagrees) => {
2304 audit.compared += 1;
2305 if disagrees {
2306 let verdict =
2307 |passes: bool| if passes { "passes" } else { "fails" };
2308 audit.source_disagreements.push(report::SourceDisagreement {
2309 at: report::location(&file.display, site),
2310 mutant: report::describe(site, mutation_of(site, mutant)),
2311 as_probe: verdict(as_probe).to_string(),
2312 built: verdict(!as_probe).to_string(),
2313 });
2314 }
2315 }
2316 None => audit.not_compared += 1,
2317 }
2318 continue;
2319 }
2320 match outcome {
2321 None => report.unviable_mutants += 1,
2322 Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
2323 Some(outcome) => {
2324 report.mutants_run += 1;
2325 report.mutants_killed += (outcome != Outcome::Pass) as usize;
2326 report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
2327 report.mutants_survived += (outcome == Outcome::Pass) as usize;
2328 }
2329 }
2330 let survived = outcome == Some(Outcome::Pass);
2331 if survived {
2332 let at = report::location(&file.display, site);
2333 let removed = mutant.replacement.trim().is_empty();
2335 let text = match (&site.kind, removed) {
2336 (SiteKind::Field { .. }, true) => {
2337 format!("without the field `{}`", report::one_line(&site.text))
2338 }
2339 (
2340 SiteKind::LiteralSet {
2341 receiver, argument, ..
2342 },
2343 true,
2344 ) => format!(
2345 "without `{}` in `{}.contains({})`",
2346 report::one_line(&mutant.into),
2347 report::one_line(receiver),
2348 report::one_line(argument)
2349 ),
2350 _ => report::describe(site, mutation_of(site, mutant)),
2351 };
2352 match survivors.last_mut() {
2353 Some((last, texts)) if *last == at => texts.push(text),
2354 _ => survivors.push((at, vec![text])),
2355 }
2356 }
2357 }
2358 Ok(())
2359 },
2360 )?;
2361 if let Some(phase) = &source_checkpoint {
2362 phase.finish_if_complete()?;
2363 }
2364 for (at, survivors) in survivors {
2365 finding_run_survivors.push(survivors.len());
2366 report.findings.push(Finding::Survivor {
2367 at,
2368 survivors,
2369 witness: None,
2370 change_since: None,
2371 advice: None,
2372 });
2373 }
2374 }
2375
2376 if let Some(revision) = options
2378 .since
2379 .as_deref()
2380 .filter(|_| !options.list && options.shard.is_none())
2381 {
2382 let hunks = scope::hunks(&since_diff(&workspace, revision)?);
2383 let not_built_changes = std::cell::Cell::new(0usize);
2384 let changed: Vec<(&SourceFile, Vec<reverts::Change>)> = files
2385 .iter()
2386 .filter(|file| built_sources.contains(file) || !options.source_only && !options.rebuild)
2387 .filter_map(|file| {
2388 let relative = file
2389 .path
2390 .strip_prefix(©)
2391 .ok()?
2392 .to_string_lossy()
2393 .replace('\\', "/");
2394 let of_file: Vec<_> = hunks
2395 .iter()
2396 .filter(|hunk| hunk.file == relative)
2397 .cloned()
2398 .collect();
2399 let mut changes = reverts::changes(&file.original, &of_file);
2400 if options.rebuild || options.source_only {
2403 for change in &mut changes {
2404 change.outside = change.undone.as_deref().is_some_and(|undone| {
2407 built_sources.same_program(file, &file.original, undone)
2408 });
2409 }
2410 not_built_changes.set(
2411 not_built_changes.get()
2412 + changes.iter().filter(|change| change.outside).count(),
2413 );
2414 }
2415 (!changes.is_empty()).then_some((file, changes))
2416 })
2417 .collect();
2418 let not_built_changes = not_built_changes.get();
2419 report.mutants_not_evaluated += not_built_changes;
2420 report.mutants_not_compiled += not_built_changes;
2421 let total: usize = changed
2423 .iter()
2424 .map(|(_, changes)| changes.iter().filter(|change| !change.outside).count())
2425 .sum();
2426 let mixed: usize = files
2429 .iter()
2430 .map(|file| {
2431 let relative = file
2432 .path
2433 .strip_prefix(©)
2434 .unwrap_or(&file.path)
2435 .to_string_lossy()
2436 .replace('\\', "/");
2437 let of_file: Vec<_> = hunks
2438 .iter()
2439 .filter(|hunk| hunk.file == relative)
2440 .cloned()
2441 .collect();
2442 reverts::mixed(&file.original, &of_file)
2443 })
2444 .sum();
2445 if mixed > 0 && (options.rebuild || options.source_only) {
2446 report.mutants_not_evaluated += mixed;
2447 session.note(&format!(
2448 "{mixed} changes are of the program and its tests in the same lines: they are not tried undone"
2449 ));
2450 }
2451 if !(options.rebuild || options.source_only) {
2452 report.mutants_not_built += not_built_reverts;
2453 } else if total > 0
2454 || changed.iter().any(|(_, changes)| {
2455 changes.iter().filter(|change| !change.is_subhunk()).count() > 1
2456 })
2457 {
2458 session.note(&format!(
2461 "building {total} changes undone, one by one (the code as it was at {})",
2462 report::short_revision(revision)
2463 ));
2464 let write = |file: &SourceFile, text: &str, suffix: &str| -> Result<()> {
2465 let suffix = if file.path == root_file { suffix } else { "" };
2466 state.write(&file.path, &format!("{text}{suffix}"))
2467 };
2468 let undone = |edits: &[(&SourceFile, &str)]| -> Result<Option<Outcome>> {
2470 let attempted = (|| -> Result<Option<Outcome>> {
2471 for (file, text) in edits {
2472 write(file, text, root_mutant_suffix)?;
2473 }
2474 Ok(match source_build(&cargo_build()?) {
2475 SourceBuild::Built => Some(run_source_tests(&by_speed)?),
2476 SourceBuild::Refused => None,
2477 SourceBuild::Failed(why) => {
2478 session.note(&format!(
2479 "a build failed without the compiler refusing the code; the change undone is not evaluated: {why}"
2480 ));
2481 Some(Outcome::Unable)
2482 }
2483 })
2484 })();
2485 for (file, _) in edits {
2487 let rendered = file.rendered.as_ref().expect("rendered before building");
2488 write(file, &rendered.text, &root_suffix)?;
2489 }
2490 attempted
2491 };
2492 let mut judged = |outcome: Option<Outcome>, at: report::Location, what: String| {
2493 match outcome {
2494 None => report.unviable_mutants += 1,
2495 Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
2496 Some(outcome) => {
2497 report.mutants_run += 1;
2498 report.mutants_killed += (outcome != Outcome::Pass) as usize;
2499 report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
2500 report.mutants_survived += (outcome == Outcome::Pass) as usize;
2501 }
2502 }
2503 if outcome == Some(Outcome::Pass) {
2504 finding_run_survivors.push(1);
2505 report.findings.push(Finding::Survivor {
2506 at,
2507 survivors: vec![what],
2508 witness: None,
2509 advice: None,
2510 change_since: Some(revision.to_string()),
2511 });
2512 }
2513 };
2514 let place = |file: &SourceFile, change: &reverts::Change| report::Location {
2515 file: file.display.clone(),
2516 line: change.line,
2517 column: 1,
2518 code: change.code.clone(),
2519 ..Default::default()
2520 };
2521 let mut stuck_files = 0;
2524 for (file, changes) in &changed {
2525 let mut stuck = false;
2526 let whole_total = changes.iter().filter(|change| !change.is_subhunk()).count();
2527 let whole_alone = changes
2528 .iter()
2529 .filter(|change| !change.is_subhunk() && !change.outside)
2530 .count();
2531 for change in changes.iter().filter(|change| !change.outside) {
2532 let outcome = match &change.undone {
2533 Some(text) => undone(&[(file, text.as_str())])?,
2534 None => None,
2535 };
2536 if !change.is_subhunk() {
2537 stuck |= outcome.is_none();
2538 }
2539 judged(outcome, place(file, change), change.describe());
2540 }
2541 let whole = reverts::all_undone(&file.original, changes);
2546 let same = |a: &str, b: &str| built_sources.same_program(file, a, b);
2547 let tried: Vec<reverts::Change> = changes
2548 .iter()
2549 .filter(|change| !change.outside)
2550 .cloned()
2551 .collect();
2552 let left_out_matter = whole_alone < whole_total
2553 && match (&whole, reverts::all_undone(&file.original, &tried)) {
2554 (Some(all), Some(without)) => !same(all, &without),
2555 _ => true,
2556 };
2557 let another = whole
2559 .as_deref()
2560 .is_none_or(|all| !same(all, &file.original));
2561 if whole_total > 1 && another && (stuck || left_out_matter) {
2562 let outcome = match &whole {
2563 Some(text) => undone(&[(file, text.as_str())])?,
2564 None => None,
2565 };
2566 stuck = outcome.is_none();
2567 let first_whole = changes
2568 .iter()
2569 .find(|change| !change.is_subhunk())
2570 .unwrap_or(&changes[0]);
2571 judged(
2572 outcome,
2573 place(file, first_whole),
2574 format!("with all {whole_total} changes to this file undone"),
2575 );
2576 }
2577 stuck_files += usize::from(stuck);
2578 }
2579 let with_left_out = changed.iter().any(|(_, changes)| {
2583 changes
2584 .iter()
2585 .any(|change| !change.is_subhunk() && change.outside)
2586 });
2587 if (stuck_files > 0 || with_left_out) && changed.len() > 1 {
2588 let whole: Option<Vec<String>> = changed
2589 .iter()
2590 .map(|(file, changes)| reverts::all_undone(&file.original, changes))
2591 .collect();
2592 let same =
2593 |file: &SourceFile, a: &str, b: &str| built_sources.same_program(file, a, b);
2594 let another = whole.as_ref().is_none_or(|texts| {
2596 changed
2597 .iter()
2598 .zip(texts)
2599 .any(|((file, _), text)| !same(file, text, &file.original))
2600 });
2601 let left_out_matter = whole.as_ref().is_none_or(|texts| {
2604 changed.iter().zip(texts).any(|((file, changes), text)| {
2605 let tried: Vec<reverts::Change> = changes
2606 .iter()
2607 .filter(|change| !change.outside)
2608 .cloned()
2609 .collect();
2610 reverts::all_undone(&file.original, &tried)
2611 .is_none_or(|without| !same(file, text, &without))
2612 })
2613 });
2614 if another && (stuck_files > 0 || (with_left_out && left_out_matter)) {
2615 let outcome = match &whole {
2616 Some(texts) => {
2617 let edits: Vec<(&SourceFile, &str)> = changed
2618 .iter()
2619 .zip(texts)
2620 .map(|((file, _), text)| (*file, text.as_str()))
2621 .collect();
2622 undone(&edits)?
2623 }
2624 None => None,
2625 };
2626 let (file, changes) = &changed[0];
2627 judged(
2628 outcome,
2629 place(file, &changes[0]),
2630 format!("with every change undone, in all {} files", changed.len()),
2631 );
2632 }
2633 }
2634 }
2635 }
2636
2637 let mut witness_files: Vec<&PathBuf> = vec![];
2640 for candidate in &witness_candidates {
2641 if !witness_files.contains(&&candidate.file) {
2642 witness_files.push(&candidate.file);
2643 }
2644 }
2645 for witness_file in witness_files {
2646 let in_root = *witness_file == root_file;
2647 let witness_candidates: Vec<&witness::Candidate> = witness_candidates
2648 .iter()
2649 .filter(|candidate| candidate.file == *witness_file)
2650 .collect();
2651 let file = files
2652 .iter()
2653 .find(|file| file.path == *witness_file)
2654 .expect("witness candidates are of files that are analysed");
2655 let rendered = file.rendered.as_ref().expect("rendered before building");
2656 let left_out_here = built_sources.left_out(file);
2657 let restore = if in_root {
2658 format!("{}{root_suffix}", rendered.text)
2659 } else {
2660 rendered.text.clone()
2661 };
2662 let library_runners: Vec<_> = session
2663 .binaries
2664 .iter()
2665 .filter(|bin| {
2666 root_exe
2667 .as_deref()
2668 .is_some_and(|exe| bin.runner.executable() == Some(exe))
2669 })
2670 .collect();
2671 let ignored = library_runners
2672 .iter()
2673 .find_map(|bin| match &bin.runner {
2674 Runner::Exe(exe) => Some(list_tests(
2675 exe,
2676 &bin.cwd,
2677 &bin.git_ceiling,
2678 true,
2679 false,
2680 bin.work_lock.as_deref(),
2681 )),
2682 _ => None,
2683 })
2684 .transpose()?
2685 .unwrap_or_default();
2686 let runner_for = |scenario: &witness::Scenario| {
2687 library_runners.iter().copied().find(|bin| {
2688 scenario
2689 .source_test
2690 .as_ref()
2691 .is_none_or(|required| match &bin.runner {
2692 Runner::Exe(_) if !in_root => {
2695 let inner = format!("::{required}");
2696 bin.tests
2697 .iter()
2698 .any(|test| test.ends_with(&inner) && !ignored.contains(test))
2699 }
2700 Runner::Exe(_) => {
2701 bin.tests.contains(required) && !ignored.contains(required)
2702 }
2703 Runner::Isolated { test, .. } if !in_root => {
2704 test.ends_with(&format!("::{required}"))
2705 }
2706 Runner::Isolated { test, .. } => test == required,
2707 Runner::Doc { .. } | Runner::Nextest { .. } => false,
2708 })
2709 })
2710 };
2711 let write_edits = |edits: &[witness::Edit]| -> Result<bool> {
2712 let Some(source) = witness::render_edits(&file.original, edits, None) else {
2713 return Ok(false);
2714 };
2715 let suffix = if in_root { root_mutant_suffix } else { "" };
2716 state.write(&file.path, &format!("{source}{suffix}"))?;
2717 Ok(true)
2718 };
2719 let suite = |edits: &[witness::Edit]| -> Result<Option<Outcome>> {
2720 if !write_edits(edits)? {
2721 return Ok(None);
2722 }
2723 Ok(match source_build(&cargo_build()?) {
2724 SourceBuild::Built => Some(run_source_tests(&by_speed)?),
2725 SourceBuild::Refused => None,
2726 SourceBuild::Failed(why) => {
2727 session.note(&format!(
2728 "a build failed without the compiler refusing the code; the mutant is not evaluated: {why}"
2729 ));
2730 Some(Outcome::Unable)
2731 }
2732 })
2733 };
2734 let compile_observer = |edits: &[witness::Edit]| -> Result<Option<PathBuf>> {
2735 if !write_edits(edits)? {
2736 return Ok(None);
2737 }
2738 let build = build_test_binaries(true)?;
2739 if !build.status.success() {
2740 return Ok(None);
2741 }
2742 let artifacts = parse_build_output(
2743 &String::from_utf8_lossy(&build.stdout),
2744 &[package.name.as_str()],
2745 );
2746 Ok(root_test_exe(&artifacts))
2747 };
2748 let observe = |scenario: &witness::Scenario,
2749 baseline: &TestBinary,
2750 edits: &[witness::Edit],
2751 field_path: Option<&str>,
2752 expected: Option<&str>|
2753 -> Result<Option<witness::Observation>> {
2754 let test = scenario.test_edit_with_field(
2755 &file.original,
2756 witness::TEST_NAME,
2757 field_path,
2758 expected,
2759 );
2760 let edits: Vec<_> = edits.iter().cloned().chain([test]).collect();
2761 let Some(exe) = compile_observer(&edits)? else {
2762 return Ok(None);
2763 };
2764 observe_witness(
2765 baseline,
2766 exe,
2767 wrapper.as_deref(),
2768 scenario,
2769 witness::TEST_NAME,
2770 expected.is_some(),
2771 in_root,
2772 )
2773 };
2774 let witness_checkpoint = if checkpoint.is_some() {
2775 let keys = witness_candidates
2776 .iter()
2777 .map(|candidate| {
2778 let edits = candidate
2779 .edits
2780 .iter()
2781 .map(|edit| (&edit.span, &edit.replacement))
2782 .collect::<Vec<_>>();
2783 serde_json::to_string(&(&candidate.description, edits))
2784 })
2785 .collect::<std::result::Result<Vec<_>, _>>()?;
2786 let name = if in_root {
2787 "witness".to_string()
2788 } else {
2789 format!("witness:{}", file.display)
2790 };
2791 phase(&name, keys)?
2792 } else {
2793 None
2794 };
2795 let mut survivors = vec![];
2796 let mut claimed = BTreeSet::new();
2797 progress::track(
2798 options.progress,
2799 "source witness mutants",
2800 witness_candidates.len(),
2801 |progress| -> Result<()> {
2802 for (index, candidate) in witness_candidates.iter().copied().enumerate() {
2803 let cached = witness_checkpoint
2804 .as_ref()
2805 .map(|phase| phase.get::<WitnessTrial>(index))
2806 .transpose()?
2807 .flatten();
2808 let at = witness_location(file, candidate);
2809 if !built_sources.contains(file)
2811 || candidate.edits.iter().any(|edit| {
2812 left_out_here
2813 .iter()
2814 .any(|(from, to)| *from <= edit.span.start && edit.span.end <= *to)
2815 })
2816 {
2817 if let Some(phase) =
2818 witness_checkpoint.as_ref().filter(|_| cached.is_none())
2819 {
2820 phase.record(index, &WitnessTrial::Inapplicable)?;
2821 }
2822 if !candidate.existing {
2823 report.mutants_not_evaluated += 1;
2824 report.mutants_not_compiled += 1;
2825 let span = &candidate.edits[0].span;
2826 report.skipped.push(report::SkippedSite::new(
2827 at,
2828 file.lines.position(&file.original, span.end),
2829 report::SkipReason::SourceNotBuilt,
2830 Some(
2831 "under a `cfg` that the features of this build turn off"
2832 .to_string(),
2833 ),
2834 ));
2835 }
2836 progress.complete(progress::Outcome::Unable);
2837 continue;
2838 }
2839 let existing = candidate
2840 .existing
2841 .then(|| {
2842 report.findings.iter().position(|finding| {
2843 let location = finding.at();
2844 location.file == at.file
2845 && location.line == at.line
2846 && location.column == at.column
2847 && finding.survivors().contains(&candidate.description)
2848 && (candidate.finding_at.is_none()
2849 || !matches!(finding, Finding::InputGap { .. }))
2850 })
2851 })
2852 .flatten();
2853 let existing = existing
2857 .filter(|index| candidate.finding_at.is_none() || !claimed.contains(index));
2858 let scenarios: Vec<_> = candidate
2859 .scenarios
2860 .iter()
2861 .filter_map(|scenario| {
2862 runner_for(scenario).map(|runner| (scenario, runner))
2863 })
2864 .take(4)
2865 .collect();
2866 let paired = candidate.edits.len() > 1;
2867 if (candidate.existing && (existing.is_none() || scenarios.is_empty()))
2868 || (paired && scenarios.is_empty())
2869 {
2870 if let Some(phase) =
2871 witness_checkpoint.as_ref().filter(|_| cached.is_none())
2872 {
2873 phase.record(index, &WitnessTrial::Inapplicable)?;
2874 }
2875 progress.complete(progress::Outcome::Unable);
2876 continue;
2877 }
2878 let trial = if let Some(cached) = cached {
2881 cached
2882 } else {
2883 let attempted = (|| -> Result<WitnessTrial> {
2884 if paired {
2885 for edit in &candidate.edits {
2886 match suite(std::slice::from_ref(edit))? {
2887 Some(Outcome::Fail) => {}
2888 Some(Outcome::Unable) => {
2889 return Ok(WitnessTrial::Evaluated(Outcome::Unable));
2890 }
2891 _ => return Ok(WitnessTrial::Inapplicable),
2892 }
2893 }
2894 }
2895 Ok(suite(&candidate.edits)?
2896 .map_or(WitnessTrial::Unviable, WitnessTrial::Evaluated))
2897 })();
2898 state.write(&file.path, &restore)?;
2899 let trial = attempted?;
2900 if let Some(phase) = &witness_checkpoint
2901 && !matches!(trial, WitnessTrial::Evaluated(Outcome::Unable))
2902 {
2903 phase.record(index, &trial)?;
2904 }
2905 trial
2906 };
2907 let outcome = match trial {
2908 WitnessTrial::Inapplicable => {
2909 progress.complete(progress::Outcome::Unable);
2910 continue;
2911 }
2912 WitnessTrial::Unviable => {
2913 progress.complete(progress::Outcome::Unable);
2914 report.unviable_mutants += usize::from(!candidate.existing);
2915 continue;
2916 }
2917 WitnessTrial::Evaluated(outcome) => outcome,
2918 };
2919 progress.complete(outcome.into());
2920 if !candidate.existing {
2921 match outcome {
2922 Outcome::Unable => report.mutants_not_evaluated += 1,
2923 Outcome::Pass => {
2924 report.mutants_run += 1;
2925 report.mutants_survived += 1;
2926 }
2927 Outcome::Fail => {
2928 report.mutants_run += 1;
2929 report.mutants_killed += 1;
2930 }
2931 Outcome::Timeout => {
2932 report.mutants_run += 1;
2933 report.mutants_killed += 1;
2934 report.mutants_timed_out += 1;
2935 }
2936 }
2937 }
2938 if outcome == Outcome::Pass {
2939 survivors.push(WitnessSurvivor {
2940 candidate,
2941 at,
2942 existing,
2943 scenarios,
2944 });
2945 }
2946 }
2947 Ok(())
2948 },
2949 )?;
2950
2951 if let Some(phase) = &witness_checkpoint {
2952 phase.finish()?;
2953 }
2954 let originals = shared_witnesses(
2955 &file.original,
2956 &survivors,
2957 wrapper.as_deref(),
2958 in_root,
2959 compile_observer,
2960 note,
2961 );
2962 if !survivors.is_empty() {
2963 state.write(&file.path, &restore)?;
2964 }
2965 let originals = originals?;
2966
2967 progress::track(
2968 options.progress,
2969 "distinguishing tests",
2970 survivors.len(),
2971 |progress| -> Result<()> {
2972 for (survivor, original) in survivors.into_iter().zip(originals) {
2973 if survivor.existing.is_some_and(|index| {
2974 survivor.candidate.finding_at.is_some() && claimed.contains(&index)
2975 }) {
2976 progress.complete(progress::Outcome::Unable);
2977 continue;
2978 }
2979 let mut evidence = None;
2980 let mut original = original;
2981 for (scenario, baseline) in survivor.scenarios {
2982 let shared = original.take();
2983 let distinction = (|| -> Result<_> {
2984 if let Some(shared) = shared {
2985 let edits: Vec<_> = survivor
2987 .candidate
2988 .edits
2989 .iter()
2990 .chain(shared.tests.iter())
2991 .cloned()
2992 .collect();
2993 if let Some(exe) = compile_observer(&edits)?
2994 && let Some(mutant) = observe_witness(
2995 baseline,
2996 exe,
2997 wrapper.as_deref(),
2998 scenario,
2999 &shared.name,
3000 true,
3001 in_root,
3002 )
3003 .ok()
3004 .flatten()
3005 && mutant.equals_expected == Some(false)
3006 && observe_witness(
3009 baseline,
3010 shared.original_exe.path.clone(),
3011 wrapper.as_deref(),
3012 scenario,
3013 &shared.name,
3014 true,
3015 in_root,
3016 )
3017 .ok()
3018 .flatten()
3019 .is_some_and(|rechecked| {
3020 rechecked.equals_expected == Some(true)
3021 && rechecked.value == shared.value
3022 })
3023 && let Some(verified) =
3024 scenario.verified(shared.value, mutant.value)
3025 {
3026 return Ok(Some(verified));
3027 }
3028 }
3031 let Some(original) = observe(scenario, baseline, &[], None, None)?
3032 else {
3033 return Ok(None);
3034 };
3035 let value = original.value;
3036 if witness::is_expected_literal(&value) {
3037 let Some(mutant) = observe(
3038 scenario,
3039 baseline,
3040 &survivor.candidate.edits,
3041 None,
3042 Some(&value),
3043 )?
3044 else {
3045 return Ok(None);
3046 };
3047 if mutant.equals_expected != Some(false) || value == mutant.value {
3048 return Ok(None);
3049 }
3050 let Some(checked) =
3051 observe(scenario, baseline, &[], None, Some(&value))?
3052 else {
3053 return Ok(None);
3054 };
3055 if checked.equals_expected != Some(true) || checked.value != value {
3056 return Ok(None);
3057 }
3058 return Ok(scenario.verified(value, mutant.value));
3059 }
3060 if witness::parse_debug_struct(&value).is_none() {
3063 return Ok(None);
3064 }
3065 let Some(raw_mutant) =
3066 observe(scenario, baseline, &survivor.candidate.edits, None, None)?
3067 else {
3068 return Ok(None);
3069 };
3070 let Some((path, field_orig, _)) =
3071 witness::narrow_struct_field(&value, &raw_mutant.value)
3072 else {
3073 return Ok(None);
3074 };
3075 if !witness::is_expected_literal(&field_orig) {
3076 return Ok(None);
3077 }
3078 let field_path = path.join(".");
3079 let Some(mutant) = observe(
3080 scenario,
3081 baseline,
3082 &survivor.candidate.edits,
3083 Some(&field_path),
3084 Some(&field_orig),
3085 )?
3086 else {
3087 return Ok(None);
3088 };
3089 if mutant.equals_expected != Some(false)
3090 || mutant.value != raw_mutant.value
3091 || value == mutant.value
3092 {
3093 return Ok(None);
3094 }
3095 let Some(checked) = observe(
3096 scenario,
3097 baseline,
3098 &[],
3099 Some(&field_path),
3100 Some(&field_orig),
3101 )?
3102 else {
3103 return Ok(None);
3104 };
3105 if checked.equals_expected != Some(true) || checked.value != value {
3106 return Ok(None);
3107 }
3108 Ok(
3109 scenario.verified_field(
3110 value,
3111 mutant.value,
3112 field_path,
3113 field_orig,
3114 ),
3115 )
3116 })();
3117 match distinction {
3118 Ok(Some(mut verified)) => {
3119 let edits = survivor.candidate.edits.len();
3120 verified.individually_killed = (edits > 1).then_some(edits);
3121 evidence = Some(verified);
3122 break;
3123 }
3124 Ok(None) => {}
3125 Err(err) => note(&format!(
3126 "could not check a distinguishing test for {}: {err:#}",
3127 scenario.expression,
3128 )),
3129 }
3130 }
3131 state.write(&file.path, &restore)?;
3132 progress.complete(Outcome::Pass.into());
3133 if let Some(index) = survivor.existing {
3134 if let Some(evidence) = evidence {
3135 report.findings[index].set_witness(evidence);
3136 if survivor.candidate.finding_at.is_some() {
3137 claimed.insert(index);
3138 }
3139 }
3140 } else {
3141 finding_run_survivors.push(1);
3142 report.findings.push(Finding::Survivor {
3143 at: survivor.at,
3144 survivors: vec![survivor.candidate.description.clone()],
3145 advice: survivor
3146 .candidate
3147 .advice
3148 .clone()
3149 .filter(|_| evidence.is_none()),
3150 witness: evidence,
3151 change_since: None,
3152 });
3153 }
3154 }
3155 Ok(())
3156 },
3157 )?;
3158 }
3159
3160 report.record_evaluation();
3161 debug_assert_eq!(report.findings.len(), finding_run_survivors.len());
3162 let mut paired_findings: Vec<(Finding, usize)> = report
3163 .findings
3164 .into_iter()
3165 .zip(finding_run_survivors)
3166 .collect();
3167 paired_findings.sort_by(|(a, _), (b, _)| {
3168 let (a, b) = (a.at(), b.at());
3169 (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column))
3170 });
3171 let (sorted_findings, finding_run_survivors): (Vec<_>, Vec<_>) =
3172 paired_findings.into_iter().unzip();
3173 report.findings = sorted_findings;
3174 let places: Vec<FilePlaces> = files
3175 .iter()
3176 .map(|file| FilePlaces {
3177 display: &file.display,
3178 source: &file.original,
3179 lines: &file.lines,
3180 places: &file.places,
3181 })
3182 .collect();
3183 name_findings(&mut report.findings, &places);
3184
3185 apply_suppressions_and_finish(
3187 options,
3188 &files,
3189 &mut report,
3190 &finding_run_survivors,
3191 checkpoint.as_ref(),
3192 )?;
3193 debug_assert!(
3194 report.counts_reconcile(),
3195 "report counts do not reconcile: {report:#?}"
3196 );
3197 Ok(report)
3198}
3199
3200fn validate_package_options(options: &Options) -> Result<Vec<&str>> {
3201 if let Some(shard) = options.shard
3202 && (!options.source_only || shard.index >= shard.count)
3203 {
3204 bail!("shards require --source-only and a valid shard index");
3205 }
3206 let mut seen_errors = HashSet::new();
3207 let mut error_values = vec![];
3208 for expression in &options.error_values {
3209 let expression = expression.trim();
3210 if expression.chars().any(char::is_control) {
3213 bail!(
3214 "invalid --error expression {expression:?}: it has to be on one line, \
3215 without control characters"
3216 );
3217 }
3218 let parsed = syn::parse_str::<syn::Expr>(expression)
3219 .with_context(|| format!("invalid --error expression {expression:?}"))?;
3220 if seen_errors.insert(quote::ToTokens::to_token_stream(&parsed).to_string()) {
3221 error_values.push(expression);
3222 }
3223 }
3224 let selection = &options.test_selection;
3225 if options.nextest.is_some() {
3226 if !cfg!(unix) {
3227 bail!("the nextest runner is available on Unix");
3228 }
3229 if !options.source_only || options.doc || selection.enabled() {
3230 bail!(
3231 "--test-tool nextest requires --source-only; select tests through the nextest profile"
3232 );
3233 }
3234 }
3235 if options.baseline_jobs > 1 && !selection.enabled() {
3236 bail!("--baseline-jobs requires isolated tests or a test wrapper or selection");
3237 }
3238 if options.doc && selection.enabled() {
3239 bail!("--doc cannot be combined with isolated test selection");
3240 }
3241 if options.source_only && options.jobs > 1 {
3242 eprintln!(
3243 "tmt: warning: --source-only runs mutants serially in one working copy; ignoring --jobs {}",
3244 options.jobs
3245 );
3246 }
3247 Ok(error_values)
3248}
3249
3250struct PreparedWorkCopy {
3251 workspace: PathBuf,
3252 work: PathBuf,
3253 work_lock: Option<Arc<WorkLock>>,
3254 copy: PathBuf,
3255 state: WorkCopy,
3256 external_deps: BTreeSet<PathBuf>,
3257}
3258
3259fn prepare_work_copy(
3260 options: &Options,
3261 metadata: &Metadata,
3262 batch: Option<&WorkspaceBatch<'_>>,
3263 catalogue: Option<&CatalogueSnapshot>,
3264 note: &impl Fn(&str),
3265) -> Result<PreparedWorkCopy> {
3266 let workspace = metadata.workspace_root.canonicalize()?;
3267 let requested_work = catalogue
3268 .map(|catalogue| &catalogue.path)
3269 .or(options.work_dir.as_ref());
3270 let work = match requested_work {
3271 Some(dir) => {
3272 fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
3273 dir.canonicalize()?
3274 }
3275 None => metadata.target_directory.join("tmt"),
3276 };
3277 if workspace.starts_with(&work) {
3280 bail!(
3281 "the work directory {} contains the workspace; choose a directory of its own",
3282 work.display()
3283 );
3284 }
3285 fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?;
3286 let work = work.canonicalize()?;
3287 let work_lock = if catalogue.is_none() {
3288 Some(Arc::new(WorkLock::take(&work)?))
3289 } else {
3290 None
3291 };
3292 let stage_root = work.join("src");
3293 let copy_subdir = staged_copy_subdir(&workspace, &options.stage_external)?;
3294 let copy = if copy_subdir.as_os_str().is_empty() {
3295 stage_root.clone()
3296 } else {
3297 stage_root.join(©_subdir)
3298 };
3299 let marker = work.join(WORK_MARKER);
3300 if stage_root.exists() && !marker.exists() {
3301 bail!(
3302 "{} exists and was not created by tmt; refusing to delete it. \
3303 Choose another --work-dir or remove it yourself.",
3304 stage_root.display()
3305 );
3306 }
3307 fs::write(
3308 &marker,
3309 "Working directory of tmt (targeted-mutation). Safe to delete.\n",
3310 )?;
3311 let target_dir = metadata.target_directory.clone();
3312 let forbidden = |path: &Path| {
3313 path == target_dir
3314 || path == work
3315 || batch.is_some_and(|batch| path == batch.work)
3316 || path.file_name().is_some_and(|n| n == ".git")
3317 || (path.parent() == Some(workspace.as_path())
3318 && path.file_name().is_some_and(|n| n == "target"))
3319 };
3320 let state = WorkCopy::open_with_copy_root(&work, &stage_root, ©);
3321 let fixtures = options
3322 .copy_fixtures
3323 .iter()
3324 .map(|path| fixture_relative(path))
3325 .collect::<Result<Vec<_>>>()?;
3326 let excluded = fixture_exclusions(&workspace, &fixtures, &options.copy_fixture_excludes)?;
3327 let fixture_forbidden = |path: &Path| forbidden(path) || excluded.contains(path);
3328 let skip = |path: &Path| {
3329 fixture_forbidden(path) || path.file_name().is_some_and(|n| n == "node_modules")
3330 };
3331 if options.progress && !options.list {
3332 for path in &excluded {
3333 note(&format!(
3334 "excluded fixture {}",
3335 path.strip_prefix(&workspace).unwrap_or(path).display()
3336 ));
3337 }
3338 }
3339 if catalogue.is_none_or(|catalogue| !catalogue.ready.get()) {
3340 work_directory(&work, "src")?;
3341 real_dir(©, &state)?;
3342 if copy != stage_root {
3343 for ancestor in copy.ancestors() {
3344 if ancestor == stage_root || !ancestor.starts_with(&stage_root) {
3345 break;
3346 }
3347 state.kept.borrow_mut().insert(ancestor.to_path_buf());
3348 }
3349 }
3350 let visible = if options.all_files {
3351 None
3352 } else {
3353 git_visible_files(&workspace)?
3354 };
3355 match visible {
3356 Some(files) => {
3359 let copied = copy_git_visible(&workspace, ©, files, &workspace, &skip, &state)?;
3360 note(&format!(
3361 "copied {copied} files (ignored files are left out)"
3362 ));
3363 }
3364 None => copy_tree(&workspace, ©, &workspace, &skip, &state)?,
3365 }
3366 for relative in &fixtures {
3367 copy_fixture_entry(
3368 &workspace.join(relative),
3369 ©.join(relative),
3370 &workspace,
3371 &fixture_forbidden,
3372 &state,
3373 &mut BTreeSet::new(),
3374 )?;
3375 }
3376 let mut staged_destinations: Vec<PathBuf> = Vec::new();
3377 let mut folded_ancestors: BTreeMap<String, PathBuf> = BTreeMap::new();
3378 for entry in &options.stage_external {
3379 let (rel, _) = parse_external_rel(&entry.rel)?;
3380 let dst = normalize(©.join(&rel));
3381 let copy_rel_in_stage = copy.strip_prefix(&stage_root).unwrap_or(©);
3382 let dst_rel_in_stage = dst.strip_prefix(&stage_root).unwrap_or(&dst);
3383 if !dst.starts_with(&stage_root)
3384 || dst == stage_root
3385 || copy.starts_with(&dst)
3386 || dst.starts_with(©)
3387 || paths_overlap_case_insensitive(copy_rel_in_stage, dst_rel_in_stage)
3388 || staged_destinations.iter().any(|prev| {
3389 let prev_rel = prev.strip_prefix(&stage_root).unwrap_or(prev);
3390 paths_overlap_case_insensitive(prev_rel, dst_rel_in_stage)
3391 })
3392 {
3393 bail!(
3394 "--stage-external destination collides with the workspace copy or another staged path: {}",
3395 entry.rel.display()
3396 );
3397 }
3398 for ancestor in dst_rel_in_stage.ancestors() {
3399 if ancestor.as_os_str().is_empty() {
3400 continue;
3401 }
3402 let folded = ancestor.to_string_lossy().to_lowercase();
3403 if let Some(previous) = folded_ancestors.get(&folded)
3404 && previous != ancestor
3405 {
3406 bail!(
3407 "--stage-external destinations differ only by case: {} and {}",
3408 previous.display(),
3409 ancestor.display()
3410 );
3411 }
3412 folded_ancestors.insert(folded, ancestor.to_path_buf());
3413 }
3414 staged_destinations.push(dst.clone());
3415 let src = if entry.from.is_absolute() {
3416 entry.from.clone()
3417 } else {
3418 workspace.join(&entry.from)
3419 };
3420 copy_external_entry(
3421 &src,
3422 &dst,
3423 None,
3424 &work,
3425 &forbidden,
3426 &state,
3427 &mut BTreeSet::new(),
3428 )?;
3429 }
3430 prune(&stage_root, &state)?;
3431 if options.git_index {
3432 git_index::snapshot(&workspace, ©)?;
3433 }
3434 let mut external_deps = BTreeSet::new();
3435 if !options.list {
3436 let mut manifests: Vec<&Path> = metadata
3438 .packages
3439 .iter()
3440 .map(|p| p.manifest_path.as_path())
3441 .collect();
3442 let root_manifest = metadata.workspace_root.join("Cargo.toml");
3443 manifests.push(&root_manifest);
3444 for manifest in manifests {
3445 let Ok(canonical) = manifest.canonicalize() else {
3446 continue;
3447 };
3448 let (Some(manifest_dir), Ok(relative)) =
3449 (canonical.parent(), canonical.strip_prefix(&workspace))
3450 else {
3451 continue;
3452 };
3453 let text = fs::read_to_string(&canonical)?;
3454 let (rewritten, externals) = absolutize_path_dependencies_with_externals(
3455 &text,
3456 manifest_dir,
3457 &workspace,
3458 ©,
3459 )?;
3460 external_deps.extend(externals);
3461 if let Some(rewritten) = rewritten {
3462 state.write(©.join(relative), &rewritten)?;
3463 }
3464 }
3465 }
3466 if let Some(catalogue) = catalogue {
3467 state.settle(&workspace)?;
3468 catalogue.ready.set(true);
3469 }
3470 return Ok(PreparedWorkCopy {
3471 workspace,
3472 work,
3473 work_lock,
3474 copy,
3475 state,
3476 external_deps,
3477 });
3478 }
3479 Ok(PreparedWorkCopy {
3480 workspace,
3481 work,
3482 work_lock,
3483 copy,
3484 state,
3485 external_deps: BTreeSet::new(),
3486 })
3487}
3488
3489#[allow(clippy::too_many_arguments)]
3490fn run_audit_phase<'a>(
3491 session: &Session,
3492 files: &[SourceFile],
3493 jobs: &[Job],
3494 results: &mut [JobResult],
3495 timeout_rechecks: &mut report::TimeoutRechecks,
3496 scratch: &Path,
3497 wanted: usize,
3498 workers: usize,
3499 probe_phase: &impl Fn(&str, &[Job]) -> Result<Option<Phase<'a>>>,
3500) -> Result<report::Audit> {
3501 let survivors: Vec<usize> = (0..jobs.len())
3502 .filter(|job| results[*job].survived.is_some())
3503 .collect();
3504 let chosen: Vec<usize> = spread(survivors.len(), wanted)
3505 .into_iter()
3506 .map(|nth| survivors[nth])
3507 .collect();
3508 session.note(&format!(
3509 "audit: running {} of {} surviving mutants against all tests",
3510 chosen.len(),
3511 survivors.len()
3512 ));
3513 let against_all: Vec<Job> = chosen
3514 .iter()
3515 .map(|job| Job {
3516 site: jobs[*job].site,
3517 mutation: jobs[*job].mutation,
3518 tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
3519 })
3520 .collect();
3521 let mut audit = report::Audit {
3522 sampled: chosen.len(),
3523 survivors: survivors.len(),
3524 ..report::Audit::default()
3525 };
3526 let audit_checkpoint = probe_phase("audit", &against_all)?;
3527 for (job, again) in chosen.iter().zip(session.run_jobs(
3528 &against_all,
3529 workers,
3530 "audit mutants",
3531 audit_checkpoint.as_ref(),
3532 )?) {
3533 timeout_rechecks.include(&again);
3534 if again.unable || again.unconfirmed_timeout {
3535 audit.not_audited += 1;
3536 } else if audit_all_tests_disagrees(&again) {
3537 results[*job] = again;
3539 let site = files
3540 .iter()
3541 .find_map(|f| Some((f, f.sites.iter().find(|s| s.id == jobs[*job].site)?)));
3542 if let Some((file, site)) = site {
3543 audit
3544 .disagreements
3545 .push(report::location(&file.display, site));
3546 }
3547 }
3548 }
3549 session.note("audit: recording the tests once more");
3550 for (index, bin) in session.binaries.iter().enumerate() {
3551 let path = scratch.join(format!("trace-{index}-audit.tsv"));
3552 let _ = fs::remove_file(&path);
3553 let trace_env = path.to_string_lossy().into_owned();
3554 let limit = Duration::from_secs(3600);
3555 let outcome = run_binary(
3556 bin,
3557 None,
3558 &[("TMT_TRACE", &trace_env)],
3559 limit,
3560 RunOutput::Quiet,
3561 1,
3562 )?;
3563 let again = Trace::parse(&fs::read_to_string(&path).unwrap_or_default());
3564 let _ = fs::remove_file(&path);
3565 let records = bin.trace.differences(&again);
3566 if outcome != Outcome::Pass || records > 0 {
3567 audit.trace_differences.push(report::TraceDifference {
3568 binary: bin.name.clone(),
3569 records,
3570 rerun_failed: outcome != Outcome::Pass,
3571 });
3572 }
3573 }
3574 Ok(audit)
3575}
3576
3577fn run_effects_phase(
3578 session: &Session,
3579 files: &[SourceFile],
3580 jobs: &[Job],
3581 effect_jobs: &[(usize, usize)],
3582 scratch: &Path,
3583 workers: usize,
3584 findings: &mut [Finding],
3585) -> Result<()> {
3586 session.note(&format!("tracing {} surviving mutants", effect_jobs.len()));
3587 let sites: BTreeMap<u32, (&str, &Site)> = files
3588 .iter()
3589 .flat_map(|f| f.sites.iter().map(move |s| (s.id, (f.display.as_str(), s))))
3590 .collect();
3591 let traced = run_pool(effect_jobs.len(), workers, |index| {
3592 session.trace_job(
3593 &jobs[effect_jobs[index].1],
3594 scratch,
3595 workers.clamp(1, effect_jobs.len()),
3596 )
3597 })?;
3598 for ((finding, job), mut changes) in effect_jobs.iter().zip(traced) {
3599 if let Some((mutated_file, mutated)) = sites.get(&jobs[*job].site) {
3602 for found in changes.values_mut() {
3603 found.retain(|change| {
3604 sites.get(&change.site()).is_none_or(|(file, site)| {
3605 file != mutated_file
3606 || site.end <= mutated.start
3607 || mutated.end <= site.start
3608 })
3609 });
3610 }
3611 changes.retain(|_, found| !found.is_empty());
3612 }
3613 if let Finding::AssertionGap {
3614 effects,
3615 effects_of,
3616 ..
3617 } = &mut findings[*finding]
3618 {
3619 *effects = describe_effects(&changes, &sites);
3620 *effects_of = sites
3621 .get(&jobs[*job].site)
3622 .map(|(_, site)| report::describe(site, jobs[*job].mutation));
3623 }
3624 }
3625 Ok(())
3626}
3627
3628fn apply_suppressions_and_finish(
3629 options: &Options,
3630 files: &[SourceFile],
3631 report: &mut Report,
3632 finding_run_survivors: &[usize],
3633 checkpoint: Option<&Checkpoint>,
3634) -> Result<()> {
3635 let files_with_findings: BTreeSet<&str> = report
3636 .findings
3637 .iter()
3638 .map(|finding| finding.at().file.as_str())
3639 .collect();
3640 let ignored: BTreeMap<&str, BTreeMap<usize, String>> = files
3641 .iter()
3642 .filter(|file| files_with_findings.contains(file.display.as_str()))
3643 .map(|f| {
3644 (
3645 f.display.as_str(),
3646 crate::baseline::ignored_lines(&f.original),
3647 )
3648 })
3649 .collect();
3650 let known = match &options.baseline {
3651 Some(path) => Some(crate::baseline::load(path)?),
3652 None => None,
3653 };
3654 let before = report.findings.len();
3655 let mut after_inline: Vec<(Finding, usize)> = Vec::with_capacity(before);
3656 for (finding, run_survivors) in report
3657 .findings
3658 .drain(..)
3659 .zip(finding_run_survivors.iter().copied())
3660 {
3661 let at = finding.at();
3662 if ignored
3663 .get(at.file.as_str())
3664 .is_some_and(|lines| lines.contains_key(&at.line))
3665 {
3666 report.survivor_breakdown.suppressed += run_survivors;
3667 } else {
3668 after_inline.push((finding, run_survivors));
3669 }
3670 }
3671 if let Some(path) = &options.write_baseline {
3672 let unignored: Vec<Finding> = after_inline.iter().map(|(f, _)| f.clone()).collect();
3673 crate::baseline::write(path, &unignored)?;
3674 }
3675 for (finding, run_survivors) in after_inline {
3676 if known.as_ref().is_some_and(|known| known.knows(&finding)) {
3677 report.survivor_breakdown.suppressed += run_survivors;
3678 } else {
3679 report.survivor_breakdown.reported += run_survivors;
3680 report.findings.push(finding);
3681 }
3682 }
3683 report.suppressed = before - report.findings.len();
3684 if let Some(checkpoint) = checkpoint {
3685 checkpoint.finish_if_complete()?;
3686 }
3687 Ok(())
3688}
3689
3690fn workspace_report_prefix(relative: &Path) -> String {
3691 let parts: Vec<_> = relative
3692 .components()
3693 .filter_map(|part| match part {
3694 std::path::Component::Normal(name) => Some(name.to_string_lossy()),
3695 _ => None,
3696 })
3697 .collect();
3698 if parts.is_empty() {
3699 String::new()
3700 } else {
3701 format!("{}/", parts.join("/"))
3702 }
3703}
3704
3705fn repository_prefix(dir: &Path) -> String {
3709 let shown = Command::new("git")
3710 .arg("-C")
3711 .arg(dir)
3712 .args(["rev-parse", "--show-prefix"])
3713 .stderr(Stdio::null())
3714 .output();
3715 match shown {
3716 Ok(output) if output.status.success() => {
3717 String::from_utf8_lossy(&output.stdout).trim().to_string()
3718 }
3719 _ => String::new(),
3720 }
3721}
3722
3723fn spread(count: usize, wanted: usize) -> Vec<usize> {
3726 let wanted = wanted.min(count);
3727 (0..wanted).map(|nth| nth * count / wanted).collect()
3728}
3729
3730struct FilePlaces<'a> {
3732 display: &'a str,
3733 source: &'a str,
3734 lines: &'a scope::LineIndex,
3735 places: &'a [(usize, usize, String)],
3737}
3738
3739fn name_findings(findings: &mut [Finding], files: &[FilePlaces]) {
3744 let mut by_file: BTreeMap<String, Vec<&mut Finding>> = BTreeMap::new();
3745 for finding in findings {
3746 by_file
3747 .entry(finding.at().file.clone())
3748 .or_default()
3749 .push(finding);
3750 }
3751 for file in files {
3752 let Some(findings) = by_file.remove(file.display) else {
3753 continue;
3754 };
3755 let items = instrument::named_items(file.source);
3756 let index = instrument::ItemIndex::new(&items);
3757 let item_at = |line, column| {
3758 file.lines
3759 .offset_of(file.source, line, column)
3760 .map_or("", |offset| index.at(offset))
3761 };
3762 let mut positions: BTreeMap<(&str, &str), Vec<(usize, usize)>> = BTreeMap::new();
3763 for (line, column, code) in file.places {
3764 positions
3765 .entry((item_at(*line, *column), code))
3766 .or_default()
3767 .push((*line, *column));
3768 }
3769 for places in positions.values_mut() {
3770 places.sort_unstable();
3771 places.dedup();
3772 }
3773 for finding in findings {
3774 let kind = finding.kind();
3775 let at = finding.at_mut();
3776 let item = item_at(at.line, at.column);
3777 let nth = positions.get(&(item, &at.code)).map_or(0, |places| {
3778 places.partition_point(|&place| place < (at.line, at.column))
3779 });
3780 at.item = item.to_string();
3781 at.id = report::finding_id(kind, at, nth);
3782 }
3783 }
3784}
3785
3786fn mutation_of(site: &Site, mutant: &instrument::SourceMutant) -> Mutation {
3788 match &site.kind {
3789 SiteKind::Cmp { .. } => plan::CmpOp::ALL
3790 .into_iter()
3791 .find(|op| op.symbol() == mutant.into)
3792 .map_or(Mutation::Negate, Mutation::Op),
3793 SiteKind::Arith { op, .. } => {
3794 if mutant.into.trim_end_matches('=') == op.swapped().symbol() {
3795 Mutation::ArithSwap
3796 } else {
3797 Mutation::ArithSwap2
3798 }
3799 }
3800 SiteKind::Guard { .. } => Mutation::Const(mutant.into == "true"),
3801 SiteKind::Logic { .. } => Mutation::LogicSwap,
3802 SiteKind::Not { .. } => Mutation::DropNot,
3803 SiteKind::Range { .. } => Mutation::RangeEnd,
3804 SiteKind::SliceEnd { .. } => Mutation::OtherEnd,
3805 SiteKind::StrAffix { .. } => Mutation::StrContains,
3806 SiteKind::StrReplace { .. } => Mutation::StrReplaceMultiplicity,
3807 SiteKind::Clamp { .. } => {
3808 if mutant.into.contains("lower") {
3809 Mutation::ClampDropLower
3810 } else {
3811 Mutation::ClampDropUpper
3812 }
3813 }
3814 SiteKind::Rounding { op, .. } => {
3815 if mutant.into == op.alt1().name() {
3816 Mutation::RoundAlt1
3817 } else {
3818 Mutation::RoundAlt2
3819 }
3820 }
3821 SiteKind::Quantifier { .. } => Mutation::QuantifierSwap,
3822 _ => Mutation::Delete,
3825 }
3826}
3827
3828fn mutations_like(site: &Site, mutant: &instrument::SourceMutant, integers: bool) -> Vec<Mutation> {
3837 let mut all = vec![mutation_of(site, mutant)];
3838 if let (SiteKind::Cmp { op, .. }, Mutation::Op(into)) = (&site.kind, all[0]) {
3839 let an_order_is_needed = matches!(op, plan::CmpOp::Le | plan::CmpOp::Ge);
3840 if into == op.negated() && (integers || !an_order_is_needed) {
3841 all.push(Mutation::Negate);
3842 }
3843 match (op, into) {
3844 (plan::CmpOp::Lt, plan::CmpOp::Le) | (plan::CmpOp::Ge, plan::CmpOp::Gt) => {
3845 all.push(Mutation::Shift(1))
3846 }
3847 (plan::CmpOp::Gt, plan::CmpOp::Ge) | (plan::CmpOp::Le, plan::CmpOp::Lt) => {
3848 all.push(Mutation::Shift(-1))
3849 }
3850 _ => {}
3851 }
3852 }
3853 all
3854}
3855
3856fn describe_effects(
3859 changes: &BTreeMap<String, BTreeSet<Change>>,
3860 sites: &BTreeMap<u32, (&str, &Site)>,
3861) -> Vec<String> {
3862 let mut by_change: BTreeMap<&Change, Vec<&str>> = BTreeMap::new();
3863 for (test, found) in changes {
3864 for change in found {
3865 by_change.entry(change).or_default().push(test);
3866 }
3867 }
3868 if by_change.is_empty() {
3869 return vec![
3870 "with the mutant, these tests still reach the same code with the same outcomes, as far as that is recorded: they do not use its result, it is the same for their inputs, or what they assert holds for both".to_string(),
3871 ];
3872 }
3873 let mut out = vec![];
3874 for (change, tests) in by_change.iter().take(3) {
3875 let Some((file, site)) = sites.get(&change.site()) else {
3876 continue;
3877 };
3878 let code = report::location(file, site).code;
3879 let at = format!("{file}:{}", site.line);
3880 let who = if tests.is_empty() {
3881 continue;
3882 } else if let Some(first) = tests
3883 .iter()
3884 .copied()
3885 .find(|test| *test != crate::trace::UNKNOWN_TEST)
3886 {
3887 if tests.len() == 1 {
3888 format!("`{first}`")
3889 } else {
3890 format!("`{first}` (and {} more)", tests.len() - 1)
3891 }
3892 } else if tests.len() == 1 {
3893 "a test".to_string()
3894 } else {
3895 format!("a test (and {} more)", tests.len() - 1)
3896 };
3897 out.push(match change {
3898 Change::Returns { value, .. } => {
3899 format!("with the mutant, {who} gets `{value}` from `{code}` ({at})")
3900 }
3901 Change::NowRuns { .. } => format!("with the mutant, {who} now runs `{code}` ({at})"),
3902 Change::NoLongerRuns { .. } => {
3903 format!("with the mutant, {who} no longer runs `{code}` ({at})")
3904 }
3905 Change::NewOutcome { .. } => {
3906 format!("with the mutant, {who} takes `{code}` ({at}) a way it did not before")
3907 }
3908 });
3909 }
3910 if by_change.len() > 3 {
3911 out.push(format!("(and {} more such changes)", by_change.len() - 3));
3912 }
3913 out
3914}
3915
3916#[cfg(test)]
3917mod tests;