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 not_built_reverts: usize = 0;
631 let mut beyond_places: HashSet<(PathBuf, usize, usize)> = HashSet::new();
632 if let Some(scope) = &scope {
634 for file in &mut files {
635 let relative = file
636 .path
637 .strip_prefix(©)
638 .unwrap_or(&file.path)
639 .to_string_lossy()
640 .into_owned();
641 let in_scope = |site: &Site| {
642 scope.touches(&relative, file.lines.line_of(site.start), file.lines.line_of(site.end))
643 || scope.touches(&relative, site.line, site.line)
645 };
646 let of_file: Vec<scope::Hunk> = since_hunks
647 .iter()
648 .filter(|hunk| hunk.file == relative)
649 .cloned()
650 .collect();
651 let changes_count = reverts::changes(&file.original, &of_file).len();
652 if options.rebuild || options.source_only {
653 if changes_count > 0 || reverts::mixed(&file.original, &of_file) > 0 {
654 undo_paths.insert(file.path.clone());
655 }
656 } else {
657 not_built_reverts += changes_count;
658 }
659 let of_tests = reverts::test_hunks(&file.original, &of_file);
660 if of_tests.is_empty() {
661 file.sites.retain(in_scope);
662 } else {
663 beyond_places.extend(
664 file.sites
665 .iter()
666 .filter(|site| !in_scope(site))
667 .map(|site| (file.path.clone(), site.start, site.end)),
668 );
669 tests_changed.push((file.path.clone(), of_tests));
670 }
671 file.rebuild_sites.retain(in_scope);
672 }
673 files.retain(|f| {
674 !f.sites.is_empty()
675 || !f.rebuild_sites.is_empty()
676 || f.path == root_file
677 || witness_candidates.iter().any(|c| c.file == f.path)
678 || undo_paths.contains(&f.path)
679 });
680 }
681 if !options.list {
682 for candidate in witness_candidates.iter().filter(|c| !c.existing) {
683 if let Some(file) = files.iter_mut().find(|file| file.path == candidate.file) {
684 let at = witness_location(file, candidate);
685 file.places.push((at.line, at.column, at.code));
686 }
687 }
688 }
689 witness_candidates.retain(|candidate| {
690 let Some(file) = files.iter().find(|file| file.path == candidate.file) else {
691 return false;
692 };
693 let relative = file
694 .path
695 .strip_prefix(©)
696 .unwrap_or(&file.path)
697 .to_string_lossy();
698 scope.as_ref().is_none_or(|scope| {
699 let site_in_scope = if candidate.edits.len() == 1 {
700 scope.touches(&relative, *candidate.scope.start(), *candidate.scope.end())
701 } else {
702 candidate.edits.iter().any(|edit| {
703 scope.touches(
704 &relative,
705 file.lines.line_of(edit.span.start),
706 file.lines.line_of(edit.span.end),
707 )
708 })
709 };
710 site_in_scope
711 || candidate
712 .signature_lines
713 .iter()
714 .any(|&line| scope.touches(&relative, line, line))
715 })
716 });
717 let total_sites: usize = files
718 .iter()
719 .map(|f| f.sites.len() + f.rebuild_sites.len())
720 .sum::<usize>()
721 + witness_candidates
722 .iter()
723 .filter(|candidate| !candidate.existing)
724 .count();
725 note(&format!("{} sites in {} files", total_sites, files.len()));
726 if options.source_only {
727 for file in &mut files {
728 file.rebuild_sites.append(&mut file.sites);
729 }
730 }
731
732 let source_mutants = |file: &SourceFile, site: &Site, include_boundary: bool| {
733 let mut mutants = instrument::source_mutants(site);
734 if include_boundary {
735 mutants.extend(instrument::source_boundary_mutant(site));
736 }
737 if options.literal_operators {
738 instrument::literal_operator_mutants(&file.original, site, &mut mutants);
739 }
740 instrument::keep_line_ends(&file.original, &mut mutants);
741 mutants
742 };
743 let counts = options.shard.map(|_| {
744 let regular: usize = files
745 .iter()
746 .map(|file| {
747 file.rebuild_sites
748 .iter()
749 .map(|site| source_mutants(file, site, true).len())
750 .sum::<usize>()
751 })
752 .sum();
753 let total = regular
754 + witness_candidates
755 .iter()
756 .filter(|candidate| !candidate.existing)
757 .count();
758 (regular, total)
759 });
760 if let (Some(range), Some((_, local_total))) = (workspace_shard, counts)
761 && range.member_total != local_total
762 {
763 bail!("package catalogue changed while preparing its workspace shard");
764 }
765 let in_shard = |index| match (options.shard, counts, workspace_shard) {
766 (Some(shard), _, Some(range)) => shard.contains(range.offset + index, range.total),
767 (Some(shard), Some((_, total)), _) => shard.contains(index, total),
768 _ => true,
769 };
770 if let Some((mut index, _)) = counts {
771 witness_candidates.retain(|candidate| {
772 if candidate.existing {
773 return true;
774 }
775 let selected = in_shard(index);
776 index += 1;
777 selected
778 });
779 }
780 let empty_shard = counts.is_some_and(|(_, total)| !(0..total).any(in_shard));
781
782 let package_path = package.manifest_path.parent().unwrap_or(Path::new("."));
783 let mut report_path = repository_prefix(package_path);
784 if report_path.is_empty()
785 && batch.is_some()
786 && let Ok(relative) = package_path.strip_prefix(&workspace)
787 {
788 report_path = workspace_report_prefix(relative);
789 }
790 let mut report = Report {
791 package: package.name.clone(),
792 sites: if empty_shard { 0 } else { total_sites },
793 analysis: report::Analysis {
794 package_path: report_path,
795 since: options.since.clone(),
796 lines: options.lines.clone(),
797 tests_of: test_packages.iter().map(|p| p.name.clone()).collect(),
798 cargo: options.cargo.clone(),
799 opt_level: options.opt_level,
800 timeout_seconds: options.timeout_seconds,
801 baseline_jobs: (options.baseline_jobs > 1).then_some(options.baseline_jobs),
802 timeout_recheck: if options.serial_timeout_rechecks {
803 "serial"
804 } else {
805 "none"
806 },
807 wrapper_grace_seconds: selection
808 .wrapper
809 .as_ref()
810 .map(|_| options.wrapper_grace.as_secs()),
811 rebuild: options.rebuild || options.source_only,
812 verified: options.verify && !options.source_only,
813 doc_tests: options.doc,
814 source_only: options.source_only,
815 literal_operators: options.literal_operators,
816 shard: options.shard,
817 nextest: options.nextest.clone(),
818 error_values: error_values
819 .iter()
820 .map(|value| (*value).to_owned())
821 .collect(),
822 test_selection: None,
823 git_index: options.git_index,
824 copy_fixtures: options.copy_fixtures.clone(),
825 copy_fixture_excludes: options.copy_fixture_excludes.clone(),
826 output_fixtures: options.output_fixtures.clone(),
827 checkpoint: (options.checkpoint && !options.list)
828 .then(|| work.join("checkpoint.jsonl")),
829 },
830 skipped,
831 ..Report::default()
832 };
833 if options.list {
834 if catalogue.is_none() {
835 state.settle(&workspace)?;
836 }
837 let mut candidates = vec![];
838 let mut index = 0;
839 for file in &files {
840 let sites = file
841 .sites
842 .iter()
843 .map(|site| (site, false))
844 .chain(file.rebuild_sites.iter().map(|site| (site, true)));
845 for (site, requires_rebuild) in sites {
846 for mutant in source_mutants(file, site, true) {
847 if in_shard(index) {
848 candidates.push(report::Candidate {
849 what: mutant.what,
850 into: mutant.into,
851 requires_rebuild,
852 edits: vec![candidate_edit(
853 file,
854 mutant.start,
855 mutant.end,
856 mutant.replacement,
857 )],
858 });
859 }
860 index += 1;
861 }
862 }
863 }
864 candidates.extend(
865 witness_candidates
866 .iter()
867 .filter(|candidate| !candidate.existing)
868 .filter_map(|candidate| {
869 let file = files.iter().find(|file| file.path == candidate.file)?;
870 Some(report::Candidate {
871 what: "witness".into(),
872 into: candidate.description.clone(),
873 requires_rebuild: true,
874 edits: candidate
875 .edits
876 .iter()
877 .map(|edit| {
878 candidate_edit(
879 file,
880 edit.span.start,
881 edit.span.end,
882 edit.replacement.clone(),
883 )
884 })
885 .collect(),
886 })
887 }),
888 );
889 report.mutants = Some(candidates);
890 return Ok(report);
891 }
892 if empty_shard || (scope.is_some() && total_sites == 0 && undo_paths.is_empty()) {
893 state.settle(&workspace)?;
895 if let Some(path) = &options.baseline {
896 crate::baseline::load(path)?;
897 }
898 if let Some(path) = &options.write_baseline {
899 crate::baseline::write(path, &[])?;
900 }
901 if !empty_shard {
902 report.mutants_not_built += not_built_reverts;
903 }
904 report.record_evaluation();
905 if let Some(path) = report.analysis.checkpoint.as_deref() {
906 let checkpoint = Checkpoint::open(path)?;
907 let settings =
908 serde_json::json!({"analysis": &report.analysis, "package": &package.name});
909 let identity = crate::campaign_identity::compute(©, &settings, [], false)?;
910 checkpoint.start(&identity, settings)?;
911 checkpoint.finish()?;
912 }
913 return Ok(report);
914 }
915
916 for (id, site) in files
919 .iter_mut()
920 .flat_map(|file| &mut file.sites)
921 .enumerate()
922 {
923 site.id = id as u32;
924 }
925 let beyond: HashSet<u32> = files
927 .iter()
928 .flat_map(|file| {
929 file.sites
930 .iter()
931 .filter(|site| beyond_places.contains(&(file.path.clone(), site.start, site.end)))
932 .map(|site| site.id)
933 })
934 .collect();
935
936 let root_source = state
937 .original(&root_file, &workspace)?
938 .with_context(|| format!("{} is missing", root_target.src_path.display()))?;
939 let root_suffix = if options.source_only || files.iter().all(|file| file.sites.is_empty()) {
940 String::new()
941 } else {
942 state.write(
943 &source_dir.join(format!("{RUNTIME_MOD}.rs")),
944 crate::RUNTIME_SOURCE,
945 )?;
946 let std_alias = format!("extern crate std as {STD_ALIAS};");
947 if root_source.contains(&std_alias) {
948 format!("\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
949 } else {
950 format!("\n#[doc(hidden)]\n{std_alias}\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
951 }
952 };
953
954 let mut disabled: HashSet<u32> = HashSet::new();
956 let mut repairs = BTreeMap::new();
957 let build_target = work_directory(&work, "target")?;
958 let target_flags = test_build_flags(
959 &test_packages,
960 &selection.targets,
961 &workspace,
962 &options.cargo,
963 );
964 let build_scope = if target_flags.is_some() {
965 report::TestBuildScope::SelectedTargets
966 } else {
967 report::TestBuildScope::PackageWide
968 };
969 let build_note = if !selection.targets.is_empty() && target_flags.is_none() {
970 "Cargo is using a package-wide build because the selected test targets cannot be expressed exactly.\n"
971 } else {
972 ""
973 };
974 if !build_note.is_empty() {
975 note(build_note.trim_end());
976 }
977 let can_build_only_observer = !options.doc
980 && target_flags.is_none()
981 && test_packages.len() == 1
982 && package.targets.len() == 1
983 && root_target.test
984 && root_target.test_build_arg() == Some(("--lib", None));
985 let build_test_binaries = |observer: bool| {
986 let mut command = Command::new("cargo");
987 isolate_copy_command(&mut command, &work);
988 if let Some(lock) = &work_lock {
989 lock.retain_for(&mut command);
990 }
991 command
992 .args(["test", "--no-run", "--message-format=json"])
993 .args(test_packages.iter().flat_map(|p| ["-p", p.name.as_str()]))
994 .args(target_flags.as_deref().unwrap_or_default())
995 .args((observer && can_build_only_observer).then_some("--lib"))
996 .args(options.cargo.flags())
997 .current_dir(©)
998 .env("CARGO_TARGET_DIR", &build_target)
999 .env("CARGO_BUILD_BUILD_DIR", &build_target)
1000 .envs(profile_env(options.opt_level))
1001 .stderr(Stdio::piped())
1002 .output()
1003 .context("running cargo test --no-run")
1004 };
1005 let cargo_build = || build_test_binaries(false);
1006 let mut rounds = 0;
1007 let mut newly_disabled = HashSet::new();
1008 let build = loop {
1009 for file in &mut files {
1010 let suffix = if file.path == root_file {
1011 root_suffix.as_str()
1012 } else {
1013 ""
1014 };
1015 write_rendered(file, &state, suffix, &disabled, &newly_disabled)?;
1016 }
1017 if !files.iter().any(|f| f.path == root_file) {
1018 state.write(&root_file, &format!("{root_source}{root_suffix}"))?;
1019 }
1020 if rounds == 0 {
1021 state.settle(&workspace)?;
1022 }
1023 note(if rounds == 0 {
1024 "building the instrumented crate"
1025 } else {
1026 "rebuilding without the sites that failed to compile"
1027 });
1028 let output = cargo_build()?;
1029 let names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
1030 let build = parse_build_output(&String::from_utf8_lossy(&output.stdout), &names);
1031 if output.status.success() {
1032 break build;
1033 }
1034 let diagnostics = || {
1035 [
1036 build.diagnostics.join("\n"),
1037 String::from_utf8_lossy(&output.stderr).into_owned(),
1038 ]
1039 .into_iter()
1040 .filter(|part| !part.trim().is_empty())
1041 .collect::<Vec<_>>()
1042 .join("\n")
1043 };
1044 if build.errors.is_empty() {
1045 bail!("the build failed:\n{build_note}{}", diagnostics());
1046 }
1047 rounds += 1;
1048 let before = disabled.len();
1049 let mut blamed_now: HashSet<u32> = HashSet::new();
1050 for error in &build.errors {
1051 let blamed = blame_error(error, &files, ©, &disabled);
1052 if std::env::var_os("TMT_DEBUG").is_some() {
1053 eprintln!(
1054 "tmt: debug: blaming {blamed:?} for\n{}",
1055 report::sanitize_terminal(&error.rendered)
1056 );
1057 }
1058 for id in blamed {
1059 repairs
1060 .entry(id)
1061 .or_insert_with(|| error.rendered.lines().next().unwrap_or("").to_string());
1062 blamed_now.insert(id);
1063 }
1064 }
1065 disabled.extend(blamed_now.iter().copied());
1066 newly_disabled = blamed_now;
1067 if disabled.len() == before || rounds > MAX_REPAIR_ROUNDS {
1068 bail!(
1069 "the crate does not build after instrumentation.\n\
1070 {build_note}Does `cargo test --no-run` pass on the original for the same targets?\n{}",
1071 diagnostics()
1072 );
1073 }
1074 };
1075 let built_sources = if options.rebuild || options.source_only || options.audit.is_some() {
1076 let behind_cargo = features_from_flags(
1081 std::env::vars_os()
1082 .filter(|(name, _)| name.to_string_lossy().ends_with("RUSTFLAGS"))
1083 .map(|(_, value)| Some(value)),
1084 ) || build.build_scripts.iter().any(|script| {
1085 script["cfgs"].as_array().is_some_and(|cfgs| {
1086 cfgs.iter()
1087 .any(|cfg| cfg.as_str().is_some_and(|cfg| cfg.contains("feature")))
1088 })
1089 }) || configuration_names_a_feature(
1090 ©,
1091 std::env::var_os("CARGO_HOME").map(PathBuf::from),
1092 );
1093 BuiltSources::from_artifacts(&build.artifacts, &build.features, !behind_cargo, ©)
1094 } else {
1095 BuiltSources::default()
1096 };
1097 output_fixture::stage(&workspace, &work, &build_target, &options.output_fixtures)?;
1098 let checkpoint_path = report.analysis.checkpoint.as_deref();
1099 let checkpoint = checkpoint_path.map(Checkpoint::open).transpose()?;
1100 let doc_packages = test_packages
1101 .iter()
1102 .filter(|p| options.doc && p.targets.iter().any(|target| target.doctest));
1103 if build.test_binaries.is_empty() && doc_packages.clone().next().is_none() {
1104 bail!("{build_note}`{}` has no test binaries", package.name);
1105 }
1106
1107 let mut session = Session {
1109 progress: options.progress,
1110 serial_timeout_rechecks: options.serial_timeout_rechecks,
1111 package_dir,
1112 binaries: vec![],
1113 };
1114 let wrapper = selection
1115 .wrapper
1116 .as_ref()
1117 .map(|path| {
1118 let relative = wrapper_relative(path)?;
1119 let copied = copy.join(&relative);
1120 if !copied.is_file() {
1121 bail!(
1122 "test wrapper is missing from the work copy: {}",
1123 copied.display()
1124 );
1125 }
1126 Ok(copied)
1127 })
1128 .transpose()?;
1129 let mut runners: Vec<(String, Runner, PathBuf)> = vec![];
1130 let root_test_exe = |built: &BuildOutput| {
1131 built
1132 .test_binaries
1133 .iter()
1134 .find(|(name, _, owner, kind)| {
1135 *name == root_target.name && *owner == package.name && *kind == root_target.kind
1136 })
1137 .map(|(_, exe, _, _)| exe.clone())
1138 };
1139 let root_exe = (!witness_candidates.is_empty())
1140 .then(|| root_test_exe(&build))
1141 .flatten();
1142 if let Some(nextest) = &options.nextest {
1143 let mut flags: Vec<_> = test_packages
1144 .iter()
1145 .flat_map(|p| ["-p".to_owned(), p.name.clone()])
1146 .collect();
1147 flags.extend(options.cargo.flags());
1148 runners.push((
1149 "nextest".to_owned(),
1150 Runner::Nextest {
1151 copy: copy.clone(),
1152 target_dir: build_target.clone(),
1153 profile: nextest.profile.clone(),
1154 opt_level: options.opt_level,
1155 flags,
1156 },
1157 session.package_dir.clone(),
1158 ));
1159 } else {
1160 for (name, exe, owner, kind) in build.test_binaries {
1161 if !selection.targets.is_empty() && !selection.targets.contains(&name) {
1162 continue;
1163 }
1164 let owner_package = test_packages
1165 .iter()
1166 .find(|p| p.name == owner)
1167 .expect("binaries are filtered by these packages");
1168 let cwd = in_copy(
1169 owner_package
1170 .manifest_path
1171 .parent()
1172 .expect("manifest has a parent"),
1173 )?;
1174 if selection.enabled() {
1175 let all = list_tests(&exe, &cwd, &work, false, true, work_lock.as_deref())?;
1176 let ignored = list_tests(&exe, &cwd, &work, true, true, work_lock.as_deref())?;
1177 for test in all {
1178 let was_ignored = ignored.contains(&test);
1179 if (was_ignored && !selection.include_ignored)
1180 || (!selection.include.is_empty() && !selection.include.contains(&test))
1181 || selection.exclude.contains(&test)
1182 {
1183 continue;
1184 }
1185 runners.push((
1186 format!("{owner}::{}::{name}::{test}", kind.join("+")),
1187 Runner::Isolated {
1188 exe: exe.clone(),
1189 test,
1190 ignored: was_ignored,
1191 wrapper: wrapper.clone(),
1192 },
1193 cwd.clone(),
1194 ));
1195 }
1196 continue;
1197 }
1198 let name = if owner == package.name {
1200 name
1201 } else {
1202 format!("{owner}::{name}")
1203 };
1204 runners.push((name, Runner::Exe(exe), cwd));
1205 }
1206 }
1207 if selection.enabled() && runners.is_empty() {
1208 bail!("{build_note}no tests matched the requested selection");
1209 }
1210 let selected_tests = selection.enabled().then(|| report::TestSelection {
1211 build_scope,
1212 wrapper: selection
1213 .wrapper
1214 .as_ref()
1215 .map(|path| path.display().to_string()),
1216 tests: runners.iter().map(|(name, _, _)| name.clone()).collect(),
1217 });
1218 for owner in doc_packages {
1219 let doc = Runner::Doc {
1220 copy: copy.clone(),
1221 target_dir: build_target.clone(),
1222 package: owner.name.clone(),
1223 opt_level: options.opt_level,
1224 flags: options.cargo.flags(),
1225 };
1226 let name = if owner.name == package.name {
1227 "doc tests".to_owned()
1228 } else {
1229 format!("{}::doc tests", owner.name)
1230 };
1231 let cwd = in_copy(owner.manifest_path.parent().expect("manifest has a parent"))?;
1232 runners.push((name, doc, cwd));
1233 }
1234 report.analysis.test_selection = selected_tests;
1235 let identity = if checkpoint.is_some() {
1236 let mut build_inputs: Vec<_> = build
1237 .build_scripts
1238 .iter()
1239 .map(serde_json::Value::to_string)
1240 .collect();
1241 build_inputs.sort();
1242 let settings = serde_json::json!({
1245 "build_scripts": build_inputs,
1246 "analysis": &report.analysis, "package": &package.name, "jobs": effective_jobs,
1247 "verify": options.verify, "audit": options.audit, "effects": options.effects,
1248 "all_files": options.all_files, "build_scope": build_scope,
1249 "runners": runners.iter().map(|(name, runner, cwd)| (name, runner.executable(), cwd)).collect::<Vec<_>>()
1250 });
1251 let mut inputs = BTreeSet::new();
1252 for (root, artifacts) in &build.artifacts {
1253 inputs.insert(root.clone());
1254 if let Some(dependencies) = artifacts
1255 .iter()
1256 .map(|artifact| artifact_inputs(artifact, root, ©))
1257 .find(|deps| !deps.is_empty())
1258 {
1259 inputs.extend(dependencies);
1260 } else {
1261 inputs.extend(artifacts.iter().cloned());
1264 }
1265 }
1266 inputs.extend(
1267 build
1268 .build_scripts
1269 .iter()
1270 .filter_map(|script| script.get("out_dir")?.as_str().map(PathBuf::from)),
1271 );
1272 inputs.retain(|path| !path.starts_with(©));
1275 inputs.extend(
1276 options
1277 .output_fixtures
1278 .iter()
1279 .map(|fixture| build_target.join(&fixture.to)),
1280 );
1281 Some(crate::campaign_identity::compute(
1282 ©,
1283 &settings,
1284 inputs,
1285 options.nextest.is_some(),
1286 )?)
1287 } else {
1288 None
1289 };
1290 let marks = marks_dir(&work)?;
1295 let baseline_jobs = if selection.enabled() {
1296 options.baseline_jobs
1297 } else {
1298 1
1299 };
1300 if options.progress {
1301 eprintln!(
1302 "tmt: baselines: 0/{} completed ({} workers)",
1303 runners.len(),
1304 baseline_jobs
1305 );
1306 }
1307
1308 session.binaries = progress::track_baselines(options.progress, runners.len(), |progress| {
1309 run_pool(runners.len(), baseline_jobs, |slot| {
1310 let index = slot;
1311 let (name, runner, cwd) = runners[index].clone();
1312 let result = (|| {
1313 let trace_path = work.join(format!("trace-{index}.tsv"));
1314 let _ = fs::remove_file(&trace_path);
1315 let mut bin = TestBinary {
1316 name,
1317 cwd,
1318 marks: marks.clone(),
1319 git_ceiling: work.clone(),
1320 work_lock: work_lock.clone(),
1321 tests: BTreeSet::new(),
1322 runner,
1323 baseline: Duration::ZERO,
1324 untraced_baseline: None,
1325 timeout_diagnostic: std::sync::Once::new(),
1326 traced: Duration::ZERO,
1327 timeout: options.timeout_seconds.map(Duration::from_secs),
1328 wrapper_grace: options.wrapper_grace,
1329 report_slow: options.progress,
1330 filtered_timings: Default::default(),
1331 trace: Trace::default(),
1332 effects_baseline: std::sync::OnceLock::new(),
1333 };
1334 session.note(&format!("tracing `{}`", bin.name));
1335 let started = Instant::now();
1336 let trace_env = trace_path.to_string_lossy().into_owned();
1337 let trace = [("TMT_TRACE", trace_env.as_str())];
1338 run_baseline(
1339 &bin,
1340 if options.source_only { &[] } else { &trace },
1341 Duration::from_secs(3600),
1342 &work.join(format!("baseline-{index}.log")),
1343 false,
1344 )?;
1345 bin.traced = started.elapsed();
1346 bin.baseline = bin.traced;
1347 if options.source_only {
1348 bin.untraced_baseline = Some(BaselineTiming::Completed(bin.baseline));
1349 }
1350 if !options.source_only && bin.traced > SLOW_TRACE {
1353 let started = Instant::now();
1354 let passed = run_baseline(
1355 &bin,
1356 &[],
1357 bin.traced,
1358 &work.join(format!("baseline-{index}-untraced.log")),
1359 true,
1360 )?;
1361 let elapsed = started.elapsed();
1362 if passed {
1363 bin.untraced_baseline = Some(BaselineTiming::Completed(elapsed));
1364 bin.baseline = elapsed;
1365 } else {
1366 bin.untraced_baseline = Some(BaselineTiming::StillRunning(bin.traced));
1367 }
1368 }
1369 let text = match fs::read_to_string(&trace_path) {
1372 Ok(text) => text,
1373 Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
1374 Err(err) => bail!("cannot read the trace of `{}`: {err}", bin.name),
1375 };
1376 bin.trace = Trace::parse(&text);
1377 if bin.trace.malformed_lines > 0 {
1378 bail!(
1379 "the trace of `{}` has {} malformed lines; not drawing conclusions from it",
1380 bin.name,
1381 bin.trace.malformed_lines
1382 );
1383 }
1384 if let Runner::Exe(exe) = &bin.runner {
1385 bin.tests =
1386 list_tests(exe, &bin.cwd, &work, false, false, work_lock.as_deref())?;
1387 }
1388 Ok(bin)
1389 })();
1390 progress.complete(if result.is_ok() {
1391 progress::Outcome::Survived
1392 } else {
1393 progress::Outcome::Failed
1394 });
1395 result
1396 })
1397 })?;
1398
1399 for file in &files {
1401 for site in &file.sites {
1402 if disabled.contains(&site.id) {
1403 let fallback = options.rebuild
1404 && !matches!(site.kind, SiteKind::Body { .. })
1405 && !instrument::source_mutants(site).is_empty();
1406 match site.kind {
1407 SiteKind::Body { .. } => report.unviable_mutants += 1,
1408 _ if fallback => {}
1409 _ => report.skipped_sites += 1,
1410 }
1411 report.skipped.push(report::SkippedSite::new(
1412 report::location(&file.display, site),
1413 file.lines.position(&file.original, site.end),
1414 if fallback {
1415 report::SkipReason::ProbeReplacedBySourceRebuild
1416 } else {
1417 report::SkipReason::ProbeCompileError
1418 },
1419 repairs.get(&site.id).cloned(),
1420 ));
1421 }
1422 }
1423 if !options.rebuild && !options.source_only {
1424 report.skipped.extend(file.rebuild_sites.iter().map(|site| {
1425 report::SkippedSite::new(
1426 report::location(&file.display, site),
1427 file.lines.position(&file.original, site.end),
1428 report::SkipReason::RequiresSourceRebuild,
1429 None,
1430 )
1431 }));
1432 }
1433 }
1434 if let (Some(checkpoint), Some(identity)) = (&checkpoint, &identity) {
1435 checkpoint.start(
1436 identity,
1437 serde_json::json!({
1438 "package": &package.name, "analysis": &report.analysis,
1439 "runners": session.binaries.iter().map(|bin| &bin.name).collect::<Vec<_>>(),
1440 "jobs": effective_jobs, "tool_version": env!("CARGO_PKG_VERSION")
1441 }),
1442 )?;
1443 }
1444 let phase = |name: &str, keys: Vec<String>| {
1445 checkpoint
1446 .as_ref()
1447 .zip(identity.as_deref())
1448 .map(|(checkpoint, identity)| checkpoint.begin(name, identity, keys))
1449 .transpose()
1450 };
1451 let probe_phase = |name: &str, jobs: &[Job]| -> Result<Option<Phase<'_>>> {
1452 if checkpoint.is_none() {
1453 return Ok(None);
1454 }
1455 let locations: BTreeMap<_, _> = files
1456 .iter()
1457 .flat_map(|file| {
1458 file.sites
1459 .iter()
1460 .map(|site| (site.id, (&file.display, site.line, site.column, &site.text)))
1461 })
1462 .collect();
1463 let keys = jobs
1464 .iter()
1465 .map(|job| {
1466 let tests = job
1467 .tests
1468 .iter()
1469 .map(|(bin, selected)| (&session.binaries[*bin].name, selected))
1470 .collect::<Vec<_>>();
1471 serde_json::to_string(&(locations.get(&job.site), job.mutation.encode(), tests))
1472 })
1473 .collect::<std::result::Result<Vec<_>, _>>()?;
1474 phase(name, keys)
1475 };
1476 let scratch = work.clone();
1477 let mut jobs: Vec<Job> = vec![];
1478 let mut not_evaluated: HashSet<u32> = HashSet::new();
1481 let mut site_work: Vec<SiteWork> = vec![];
1482 let mut effect_jobs: Vec<(usize, usize)> = vec![];
1484 for file in &files {
1485 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
1486 let primitive = |from: usize, to: usize| {
1489 let Some(mut text) = file.original.get(from..to) else {
1490 return false;
1491 };
1492 let mut start = from;
1493 loop {
1494 let trimmed = text.trim_start();
1495 start += text.len() - trimmed.len();
1496 text = trimmed.trim_end();
1497 match text
1498 .strip_prefix('(')
1499 .and_then(|inner| inner.strip_suffix(')'))
1500 {
1501 Some(inner) => {
1502 start += 1;
1503 text = inner;
1504 }
1505 None => break,
1506 }
1507 }
1508 file.sites.iter().any(|other| {
1509 matches!(other.kind, SiteKind::Arith { .. })
1510 && other.start == start
1511 && other.end == start + text.len()
1512 && !disabled.contains(&other.id)
1513 && {
1514 let seen =
1515 session.merged(|t| t.arith.get(&other.id), plan::ArithObs::merge);
1516 !seen.opaque
1517 && (seen.same || seen.differs || seen.same2 || seen.differs2)
1518 }
1519 })
1520 };
1521 let plan = match session.plan(&file.display, site, options.verify, &primitive) {
1522 Planned::Unreached if beyond.contains(&site.id) => continue,
1525 Planned::Unreached => {
1526 let at = report::location(&file.display, site);
1528 if report.unreached.last() != Some(&at) {
1529 report.unreached.push(at);
1530 }
1531 continue;
1532 }
1533 Planned::Nothing => continue,
1534 Planned::NotEvaluated => {
1535 not_evaluated.insert(site.id);
1536 continue;
1537 }
1538 Planned::Plan(plan) => plan,
1539 };
1540 let mut add =
1541 |mutation: Mutation, tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>| {
1542 jobs.push(session.job(site.id, mutation, tests_of));
1543 jobs.len() - 1
1544 };
1545 let gaps = plan
1546 .gaps
1547 .into_iter()
1548 .map(
1549 |PlannedGap {
1550 finding,
1551 survivors,
1552 constant_expr,
1553 }| {
1554 let confirm = if options.verify {
1557 survivors
1558 .into_iter()
1559 .map(|m| add(m, &*plan.reaching))
1560 .collect()
1561 } else {
1562 vec![]
1563 };
1564 (finding, confirm, constant_expr)
1565 },
1566 )
1567 .collect();
1568 let infected = &plan.infected;
1569 let runs = plan
1570 .run
1571 .iter()
1572 .map(|m| (*m, add(*m, &|bin| infected(bin, *m))))
1573 .collect();
1574 site_work.push(SiteWork {
1575 file: &file.display,
1576 site,
1577 gaps,
1578 constant: plan.constant,
1579 cannot_differ: plan.cannot_differ,
1580 runs,
1581 });
1582 }
1583 }
1584 session.note(&format!(
1585 "running {} mutants on {} thread(s)",
1586 jobs.len(),
1587 options.jobs.max(1)
1588 ));
1589 let probe_checkpoint = probe_phase("probe", &jobs)?;
1590 let mut results =
1591 session.run_jobs(&jobs, options.jobs, "mutants", probe_checkpoint.as_ref())?;
1592 for result in &results {
1593 report.timeout_rechecks.include(result);
1594 }
1595
1596 if let Some(wanted) = options.audit {
1599 report.audit = Some(run_audit_phase(
1600 &session,
1601 &files,
1602 &jobs,
1603 &mut results,
1604 &mut report.timeout_rechecks,
1605 &scratch,
1606 wanted,
1607 options.jobs,
1608 &probe_phase,
1609 )?);
1610 }
1611 #[derive(Clone, Copy, PartialEq, Eq)]
1615 enum EarlierVerdict {
1616 Killed,
1617 Survived,
1618 Unknown,
1619 }
1620 let mut earlier_verdict: BTreeMap<usize, EarlierVerdict> = BTreeMap::new();
1621 let asked: Vec<usize> = site_work
1622 .iter()
1623 .filter(|item| beyond.contains(&item.site.id))
1624 .flat_map(|item| {
1625 item.gaps
1626 .iter()
1627 .flat_map(|(_, confirm, _)| confirm.iter().copied())
1628 .chain(item.runs.iter().map(|(_, job)| *job))
1629 })
1630 .filter(|job| results[*job].survived.is_some())
1631 .collect();
1632 if !asked.is_empty() {
1633 let revision = report::short_revision(options.since.as_deref().unwrap_or_default());
1634 session.note(&format!(
1635 "running {} surviving mutants against the tests as they were at {revision}",
1636 asked.len()
1637 ));
1638 let suffix = |file: &SourceFile| {
1639 if file.path == root_file {
1640 root_suffix.as_str()
1641 } else {
1642 ""
1643 }
1644 };
1645 let earlier: Option<Vec<(&SourceFile, String)>> = tests_changed
1647 .iter()
1648 .map(|(path, hunks)| {
1649 let file = files.iter().find(|file| file.path == *path)?;
1650 let rendered = file.rendered.as_ref()?;
1651 let mut places = hunks
1652 .iter()
1653 .map(|hunk| {
1654 let (from, to) = scope::range_of(&file.original, hunk);
1655 Some((rendered.copied(from, to)?, hunk.old.as_str()))
1656 })
1657 .collect::<Option<Vec<_>>>()?;
1658 places.sort_by_key(|((from, _), _)| std::cmp::Reverse(*from));
1659 let mut text = rendered.text.clone();
1660 for ((from, to), old) in places {
1661 text.replace_range(from..to, old);
1662 }
1663 Some((file, text))
1664 })
1665 .collect();
1666 let attempted = if let Some(earlier) = earlier {
1667 let attempted = (|| -> Result<Option<Vec<JobResult>>> {
1668 for (file, text) in &earlier {
1669 state.write(&file.path, &format!("{text}{}", suffix(file)))?;
1670 }
1671 if !cargo_build()?.status.success() {
1672 session.note(
1673 "the tests as they were do not build with the code as it is: what they found out is not known",
1674 );
1675 return Ok(None);
1676 }
1677 let all: Vec<&TestBinary> = session.binaries.iter().collect();
1679 if run_source_tests(&all)? != Outcome::Pass {
1680 session.note(
1681 "the tests as they were fail on the code as it is: what they found out is not known",
1682 );
1683 return Ok(None);
1684 }
1685 let against_all: Vec<Job> = asked
1686 .iter()
1687 .map(|job| Job {
1688 site: jobs[*job].site,
1689 mutation: jobs[*job].mutation,
1690 tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
1691 })
1692 .collect();
1693 session
1694 .run_jobs(&against_all, options.jobs, "mutants, earlier tests", None)
1695 .map(Some)
1696 })();
1697 for (file, _) in &earlier {
1699 let rendered = file.rendered.as_ref().expect("rendered before building");
1700 state.write(&file.path, &format!("{}{}", rendered.text, suffix(file)))?;
1701 }
1702 if !cargo_build()?.status.success() {
1703 bail!("the crate does not build once its tests are put back as they are");
1704 }
1705 attempted
1706 } else {
1707 session.note(
1708 "not all changed test files could be restored as they were: what they found out is not known",
1709 );
1710 Ok(None)
1711 };
1712 if let Some(again) = attempted? {
1713 for (job, result) in asked.iter().zip(again) {
1714 let verdict = if result.unable || result.unconfirmed_timeout {
1715 EarlierVerdict::Unknown
1716 } else if result.survived.is_none() {
1717 EarlierVerdict::Killed
1718 } else {
1719 EarlierVerdict::Survived
1720 };
1721 earlier_verdict.insert(*job, verdict);
1722 }
1723 } else {
1724 for job in &asked {
1725 earlier_verdict.insert(*job, EarlierVerdict::Unknown);
1726 }
1727 }
1728 }
1729 let unable = results
1730 .iter()
1731 .filter(|r| r.unable || r.unconfirmed_timeout)
1732 .count();
1733 not_evaluated.extend(
1734 jobs.iter()
1735 .zip(&results)
1736 .filter(|(_, result)| result.unable || result.unconfirmed_timeout)
1737 .map(|(job, _)| job.site),
1738 );
1739 if !options.rebuild {
1740 report.mutants_not_evaluated = not_evaluated.len();
1741 }
1742 report.mutants_run = results.len() - unable;
1743 report.mutants_killed = results.iter().filter(|r| r.survived.is_none()).count() - unable;
1744 report.mutants_survived = report.mutants_run - report.mutants_killed;
1745 report.mutants_timed_out = results
1746 .iter()
1747 .filter(|r| r.timed_out && !r.unconfirmed_timeout)
1748 .count();
1749
1750 let mut finding_run_survivors: Vec<usize> = vec![];
1753
1754 let confirmed = |w: &SiteWork| {
1757 w.gaps
1758 .iter()
1759 .all(|(_, confirm, _)| confirm.iter().all(|j| results[*j].survived.is_some()))
1760 };
1761 let constants: BTreeSet<(&str, usize, usize)> = site_work
1762 .iter()
1763 .filter(|w| w.cannot_differ || (w.constant && confirmed(w)))
1764 .map(|w| (w.file, w.site.start, w.site.end))
1765 .collect();
1766 for item in &site_work {
1767 let at = report::location(item.file, item.site);
1768 for (finding, confirm, constant_expr) in &item.gaps {
1769 let repeats = constant_expr
1772 .is_some_and(|(start, end)| constants.contains(&(item.file, start, end)));
1773 let survived_count = confirm
1774 .iter()
1775 .filter(|j| results[**j].survived.is_some())
1776 .count();
1777 if beyond.contains(&item.site.id) {
1778 let confirmed = confirm.iter().all(|j| results[*j].survived.is_some());
1780 let killed_before = confirm
1781 .iter()
1782 .any(|j| earlier_verdict.get(j) == Some(&EarlierVerdict::Killed));
1783 if confirmed && !repeats && killed_before {
1784 report.weakened.push(finding.at().clone());
1785 report.findings.push(finding.clone());
1786 finding_run_survivors.push(survived_count);
1787 } else if !confirmed {
1788 report.survivor_breakdown.unconfirmed_gap += survived_count;
1789 } else if repeats {
1790 report.survivor_breakdown.redundant_constant += survived_count;
1791 } else {
1792 for job in confirm {
1793 if results[*job].survived.is_some() {
1794 if earlier_verdict.get(job) == Some(&EarlierVerdict::Survived) {
1795 report.survivor_breakdown.preexisting_unchanged += 1;
1796 } else {
1797 report.survivor_breakdown.unchanged_not_compared += 1;
1798 }
1799 }
1800 }
1801 }
1802 continue;
1803 }
1804 match Prediction::of(confirm.iter().map(|j| &results[*j])) {
1805 Prediction::Refuted => {
1806 report.unstable.push(at.clone());
1807 report.survivor_breakdown.unconfirmed_gap += survived_count;
1808 }
1809 Prediction::Confirmed if !repeats => {
1810 report.findings.push(finding.clone());
1811 finding_run_survivors.push(survived_count);
1812 }
1813 Prediction::Confirmed => {
1814 report.survivor_breakdown.redundant_constant += survived_count;
1815 }
1816 Prediction::Unknown => {
1818 report.survivor_breakdown.unconfirmed_gap += survived_count;
1819 }
1820 }
1821 }
1822 if let SiteKind::Body {
1825 sole_expr: Some((start, end)),
1826 ..
1827 } = item.site.kind
1828 && constants.contains(&(item.file, start, end))
1829 {
1830 report.survivor_breakdown.redundant_constant += item
1831 .runs
1832 .iter()
1833 .filter(|(_, job)| results[*job].survived.is_some())
1834 .count();
1835 continue;
1836 }
1837 let mut survivors = vec![];
1838 let mut passing_tests = BTreeSet::new();
1839 for (mutation, job) in &item.runs {
1840 if let Some(tests) = &results[*job].survived {
1841 if beyond.contains(&item.site.id) {
1842 match earlier_verdict.get(job) {
1843 Some(EarlierVerdict::Killed) => {}
1844 Some(EarlierVerdict::Survived) => {
1845 report.survivor_breakdown.preexisting_unchanged += 1;
1846 continue;
1847 }
1848 Some(EarlierVerdict::Unknown) | None => {
1849 report.survivor_breakdown.unchanged_not_compared += 1;
1850 continue;
1851 }
1852 }
1853 }
1854 survivors.push(report::describe(item.site, *mutation));
1855 passing_tests.extend(tests.iter().cloned());
1856 }
1857 }
1858 if !survivors.is_empty() {
1859 let first = item.runs.iter().find(|(_, job)| {
1861 results[*job].survived.is_some()
1862 && (!beyond.contains(&item.site.id)
1863 || earlier_verdict.get(job) == Some(&EarlierVerdict::Killed))
1864 });
1865 if beyond.contains(&item.site.id) {
1866 report.weakened.push(at.clone());
1867 }
1868 effect_jobs.push((report.findings.len(), first.expect("a survivor").1));
1869 finding_run_survivors.push(survivors.len());
1870 report.findings.push(Finding::AssertionGap {
1871 at,
1872 survivors,
1873 tests: passing_tests.into_iter().collect(),
1874 effects: vec![],
1875 effects_of: None,
1876 witness: None,
1877 });
1878 }
1879 }
1880
1881 if options.effects && !effect_jobs.is_empty() {
1883 run_effects_phase(
1884 &session,
1885 &files,
1886 &jobs,
1887 &effect_jobs,
1888 &scratch,
1889 options.jobs,
1890 &mut report.findings,
1891 )?;
1892 }
1893
1894 let mut built: Vec<(&SourceFile, &Site, instrument::SourceMutant, Option<usize>)> = vec![];
1898 let build_regular_mutants = options.rebuild || options.source_only;
1899 let mut index = 0;
1900 for file in &files {
1901 let retried = file.sites.iter().filter(|site| {
1904 (disabled.contains(&site.id) && !matches!(site.kind, SiteKind::Body { .. }))
1905 || not_evaluated.contains(&site.id)
1906 });
1907 for site in file.rebuild_sites.iter().chain(retried) {
1908 let mutants = source_mutants(file, site, true);
1909 if build_regular_mutants {
1910 built.extend(mutants.into_iter().filter_map(|mutant| {
1911 let selected = in_shard(index);
1912 index += 1;
1913 selected.then_some((file, site, mutant, None))
1914 }));
1915 } else {
1916 report.mutants_not_built += mutants.len();
1917 }
1918 }
1919 }
1920 if let (Some(wanted), Some(audit)) = (options.audit, report.audit.as_mut()) {
1923 let mut twins = vec![];
1924 for file in &files {
1925 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
1926 let integers = session.binaries.iter().all(|bin| {
1928 let seen = bin.trace.merged(site.id);
1929 !seen.reached() || seen.valued()
1930 });
1931 let candidates = jobs_for_site(&jobs, site.id);
1932 let job_of = |mutation: Mutation| {
1933 candidates
1934 .clone()
1935 .find(|&index| jobs[index].mutation == mutation)
1936 };
1937 let mut compared = vec![];
1938 let mut mutants = instrument::source_mutants(site);
1939 instrument::keep_line_ends(&file.original, &mut mutants);
1940 for mutant in mutants {
1941 let job = mutations_like(site, &mutant, integers)
1943 .into_iter()
1944 .find_map(job_of);
1945 if let Some(job) = job {
1946 compared.push(job);
1947 twins.push((file, site, mutant, Some(job)));
1948 }
1949 }
1950 if let (SiteKind::Cmp { op, .. }, Some(job)) =
1953 (&site.kind, job_of(Mutation::Negate))
1954 && !compared.contains(&job)
1955 {
1956 let negated = instrument::SourceMutant {
1957 start: site.start,
1958 end: site.end,
1959 replacement: format!("!({})", site.text),
1960 what: op.symbol().to_string(),
1961 into: "!".to_string(),
1962 };
1963 twins.push((file, site, negated, Some(job)));
1964 }
1965 }
1966 }
1967 let chosen = spread(twins.len(), wanted);
1968 audit.rebuilt = chosen.len();
1969 let mut twins: Vec<Option<_>> = twins.into_iter().map(Some).collect();
1970 built.extend(chosen.into_iter().filter_map(|nth| twins[nth].take()));
1971 }
1972 let mut by_speed: Vec<&TestBinary> = session.binaries.iter().collect();
1973 by_speed.sort_by_key(|bin| bin.baseline);
1974 let root_mutant_suffix = if files.iter().any(|file| {
1976 file.path != root_file
1977 && file
1978 .rendered
1979 .as_ref()
1980 .is_some_and(|rendered| rendered.text != file.original)
1981 }) {
1982 root_suffix.as_str()
1983 } else {
1984 ""
1985 };
1986 if !built.is_empty() {
1987 if options.timeout_seconds.is_some()
1988 && built
1989 .iter()
1990 .any(|(file, _, _, _)| built_sources.contains(file))
1991 {
1992 for bin in &by_speed {
1993 bin.warn_timeout_conflict(None);
1994 }
1995 }
1996 let source_checkpoint = if checkpoint.is_some() {
1997 let keys = built
1998 .iter()
1999 .map(|(file, _, mutation, twin)| {
2000 serde_json::to_string(&(
2001 &file.display,
2002 mutation.start,
2003 mutation.end,
2004 &mutation.replacement,
2005 twin,
2006 ))
2007 })
2008 .collect::<std::result::Result<Vec<_>, _>>()?;
2009 phase("source", keys)?
2010 } else {
2011 None
2012 };
2013 session.note(&format!(
2014 "building {} mutants one by one (code a probe cannot be put in, or to compare with the probe)",
2015 built.len()
2016 ));
2017 let instrumented = |file: &SourceFile, text: &str, suffix: &str| {
2018 if file.path == root_file {
2019 format!("{text}{suffix}")
2020 } else {
2021 text.to_string()
2022 }
2023 };
2024 let mut skipped_targets = BTreeSet::new();
2027 let mut left_out: BTreeMap<&PathBuf, Vec<(usize, usize)>> = BTreeMap::new();
2029 let mut survivors: Vec<(report::Location, Vec<String>)> = vec![];
2030 progress::track(
2031 options.progress,
2032 "source mutants",
2033 built.len(),
2034 |progress| -> Result<()> {
2035 for (index, (file, site, mutant, twin)) in built.iter().enumerate() {
2036 let cached = source_checkpoint
2037 .as_ref()
2038 .map(|phase| phase.get::<Option<Outcome>>(index))
2039 .transpose()?
2040 .flatten();
2041 let left_out = left_out
2042 .entry(&file.path)
2043 .or_insert_with(|| built_sources.left_out(file))
2044 .iter()
2045 .any(|(from, to)| *from <= site.start && site.end <= *to);
2046 if left_out || !built_sources.contains(file) {
2047 if let Some(phase) = source_checkpoint.as_ref().filter(|_| cached.is_none())
2048 {
2049 phase.record(index, &Some(Outcome::Unable))?;
2050 }
2051 if twin.is_none() {
2052 report.mutants_not_evaluated += 1;
2053 report.mutants_not_compiled += 1;
2054 if skipped_targets.insert((&file.path, site.start, site.end)) {
2055 report.skipped.push(report::SkippedSite::new(
2056 report::location(&file.display, site),
2057 file.lines.position(&file.original, site.end),
2058 report::SkipReason::SourceNotBuilt,
2059 left_out.then(|| {
2060 "under a `cfg` that the features of this build turn off"
2061 .to_string()
2062 }),
2063 ));
2064 }
2065 } else if let Some(audit) = report.audit.as_mut() {
2066 audit.not_compared += 1;
2067 }
2068 progress.complete(progress::Outcome::Unable);
2069 continue;
2070 }
2071 let outcome = if let Some(cached) = cached {
2072 cached
2073 } else {
2074 let mutated = format!(
2075 "{}{}{}",
2076 &file.original[..mutant.start],
2077 mutant.replacement,
2078 &file.original[mutant.end..]
2079 );
2080 let attempt = || -> Result<Option<Outcome>> {
2082 state.write(
2083 &file.path,
2084 &instrumented(file, &mutated, root_mutant_suffix),
2085 )?;
2086 match source_build(&cargo_build()?) {
2087 SourceBuild::Built => run_source_tests(&by_speed).map(Some),
2088 SourceBuild::Refused => Ok(None),
2089 SourceBuild::Failed(why) => {
2092 session.note(&format!(
2093 "a build failed without the compiler refusing the code; its mutant is not evaluated: {why}"
2094 ));
2095 Ok(Some(Outcome::Unable))
2096 }
2097 }
2098 };
2099 let attempted = attempt();
2100 let rendered = file.rendered.as_ref().expect("rendered before building");
2102 state.write(
2103 &file.path,
2104 &instrumented(file, &rendered.text, &root_suffix),
2105 )?;
2106 let outcome = attempted?;
2107 if let Some(phase) = &source_checkpoint
2110 && outcome != Some(Outcome::Unable)
2111 {
2112 phase.record(index, &outcome)?;
2113 }
2114 outcome
2115 };
2116 progress.complete(outcome.map_or(progress::Outcome::Unable, Into::into));
2117 if let Some(job) = twin {
2118 let as_probe = results[*job].survived.is_some();
2120 let Some(audit) = report.audit.as_mut() else {
2121 continue;
2122 };
2123 match audit_source_comparison(&results[*job], outcome) {
2126 Some(disagrees) => {
2127 audit.compared += 1;
2128 if disagrees {
2129 let verdict =
2130 |passes: bool| if passes { "passes" } else { "fails" };
2131 audit.source_disagreements.push(report::SourceDisagreement {
2132 at: report::location(&file.display, site),
2133 mutant: report::describe(site, mutation_of(site, mutant)),
2134 as_probe: verdict(as_probe).to_string(),
2135 built: verdict(!as_probe).to_string(),
2136 });
2137 }
2138 }
2139 None => audit.not_compared += 1,
2140 }
2141 continue;
2142 }
2143 match outcome {
2144 None => report.unviable_mutants += 1,
2145 Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
2146 Some(outcome) => {
2147 report.mutants_run += 1;
2148 report.mutants_killed += (outcome != Outcome::Pass) as usize;
2149 report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
2150 report.mutants_survived += (outcome == Outcome::Pass) as usize;
2151 }
2152 }
2153 let survived = outcome == Some(Outcome::Pass);
2154 if survived {
2155 let at = report::location(&file.display, site);
2156 let removed = mutant.replacement.trim().is_empty();
2158 let text = match (&site.kind, removed) {
2159 (SiteKind::Field { .. }, true) => {
2160 format!("without the field `{}`", report::one_line(&site.text))
2161 }
2162 (
2163 SiteKind::LiteralSet {
2164 receiver, argument, ..
2165 },
2166 true,
2167 ) => format!(
2168 "without `{}` in `{}.contains({})`",
2169 report::one_line(&mutant.into),
2170 report::one_line(receiver),
2171 report::one_line(argument)
2172 ),
2173 _ => report::describe(site, mutation_of(site, mutant)),
2174 };
2175 match survivors.last_mut() {
2176 Some((last, texts)) if *last == at => texts.push(text),
2177 _ => survivors.push((at, vec![text])),
2178 }
2179 }
2180 }
2181 Ok(())
2182 },
2183 )?;
2184 if let Some(phase) = &source_checkpoint {
2185 phase.finish_if_complete()?;
2186 }
2187 for (at, survivors) in survivors {
2188 finding_run_survivors.push(survivors.len());
2189 report.findings.push(Finding::Survivor {
2190 at,
2191 survivors,
2192 witness: None,
2193 change_since: None,
2194 advice: None,
2195 });
2196 }
2197 }
2198
2199 if let Some(revision) = options
2201 .since
2202 .as_deref()
2203 .filter(|_| !options.list && options.shard.is_none())
2204 {
2205 let hunks = scope::hunks(&since_diff(&workspace, revision)?);
2206 let not_built_changes = std::cell::Cell::new(0usize);
2207 let changed: Vec<(&SourceFile, Vec<reverts::Change>)> = files
2208 .iter()
2209 .filter(|file| built_sources.contains(file) || !options.source_only && !options.rebuild)
2210 .filter_map(|file| {
2211 let relative = file
2212 .path
2213 .strip_prefix(©)
2214 .ok()?
2215 .to_string_lossy()
2216 .replace('\\', "/");
2217 let of_file: Vec<_> = hunks
2218 .iter()
2219 .filter(|hunk| hunk.file == relative)
2220 .cloned()
2221 .collect();
2222 let mut changes = reverts::changes(&file.original, &of_file);
2223 if options.rebuild || options.source_only {
2226 for change in &mut changes {
2227 change.outside = change.undone.as_deref().is_some_and(|undone| {
2230 built_sources.same_program(file, &file.original, undone)
2231 });
2232 }
2233 not_built_changes.set(
2234 not_built_changes.get()
2235 + changes.iter().filter(|change| change.outside).count(),
2236 );
2237 }
2238 (!changes.is_empty()).then_some((file, changes))
2239 })
2240 .collect();
2241 let not_built_changes = not_built_changes.get();
2242 report.mutants_not_evaluated += not_built_changes;
2243 report.mutants_not_compiled += not_built_changes;
2244 let total: usize = changed
2246 .iter()
2247 .map(|(_, changes)| changes.iter().filter(|change| !change.outside).count())
2248 .sum();
2249 let mixed: usize = files
2252 .iter()
2253 .map(|file| {
2254 let relative = file
2255 .path
2256 .strip_prefix(©)
2257 .unwrap_or(&file.path)
2258 .to_string_lossy()
2259 .replace('\\', "/");
2260 let of_file: Vec<_> = hunks
2261 .iter()
2262 .filter(|hunk| hunk.file == relative)
2263 .cloned()
2264 .collect();
2265 reverts::mixed(&file.original, &of_file)
2266 })
2267 .sum();
2268 if mixed > 0 && (options.rebuild || options.source_only) {
2269 report.mutants_not_evaluated += mixed;
2270 session.note(&format!(
2271 "{mixed} changes are of the program and its tests in the same lines: they are not tried undone"
2272 ));
2273 }
2274 if !(options.rebuild || options.source_only) {
2275 report.mutants_not_built += not_built_reverts;
2276 } else if total > 0
2277 || changed.iter().any(|(_, changes)| {
2278 changes.iter().filter(|change| !change.is_subhunk()).count() > 1
2279 })
2280 {
2281 session.note(&format!(
2284 "building {total} changes undone, one by one (the code as it was at {})",
2285 report::short_revision(revision)
2286 ));
2287 let write = |file: &SourceFile, text: &str, suffix: &str| -> Result<()> {
2288 let suffix = if file.path == root_file { suffix } else { "" };
2289 state.write(&file.path, &format!("{text}{suffix}"))
2290 };
2291 let undone = |edits: &[(&SourceFile, &str)]| -> Result<Option<Outcome>> {
2293 let attempted = (|| -> Result<Option<Outcome>> {
2294 for (file, text) in edits {
2295 write(file, text, root_mutant_suffix)?;
2296 }
2297 Ok(match source_build(&cargo_build()?) {
2298 SourceBuild::Built => Some(run_source_tests(&by_speed)?),
2299 SourceBuild::Refused => None,
2300 SourceBuild::Failed(why) => {
2301 session.note(&format!(
2302 "a build failed without the compiler refusing the code; the change undone is not evaluated: {why}"
2303 ));
2304 Some(Outcome::Unable)
2305 }
2306 })
2307 })();
2308 for (file, _) in edits {
2310 let rendered = file.rendered.as_ref().expect("rendered before building");
2311 write(file, &rendered.text, &root_suffix)?;
2312 }
2313 attempted
2314 };
2315 let mut judged = |outcome: Option<Outcome>, at: report::Location, what: String| {
2316 match outcome {
2317 None => report.unviable_mutants += 1,
2318 Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
2319 Some(outcome) => {
2320 report.mutants_run += 1;
2321 report.mutants_killed += (outcome != Outcome::Pass) as usize;
2322 report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
2323 report.mutants_survived += (outcome == Outcome::Pass) as usize;
2324 }
2325 }
2326 if outcome == Some(Outcome::Pass) {
2327 finding_run_survivors.push(1);
2328 report.findings.push(Finding::Survivor {
2329 at,
2330 survivors: vec![what],
2331 witness: None,
2332 advice: None,
2333 change_since: Some(revision.to_string()),
2334 });
2335 }
2336 };
2337 let place = |file: &SourceFile, change: &reverts::Change| report::Location {
2338 file: file.display.clone(),
2339 line: change.line,
2340 column: 1,
2341 code: change.code.clone(),
2342 ..Default::default()
2343 };
2344 let mut stuck_files = 0;
2347 for (file, changes) in &changed {
2348 let mut stuck = false;
2349 let whole_total = changes.iter().filter(|change| !change.is_subhunk()).count();
2350 let whole_alone = changes
2351 .iter()
2352 .filter(|change| !change.is_subhunk() && !change.outside)
2353 .count();
2354 for change in changes.iter().filter(|change| !change.outside) {
2355 let outcome = match &change.undone {
2356 Some(text) => undone(&[(file, text.as_str())])?,
2357 None => None,
2358 };
2359 if !change.is_subhunk() {
2360 stuck |= outcome.is_none();
2361 }
2362 judged(outcome, place(file, change), change.describe());
2363 }
2364 let whole = reverts::all_undone(&file.original, changes);
2369 let same = |a: &str, b: &str| built_sources.same_program(file, a, b);
2370 let tried: Vec<reverts::Change> = changes
2371 .iter()
2372 .filter(|change| !change.outside)
2373 .cloned()
2374 .collect();
2375 let left_out_matter = whole_alone < whole_total
2376 && match (&whole, reverts::all_undone(&file.original, &tried)) {
2377 (Some(all), Some(without)) => !same(all, &without),
2378 _ => true,
2379 };
2380 let another = whole
2382 .as_deref()
2383 .is_none_or(|all| !same(all, &file.original));
2384 if whole_total > 1 && another && (stuck || left_out_matter) {
2385 let outcome = match &whole {
2386 Some(text) => undone(&[(file, text.as_str())])?,
2387 None => None,
2388 };
2389 stuck = outcome.is_none();
2390 let first_whole = changes
2391 .iter()
2392 .find(|change| !change.is_subhunk())
2393 .unwrap_or(&changes[0]);
2394 judged(
2395 outcome,
2396 place(file, first_whole),
2397 format!("with all {whole_total} changes to this file undone"),
2398 );
2399 }
2400 stuck_files += usize::from(stuck);
2401 }
2402 let with_left_out = changed.iter().any(|(_, changes)| {
2406 changes
2407 .iter()
2408 .any(|change| !change.is_subhunk() && change.outside)
2409 });
2410 if (stuck_files > 0 || with_left_out) && changed.len() > 1 {
2411 let whole: Option<Vec<String>> = changed
2412 .iter()
2413 .map(|(file, changes)| reverts::all_undone(&file.original, changes))
2414 .collect();
2415 let same =
2416 |file: &SourceFile, a: &str, b: &str| built_sources.same_program(file, a, b);
2417 let another = whole.as_ref().is_none_or(|texts| {
2419 changed
2420 .iter()
2421 .zip(texts)
2422 .any(|((file, _), text)| !same(file, text, &file.original))
2423 });
2424 let left_out_matter = whole.as_ref().is_none_or(|texts| {
2427 changed.iter().zip(texts).any(|((file, changes), text)| {
2428 let tried: Vec<reverts::Change> = changes
2429 .iter()
2430 .filter(|change| !change.outside)
2431 .cloned()
2432 .collect();
2433 reverts::all_undone(&file.original, &tried)
2434 .is_none_or(|without| !same(file, text, &without))
2435 })
2436 });
2437 if another && (stuck_files > 0 || (with_left_out && left_out_matter)) {
2438 let outcome = match &whole {
2439 Some(texts) => {
2440 let edits: Vec<(&SourceFile, &str)> = changed
2441 .iter()
2442 .zip(texts)
2443 .map(|((file, _), text)| (*file, text.as_str()))
2444 .collect();
2445 undone(&edits)?
2446 }
2447 None => None,
2448 };
2449 let (file, changes) = &changed[0];
2450 judged(
2451 outcome,
2452 place(file, &changes[0]),
2453 format!("with every change undone, in all {} files", changed.len()),
2454 );
2455 }
2456 }
2457 }
2458 }
2459
2460 let mut witness_files: Vec<&PathBuf> = vec![];
2463 for candidate in &witness_candidates {
2464 if !witness_files.contains(&&candidate.file) {
2465 witness_files.push(&candidate.file);
2466 }
2467 }
2468 for witness_file in witness_files {
2469 let in_root = *witness_file == root_file;
2470 let witness_candidates: Vec<&witness::Candidate> = witness_candidates
2471 .iter()
2472 .filter(|candidate| candidate.file == *witness_file)
2473 .collect();
2474 let file = files
2475 .iter()
2476 .find(|file| file.path == *witness_file)
2477 .expect("witness candidates are of files that are analysed");
2478 let rendered = file.rendered.as_ref().expect("rendered before building");
2479 let left_out_here = built_sources.left_out(file);
2480 let restore = if in_root {
2481 format!("{}{root_suffix}", rendered.text)
2482 } else {
2483 rendered.text.clone()
2484 };
2485 let library_runners: Vec<_> = session
2486 .binaries
2487 .iter()
2488 .filter(|bin| {
2489 root_exe
2490 .as_deref()
2491 .is_some_and(|exe| bin.runner.executable() == Some(exe))
2492 })
2493 .collect();
2494 let ignored = library_runners
2495 .iter()
2496 .find_map(|bin| match &bin.runner {
2497 Runner::Exe(exe) => Some(list_tests(
2498 exe,
2499 &bin.cwd,
2500 &bin.git_ceiling,
2501 true,
2502 false,
2503 bin.work_lock.as_deref(),
2504 )),
2505 _ => None,
2506 })
2507 .transpose()?
2508 .unwrap_or_default();
2509 let runner_for = |scenario: &witness::Scenario| {
2510 library_runners.iter().copied().find(|bin| {
2511 scenario
2512 .source_test
2513 .as_ref()
2514 .is_none_or(|required| match &bin.runner {
2515 Runner::Exe(_) if !in_root => {
2518 let inner = format!("::{required}");
2519 bin.tests
2520 .iter()
2521 .any(|test| test.ends_with(&inner) && !ignored.contains(test))
2522 }
2523 Runner::Exe(_) => {
2524 bin.tests.contains(required) && !ignored.contains(required)
2525 }
2526 Runner::Isolated { test, .. } if !in_root => {
2527 test.ends_with(&format!("::{required}"))
2528 }
2529 Runner::Isolated { test, .. } => test == required,
2530 Runner::Doc { .. } | Runner::Nextest { .. } => false,
2531 })
2532 })
2533 };
2534 let write_edits = |edits: &[witness::Edit]| -> Result<bool> {
2535 let Some(source) = witness::render_edits(&file.original, edits, None) else {
2536 return Ok(false);
2537 };
2538 let suffix = if in_root { root_mutant_suffix } else { "" };
2539 state.write(&file.path, &format!("{source}{suffix}"))?;
2540 Ok(true)
2541 };
2542 let suite = |edits: &[witness::Edit]| -> Result<Option<Outcome>> {
2543 if !write_edits(edits)? {
2544 return Ok(None);
2545 }
2546 Ok(match source_build(&cargo_build()?) {
2547 SourceBuild::Built => Some(run_source_tests(&by_speed)?),
2548 SourceBuild::Refused => None,
2549 SourceBuild::Failed(why) => {
2550 session.note(&format!(
2551 "a build failed without the compiler refusing the code; the mutant is not evaluated: {why}"
2552 ));
2553 Some(Outcome::Unable)
2554 }
2555 })
2556 };
2557 let compile_observer = |edits: &[witness::Edit]| -> Result<Option<PathBuf>> {
2558 if !write_edits(edits)? {
2559 return Ok(None);
2560 }
2561 let build = build_test_binaries(true)?;
2562 if !build.status.success() {
2563 return Ok(None);
2564 }
2565 let artifacts = parse_build_output(
2566 &String::from_utf8_lossy(&build.stdout),
2567 &[package.name.as_str()],
2568 );
2569 Ok(root_test_exe(&artifacts))
2570 };
2571 let observe = |scenario: &witness::Scenario,
2572 baseline: &TestBinary,
2573 edits: &[witness::Edit],
2574 field_path: Option<&str>,
2575 expected: Option<&str>|
2576 -> Result<Option<witness::Observation>> {
2577 let test = scenario.test_edit_with_field(
2578 &file.original,
2579 witness::TEST_NAME,
2580 field_path,
2581 expected,
2582 );
2583 let edits: Vec<_> = edits.iter().cloned().chain([test]).collect();
2584 let Some(exe) = compile_observer(&edits)? else {
2585 return Ok(None);
2586 };
2587 observe_witness(
2588 baseline,
2589 exe,
2590 wrapper.as_deref(),
2591 scenario,
2592 witness::TEST_NAME,
2593 expected.is_some(),
2594 in_root,
2595 )
2596 };
2597 let witness_checkpoint = if checkpoint.is_some() {
2598 let keys = witness_candidates
2599 .iter()
2600 .map(|candidate| {
2601 let edits = candidate
2602 .edits
2603 .iter()
2604 .map(|edit| (&edit.span, &edit.replacement))
2605 .collect::<Vec<_>>();
2606 serde_json::to_string(&(&candidate.description, edits))
2607 })
2608 .collect::<std::result::Result<Vec<_>, _>>()?;
2609 let name = if in_root {
2610 "witness".to_string()
2611 } else {
2612 format!("witness:{}", file.display)
2613 };
2614 phase(&name, keys)?
2615 } else {
2616 None
2617 };
2618 let mut survivors = vec![];
2619 let mut claimed = BTreeSet::new();
2620 progress::track(
2621 options.progress,
2622 "source witness mutants",
2623 witness_candidates.len(),
2624 |progress| -> Result<()> {
2625 for (index, candidate) in witness_candidates.iter().copied().enumerate() {
2626 let cached = witness_checkpoint
2627 .as_ref()
2628 .map(|phase| phase.get::<WitnessTrial>(index))
2629 .transpose()?
2630 .flatten();
2631 let at = witness_location(file, candidate);
2632 if !built_sources.contains(file)
2634 || candidate.edits.iter().any(|edit| {
2635 left_out_here
2636 .iter()
2637 .any(|(from, to)| *from <= edit.span.start && edit.span.end <= *to)
2638 })
2639 {
2640 if let Some(phase) =
2641 witness_checkpoint.as_ref().filter(|_| cached.is_none())
2642 {
2643 phase.record(index, &WitnessTrial::Inapplicable)?;
2644 }
2645 if !candidate.existing {
2646 report.mutants_not_evaluated += 1;
2647 report.mutants_not_compiled += 1;
2648 let span = &candidate.edits[0].span;
2649 report.skipped.push(report::SkippedSite::new(
2650 at,
2651 file.lines.position(&file.original, span.end),
2652 report::SkipReason::SourceNotBuilt,
2653 Some(
2654 "under a `cfg` that the features of this build turn off"
2655 .to_string(),
2656 ),
2657 ));
2658 }
2659 progress.complete(progress::Outcome::Unable);
2660 continue;
2661 }
2662 let existing = candidate
2663 .existing
2664 .then(|| {
2665 report.findings.iter().position(|finding| {
2666 let location = finding.at();
2667 location.file == at.file
2668 && location.line == at.line
2669 && location.column == at.column
2670 && finding.survivors().contains(&candidate.description)
2671 && (candidate.finding_at.is_none()
2672 || !matches!(finding, Finding::InputGap { .. }))
2673 })
2674 })
2675 .flatten();
2676 let existing = existing
2680 .filter(|index| candidate.finding_at.is_none() || !claimed.contains(index));
2681 let scenarios: Vec<_> = candidate
2682 .scenarios
2683 .iter()
2684 .filter_map(|scenario| {
2685 runner_for(scenario).map(|runner| (scenario, runner))
2686 })
2687 .take(4)
2688 .collect();
2689 let paired = candidate.edits.len() > 1;
2690 if (candidate.existing && (existing.is_none() || scenarios.is_empty()))
2691 || (paired && scenarios.is_empty())
2692 {
2693 if let Some(phase) =
2694 witness_checkpoint.as_ref().filter(|_| cached.is_none())
2695 {
2696 phase.record(index, &WitnessTrial::Inapplicable)?;
2697 }
2698 progress.complete(progress::Outcome::Unable);
2699 continue;
2700 }
2701 let trial = if let Some(cached) = cached {
2704 cached
2705 } else {
2706 let attempted = (|| -> Result<WitnessTrial> {
2707 if paired {
2708 for edit in &candidate.edits {
2709 match suite(std::slice::from_ref(edit))? {
2710 Some(Outcome::Fail) => {}
2711 Some(Outcome::Unable) => {
2712 return Ok(WitnessTrial::Evaluated(Outcome::Unable));
2713 }
2714 _ => return Ok(WitnessTrial::Inapplicable),
2715 }
2716 }
2717 }
2718 Ok(suite(&candidate.edits)?
2719 .map_or(WitnessTrial::Unviable, WitnessTrial::Evaluated))
2720 })();
2721 state.write(&file.path, &restore)?;
2722 let trial = attempted?;
2723 if let Some(phase) = &witness_checkpoint
2724 && !matches!(trial, WitnessTrial::Evaluated(Outcome::Unable))
2725 {
2726 phase.record(index, &trial)?;
2727 }
2728 trial
2729 };
2730 let outcome = match trial {
2731 WitnessTrial::Inapplicable => {
2732 progress.complete(progress::Outcome::Unable);
2733 continue;
2734 }
2735 WitnessTrial::Unviable => {
2736 progress.complete(progress::Outcome::Unable);
2737 report.unviable_mutants += usize::from(!candidate.existing);
2738 continue;
2739 }
2740 WitnessTrial::Evaluated(outcome) => outcome,
2741 };
2742 progress.complete(outcome.into());
2743 if !candidate.existing {
2744 match outcome {
2745 Outcome::Unable => report.mutants_not_evaluated += 1,
2746 Outcome::Pass => {
2747 report.mutants_run += 1;
2748 report.mutants_survived += 1;
2749 }
2750 Outcome::Fail => {
2751 report.mutants_run += 1;
2752 report.mutants_killed += 1;
2753 }
2754 Outcome::Timeout => {
2755 report.mutants_run += 1;
2756 report.mutants_killed += 1;
2757 report.mutants_timed_out += 1;
2758 }
2759 }
2760 }
2761 if outcome == Outcome::Pass {
2762 survivors.push(WitnessSurvivor {
2763 candidate,
2764 at,
2765 existing,
2766 scenarios,
2767 });
2768 }
2769 }
2770 Ok(())
2771 },
2772 )?;
2773
2774 if let Some(phase) = &witness_checkpoint {
2775 phase.finish()?;
2776 }
2777 let originals = shared_witnesses(
2778 &file.original,
2779 &survivors,
2780 wrapper.as_deref(),
2781 in_root,
2782 compile_observer,
2783 note,
2784 );
2785 if !survivors.is_empty() {
2786 state.write(&file.path, &restore)?;
2787 }
2788 let originals = originals?;
2789
2790 progress::track(
2791 options.progress,
2792 "distinguishing tests",
2793 survivors.len(),
2794 |progress| -> Result<()> {
2795 for (survivor, original) in survivors.into_iter().zip(originals) {
2796 if survivor.existing.is_some_and(|index| {
2797 survivor.candidate.finding_at.is_some() && claimed.contains(&index)
2798 }) {
2799 progress.complete(progress::Outcome::Unable);
2800 continue;
2801 }
2802 let mut evidence = None;
2803 let mut original = original;
2804 for (scenario, baseline) in survivor.scenarios {
2805 let shared = original.take();
2806 let distinction = (|| -> Result<_> {
2807 if let Some(shared) = shared {
2808 let edits: Vec<_> = survivor
2810 .candidate
2811 .edits
2812 .iter()
2813 .chain(shared.tests.iter())
2814 .cloned()
2815 .collect();
2816 if let Some(exe) = compile_observer(&edits)?
2817 && let Some(mutant) = observe_witness(
2818 baseline,
2819 exe,
2820 wrapper.as_deref(),
2821 scenario,
2822 &shared.name,
2823 true,
2824 in_root,
2825 )
2826 .ok()
2827 .flatten()
2828 && mutant.equals_expected == Some(false)
2829 && observe_witness(
2832 baseline,
2833 shared.original_exe.path.clone(),
2834 wrapper.as_deref(),
2835 scenario,
2836 &shared.name,
2837 true,
2838 in_root,
2839 )
2840 .ok()
2841 .flatten()
2842 .is_some_and(|rechecked| {
2843 rechecked.equals_expected == Some(true)
2844 && rechecked.value == shared.value
2845 })
2846 && let Some(verified) =
2847 scenario.verified(shared.value, mutant.value)
2848 {
2849 return Ok(Some(verified));
2850 }
2851 }
2854 let Some(original) = observe(scenario, baseline, &[], None, None)?
2855 else {
2856 return Ok(None);
2857 };
2858 let value = original.value;
2859 if witness::is_expected_literal(&value) {
2860 let Some(mutant) = observe(
2861 scenario,
2862 baseline,
2863 &survivor.candidate.edits,
2864 None,
2865 Some(&value),
2866 )?
2867 else {
2868 return Ok(None);
2869 };
2870 if mutant.equals_expected != Some(false) || value == mutant.value {
2871 return Ok(None);
2872 }
2873 let Some(checked) =
2874 observe(scenario, baseline, &[], None, Some(&value))?
2875 else {
2876 return Ok(None);
2877 };
2878 if checked.equals_expected != Some(true) || checked.value != value {
2879 return Ok(None);
2880 }
2881 return Ok(scenario.verified(value, mutant.value));
2882 }
2883 if witness::parse_debug_struct(&value).is_none() {
2886 return Ok(None);
2887 }
2888 let Some(raw_mutant) =
2889 observe(scenario, baseline, &survivor.candidate.edits, None, None)?
2890 else {
2891 return Ok(None);
2892 };
2893 let Some((path, field_orig, _)) =
2894 witness::narrow_struct_field(&value, &raw_mutant.value)
2895 else {
2896 return Ok(None);
2897 };
2898 if !witness::is_expected_literal(&field_orig) {
2899 return Ok(None);
2900 }
2901 let field_path = path.join(".");
2902 let Some(mutant) = observe(
2903 scenario,
2904 baseline,
2905 &survivor.candidate.edits,
2906 Some(&field_path),
2907 Some(&field_orig),
2908 )?
2909 else {
2910 return Ok(None);
2911 };
2912 if mutant.equals_expected != Some(false)
2913 || mutant.value != raw_mutant.value
2914 || value == mutant.value
2915 {
2916 return Ok(None);
2917 }
2918 let Some(checked) = observe(
2919 scenario,
2920 baseline,
2921 &[],
2922 Some(&field_path),
2923 Some(&field_orig),
2924 )?
2925 else {
2926 return Ok(None);
2927 };
2928 if checked.equals_expected != Some(true) || checked.value != value {
2929 return Ok(None);
2930 }
2931 Ok(
2932 scenario.verified_field(
2933 value,
2934 mutant.value,
2935 field_path,
2936 field_orig,
2937 ),
2938 )
2939 })();
2940 match distinction {
2941 Ok(Some(mut verified)) => {
2942 let edits = survivor.candidate.edits.len();
2943 verified.individually_killed = (edits > 1).then_some(edits);
2944 evidence = Some(verified);
2945 break;
2946 }
2947 Ok(None) => {}
2948 Err(err) => note(&format!(
2949 "could not check a distinguishing test for {}: {err:#}",
2950 scenario.expression,
2951 )),
2952 }
2953 }
2954 state.write(&file.path, &restore)?;
2955 progress.complete(Outcome::Pass.into());
2956 if let Some(index) = survivor.existing {
2957 if let Some(evidence) = evidence {
2958 report.findings[index].set_witness(evidence);
2959 if survivor.candidate.finding_at.is_some() {
2960 claimed.insert(index);
2961 }
2962 }
2963 } else {
2964 finding_run_survivors.push(1);
2965 report.findings.push(Finding::Survivor {
2966 at: survivor.at,
2967 survivors: vec![survivor.candidate.description.clone()],
2968 advice: survivor
2969 .candidate
2970 .advice
2971 .clone()
2972 .filter(|_| evidence.is_none()),
2973 witness: evidence,
2974 change_since: None,
2975 });
2976 }
2977 }
2978 Ok(())
2979 },
2980 )?;
2981 }
2982
2983 report.record_evaluation();
2984 debug_assert_eq!(report.findings.len(), finding_run_survivors.len());
2985 let mut paired_findings: Vec<(Finding, usize)> = report
2986 .findings
2987 .into_iter()
2988 .zip(finding_run_survivors)
2989 .collect();
2990 paired_findings.sort_by(|(a, _), (b, _)| {
2991 let (a, b) = (a.at(), b.at());
2992 (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column))
2993 });
2994 let (sorted_findings, finding_run_survivors): (Vec<_>, Vec<_>) =
2995 paired_findings.into_iter().unzip();
2996 report.findings = sorted_findings;
2997 let places: Vec<FilePlaces> = files
2998 .iter()
2999 .map(|file| FilePlaces {
3000 display: &file.display,
3001 source: &file.original,
3002 lines: &file.lines,
3003 places: &file.places,
3004 })
3005 .collect();
3006 name_findings(&mut report.findings, &places);
3007
3008 apply_suppressions_and_finish(
3010 options,
3011 &files,
3012 &mut report,
3013 &finding_run_survivors,
3014 checkpoint.as_ref(),
3015 )?;
3016 debug_assert!(
3017 report.counts_reconcile(),
3018 "report counts do not reconcile: {report:#?}"
3019 );
3020 Ok(report)
3021}
3022
3023fn validate_package_options(options: &Options) -> Result<Vec<&str>> {
3024 if let Some(shard) = options.shard
3025 && (!options.source_only || shard.index >= shard.count)
3026 {
3027 bail!("shards require --source-only and a valid shard index");
3028 }
3029 let mut seen_errors = HashSet::new();
3030 let mut error_values = vec![];
3031 for expression in &options.error_values {
3032 let expression = expression.trim();
3033 if expression.chars().any(char::is_control) {
3036 bail!(
3037 "invalid --error expression {expression:?}: it has to be on one line, \
3038 without control characters"
3039 );
3040 }
3041 let parsed = syn::parse_str::<syn::Expr>(expression)
3042 .with_context(|| format!("invalid --error expression {expression:?}"))?;
3043 if seen_errors.insert(quote::ToTokens::to_token_stream(&parsed).to_string()) {
3044 error_values.push(expression);
3045 }
3046 }
3047 let selection = &options.test_selection;
3048 if options.nextest.is_some() {
3049 if !cfg!(unix) {
3050 bail!("the nextest runner is available on Unix");
3051 }
3052 if !options.source_only || options.doc || selection.enabled() {
3053 bail!(
3054 "--test-tool nextest requires --source-only; select tests through the nextest profile"
3055 );
3056 }
3057 }
3058 if options.baseline_jobs > 1 && !selection.enabled() {
3059 bail!("--baseline-jobs requires isolated tests or a test wrapper or selection");
3060 }
3061 if options.doc && selection.enabled() {
3062 bail!("--doc cannot be combined with isolated test selection");
3063 }
3064 if options.source_only && options.jobs > 1 {
3065 eprintln!(
3066 "tmt: warning: --source-only runs mutants serially in one working copy; ignoring --jobs {}",
3067 options.jobs
3068 );
3069 }
3070 Ok(error_values)
3071}
3072
3073struct PreparedWorkCopy {
3074 workspace: PathBuf,
3075 work: PathBuf,
3076 work_lock: Option<Arc<WorkLock>>,
3077 copy: PathBuf,
3078 state: WorkCopy,
3079}
3080
3081fn prepare_work_copy(
3082 options: &Options,
3083 metadata: &Metadata,
3084 batch: Option<&WorkspaceBatch<'_>>,
3085 catalogue: Option<&CatalogueSnapshot>,
3086 note: &impl Fn(&str),
3087) -> Result<PreparedWorkCopy> {
3088 let workspace = metadata.workspace_root.canonicalize()?;
3089 let requested_work = catalogue
3090 .map(|catalogue| &catalogue.path)
3091 .or(options.work_dir.as_ref());
3092 let work = match requested_work {
3093 Some(dir) => {
3094 fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
3095 dir.canonicalize()?
3096 }
3097 None => metadata.target_directory.join("tmt"),
3098 };
3099 if workspace.starts_with(&work) {
3102 bail!(
3103 "the work directory {} contains the workspace; choose a directory of its own",
3104 work.display()
3105 );
3106 }
3107 fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?;
3108 let work = work.canonicalize()?;
3109 let work_lock = if catalogue.is_none() {
3110 Some(Arc::new(WorkLock::take(&work)?))
3111 } else {
3112 None
3113 };
3114 let copy = work.join("src");
3115 let marker = work.join(WORK_MARKER);
3116 if copy.exists() && !marker.exists() {
3117 bail!(
3118 "{} exists and was not created by tmt; refusing to delete it. \
3119 Choose another --work-dir or remove it yourself.",
3120 copy.display()
3121 );
3122 }
3123 fs::write(
3124 &marker,
3125 "Working directory of tmt (targeted-mutation). Safe to delete.\n",
3126 )?;
3127 let target_dir = metadata.target_directory.clone();
3128 let forbidden = |path: &Path| {
3129 path == target_dir
3130 || path == work
3131 || batch.is_some_and(|batch| path == batch.work)
3132 || path.file_name().is_some_and(|n| n == ".git")
3133 || (path.parent() == Some(workspace.as_path())
3134 && path.file_name().is_some_and(|n| n == "target"))
3135 };
3136 let state = WorkCopy::open(&work, ©);
3137 let fixtures = options
3138 .copy_fixtures
3139 .iter()
3140 .map(|path| fixture_relative(path))
3141 .collect::<Result<Vec<_>>>()?;
3142 let excluded = fixture_exclusions(&workspace, &fixtures, &options.copy_fixture_excludes)?;
3143 let fixture_forbidden = |path: &Path| forbidden(path) || excluded.contains(path);
3144 let skip = |path: &Path| {
3145 fixture_forbidden(path) || path.file_name().is_some_and(|n| n == "node_modules")
3146 };
3147 if options.progress && !options.list {
3148 for path in &excluded {
3149 note(&format!(
3150 "excluded fixture {}",
3151 path.strip_prefix(&workspace).unwrap_or(path).display()
3152 ));
3153 }
3154 }
3155 if catalogue.is_none_or(|catalogue| !catalogue.ready.get()) {
3156 work_directory(&work, "src")?;
3157 let visible = if options.all_files {
3158 None
3159 } else {
3160 git_visible_files(&workspace)?
3161 };
3162 match visible {
3163 Some(files) => {
3166 let copied = copy_git_visible(&workspace, ©, files, &workspace, &skip, &state)?;
3167 note(&format!(
3168 "copied {copied} files (ignored files are left out)"
3169 ));
3170 }
3171 None => copy_tree(&workspace, ©, &workspace, &skip, &state)?,
3172 }
3173 for relative in &fixtures {
3174 copy_fixture_entry(
3175 &workspace.join(relative),
3176 ©.join(relative),
3177 &workspace,
3178 &fixture_forbidden,
3179 &state,
3180 &mut BTreeSet::new(),
3181 )?;
3182 }
3183 prune(©, &state)?;
3184 if options.git_index {
3185 git_index::snapshot(&workspace, ©)?;
3186 }
3187 if !options.list {
3188 let mut manifests: Vec<&Path> = metadata
3190 .packages
3191 .iter()
3192 .map(|p| p.manifest_path.as_path())
3193 .collect();
3194 let root_manifest = metadata.workspace_root.join("Cargo.toml");
3195 manifests.push(&root_manifest);
3196 for manifest in manifests {
3197 let Ok(canonical) = manifest.canonicalize() else {
3198 continue;
3199 };
3200 let (Some(manifest_dir), Ok(relative)) =
3201 (canonical.parent(), canonical.strip_prefix(&workspace))
3202 else {
3203 continue;
3204 };
3205 let text = fs::read_to_string(&canonical)?;
3206 if let Some(rewritten) =
3207 absolutize_path_dependencies(&text, manifest_dir, &workspace, ©)?
3208 {
3209 state.write(©.join(relative), &rewritten)?;
3210 }
3211 }
3212 }
3213 if let Some(catalogue) = catalogue {
3214 state.settle(&workspace)?;
3215 catalogue.ready.set(true);
3216 }
3217 }
3218 Ok(PreparedWorkCopy {
3219 workspace,
3220 work,
3221 work_lock,
3222 copy,
3223 state,
3224 })
3225}
3226
3227#[allow(clippy::too_many_arguments)]
3228fn run_audit_phase<'a>(
3229 session: &Session,
3230 files: &[SourceFile],
3231 jobs: &[Job],
3232 results: &mut [JobResult],
3233 timeout_rechecks: &mut report::TimeoutRechecks,
3234 scratch: &Path,
3235 wanted: usize,
3236 workers: usize,
3237 probe_phase: &impl Fn(&str, &[Job]) -> Result<Option<Phase<'a>>>,
3238) -> Result<report::Audit> {
3239 let survivors: Vec<usize> = (0..jobs.len())
3240 .filter(|job| results[*job].survived.is_some())
3241 .collect();
3242 let chosen: Vec<usize> = spread(survivors.len(), wanted)
3243 .into_iter()
3244 .map(|nth| survivors[nth])
3245 .collect();
3246 session.note(&format!(
3247 "audit: running {} of {} surviving mutants against all tests",
3248 chosen.len(),
3249 survivors.len()
3250 ));
3251 let against_all: Vec<Job> = chosen
3252 .iter()
3253 .map(|job| Job {
3254 site: jobs[*job].site,
3255 mutation: jobs[*job].mutation,
3256 tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
3257 })
3258 .collect();
3259 let mut audit = report::Audit {
3260 sampled: chosen.len(),
3261 survivors: survivors.len(),
3262 ..report::Audit::default()
3263 };
3264 let audit_checkpoint = probe_phase("audit", &against_all)?;
3265 for (job, again) in chosen.iter().zip(session.run_jobs(
3266 &against_all,
3267 workers,
3268 "audit mutants",
3269 audit_checkpoint.as_ref(),
3270 )?) {
3271 timeout_rechecks.include(&again);
3272 if again.unable || again.unconfirmed_timeout {
3273 audit.not_audited += 1;
3274 } else if audit_all_tests_disagrees(&again) {
3275 results[*job] = again;
3277 let site = files
3278 .iter()
3279 .find_map(|f| Some((f, f.sites.iter().find(|s| s.id == jobs[*job].site)?)));
3280 if let Some((file, site)) = site {
3281 audit
3282 .disagreements
3283 .push(report::location(&file.display, site));
3284 }
3285 }
3286 }
3287 session.note("audit: recording the tests once more");
3288 for (index, bin) in session.binaries.iter().enumerate() {
3289 let path = scratch.join(format!("trace-{index}-audit.tsv"));
3290 let _ = fs::remove_file(&path);
3291 let trace_env = path.to_string_lossy().into_owned();
3292 let limit = Duration::from_secs(3600);
3293 let outcome = run_binary(
3294 bin,
3295 None,
3296 &[("TMT_TRACE", &trace_env)],
3297 limit,
3298 RunOutput::Quiet,
3299 1,
3300 )?;
3301 let again = Trace::parse(&fs::read_to_string(&path).unwrap_or_default());
3302 let _ = fs::remove_file(&path);
3303 let records = bin.trace.differences(&again);
3304 if outcome != Outcome::Pass || records > 0 {
3305 audit.trace_differences.push(report::TraceDifference {
3306 binary: bin.name.clone(),
3307 records,
3308 rerun_failed: outcome != Outcome::Pass,
3309 });
3310 }
3311 }
3312 Ok(audit)
3313}
3314
3315fn run_effects_phase(
3316 session: &Session,
3317 files: &[SourceFile],
3318 jobs: &[Job],
3319 effect_jobs: &[(usize, usize)],
3320 scratch: &Path,
3321 workers: usize,
3322 findings: &mut [Finding],
3323) -> Result<()> {
3324 session.note(&format!("tracing {} surviving mutants", effect_jobs.len()));
3325 let sites: BTreeMap<u32, (&str, &Site)> = files
3326 .iter()
3327 .flat_map(|f| f.sites.iter().map(move |s| (s.id, (f.display.as_str(), s))))
3328 .collect();
3329 let traced = run_pool(effect_jobs.len(), workers, |index| {
3330 session.trace_job(
3331 &jobs[effect_jobs[index].1],
3332 scratch,
3333 workers.clamp(1, effect_jobs.len()),
3334 )
3335 })?;
3336 for ((finding, job), mut changes) in effect_jobs.iter().zip(traced) {
3337 if let Some((mutated_file, mutated)) = sites.get(&jobs[*job].site) {
3340 for found in changes.values_mut() {
3341 found.retain(|change| {
3342 sites.get(&change.site()).is_none_or(|(file, site)| {
3343 file != mutated_file
3344 || site.end <= mutated.start
3345 || mutated.end <= site.start
3346 })
3347 });
3348 }
3349 changes.retain(|_, found| !found.is_empty());
3350 }
3351 if let Finding::AssertionGap {
3352 effects,
3353 effects_of,
3354 ..
3355 } = &mut findings[*finding]
3356 {
3357 *effects = describe_effects(&changes, &sites);
3358 *effects_of = sites
3359 .get(&jobs[*job].site)
3360 .map(|(_, site)| report::describe(site, jobs[*job].mutation));
3361 }
3362 }
3363 Ok(())
3364}
3365
3366fn apply_suppressions_and_finish(
3367 options: &Options,
3368 files: &[SourceFile],
3369 report: &mut Report,
3370 finding_run_survivors: &[usize],
3371 checkpoint: Option<&Checkpoint>,
3372) -> Result<()> {
3373 let files_with_findings: BTreeSet<&str> = report
3374 .findings
3375 .iter()
3376 .map(|finding| finding.at().file.as_str())
3377 .collect();
3378 let ignored: BTreeMap<&str, BTreeMap<usize, String>> = files
3379 .iter()
3380 .filter(|file| files_with_findings.contains(file.display.as_str()))
3381 .map(|f| {
3382 (
3383 f.display.as_str(),
3384 crate::baseline::ignored_lines(&f.original),
3385 )
3386 })
3387 .collect();
3388 let known = match &options.baseline {
3389 Some(path) => Some(crate::baseline::load(path)?),
3390 None => None,
3391 };
3392 let before = report.findings.len();
3393 let mut after_inline: Vec<(Finding, usize)> = Vec::with_capacity(before);
3394 for (finding, run_survivors) in report
3395 .findings
3396 .drain(..)
3397 .zip(finding_run_survivors.iter().copied())
3398 {
3399 let at = finding.at();
3400 if ignored
3401 .get(at.file.as_str())
3402 .is_some_and(|lines| lines.contains_key(&at.line))
3403 {
3404 report.survivor_breakdown.suppressed += run_survivors;
3405 } else {
3406 after_inline.push((finding, run_survivors));
3407 }
3408 }
3409 if let Some(path) = &options.write_baseline {
3410 let unignored: Vec<Finding> = after_inline.iter().map(|(f, _)| f.clone()).collect();
3411 crate::baseline::write(path, &unignored)?;
3412 }
3413 for (finding, run_survivors) in after_inline {
3414 if known.as_ref().is_some_and(|known| known.knows(&finding)) {
3415 report.survivor_breakdown.suppressed += run_survivors;
3416 } else {
3417 report.survivor_breakdown.reported += run_survivors;
3418 report.findings.push(finding);
3419 }
3420 }
3421 report.suppressed = before - report.findings.len();
3422 if let Some(checkpoint) = checkpoint {
3423 checkpoint.finish_if_complete()?;
3424 }
3425 Ok(())
3426}
3427
3428fn workspace_report_prefix(relative: &Path) -> String {
3429 let parts: Vec<_> = relative
3430 .components()
3431 .filter_map(|part| match part {
3432 std::path::Component::Normal(name) => Some(name.to_string_lossy()),
3433 _ => None,
3434 })
3435 .collect();
3436 if parts.is_empty() {
3437 String::new()
3438 } else {
3439 format!("{}/", parts.join("/"))
3440 }
3441}
3442
3443fn repository_prefix(dir: &Path) -> String {
3447 let shown = Command::new("git")
3448 .arg("-C")
3449 .arg(dir)
3450 .args(["rev-parse", "--show-prefix"])
3451 .stderr(Stdio::null())
3452 .output();
3453 match shown {
3454 Ok(output) if output.status.success() => {
3455 String::from_utf8_lossy(&output.stdout).trim().to_string()
3456 }
3457 _ => String::new(),
3458 }
3459}
3460
3461fn spread(count: usize, wanted: usize) -> Vec<usize> {
3464 let wanted = wanted.min(count);
3465 (0..wanted).map(|nth| nth * count / wanted).collect()
3466}
3467
3468struct FilePlaces<'a> {
3470 display: &'a str,
3471 source: &'a str,
3472 lines: &'a scope::LineIndex,
3473 places: &'a [(usize, usize, String)],
3475}
3476
3477fn name_findings(findings: &mut [Finding], files: &[FilePlaces]) {
3482 let mut by_file: BTreeMap<String, Vec<&mut Finding>> = BTreeMap::new();
3483 for finding in findings {
3484 by_file
3485 .entry(finding.at().file.clone())
3486 .or_default()
3487 .push(finding);
3488 }
3489 for file in files {
3490 let Some(findings) = by_file.remove(file.display) else {
3491 continue;
3492 };
3493 let items = instrument::named_items(file.source);
3494 let index = instrument::ItemIndex::new(&items);
3495 let item_at = |line, column| {
3496 file.lines
3497 .offset_of(file.source, line, column)
3498 .map_or("", |offset| index.at(offset))
3499 };
3500 let mut positions: BTreeMap<(&str, &str), Vec<(usize, usize)>> = BTreeMap::new();
3501 for (line, column, code) in file.places {
3502 positions
3503 .entry((item_at(*line, *column), code))
3504 .or_default()
3505 .push((*line, *column));
3506 }
3507 for places in positions.values_mut() {
3508 places.sort_unstable();
3509 places.dedup();
3510 }
3511 for finding in findings {
3512 let kind = finding.kind();
3513 let at = finding.at_mut();
3514 let item = item_at(at.line, at.column);
3515 let nth = positions.get(&(item, &at.code)).map_or(0, |places| {
3516 places.partition_point(|&place| place < (at.line, at.column))
3517 });
3518 at.item = item.to_string();
3519 at.id = report::finding_id(kind, at, nth);
3520 }
3521 }
3522}
3523
3524fn mutation_of(site: &Site, mutant: &instrument::SourceMutant) -> Mutation {
3526 match &site.kind {
3527 SiteKind::Cmp { .. } => plan::CmpOp::ALL
3528 .into_iter()
3529 .find(|op| op.symbol() == mutant.into)
3530 .map_or(Mutation::Negate, Mutation::Op),
3531 SiteKind::Arith { op, .. } => {
3532 if mutant.into.trim_end_matches('=') == op.swapped().symbol() {
3533 Mutation::ArithSwap
3534 } else {
3535 Mutation::ArithSwap2
3536 }
3537 }
3538 SiteKind::Guard { .. } => Mutation::Const(mutant.into == "true"),
3539 SiteKind::Logic { .. } => Mutation::LogicSwap,
3540 SiteKind::Not { .. } => Mutation::DropNot,
3541 SiteKind::Range { .. } => Mutation::RangeEnd,
3542 SiteKind::SliceEnd { .. } => Mutation::OtherEnd,
3543 SiteKind::StrAffix { .. } => Mutation::StrContains,
3544 SiteKind::StrReplace { .. } => Mutation::StrReplaceMultiplicity,
3545 SiteKind::Clamp { .. } => {
3546 if mutant.into.contains("lower") {
3547 Mutation::ClampDropLower
3548 } else {
3549 Mutation::ClampDropUpper
3550 }
3551 }
3552 SiteKind::Rounding { op, .. } => {
3553 if mutant.into == op.alt1().name() {
3554 Mutation::RoundAlt1
3555 } else {
3556 Mutation::RoundAlt2
3557 }
3558 }
3559 SiteKind::Quantifier { .. } => Mutation::QuantifierSwap,
3560 _ => Mutation::Delete,
3563 }
3564}
3565
3566fn mutations_like(site: &Site, mutant: &instrument::SourceMutant, integers: bool) -> Vec<Mutation> {
3575 let mut all = vec![mutation_of(site, mutant)];
3576 if let (SiteKind::Cmp { op, .. }, Mutation::Op(into)) = (&site.kind, all[0]) {
3577 let an_order_is_needed = matches!(op, plan::CmpOp::Le | plan::CmpOp::Ge);
3578 if into == op.negated() && (integers || !an_order_is_needed) {
3579 all.push(Mutation::Negate);
3580 }
3581 match (op, into) {
3582 (plan::CmpOp::Lt, plan::CmpOp::Le) | (plan::CmpOp::Ge, plan::CmpOp::Gt) => {
3583 all.push(Mutation::Shift(1))
3584 }
3585 (plan::CmpOp::Gt, plan::CmpOp::Ge) | (plan::CmpOp::Le, plan::CmpOp::Lt) => {
3586 all.push(Mutation::Shift(-1))
3587 }
3588 _ => {}
3589 }
3590 }
3591 all
3592}
3593
3594fn describe_effects(
3597 changes: &BTreeMap<String, BTreeSet<Change>>,
3598 sites: &BTreeMap<u32, (&str, &Site)>,
3599) -> Vec<String> {
3600 let mut by_change: BTreeMap<&Change, Vec<&str>> = BTreeMap::new();
3601 for (test, found) in changes {
3602 for change in found {
3603 by_change.entry(change).or_default().push(test);
3604 }
3605 }
3606 if by_change.is_empty() {
3607 return vec![
3608 "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(),
3609 ];
3610 }
3611 let mut out = vec![];
3612 for (change, tests) in by_change.iter().take(3) {
3613 let Some((file, site)) = sites.get(&change.site()) else {
3614 continue;
3615 };
3616 let code = report::location(file, site).code;
3617 let at = format!("{file}:{}", site.line);
3618 let who = match tests[..] {
3619 ["?"] => "a test".to_string(),
3620 [one] => format!("`{one}`"),
3621 [first, ..] => format!("`{first}` (and {} more)", tests.len() - 1),
3622 [] => continue,
3623 };
3624 out.push(match change {
3625 Change::Returns { value, .. } => {
3626 format!("with the mutant, {who} gets `{value}` from `{code}` ({at})")
3627 }
3628 Change::NowRuns { .. } => format!("with the mutant, {who} now runs `{code}` ({at})"),
3629 Change::NoLongerRuns { .. } => {
3630 format!("with the mutant, {who} no longer runs `{code}` ({at})")
3631 }
3632 Change::NewOutcome { .. } => {
3633 format!("with the mutant, {who} takes `{code}` ({at}) a way it did not before")
3634 }
3635 });
3636 }
3637 if by_change.len() > 3 {
3638 out.push(format!("(and {} more such changes)", by_change.len() - 3));
3639 }
3640 out
3641}
3642
3643#[cfg(test)]
3644mod tests;