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