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