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
28pub use runner::summarize_baseline_log;
29
30#[derive(Debug)]
32pub enum BaselineError {
33 Timeout {
34 diagnostic: Box<report::BaselineTimeoutDiagnostic>,
35 wrapper_grace_outcomes: Option<report::WrapperGraceOutcomes>,
36 message: String,
37 },
38 Failed {
39 diagnostic: Box<report::BaselineFailureDiagnostic>,
40 wrapper_grace_outcomes: Option<report::WrapperGraceOutcomes>,
41 message: String,
42 },
43}
44
45impl BaselineError {
46 pub fn to_report(&self) -> report::BaselineErrorReport {
48 match self {
49 Self::Timeout {
50 diagnostic,
51 wrapper_grace_outcomes,
52 message,
53 } => report::BaselineErrorReport {
54 schema_version: report::SCHEMA_VERSION,
55 package: diagnostic.package.clone(),
56 evaluation: report::Evaluation::BaselineFailed,
57 error: message.clone(),
58 wrapper_grace_outcomes: *wrapper_grace_outcomes,
59 baseline_timeout: Some((**diagnostic).clone()),
60 baseline_failure: None,
61 },
62 Self::Failed {
63 diagnostic,
64 wrapper_grace_outcomes,
65 message,
66 } => report::BaselineErrorReport {
67 schema_version: report::SCHEMA_VERSION,
68 package: diagnostic.package.clone(),
69 evaluation: report::Evaluation::BaselineFailed,
70 error: message.clone(),
71 wrapper_grace_outcomes: *wrapper_grace_outcomes,
72 baseline_timeout: None,
73 baseline_failure: Some((**diagnostic).clone()),
74 },
75 }
76 }
77}
78
79impl std::fmt::Display for BaselineError {
80 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81 match self {
82 Self::Timeout { message, .. } | Self::Failed { message, .. } => f.write_str(message),
83 }
84 }
85}
86
87impl std::error::Error for BaselineError {}
88
89fn round_millis(d: Duration) -> f64 {
90 (d.as_secs_f64() * 1000.0).round() / 1000.0
91}
92
93fn format_baseline_timings_section(
94 completed: &[report::BaselineTimingEntry],
95 failed_runner: &str,
96 failed_elapsed: f64,
97 failed_label: &str,
98 total: usize,
99) -> String {
100 if completed.is_empty() && total <= 1 {
101 return String::new();
102 }
103 const MAX_DISPLAY: usize = 10;
104 let mut out = format!(
105 "\nbaseline timings ({}/{} completed):",
106 completed.len(),
107 total
108 );
109 for entry in completed.iter().take(MAX_DISPLAY) {
110 out.push_str(&format!(
111 "\n {}: {:.3}s",
112 entry.runner, entry.elapsed_seconds
113 ));
114 }
115 if completed.len() > MAX_DISPLAY {
116 out.push_str(&format!(
117 "\n ... and {} more completed",
118 completed.len() - MAX_DISPLAY
119 ));
120 }
121 let prefix = if failed_label == "timed out" { ">" } else { "" };
122 out.push_str(&format!(
123 "\n {failed_runner}: {prefix}{failed_elapsed:.3}s ({failed_label})"
124 ));
125 out
126}
127
128fn format_log_summary_section(summary: &[String]) -> String {
129 if summary.is_empty() {
130 return String::new();
131 }
132 let mut out = String::from("\nlog summary:");
133 for line in summary {
134 out.push_str("\n ");
135 out.push_str(line);
136 }
137 out
138}
139
140#[derive(Clone)]
141pub struct Options {
142 pub dir: PathBuf,
144 pub package: Option<String>,
145 pub list: bool,
147 pub test_workspace: bool,
149 pub verify: bool,
151 pub work_dir: Option<PathBuf>,
153 pub progress: bool,
155 pub since: Option<String>,
157 pub lines: Vec<String>,
159 pub exclude_files: Vec<String>,
161 pub baseline: Option<PathBuf>,
163 pub write_baseline: Option<PathBuf>,
165 pub also_test: Vec<String>,
167 pub dependents: bool,
169 pub effects: bool,
171 pub rebuild: bool,
173 pub error_values: Vec<String>,
175 pub source_only: bool,
176 pub literal_operators: bool,
177 pub shard: Option<report::Shard>,
178 pub nextest: Option<report::Nextest>,
179 pub test_selection: TestSelection,
180 pub opt_level: Option<u8>,
182 pub timeout_seconds: Option<u64>,
184 pub baseline_timeout_seconds: Option<u64>,
186 pub baseline_jobs: usize,
187 pub serial_timeout_rechecks: bool,
188 pub wrapper_grace: Duration,
189 pub audit: Option<usize>,
191 pub cargo: CargoConfig,
193 pub jobs: usize,
195 pub all_files: bool,
197 pub git_index: bool,
198 pub copy_fixtures: Vec<PathBuf>,
199 pub copy_fixture_excludes: Vec<PathBuf>,
200 pub output_fixtures: Vec<Fixture>,
201 pub stage_external: Vec<StageExternal>,
202 pub checkpoint: bool,
203 pub doc: bool,
205}
206
207#[derive(Clone, Default)]
208pub struct TestSelection {
209 pub isolate: bool,
210 pub lib: bool,
211 pub bins: bool,
212 pub integration_tests: Vec<String>,
213 pub targets: Vec<String>,
214 pub include: Vec<String>,
215 pub filter: Vec<String>,
216 pub exclude: Vec<String>,
217 pub include_ignored: bool,
218 pub wrapper: Option<PathBuf>,
219}
220
221impl TestSelection {
222 pub(crate) fn has_target_filters(&self) -> bool {
223 self.lib || self.bins || !self.integration_tests.is_empty() || !self.targets.is_empty()
224 }
225
226 fn enabled(&self) -> bool {
227 self.isolate
228 || self.has_target_filters()
229 || !self.include.is_empty()
230 || !self.filter.is_empty()
231 || !self.exclude.is_empty()
232 || self.include_ignored
233 || self.wrapper.is_some()
234 }
235
236 pub(crate) fn matches_test(&self, test: &str, was_ignored: bool) -> bool {
237 if was_ignored && !self.include_ignored {
238 return false;
239 }
240 if self.exclude.iter().any(|name| name == test) {
241 return false;
242 }
243 if !self.include.is_empty() || !self.filter.is_empty() {
244 let exact = self.include.iter().any(|name| name == test);
245 let partial = self.filter.iter().any(|pat| test.contains(pat));
246 if !exact && !partial {
247 return false;
248 }
249 }
250 true
251 }
252}
253
254pub use crate::report::CargoConfig;
255pub use workcopy::StageExternal;
256
257impl CargoConfig {
258 pub fn flags(&self) -> Vec<String> {
260 let mut flags = vec![];
261 if !self.features.is_empty() {
262 flags.extend(["--features".to_string(), self.features.join(",")]);
263 }
264 for (on, flag) in [
265 (self.all_features, "--all-features"),
266 (self.no_default_features, "--no-default-features"),
267 (self.locked, "--locked"),
268 ] {
269 if on {
270 flags.push(flag.to_string());
271 }
272 }
273 flags
274 }
275}
276
277const NEARBY_LINES: usize = 6;
280const WORK_MARKER: &str = ".tmt-work-dir";
282const STD_ALIAS: &str = "__tmt_std";
284const MAX_REPAIR_ROUNDS: usize = 40;
286const MAX_TEST_FILTERS: usize = 200;
288
289mod cargo;
290mod repair_cache;
291mod runner;
292mod scope_blame;
293mod session;
294mod witness_runner;
295mod workcopy;
296
297use cargo::*;
298use runner::*;
299use scope_blame::*;
300use session::*;
301use witness_runner::*;
302use workcopy::*;
303
304struct SourceFile {
305 display: String,
307 path: PathBuf,
309 owners: BTreeSet<PathBuf>,
310 original: String,
311 lines: scope::LineIndex,
312 sites: Vec<Site>,
313 rebuild_sites: Vec<Site>,
315 places: Vec<(usize, usize, String)>,
318 rendered: Option<Rendered>,
319}
320
321fn write_rendered(
322 file: &mut SourceFile,
323 state: &WorkCopy,
324 suffix: &str,
325 disabled: &HashSet<u32>,
326 newly_disabled: &HashSet<u32>,
327) -> Result<()> {
328 if file.rendered.is_none()
329 || file
330 .sites
331 .iter()
332 .any(|site| newly_disabled.contains(&site.id))
333 {
334 file.rendered = Some(instrument::render(&file.original, &file.sites, &|id| {
335 !disabled.contains(&id)
336 }));
337 }
338 let rendered = file.rendered.as_ref().expect("rendered before writing");
339 if suffix.is_empty() {
340 state.write(&file.path, &rendered.text)
341 } else {
342 state.write(&file.path, &format!("{}{suffix}", rendered.text))
343 }
344}
345
346#[derive(Clone, Copy)]
347struct WorkspaceShard {
348 offset: usize,
349 total: usize,
350 member_total: usize,
351}
352
353struct CatalogueSnapshot {
354 path: PathBuf,
355 ready: std::cell::Cell<bool>,
356 _lock: WorkLock,
357}
358
359struct WorkspaceBatch<'a> {
360 metadata: &'a Metadata,
361 work: &'a Path,
362 catalogue: Option<CatalogueSnapshot>,
363}
364
365pub fn select_single_package_name(dir: &Path, cargo: &CargoConfig) -> Option<String> {
368 let canon = dir.canonicalize().ok()?;
369 let metadata = cargo_metadata(&canon, cargo).ok()?;
370 metadata
371 .packages
372 .iter()
373 .find(|p| p.manifest_path.parent() == Some(canon.as_path()))
374 .or(match &metadata.packages[..] {
375 [only] => Some(only),
376 _ => None,
377 })
378 .map(|p| p.name.clone())
379}
380
381pub fn run_packages(options: &Options, names: &[String]) -> Result<Vec<(String, Result<Report>)>> {
383 run_packages_with(options, names, |_, base| Ok(base.clone()))
384}
385
386pub fn run_packages_with(
388 options: &Options,
389 names: &[String],
390 options_for_package: impl FnMut(&str, &Options) -> Result<Options>,
391) -> Result<Vec<(String, Result<Report>)>> {
392 let mut reports = vec![];
393 run_packages_each_with(options, names, options_for_package, |name, result| {
394 reports.push((name, result));
395 Ok(())
396 })?;
397 Ok(reports)
398}
399
400pub fn run_packages_each(
402 options: &Options,
403 names: &[String],
404 completed: impl FnMut(String, Result<Report>) -> Result<()>,
405) -> Result<()> {
406 run_packages_each_with(options, names, |_, base| Ok(base.clone()), completed)
407}
408
409pub fn run_packages_each_with(
412 options: &Options,
413 names: &[String],
414 mut options_for_package: impl FnMut(&str, &Options) -> Result<Options>,
415 mut completed: impl FnMut(String, Result<Report>) -> Result<()>,
416) -> Result<()> {
417 let dir = options
418 .dir
419 .canonicalize()
420 .with_context(|| format!("no such directory: {}", options.dir.display()))?;
421 if dir.is_file() {
422 let given = crate::report::sanitize_inline(&options.dir.display().to_string());
423 bail!(
424 "`{given}` is a file, not a Cargo package directory; pass the workspace/package directory and `--lines <path-relative-to-package-or-workspace>` to analyse a single file"
425 );
426 }
427 let metadata = cargo_metadata(&dir, &options.cargo)?;
428 let all: BTreeSet<_> = metadata.packages.iter().map(|p| p.name.clone()).collect();
429 let selected = if names.is_empty() {
430 all.clone()
431 } else {
432 names.iter().cloned().collect()
433 };
434 if let Some(unknown) = selected.difference(&all).next() {
435 bail!("no package `{unknown}` in the workspace");
436 }
437 if !options.lines.is_empty() {
438 let selected_pkgs: Vec<&Package> = metadata
439 .packages
440 .iter()
441 .filter(|p| selected.contains(&p.name))
442 .collect();
443 validate_workspace_lines(&options.lines, &metadata.workspace_root, &selected_pkgs)?;
444 }
445 let base = options
446 .work_dir
447 .clone()
448 .unwrap_or_else(|| metadata.target_directory.join("tmt-workspace"));
449 fs::create_dir_all(&base).with_context(|| format!("creating {}", base.display()))?;
450 let base = base.canonicalize()?;
451 let workspace_canon = metadata.workspace_root.canonicalize()?;
452 if workspace_canon.starts_with(&base) {
453 bail!(
454 "the work directory {} contains the workspace",
455 base.display()
456 );
457 }
458 let mut member_options = Vec::with_capacity(selected.len());
459 let mut used_work_dirs: Vec<(String, PathBuf)> = Vec::new();
460 for name in selected {
461 let mut member = options_for_package(&name, options)?;
462 member.package = Some(name.clone());
463 let custom_work = member
464 .work_dir
465 .as_ref()
466 .is_some_and(|w| options.work_dir.as_ref() != Some(w));
467 let member_work = if custom_work {
468 let custom = member.work_dir.clone().expect("custom work_dir");
469 fs::create_dir_all(&custom)
470 .with_context(|| format!("creating {}", custom.display()))?;
471 let canon = custom.canonicalize()?;
472 if workspace_canon.starts_with(&canon) {
473 bail!(
474 "the work directory {} for `{name}` contains the workspace",
475 canon.display()
476 );
477 }
478 canon
479 } else {
480 base.join(&name)
481 };
482 for (other_name, other_dir) in &used_work_dirs {
483 if member_work == *other_dir
484 || member_work.starts_with(other_dir)
485 || other_dir.starts_with(&member_work)
486 {
487 bail!(
488 "overlapping work directories for `{name}` ({}) and `{other_name}` ({})",
489 member_work.display(),
490 other_dir.display()
491 );
492 }
493 }
494 used_work_dirs.push((name.clone(), member_work.clone()));
495 member.work_dir = Some(member_work);
496 member_options.push((name, member));
497 }
498 let uniform_copy_settings = member_options
499 .first()
500 .map(|(_, first)| {
501 member_options.iter().all(|(_, m)| {
502 m.all_files == first.all_files
503 && m.git_index == first.git_index
504 && m.copy_fixtures == first.copy_fixtures
505 && m.copy_fixture_excludes == first.copy_fixture_excludes
506 && m.stage_external == first.stage_external
507 })
508 })
509 .unwrap_or(true);
510 let catalogue_dir = base.join(".catalogue");
511 let catalogue = if uniform_copy_settings && (options.list || options.shard.is_some()) {
512 for (name, member_dir) in &used_work_dirs {
513 if *member_dir == catalogue_dir
514 || member_dir.starts_with(&catalogue_dir)
515 || catalogue_dir.starts_with(member_dir)
516 {
517 bail!(
518 "work directory {} for `{name}` overlaps shared workspace catalogue {}",
519 member_dir.display(),
520 catalogue_dir.display()
521 );
522 }
523 }
524 let path = work_directory(&base, ".catalogue")?;
525 Some(CatalogueSnapshot {
526 _lock: WorkLock::take(&path)?,
527 path,
528 ready: std::cell::Cell::new(false),
529 })
530 } else {
531 None
532 };
533 let batch = WorkspaceBatch {
534 metadata: &metadata,
535 work: &base,
536 catalogue,
537 };
538 let Some(shard) = options.shard else {
539 for (name, member) in member_options {
540 if crate::interrupt::is_interrupted() {
541 return Ok(());
542 }
543 let result = run_package(&member, Some(&batch), None);
544 if let Err(err) = &result
545 && crate::interrupt::is_interrupted_err(err)
546 {
547 return Err(crate::interrupt::Interrupted.into());
548 }
549 let interrupted = result.as_ref().is_ok_and(|report| report.interrupted);
550 completed(name, result)?;
551 if interrupted || crate::interrupt::is_interrupted() {
552 return Ok(());
553 }
554 }
555 return Ok(());
556 };
557 if shard.index >= shard.count || member_options.iter().any(|(_, m)| !m.source_only) {
558 bail!("shards require --source-only and a valid shard index");
559 }
560 let mut catalogues = Vec::with_capacity(member_options.len());
563 for (name, member) in member_options {
564 if crate::interrupt::is_interrupted() {
565 return Err(crate::interrupt::Interrupted.into());
566 }
567 let mut preview = member.clone();
568 preview.list = true;
569 preview.shard = None;
570 preview.progress = false;
571 let catalogue = run_package(&preview, Some(&batch), None).map(|mut report| {
572 let count = report.mutants.as_ref().map_or(0, Vec::len);
573 if !member.list {
574 report.mutants = None;
575 }
576 (count, report)
577 });
578 if catalogue
579 .as_ref()
580 .is_ok_and(|(_, report)| report.interrupted)
581 || crate::interrupt::is_interrupted()
582 {
583 return Err(crate::interrupt::Interrupted.into());
584 }
585 catalogues.push((name, member, catalogue));
586 }
587 let total = catalogues
588 .iter()
589 .filter_map(|(_, _, catalogue)| catalogue.as_ref().ok())
590 .map(|(count, _)| count)
591 .sum();
592 let mut offset = 0;
593 for (name, member, catalogue) in catalogues {
594 if crate::interrupt::is_interrupted() {
595 return Ok(());
596 }
597 let result = catalogue.and_then(|(member_total, mut report)| {
598 let range = WorkspaceShard {
599 offset,
600 total,
601 member_total,
602 };
603 offset += member_total;
604 if member.list {
605 report.analysis.shard = Some(shard);
606 let mut index = range.offset;
607 if let Some(mutants) = report.mutants.as_mut() {
608 mutants.retain(|_| {
609 let keep = shard.contains(index, total);
610 index += 1;
611 keep
612 });
613 }
614 Ok(report)
615 } else {
616 run_package(&member, Some(&batch), Some(range))
617 }
618 });
619 let interrupted = result.as_ref().is_ok_and(|report| report.interrupted);
620 completed(name, result)?;
621 if interrupted || crate::interrupt::is_interrupted() {
622 return Ok(());
623 }
624 }
625 Ok(())
626}
627
628struct LeftoverNote(bool);
630
631impl Drop for LeftoverNote {
632 fn drop(&mut self) {
633 use std::sync::atomic::Ordering;
634 let stopped = leftovers::STOPPED.swap(0, Ordering::Relaxed);
635 let not_stopped = leftovers::NOT_STOPPED.swap(0, Ordering::Relaxed);
636 if let Some(text) = leftover_note(stopped, not_stopped)
637 && self.0
638 {
639 eprintln!("tmt: {text}");
640 }
641 }
642}
643
644fn leftover_note(stopped: usize, not_stopped: usize) -> Option<String> {
645 let stopped = (stopped > 0).then(|| {
646 format!("stopped {stopped} processes that the tests had left running after their run")
647 });
648 let not_stopped = (not_stopped > 0).then(|| {
649 format!(
650 "after {not_stopped} runs something the tests started may still be running \
651 (it could not be found or stopped)"
652 )
653 });
654 match (stopped, not_stopped) {
655 (None, None) => None,
656 (Some(one), None) | (None, Some(one)) => Some(one),
657 (Some(stopped), Some(not_stopped)) => Some(format!("{stopped}; {not_stopped}")),
658 }
659}
660
661pub fn run(options: &Options) -> Result<Report> {
662 run_package(options, None, None)
663}
664
665fn interrupted_stub_report(options: &Options, package: Option<String>) -> Report {
666 let mut report = Report {
667 package: package
668 .or_else(|| options.package.clone())
669 .unwrap_or_default(),
670 interrupted: true,
671 wrapper_grace_outcomes: options
672 .test_selection
673 .wrapper
674 .as_ref()
675 .map(|_| report::WrapperGraceOutcomes::default()),
676 ..Report::default()
677 };
678 if crate::interrupt::is_interrupted() {
679 report.interrupted = true;
680 }
681 report.record_evaluation();
682 report
683}
684
685fn run_package(
686 options: &Options,
687 batch: Option<&WorkspaceBatch<'_>>,
688 workspace_shard: Option<WorkspaceShard>,
689) -> Result<Report> {
690 let mut resolved_package: Option<String> = options.package.clone();
691 match run_package_inner(options, batch, workspace_shard, &mut resolved_package) {
692 Ok(report) => Ok(report),
693 Err(err)
694 if crate::interrupt::is_interrupted() || crate::interrupt::is_interrupted_err(&err) =>
695 {
696 Ok(interrupted_stub_report(options, resolved_package))
697 }
698 Err(err) => Err(err),
699 }
700}
701
702fn run_package_inner(
703 options: &Options,
704 batch: Option<&WorkspaceBatch<'_>>,
705 workspace_shard: Option<WorkspaceShard>,
706 resolved_package: &mut Option<String>,
707) -> Result<Report> {
708 let _leftovers = LeftoverNote(options.progress);
709 let error_values = validate_package_options(options)?;
710 let selection = &options.test_selection;
711 let effective_jobs = if options.source_only { 1 } else { options.jobs };
712 let note = |text: &str| {
713 if options.progress {
714 eprintln!("tmt: {}", report::sanitize_inline(text));
715 }
716 };
717 let dir = options
718 .dir
719 .canonicalize()
720 .with_context(|| format!("no such directory: {}", options.dir.display()))?;
721 if dir.is_file() {
722 let given = crate::report::sanitize_inline(&options.dir.display().to_string());
723 bail!(
724 "`{given}` is a file, not a Cargo package directory; pass the package directory and `--lines <path-relative-to-package-or-workspace>` to analyse a single file"
725 );
726 }
727
728 let local_metadata;
729 let metadata = if let Some(batch) = batch {
730 batch.metadata
731 } else {
732 local_metadata = cargo_metadata(&dir, &options.cargo)?;
733 &local_metadata
734 };
735 let catalogue = batch
736 .and_then(|batch| batch.catalogue.as_ref())
737 .filter(|_| options.list);
738 let enclosing_package = metadata
739 .packages
740 .iter()
741 .filter(|p| {
742 p.manifest_path
743 .parent()
744 .is_some_and(|root| dir != root && dir.starts_with(root))
745 })
746 .max_by_key(|p| {
747 p.manifest_path
748 .parent()
749 .map_or(0, |root| root.as_os_str().len())
750 });
751 let package = match &options.package {
752 Some(name) => metadata.packages.iter().find(|p| &p.name == name),
753 None => metadata
754 .packages
755 .iter()
756 .find(|p| p.manifest_path.parent() == Some(dir.as_path()))
757 .or(match &metadata.packages[..] {
758 [only] => Some(only),
759 _ => None,
760 }),
761 }
762 .ok_or_else(|| {
763 if let Some(name) = &options.package {
764 anyhow!(
765 "no package `{}` in workspace",
766 crate::report::sanitize_inline(name)
767 )
768 } else if let Some(owner) = enclosing_package {
769 anyhow!(
770 "`{}` is a subdirectory of package `{}` (no Cargo.toml); pass `--package {}` from the workspace/package root (and `--lines <path-relative-to-package-or-workspace>` to narrow files)",
771 crate::report::sanitize_inline(&options.dir.display().to_string()),
772 crate::report::sanitize_inline(&owner.name),
773 crate::report::sanitize_inline(&owner.name),
774 )
775 } else {
776 anyhow!("cannot tell which package to analyse; pass --package <name>")
777 }
778 })?;
779 *resolved_package = Some(package.name.clone());
780 if options.package.is_none()
781 && !dir.join("Cargo.toml").is_file()
782 && package.manifest_path.parent() != Some(dir.as_path())
783 && options.progress
784 {
785 eprintln!(
786 "tmt: note: `{}` has no Cargo.toml; analysing package `{}` (use `--lines <file>` to scope to specific files)",
787 crate::report::sanitize_inline(&options.dir.display().to_string()),
788 crate::report::sanitize_inline(&package.name),
789 );
790 }
791 let mut test_packages: Vec<&Package> = vec![package];
794 for name in &options.also_test {
795 let other = metadata
796 .packages
797 .iter()
798 .find(|p| &p.name == name)
799 .ok_or_else(|| anyhow!("--also-test: no package `{name}` in the workspace"))?;
800 if !test_packages.iter().any(|p| p.name == other.name) {
801 test_packages.push(other);
802 }
803 }
804 if options.test_workspace {
805 test_packages.extend(
806 metadata
807 .packages
808 .iter()
809 .filter(|other| {
810 !test_packages
811 .iter()
812 .any(|selected| selected.name == other.name)
813 })
814 .collect::<Vec<_>>(),
815 );
816 }
817 if options.dependents {
818 for name in dependents_of(&package.name, &metadata.packages) {
819 if let Some(other) = metadata.packages.iter().find(|p| p.name == name)
820 && !test_packages.iter().any(|p| p.name == other.name)
821 {
822 test_packages.push(other);
823 }
824 }
825 }
826 if !options.list {
827 validate_target_selection(&test_packages, selection)?;
828 }
829 let is_kind = |t: &Target, kinds: &[&str]| t.kind.iter().any(|k| kinds.contains(&k.as_str()));
830 let root_target = package
831 .targets
832 .iter()
833 .find(|t| {
834 is_kind(
835 t,
836 &["lib", "rlib", "cdylib", "staticlib", "dylib", "proc-macro"],
837 )
838 })
839 .or_else(|| package.targets.iter().find(|t| is_kind(t, &["bin"])))
840 .ok_or_else(|| anyhow!("package `{}` has no lib or bin target", package.name))?;
841
842 let PreparedWorkCopy {
844 workspace,
845 work,
846 work_lock,
847 copy,
848 state,
849 external_deps,
850 } = prepare_work_copy(options, metadata, batch, catalogue, ¬e)?;
851
852 let in_copy = |path: &Path| -> Result<PathBuf> {
853 let canonical = path.canonicalize()?;
854 let relative = canonical
855 .strip_prefix(&workspace)
856 .with_context(|| format!("{} is outside the workspace", path.display()))?;
857 Ok(copy.join(relative))
858 };
859 let package_dir = in_copy(
860 package
861 .manifest_path
862 .parent()
863 .expect("manifest has a parent"),
864 )?;
865 let root_file = in_copy(&root_target.src_path)?;
866 let source_dir = root_file
867 .parent()
868 .expect("source file has a parent")
869 .to_path_buf();
870
871 let mut roots = BTreeMap::new();
874 for owner in &metadata.packages {
875 for target in &owner.targets {
876 let production = owner.name == package.name && target.is_production();
877 if let Ok(path) = in_copy(&target.src_path)
878 && path.is_file()
879 {
880 let selected = roots.entry(path).or_insert(false);
881 *selected |= production;
882 }
883 }
884 }
885 let paths = source_graph(roots, ©, |path| state.original(path, &workspace))?;
886 let package_orig_dir = package
887 .manifest_path
888 .parent()
889 .expect("manifest has a parent");
890 let scope = requested_scope(
891 options,
892 &workspace,
893 package_orig_dir,
894 &package.name,
895 batch.is_some(),
896 )?;
897 let mut skipped = vec![];
898 let mut files = vec![];
899 let mut excluded_any = false;
900 let mut next_id = 0u32;
901 let want_witnesses = (options.list || options.rebuild || options.source_only)
902 && root_target.test_build_arg() == Some(("--lib", None));
903 let count_rebuild_witnesses =
904 !want_witnesses && root_target.test_build_arg() == Some(("--lib", None));
905 let mut witness_candidates = vec![];
906 let mut unbuilt_witness_candidates = vec![];
907 for (path, owners) in paths {
908 let Some(original) = state.original(&path, &workspace)? else {
909 continue; };
911 let display = relative_source(&path, &package_dir).display().to_string();
912 if scope::matches_any_glob(&options.exclude_files, &display) {
913 excluded_any = true;
914 continue;
915 }
916 let selected_file = scope.as_ref().is_none_or(|scope| {
917 let relative = path.strip_prefix(©).unwrap_or(&path).to_string_lossy();
918 scope.touches(&relative, 1, usize::MAX)
919 });
920 if !selected_file && path != root_file {
921 continue;
922 }
923 match instrument::parse_source(&original) {
924 Ok(parsed) => {
925 let mut found =
926 instrument::discover_parsed(&original, &parsed, next_id, &error_values);
927 if (want_witnesses || count_rebuild_witnesses)
929 && selected_file
930 && owners.consumers.len() == 1
931 && owners.consumers.contains(&root_file)
932 {
933 let discovered = witness::discover_parsed(
934 &original,
935 &parsed,
936 want_witnesses && !options.list,
937 )
938 .into_iter()
939 .map(|mut candidate| {
940 candidate.file = path.clone();
941 candidate
942 });
943 if want_witnesses {
944 witness_candidates.extend(discovered);
945 } else {
946 unbuilt_witness_candidates.extend(discovered);
947 }
948 if want_witnesses && !options.list && !options.literal_operators {
951 witness_candidates.extend(
952 stronger_assertions(
955 &original,
956 &parsed,
957 found.sites.iter().chain(&found.rebuild_sites),
958 )
959 .into_iter()
960 .map(|mut candidate| {
961 candidate.file = path.clone();
962 candidate
963 }),
964 );
965 }
966 }
967 next_id += found.sites.len() as u32;
968 if owners.consumers.len() != 1 || !owners.consumers.contains(&root_file) {
969 found.rebuild_sites.append(&mut found.sites);
970 }
971 let places = if options.list {
972 vec![]
973 } else {
974 found
975 .sites
976 .iter()
977 .chain(&found.rebuild_sites)
978 .map(|site| (site.line, site.column, report::one_line(&site.text)))
979 .collect()
980 };
981 files.push(SourceFile {
982 display,
983 path,
984 owners: owners.production,
985 lines: scope::LineIndex::new(&original),
986 original,
987 places,
988 sites: found.sites,
989 rebuild_sites: found.rebuild_sites,
990 rendered: None,
991 });
992 }
993 Err(err) => {
994 if selected_file {
995 let diagnostic = format!("{err:#}");
996 note(&format!("skipping {display}: {diagnostic}"));
997 let end_line = scope::line_of(&original, original.len());
998 let end_column = original.rsplit('\n').next().unwrap_or("").chars().count() + 1;
999 skipped.push(report::SkippedSite::new(
1000 report::Location {
1001 file: display,
1002 line: 1,
1003 column: 1,
1004 ..Default::default()
1005 },
1006 (end_line, end_column),
1007 report::SkipReason::UnparseableSource,
1008 Some(diagnostic),
1009 ));
1010 }
1011 }
1012 }
1013 }
1014
1015 let since_hunks = match options.since.as_deref() {
1018 Some(revision) if !options.list && options.shard.is_none() => {
1019 scope::hunks(&since_diff(&workspace, revision)?)
1020 }
1021 _ => vec![],
1022 };
1023 let mut tests_changed: Vec<(PathBuf, Vec<scope::Hunk>)> = vec![];
1024 let mut undo_paths: HashSet<PathBuf> = HashSet::new();
1026 let mut not_built_reverts: usize = 0;
1027 let mut beyond_places: HashSet<(PathBuf, usize, usize)> = HashSet::new();
1028 if let Some(scope) = &scope {
1030 for file in &mut files {
1031 let relative = file
1032 .path
1033 .strip_prefix(©)
1034 .unwrap_or(&file.path)
1035 .to_string_lossy()
1036 .into_owned();
1037 let in_scope = |site: &Site| {
1038 scope.touches(&relative, file.lines.line_of(site.start), file.lines.line_of(site.end))
1039 || scope.touches(&relative, site.line, site.line)
1041 };
1042 let of_file: Vec<scope::Hunk> = since_hunks
1043 .iter()
1044 .filter(|hunk| hunk.file == relative)
1045 .cloned()
1046 .collect();
1047 let changes_count = reverts::changes(&file.original, &of_file).len();
1048 if options.rebuild || options.source_only {
1049 if changes_count > 0 || reverts::mixed(&file.original, &of_file) > 0 {
1050 undo_paths.insert(file.path.clone());
1051 }
1052 } else {
1053 not_built_reverts += changes_count;
1054 }
1055 let of_tests = reverts::test_hunks(&file.original, &of_file);
1056 if of_tests.is_empty() {
1057 file.sites.retain(in_scope);
1058 } else {
1059 beyond_places.extend(
1060 file.sites
1061 .iter()
1062 .filter(|site| !in_scope(site))
1063 .map(|site| (file.path.clone(), site.start, site.end)),
1064 );
1065 tests_changed.push((file.path.clone(), of_tests));
1066 }
1067 file.rebuild_sites.retain(in_scope);
1068 }
1069 files.retain(|f| {
1070 !f.sites.is_empty()
1071 || !f.rebuild_sites.is_empty()
1072 || f.path == root_file
1073 || witness_candidates.iter().any(|c| c.file == f.path)
1074 || unbuilt_witness_candidates.iter().any(|c| c.file == f.path)
1075 || undo_paths.contains(&f.path)
1076 });
1077 }
1078 if !options.list {
1079 for candidate in witness_candidates.iter().filter(|c| !c.existing) {
1080 if let Some(file) = files.iter_mut().find(|file| file.path == candidate.file) {
1081 let at = witness_location(file, candidate);
1082 file.places.push((at.line, at.column, at.code));
1083 }
1084 }
1085 }
1086 let witness_in_scope = |candidate: &witness::Candidate| {
1087 let Some(file) = files.iter().find(|file| file.path == candidate.file) else {
1088 return false;
1089 };
1090 let relative = file
1091 .path
1092 .strip_prefix(©)
1093 .unwrap_or(&file.path)
1094 .to_string_lossy();
1095 scope.as_ref().is_none_or(|scope| {
1096 let site_in_scope = if candidate.edits.len() == 1 {
1097 scope.touches(&relative, *candidate.scope.start(), *candidate.scope.end())
1098 } else {
1099 candidate.edits.iter().any(|edit| {
1100 scope.touches(
1101 &relative,
1102 file.lines.line_of(edit.span.start),
1103 file.lines.line_of(edit.span.end),
1104 )
1105 })
1106 };
1107 site_in_scope
1108 || candidate
1109 .signature_lines
1110 .iter()
1111 .any(|&line| scope.touches(&relative, line, line))
1112 })
1113 };
1114 witness_candidates.retain(&witness_in_scope);
1115 unbuilt_witness_candidates.retain(&witness_in_scope);
1116 let not_built_witnesses = unbuilt_witness_candidates
1117 .iter()
1118 .filter(|candidate| !candidate.existing)
1119 .count();
1120
1121 let unassessed_test_changes: Vec<String> = if let Some(revision) = options.since.as_deref()
1122 && !options.list
1123 {
1124 let integration_prefixes: Vec<String> = test_packages
1125 .iter()
1126 .flat_map(|pkg| {
1127 let pkg_dir = pkg.manifest_path.parent().unwrap_or(&workspace);
1128 let pkg_rel = pkg_dir.strip_prefix(&workspace).ok();
1129 let pkg_tests_dir = pkg_rel.map(|rel| {
1130 let s = rel.join("tests").to_string_lossy().replace('\\', "/");
1131 format!("{s}/")
1132 });
1133 let workspace_ref = &workspace;
1134 let explicit_targets = pkg.targets.iter().flat_map(move |t| {
1135 if !t.kind.iter().any(|k| k == "test") {
1136 return vec![];
1137 }
1138 let Ok(rel) = t.src_path.strip_prefix(workspace_ref) else {
1139 return vec![];
1140 };
1141 let mut out = vec![rel.to_string_lossy().replace('\\', "/")];
1142 if let (Some(parent), Some(pkg_r)) = (rel.parent(), pkg_rel) {
1146 let is_pkg_root = parent == pkg_r;
1147 let is_src = parent == pkg_r.join("src");
1148 if !is_pkg_root && !is_src && !parent.as_os_str().is_empty() {
1149 out.push(format!("{}/", parent.to_string_lossy().replace('\\', "/")));
1150 }
1151 }
1152 out
1153 });
1154 pkg_tests_dir.into_iter().chain(explicit_targets)
1155 })
1156 .collect();
1157 let is_integration_test = |ws_rel: &str| {
1158 ws_rel.ends_with(".rs")
1159 && integration_prefixes.iter().any(|prefix| {
1160 if prefix.ends_with('/') {
1161 ws_rel.starts_with(prefix)
1162 } else {
1163 ws_rel == prefix
1164 }
1165 })
1166 };
1167 since_changed_files(&workspace, revision)?
1168 .into_iter()
1169 .filter(|f| is_integration_test(f))
1170 .collect()
1171 } else {
1172 vec![]
1173 };
1174 let total_sites: usize = files
1175 .iter()
1176 .map(|f| f.sites.len() + f.rebuild_sites.len())
1177 .sum::<usize>()
1178 + witness_candidates
1179 .iter()
1180 .filter(|candidate| !candidate.existing)
1181 .count();
1182 let files_with_sites = files
1183 .iter()
1184 .filter(|f| {
1185 !f.sites.is_empty()
1186 || !f.rebuild_sites.is_empty()
1187 || witness_candidates
1188 .iter()
1189 .any(|c| !c.existing && c.file == f.path)
1190 })
1191 .count();
1192 note(&format!(
1193 "{total_sites} sites in {files_with_sites} {}",
1194 if files_with_sites == 1 {
1195 "file"
1196 } else {
1197 "files"
1198 }
1199 ));
1200 if options.source_only {
1201 for file in &mut files {
1202 file.rebuild_sites.append(&mut file.sites);
1203 }
1204 }
1205
1206 let source_mutants = |file: &SourceFile, site: &Site, include_boundary: bool| {
1207 let mut mutants = instrument::source_mutants(site);
1208 if include_boundary {
1209 mutants.extend(instrument::source_boundary_mutant(site));
1210 }
1211 if options.literal_operators {
1212 instrument::literal_operator_mutants(&file.original, site, &mut mutants);
1213 }
1214 instrument::keep_line_ends(&file.original, &mut mutants);
1215 mutants
1216 };
1217 let counts = options.shard.map(|_| {
1218 let regular: usize = files
1219 .iter()
1220 .map(|file| {
1221 file.rebuild_sites
1222 .iter()
1223 .map(|site| source_mutants(file, site, true).len())
1224 .sum::<usize>()
1225 })
1226 .sum();
1227 let total = regular
1228 + witness_candidates
1229 .iter()
1230 .filter(|candidate| !candidate.existing)
1231 .count();
1232 (regular, total)
1233 });
1234 if let (Some(range), Some((_, local_total))) = (workspace_shard, counts)
1235 && range.member_total != local_total
1236 {
1237 bail!("package catalogue changed while preparing its workspace shard");
1238 }
1239 let in_shard = |index| match (options.shard, counts, workspace_shard) {
1240 (Some(shard), _, Some(range)) => shard.contains(range.offset + index, range.total),
1241 (Some(shard), Some((_, total)), _) => shard.contains(index, total),
1242 _ => true,
1243 };
1244 if let Some((mut index, _)) = counts {
1245 witness_candidates.retain(|candidate| {
1246 if candidate.existing {
1247 return true;
1248 }
1249 let selected = in_shard(index);
1250 index += 1;
1251 selected
1252 });
1253 }
1254 let empty_shard = counts.is_some_and(|(_, total)| !(0..total).any(in_shard));
1255
1256 let package_path = package.manifest_path.parent().unwrap_or(Path::new("."));
1257 let mut report_path = repository_prefix(package_path);
1258 if report_path.is_empty()
1259 && batch.is_some()
1260 && let Ok(relative) = package_path.strip_prefix(&workspace)
1261 {
1262 report_path = workspace_report_prefix(relative);
1263 }
1264 let mut report = Report {
1265 package: package.name.clone(),
1266 sites: if empty_shard { 0 } else { total_sites },
1267 analysis: report::Analysis {
1268 package_path: report_path,
1269 since: options.since.clone(),
1270 lines: options.lines.clone(),
1271 exclude_files: options.exclude_files.clone(),
1272 tests_of: test_packages.iter().map(|p| p.name.clone()).collect(),
1273 cargo: options.cargo.clone(),
1274 opt_level: options.opt_level,
1275 timeout_seconds: options.timeout_seconds,
1276 baseline_timeout_seconds: options.baseline_timeout_seconds,
1277 baseline_jobs: (options.baseline_jobs > 1).then_some(options.baseline_jobs),
1278 timeout_recheck: if options.serial_timeout_rechecks {
1279 "serial"
1280 } else {
1281 "none"
1282 },
1283 wrapper_grace_seconds: selection
1284 .wrapper
1285 .as_ref()
1286 .map(|_| options.wrapper_grace.as_secs()),
1287 rebuild: options.rebuild || options.source_only,
1288 verified: options.verify && !options.source_only,
1289 doc_tests: options.doc,
1290 source_only: options.source_only,
1291 literal_operators: options.literal_operators,
1292 shard: options.shard,
1293 nextest: options.nextest.clone(),
1294 error_values: error_values
1295 .iter()
1296 .map(|value| (*value).to_owned())
1297 .collect(),
1298 test_selection: None,
1299 git_index: options.git_index,
1300 copy_fixtures: options.copy_fixtures.clone(),
1301 copy_fixture_excludes: options.copy_fixture_excludes.clone(),
1302 output_fixtures: options.output_fixtures.clone(),
1303 stage_external: options.stage_external.clone(),
1304 checkpoint: (options.checkpoint && !options.list)
1305 .then(|| work.join("checkpoint.jsonl")),
1306 },
1307 skipped,
1308 wrapper_grace_outcomes: if options.list {
1309 None
1310 } else {
1311 selection
1312 .wrapper
1313 .as_ref()
1314 .map(|_| report::WrapperGraceOutcomes::default())
1315 },
1316 baseline: if options.list {
1317 None
1318 } else {
1319 options.baseline.clone()
1320 },
1321 unassessed_test_changes,
1322 ..Report::default()
1323 };
1324 if options.list {
1325 if catalogue.is_none() {
1326 state.settle(&workspace)?;
1327 }
1328 let mut candidates = vec![];
1329 let mut index = 0;
1330 for file in &files {
1331 let sites = file
1332 .sites
1333 .iter()
1334 .map(|site| (site, false))
1335 .chain(file.rebuild_sites.iter().map(|site| (site, true)));
1336 for (site, requires_rebuild) in sites {
1337 for mutant in source_mutants(file, site, true) {
1338 if in_shard(index) {
1339 candidates.push(report::Candidate {
1340 what: mutant.what,
1341 into: mutant.into,
1342 requires_rebuild,
1343 edits: vec![candidate_edit(
1344 file,
1345 mutant.start,
1346 mutant.end,
1347 mutant.replacement,
1348 )],
1349 });
1350 }
1351 index += 1;
1352 }
1353 }
1354 }
1355 candidates.extend(
1356 witness_candidates
1357 .iter()
1358 .filter(|candidate| !candidate.existing)
1359 .filter_map(|candidate| {
1360 let file = files.iter().find(|file| file.path == candidate.file)?;
1361 Some(report::Candidate {
1362 what: "witness".into(),
1363 into: candidate.description.clone(),
1364 requires_rebuild: true,
1365 edits: candidate
1366 .edits
1367 .iter()
1368 .map(|edit| {
1369 candidate_edit(
1370 file,
1371 edit.span.start,
1372 edit.span.end,
1373 edit.replacement.clone(),
1374 )
1375 })
1376 .collect(),
1377 })
1378 }),
1379 );
1380 report.mutants = Some(candidates);
1381 return Ok(report);
1382 }
1383 let ws_package_prefix = package_dir
1384 .strip_prefix(©)
1385 .unwrap_or(Path::new(""))
1386 .to_string_lossy()
1387 .replace('\\', "/");
1388 let all_files_excluded = excluded_any && files.is_empty();
1389 let is_partial_scope =
1390 scope.is_some() || !options.exclude_files.is_empty() || options.shard.is_some();
1391 if empty_shard
1392 || ((scope.is_some() || all_files_excluded) && total_sites == 0 && undo_paths.is_empty())
1393 {
1394 state.settle(&workspace)?;
1396 if let Some(path) = &options.baseline {
1397 let loaded = crate::baseline::load(path)?;
1398 loaded.validate_for_package(&package.name, path)?;
1399 }
1400 if crate::interrupt::is_interrupted() {
1401 report.interrupted = true;
1402 }
1403 if !report.interrupted
1404 && let Some(path) = &options.write_baseline
1405 {
1406 let partial = crate::baseline::PartialScope {
1407 scope: scope.as_ref(),
1408 exclude_files: &options.exclude_files,
1409 preserve_all_existing: true,
1410 };
1411 let single_pkg = batch.is_none().then_some(package.name.as_str());
1412 let summary = crate::baseline::write_scoped(
1413 path,
1414 &package.name,
1415 &ws_package_prefix,
1416 &[],
1417 Some(&partial),
1418 single_pkg,
1419 )?;
1420 if summary.preserved > 0 {
1421 note(&format!(
1422 "baseline {}: preserved {} out-of-scope entries (no sites evaluated)",
1423 path.display(),
1424 summary.preserved
1425 ));
1426 }
1427 }
1428 if !empty_shard {
1429 report.mutants_not_built += not_built_reverts + not_built_witnesses;
1430 }
1431 if crate::interrupt::is_interrupted() {
1432 report.interrupted = true;
1433 }
1434 report.record_evaluation();
1435 if let Some(path) = report.analysis.checkpoint.as_deref() {
1436 let checkpoint = Checkpoint::open(path)?;
1437 let settings =
1438 serde_json::json!({"analysis": &report.analysis, "package": &package.name});
1439 let identity = crate::campaign_identity::compute(©, &settings, [], false)?;
1440 checkpoint.start(&identity, settings)?;
1441 checkpoint.finish()?;
1442 }
1443 return Ok(report);
1444 }
1445
1446 for (id, site) in files
1449 .iter_mut()
1450 .flat_map(|file| &mut file.sites)
1451 .enumerate()
1452 {
1453 site.id = id as u32;
1454 }
1455 let beyond: HashSet<u32> = files
1457 .iter()
1458 .flat_map(|file| {
1459 file.sites
1460 .iter()
1461 .filter(|site| beyond_places.contains(&(file.path.clone(), site.start, site.end)))
1462 .map(|site| site.id)
1463 })
1464 .collect();
1465
1466 let root_source = state
1467 .original(&root_file, &workspace)?
1468 .with_context(|| format!("{} is missing", root_target.src_path.display()))?;
1469 let root_suffix = if options.source_only || files.iter().all(|file| file.sites.is_empty()) {
1470 String::new()
1471 } else {
1472 state.write(
1473 &source_dir.join(format!("{RUNTIME_MOD}.rs")),
1474 crate::RUNTIME_SOURCE,
1475 )?;
1476 let std_alias = format!("extern crate std as {STD_ALIAS};");
1477 if root_source.contains(&std_alias) {
1478 format!("\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
1479 } else {
1480 format!("\n#[doc(hidden)]\n{std_alias}\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
1481 }
1482 };
1483
1484 let mut disabled: HashSet<u32> = HashSet::new();
1486 let mut repairs = BTreeMap::new();
1487 let build_target = work_directory(&work, "target")?;
1488 let target_flags = test_build_flags(&test_packages, selection, &workspace, &options.cargo);
1489 let build_scope = if target_flags.is_some() {
1490 report::TestBuildScope::SelectedTargets
1491 } else {
1492 report::TestBuildScope::PackageWide
1493 };
1494 let build_note = if selection.has_target_filters() && target_flags.is_none() {
1495 "Cargo is using a package-wide build because the selected test targets cannot be expressed exactly.\n"
1496 } else {
1497 ""
1498 };
1499 if !build_note.is_empty() {
1500 note(build_note.trim_end());
1501 }
1502 let can_build_only_observer = !options.doc
1505 && target_flags.is_none()
1506 && test_packages.len() == 1
1507 && package.targets.len() == 1
1508 && root_target.test
1509 && root_target.test_build_arg() == Some(("--lib", None));
1510 let build_test_binaries = |observer: bool| {
1511 let mut command = Command::new("cargo");
1512 isolate_copy_command(&mut command, &work);
1513 if let Some(lock) = &work_lock {
1514 lock.retain_for(&mut command);
1515 }
1516 command
1517 .args(["test", "--no-run", "--message-format=json"])
1518 .args(test_packages.iter().flat_map(|p| ["-p", p.name.as_str()]))
1519 .args(target_flags.as_deref().unwrap_or_default())
1520 .args((observer && can_build_only_observer).then_some("--lib"))
1521 .args(options.cargo.flags())
1522 .current_dir(©)
1523 .env("CARGO_TARGET_DIR", &build_target)
1524 .env("CARGO_BUILD_BUILD_DIR", &build_target)
1525 .envs(profile_env(options.opt_level));
1526 run_cargo_with_progress(&mut command, options.progress && !observer)
1527 };
1528 let cargo_build = || build_test_binaries(false);
1529 let has_probe_sites = !options.source_only && files.iter().any(|f| !f.sites.is_empty());
1530 let repair_fingerprint = has_probe_sites.then(|| {
1531 let test_pkg_names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
1532 repair_cache::compute_fingerprint(
1533 &state.root,
1534 ©,
1535 &workspace,
1536 &state,
1537 &external_deps,
1538 &package.name,
1539 &test_pkg_names,
1540 &options.cargo,
1541 options.opt_level,
1542 target_flags.as_deref(),
1543 &error_values,
1544 options.doc,
1545 &files,
1546 )
1547 });
1548 if let Some(fingerprint) = &repair_fingerprint {
1549 let cached = repair_cache::load(&work, fingerprint);
1550 if !cached.is_empty() {
1551 for entry in cached {
1552 if let Some(file) = files.iter().find(|f| f.display == entry.file)
1553 && let Some(site) = file.sites.get(entry.site_index)
1554 && site.start == entry.start
1555 && site.end == entry.end
1556 && site.text == entry.text
1557 && format!("{:?}", site.kind) == entry.kind
1558 {
1559 disabled.insert(site.id);
1560 repairs.entry(site.id).or_insert(entry.reason);
1561 }
1562 }
1563 if !disabled.is_empty() {
1564 note(&format!(
1565 "reusing {} cached repair exclusion(s)",
1566 disabled.len()
1567 ));
1568 }
1569 }
1570 }
1571 let mut rounds = 0;
1572 let mut newly_disabled = HashSet::new();
1573 let build = loop {
1574 for file in &mut files {
1575 let suffix = if file.path == root_file {
1576 root_suffix.as_str()
1577 } else {
1578 ""
1579 };
1580 write_rendered(file, &state, suffix, &disabled, &newly_disabled)?;
1581 }
1582 if !files.iter().any(|f| f.path == root_file) {
1583 state.write(&root_file, &format!("{root_source}{root_suffix}"))?;
1584 }
1585 if rounds == 0 {
1586 state.settle(&workspace)?;
1587 }
1588 note(if rounds == 0 {
1589 "building the instrumented crate"
1590 } else {
1591 "rebuilding without the sites that failed to compile"
1592 });
1593 let output = cargo_build()?;
1594 let names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
1595 let build = parse_build_output(&String::from_utf8_lossy(&output.stdout), &names);
1596 if output.status.success() {
1597 if let Some(fingerprint) = &repair_fingerprint {
1598 let cached_entries: Vec<repair_cache::CachedSite> = files
1599 .iter()
1600 .flat_map(|file| {
1601 file.sites
1602 .iter()
1603 .enumerate()
1604 .filter(|(_, site)| disabled.contains(&site.id))
1605 .map(|(site_index, site)| repair_cache::CachedSite {
1606 file: file.display.clone(),
1607 site_index,
1608 start: site.start,
1609 end: site.end,
1610 text: site.text.clone(),
1611 kind: format!("{:?}", site.kind),
1612 reason: repairs.get(&site.id).cloned().unwrap_or_default(),
1613 })
1614 })
1615 .collect();
1616 let _ = repair_cache::save(&work, fingerprint, &cached_entries);
1617 }
1618 break build;
1619 }
1620 let diagnostics = || {
1621 [
1622 build.diagnostics.join("\n"),
1623 String::from_utf8_lossy(&output.stderr).into_owned(),
1624 ]
1625 .into_iter()
1626 .filter(|part| !part.trim().is_empty())
1627 .collect::<Vec<_>>()
1628 .join("\n")
1629 };
1630 if build.errors.is_empty() {
1631 bail!("the build failed:\n{build_note}{}", diagnostics());
1632 }
1633 if build
1634 .errors
1635 .iter()
1636 .any(|error| is_non_probe_error(error, &files, ©))
1637 {
1638 bail!(
1639 "the build failed with an error unrelated to instrumentation:\n{build_note}{}",
1640 diagnostics()
1641 );
1642 }
1643 rounds += 1;
1644 let before = disabled.len();
1645 let mut blamed_now: HashSet<u32> = HashSet::new();
1646 for error in &build.errors {
1647 let blamed = blame_error(error, &files, ©, &disabled);
1648 if std::env::var_os("TMT_DEBUG").is_some() {
1649 eprintln!(
1650 "tmt: debug: blaming {blamed:?} for\n{}",
1651 report::sanitize_terminal(&error.rendered)
1652 );
1653 }
1654 for id in blamed {
1655 repairs
1656 .entry(id)
1657 .or_insert_with(|| error.rendered.lines().next().unwrap_or("").to_string());
1658 blamed_now.insert(id);
1659 }
1660 }
1661 disabled.extend(blamed_now.iter().copied());
1662 newly_disabled = blamed_now;
1663 if disabled.len() == before || rounds > MAX_REPAIR_ROUNDS {
1664 bail!(
1665 "the crate does not build after instrumentation.\n\
1666 {build_note}Does `cargo test --no-run` pass on the original for the same targets?\n{}",
1667 diagnostics()
1668 );
1669 }
1670 };
1671 let built_sources = if options.rebuild || options.source_only || options.audit.is_some() {
1672 let behind_cargo = features_from_flags(
1677 std::env::vars_os()
1678 .filter(|(name, _)| name.to_string_lossy().ends_with("RUSTFLAGS"))
1679 .map(|(_, value)| Some(value)),
1680 ) || build.build_scripts.iter().any(|script| {
1681 script["cfgs"].as_array().is_some_and(|cfgs| {
1682 cfgs.iter()
1683 .any(|cfg| cfg.as_str().is_some_and(|cfg| cfg.contains("feature")))
1684 })
1685 }) || configuration_names_a_feature(
1686 ©,
1687 std::env::var_os("CARGO_HOME").map(PathBuf::from),
1688 );
1689 BuiltSources::from_artifacts(&build.artifacts, &build.features, !behind_cargo, ©)
1690 } else {
1691 BuiltSources::default()
1692 };
1693 output_fixture::stage(&workspace, &work, &build_target, &options.output_fixtures)?;
1694 let checkpoint_path = report.analysis.checkpoint.as_deref();
1695 let checkpoint = checkpoint_path.map(Checkpoint::open).transpose()?;
1696 let doc_packages = test_packages
1697 .iter()
1698 .filter(|p| options.doc && p.targets.iter().any(|target| target.doctest));
1699 if build.test_binaries.is_empty() && doc_packages.clone().next().is_none() {
1700 bail!("{build_note}`{}` has no test binaries", package.name);
1701 }
1702
1703 let mut session = Session {
1705 progress: options.progress,
1706 serial_timeout_rechecks: options.serial_timeout_rechecks,
1707 package_dir,
1708 binaries: vec![],
1709 };
1710 let wrapper = selection
1711 .wrapper
1712 .as_ref()
1713 .map(|path| {
1714 let relative = wrapper_relative(path)?;
1715 let copied = copy.join(&relative);
1716 if !copied.is_file() {
1717 bail!(
1718 "test wrapper is missing from the work copy: {}",
1719 copied.display()
1720 );
1721 }
1722 Ok(copied)
1723 })
1724 .transpose()?;
1725 let mut runners: Vec<(String, Runner, PathBuf)> = vec![];
1726 let root_test_exe = |built: &BuildOutput| {
1727 built
1728 .test_binaries
1729 .iter()
1730 .find(|(name, _, owner, kind)| {
1731 *name == root_target.name && *owner == package.name && *kind == root_target.kind
1732 })
1733 .map(|(_, exe, _, _)| exe.clone())
1734 };
1735 let root_exe = (!witness_candidates.is_empty())
1736 .then(|| root_test_exe(&build))
1737 .flatten();
1738 let mut discovered_tests: Vec<String> = vec![];
1739 let mut empty_bin_targets: Vec<(String, String)> = vec![];
1740 if let Some(nextest) = &options.nextest {
1741 let mut flags: Vec<_> = test_packages
1742 .iter()
1743 .flat_map(|p| ["-p".to_owned(), p.name.clone()])
1744 .collect();
1745 flags.extend(options.cargo.flags());
1746 runners.push((
1747 "nextest".to_owned(),
1748 Runner::Nextest {
1749 copy: copy.clone(),
1750 target_dir: build_target.clone(),
1751 profile: nextest.profile.clone(),
1752 opt_level: options.opt_level,
1753 flags,
1754 },
1755 session.package_dir.clone(),
1756 ));
1757 } else {
1758 for (name, exe, owner, kind) in build.test_binaries {
1759 if !artifact_target_selected(&name, &kind, selection) {
1760 continue;
1761 }
1762 let owner_package = test_packages
1763 .iter()
1764 .find(|p| p.name == owner)
1765 .expect("binaries are filtered by these packages");
1766 let cwd = in_copy(
1767 owner_package
1768 .manifest_path
1769 .parent()
1770 .expect("manifest has a parent"),
1771 )?;
1772 if selection.enabled() {
1773 let all = list_tests(&exe, &cwd, &work, false, true, work_lock.as_deref())?;
1774 if all.is_empty() && kind.first().map(String::as_str) == Some("bin") {
1775 empty_bin_targets.push((owner.clone(), name.clone()));
1776 }
1777 let ignored = list_tests(&exe, &cwd, &work, true, true, work_lock.as_deref())?;
1778 for test in all {
1779 let was_ignored = ignored.contains(&test);
1780 if (!was_ignored || selection.include_ignored)
1781 && !selection.exclude.iter().any(|name| name == &test)
1782 {
1783 discovered_tests.push(test.clone());
1784 }
1785 if !selection.matches_test(&test, was_ignored) {
1786 continue;
1787 }
1788 runners.push((
1789 format!("{owner}::{}::{name}::{test}", kind.join("+")),
1790 Runner::Isolated {
1791 exe: exe.clone(),
1792 test,
1793 ignored: was_ignored,
1794 wrapper: wrapper.clone(),
1795 },
1796 cwd.clone(),
1797 ));
1798 }
1799 continue;
1800 }
1801 let name = if owner == package.name {
1803 name
1804 } else {
1805 format!("{owner}::{name}")
1806 };
1807 runners.push((name, Runner::Exe(exe), cwd));
1808 }
1809 }
1810 if selection.enabled() && runners.is_empty() {
1811 let hint = no_tests_matched_hint(
1812 &test_packages,
1813 selection,
1814 &empty_bin_targets,
1815 &discovered_tests,
1816 );
1817 bail!("{build_note}no tests matched the requested selection{hint}");
1818 }
1819 let selected_tests = selection.enabled().then(|| report::TestSelection {
1820 build_scope,
1821 wrapper: selection
1822 .wrapper
1823 .as_ref()
1824 .map(|path| path.display().to_string()),
1825 tests: runners.iter().map(|(name, _, _)| name.clone()).collect(),
1826 });
1827 for owner in doc_packages {
1828 let doc = Runner::Doc {
1829 copy: copy.clone(),
1830 target_dir: build_target.clone(),
1831 package: owner.name.clone(),
1832 opt_level: options.opt_level,
1833 flags: options.cargo.flags(),
1834 };
1835 let name = if owner.name == package.name {
1836 "doc tests".to_owned()
1837 } else {
1838 format!("{}::doc tests", owner.name)
1839 };
1840 let cwd = in_copy(owner.manifest_path.parent().expect("manifest has a parent"))?;
1841 runners.push((name, doc, cwd));
1842 }
1843 report.analysis.test_selection = selected_tests;
1844 let identity = if checkpoint.is_some() {
1845 let mut build_inputs: Vec<_> = build
1846 .build_scripts
1847 .iter()
1848 .map(serde_json::Value::to_string)
1849 .collect();
1850 build_inputs.sort();
1851 let settings = serde_json::json!({
1854 "build_scripts": build_inputs,
1855 "analysis": &report.analysis, "package": &package.name, "jobs": effective_jobs,
1856 "verify": options.verify, "audit": options.audit, "effects": options.effects,
1857 "all_files": options.all_files, "build_scope": build_scope,
1858 "runners": runners.iter().map(|(name, runner, cwd)| (name, runner.executable(), cwd)).collect::<Vec<_>>()
1859 });
1860 let mut inputs = BTreeSet::new();
1861 for (root, artifacts) in &build.artifacts {
1862 inputs.insert(root.clone());
1863 if let Some(dependencies) = artifacts
1864 .iter()
1865 .map(|artifact| artifact_inputs(artifact, root, ©))
1866 .find(|deps| !deps.is_empty())
1867 {
1868 inputs.extend(dependencies);
1869 } else {
1870 inputs.extend(artifacts.iter().cloned());
1873 }
1874 }
1875 inputs.extend(
1876 build
1877 .build_scripts
1878 .iter()
1879 .filter_map(|script| script.get("out_dir")?.as_str().map(PathBuf::from)),
1880 );
1881 inputs.retain(|path| !path.starts_with(©));
1884 inputs.extend(
1885 options
1886 .output_fixtures
1887 .iter()
1888 .map(|fixture| build_target.join(&fixture.to)),
1889 );
1890 inputs.extend(
1891 options
1892 .stage_external
1893 .iter()
1894 .map(|entry| normalize(©.join(&entry.rel))),
1895 );
1896 Some(crate::campaign_identity::compute(
1897 ©,
1898 &settings,
1899 inputs,
1900 options.nextest.is_some(),
1901 )?)
1902 } else {
1903 None
1904 };
1905 let marks = marks_dir(&work)?;
1910 let baseline_jobs = if selection.enabled() {
1911 options.baseline_jobs
1912 } else {
1913 1
1914 };
1915 if options.progress {
1916 eprintln!(
1917 "tmt: baselines: 0/{} completed ({} workers)",
1918 runners.len(),
1919 baseline_jobs
1920 );
1921 }
1922
1923 let baseline_budget = options
1924 .baseline_timeout_seconds
1925 .map(Duration::from_secs)
1926 .unwrap_or(DEFAULT_BASELINE_TIMEOUT);
1927 let baseline_stage = if options.source_only {
1928 "baseline_untraced"
1929 } else {
1930 "baseline_trace"
1931 };
1932 let diagnostic_path = work.join("baseline-timeout.json");
1933 let _ = fs::remove_file(&diagnostic_path);
1934 let completed_baselines = std::sync::atomic::AtomicUsize::new(0);
1935 let completed_timings = std::sync::Mutex::new(Vec::<report::BaselineTimingEntry>::new());
1936 let total_baselines = runners.len();
1937 let wrapper_grace_counter = selection
1938 .wrapper
1939 .as_ref()
1940 .map(|_| Arc::new(runner::WrapperGraceCounter::default()));
1941
1942 #[derive(Debug)]
1943 enum BaselinePoolError {
1944 Timeout(Box<report::BaselineTimeoutDiagnostic>),
1945 Failed(Box<report::BaselineFailureDiagnostic>),
1946 }
1947
1948 impl std::fmt::Display for BaselinePoolError {
1949 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1950 match self {
1951 Self::Timeout(diag) => write!(
1952 f,
1953 "baseline timeout in stage `{}` for `{}`",
1954 diag.stage, diag.runner
1955 ),
1956 Self::Failed(diag) => write!(f, "the tests in `{}` {}", diag.runner, diag.reason),
1957 }
1958 }
1959 }
1960
1961 impl std::error::Error for BaselinePoolError {}
1962
1963 let disable_proptest_persistence = should_disable_proptest_persistence(
1964 copy_has_proptest_regressions(©),
1965 std::env::var_os(PROPTEST_DISABLE_ENV).is_some(),
1966 keep_proptest_persistence_requested(std::env::var_os(TMT_KEEP_PROPTEST_PERSISTENCE_ENV)),
1967 );
1968
1969 let baseline_result = progress::track_baselines(options.progress, runners.len(), |progress| {
1970 run_pool(runners.len(), baseline_jobs, |slot| {
1971 let index = slot;
1972 let (name, runner, cwd) = runners[index].clone();
1973 let result = (|| {
1974 let trace_path = work.join(format!("trace-{index}.tsv"));
1975 let _ = fs::remove_file(&trace_path);
1976 let mut bin = TestBinary {
1977 name,
1978 cwd,
1979 marks: marks.clone(),
1980 git_ceiling: work.clone(),
1981 work_lock: work_lock.clone(),
1982 tests: BTreeSet::new(),
1983 runner,
1984 baseline: Duration::ZERO,
1985 untraced_baseline: None,
1986 timeout_diagnostic: std::sync::Once::new(),
1987 traced: Duration::ZERO,
1988 timeout: options.timeout_seconds.map(Duration::from_secs),
1989 wrapper_grace: options.wrapper_grace,
1990 wrapper_grace_counter: wrapper_grace_counter.clone(),
1991 report_slow: options.progress,
1992 disable_proptest_persistence,
1993 filtered_timings: Default::default(),
1994 trace: Trace::default(),
1995 effects_baseline: std::sync::OnceLock::new(),
1996 };
1997 session.note(&format!("tracing `{}`", bin.name));
1998 let started = Instant::now();
1999 let trace_env = trace_path.to_string_lossy().into_owned();
2000 let trace = [("TMT_TRACE", trace_env.as_str())];
2001 let isolated_test = match &bin.runner {
2002 Runner::Isolated { test, .. } => Some(test.clone()),
2003 _ => None,
2004 };
2005 match run_baseline(
2006 &bin,
2007 if options.source_only { &[] } else { &trace },
2008 baseline_budget,
2009 &work.join(format!("baseline-{index}.log")),
2010 false,
2011 )? {
2012 BaselineRun::Passed => {}
2013 BaselineRun::TimedOut {
2014 elapsed,
2015 log,
2016 log_summary,
2017 } => {
2018 let log_path =
2019 log.unwrap_or_else(|| work.join(format!("baseline-{index}.log")));
2020 let (rerun_args, exclude_args) = match &bin.runner {
2021 Runner::Isolated { test, .. } => (
2022 vec!["--include-test".to_string(), test.clone()],
2023 vec!["--exclude-test".to_string(), test.clone()],
2024 ),
2025 Runner::Exe(_) => {
2026 let target = bin
2027 .name
2028 .rsplit_once("::")
2029 .map_or(bin.name.as_str(), |(_, t)| t)
2030 .to_string();
2031 (vec!["--test-target".to_string(), target], vec![])
2032 }
2033 Runner::Nextest { .. } | Runner::Doc { .. } => (vec![], vec![]),
2034 };
2035 let completed =
2036 completed_baselines.load(std::sync::atomic::Ordering::Acquire);
2037 let diagnostic = report::BaselineTimeoutDiagnostic {
2038 schema_version: report::SCHEMA_VERSION,
2039 package: package.name.clone(),
2040 stage: baseline_stage,
2041 runner: bin.name.clone(),
2042 test: isolated_test,
2043 elapsed_seconds: round_millis(elapsed),
2044 budget_seconds: baseline_budget.as_secs(),
2045 completed_baselines: completed,
2046 total_baselines,
2047 partial_baseline: true,
2048 log: log_path,
2049 lines: options.lines.clone(),
2050 rerun_args,
2051 exclude_args,
2052 completed_timings: Vec::new(),
2053 log_summary,
2054 };
2055 return Err(BaselinePoolError::Timeout(Box::new(diagnostic)).into());
2056 }
2057 BaselineRun::Failed {
2058 reason,
2059 elapsed,
2060 log,
2061 log_summary,
2062 } => {
2063 let completed =
2064 completed_baselines.load(std::sync::atomic::Ordering::Acquire);
2065 let diagnostic = report::BaselineFailureDiagnostic {
2066 schema_version: report::SCHEMA_VERSION,
2067 package: package.name.clone(),
2068 stage: baseline_stage,
2069 runner: bin.name.clone(),
2070 test: isolated_test,
2071 reason,
2072 elapsed_seconds: round_millis(elapsed),
2073 completed_baselines: completed,
2074 total_baselines,
2075 log,
2076 completed_timings: Vec::new(),
2077 log_summary,
2078 };
2079 return Err(BaselinePoolError::Failed(Box::new(diagnostic)).into());
2080 }
2081 }
2082 bin.traced = started.elapsed();
2083 bin.baseline = bin.traced;
2084 if options.source_only {
2085 bin.untraced_baseline = Some(BaselineTiming::Completed(bin.baseline));
2086 }
2087 if !options.source_only && bin.traced > SLOW_TRACE {
2090 let started = Instant::now();
2091 match run_baseline(
2092 &bin,
2093 &[],
2094 bin.traced,
2095 &work.join(format!("baseline-{index}-untraced.log")),
2096 true,
2097 )? {
2098 BaselineRun::Passed => {
2099 let elapsed = started.elapsed();
2100 bin.untraced_baseline = Some(BaselineTiming::Completed(elapsed));
2101 bin.baseline = elapsed;
2102 }
2103 BaselineRun::TimedOut { .. } => {
2104 bin.untraced_baseline = Some(BaselineTiming::StillRunning(bin.traced));
2105 }
2106 BaselineRun::Failed {
2107 reason,
2108 elapsed,
2109 log,
2110 log_summary,
2111 } => {
2112 let completed =
2113 completed_baselines.load(std::sync::atomic::Ordering::Acquire);
2114 let diagnostic = report::BaselineFailureDiagnostic {
2115 schema_version: report::SCHEMA_VERSION,
2116 package: package.name.clone(),
2117 stage: "baseline_untraced",
2118 runner: bin.name.clone(),
2119 test: isolated_test,
2120 reason,
2121 elapsed_seconds: round_millis(elapsed),
2122 completed_baselines: completed,
2123 total_baselines,
2124 log,
2125 completed_timings: Vec::new(),
2126 log_summary,
2127 };
2128 return Err(BaselinePoolError::Failed(Box::new(diagnostic)).into());
2129 }
2130 }
2131 }
2132 let make_baseline_failure =
2135 |stage: &'static str, reason: &'static str, log: PathBuf, detail: String| {
2136 let completed =
2137 completed_baselines.load(std::sync::atomic::Ordering::Acquire);
2138 BaselinePoolError::Failed(Box::new(report::BaselineFailureDiagnostic {
2139 schema_version: report::SCHEMA_VERSION,
2140 package: package.name.clone(),
2141 stage,
2142 runner: bin.name.clone(),
2143 test: isolated_test.clone(),
2144 reason,
2145 elapsed_seconds: round_millis(bin.baseline),
2146 completed_baselines: completed,
2147 total_baselines,
2148 log,
2149 completed_timings: Vec::new(),
2150 log_summary: vec![detail],
2151 }))
2152 };
2153 let text = match fs::read_to_string(&trace_path) {
2154 Ok(text) => text,
2155 Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
2156 Err(err) => {
2157 return Err(make_baseline_failure(
2158 baseline_stage,
2159 "failed to read baseline trace",
2160 trace_path.clone(),
2161 format!("cannot read the trace of `{}`: {err}", bin.name),
2162 )
2163 .into());
2164 }
2165 };
2166 bin.trace = Trace::parse(&text);
2167 if bin.trace.malformed_lines > 0 {
2168 return Err(make_baseline_failure(
2169 baseline_stage,
2170 "produced a malformed baseline trace",
2171 trace_path.clone(),
2172 format!(
2173 "the trace of `{}` has {} malformed lines; not drawing conclusions from it",
2174 bin.name, bin.trace.malformed_lines
2175 ),
2176 )
2177 .into());
2178 }
2179 if let Runner::Exe(exe) = &bin.runner {
2180 bin.tests = match list_tests(
2181 exe,
2182 &bin.cwd,
2183 &work,
2184 false,
2185 false,
2186 work_lock.as_deref(),
2187 ) {
2188 Ok(tests) => tests,
2189 Err(err)
2190 if crate::interrupt::is_interrupted()
2191 || crate::interrupt::is_interrupted_err(&err) =>
2192 {
2193 return Err(err);
2194 }
2195 Err(err) => {
2196 return Err(make_baseline_failure(
2197 baseline_stage,
2198 "failed to list baseline tests",
2199 exe.clone(),
2200 format!("{err:#}"),
2201 )
2202 .into());
2203 }
2204 };
2205 }
2206 if let Ok(mut timings) = completed_timings.lock() {
2207 timings.push(report::BaselineTimingEntry {
2208 runner: bin.name.clone(),
2209 test: isolated_test,
2210 elapsed_seconds: round_millis(bin.baseline),
2211 });
2212 }
2213 completed_baselines.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
2214 Ok(bin)
2215 })();
2216 progress.complete(if result.is_ok() {
2217 progress::Outcome::Survived
2218 } else {
2219 progress::Outcome::Failed
2220 });
2221 result
2222 })
2223 });
2224 let collect_completed_timings = || -> Vec<report::BaselineTimingEntry> {
2225 let mut timings = completed_timings
2226 .lock()
2227 .unwrap_or_else(|e| e.into_inner())
2228 .clone();
2229 timings.sort_by(|a, b| {
2230 b.elapsed_seconds
2231 .total_cmp(&a.elapsed_seconds)
2232 .then_with(|| a.runner.cmp(&b.runner))
2233 });
2234 timings
2235 };
2236 session.binaries = match baseline_result {
2237 Ok(binaries) => binaries,
2238 Err(err) => match err.downcast::<BaselinePoolError>() {
2239 Ok(BaselinePoolError::Timeout(mut diagnostic)) => {
2240 diagnostic.completed_baselines =
2243 completed_baselines.load(std::sync::atomic::Ordering::Acquire);
2244 diagnostic.completed_timings = collect_completed_timings();
2245 let write_status = serde_json::to_string_pretty(&diagnostic)
2246 .map_err(anyhow::Error::from)
2247 .and_then(|json| {
2248 use std::io::Write as _;
2249 static NEXT_DIAG_TMP: std::sync::atomic::AtomicUsize =
2250 std::sync::atomic::AtomicUsize::new(0);
2251 let seq = NEXT_DIAG_TMP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2252 let tmp = work.join(format!(
2253 ".baseline-timeout.{}.{seq}.tmp",
2254 std::process::id()
2255 ));
2256 let mut file = fs::OpenOptions::new()
2257 .write(true)
2258 .create_new(true)
2259 .open(&tmp)?;
2260 if let Err(err) = file
2261 .write_all(format!("{json}\n").as_bytes())
2262 .and_then(|()| file.flush())
2263 {
2264 drop(file);
2265 let _ = fs::remove_file(&tmp);
2266 return Err(err.into());
2267 }
2268 drop(file);
2269 if let Err(rename_err) = fs::rename(&tmp, &diagnostic_path) {
2270 let _ = fs::remove_file(&tmp);
2271 return Err(rename_err.into());
2272 }
2273 Ok(())
2274 });
2275 let diag_note = match write_status {
2276 Ok(()) => format!("diagnostic: {}", diagnostic_path.display()),
2277 Err(write_err) => format!(
2278 "failed to write diagnostic {}: {write_err}",
2279 diagnostic_path.display()
2280 ),
2281 };
2282 let subject = match &diagnostic.test {
2283 Some(test) => format!("`{}` (test `{test}`)", diagnostic.runner),
2284 None => format!("`{}`", diagnostic.runner),
2285 };
2286 let hint =
2287 if !diagnostic.rerun_args.is_empty() && !diagnostic.exclude_args.is_empty() {
2288 format!(
2289 "; rerun separately with `{}` or exclude with `{}`",
2290 diagnostic.rerun_args.join(" "),
2291 diagnostic.exclude_args.join(" ")
2292 )
2293 } else if !diagnostic.rerun_args.is_empty() {
2294 format!(
2295 "; rerun separately with `{}`",
2296 diagnostic.rerun_args.join(" ")
2297 )
2298 } else {
2299 String::new()
2300 };
2301 let timings_section = format_baseline_timings_section(
2302 &diagnostic.completed_timings,
2303 &diagnostic.runner,
2304 diagnostic.elapsed_seconds,
2305 "timed out",
2306 diagnostic.total_baselines,
2307 );
2308 let summary_section = format_log_summary_section(&diagnostic.log_summary);
2309 let message = format!(
2310 "baseline timeout in stage `{}` for {subject}: elapsed {:.3}s exceeded budget {}s (increase with --baseline-timeout <SECONDS>; completed {}/{} baselines; partial baseline was not used as a complete trace); {diag_note}; log: {}{hint}{timings_section}{summary_section}",
2311 diagnostic.stage,
2312 diagnostic.elapsed_seconds,
2313 diagnostic.budget_seconds,
2314 diagnostic.completed_baselines,
2315 diagnostic.total_baselines,
2316 diagnostic.log.display()
2317 );
2318 return Err(BaselineError::Timeout {
2319 diagnostic,
2320 wrapper_grace_outcomes: wrapper_grace_counter.as_ref().map(|c| c.snapshot()),
2321 message,
2322 }
2323 .into());
2324 }
2325 Ok(BaselinePoolError::Failed(mut diagnostic)) => {
2326 diagnostic.completed_baselines =
2327 completed_baselines.load(std::sync::atomic::Ordering::Acquire);
2328 diagnostic.completed_timings = collect_completed_timings();
2329 let timings_section = format_baseline_timings_section(
2330 &diagnostic.completed_timings,
2331 &diagnostic.runner,
2332 diagnostic.elapsed_seconds,
2333 "failed",
2334 diagnostic.total_baselines,
2335 );
2336 let summary_section = format_log_summary_section(&diagnostic.log_summary);
2337 let message = format!(
2338 "the tests in `{}` {}; full output: {}{timings_section}{summary_section}",
2339 diagnostic.runner,
2340 diagnostic.reason,
2341 diagnostic.log.display()
2342 );
2343 return Err(BaselineError::Failed {
2344 diagnostic,
2345 wrapper_grace_outcomes: wrapper_grace_counter.as_ref().map(|c| c.snapshot()),
2346 message,
2347 }
2348 .into());
2349 }
2350 Err(other) => return Err(other),
2351 },
2352 };
2353
2354 for file in &files {
2356 for site in &file.sites {
2357 if disabled.contains(&site.id) {
2358 let fallback = options.rebuild
2359 && !matches!(site.kind, SiteKind::Body { .. })
2360 && !instrument::source_mutants(site).is_empty();
2361 match site.kind {
2362 SiteKind::Body { .. } => report.unviable_mutants += 1,
2363 _ if fallback => {}
2364 _ => report.skipped_sites += 1,
2365 }
2366 report.skipped.push(report::SkippedSite::new(
2367 report::location(&file.display, site),
2368 file.lines.position(&file.original, site.end),
2369 if fallback {
2370 report::SkipReason::ProbeReplacedBySourceRebuild
2371 } else {
2372 report::SkipReason::ProbeCompileError
2373 },
2374 repairs.get(&site.id).cloned(),
2375 ));
2376 }
2377 }
2378 if !options.rebuild && !options.source_only {
2379 report.skipped.extend(file.rebuild_sites.iter().map(|site| {
2380 report::SkippedSite::new(
2381 report::location(&file.display, site),
2382 file.lines.position(&file.original, site.end),
2383 report::SkipReason::RequiresSourceRebuild,
2384 None,
2385 )
2386 }));
2387 }
2388 }
2389 if let (Some(checkpoint), Some(identity)) = (&checkpoint, &identity) {
2390 checkpoint.start(
2391 identity,
2392 serde_json::json!({
2393 "package": &package.name, "analysis": &report.analysis,
2394 "runners": session.binaries.iter().map(|bin| &bin.name).collect::<Vec<_>>(),
2395 "jobs": effective_jobs, "tool_version": env!("CARGO_PKG_VERSION")
2396 }),
2397 )?;
2398 }
2399 let phase = |name: &str, keys: Vec<String>| {
2400 checkpoint
2401 .as_ref()
2402 .zip(identity.as_deref())
2403 .map(|(checkpoint, identity)| checkpoint.begin(name, identity, keys))
2404 .transpose()
2405 };
2406 let probe_phase = |name: &str, jobs: &[Job]| -> Result<Option<Phase<'_>>> {
2407 if checkpoint.is_none() {
2408 return Ok(None);
2409 }
2410 let locations: BTreeMap<_, _> = files
2411 .iter()
2412 .flat_map(|file| {
2413 file.sites
2414 .iter()
2415 .map(|site| (site.id, (&file.display, site.line, site.column, &site.text)))
2416 })
2417 .collect();
2418 let keys = jobs
2419 .iter()
2420 .map(|job| {
2421 let tests = job
2422 .tests
2423 .iter()
2424 .map(|(bin, selected)| (&session.binaries[*bin].name, selected))
2425 .collect::<Vec<_>>();
2426 serde_json::to_string(&(locations.get(&job.site), job.mutation.encode(), tests))
2427 })
2428 .collect::<std::result::Result<Vec<_>, _>>()?;
2429 phase(name, keys)
2430 };
2431 let scratch = work.clone();
2432 let mut jobs: Vec<Job> = vec![];
2433 let mut not_evaluated: HashSet<u32> = HashSet::new();
2436 let mut site_work: Vec<SiteWork> = vec![];
2437 let mut effect_jobs: Vec<(usize, usize)> = vec![];
2439 for file in &files {
2440 let mut primitive_arith_spans: HashSet<(usize, usize)> = HashSet::new();
2443 let mut primitive_cmp_spans: HashSet<(usize, usize)> = HashSet::new();
2444 let mut cast_probe_spans: std::collections::HashMap<(usize, usize), (u32, u32)> =
2445 std::collections::HashMap::new();
2446 for other in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
2447 if matches!(other.kind, SiteKind::Cmp { .. })
2448 && session
2449 .binaries
2450 .iter()
2451 .any(|b| b.trace.bounds.contains_key(&other.id))
2452 {
2453 primitive_cmp_spans.insert((other.start, other.end));
2454 }
2455 if let SiteKind::Arith { cast_probes, .. } = &other.kind {
2456 let seen = session.merged(|t| t.arith.get(&other.id), plan::ArithObs::merge);
2457 if !seen.opaque && (seen.same || seen.differs || seen.same2 || seen.differs2) {
2458 primitive_arith_spans.insert((other.start, other.end));
2459 }
2460 for &(slot, start, end) in cast_probes {
2461 cast_probe_spans
2462 .entry((start, end))
2463 .or_insert((other.id, slot));
2464 }
2465 }
2466 }
2467 let primitive = |from: usize, to: usize| {
2468 let Some(mut text) = file.original.get(from..to) else {
2469 return false;
2470 };
2471 let mut start = from;
2472 loop {
2473 let trimmed = text.trim_start();
2474 start += text.len() - trimmed.len();
2475 text = trimmed.trim_end();
2476 if text.starts_with('(')
2477 && text.ends_with(')')
2478 && matches!(syn::parse_str::<syn::Expr>(text), Ok(syn::Expr::Paren(_)))
2479 && let Some(inner) = text
2480 .strip_prefix('(')
2481 .and_then(|inner| inner.strip_suffix(')'))
2482 {
2483 start += 1;
2484 text = inner;
2485 } else {
2486 break;
2487 }
2488 }
2489 primitive_arith_spans.contains(&(start, start + text.len()))
2490 };
2491 let cast_bounds = |from: usize, to: usize| -> Option<(i128, i128)> {
2492 let &(owner_id, slot) = cast_probe_spans.get(&(from, to))?;
2493 let mut recorded = session
2494 .binaries
2495 .iter()
2496 .filter_map(|b| b.trace.cast_bounds.get(&(owner_id, slot)));
2497 let first = recorded.next()?;
2498 if recorded.all(|other| other == first) {
2499 *first
2500 } else {
2501 None
2502 }
2503 };
2504 let primitive_cmp = |from: usize, to: usize| primitive_cmp_spans.contains(&(from, to));
2505 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
2506 let plan = match session.plan(
2507 &file.display,
2508 site,
2509 options.verify,
2510 &primitive,
2511 &primitive_cmp,
2512 &cast_bounds,
2513 ) {
2514 Planned::Unreached if beyond.contains(&site.id) => continue,
2517 Planned::Unreached => {
2518 let at = report::location(&file.display, site);
2520 if report.unreached.last() != Some(&at) {
2521 report.unreached.push(at);
2522 }
2523 continue;
2524 }
2525 Planned::Nothing => continue,
2526 Planned::NotEvaluated => {
2527 not_evaluated.insert(site.id);
2528 continue;
2529 }
2530 Planned::Plan(plan) => plan,
2531 };
2532 let mut add =
2533 |mutation: Mutation, tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>| {
2534 jobs.push(session.job(site.id, mutation, tests_of));
2535 jobs.len() - 1
2536 };
2537 let gaps = plan
2538 .gaps
2539 .into_iter()
2540 .map(
2541 |PlannedGap {
2542 finding,
2543 survivors,
2544 constant_expr,
2545 }| {
2546 let confirm = if options.verify {
2549 survivors
2550 .into_iter()
2551 .map(|m| add(m, &*plan.reaching))
2552 .collect()
2553 } else {
2554 vec![]
2555 };
2556 (finding, confirm, constant_expr)
2557 },
2558 )
2559 .collect();
2560 let infected = &plan.infected;
2561 let runs = plan
2562 .run
2563 .iter()
2564 .map(|m| (*m, add(*m, &|bin| infected(bin, *m))))
2565 .collect();
2566 site_work.push(SiteWork {
2567 file: &file.display,
2568 site,
2569 gaps,
2570 constant: plan.constant,
2571 cannot_differ: plan.cannot_differ,
2572 redundant_logic_swap: plan.redundant_logic_swap,
2573 runs,
2574 });
2575 }
2576 }
2577 session.note(&format!(
2578 "running {} mutants on {} thread(s)",
2579 jobs.len(),
2580 options.jobs.max(1)
2581 ));
2582 let probe_checkpoint = probe_phase("probe", &jobs)?;
2583 let mut results =
2584 session.run_jobs(&jobs, options.jobs, "mutants", probe_checkpoint.as_ref())?;
2585 if crate::interrupt::is_interrupted() {
2586 report.interrupted = true;
2587 }
2588 for result in &results {
2589 report.timeout_rechecks.include(result);
2590 }
2591
2592 if !report.interrupted
2595 && let Some(wanted) = options.audit
2596 {
2597 match run_audit_phase(
2598 &session,
2599 &files,
2600 &jobs,
2601 &mut results,
2602 &mut report.timeout_rechecks,
2603 &scratch,
2604 wanted,
2605 options.jobs,
2606 &probe_phase,
2607 ) {
2608 Ok(audit) => report.audit = Some(audit),
2609 Err(err)
2610 if crate::interrupt::is_interrupted()
2611 || crate::interrupt::is_interrupted_err(&err) =>
2612 {
2613 report.interrupted = true;
2614 }
2615 Err(err) => return Err(err),
2616 }
2617 if crate::interrupt::is_interrupted() {
2618 report.interrupted = true;
2619 }
2620 }
2621 #[derive(Clone, Copy, PartialEq, Eq)]
2625 enum EarlierVerdict {
2626 Killed,
2627 Survived,
2628 Unknown,
2629 }
2630 let mut earlier_verdict: BTreeMap<usize, EarlierVerdict> = BTreeMap::new();
2631 let asked: Vec<usize> = site_work
2632 .iter()
2633 .filter(|item| beyond.contains(&item.site.id))
2634 .flat_map(|item| {
2635 item.gaps
2636 .iter()
2637 .flat_map(|(_, confirm, _)| confirm.iter().copied())
2638 .chain(
2639 item.runs
2640 .iter()
2641 .filter(|(m, _)| !(*m == Mutation::LogicSwap && item.redundant_logic_swap))
2642 .map(|(_, job)| *job),
2643 )
2644 })
2645 .filter(|job| results[*job].survived.is_some())
2646 .collect();
2647 if !report.interrupted && !asked.is_empty() {
2648 let revision = report::short_revision(options.since.as_deref().unwrap_or_default());
2649 session.note(&format!(
2650 "running {} surviving mutants against the tests as they were at {revision}",
2651 asked.len()
2652 ));
2653 let suffix = |file: &SourceFile| {
2654 if file.path == root_file {
2655 root_suffix.as_str()
2656 } else {
2657 ""
2658 }
2659 };
2660 let earlier: Option<Vec<(&SourceFile, String)>> = tests_changed
2662 .iter()
2663 .map(|(path, hunks)| {
2664 let file = files.iter().find(|file| file.path == *path)?;
2665 let rendered = file.rendered.as_ref()?;
2666 let mut places = hunks
2667 .iter()
2668 .map(|hunk| {
2669 let (from, to) = scope::range_of(&file.original, hunk);
2670 Some((rendered.copied(from, to)?, hunk.old.as_str()))
2671 })
2672 .collect::<Option<Vec<_>>>()?;
2673 places.sort_by_key(|((from, _), _)| std::cmp::Reverse(*from));
2674 let mut text = rendered.text.clone();
2675 for ((from, to), old) in places {
2676 text.replace_range(from..to, old);
2677 }
2678 Some((file, text))
2679 })
2680 .collect();
2681 let attempted = if let Some(earlier) = earlier {
2682 let attempted = (|| -> Result<Option<Vec<JobResult>>> {
2683 for (file, text) in &earlier {
2684 state.write(&file.path, &format!("{text}{}", suffix(file)))?;
2685 }
2686 if !cargo_build()?.status.success() {
2687 session.note(
2688 "the tests as they were do not build with the code as it is: what they found out is not known",
2689 );
2690 return Ok(None);
2691 }
2692 let all: Vec<&TestBinary> = session.binaries.iter().collect();
2694 if run_source_tests(&all)? != Outcome::Pass {
2695 session.note(
2696 "the tests as they were fail on the code as it is: what they found out is not known",
2697 );
2698 return Ok(None);
2699 }
2700 let against_all: Vec<Job> = asked
2701 .iter()
2702 .map(|job| Job {
2703 site: jobs[*job].site,
2704 mutation: jobs[*job].mutation,
2705 tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
2706 })
2707 .collect();
2708 session
2709 .run_jobs(&against_all, options.jobs, "mutants, earlier tests", None)
2710 .map(Some)
2711 })();
2712 for (file, _) in &earlier {
2714 let rendered = file.rendered.as_ref().expect("rendered before building");
2715 state.write(&file.path, &format!("{}{}", rendered.text, suffix(file)))?;
2716 }
2717 if !crate::interrupt::is_interrupted() {
2718 match cargo_build() {
2719 Ok(output) if output.status.success() => {}
2720 Ok(_) => {
2721 bail!("the crate does not build once its tests are put back as they are");
2722 }
2723 Err(err)
2724 if crate::interrupt::is_interrupted()
2725 || crate::interrupt::is_interrupted_err(&err) =>
2726 {
2727 report.interrupted = true;
2728 }
2729 Err(err) => return Err(err),
2730 }
2731 } else {
2732 report.interrupted = true;
2733 }
2734 attempted
2735 } else {
2736 session.note(
2737 "not all changed test files could be restored as they were: what they found out is not known",
2738 );
2739 Ok(None)
2740 };
2741 match attempted {
2742 Ok(Some(again)) => {
2743 for (job, result) in asked.iter().zip(again) {
2744 let verdict = if result.unable || result.unconfirmed_timeout {
2745 EarlierVerdict::Unknown
2746 } else if result.survived.is_none() {
2747 EarlierVerdict::Killed
2748 } else {
2749 EarlierVerdict::Survived
2750 };
2751 earlier_verdict.insert(*job, verdict);
2752 }
2753 }
2754 Ok(None) => {
2755 for job in &asked {
2756 earlier_verdict.insert(*job, EarlierVerdict::Unknown);
2757 }
2758 }
2759 Err(err)
2760 if crate::interrupt::is_interrupted()
2761 || crate::interrupt::is_interrupted_err(&err) =>
2762 {
2763 report.interrupted = true;
2764 for job in &asked {
2765 earlier_verdict.insert(*job, EarlierVerdict::Unknown);
2766 }
2767 }
2768 Err(err) => return Err(err),
2769 }
2770 if crate::interrupt::is_interrupted() {
2771 report.interrupted = true;
2772 }
2773 }
2774 let pre_job_not_evaluated = not_evaluated.len();
2775 let unable = results
2776 .iter()
2777 .filter(|r| r.unable || r.unconfirmed_timeout)
2778 .count();
2779 not_evaluated.extend(
2780 jobs.iter()
2781 .zip(&results)
2782 .filter(|(_, result)| result.unable || result.unconfirmed_timeout)
2783 .map(|(job, _)| job.site),
2784 );
2785 if !options.rebuild || report.interrupted {
2786 report.mutants_not_evaluated = pre_job_not_evaluated + unable;
2787 }
2788 report.mutants_run = results.len() - unable;
2789 report.mutants_killed = results.iter().filter(|r| r.survived.is_none()).count() - unable;
2790 report.mutants_survived = report.mutants_run - report.mutants_killed;
2791 report.mutants_timed_out = results
2792 .iter()
2793 .filter(|r| r.timed_out && !r.unconfirmed_timeout)
2794 .count();
2795
2796 let mut finding_run_survivors: Vec<usize> = vec![];
2799 let mut killed_by_loc: BTreeMap<(String, usize, usize, &'static str), usize> = BTreeMap::new();
2801
2802 let confirmed = |w: &SiteWork| {
2805 w.gaps
2806 .iter()
2807 .all(|(_, confirm, _)| confirm.iter().all(|j| results[*j].survived.is_some()))
2808 };
2809 let constants: BTreeSet<(&str, usize, usize)> = site_work
2810 .iter()
2811 .filter(|w| w.cannot_differ || (w.constant && confirmed(w)))
2812 .map(|w| (w.file, w.site.start, w.site.end))
2813 .collect();
2814 for item in &site_work {
2815 let at = report::location(item.file, item.site);
2816 for (finding, confirm, constant_expr) in &item.gaps {
2817 let repeats = constant_expr
2820 .is_some_and(|(start, end)| constants.contains(&(item.file, start, end)));
2821 let survived_count = confirm
2822 .iter()
2823 .filter(|j| results[**j].survived.is_some())
2824 .count();
2825 if beyond.contains(&item.site.id) {
2826 let confirmed = confirm.iter().all(|j| results[*j].survived.is_some());
2828 let killed_before = confirm
2829 .iter()
2830 .any(|j| earlier_verdict.get(j) == Some(&EarlierVerdict::Killed));
2831 if confirmed && !repeats && killed_before {
2832 report.weakened.push(finding.at().clone());
2833 report.findings.push(finding.clone());
2834 finding_run_survivors.push(survived_count);
2835 } else if !confirmed {
2836 report.survivor_breakdown.unconfirmed_gap += survived_count;
2837 } else if repeats {
2838 report.survivor_breakdown.redundant_constant += survived_count;
2839 } else {
2840 for job in confirm {
2841 if results[*job].survived.is_some() {
2842 if earlier_verdict.get(job) == Some(&EarlierVerdict::Survived) {
2843 report.survivor_breakdown.preexisting_unchanged += 1;
2844 } else {
2845 report.survivor_breakdown.unchanged_not_compared += 1;
2846 }
2847 }
2848 }
2849 }
2850 continue;
2851 }
2852 match Prediction::of(confirm.iter().map(|j| &results[*j])) {
2853 Prediction::Refuted => {
2854 report.unstable.push(at.clone());
2855 report.survivor_breakdown.unconfirmed_gap += survived_count;
2856 }
2857 Prediction::Confirmed if !repeats => {
2858 report.findings.push(finding.clone());
2859 finding_run_survivors.push(survived_count);
2860 }
2861 Prediction::Confirmed => {
2862 report.survivor_breakdown.redundant_constant += survived_count;
2863 }
2864 Prediction::Unknown => {
2866 report.survivor_breakdown.unconfirmed_gap += survived_count;
2867 }
2868 }
2869 }
2870 if let SiteKind::Body {
2873 sole_expr: Some((start, end)),
2874 ..
2875 } = item.site.kind
2876 && constants.contains(&(item.file, start, end))
2877 {
2878 report.survivor_breakdown.redundant_constant += item
2879 .runs
2880 .iter()
2881 .filter(|(_, job)| results[*job].survived.is_some())
2882 .count();
2883 continue;
2884 }
2885 let mut survivors = vec![];
2886 let mut passing_tests = BTreeSet::new();
2887 for (mutation, job) in &item.runs {
2888 let res = &results[*job];
2889 if !res.unable && !res.unconfirmed_timeout && res.survived.is_none() {
2890 *killed_by_loc
2891 .entry((
2892 item.file.to_string(),
2893 item.site.line,
2894 item.site.column,
2895 "assertion_gap",
2896 ))
2897 .or_insert(0) += 1;
2898 }
2899 if let Some(tests) = &res.survived {
2900 if *mutation == Mutation::LogicSwap && item.redundant_logic_swap {
2901 report.survivor_breakdown.redundant_constant += 1;
2902 continue;
2903 }
2904 if beyond.contains(&item.site.id) {
2905 match earlier_verdict.get(job) {
2906 Some(EarlierVerdict::Killed) => {}
2907 Some(EarlierVerdict::Survived) => {
2908 report.survivor_breakdown.preexisting_unchanged += 1;
2909 continue;
2910 }
2911 Some(EarlierVerdict::Unknown) | None => {
2912 report.survivor_breakdown.unchanged_not_compared += 1;
2913 continue;
2914 }
2915 }
2916 }
2917 survivors.push(report::describe(item.site, *mutation));
2918 passing_tests.extend(tests.iter().cloned());
2919 }
2920 }
2921 if !survivors.is_empty() {
2922 let first = item.runs.iter().find(|(mutation, job)| {
2924 !(*mutation == Mutation::LogicSwap && item.redundant_logic_swap)
2925 && results[*job].survived.is_some()
2926 && (!beyond.contains(&item.site.id)
2927 || earlier_verdict.get(job) == Some(&EarlierVerdict::Killed))
2928 });
2929 if beyond.contains(&item.site.id) {
2930 report.weakened.push(at.clone());
2931 }
2932 effect_jobs.push((report.findings.len(), first.expect("a survivor").1));
2933 finding_run_survivors.push(survivors.len());
2934 report.findings.push(Finding::AssertionGap {
2935 at,
2936 survivors,
2937 tests: passing_tests.into_iter().collect(),
2938 effects: vec![],
2939 effects_of: None,
2940 witness: None,
2941 });
2942 }
2943 }
2944
2945 if !report.interrupted && options.effects && !effect_jobs.is_empty() {
2947 match run_effects_phase(
2948 &session,
2949 &files,
2950 &jobs,
2951 &effect_jobs,
2952 &scratch,
2953 options.jobs,
2954 &mut report.findings,
2955 ) {
2956 Ok(()) => {}
2957 Err(err)
2958 if crate::interrupt::is_interrupted()
2959 || crate::interrupt::is_interrupted_err(&err) =>
2960 {
2961 report.interrupted = true;
2962 }
2963 Err(err) => return Err(err),
2964 }
2965 if crate::interrupt::is_interrupted() {
2966 report.interrupted = true;
2967 }
2968 }
2969
2970 let mut built: Vec<(&SourceFile, &Site, instrument::SourceMutant, Option<usize>)> = vec![];
2974 let build_regular_mutants = options.rebuild || options.source_only;
2975 let mut index = 0;
2976 for file in &files {
2977 let retried = file.sites.iter().filter(|site| {
2980 (disabled.contains(&site.id) && !matches!(site.kind, SiteKind::Body { .. }))
2981 || not_evaluated.contains(&site.id)
2982 });
2983 for site in file.rebuild_sites.iter().chain(retried) {
2984 let mutants = source_mutants(file, site, true);
2985 if build_regular_mutants {
2986 built.extend(mutants.into_iter().filter_map(|mutant| {
2987 let selected = in_shard(index);
2988 index += 1;
2989 selected.then_some((file, site, mutant, None))
2990 }));
2991 } else {
2992 report.mutants_not_built += mutants.len();
2993 }
2994 }
2995 }
2996 if !build_regular_mutants {
2997 report.mutants_not_built += not_built_witnesses;
2998 }
2999 if !report.interrupted
3002 && let (Some(wanted), Some(audit)) = (options.audit, report.audit.as_mut())
3003 {
3004 let mut twins = vec![];
3005 for file in &files {
3006 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
3007 let integers = session.binaries.iter().all(|bin| {
3009 let seen = bin.trace.merged(site.id);
3010 !seen.reached() || seen.valued()
3011 });
3012 let candidates = jobs_for_site(&jobs, site.id);
3013 let job_of = |mutation: Mutation| {
3014 candidates
3015 .clone()
3016 .find(|&index| jobs[index].mutation == mutation)
3017 };
3018 let mut compared = vec![];
3019 let mut mutants = instrument::source_mutants(site);
3020 instrument::keep_line_ends(&file.original, &mut mutants);
3021 for mutant in mutants {
3022 let job = mutations_like(site, &mutant, integers)
3024 .into_iter()
3025 .find_map(job_of);
3026 if let Some(job) = job {
3027 compared.push(job);
3028 twins.push((file, site, mutant, Some(job)));
3029 }
3030 }
3031 if let (SiteKind::Cmp { op, .. }, Some(job)) =
3034 (&site.kind, job_of(Mutation::Negate))
3035 && !compared.contains(&job)
3036 {
3037 let negated = instrument::SourceMutant {
3038 start: site.start,
3039 end: site.end,
3040 replacement: format!("!({})", site.text),
3041 what: op.symbol().to_string(),
3042 into: "!".to_string(),
3043 };
3044 twins.push((file, site, negated, Some(job)));
3045 }
3046 }
3047 }
3048 let chosen = spread(twins.len(), wanted);
3049 audit.rebuilt = chosen.len();
3050 let mut twins: Vec<Option<_>> = twins.into_iter().map(Some).collect();
3051 built.extend(chosen.into_iter().filter_map(|nth| twins[nth].take()));
3052 }
3053 let mut by_speed: Vec<&TestBinary> = session.binaries.iter().collect();
3054 by_speed.sort_by_key(|bin| bin.baseline);
3055 let root_mutant_suffix = if files.iter().any(|file| {
3057 file.path != root_file
3058 && file
3059 .rendered
3060 .as_ref()
3061 .is_some_and(|rendered| rendered.text != file.original)
3062 }) {
3063 root_suffix.as_str()
3064 } else {
3065 ""
3066 };
3067 if !built.is_empty() && report.interrupted {
3068 report.mutants_not_evaluated += built
3069 .iter()
3070 .filter(|(_, _, _, twin)| twin.is_none())
3071 .count();
3072 if let Some(audit) = report.audit.as_mut() {
3073 audit.not_compared += built
3074 .iter()
3075 .filter(|(_, _, _, twin)| twin.is_some())
3076 .count();
3077 }
3078 } else if !built.is_empty() {
3079 if options.timeout_seconds.is_some()
3080 && built
3081 .iter()
3082 .any(|(file, _, _, _)| built_sources.contains(file))
3083 {
3084 for bin in &by_speed {
3085 bin.warn_timeout_conflict(None);
3086 }
3087 }
3088 let source_checkpoint = if checkpoint.is_some() {
3089 let keys = built
3090 .iter()
3091 .map(|(file, _, mutation, twin)| {
3092 serde_json::to_string(&(
3093 &file.display,
3094 mutation.start,
3095 mutation.end,
3096 &mutation.replacement,
3097 twin,
3098 ))
3099 })
3100 .collect::<std::result::Result<Vec<_>, _>>()?;
3101 phase("source", keys)?
3102 } else {
3103 None
3104 };
3105 session.note(&format!(
3106 "building {} mutants one by one (code a probe cannot be put in, or to compare with the probe)",
3107 built.len()
3108 ));
3109 let instrumented = |file: &SourceFile, text: &str, suffix: &str| {
3110 if file.path == root_file {
3111 format!("{text}{suffix}")
3112 } else {
3113 text.to_string()
3114 }
3115 };
3116 let mut skipped_targets = BTreeSet::new();
3119 let mut left_out: BTreeMap<&PathBuf, Vec<(usize, usize)>> = BTreeMap::new();
3121 let mut survivors: Vec<(report::Location, Vec<String>)> = vec![];
3122 progress::track(
3123 options.progress,
3124 "source mutants",
3125 built.len(),
3126 |progress| -> Result<()> {
3127 for (index, (file, site, mutant, twin)) in built.iter().enumerate() {
3128 if crate::interrupt::is_interrupted() {
3129 report.mutants_not_evaluated += built[index..]
3130 .iter()
3131 .filter(|(_, _, _, t)| t.is_none())
3132 .count();
3133 if let Some(audit) = report.audit.as_mut() {
3134 audit.not_compared += built[index..]
3135 .iter()
3136 .filter(|(_, _, _, t)| t.is_some())
3137 .count();
3138 }
3139 report.interrupted = true;
3140 break;
3141 }
3142 let cached = source_checkpoint
3143 .as_ref()
3144 .map(|phase| phase.get::<Option<Outcome>>(index))
3145 .transpose()?
3146 .flatten();
3147 let left_out = left_out
3148 .entry(&file.path)
3149 .or_insert_with(|| built_sources.left_out(file))
3150 .iter()
3151 .any(|(from, to)| *from <= site.start && site.end <= *to);
3152 if left_out || !built_sources.contains(file) {
3153 if let Some(phase) = source_checkpoint.as_ref().filter(|_| cached.is_none())
3154 {
3155 phase.record(index, &Some(Outcome::Unable))?;
3156 }
3157 if twin.is_none() {
3158 report.mutants_not_evaluated += 1;
3159 report.mutants_not_compiled += 1;
3160 if skipped_targets.insert((&file.path, site.start, site.end)) {
3161 report.skipped.push(report::SkippedSite::new(
3162 report::location(&file.display, site),
3163 file.lines.position(&file.original, site.end),
3164 report::SkipReason::SourceNotBuilt,
3165 left_out.then(|| {
3166 "under a `cfg` that the features of this build turn off"
3167 .to_string()
3168 }),
3169 ));
3170 }
3171 } else if let Some(audit) = report.audit.as_mut() {
3172 audit.not_compared += 1;
3173 }
3174 progress.complete(progress::Outcome::Unable);
3175 continue;
3176 }
3177 let outcome = if let Some(cached) = cached {
3178 cached
3179 } else {
3180 let mutated = format!(
3181 "{}{}{}",
3182 &file.original[..mutant.start],
3183 mutant.replacement,
3184 &file.original[mutant.end..]
3185 );
3186 let attempt = || -> Result<Option<Outcome>> {
3188 state.write(
3189 &file.path,
3190 &instrumented(file, &mutated, root_mutant_suffix),
3191 )?;
3192 match source_build(&cargo_build()?) {
3193 SourceBuild::Built => run_source_tests(&by_speed).map(Some),
3194 SourceBuild::Refused => Ok(None),
3195 SourceBuild::Failed(why) => {
3198 session.note(&format!(
3199 "a build failed without the compiler refusing the code; its mutant is not evaluated: {why}"
3200 ));
3201 Ok(Some(Outcome::Unable))
3202 }
3203 }
3204 };
3205 let attempted = attempt();
3206 let rendered = file.rendered.as_ref().expect("rendered before building");
3208 state.write(
3209 &file.path,
3210 &instrumented(file, &rendered.text, &root_suffix),
3211 )?;
3212 let outcome = match attempted {
3213 Ok(outcome) => outcome,
3214 Err(err)
3215 if crate::interrupt::is_interrupted()
3216 || crate::interrupt::is_interrupted_err(&err) =>
3217 {
3218 report.mutants_not_evaluated += built[index..]
3219 .iter()
3220 .filter(|(_, _, _, t)| t.is_none())
3221 .count();
3222 if let Some(audit) = report.audit.as_mut() {
3223 audit.not_compared += built[index..]
3224 .iter()
3225 .filter(|(_, _, _, t)| t.is_some())
3226 .count();
3227 }
3228 report.interrupted = true;
3229 break;
3230 }
3231 Err(err) => return Err(err),
3232 };
3233 if let Some(phase) = &source_checkpoint
3236 && outcome != Some(Outcome::Unable)
3237 {
3238 phase.record(index, &outcome)?;
3239 }
3240 outcome
3241 };
3242 progress.complete(outcome.map_or(progress::Outcome::Unable, Into::into));
3243 if let Some(job) = twin {
3244 let as_probe = results[*job].survived.is_some();
3246 let Some(audit) = report.audit.as_mut() else {
3247 continue;
3248 };
3249 match audit_source_comparison(&results[*job], outcome) {
3252 Some(disagrees) => {
3253 audit.compared += 1;
3254 if disagrees {
3255 let verdict =
3256 |passes: bool| if passes { "passes" } else { "fails" };
3257 audit.source_disagreements.push(report::SourceDisagreement {
3258 at: report::location(&file.display, site),
3259 mutant: report::describe(site, mutation_of(site, mutant)),
3260 as_probe: verdict(as_probe).to_string(),
3261 built: verdict(!as_probe).to_string(),
3262 });
3263 }
3264 }
3265 None => audit.not_compared += 1,
3266 }
3267 continue;
3268 }
3269 match outcome {
3270 None => report.unviable_mutants += 1,
3271 Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
3272 Some(outcome) => {
3273 report.mutants_run += 1;
3274 if outcome != Outcome::Pass {
3275 report.mutants_killed += 1;
3276 *killed_by_loc
3277 .entry((
3278 file.display.clone(),
3279 site.line,
3280 site.column,
3281 "survivor",
3282 ))
3283 .or_insert(0) += 1;
3284 }
3285 report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
3286 report.mutants_survived += (outcome == Outcome::Pass) as usize;
3287 }
3288 }
3289 let survived = outcome == Some(Outcome::Pass);
3290 if survived {
3291 let at = report::location(&file.display, site);
3292 let removed = mutant.replacement.trim().is_empty();
3294 let text = match (&site.kind, removed) {
3295 (SiteKind::Field { .. }, true) => {
3296 format!("without the field `{}`", report::one_line(&site.text))
3297 }
3298 (
3299 SiteKind::LiteralSet {
3300 receiver, argument, ..
3301 },
3302 true,
3303 ) => format!(
3304 "without `{}` in `{}.contains({})`",
3305 report::one_line(&mutant.into),
3306 report::one_line(receiver),
3307 report::one_line(argument)
3308 ),
3309 _ => report::describe(site, mutation_of(site, mutant)),
3310 };
3311 match survivors.last_mut() {
3312 Some((last, texts)) if *last == at => texts.push(text),
3313 _ => survivors.push((at, vec![text])),
3314 }
3315 }
3316 }
3317 Ok(())
3318 },
3319 )?;
3320 if !report.interrupted
3321 && let Some(phase) = &source_checkpoint
3322 {
3323 phase.finish_if_complete()?;
3324 }
3325 for (at, survivors) in survivors {
3326 finding_run_survivors.push(survivors.len());
3327 report.findings.push(Finding::Survivor {
3328 at,
3329 survivors,
3330 witness: None,
3331 change_since: None,
3332 advice: None,
3333 });
3334 }
3335 }
3336
3337 if !report.interrupted
3339 && let Some(revision) = options
3340 .since
3341 .as_deref()
3342 .filter(|_| !options.list && options.shard.is_none())
3343 {
3344 let hunks = scope::hunks(&since_diff(&workspace, revision)?);
3345 let not_built_changes = std::cell::Cell::new(0usize);
3346 let changed: Vec<(&SourceFile, Vec<reverts::Change>)> = files
3347 .iter()
3348 .filter(|file| built_sources.contains(file) || !options.source_only && !options.rebuild)
3349 .filter_map(|file| {
3350 let relative = file
3351 .path
3352 .strip_prefix(©)
3353 .ok()?
3354 .to_string_lossy()
3355 .replace('\\', "/");
3356 let of_file: Vec<_> = hunks
3357 .iter()
3358 .filter(|hunk| hunk.file == relative)
3359 .cloned()
3360 .collect();
3361 let mut changes = reverts::changes(&file.original, &of_file);
3362 if options.rebuild || options.source_only {
3365 for change in &mut changes {
3366 change.outside = change.undone.as_deref().is_some_and(|undone| {
3369 built_sources.same_program(file, &file.original, undone)
3370 });
3371 }
3372 not_built_changes.set(
3373 not_built_changes.get()
3374 + changes.iter().filter(|change| change.outside).count(),
3375 );
3376 }
3377 (!changes.is_empty()).then_some((file, changes))
3378 })
3379 .collect();
3380 let not_built_changes = not_built_changes.get();
3381 report.mutants_not_evaluated += not_built_changes;
3382 report.mutants_not_compiled += not_built_changes;
3383 let total: usize = changed
3385 .iter()
3386 .map(|(_, changes)| changes.iter().filter(|change| !change.outside).count())
3387 .sum();
3388 let mixed: usize = files
3391 .iter()
3392 .map(|file| {
3393 let relative = file
3394 .path
3395 .strip_prefix(©)
3396 .unwrap_or(&file.path)
3397 .to_string_lossy()
3398 .replace('\\', "/");
3399 let of_file: Vec<_> = hunks
3400 .iter()
3401 .filter(|hunk| hunk.file == relative)
3402 .cloned()
3403 .collect();
3404 reverts::mixed(&file.original, &of_file)
3405 })
3406 .sum();
3407 if mixed > 0 && (options.rebuild || options.source_only) {
3408 report.mutants_not_evaluated += mixed;
3409 session.note(&format!(
3410 "{mixed} changes are of the program and its tests in the same lines: they are not tried undone"
3411 ));
3412 }
3413 if !(options.rebuild || options.source_only) {
3414 report.mutants_not_built += not_built_reverts;
3415 } else if total > 0
3416 || changed.iter().any(|(_, changes)| {
3417 changes.iter().filter(|change| !change.is_subhunk()).count() > 1
3418 })
3419 {
3420 let reverts_result = (|| -> Result<()> {
3421 session.note(&format!(
3424 "building {total} changes undone, one by one (the code as it was at {})",
3425 report::short_revision(revision)
3426 ));
3427 let write = |file: &SourceFile, text: &str, suffix: &str| -> Result<()> {
3428 let suffix = if file.path == root_file { suffix } else { "" };
3429 state.write(&file.path, &format!("{text}{suffix}"))
3430 };
3431 let undone = |edits: &[(&SourceFile, &str)]| -> Result<Option<Outcome>> {
3433 let attempted = (|| -> Result<Option<Outcome>> {
3434 for (file, text) in edits {
3435 write(file, text, root_mutant_suffix)?;
3436 }
3437 Ok(match source_build(&cargo_build()?) {
3438 SourceBuild::Built => Some(run_source_tests(&by_speed)?),
3439 SourceBuild::Refused => None,
3440 SourceBuild::Failed(why) => {
3441 session.note(&format!(
3442 "a build failed without the compiler refusing the code; the change undone is not evaluated: {why}"
3443 ));
3444 Some(Outcome::Unable)
3445 }
3446 })
3447 })();
3448 for (file, _) in edits {
3450 let rendered = file.rendered.as_ref().expect("rendered before building");
3451 write(file, &rendered.text, &root_suffix)?;
3452 }
3453 attempted
3454 };
3455 let mut judged = |outcome: Option<Outcome>, at: report::Location, what: String| {
3456 match outcome {
3457 None => report.unviable_mutants += 1,
3458 Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
3459 Some(outcome) => {
3460 report.mutants_run += 1;
3461 report.mutants_killed += (outcome != Outcome::Pass) as usize;
3462 report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
3463 report.mutants_survived += (outcome == Outcome::Pass) as usize;
3464 }
3465 }
3466 if outcome == Some(Outcome::Pass) {
3467 finding_run_survivors.push(1);
3468 report.findings.push(Finding::Survivor {
3469 at,
3470 survivors: vec![what],
3471 witness: None,
3472 advice: None,
3473 change_since: Some(revision.to_string()),
3474 });
3475 }
3476 };
3477 let place = |file: &SourceFile, change: &reverts::Change| report::Location {
3478 file: file.display.clone(),
3479 line: change.line,
3480 column: 1,
3481 code: change.code.clone(),
3482 ..Default::default()
3483 };
3484 let mut stuck_files = 0;
3487 for (file, changes) in &changed {
3488 let mut stuck = false;
3489 let whole_total = changes.iter().filter(|change| !change.is_subhunk()).count();
3490 let whole_alone = changes
3491 .iter()
3492 .filter(|change| !change.is_subhunk() && !change.outside)
3493 .count();
3494 for change in changes.iter().filter(|change| !change.outside) {
3495 let outcome = match &change.undone {
3496 Some(text) => undone(&[(file, text.as_str())])?,
3497 None => None,
3498 };
3499 if !change.is_subhunk() {
3500 stuck |= outcome.is_none();
3501 }
3502 judged(outcome, place(file, change), change.describe());
3503 }
3504 let whole = reverts::all_undone(&file.original, changes);
3509 let same = |a: &str, b: &str| built_sources.same_program(file, a, b);
3510 let tried: Vec<reverts::Change> = changes
3511 .iter()
3512 .filter(|change| !change.outside)
3513 .cloned()
3514 .collect();
3515 let left_out_matter = whole_alone < whole_total
3516 && match (&whole, reverts::all_undone(&file.original, &tried)) {
3517 (Some(all), Some(without)) => !same(all, &without),
3518 _ => true,
3519 };
3520 let another = whole
3522 .as_deref()
3523 .is_none_or(|all| !same(all, &file.original));
3524 if whole_total > 1 && another && (stuck || left_out_matter) {
3525 let outcome = match &whole {
3526 Some(text) => undone(&[(file, text.as_str())])?,
3527 None => None,
3528 };
3529 stuck = outcome.is_none();
3530 let first_whole = changes
3531 .iter()
3532 .find(|change| !change.is_subhunk())
3533 .unwrap_or(&changes[0]);
3534 judged(
3535 outcome,
3536 place(file, first_whole),
3537 format!("with all {whole_total} changes to this file undone"),
3538 );
3539 }
3540 stuck_files += usize::from(stuck);
3541 }
3542 let with_left_out = changed.iter().any(|(_, changes)| {
3546 changes
3547 .iter()
3548 .any(|change| !change.is_subhunk() && change.outside)
3549 });
3550 if (stuck_files > 0 || with_left_out) && changed.len() > 1 {
3551 let whole: Option<Vec<String>> = changed
3552 .iter()
3553 .map(|(file, changes)| reverts::all_undone(&file.original, changes))
3554 .collect();
3555 let same = |file: &SourceFile, a: &str, b: &str| {
3556 built_sources.same_program(file, a, b)
3557 };
3558 let another = whole.as_ref().is_none_or(|texts| {
3560 changed
3561 .iter()
3562 .zip(texts)
3563 .any(|((file, _), text)| !same(file, text, &file.original))
3564 });
3565 let left_out_matter = whole.as_ref().is_none_or(|texts| {
3568 changed.iter().zip(texts).any(|((file, changes), text)| {
3569 let tried: Vec<reverts::Change> = changes
3570 .iter()
3571 .filter(|change| !change.outside)
3572 .cloned()
3573 .collect();
3574 reverts::all_undone(&file.original, &tried)
3575 .is_none_or(|without| !same(file, text, &without))
3576 })
3577 });
3578 if another && (stuck_files > 0 || (with_left_out && left_out_matter)) {
3579 let outcome = match &whole {
3580 Some(texts) => {
3581 let edits: Vec<(&SourceFile, &str)> = changed
3582 .iter()
3583 .zip(texts)
3584 .map(|((file, _), text)| (*file, text.as_str()))
3585 .collect();
3586 undone(&edits)?
3587 }
3588 None => None,
3589 };
3590 let (file, changes) = &changed[0];
3591 judged(
3592 outcome,
3593 place(file, &changes[0]),
3594 format!("with every change undone, in all {} files", changed.len()),
3595 );
3596 }
3597 }
3598 Ok(())
3599 })();
3600 match reverts_result {
3601 Ok(()) => {}
3602 Err(err)
3603 if crate::interrupt::is_interrupted()
3604 || crate::interrupt::is_interrupted_err(&err) =>
3605 {
3606 report.interrupted = true;
3607 }
3608 Err(err) => return Err(err),
3609 }
3610 }
3611 }
3612
3613 let mut witness_files: Vec<&PathBuf> = vec![];
3616 for candidate in &witness_candidates {
3617 if !witness_files.contains(&&candidate.file) {
3618 witness_files.push(&candidate.file);
3619 }
3620 }
3621 let witness_result = (|| -> Result<()> {
3622 for (file_idx, witness_file) in witness_files.iter().enumerate() {
3623 if report.interrupted || crate::interrupt::is_interrupted() {
3624 report.interrupted = true;
3625 for remaining_file in &witness_files[file_idx..] {
3626 report.mutants_not_evaluated += witness_candidates
3627 .iter()
3628 .filter(|candidate| {
3629 candidate.file == **remaining_file && !candidate.existing
3630 })
3631 .count();
3632 }
3633 break;
3634 }
3635 let in_root = **witness_file == root_file;
3636 let file = files
3637 .iter()
3638 .find(|file| file.path == **witness_file)
3639 .expect("witness candidates are of files that are analysed");
3640 let rendered = file.rendered.as_ref().expect("rendered before building");
3641 let left_out_here = built_sources.left_out(file);
3642 let restore = if in_root {
3643 format!("{}{root_suffix}", rendered.text)
3644 } else {
3645 rendered.text.clone()
3646 };
3647 let library_runners: Vec<_> = session
3648 .binaries
3649 .iter()
3650 .filter(|bin| {
3651 root_exe
3652 .as_deref()
3653 .is_some_and(|exe| bin.runner.executable() == Some(exe))
3654 })
3655 .collect();
3656 let ignored = match library_runners
3657 .iter()
3658 .find_map(|bin| match &bin.runner {
3659 Runner::Exe(exe) => Some(list_tests(
3660 exe,
3661 &bin.cwd,
3662 &bin.git_ceiling,
3663 true,
3664 false,
3665 bin.work_lock.as_deref(),
3666 )),
3667 _ => None,
3668 })
3669 .transpose()
3670 {
3671 Ok(ignored) => ignored.unwrap_or_default(),
3672 Err(err)
3673 if crate::interrupt::is_interrupted()
3674 || crate::interrupt::is_interrupted_err(&err) =>
3675 {
3676 report.interrupted = true;
3677 for remaining_file in &witness_files[file_idx..] {
3678 report.mutants_not_evaluated += witness_candidates
3679 .iter()
3680 .filter(|candidate| {
3681 candidate.file == **remaining_file && !candidate.existing
3682 })
3683 .count();
3684 }
3685 break;
3686 }
3687 Err(err) => return Err(err),
3688 };
3689 let witness_candidates: Vec<&witness::Candidate> = witness_candidates
3690 .iter()
3691 .filter(|candidate| candidate.file == **witness_file)
3692 .collect();
3693 let runner_for = |scenario: &witness::Scenario| {
3694 library_runners.iter().copied().find(|bin| {
3695 scenario
3696 .source_test
3697 .as_ref()
3698 .is_none_or(|required| match &bin.runner {
3699 Runner::Exe(_) if !in_root => {
3702 let inner = format!("::{required}");
3703 bin.tests
3704 .iter()
3705 .any(|test| test.ends_with(&inner) && !ignored.contains(test))
3706 }
3707 Runner::Exe(_) => {
3708 bin.tests.contains(required) && !ignored.contains(required)
3709 }
3710 Runner::Isolated { test, .. } if !in_root => {
3711 test.ends_with(&format!("::{required}"))
3712 }
3713 Runner::Isolated { test, .. } => test == required,
3714 Runner::Doc { .. } | Runner::Nextest { .. } => false,
3715 })
3716 })
3717 };
3718 let write_edits = |edits: &[witness::Edit]| -> Result<bool> {
3719 let Some(source) = witness::render_edits(&file.original, edits, None) else {
3720 return Ok(false);
3721 };
3722 let suffix = if in_root { root_mutant_suffix } else { "" };
3723 state.write(&file.path, &format!("{source}{suffix}"))?;
3724 Ok(true)
3725 };
3726 let suite = |edits: &[witness::Edit]| -> Result<Option<Outcome>> {
3727 if !write_edits(edits)? {
3728 return Ok(None);
3729 }
3730 Ok(match source_build(&cargo_build()?) {
3731 SourceBuild::Built => Some(run_source_tests(&by_speed)?),
3732 SourceBuild::Refused => None,
3733 SourceBuild::Failed(why) => {
3734 session.note(&format!(
3735 "a build failed without the compiler refusing the code; the mutant is not evaluated: {why}"
3736 ));
3737 Some(Outcome::Unable)
3738 }
3739 })
3740 };
3741 let compile_observer = |edits: &[witness::Edit]| -> Result<Option<PathBuf>> {
3742 if !write_edits(edits)? {
3743 return Ok(None);
3744 }
3745 let build = build_test_binaries(true)?;
3746 if !build.status.success() {
3747 return Ok(None);
3748 }
3749 let artifacts = parse_build_output(
3750 &String::from_utf8_lossy(&build.stdout),
3751 &[package.name.as_str()],
3752 );
3753 Ok(root_test_exe(&artifacts))
3754 };
3755 let observe = |scenario: &witness::Scenario,
3756 baseline: &TestBinary,
3757 edits: &[witness::Edit],
3758 field_path: Option<&str>,
3759 expected: Option<&str>|
3760 -> Result<Option<witness::Observation>> {
3761 let test = scenario.test_edit_with_field(
3762 &file.original,
3763 witness::TEST_NAME,
3764 field_path,
3765 expected,
3766 );
3767 let edits: Vec<_> = edits.iter().cloned().chain([test]).collect();
3768 let Some(exe) = compile_observer(&edits)? else {
3769 return Ok(None);
3770 };
3771 observe_witness(
3772 baseline,
3773 exe,
3774 wrapper.as_deref(),
3775 scenario,
3776 witness::TEST_NAME,
3777 expected.is_some(),
3778 in_root,
3779 )
3780 };
3781 let witness_checkpoint = if checkpoint.is_some() {
3782 let keys = witness_candidates
3783 .iter()
3784 .map(|candidate| {
3785 let edits = candidate
3786 .edits
3787 .iter()
3788 .map(|edit| (&edit.span, &edit.replacement))
3789 .collect::<Vec<_>>();
3790 serde_json::to_string(&(&candidate.description, edits))
3791 })
3792 .collect::<std::result::Result<Vec<_>, _>>()?;
3793 let name = if in_root {
3794 "witness".to_string()
3795 } else {
3796 format!("witness:{}", file.display)
3797 };
3798 phase(&name, keys)?
3799 } else {
3800 None
3801 };
3802 let mut survivors = vec![];
3803 let mut claimed = BTreeSet::new();
3804 let mut witness_loop_interrupted = false;
3805 progress::track(
3806 options.progress,
3807 "source witness mutants",
3808 witness_candidates.len(),
3809 |progress| -> Result<()> {
3810 for (index, candidate) in witness_candidates.iter().copied().enumerate() {
3811 if crate::interrupt::is_interrupted() {
3812 report.mutants_not_evaluated += witness_candidates[index..]
3813 .iter()
3814 .filter(|c| !c.existing)
3815 .count();
3816 report.interrupted = true;
3817 witness_loop_interrupted = true;
3818 break;
3819 }
3820 let cached = witness_checkpoint
3821 .as_ref()
3822 .map(|phase| phase.get::<WitnessTrial>(index))
3823 .transpose()?
3824 .flatten();
3825 let at = witness_location(file, candidate);
3826 if !built_sources.contains(file)
3828 || candidate.edits.iter().any(|edit| {
3829 left_out_here.iter().any(|(from, to)| {
3830 *from <= edit.span.start && edit.span.end <= *to
3831 })
3832 })
3833 {
3834 if let Some(phase) =
3835 witness_checkpoint.as_ref().filter(|_| cached.is_none())
3836 {
3837 phase.record(index, &WitnessTrial::Inapplicable)?;
3838 }
3839 if !candidate.existing {
3840 report.mutants_not_evaluated += 1;
3841 report.mutants_not_compiled += 1;
3842 let span = &candidate.edits[0].span;
3843 report.skipped.push(report::SkippedSite::new(
3844 at,
3845 file.lines.position(&file.original, span.end),
3846 report::SkipReason::SourceNotBuilt,
3847 Some(
3848 "under a `cfg` that the features of this build turn off"
3849 .to_string(),
3850 ),
3851 ));
3852 }
3853 progress.complete(progress::Outcome::Unable);
3854 continue;
3855 }
3856 let existing = candidate
3857 .existing
3858 .then(|| {
3859 report.findings.iter().position(|finding| {
3860 let location = finding.at();
3861 location.file == at.file
3862 && location.line == at.line
3863 && location.column == at.column
3864 && finding.survivors().contains(&candidate.description)
3865 && (candidate.finding_at.is_none()
3866 || !matches!(finding, Finding::InputGap { .. }))
3867 })
3868 })
3869 .flatten();
3870 let existing = existing.filter(|index| {
3874 candidate.finding_at.is_none() || !claimed.contains(index)
3875 });
3876 let scenarios: Vec<_> = candidate
3877 .scenarios
3878 .iter()
3879 .filter_map(|scenario| {
3880 runner_for(scenario).map(|runner| (scenario, runner))
3881 })
3882 .take(4)
3883 .collect();
3884 let paired = candidate.edits.len() > 1;
3885 if (candidate.existing && (existing.is_none() || scenarios.is_empty()))
3886 || (paired && scenarios.is_empty())
3887 {
3888 if let Some(phase) =
3889 witness_checkpoint.as_ref().filter(|_| cached.is_none())
3890 {
3891 phase.record(index, &WitnessTrial::Inapplicable)?;
3892 }
3893 progress.complete(progress::Outcome::Unable);
3894 continue;
3895 }
3896 let trial = if let Some(cached) = cached {
3899 cached
3900 } else {
3901 let attempted = (|| -> Result<WitnessTrial> {
3902 if paired {
3903 for edit in &candidate.edits {
3904 match suite(std::slice::from_ref(edit))? {
3905 Some(Outcome::Fail) => {}
3906 Some(Outcome::Unable) => {
3907 return Ok(WitnessTrial::Evaluated(
3908 Outcome::Unable,
3909 ));
3910 }
3911 _ => return Ok(WitnessTrial::Inapplicable),
3912 }
3913 }
3914 }
3915 Ok(suite(&candidate.edits)?
3916 .map_or(WitnessTrial::Unviable, WitnessTrial::Evaluated))
3917 })();
3918 state.write(&file.path, &restore)?;
3919 let trial = match attempted {
3920 Ok(trial) => trial,
3921 Err(err)
3922 if crate::interrupt::is_interrupted()
3923 || crate::interrupt::is_interrupted_err(&err) =>
3924 {
3925 report.mutants_not_evaluated += witness_candidates[index..]
3926 .iter()
3927 .filter(|c| !c.existing)
3928 .count();
3929 report.interrupted = true;
3930 witness_loop_interrupted = true;
3931 break;
3932 }
3933 Err(err) => return Err(err),
3934 };
3935 if let Some(phase) = &witness_checkpoint
3936 && !matches!(trial, WitnessTrial::Evaluated(Outcome::Unable))
3937 {
3938 phase.record(index, &trial)?;
3939 }
3940 trial
3941 };
3942 let outcome = match trial {
3943 WitnessTrial::Inapplicable => {
3944 progress.complete(progress::Outcome::Unable);
3945 continue;
3946 }
3947 WitnessTrial::Unviable => {
3948 progress.complete(progress::Outcome::Unable);
3949 report.unviable_mutants += usize::from(!candidate.existing);
3950 continue;
3951 }
3952 WitnessTrial::Evaluated(outcome) => outcome,
3953 };
3954 progress.complete(outcome.into());
3955 if !candidate.existing {
3956 match outcome {
3957 Outcome::Unable => report.mutants_not_evaluated += 1,
3958 Outcome::Pass => {
3959 report.mutants_run += 1;
3960 report.mutants_survived += 1;
3961 }
3962 Outcome::Fail => {
3963 report.mutants_run += 1;
3964 report.mutants_killed += 1;
3965 }
3966 Outcome::Timeout => {
3967 report.mutants_run += 1;
3968 report.mutants_killed += 1;
3969 report.mutants_timed_out += 1;
3970 }
3971 }
3972 }
3973 if outcome == Outcome::Pass {
3974 survivors.push(WitnessSurvivor {
3975 candidate,
3976 at,
3977 existing,
3978 scenarios,
3979 });
3980 }
3981 }
3982 Ok(())
3983 },
3984 )?;
3985
3986 if !witness_loop_interrupted
3987 && !crate::interrupt::is_interrupted()
3988 && let Some(phase) = &witness_checkpoint
3989 {
3990 phase.finish_if_complete()?;
3991 }
3992 let record_unwitnessed_survivors =
3993 |survivors: Vec<WitnessSurvivor<'_>>,
3994 report: &mut Report,
3995 finding_run_survivors: &mut Vec<usize>| {
3996 for survivor in survivors {
3997 if survivor.existing.is_none() {
3998 finding_run_survivors.push(1);
3999 report.findings.push(Finding::Survivor {
4000 at: survivor.at,
4001 survivors: vec![survivor.candidate.description.clone()],
4002 advice: survivor.candidate.advice.clone(),
4003 witness: None,
4004 change_since: None,
4005 });
4006 }
4007 }
4008 };
4009 if witness_loop_interrupted || crate::interrupt::is_interrupted() {
4010 report.interrupted = true;
4011 record_unwitnessed_survivors(survivors, &mut report, &mut finding_run_survivors);
4012 continue;
4013 }
4014 let originals = shared_witnesses(
4015 &file.original,
4016 &survivors,
4017 wrapper.as_deref(),
4018 in_root,
4019 compile_observer,
4020 note,
4021 );
4022 if !survivors.is_empty() {
4023 state.write(&file.path, &restore)?;
4024 }
4025 let originals = match originals {
4026 Ok(originals) => originals,
4027 Err(err)
4028 if crate::interrupt::is_interrupted()
4029 || crate::interrupt::is_interrupted_err(&err) =>
4030 {
4031 report.interrupted = true;
4032 record_unwitnessed_survivors(
4033 survivors,
4034 &mut report,
4035 &mut finding_run_survivors,
4036 );
4037 continue;
4038 }
4039 Err(err) => return Err(err),
4040 };
4041
4042 progress::track(
4043 options.progress,
4044 "distinguishing tests",
4045 survivors.len(),
4046 |progress| -> Result<()> {
4047 for (survivor, original) in survivors.into_iter().zip(originals) {
4048 if report.interrupted || crate::interrupt::is_interrupted() {
4049 report.interrupted = true;
4050 if survivor.existing.is_none() {
4051 finding_run_survivors.push(1);
4052 report.findings.push(Finding::Survivor {
4053 at: survivor.at,
4054 survivors: vec![survivor.candidate.description.clone()],
4055 advice: survivor.candidate.advice.clone(),
4056 witness: None,
4057 change_since: None,
4058 });
4059 }
4060 continue;
4061 }
4062 if survivor.existing.is_some_and(|index| {
4063 survivor.candidate.finding_at.is_some() && claimed.contains(&index)
4064 }) {
4065 progress.complete(progress::Outcome::Unable);
4066 continue;
4067 }
4068 let mut evidence = None;
4069 let mut original = original;
4070 for (scenario, baseline) in survivor.scenarios {
4071 if report.interrupted || crate::interrupt::is_interrupted() {
4072 report.interrupted = true;
4073 break;
4074 }
4075 let shared = original.take();
4076 let distinction = (|| -> Result<_> {
4077 if let Some(shared) = shared {
4078 let edits: Vec<_> = survivor
4080 .candidate
4081 .edits
4082 .iter()
4083 .chain(shared.tests.iter())
4084 .cloned()
4085 .collect();
4086 if let Some(exe) = compile_observer(&edits)? {
4087 let mutant = match observe_witness(
4088 baseline,
4089 exe,
4090 wrapper.as_deref(),
4091 scenario,
4092 &shared.name,
4093 true,
4094 in_root,
4095 ) {
4096 Ok(obs) => obs,
4097 Err(err)
4098 if crate::interrupt::is_interrupted()
4099 || crate::interrupt::is_interrupted_err(
4100 &err,
4101 ) =>
4102 {
4103 return Err(err);
4104 }
4105 Err(_) => None,
4106 };
4107 if let Some(mutant) = mutant
4108 && mutant.equals_expected == Some(false)
4109 {
4110 let rechecked = match observe_witness(
4113 baseline,
4114 shared.original_exe.path.clone(),
4115 wrapper.as_deref(),
4116 scenario,
4117 &shared.name,
4118 true,
4119 in_root,
4120 ) {
4121 Ok(obs) => obs,
4122 Err(err)
4123 if crate::interrupt::is_interrupted()
4124 || crate::interrupt::is_interrupted_err(
4125 &err,
4126 ) =>
4127 {
4128 return Err(err);
4129 }
4130 Err(_) => None,
4131 };
4132 if rechecked.is_some_and(|rechecked| {
4133 rechecked.equals_expected == Some(true)
4134 && rechecked.value == shared.value
4135 }) && let Some(verified) =
4136 scenario.verified(shared.value, mutant.value)
4137 {
4138 return Ok(Some(verified));
4139 }
4140 }
4141 }
4142 }
4145 let Some(original) = observe(scenario, baseline, &[], None, None)?
4146 else {
4147 return Ok(None);
4148 };
4149 let value = original.value;
4150 if witness::is_expected_literal(&value) {
4151 let Some(mutant) = observe(
4152 scenario,
4153 baseline,
4154 &survivor.candidate.edits,
4155 None,
4156 Some(&value),
4157 )?
4158 else {
4159 return Ok(None);
4160 };
4161 if mutant.equals_expected != Some(false)
4162 || value == mutant.value
4163 {
4164 return Ok(None);
4165 }
4166 let Some(checked) =
4167 observe(scenario, baseline, &[], None, Some(&value))?
4168 else {
4169 return Ok(None);
4170 };
4171 if checked.equals_expected != Some(true)
4172 || checked.value != value
4173 {
4174 return Ok(None);
4175 }
4176 return Ok(scenario.verified(value, mutant.value));
4177 }
4178 if witness::parse_debug_struct(&value).is_none() {
4181 return Ok(None);
4182 }
4183 let Some(raw_mutant) = observe(
4184 scenario,
4185 baseline,
4186 &survivor.candidate.edits,
4187 None,
4188 None,
4189 )?
4190 else {
4191 return Ok(None);
4192 };
4193 let Some((path, field_orig, _)) =
4194 witness::narrow_struct_field(&value, &raw_mutant.value)
4195 else {
4196 return Ok(None);
4197 };
4198 if !witness::is_expected_literal(&field_orig) {
4199 return Ok(None);
4200 }
4201 let field_path = path.join(".");
4202 let Some(mutant) = observe(
4203 scenario,
4204 baseline,
4205 &survivor.candidate.edits,
4206 Some(&field_path),
4207 Some(&field_orig),
4208 )?
4209 else {
4210 return Ok(None);
4211 };
4212 if mutant.equals_expected != Some(false)
4213 || mutant.value != raw_mutant.value
4214 || value == mutant.value
4215 {
4216 return Ok(None);
4217 }
4218 let Some(checked) = observe(
4219 scenario,
4220 baseline,
4221 &[],
4222 Some(&field_path),
4223 Some(&field_orig),
4224 )?
4225 else {
4226 return Ok(None);
4227 };
4228 if checked.equals_expected != Some(true) || checked.value != value {
4229 return Ok(None);
4230 }
4231 Ok(scenario.verified_field(
4232 value,
4233 mutant.value,
4234 field_path,
4235 field_orig,
4236 ))
4237 })();
4238 match distinction {
4239 Ok(Some(mut verified)) => {
4240 let edits = survivor.candidate.edits.len();
4241 verified.individually_killed = (edits > 1).then_some(edits);
4242 evidence = Some(verified);
4243 break;
4244 }
4245 Ok(None) => {}
4246 Err(err)
4247 if crate::interrupt::is_interrupted()
4248 || crate::interrupt::is_interrupted_err(&err) =>
4249 {
4250 report.interrupted = true;
4251 break;
4252 }
4253 Err(err) => note(&format!(
4254 "could not check a distinguishing test for {}: {err:#}",
4255 scenario.expression,
4256 )),
4257 }
4258 }
4259 state.write(&file.path, &restore)?;
4260 progress.complete(Outcome::Pass.into());
4261 if let Some(index) = survivor.existing {
4262 if let Some(evidence) = evidence {
4263 report.findings[index].set_witness(evidence);
4264 if survivor.candidate.finding_at.is_some() {
4265 claimed.insert(index);
4266 }
4267 }
4268 } else {
4269 finding_run_survivors.push(1);
4270 report.findings.push(Finding::Survivor {
4271 at: survivor.at,
4272 survivors: vec![survivor.candidate.description.clone()],
4273 advice: survivor
4274 .candidate
4275 .advice
4276 .clone()
4277 .filter(|_| evidence.is_none()),
4278 witness: evidence,
4279 change_since: None,
4280 });
4281 }
4282 }
4283 Ok(())
4284 },
4285 )?;
4286 }
4287 Ok(())
4288 })();
4289 match witness_result {
4290 Ok(()) => {}
4291 Err(err)
4292 if crate::interrupt::is_interrupted() || crate::interrupt::is_interrupted_err(&err) =>
4293 {
4294 report.interrupted = true;
4295 }
4296 Err(err) => return Err(err),
4297 }
4298
4299 if crate::interrupt::is_interrupted() {
4300 report.interrupted = true;
4301 }
4302 report.record_evaluation();
4303 debug_assert_eq!(report.findings.len(), finding_run_survivors.len());
4304 let mut paired_findings: Vec<(Finding, usize)> = report
4305 .findings
4306 .into_iter()
4307 .zip(finding_run_survivors)
4308 .collect();
4309 paired_findings.sort_by(|(a, _), (b, _)| {
4310 let (a, b) = (a.at(), b.at());
4311 (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column))
4312 });
4313 let (sorted_findings, finding_run_survivors): (Vec<_>, Vec<_>) =
4314 paired_findings.into_iter().unzip();
4315 report.findings = sorted_findings;
4316 let places: Vec<FilePlaces> = files
4317 .iter()
4318 .map(|file| FilePlaces {
4319 display: &file.display,
4320 source: &file.original,
4321 lines: &file.lines,
4322 places: &file.places,
4323 })
4324 .collect();
4325 name_findings(&mut report.findings, &places);
4326
4327 let partial_scope = is_partial_scope.then(|| crate::baseline::PartialScope {
4329 scope: scope.as_ref(),
4330 exclude_files: &options.exclude_files,
4331 preserve_all_existing: options.shard.is_some(),
4332 });
4333 let write_ctx = BaselineWriteContext {
4334 ws_package_prefix: &ws_package_prefix,
4335 partial_scope: partial_scope.as_ref(),
4336 single_package_run: batch.is_none(),
4337 note: ¬e,
4338 };
4339 apply_suppressions_and_finish(
4340 options,
4341 &files,
4342 &mut report,
4343 &finding_run_survivors,
4344 &killed_by_loc,
4345 checkpoint.as_ref(),
4346 &write_ctx,
4347 )?;
4348 report.wrapper_grace_outcomes = wrapper_grace_counter.as_ref().map(|c| c.snapshot());
4349 debug_assert!(
4350 report.counts_reconcile(),
4351 "report counts do not reconcile: {report:#?}"
4352 );
4353 Ok(report)
4354}
4355
4356fn validate_package_options(options: &Options) -> Result<Vec<&str>> {
4357 if let Some(shard) = options.shard
4358 && (!options.source_only || shard.index >= shard.count)
4359 {
4360 bail!("shards require --source-only and a valid shard index");
4361 }
4362 let mut seen_errors = HashSet::new();
4363 let mut error_values = vec![];
4364 for expression in &options.error_values {
4365 let expression = expression.trim();
4366 if expression.chars().any(char::is_control) {
4369 bail!(
4370 "invalid --error expression {expression:?}: it has to be on one line, \
4371 without control characters"
4372 );
4373 }
4374 let parsed = syn::parse_str::<syn::Expr>(expression)
4375 .with_context(|| format!("invalid --error expression {expression:?}"))?;
4376 if seen_errors.insert(quote::ToTokens::to_token_stream(&parsed).to_string()) {
4377 error_values.push(expression);
4378 }
4379 }
4380 let selection = &options.test_selection;
4381 if options.nextest.is_some() {
4382 if !cfg!(unix) {
4383 bail!("the nextest runner is available on Unix");
4384 }
4385 if !options.source_only || options.doc || selection.enabled() {
4386 bail!(
4387 "--test-tool nextest requires --source-only; select tests through the nextest profile"
4388 );
4389 }
4390 }
4391 if options.baseline_jobs > 1 && !selection.enabled() {
4392 bail!("--baseline-jobs requires isolated tests or a test wrapper or selection");
4393 }
4394 if options.doc && selection.enabled() {
4395 bail!("--doc cannot be combined with isolated test selection");
4396 }
4397 if options.source_only && options.jobs > 1 {
4398 eprintln!(
4399 "tmt: warning: --source-only runs mutants serially in one working copy; ignoring --jobs {}",
4400 options.jobs
4401 );
4402 }
4403 Ok(error_values)
4404}
4405
4406struct PreparedWorkCopy {
4407 workspace: PathBuf,
4408 work: PathBuf,
4409 work_lock: Option<Arc<WorkLock>>,
4410 copy: PathBuf,
4411 state: WorkCopy,
4412 external_deps: BTreeSet<PathBuf>,
4413}
4414
4415fn prepare_work_copy(
4416 options: &Options,
4417 metadata: &Metadata,
4418 batch: Option<&WorkspaceBatch<'_>>,
4419 catalogue: Option<&CatalogueSnapshot>,
4420 note: &impl Fn(&str),
4421) -> Result<PreparedWorkCopy> {
4422 let workspace = metadata.workspace_root.canonicalize()?;
4423 let requested_work = catalogue
4424 .map(|catalogue| &catalogue.path)
4425 .or(options.work_dir.as_ref());
4426 let work = match requested_work {
4427 Some(dir) => {
4428 fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
4429 dir.canonicalize()?
4430 }
4431 None => metadata.target_directory.join("tmt"),
4432 };
4433 if workspace.starts_with(&work) {
4436 bail!(
4437 "the work directory {} contains the workspace; choose a directory of its own",
4438 work.display()
4439 );
4440 }
4441 fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?;
4442 let work = work.canonicalize()?;
4443 let work_lock = if catalogue.is_none() {
4444 Some(Arc::new(WorkLock::take(&work)?))
4445 } else {
4446 None
4447 };
4448 let stage_root = work.join("src");
4449 let copy_subdir = staged_copy_subdir(&workspace, &options.stage_external)?;
4450 let copy = if copy_subdir.as_os_str().is_empty() {
4451 stage_root.clone()
4452 } else {
4453 stage_root.join(©_subdir)
4454 };
4455 let marker = work.join(WORK_MARKER);
4456 if stage_root.exists() && !marker.exists() {
4457 bail!(
4458 "{} exists and was not created by tmt; refusing to delete it. \
4459 Choose another --work-dir or remove it yourself.",
4460 stage_root.display()
4461 );
4462 }
4463 fs::write(
4464 &marker,
4465 "Working directory of tmt (targeted-mutation). Safe to delete.\n",
4466 )?;
4467 let target_dir = metadata.target_directory.clone();
4468 let forbidden = |path: &Path| {
4469 path == target_dir
4470 || path == work
4471 || batch.is_some_and(|batch| path == batch.work)
4472 || path.file_name().is_some_and(|n| n == ".git")
4473 || (path.parent() == Some(workspace.as_path())
4474 && path.file_name().is_some_and(|n| n == "target"))
4475 };
4476 let state = WorkCopy::open_with_copy_root(&work, &stage_root, ©);
4477 let fixtures = options
4478 .copy_fixtures
4479 .iter()
4480 .map(|path| fixture_relative(path))
4481 .collect::<Result<Vec<_>>>()?;
4482 let excluded = fixture_exclusions(&workspace, &fixtures, &options.copy_fixture_excludes)?;
4483 let fixture_forbidden = |path: &Path| forbidden(path) || excluded.contains(path);
4484 let skip = |path: &Path| {
4485 fixture_forbidden(path) || path.file_name().is_some_and(|n| n == "node_modules")
4486 };
4487 if options.progress && !options.list {
4488 for path in &excluded {
4489 note(&format!(
4490 "excluded fixture {}",
4491 path.strip_prefix(&workspace).unwrap_or(path).display()
4492 ));
4493 }
4494 }
4495 if catalogue.is_none_or(|catalogue| !catalogue.ready.get()) {
4496 work_directory(&work, "src")?;
4497 real_dir(©, &state)?;
4498 if copy != stage_root {
4499 for ancestor in copy.ancestors() {
4500 if ancestor == stage_root || !ancestor.starts_with(&stage_root) {
4501 break;
4502 }
4503 state.kept.borrow_mut().insert(ancestor.to_path_buf());
4504 }
4505 }
4506 let visible = if options.all_files {
4507 None
4508 } else {
4509 git_visible_files(&workspace)?
4510 };
4511 match visible {
4512 Some(files) => {
4515 let copied = copy_git_visible(&workspace, ©, files, &workspace, &skip, &state)?;
4516 note(&format!(
4517 "copied {copied} files (ignored files are left out)"
4518 ));
4519 }
4520 None => copy_tree(&workspace, ©, &workspace, &skip, &state)?,
4521 }
4522 for relative in &fixtures {
4523 copy_fixture_entry(
4524 &workspace.join(relative),
4525 ©.join(relative),
4526 &workspace,
4527 &fixture_forbidden,
4528 &state,
4529 &mut BTreeSet::new(),
4530 )?;
4531 }
4532 let mut staged_destinations: Vec<PathBuf> = Vec::new();
4533 let mut folded_ancestors: BTreeMap<String, PathBuf> = BTreeMap::new();
4534 for entry in &options.stage_external {
4535 let (rel, _) = parse_external_rel(&entry.rel)?;
4536 let dst = normalize(©.join(&rel));
4537 let copy_rel_in_stage = copy.strip_prefix(&stage_root).unwrap_or(©);
4538 let dst_rel_in_stage = dst.strip_prefix(&stage_root).unwrap_or(&dst);
4539 if !dst.starts_with(&stage_root)
4540 || dst == stage_root
4541 || copy.starts_with(&dst)
4542 || dst.starts_with(©)
4543 || paths_overlap_case_insensitive(copy_rel_in_stage, dst_rel_in_stage)
4544 || staged_destinations.iter().any(|prev| {
4545 let prev_rel = prev.strip_prefix(&stage_root).unwrap_or(prev);
4546 paths_overlap_case_insensitive(prev_rel, dst_rel_in_stage)
4547 })
4548 {
4549 bail!(
4550 "--stage-external destination collides with the workspace copy or another staged path: {}",
4551 entry.rel.display()
4552 );
4553 }
4554 for ancestor in dst_rel_in_stage.ancestors() {
4555 if ancestor.as_os_str().is_empty() {
4556 continue;
4557 }
4558 let folded = ancestor.to_string_lossy().to_lowercase();
4559 if let Some(previous) = folded_ancestors.get(&folded)
4560 && previous != ancestor
4561 {
4562 bail!(
4563 "--stage-external destinations differ only by case: {} and {}",
4564 previous.display(),
4565 ancestor.display()
4566 );
4567 }
4568 folded_ancestors.insert(folded, ancestor.to_path_buf());
4569 }
4570 staged_destinations.push(dst.clone());
4571 let src = if entry.from.is_absolute() {
4572 entry.from.clone()
4573 } else {
4574 workspace.join(&entry.from)
4575 };
4576 copy_external_entry(
4577 &src,
4578 &dst,
4579 None,
4580 &work,
4581 &forbidden,
4582 &state,
4583 &mut BTreeSet::new(),
4584 )?;
4585 }
4586 prune(&stage_root, &state)?;
4587 if options.git_index {
4588 git_index::snapshot(&workspace, ©)?;
4589 }
4590 let mut external_deps = BTreeSet::new();
4591 if !options.list {
4592 let mut manifests: Vec<&Path> = metadata
4594 .packages
4595 .iter()
4596 .map(|p| p.manifest_path.as_path())
4597 .collect();
4598 let root_manifest = metadata.workspace_root.join("Cargo.toml");
4599 manifests.push(&root_manifest);
4600 for manifest in manifests {
4601 let Ok(canonical) = manifest.canonicalize() else {
4602 continue;
4603 };
4604 let (Some(manifest_dir), Ok(relative)) =
4605 (canonical.parent(), canonical.strip_prefix(&workspace))
4606 else {
4607 continue;
4608 };
4609 let text = fs::read_to_string(&canonical)?;
4610 let (rewritten, externals) = absolutize_path_dependencies_with_externals(
4611 &text,
4612 manifest_dir,
4613 &workspace,
4614 ©,
4615 )?;
4616 external_deps.extend(externals);
4617 if let Some(rewritten) = rewritten {
4618 state.write(©.join(relative), &rewritten)?;
4619 }
4620 }
4621 }
4622 if let Some(catalogue) = catalogue {
4623 state.settle(&workspace)?;
4624 catalogue.ready.set(true);
4625 }
4626 return Ok(PreparedWorkCopy {
4627 workspace,
4628 work,
4629 work_lock,
4630 copy,
4631 state,
4632 external_deps,
4633 });
4634 }
4635 Ok(PreparedWorkCopy {
4636 workspace,
4637 work,
4638 work_lock,
4639 copy,
4640 state,
4641 external_deps: BTreeSet::new(),
4642 })
4643}
4644
4645#[allow(clippy::too_many_arguments)]
4646fn run_audit_phase<'a>(
4647 session: &Session,
4648 files: &[SourceFile],
4649 jobs: &[Job],
4650 results: &mut [JobResult],
4651 timeout_rechecks: &mut report::TimeoutRechecks,
4652 scratch: &Path,
4653 wanted: usize,
4654 workers: usize,
4655 probe_phase: &impl Fn(&str, &[Job]) -> Result<Option<Phase<'a>>>,
4656) -> Result<report::Audit> {
4657 let survivors: Vec<usize> = (0..jobs.len())
4658 .filter(|job| results[*job].survived.is_some())
4659 .collect();
4660 let chosen: Vec<usize> = spread(survivors.len(), wanted)
4661 .into_iter()
4662 .map(|nth| survivors[nth])
4663 .collect();
4664 session.note(&format!(
4665 "audit: running {} of {} surviving mutants against all tests",
4666 chosen.len(),
4667 survivors.len()
4668 ));
4669 let against_all: Vec<Job> = chosen
4670 .iter()
4671 .map(|job| Job {
4672 site: jobs[*job].site,
4673 mutation: jobs[*job].mutation,
4674 tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
4675 })
4676 .collect();
4677 let mut audit = report::Audit {
4678 sampled: chosen.len(),
4679 survivors: survivors.len(),
4680 ..report::Audit::default()
4681 };
4682 let audit_checkpoint = probe_phase("audit", &against_all)?;
4683 for (job, again) in chosen.iter().zip(session.run_jobs(
4684 &against_all,
4685 workers,
4686 "audit mutants",
4687 audit_checkpoint.as_ref(),
4688 )?) {
4689 timeout_rechecks.include(&again);
4690 if again.unable || again.unconfirmed_timeout {
4691 audit.not_audited += 1;
4692 } else if audit_all_tests_disagrees(&again) {
4693 results[*job] = again;
4695 let site = files
4696 .iter()
4697 .find_map(|f| Some((f, f.sites.iter().find(|s| s.id == jobs[*job].site)?)));
4698 if let Some((file, site)) = site {
4699 audit
4700 .disagreements
4701 .push(report::location(&file.display, site));
4702 }
4703 }
4704 }
4705 if crate::interrupt::is_interrupted() {
4706 audit.trace_rerun_incomplete = true;
4707 return Ok(audit);
4708 }
4709 session.note("audit: recording the tests once more");
4710 for (index, bin) in session.binaries.iter().enumerate() {
4711 if crate::interrupt::is_interrupted() {
4712 audit.trace_rerun_incomplete = true;
4713 break;
4714 }
4715 let path = scratch.join(format!("trace-{index}-audit.tsv"));
4716 let _ = fs::remove_file(&path);
4717 let trace_env = path.to_string_lossy().into_owned();
4718 let limit = Duration::from_secs(3600);
4719 let outcome = match run_binary(
4720 bin,
4721 None,
4722 &[("TMT_TRACE", &trace_env)],
4723 limit,
4724 RunOutput::Quiet,
4725 1,
4726 ) {
4727 Ok(outcome) => outcome,
4728 Err(err)
4729 if crate::interrupt::is_interrupted()
4730 || crate::interrupt::is_interrupted_err(&err) =>
4731 {
4732 let _ = fs::remove_file(&path);
4733 audit.trace_rerun_incomplete = true;
4734 break;
4735 }
4736 Err(err) => return Err(err),
4737 };
4738 let again = Trace::parse(&fs::read_to_string(&path).unwrap_or_default());
4739 let _ = fs::remove_file(&path);
4740 let records = bin.trace.differences(&again);
4741 if outcome != Outcome::Pass || records > 0 {
4742 audit.trace_differences.push(report::TraceDifference {
4743 binary: bin.name.clone(),
4744 records,
4745 rerun_failed: outcome != Outcome::Pass,
4746 });
4747 }
4748 }
4749 Ok(audit)
4750}
4751
4752fn run_effects_phase(
4753 session: &Session,
4754 files: &[SourceFile],
4755 jobs: &[Job],
4756 effect_jobs: &[(usize, usize)],
4757 scratch: &Path,
4758 workers: usize,
4759 findings: &mut [Finding],
4760) -> Result<()> {
4761 session.note(&format!("tracing {} surviving mutants", effect_jobs.len()));
4762 let sites: BTreeMap<u32, (&str, &Site)> = files
4763 .iter()
4764 .flat_map(|f| f.sites.iter().map(move |s| (s.id, (f.display.as_str(), s))))
4765 .collect();
4766 let traced = run_pool(effect_jobs.len(), workers, |index| {
4767 session.trace_job(
4768 &jobs[effect_jobs[index].1],
4769 scratch,
4770 workers.clamp(1, effect_jobs.len()),
4771 )
4772 })?;
4773 for ((finding, job), mut changes) in effect_jobs.iter().zip(traced) {
4774 if let Some((mutated_file, mutated)) = sites.get(&jobs[*job].site) {
4777 for found in changes.values_mut() {
4778 found.retain(|change| {
4779 sites.get(&change.site()).is_none_or(|(file, site)| {
4780 file != mutated_file
4781 || site.end <= mutated.start
4782 || mutated.end <= site.start
4783 })
4784 });
4785 }
4786 changes.retain(|_, found| !found.is_empty());
4787 }
4788 if let Finding::AssertionGap {
4789 effects,
4790 effects_of,
4791 ..
4792 } = &mut findings[*finding]
4793 {
4794 *effects = describe_effects(&changes, &sites);
4795 *effects_of = sites
4796 .get(&jobs[*job].site)
4797 .map(|(_, site)| report::describe(site, jobs[*job].mutation));
4798 }
4799 }
4800 Ok(())
4801}
4802
4803struct BaselineWriteContext<'a> {
4804 ws_package_prefix: &'a str,
4805 partial_scope: Option<&'a crate::baseline::PartialScope<'a>>,
4806 single_package_run: bool,
4807 note: &'a dyn Fn(&str),
4808}
4809
4810fn apply_suppressions_and_finish(
4811 options: &Options,
4812 files: &[SourceFile],
4813 report: &mut Report,
4814 finding_run_survivors: &[usize],
4815 killed_by_loc: &BTreeMap<(String, usize, usize, &'static str), usize>,
4816 checkpoint: Option<&Checkpoint>,
4817 write_ctx: &BaselineWriteContext<'_>,
4818) -> Result<()> {
4819 if crate::interrupt::is_interrupted() {
4820 report.interrupted = true;
4821 report.record_evaluation();
4822 }
4823 let parsed_ignores: BTreeMap<&str, crate::baseline::ParsedLineIgnores> = files
4824 .iter()
4825 .map(|f| {
4826 (
4827 f.display.as_str(),
4828 crate::baseline::parse_line_ignores(&f.original),
4829 )
4830 })
4831 .collect();
4832 for (file, parsed) in &parsed_ignores {
4833 for warning in &parsed.warnings {
4834 match warning {
4835 crate::baseline::IgnoreWarning::EmptyScope { line } => {
4836 eprintln!(
4837 "tmt: warning: {}:{line}: empty `tmt:ignore[]` scope suppresses nothing (supported: input_gap, assertion_gap, survivor, @COL, or kind@COL)",
4838 crate::report::sanitize_inline(file),
4839 );
4840 }
4841 crate::baseline::IgnoreWarning::InvalidToken { line, token } => {
4842 eprintln!(
4843 "tmt: warning: {}:{line}: unknown `tmt:ignore` scope `{}` (supported: input_gap, assertion_gap, survivor, @COL, or kind@COL)",
4844 crate::report::sanitize_inline(file),
4845 crate::report::sanitize_inline(token),
4846 );
4847 }
4848 }
4849 }
4850 }
4851 let known = match &options.baseline {
4852 Some(path) => {
4853 let loaded = crate::baseline::load(path)?;
4854 loaded.validate_for_package(&report.package, path)?;
4855 Some(loaded)
4856 }
4857 None => None,
4858 };
4859 let before = report.findings.len();
4860 let mut after_inline: Vec<(Finding, usize)> = Vec::with_capacity(before);
4861 let mut matched_entries: BTreeMap<(&str, usize), BTreeSet<(usize, usize)>> = BTreeMap::new();
4862 for (finding, run_survivors) in report
4863 .findings
4864 .drain(..)
4865 .zip(finding_run_survivors.iter().copied())
4866 {
4867 let at = finding.at();
4868 if let Some((&file_key, parsed)) = parsed_ignores.get_key_value(at.file.as_str())
4869 && parsed
4870 .directives
4871 .get(&at.line)
4872 .is_some_and(|ignore| ignore.matches(finding.kind(), at.column))
4873 {
4874 for entry in &parsed.entries {
4875 if entry.matches(at.line, finding.kind(), at.column) {
4876 matched_entries
4877 .entry((file_key, entry.comment_line))
4878 .or_default()
4879 .insert((at.line, at.column));
4880 }
4881 }
4882 report.survivor_breakdown.suppressed += run_survivors;
4883 } else {
4884 after_inline.push((finding, run_survivors));
4885 }
4886 }
4887 if !report.interrupted && options.shard.is_none() && report.mutants_not_evaluated == 0 {
4892 let skipped_locs: BTreeSet<(&str, usize, usize)> = report
4893 .skipped
4894 .iter()
4895 .map(|s| (s.at.file.as_str(), s.at.line, s.at.column))
4896 .collect();
4897 let unreached_locs: BTreeSet<(&str, usize, usize)> = report
4898 .unreached
4899 .iter()
4900 .map(|u| (u.file.as_str(), u.line, u.column))
4901 .collect();
4902 for file in files {
4903 let Some(parsed) = parsed_ignores.get(file.display.as_str()) else {
4904 continue;
4905 };
4906 if parsed.entries.is_empty() {
4907 continue;
4908 }
4909 let evaluated_lines: BTreeSet<usize> = file
4910 .sites
4911 .iter()
4912 .chain(&file.rebuild_sites)
4913 .filter(|site| {
4914 let key = (file.display.as_str(), site.line, site.column);
4915 !skipped_locs.contains(&key) && !unreached_locs.contains(&key)
4916 })
4917 .map(|site| site.line)
4918 .collect();
4919 for entry in &parsed.entries {
4920 if !entry.is_active() {
4921 continue;
4922 }
4923 if let Some(matched_cols) =
4924 matched_entries.get(&(file.display.as_str(), entry.comment_line))
4925 {
4926 let other_killed: usize = killed_by_loc
4927 .iter()
4928 .filter(|((f, line, col, kind), _)| {
4929 f == &file.display
4930 && entry.matches(*line, kind, *col)
4931 && !matched_cols.contains(&(*line, *col))
4932 })
4933 .map(|(_, count)| *count)
4934 .sum();
4935 if other_killed > 0 {
4936 eprintln!(
4937 "tmt: warning: {}:{}: `tmt:ignore` also covers {other_killed} killed mutation(s) at other column(s) (narrow with `// tmt:ignore[kind@COL]` to avoid hiding regressions)",
4938 crate::report::sanitize_inline(&file.display),
4939 entry.comment_line,
4940 );
4941 }
4942 continue;
4943 }
4944 if entry
4945 .target_lines
4946 .iter()
4947 .any(|line| evaluated_lines.contains(line))
4948 {
4949 let covered_killed: usize = killed_by_loc
4950 .iter()
4951 .filter(|((f, line, col, kind), _)| {
4952 f == &file.display && entry.matches(*line, kind, *col)
4953 })
4954 .map(|(_, count)| *count)
4955 .sum();
4956 if covered_killed > 0 {
4957 eprintln!(
4958 "tmt: warning: {}:{}: `tmt:ignore` matched no findings on an evaluated line (covers {covered_killed} killed mutation(s); remove or narrow with `// tmt:ignore[kind@COL]`)",
4959 crate::report::sanitize_inline(&file.display),
4960 entry.comment_line,
4961 );
4962 } else {
4963 eprintln!(
4964 "tmt: warning: {}:{}: `tmt:ignore` matched no findings on an evaluated line (mutants may already be killed or selector/column may not match)",
4965 crate::report::sanitize_inline(&file.display),
4966 entry.comment_line,
4967 );
4968 }
4969 }
4970 }
4971 }
4972 }
4973 if crate::interrupt::is_interrupted() {
4974 report.interrupted = true;
4975 report.record_evaluation();
4976 }
4977 if !report.interrupted
4978 && let Some(path) = &options.write_baseline
4979 {
4980 let unignored: Vec<Finding> = after_inline.iter().map(|(f, _)| f.clone()).collect();
4981 let single_pkg = write_ctx
4982 .single_package_run
4983 .then_some(report.package.as_str());
4984 let summary = crate::baseline::write_scoped(
4985 path,
4986 &report.package,
4987 write_ctx.ws_package_prefix,
4988 &unignored,
4989 write_ctx.partial_scope,
4990 single_pkg,
4991 )?;
4992 if summary.preserved > 0 || summary.removed > 0 {
4993 (write_ctx.note)(&format!(
4994 "baseline {}: {} entries written ({} preserved out of scope, {} resolved removed)",
4995 path.display(),
4996 summary.written,
4997 summary.preserved,
4998 summary.removed
4999 ));
5000 }
5001 }
5002 for (finding, run_survivors) in after_inline {
5003 if known
5004 .as_ref()
5005 .is_some_and(|known| known.knows_in_package(&report.package, &finding))
5006 {
5007 report.survivor_breakdown.suppressed += run_survivors;
5008 } else {
5009 report.survivor_breakdown.reported += run_survivors;
5010 report.findings.push(finding);
5011 }
5012 }
5013 report.suppressed = before - report.findings.len();
5014 if crate::interrupt::is_interrupted() {
5015 report.interrupted = true;
5016 report.record_evaluation();
5017 }
5018 if !report.interrupted
5019 && let Some(checkpoint) = checkpoint
5020 {
5021 checkpoint.finish_if_complete()?;
5022 }
5023 Ok(())
5024}
5025
5026fn workspace_report_prefix(relative: &Path) -> String {
5027 let parts: Vec<_> = relative
5028 .components()
5029 .filter_map(|part| match part {
5030 std::path::Component::Normal(name) => Some(name.to_string_lossy()),
5031 _ => None,
5032 })
5033 .collect();
5034 if parts.is_empty() {
5035 String::new()
5036 } else {
5037 format!("{}/", parts.join("/"))
5038 }
5039}
5040
5041fn repository_prefix(dir: &Path) -> String {
5045 let shown = Command::new("git")
5046 .arg("-C")
5047 .arg(dir)
5048 .args(["rev-parse", "--show-prefix"])
5049 .stderr(Stdio::null())
5050 .output();
5051 match shown {
5052 Ok(output) if output.status.success() => {
5053 String::from_utf8_lossy(&output.stdout).trim().to_string()
5054 }
5055 _ => String::new(),
5056 }
5057}
5058
5059fn spread(count: usize, wanted: usize) -> Vec<usize> {
5062 let wanted = wanted.min(count);
5063 (0..wanted).map(|nth| nth * count / wanted).collect()
5064}
5065
5066struct FilePlaces<'a> {
5068 display: &'a str,
5069 source: &'a str,
5070 lines: &'a scope::LineIndex,
5071 places: &'a [(usize, usize, String)],
5073}
5074
5075fn name_findings(findings: &mut [Finding], files: &[FilePlaces]) {
5080 let mut by_file: BTreeMap<String, Vec<&mut Finding>> = BTreeMap::new();
5081 for finding in findings {
5082 by_file
5083 .entry(finding.at().file.clone())
5084 .or_default()
5085 .push(finding);
5086 }
5087 for file in files {
5088 let Some(findings) = by_file.remove(file.display) else {
5089 continue;
5090 };
5091 let items = instrument::named_items(file.source);
5092 let index = instrument::ItemIndex::new(&items);
5093 let item_at = |line, column| {
5094 file.lines
5095 .offset_of(file.source, line, column)
5096 .map_or("", |offset| index.at(offset))
5097 };
5098 let mut positions: BTreeMap<(&str, &str), Vec<(usize, usize)>> = BTreeMap::new();
5099 for (line, column, code) in file.places {
5100 positions
5101 .entry((item_at(*line, *column), code))
5102 .or_default()
5103 .push((*line, *column));
5104 }
5105 for places in positions.values_mut() {
5106 places.sort_unstable();
5107 places.dedup();
5108 }
5109 for finding in findings {
5110 let kind = finding.kind();
5111 let at = finding.at_mut();
5112 let item = item_at(at.line, at.column);
5113 let nth = positions.get(&(item, &at.code)).map_or(0, |places| {
5114 places.partition_point(|&place| place < (at.line, at.column))
5115 });
5116 at.item = item.to_string();
5117 at.id = report::finding_id(kind, at, nth);
5118 }
5119 }
5120}
5121
5122fn mutation_of(site: &Site, mutant: &instrument::SourceMutant) -> Mutation {
5124 match &site.kind {
5125 SiteKind::Cmp { .. } => plan::CmpOp::ALL
5126 .into_iter()
5127 .find(|op| op.symbol() == mutant.into)
5128 .map_or(Mutation::Negate, Mutation::Op),
5129 SiteKind::Arith { op, .. } => {
5130 if mutant.into.trim_end_matches('=') == op.swapped().symbol() {
5131 Mutation::ArithSwap
5132 } else {
5133 Mutation::ArithSwap2
5134 }
5135 }
5136 SiteKind::Guard { .. } => Mutation::Const(mutant.into == "true"),
5137 SiteKind::Logic { .. } => Mutation::LogicSwap,
5138 SiteKind::Not { .. } => Mutation::DropNot,
5139 SiteKind::Range { .. } | SiteKind::RangeContains { .. } => Mutation::RangeEnd,
5140 SiteKind::SliceEnd { .. } => Mutation::OtherEnd,
5141 SiteKind::StrAffix { .. } => Mutation::StrContains,
5142 SiteKind::StrReplace { .. } => Mutation::StrReplaceMultiplicity,
5143 SiteKind::Clamp { .. } => {
5144 if mutant.into.contains("lower") {
5145 Mutation::ClampDropLower
5146 } else {
5147 Mutation::ClampDropUpper
5148 }
5149 }
5150 SiteKind::Rounding { op, .. } => {
5151 if mutant.into == op.alt1().name() {
5152 Mutation::RoundAlt1
5153 } else {
5154 Mutation::RoundAlt2
5155 }
5156 }
5157 SiteKind::Quantifier { .. } => Mutation::QuantifierSwap,
5158 SiteKind::Position { .. } => Mutation::PositionSwap,
5159 SiteKind::SaturatingArith { .. } => Mutation::SaturatingSwap,
5160 SiteKind::StrTrim { op, .. } => {
5161 if mutant.into == op.alt1().name() {
5162 Mutation::TrimAlt1
5163 } else {
5164 Mutation::TrimAlt2
5165 }
5166 }
5167 SiteKind::StrCaseEq { .. } => Mutation::StrExactEq,
5168 SiteKind::Abs { .. } => Mutation::DropAbs,
5169 SiteKind::IterLimit { .. } => Mutation::IterLimitDrop,
5170 SiteKind::EndianSwap { .. } => Mutation::EndianSwap,
5171 SiteKind::BitCount { .. } => Mutation::BitCountSwap,
5172 SiteKind::LoopCtrl { .. } => Mutation::LoopCtrlSwap,
5173 SiteKind::LiteralSet { elements, .. } => {
5174 let idx = elements
5175 .iter()
5176 .position(|(elem, _, _)| elem == &mutant.into)
5177 .unwrap_or(0);
5178 Mutation::DropLiteralElem(idx as u8)
5179 }
5180 _ => Mutation::Delete,
5183 }
5184}
5185
5186fn mutations_like(site: &Site, mutant: &instrument::SourceMutant, integers: bool) -> Vec<Mutation> {
5195 let mut all = vec![mutation_of(site, mutant)];
5196 if let (SiteKind::Cmp { op, .. }, Mutation::Op(into)) = (&site.kind, all[0]) {
5197 let an_order_is_needed = matches!(op, plan::CmpOp::Le | plan::CmpOp::Ge);
5198 if into == op.negated() && (integers || !an_order_is_needed) {
5199 all.push(Mutation::Negate);
5200 }
5201 match (op, into) {
5202 (plan::CmpOp::Lt, plan::CmpOp::Le) | (plan::CmpOp::Ge, plan::CmpOp::Gt) => {
5203 all.push(Mutation::Shift(1))
5204 }
5205 (plan::CmpOp::Gt, plan::CmpOp::Ge) | (plan::CmpOp::Le, plan::CmpOp::Lt) => {
5206 all.push(Mutation::Shift(-1))
5207 }
5208 _ => {}
5209 }
5210 }
5211 all
5212}
5213
5214fn describe_effects(
5217 changes: &BTreeMap<String, BTreeSet<Change>>,
5218 sites: &BTreeMap<u32, (&str, &Site)>,
5219) -> Vec<String> {
5220 let mut by_change: BTreeMap<&Change, Vec<&str>> = BTreeMap::new();
5221 for (test, found) in changes {
5222 for change in found {
5223 by_change.entry(change).or_default().push(test);
5224 }
5225 }
5226 if by_change.is_empty() {
5227 return vec![
5228 "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(),
5229 ];
5230 }
5231 let mut out = vec![];
5232 for (change, tests) in by_change.iter().take(3) {
5233 let Some((file, site)) = sites.get(&change.site()) else {
5234 continue;
5235 };
5236 let code = report::location(file, site).code;
5237 let at = format!("{file}:{}", site.line);
5238 let who = if tests.is_empty() {
5239 continue;
5240 } else if let Some(first) = tests
5241 .iter()
5242 .copied()
5243 .find(|test| *test != crate::trace::UNKNOWN_TEST)
5244 {
5245 if tests.len() == 1 {
5246 format!("`{first}`")
5247 } else {
5248 format!("`{first}` (and {} more)", tests.len() - 1)
5249 }
5250 } else if tests.len() == 1 {
5251 "a test".to_string()
5252 } else {
5253 format!("a test (and {} more)", tests.len() - 1)
5254 };
5255 out.push(match change {
5256 Change::Returns { value, .. } => {
5257 format!("with the mutant, {who} gets `{value}` from `{code}` ({at})")
5258 }
5259 Change::NowRuns { .. } => format!("with the mutant, {who} now runs `{code}` ({at})"),
5260 Change::NoLongerRuns { .. } => {
5261 format!("with the mutant, {who} no longer runs `{code}` ({at})")
5262 }
5263 Change::NewOutcome { .. } => {
5264 format!("with the mutant, {who} takes `{code}` ({at}) a way it did not before")
5265 }
5266 });
5267 }
5268 if by_change.len() > 3 {
5269 out.push(format!("(and {} more such changes)", by_change.len() - 3));
5270 }
5271 out
5272}
5273
5274#[cfg(test)]
5275mod tests;