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 crate::interrupt::check()?;
541 let result = run_package(&member, Some(&batch), None);
542 if let Err(err) = &result
543 && crate::interrupt::is_interrupted_err(err)
544 {
545 return Err(crate::interrupt::Interrupted.into());
546 }
547 completed(name, result)?;
548 }
549 return Ok(());
550 };
551 if shard.index >= shard.count || member_options.iter().any(|(_, m)| !m.source_only) {
552 bail!("shards require --source-only and a valid shard index");
553 }
554 let catalogues: Vec<_> = member_options
557 .into_iter()
558 .map(|(name, member)| {
559 let mut preview = member.clone();
560 preview.list = true;
561 preview.shard = None;
562 preview.progress = false;
563 let catalogue = run_package(&preview, Some(&batch), None).map(|mut report| {
564 let count = report.mutants.as_ref().map_or(0, Vec::len);
565 if !member.list {
566 report.mutants = None;
567 }
568 (count, report)
569 });
570 (name, member, catalogue)
571 })
572 .collect();
573 let total = catalogues
574 .iter()
575 .filter_map(|(_, _, catalogue)| catalogue.as_ref().ok())
576 .map(|(count, _)| count)
577 .sum();
578 let mut offset = 0;
579 for (name, member, catalogue) in catalogues {
580 let result = catalogue.and_then(|(member_total, mut report)| {
581 let range = WorkspaceShard {
582 offset,
583 total,
584 member_total,
585 };
586 offset += member_total;
587 if member.list {
588 report.analysis.shard = Some(shard);
589 let mut index = range.offset;
590 report
591 .mutants
592 .as_mut()
593 .expect("source catalogue")
594 .retain(|_| {
595 let keep = shard.contains(index, total);
596 index += 1;
597 keep
598 });
599 Ok(report)
600 } else {
601 run_package(&member, Some(&batch), Some(range))
602 }
603 });
604 completed(name, result)?;
605 }
606 Ok(())
607}
608
609struct LeftoverNote(bool);
611
612impl Drop for LeftoverNote {
613 fn drop(&mut self) {
614 use std::sync::atomic::Ordering;
615 let stopped = leftovers::STOPPED.swap(0, Ordering::Relaxed);
616 let not_stopped = leftovers::NOT_STOPPED.swap(0, Ordering::Relaxed);
617 if let Some(text) = leftover_note(stopped, not_stopped)
618 && self.0
619 {
620 eprintln!("tmt: {text}");
621 }
622 }
623}
624
625fn leftover_note(stopped: usize, not_stopped: usize) -> Option<String> {
626 let stopped = (stopped > 0).then(|| {
627 format!("stopped {stopped} processes that the tests had left running after their run")
628 });
629 let not_stopped = (not_stopped > 0).then(|| {
630 format!(
631 "after {not_stopped} runs something the tests started may still be running \
632 (it could not be found or stopped)"
633 )
634 });
635 match (stopped, not_stopped) {
636 (None, None) => None,
637 (Some(one), None) | (None, Some(one)) => Some(one),
638 (Some(stopped), Some(not_stopped)) => Some(format!("{stopped}; {not_stopped}")),
639 }
640}
641
642pub fn run(options: &Options) -> Result<Report> {
643 run_package(options, None, None)
644}
645
646fn run_package(
647 options: &Options,
648 batch: Option<&WorkspaceBatch<'_>>,
649 workspace_shard: Option<WorkspaceShard>,
650) -> Result<Report> {
651 let _leftovers = LeftoverNote(options.progress);
652 let error_values = validate_package_options(options)?;
653 let selection = &options.test_selection;
654 let effective_jobs = if options.source_only { 1 } else { options.jobs };
655 let note = |text: &str| {
656 if options.progress {
657 eprintln!("tmt: {}", report::sanitize_inline(text));
658 }
659 };
660 let dir = options
661 .dir
662 .canonicalize()
663 .with_context(|| format!("no such directory: {}", options.dir.display()))?;
664 if dir.is_file() {
665 let given = crate::report::sanitize_inline(&options.dir.display().to_string());
666 bail!(
667 "`{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"
668 );
669 }
670
671 let local_metadata;
672 let metadata = if let Some(batch) = batch {
673 batch.metadata
674 } else {
675 local_metadata = cargo_metadata(&dir, &options.cargo)?;
676 &local_metadata
677 };
678 let catalogue = batch
679 .and_then(|batch| batch.catalogue.as_ref())
680 .filter(|_| options.list);
681 let enclosing_package = metadata
682 .packages
683 .iter()
684 .filter(|p| {
685 p.manifest_path
686 .parent()
687 .is_some_and(|root| dir != root && dir.starts_with(root))
688 })
689 .max_by_key(|p| {
690 p.manifest_path
691 .parent()
692 .map_or(0, |root| root.as_os_str().len())
693 });
694 let package = match &options.package {
695 Some(name) => metadata.packages.iter().find(|p| &p.name == name),
696 None => metadata
697 .packages
698 .iter()
699 .find(|p| p.manifest_path.parent() == Some(dir.as_path()))
700 .or(match &metadata.packages[..] {
701 [only] => Some(only),
702 _ => None,
703 }),
704 }
705 .ok_or_else(|| {
706 if let Some(name) = &options.package {
707 anyhow!(
708 "no package `{}` in workspace",
709 crate::report::sanitize_inline(name)
710 )
711 } else if let Some(owner) = enclosing_package {
712 anyhow!(
713 "`{}` 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)",
714 crate::report::sanitize_inline(&options.dir.display().to_string()),
715 crate::report::sanitize_inline(&owner.name),
716 crate::report::sanitize_inline(&owner.name),
717 )
718 } else {
719 anyhow!("cannot tell which package to analyse; pass --package <name>")
720 }
721 })?;
722 if options.package.is_none()
723 && !dir.join("Cargo.toml").is_file()
724 && package.manifest_path.parent() != Some(dir.as_path())
725 && options.progress
726 {
727 eprintln!(
728 "tmt: note: `{}` has no Cargo.toml; analysing package `{}` (use `--lines <file>` to scope to specific files)",
729 crate::report::sanitize_inline(&options.dir.display().to_string()),
730 crate::report::sanitize_inline(&package.name),
731 );
732 }
733 let mut test_packages: Vec<&Package> = vec![package];
736 for name in &options.also_test {
737 let other = metadata
738 .packages
739 .iter()
740 .find(|p| &p.name == name)
741 .ok_or_else(|| anyhow!("--also-test: no package `{name}` in the workspace"))?;
742 if !test_packages.iter().any(|p| p.name == other.name) {
743 test_packages.push(other);
744 }
745 }
746 if options.test_workspace {
747 test_packages.extend(
748 metadata
749 .packages
750 .iter()
751 .filter(|other| {
752 !test_packages
753 .iter()
754 .any(|selected| selected.name == other.name)
755 })
756 .collect::<Vec<_>>(),
757 );
758 }
759 if options.dependents {
760 for name in dependents_of(&package.name, &metadata.packages) {
761 if let Some(other) = metadata.packages.iter().find(|p| p.name == name)
762 && !test_packages.iter().any(|p| p.name == other.name)
763 {
764 test_packages.push(other);
765 }
766 }
767 }
768 if !options.list {
769 validate_target_selection(&test_packages, selection)?;
770 }
771 let is_kind = |t: &Target, kinds: &[&str]| t.kind.iter().any(|k| kinds.contains(&k.as_str()));
772 let root_target = package
773 .targets
774 .iter()
775 .find(|t| {
776 is_kind(
777 t,
778 &["lib", "rlib", "cdylib", "staticlib", "dylib", "proc-macro"],
779 )
780 })
781 .or_else(|| package.targets.iter().find(|t| is_kind(t, &["bin"])))
782 .ok_or_else(|| anyhow!("package `{}` has no lib or bin target", package.name))?;
783
784 let PreparedWorkCopy {
786 workspace,
787 work,
788 work_lock,
789 copy,
790 state,
791 external_deps,
792 } = prepare_work_copy(options, metadata, batch, catalogue, ¬e)?;
793
794 let in_copy = |path: &Path| -> Result<PathBuf> {
795 let canonical = path.canonicalize()?;
796 let relative = canonical
797 .strip_prefix(&workspace)
798 .with_context(|| format!("{} is outside the workspace", path.display()))?;
799 Ok(copy.join(relative))
800 };
801 let package_dir = in_copy(
802 package
803 .manifest_path
804 .parent()
805 .expect("manifest has a parent"),
806 )?;
807 let root_file = in_copy(&root_target.src_path)?;
808 let source_dir = root_file
809 .parent()
810 .expect("source file has a parent")
811 .to_path_buf();
812
813 let mut roots = BTreeMap::new();
816 for owner in &metadata.packages {
817 for target in &owner.targets {
818 let production = owner.name == package.name && target.is_production();
819 if let Ok(path) = in_copy(&target.src_path)
820 && path.is_file()
821 {
822 let selected = roots.entry(path).or_insert(false);
823 *selected |= production;
824 }
825 }
826 }
827 let paths = source_graph(roots, ©, |path| state.original(path, &workspace))?;
828 let package_orig_dir = package
829 .manifest_path
830 .parent()
831 .expect("manifest has a parent");
832 let scope = requested_scope(
833 options,
834 &workspace,
835 package_orig_dir,
836 &package.name,
837 batch.is_some(),
838 )?;
839 let mut skipped = vec![];
840 let mut files = vec![];
841 let mut excluded_any = false;
842 let mut next_id = 0u32;
843 let want_witnesses = (options.list || options.rebuild || options.source_only)
844 && root_target.test_build_arg() == Some(("--lib", None));
845 let count_rebuild_witnesses =
846 !want_witnesses && root_target.test_build_arg() == Some(("--lib", None));
847 let mut witness_candidates = vec![];
848 let mut unbuilt_witness_candidates = vec![];
849 for (path, owners) in paths {
850 let Some(original) = state.original(&path, &workspace)? else {
851 continue; };
853 let display = relative_source(&path, &package_dir).display().to_string();
854 if scope::matches_any_glob(&options.exclude_files, &display) {
855 excluded_any = true;
856 continue;
857 }
858 let selected_file = scope.as_ref().is_none_or(|scope| {
859 let relative = path.strip_prefix(©).unwrap_or(&path).to_string_lossy();
860 scope.touches(&relative, 1, usize::MAX)
861 });
862 if !selected_file && path != root_file {
863 continue;
864 }
865 match instrument::parse_source(&original) {
866 Ok(parsed) => {
867 let mut found =
868 instrument::discover_parsed(&original, &parsed, next_id, &error_values);
869 if (want_witnesses || count_rebuild_witnesses)
871 && selected_file
872 && owners.consumers.len() == 1
873 && owners.consumers.contains(&root_file)
874 {
875 let discovered = witness::discover_parsed(
876 &original,
877 &parsed,
878 want_witnesses && !options.list,
879 )
880 .into_iter()
881 .map(|mut candidate| {
882 candidate.file = path.clone();
883 candidate
884 });
885 if want_witnesses {
886 witness_candidates.extend(discovered);
887 } else {
888 unbuilt_witness_candidates.extend(discovered);
889 }
890 if want_witnesses && !options.list && !options.literal_operators {
893 witness_candidates.extend(
894 stronger_assertions(
897 &original,
898 &parsed,
899 found.sites.iter().chain(&found.rebuild_sites),
900 )
901 .into_iter()
902 .map(|mut candidate| {
903 candidate.file = path.clone();
904 candidate
905 }),
906 );
907 }
908 }
909 next_id += found.sites.len() as u32;
910 if owners.consumers.len() != 1 || !owners.consumers.contains(&root_file) {
911 found.rebuild_sites.append(&mut found.sites);
912 }
913 let places = if options.list {
914 vec![]
915 } else {
916 found
917 .sites
918 .iter()
919 .chain(&found.rebuild_sites)
920 .map(|site| (site.line, site.column, report::one_line(&site.text)))
921 .collect()
922 };
923 files.push(SourceFile {
924 display,
925 path,
926 owners: owners.production,
927 lines: scope::LineIndex::new(&original),
928 original,
929 places,
930 sites: found.sites,
931 rebuild_sites: found.rebuild_sites,
932 rendered: None,
933 });
934 }
935 Err(err) => {
936 if selected_file {
937 let diagnostic = format!("{err:#}");
938 note(&format!("skipping {display}: {diagnostic}"));
939 let end_line = scope::line_of(&original, original.len());
940 let end_column = original.rsplit('\n').next().unwrap_or("").chars().count() + 1;
941 skipped.push(report::SkippedSite::new(
942 report::Location {
943 file: display,
944 line: 1,
945 column: 1,
946 ..Default::default()
947 },
948 (end_line, end_column),
949 report::SkipReason::UnparseableSource,
950 Some(diagnostic),
951 ));
952 }
953 }
954 }
955 }
956
957 let since_hunks = match options.since.as_deref() {
960 Some(revision) if !options.list && options.shard.is_none() => {
961 scope::hunks(&since_diff(&workspace, revision)?)
962 }
963 _ => vec![],
964 };
965 let mut tests_changed: Vec<(PathBuf, Vec<scope::Hunk>)> = vec![];
966 let mut undo_paths: HashSet<PathBuf> = HashSet::new();
968 let mut not_built_reverts: usize = 0;
969 let mut beyond_places: HashSet<(PathBuf, usize, usize)> = HashSet::new();
970 if let Some(scope) = &scope {
972 for file in &mut files {
973 let relative = file
974 .path
975 .strip_prefix(©)
976 .unwrap_or(&file.path)
977 .to_string_lossy()
978 .into_owned();
979 let in_scope = |site: &Site| {
980 scope.touches(&relative, file.lines.line_of(site.start), file.lines.line_of(site.end))
981 || scope.touches(&relative, site.line, site.line)
983 };
984 let of_file: Vec<scope::Hunk> = since_hunks
985 .iter()
986 .filter(|hunk| hunk.file == relative)
987 .cloned()
988 .collect();
989 let changes_count = reverts::changes(&file.original, &of_file).len();
990 if options.rebuild || options.source_only {
991 if changes_count > 0 || reverts::mixed(&file.original, &of_file) > 0 {
992 undo_paths.insert(file.path.clone());
993 }
994 } else {
995 not_built_reverts += changes_count;
996 }
997 let of_tests = reverts::test_hunks(&file.original, &of_file);
998 if of_tests.is_empty() {
999 file.sites.retain(in_scope);
1000 } else {
1001 beyond_places.extend(
1002 file.sites
1003 .iter()
1004 .filter(|site| !in_scope(site))
1005 .map(|site| (file.path.clone(), site.start, site.end)),
1006 );
1007 tests_changed.push((file.path.clone(), of_tests));
1008 }
1009 file.rebuild_sites.retain(in_scope);
1010 }
1011 files.retain(|f| {
1012 !f.sites.is_empty()
1013 || !f.rebuild_sites.is_empty()
1014 || f.path == root_file
1015 || witness_candidates.iter().any(|c| c.file == f.path)
1016 || unbuilt_witness_candidates.iter().any(|c| c.file == f.path)
1017 || undo_paths.contains(&f.path)
1018 });
1019 }
1020 if !options.list {
1021 for candidate in witness_candidates.iter().filter(|c| !c.existing) {
1022 if let Some(file) = files.iter_mut().find(|file| file.path == candidate.file) {
1023 let at = witness_location(file, candidate);
1024 file.places.push((at.line, at.column, at.code));
1025 }
1026 }
1027 }
1028 let witness_in_scope = |candidate: &witness::Candidate| {
1029 let Some(file) = files.iter().find(|file| file.path == candidate.file) else {
1030 return false;
1031 };
1032 let relative = file
1033 .path
1034 .strip_prefix(©)
1035 .unwrap_or(&file.path)
1036 .to_string_lossy();
1037 scope.as_ref().is_none_or(|scope| {
1038 let site_in_scope = if candidate.edits.len() == 1 {
1039 scope.touches(&relative, *candidate.scope.start(), *candidate.scope.end())
1040 } else {
1041 candidate.edits.iter().any(|edit| {
1042 scope.touches(
1043 &relative,
1044 file.lines.line_of(edit.span.start),
1045 file.lines.line_of(edit.span.end),
1046 )
1047 })
1048 };
1049 site_in_scope
1050 || candidate
1051 .signature_lines
1052 .iter()
1053 .any(|&line| scope.touches(&relative, line, line))
1054 })
1055 };
1056 witness_candidates.retain(&witness_in_scope);
1057 unbuilt_witness_candidates.retain(&witness_in_scope);
1058 let not_built_witnesses = unbuilt_witness_candidates
1059 .iter()
1060 .filter(|candidate| !candidate.existing)
1061 .count();
1062
1063 let unassessed_test_changes: Vec<String> = if let Some(revision) = options.since.as_deref()
1064 && !options.list
1065 {
1066 let integration_prefixes: Vec<String> = test_packages
1067 .iter()
1068 .flat_map(|pkg| {
1069 let pkg_dir = pkg.manifest_path.parent().unwrap_or(&workspace);
1070 let pkg_rel = pkg_dir.strip_prefix(&workspace).ok();
1071 let pkg_tests_dir = pkg_rel.map(|rel| {
1072 let s = rel.join("tests").to_string_lossy().replace('\\', "/");
1073 format!("{s}/")
1074 });
1075 let workspace_ref = &workspace;
1076 let explicit_targets = pkg.targets.iter().flat_map(move |t| {
1077 if !t.kind.iter().any(|k| k == "test") {
1078 return vec![];
1079 }
1080 let Ok(rel) = t.src_path.strip_prefix(workspace_ref) else {
1081 return vec![];
1082 };
1083 let mut out = vec![rel.to_string_lossy().replace('\\', "/")];
1084 if let (Some(parent), Some(pkg_r)) = (rel.parent(), pkg_rel) {
1088 let is_pkg_root = parent == pkg_r;
1089 let is_src = parent == pkg_r.join("src");
1090 if !is_pkg_root && !is_src && !parent.as_os_str().is_empty() {
1091 out.push(format!("{}/", parent.to_string_lossy().replace('\\', "/")));
1092 }
1093 }
1094 out
1095 });
1096 pkg_tests_dir.into_iter().chain(explicit_targets)
1097 })
1098 .collect();
1099 let is_integration_test = |ws_rel: &str| {
1100 ws_rel.ends_with(".rs")
1101 && integration_prefixes.iter().any(|prefix| {
1102 if prefix.ends_with('/') {
1103 ws_rel.starts_with(prefix)
1104 } else {
1105 ws_rel == prefix
1106 }
1107 })
1108 };
1109 since_changed_files(&workspace, revision)?
1110 .into_iter()
1111 .filter(|f| is_integration_test(f))
1112 .collect()
1113 } else {
1114 vec![]
1115 };
1116 let total_sites: usize = files
1117 .iter()
1118 .map(|f| f.sites.len() + f.rebuild_sites.len())
1119 .sum::<usize>()
1120 + witness_candidates
1121 .iter()
1122 .filter(|candidate| !candidate.existing)
1123 .count();
1124 let files_with_sites = files
1125 .iter()
1126 .filter(|f| {
1127 !f.sites.is_empty()
1128 || !f.rebuild_sites.is_empty()
1129 || witness_candidates
1130 .iter()
1131 .any(|c| !c.existing && c.file == f.path)
1132 })
1133 .count();
1134 note(&format!(
1135 "{total_sites} sites in {files_with_sites} {}",
1136 if files_with_sites == 1 {
1137 "file"
1138 } else {
1139 "files"
1140 }
1141 ));
1142 if options.source_only {
1143 for file in &mut files {
1144 file.rebuild_sites.append(&mut file.sites);
1145 }
1146 }
1147
1148 let source_mutants = |file: &SourceFile, site: &Site, include_boundary: bool| {
1149 let mut mutants = instrument::source_mutants(site);
1150 if include_boundary {
1151 mutants.extend(instrument::source_boundary_mutant(site));
1152 }
1153 if options.literal_operators {
1154 instrument::literal_operator_mutants(&file.original, site, &mut mutants);
1155 }
1156 instrument::keep_line_ends(&file.original, &mut mutants);
1157 mutants
1158 };
1159 let counts = options.shard.map(|_| {
1160 let regular: usize = files
1161 .iter()
1162 .map(|file| {
1163 file.rebuild_sites
1164 .iter()
1165 .map(|site| source_mutants(file, site, true).len())
1166 .sum::<usize>()
1167 })
1168 .sum();
1169 let total = regular
1170 + witness_candidates
1171 .iter()
1172 .filter(|candidate| !candidate.existing)
1173 .count();
1174 (regular, total)
1175 });
1176 if let (Some(range), Some((_, local_total))) = (workspace_shard, counts)
1177 && range.member_total != local_total
1178 {
1179 bail!("package catalogue changed while preparing its workspace shard");
1180 }
1181 let in_shard = |index| match (options.shard, counts, workspace_shard) {
1182 (Some(shard), _, Some(range)) => shard.contains(range.offset + index, range.total),
1183 (Some(shard), Some((_, total)), _) => shard.contains(index, total),
1184 _ => true,
1185 };
1186 if let Some((mut index, _)) = counts {
1187 witness_candidates.retain(|candidate| {
1188 if candidate.existing {
1189 return true;
1190 }
1191 let selected = in_shard(index);
1192 index += 1;
1193 selected
1194 });
1195 }
1196 let empty_shard = counts.is_some_and(|(_, total)| !(0..total).any(in_shard));
1197
1198 let package_path = package.manifest_path.parent().unwrap_or(Path::new("."));
1199 let mut report_path = repository_prefix(package_path);
1200 if report_path.is_empty()
1201 && batch.is_some()
1202 && let Ok(relative) = package_path.strip_prefix(&workspace)
1203 {
1204 report_path = workspace_report_prefix(relative);
1205 }
1206 let mut report = Report {
1207 package: package.name.clone(),
1208 sites: if empty_shard { 0 } else { total_sites },
1209 analysis: report::Analysis {
1210 package_path: report_path,
1211 since: options.since.clone(),
1212 lines: options.lines.clone(),
1213 exclude_files: options.exclude_files.clone(),
1214 tests_of: test_packages.iter().map(|p| p.name.clone()).collect(),
1215 cargo: options.cargo.clone(),
1216 opt_level: options.opt_level,
1217 timeout_seconds: options.timeout_seconds,
1218 baseline_timeout_seconds: options.baseline_timeout_seconds,
1219 baseline_jobs: (options.baseline_jobs > 1).then_some(options.baseline_jobs),
1220 timeout_recheck: if options.serial_timeout_rechecks {
1221 "serial"
1222 } else {
1223 "none"
1224 },
1225 wrapper_grace_seconds: selection
1226 .wrapper
1227 .as_ref()
1228 .map(|_| options.wrapper_grace.as_secs()),
1229 rebuild: options.rebuild || options.source_only,
1230 verified: options.verify && !options.source_only,
1231 doc_tests: options.doc,
1232 source_only: options.source_only,
1233 literal_operators: options.literal_operators,
1234 shard: options.shard,
1235 nextest: options.nextest.clone(),
1236 error_values: error_values
1237 .iter()
1238 .map(|value| (*value).to_owned())
1239 .collect(),
1240 test_selection: None,
1241 git_index: options.git_index,
1242 copy_fixtures: options.copy_fixtures.clone(),
1243 copy_fixture_excludes: options.copy_fixture_excludes.clone(),
1244 output_fixtures: options.output_fixtures.clone(),
1245 stage_external: options.stage_external.clone(),
1246 checkpoint: (options.checkpoint && !options.list)
1247 .then(|| work.join("checkpoint.jsonl")),
1248 },
1249 skipped,
1250 wrapper_grace_outcomes: if options.list {
1251 None
1252 } else {
1253 selection
1254 .wrapper
1255 .as_ref()
1256 .map(|_| report::WrapperGraceOutcomes::default())
1257 },
1258 baseline: if options.list {
1259 None
1260 } else {
1261 options.baseline.clone()
1262 },
1263 unassessed_test_changes,
1264 ..Report::default()
1265 };
1266 if options.list {
1267 if catalogue.is_none() {
1268 state.settle(&workspace)?;
1269 }
1270 let mut candidates = vec![];
1271 let mut index = 0;
1272 for file in &files {
1273 let sites = file
1274 .sites
1275 .iter()
1276 .map(|site| (site, false))
1277 .chain(file.rebuild_sites.iter().map(|site| (site, true)));
1278 for (site, requires_rebuild) in sites {
1279 for mutant in source_mutants(file, site, true) {
1280 if in_shard(index) {
1281 candidates.push(report::Candidate {
1282 what: mutant.what,
1283 into: mutant.into,
1284 requires_rebuild,
1285 edits: vec![candidate_edit(
1286 file,
1287 mutant.start,
1288 mutant.end,
1289 mutant.replacement,
1290 )],
1291 });
1292 }
1293 index += 1;
1294 }
1295 }
1296 }
1297 candidates.extend(
1298 witness_candidates
1299 .iter()
1300 .filter(|candidate| !candidate.existing)
1301 .filter_map(|candidate| {
1302 let file = files.iter().find(|file| file.path == candidate.file)?;
1303 Some(report::Candidate {
1304 what: "witness".into(),
1305 into: candidate.description.clone(),
1306 requires_rebuild: true,
1307 edits: candidate
1308 .edits
1309 .iter()
1310 .map(|edit| {
1311 candidate_edit(
1312 file,
1313 edit.span.start,
1314 edit.span.end,
1315 edit.replacement.clone(),
1316 )
1317 })
1318 .collect(),
1319 })
1320 }),
1321 );
1322 report.mutants = Some(candidates);
1323 return Ok(report);
1324 }
1325 let ws_package_prefix = package_dir
1326 .strip_prefix(©)
1327 .unwrap_or(Path::new(""))
1328 .to_string_lossy()
1329 .replace('\\', "/");
1330 let all_files_excluded = excluded_any && files.is_empty();
1331 let is_partial_scope =
1332 scope.is_some() || !options.exclude_files.is_empty() || options.shard.is_some();
1333 if empty_shard
1334 || ((scope.is_some() || all_files_excluded) && total_sites == 0 && undo_paths.is_empty())
1335 {
1336 state.settle(&workspace)?;
1338 if let Some(path) = &options.baseline {
1339 let loaded = crate::baseline::load(path)?;
1340 loaded.validate_for_package(&package.name, path)?;
1341 }
1342 if let Some(path) = &options.write_baseline {
1343 let partial = crate::baseline::PartialScope {
1344 scope: scope.as_ref(),
1345 exclude_files: &options.exclude_files,
1346 preserve_all_existing: true,
1347 };
1348 let single_pkg = batch.is_none().then_some(package.name.as_str());
1349 let summary = crate::baseline::write_scoped(
1350 path,
1351 &package.name,
1352 &ws_package_prefix,
1353 &[],
1354 Some(&partial),
1355 single_pkg,
1356 )?;
1357 if summary.preserved > 0 {
1358 note(&format!(
1359 "baseline {}: preserved {} out-of-scope entries (no sites evaluated)",
1360 path.display(),
1361 summary.preserved
1362 ));
1363 }
1364 }
1365 if !empty_shard {
1366 report.mutants_not_built += not_built_reverts + not_built_witnesses;
1367 }
1368 report.record_evaluation();
1369 if let Some(path) = report.analysis.checkpoint.as_deref() {
1370 let checkpoint = Checkpoint::open(path)?;
1371 let settings =
1372 serde_json::json!({"analysis": &report.analysis, "package": &package.name});
1373 let identity = crate::campaign_identity::compute(©, &settings, [], false)?;
1374 checkpoint.start(&identity, settings)?;
1375 checkpoint.finish()?;
1376 }
1377 return Ok(report);
1378 }
1379
1380 for (id, site) in files
1383 .iter_mut()
1384 .flat_map(|file| &mut file.sites)
1385 .enumerate()
1386 {
1387 site.id = id as u32;
1388 }
1389 let beyond: HashSet<u32> = files
1391 .iter()
1392 .flat_map(|file| {
1393 file.sites
1394 .iter()
1395 .filter(|site| beyond_places.contains(&(file.path.clone(), site.start, site.end)))
1396 .map(|site| site.id)
1397 })
1398 .collect();
1399
1400 let root_source = state
1401 .original(&root_file, &workspace)?
1402 .with_context(|| format!("{} is missing", root_target.src_path.display()))?;
1403 let root_suffix = if options.source_only || files.iter().all(|file| file.sites.is_empty()) {
1404 String::new()
1405 } else {
1406 state.write(
1407 &source_dir.join(format!("{RUNTIME_MOD}.rs")),
1408 crate::RUNTIME_SOURCE,
1409 )?;
1410 let std_alias = format!("extern crate std as {STD_ALIAS};");
1411 if root_source.contains(&std_alias) {
1412 format!("\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
1413 } else {
1414 format!("\n#[doc(hidden)]\n{std_alias}\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
1415 }
1416 };
1417
1418 let mut disabled: HashSet<u32> = HashSet::new();
1420 let mut repairs = BTreeMap::new();
1421 let build_target = work_directory(&work, "target")?;
1422 let target_flags = test_build_flags(&test_packages, selection, &workspace, &options.cargo);
1423 let build_scope = if target_flags.is_some() {
1424 report::TestBuildScope::SelectedTargets
1425 } else {
1426 report::TestBuildScope::PackageWide
1427 };
1428 let build_note = if selection.has_target_filters() && target_flags.is_none() {
1429 "Cargo is using a package-wide build because the selected test targets cannot be expressed exactly.\n"
1430 } else {
1431 ""
1432 };
1433 if !build_note.is_empty() {
1434 note(build_note.trim_end());
1435 }
1436 let can_build_only_observer = !options.doc
1439 && target_flags.is_none()
1440 && test_packages.len() == 1
1441 && package.targets.len() == 1
1442 && root_target.test
1443 && root_target.test_build_arg() == Some(("--lib", None));
1444 let build_test_binaries = |observer: bool| {
1445 let mut command = Command::new("cargo");
1446 isolate_copy_command(&mut command, &work);
1447 if let Some(lock) = &work_lock {
1448 lock.retain_for(&mut command);
1449 }
1450 command
1451 .args(["test", "--no-run", "--message-format=json"])
1452 .args(test_packages.iter().flat_map(|p| ["-p", p.name.as_str()]))
1453 .args(target_flags.as_deref().unwrap_or_default())
1454 .args((observer && can_build_only_observer).then_some("--lib"))
1455 .args(options.cargo.flags())
1456 .current_dir(©)
1457 .env("CARGO_TARGET_DIR", &build_target)
1458 .env("CARGO_BUILD_BUILD_DIR", &build_target)
1459 .envs(profile_env(options.opt_level));
1460 run_cargo_with_progress(&mut command, options.progress && !observer)
1461 };
1462 let cargo_build = || build_test_binaries(false);
1463 let has_probe_sites = !options.source_only && files.iter().any(|f| !f.sites.is_empty());
1464 let repair_fingerprint = has_probe_sites.then(|| {
1465 let test_pkg_names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
1466 repair_cache::compute_fingerprint(
1467 &state.root,
1468 ©,
1469 &workspace,
1470 &state,
1471 &external_deps,
1472 &package.name,
1473 &test_pkg_names,
1474 &options.cargo,
1475 options.opt_level,
1476 target_flags.as_deref(),
1477 &error_values,
1478 options.doc,
1479 &files,
1480 )
1481 });
1482 if let Some(fingerprint) = &repair_fingerprint {
1483 let cached = repair_cache::load(&work, fingerprint);
1484 if !cached.is_empty() {
1485 for entry in cached {
1486 if let Some(file) = files.iter().find(|f| f.display == entry.file)
1487 && let Some(site) = file.sites.get(entry.site_index)
1488 && site.start == entry.start
1489 && site.end == entry.end
1490 && site.text == entry.text
1491 && format!("{:?}", site.kind) == entry.kind
1492 {
1493 disabled.insert(site.id);
1494 repairs.entry(site.id).or_insert(entry.reason);
1495 }
1496 }
1497 if !disabled.is_empty() {
1498 note(&format!(
1499 "reusing {} cached repair exclusion(s)",
1500 disabled.len()
1501 ));
1502 }
1503 }
1504 }
1505 let mut rounds = 0;
1506 let mut newly_disabled = HashSet::new();
1507 let build = loop {
1508 for file in &mut files {
1509 let suffix = if file.path == root_file {
1510 root_suffix.as_str()
1511 } else {
1512 ""
1513 };
1514 write_rendered(file, &state, suffix, &disabled, &newly_disabled)?;
1515 }
1516 if !files.iter().any(|f| f.path == root_file) {
1517 state.write(&root_file, &format!("{root_source}{root_suffix}"))?;
1518 }
1519 if rounds == 0 {
1520 state.settle(&workspace)?;
1521 }
1522 note(if rounds == 0 {
1523 "building the instrumented crate"
1524 } else {
1525 "rebuilding without the sites that failed to compile"
1526 });
1527 let output = cargo_build()?;
1528 let names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
1529 let build = parse_build_output(&String::from_utf8_lossy(&output.stdout), &names);
1530 if output.status.success() {
1531 if let Some(fingerprint) = &repair_fingerprint {
1532 let cached_entries: Vec<repair_cache::CachedSite> = files
1533 .iter()
1534 .flat_map(|file| {
1535 file.sites
1536 .iter()
1537 .enumerate()
1538 .filter(|(_, site)| disabled.contains(&site.id))
1539 .map(|(site_index, site)| repair_cache::CachedSite {
1540 file: file.display.clone(),
1541 site_index,
1542 start: site.start,
1543 end: site.end,
1544 text: site.text.clone(),
1545 kind: format!("{:?}", site.kind),
1546 reason: repairs.get(&site.id).cloned().unwrap_or_default(),
1547 })
1548 })
1549 .collect();
1550 let _ = repair_cache::save(&work, fingerprint, &cached_entries);
1551 }
1552 break build;
1553 }
1554 let diagnostics = || {
1555 [
1556 build.diagnostics.join("\n"),
1557 String::from_utf8_lossy(&output.stderr).into_owned(),
1558 ]
1559 .into_iter()
1560 .filter(|part| !part.trim().is_empty())
1561 .collect::<Vec<_>>()
1562 .join("\n")
1563 };
1564 if build.errors.is_empty() {
1565 bail!("the build failed:\n{build_note}{}", diagnostics());
1566 }
1567 if build
1568 .errors
1569 .iter()
1570 .any(|error| is_non_probe_error(error, &files, ©))
1571 {
1572 bail!(
1573 "the build failed with an error unrelated to instrumentation:\n{build_note}{}",
1574 diagnostics()
1575 );
1576 }
1577 rounds += 1;
1578 let before = disabled.len();
1579 let mut blamed_now: HashSet<u32> = HashSet::new();
1580 for error in &build.errors {
1581 let blamed = blame_error(error, &files, ©, &disabled);
1582 if std::env::var_os("TMT_DEBUG").is_some() {
1583 eprintln!(
1584 "tmt: debug: blaming {blamed:?} for\n{}",
1585 report::sanitize_terminal(&error.rendered)
1586 );
1587 }
1588 for id in blamed {
1589 repairs
1590 .entry(id)
1591 .or_insert_with(|| error.rendered.lines().next().unwrap_or("").to_string());
1592 blamed_now.insert(id);
1593 }
1594 }
1595 disabled.extend(blamed_now.iter().copied());
1596 newly_disabled = blamed_now;
1597 if disabled.len() == before || rounds > MAX_REPAIR_ROUNDS {
1598 bail!(
1599 "the crate does not build after instrumentation.\n\
1600 {build_note}Does `cargo test --no-run` pass on the original for the same targets?\n{}",
1601 diagnostics()
1602 );
1603 }
1604 };
1605 let built_sources = if options.rebuild || options.source_only || options.audit.is_some() {
1606 let behind_cargo = features_from_flags(
1611 std::env::vars_os()
1612 .filter(|(name, _)| name.to_string_lossy().ends_with("RUSTFLAGS"))
1613 .map(|(_, value)| Some(value)),
1614 ) || build.build_scripts.iter().any(|script| {
1615 script["cfgs"].as_array().is_some_and(|cfgs| {
1616 cfgs.iter()
1617 .any(|cfg| cfg.as_str().is_some_and(|cfg| cfg.contains("feature")))
1618 })
1619 }) || configuration_names_a_feature(
1620 ©,
1621 std::env::var_os("CARGO_HOME").map(PathBuf::from),
1622 );
1623 BuiltSources::from_artifacts(&build.artifacts, &build.features, !behind_cargo, ©)
1624 } else {
1625 BuiltSources::default()
1626 };
1627 output_fixture::stage(&workspace, &work, &build_target, &options.output_fixtures)?;
1628 let checkpoint_path = report.analysis.checkpoint.as_deref();
1629 let checkpoint = checkpoint_path.map(Checkpoint::open).transpose()?;
1630 let doc_packages = test_packages
1631 .iter()
1632 .filter(|p| options.doc && p.targets.iter().any(|target| target.doctest));
1633 if build.test_binaries.is_empty() && doc_packages.clone().next().is_none() {
1634 bail!("{build_note}`{}` has no test binaries", package.name);
1635 }
1636
1637 let mut session = Session {
1639 progress: options.progress,
1640 serial_timeout_rechecks: options.serial_timeout_rechecks,
1641 package_dir,
1642 binaries: vec![],
1643 };
1644 let wrapper = selection
1645 .wrapper
1646 .as_ref()
1647 .map(|path| {
1648 let relative = wrapper_relative(path)?;
1649 let copied = copy.join(&relative);
1650 if !copied.is_file() {
1651 bail!(
1652 "test wrapper is missing from the work copy: {}",
1653 copied.display()
1654 );
1655 }
1656 Ok(copied)
1657 })
1658 .transpose()?;
1659 let mut runners: Vec<(String, Runner, PathBuf)> = vec![];
1660 let root_test_exe = |built: &BuildOutput| {
1661 built
1662 .test_binaries
1663 .iter()
1664 .find(|(name, _, owner, kind)| {
1665 *name == root_target.name && *owner == package.name && *kind == root_target.kind
1666 })
1667 .map(|(_, exe, _, _)| exe.clone())
1668 };
1669 let root_exe = (!witness_candidates.is_empty())
1670 .then(|| root_test_exe(&build))
1671 .flatten();
1672 let mut discovered_tests: Vec<String> = vec![];
1673 let mut empty_bin_targets: Vec<(String, String)> = vec![];
1674 if let Some(nextest) = &options.nextest {
1675 let mut flags: Vec<_> = test_packages
1676 .iter()
1677 .flat_map(|p| ["-p".to_owned(), p.name.clone()])
1678 .collect();
1679 flags.extend(options.cargo.flags());
1680 runners.push((
1681 "nextest".to_owned(),
1682 Runner::Nextest {
1683 copy: copy.clone(),
1684 target_dir: build_target.clone(),
1685 profile: nextest.profile.clone(),
1686 opt_level: options.opt_level,
1687 flags,
1688 },
1689 session.package_dir.clone(),
1690 ));
1691 } else {
1692 for (name, exe, owner, kind) in build.test_binaries {
1693 if !artifact_target_selected(&name, &kind, selection) {
1694 continue;
1695 }
1696 let owner_package = test_packages
1697 .iter()
1698 .find(|p| p.name == owner)
1699 .expect("binaries are filtered by these packages");
1700 let cwd = in_copy(
1701 owner_package
1702 .manifest_path
1703 .parent()
1704 .expect("manifest has a parent"),
1705 )?;
1706 if selection.enabled() {
1707 let all = list_tests(&exe, &cwd, &work, false, true, work_lock.as_deref())?;
1708 if all.is_empty() && kind.first().map(String::as_str) == Some("bin") {
1709 empty_bin_targets.push((owner.clone(), name.clone()));
1710 }
1711 let ignored = list_tests(&exe, &cwd, &work, true, true, work_lock.as_deref())?;
1712 for test in all {
1713 let was_ignored = ignored.contains(&test);
1714 if (!was_ignored || selection.include_ignored)
1715 && !selection.exclude.iter().any(|name| name == &test)
1716 {
1717 discovered_tests.push(test.clone());
1718 }
1719 if !selection.matches_test(&test, was_ignored) {
1720 continue;
1721 }
1722 runners.push((
1723 format!("{owner}::{}::{name}::{test}", kind.join("+")),
1724 Runner::Isolated {
1725 exe: exe.clone(),
1726 test,
1727 ignored: was_ignored,
1728 wrapper: wrapper.clone(),
1729 },
1730 cwd.clone(),
1731 ));
1732 }
1733 continue;
1734 }
1735 let name = if owner == package.name {
1737 name
1738 } else {
1739 format!("{owner}::{name}")
1740 };
1741 runners.push((name, Runner::Exe(exe), cwd));
1742 }
1743 }
1744 if selection.enabled() && runners.is_empty() {
1745 let hint = no_tests_matched_hint(
1746 &test_packages,
1747 selection,
1748 &empty_bin_targets,
1749 &discovered_tests,
1750 );
1751 bail!("{build_note}no tests matched the requested selection{hint}");
1752 }
1753 let selected_tests = selection.enabled().then(|| report::TestSelection {
1754 build_scope,
1755 wrapper: selection
1756 .wrapper
1757 .as_ref()
1758 .map(|path| path.display().to_string()),
1759 tests: runners.iter().map(|(name, _, _)| name.clone()).collect(),
1760 });
1761 for owner in doc_packages {
1762 let doc = Runner::Doc {
1763 copy: copy.clone(),
1764 target_dir: build_target.clone(),
1765 package: owner.name.clone(),
1766 opt_level: options.opt_level,
1767 flags: options.cargo.flags(),
1768 };
1769 let name = if owner.name == package.name {
1770 "doc tests".to_owned()
1771 } else {
1772 format!("{}::doc tests", owner.name)
1773 };
1774 let cwd = in_copy(owner.manifest_path.parent().expect("manifest has a parent"))?;
1775 runners.push((name, doc, cwd));
1776 }
1777 report.analysis.test_selection = selected_tests;
1778 let identity = if checkpoint.is_some() {
1779 let mut build_inputs: Vec<_> = build
1780 .build_scripts
1781 .iter()
1782 .map(serde_json::Value::to_string)
1783 .collect();
1784 build_inputs.sort();
1785 let settings = serde_json::json!({
1788 "build_scripts": build_inputs,
1789 "analysis": &report.analysis, "package": &package.name, "jobs": effective_jobs,
1790 "verify": options.verify, "audit": options.audit, "effects": options.effects,
1791 "all_files": options.all_files, "build_scope": build_scope,
1792 "runners": runners.iter().map(|(name, runner, cwd)| (name, runner.executable(), cwd)).collect::<Vec<_>>()
1793 });
1794 let mut inputs = BTreeSet::new();
1795 for (root, artifacts) in &build.artifacts {
1796 inputs.insert(root.clone());
1797 if let Some(dependencies) = artifacts
1798 .iter()
1799 .map(|artifact| artifact_inputs(artifact, root, ©))
1800 .find(|deps| !deps.is_empty())
1801 {
1802 inputs.extend(dependencies);
1803 } else {
1804 inputs.extend(artifacts.iter().cloned());
1807 }
1808 }
1809 inputs.extend(
1810 build
1811 .build_scripts
1812 .iter()
1813 .filter_map(|script| script.get("out_dir")?.as_str().map(PathBuf::from)),
1814 );
1815 inputs.retain(|path| !path.starts_with(©));
1818 inputs.extend(
1819 options
1820 .output_fixtures
1821 .iter()
1822 .map(|fixture| build_target.join(&fixture.to)),
1823 );
1824 inputs.extend(
1825 options
1826 .stage_external
1827 .iter()
1828 .map(|entry| normalize(©.join(&entry.rel))),
1829 );
1830 Some(crate::campaign_identity::compute(
1831 ©,
1832 &settings,
1833 inputs,
1834 options.nextest.is_some(),
1835 )?)
1836 } else {
1837 None
1838 };
1839 let marks = marks_dir(&work)?;
1844 let baseline_jobs = if selection.enabled() {
1845 options.baseline_jobs
1846 } else {
1847 1
1848 };
1849 if options.progress {
1850 eprintln!(
1851 "tmt: baselines: 0/{} completed ({} workers)",
1852 runners.len(),
1853 baseline_jobs
1854 );
1855 }
1856
1857 let baseline_budget = options
1858 .baseline_timeout_seconds
1859 .map(Duration::from_secs)
1860 .unwrap_or(DEFAULT_BASELINE_TIMEOUT);
1861 let baseline_stage = if options.source_only {
1862 "baseline_untraced"
1863 } else {
1864 "baseline_trace"
1865 };
1866 let diagnostic_path = work.join("baseline-timeout.json");
1867 let _ = fs::remove_file(&diagnostic_path);
1868 let completed_baselines = std::sync::atomic::AtomicUsize::new(0);
1869 let completed_timings = std::sync::Mutex::new(Vec::<report::BaselineTimingEntry>::new());
1870 let total_baselines = runners.len();
1871 let wrapper_grace_counter = selection
1872 .wrapper
1873 .as_ref()
1874 .map(|_| Arc::new(runner::WrapperGraceCounter::default()));
1875
1876 #[derive(Debug)]
1877 enum BaselinePoolError {
1878 Timeout(Box<report::BaselineTimeoutDiagnostic>),
1879 Failed(Box<report::BaselineFailureDiagnostic>),
1880 }
1881
1882 impl std::fmt::Display for BaselinePoolError {
1883 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1884 match self {
1885 Self::Timeout(diag) => write!(
1886 f,
1887 "baseline timeout in stage `{}` for `{}`",
1888 diag.stage, diag.runner
1889 ),
1890 Self::Failed(diag) => write!(f, "the tests in `{}` {}", diag.runner, diag.reason),
1891 }
1892 }
1893 }
1894
1895 impl std::error::Error for BaselinePoolError {}
1896
1897 let baseline_result = progress::track_baselines(options.progress, runners.len(), |progress| {
1898 run_pool(runners.len(), baseline_jobs, |slot| {
1899 let index = slot;
1900 let (name, runner, cwd) = runners[index].clone();
1901 let result = (|| {
1902 let trace_path = work.join(format!("trace-{index}.tsv"));
1903 let _ = fs::remove_file(&trace_path);
1904 let mut bin = TestBinary {
1905 name,
1906 cwd,
1907 marks: marks.clone(),
1908 git_ceiling: work.clone(),
1909 work_lock: work_lock.clone(),
1910 tests: BTreeSet::new(),
1911 runner,
1912 baseline: Duration::ZERO,
1913 untraced_baseline: None,
1914 timeout_diagnostic: std::sync::Once::new(),
1915 traced: Duration::ZERO,
1916 timeout: options.timeout_seconds.map(Duration::from_secs),
1917 wrapper_grace: options.wrapper_grace,
1918 wrapper_grace_counter: wrapper_grace_counter.clone(),
1919 report_slow: options.progress,
1920 filtered_timings: Default::default(),
1921 trace: Trace::default(),
1922 effects_baseline: std::sync::OnceLock::new(),
1923 };
1924 session.note(&format!("tracing `{}`", bin.name));
1925 let started = Instant::now();
1926 let trace_env = trace_path.to_string_lossy().into_owned();
1927 let trace = [("TMT_TRACE", trace_env.as_str())];
1928 let isolated_test = match &bin.runner {
1929 Runner::Isolated { test, .. } => Some(test.clone()),
1930 _ => None,
1931 };
1932 match run_baseline(
1933 &bin,
1934 if options.source_only { &[] } else { &trace },
1935 baseline_budget,
1936 &work.join(format!("baseline-{index}.log")),
1937 false,
1938 )? {
1939 BaselineRun::Passed => {}
1940 BaselineRun::TimedOut {
1941 elapsed,
1942 log,
1943 log_summary,
1944 } => {
1945 let log_path =
1946 log.unwrap_or_else(|| work.join(format!("baseline-{index}.log")));
1947 let (rerun_args, exclude_args) = match &bin.runner {
1948 Runner::Isolated { test, .. } => (
1949 vec!["--include-test".to_string(), test.clone()],
1950 vec!["--exclude-test".to_string(), test.clone()],
1951 ),
1952 Runner::Exe(_) => {
1953 let target = bin
1954 .name
1955 .rsplit_once("::")
1956 .map_or(bin.name.as_str(), |(_, t)| t)
1957 .to_string();
1958 (vec!["--test-target".to_string(), target], vec![])
1959 }
1960 Runner::Nextest { .. } | Runner::Doc { .. } => (vec![], vec![]),
1961 };
1962 let completed =
1963 completed_baselines.load(std::sync::atomic::Ordering::Acquire);
1964 let diagnostic = report::BaselineTimeoutDiagnostic {
1965 schema_version: report::SCHEMA_VERSION,
1966 package: package.name.clone(),
1967 stage: baseline_stage,
1968 runner: bin.name.clone(),
1969 test: isolated_test,
1970 elapsed_seconds: round_millis(elapsed),
1971 budget_seconds: baseline_budget.as_secs(),
1972 completed_baselines: completed,
1973 total_baselines,
1974 partial_baseline: true,
1975 log: log_path,
1976 lines: options.lines.clone(),
1977 rerun_args,
1978 exclude_args,
1979 completed_timings: Vec::new(),
1980 log_summary,
1981 };
1982 return Err(BaselinePoolError::Timeout(Box::new(diagnostic)).into());
1983 }
1984 BaselineRun::Failed {
1985 reason,
1986 elapsed,
1987 log,
1988 log_summary,
1989 } => {
1990 let completed =
1991 completed_baselines.load(std::sync::atomic::Ordering::Acquire);
1992 let diagnostic = report::BaselineFailureDiagnostic {
1993 schema_version: report::SCHEMA_VERSION,
1994 package: package.name.clone(),
1995 stage: baseline_stage,
1996 runner: bin.name.clone(),
1997 test: isolated_test,
1998 reason,
1999 elapsed_seconds: round_millis(elapsed),
2000 completed_baselines: completed,
2001 total_baselines,
2002 log,
2003 completed_timings: Vec::new(),
2004 log_summary,
2005 };
2006 return Err(BaselinePoolError::Failed(Box::new(diagnostic)).into());
2007 }
2008 }
2009 bin.traced = started.elapsed();
2010 bin.baseline = bin.traced;
2011 if options.source_only {
2012 bin.untraced_baseline = Some(BaselineTiming::Completed(bin.baseline));
2013 }
2014 if !options.source_only && bin.traced > SLOW_TRACE {
2017 let started = Instant::now();
2018 match run_baseline(
2019 &bin,
2020 &[],
2021 bin.traced,
2022 &work.join(format!("baseline-{index}-untraced.log")),
2023 true,
2024 )? {
2025 BaselineRun::Passed => {
2026 let elapsed = started.elapsed();
2027 bin.untraced_baseline = Some(BaselineTiming::Completed(elapsed));
2028 bin.baseline = elapsed;
2029 }
2030 BaselineRun::TimedOut { .. } => {
2031 bin.untraced_baseline = Some(BaselineTiming::StillRunning(bin.traced));
2032 }
2033 BaselineRun::Failed {
2034 reason,
2035 elapsed,
2036 log,
2037 log_summary,
2038 } => {
2039 let completed =
2040 completed_baselines.load(std::sync::atomic::Ordering::Acquire);
2041 let diagnostic = report::BaselineFailureDiagnostic {
2042 schema_version: report::SCHEMA_VERSION,
2043 package: package.name.clone(),
2044 stage: "baseline_untraced",
2045 runner: bin.name.clone(),
2046 test: isolated_test,
2047 reason,
2048 elapsed_seconds: round_millis(elapsed),
2049 completed_baselines: completed,
2050 total_baselines,
2051 log,
2052 completed_timings: Vec::new(),
2053 log_summary,
2054 };
2055 return Err(BaselinePoolError::Failed(Box::new(diagnostic)).into());
2056 }
2057 }
2058 }
2059 let text = match fs::read_to_string(&trace_path) {
2062 Ok(text) => text,
2063 Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
2064 Err(err) => bail!("cannot read the trace of `{}`: {err}", bin.name),
2065 };
2066 bin.trace = Trace::parse(&text);
2067 if bin.trace.malformed_lines > 0 {
2068 bail!(
2069 "the trace of `{}` has {} malformed lines; not drawing conclusions from it",
2070 bin.name,
2071 bin.trace.malformed_lines
2072 );
2073 }
2074 if let Runner::Exe(exe) = &bin.runner {
2075 bin.tests =
2076 list_tests(exe, &bin.cwd, &work, false, false, work_lock.as_deref())?;
2077 }
2078 if let Ok(mut timings) = completed_timings.lock() {
2079 timings.push(report::BaselineTimingEntry {
2080 runner: bin.name.clone(),
2081 test: isolated_test,
2082 elapsed_seconds: round_millis(bin.baseline),
2083 });
2084 }
2085 completed_baselines.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
2086 Ok(bin)
2087 })();
2088 progress.complete(if result.is_ok() {
2089 progress::Outcome::Survived
2090 } else {
2091 progress::Outcome::Failed
2092 });
2093 result
2094 })
2095 });
2096 let collect_completed_timings = || -> Vec<report::BaselineTimingEntry> {
2097 let mut timings = completed_timings
2098 .lock()
2099 .unwrap_or_else(|e| e.into_inner())
2100 .clone();
2101 timings.sort_by(|a, b| {
2102 b.elapsed_seconds
2103 .total_cmp(&a.elapsed_seconds)
2104 .then_with(|| a.runner.cmp(&b.runner))
2105 });
2106 timings
2107 };
2108 session.binaries = match baseline_result {
2109 Ok(binaries) => binaries,
2110 Err(err) => match err.downcast::<BaselinePoolError>() {
2111 Ok(BaselinePoolError::Timeout(mut diagnostic)) => {
2112 diagnostic.completed_baselines =
2115 completed_baselines.load(std::sync::atomic::Ordering::Acquire);
2116 diagnostic.completed_timings = collect_completed_timings();
2117 let write_status = serde_json::to_string_pretty(&diagnostic)
2118 .map_err(anyhow::Error::from)
2119 .and_then(|json| {
2120 use std::io::Write as _;
2121 static NEXT_DIAG_TMP: std::sync::atomic::AtomicUsize =
2122 std::sync::atomic::AtomicUsize::new(0);
2123 let seq = NEXT_DIAG_TMP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2124 let tmp = work.join(format!(
2125 ".baseline-timeout.{}.{seq}.tmp",
2126 std::process::id()
2127 ));
2128 let mut file = fs::OpenOptions::new()
2129 .write(true)
2130 .create_new(true)
2131 .open(&tmp)?;
2132 if let Err(err) = file
2133 .write_all(format!("{json}\n").as_bytes())
2134 .and_then(|()| file.flush())
2135 {
2136 drop(file);
2137 let _ = fs::remove_file(&tmp);
2138 return Err(err.into());
2139 }
2140 drop(file);
2141 if let Err(rename_err) = fs::rename(&tmp, &diagnostic_path) {
2142 let _ = fs::remove_file(&tmp);
2143 return Err(rename_err.into());
2144 }
2145 Ok(())
2146 });
2147 let diag_note = match write_status {
2148 Ok(()) => format!("diagnostic: {}", diagnostic_path.display()),
2149 Err(write_err) => format!(
2150 "failed to write diagnostic {}: {write_err}",
2151 diagnostic_path.display()
2152 ),
2153 };
2154 let subject = match &diagnostic.test {
2155 Some(test) => format!("`{}` (test `{test}`)", diagnostic.runner),
2156 None => format!("`{}`", diagnostic.runner),
2157 };
2158 let hint =
2159 if !diagnostic.rerun_args.is_empty() && !diagnostic.exclude_args.is_empty() {
2160 format!(
2161 "; rerun separately with `{}` or exclude with `{}`",
2162 diagnostic.rerun_args.join(" "),
2163 diagnostic.exclude_args.join(" ")
2164 )
2165 } else if !diagnostic.rerun_args.is_empty() {
2166 format!(
2167 "; rerun separately with `{}`",
2168 diagnostic.rerun_args.join(" ")
2169 )
2170 } else {
2171 String::new()
2172 };
2173 let timings_section = format_baseline_timings_section(
2174 &diagnostic.completed_timings,
2175 &diagnostic.runner,
2176 diagnostic.elapsed_seconds,
2177 "timed out",
2178 diagnostic.total_baselines,
2179 );
2180 let summary_section = format_log_summary_section(&diagnostic.log_summary);
2181 let message = format!(
2182 "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}",
2183 diagnostic.stage,
2184 diagnostic.elapsed_seconds,
2185 diagnostic.budget_seconds,
2186 diagnostic.completed_baselines,
2187 diagnostic.total_baselines,
2188 diagnostic.log.display()
2189 );
2190 return Err(BaselineError::Timeout {
2191 diagnostic,
2192 wrapper_grace_outcomes: wrapper_grace_counter.as_ref().map(|c| c.snapshot()),
2193 message,
2194 }
2195 .into());
2196 }
2197 Ok(BaselinePoolError::Failed(mut diagnostic)) => {
2198 diagnostic.completed_baselines =
2199 completed_baselines.load(std::sync::atomic::Ordering::Acquire);
2200 diagnostic.completed_timings = collect_completed_timings();
2201 let timings_section = format_baseline_timings_section(
2202 &diagnostic.completed_timings,
2203 &diagnostic.runner,
2204 diagnostic.elapsed_seconds,
2205 "failed",
2206 diagnostic.total_baselines,
2207 );
2208 let summary_section = format_log_summary_section(&diagnostic.log_summary);
2209 let message = format!(
2210 "the tests in `{}` {}; full output: {}{timings_section}{summary_section}",
2211 diagnostic.runner,
2212 diagnostic.reason,
2213 diagnostic.log.display()
2214 );
2215 return Err(BaselineError::Failed {
2216 diagnostic,
2217 wrapper_grace_outcomes: wrapper_grace_counter.as_ref().map(|c| c.snapshot()),
2218 message,
2219 }
2220 .into());
2221 }
2222 Err(other) => return Err(other),
2223 },
2224 };
2225
2226 for file in &files {
2228 for site in &file.sites {
2229 if disabled.contains(&site.id) {
2230 let fallback = options.rebuild
2231 && !matches!(site.kind, SiteKind::Body { .. })
2232 && !instrument::source_mutants(site).is_empty();
2233 match site.kind {
2234 SiteKind::Body { .. } => report.unviable_mutants += 1,
2235 _ if fallback => {}
2236 _ => report.skipped_sites += 1,
2237 }
2238 report.skipped.push(report::SkippedSite::new(
2239 report::location(&file.display, site),
2240 file.lines.position(&file.original, site.end),
2241 if fallback {
2242 report::SkipReason::ProbeReplacedBySourceRebuild
2243 } else {
2244 report::SkipReason::ProbeCompileError
2245 },
2246 repairs.get(&site.id).cloned(),
2247 ));
2248 }
2249 }
2250 if !options.rebuild && !options.source_only {
2251 report.skipped.extend(file.rebuild_sites.iter().map(|site| {
2252 report::SkippedSite::new(
2253 report::location(&file.display, site),
2254 file.lines.position(&file.original, site.end),
2255 report::SkipReason::RequiresSourceRebuild,
2256 None,
2257 )
2258 }));
2259 }
2260 }
2261 if let (Some(checkpoint), Some(identity)) = (&checkpoint, &identity) {
2262 checkpoint.start(
2263 identity,
2264 serde_json::json!({
2265 "package": &package.name, "analysis": &report.analysis,
2266 "runners": session.binaries.iter().map(|bin| &bin.name).collect::<Vec<_>>(),
2267 "jobs": effective_jobs, "tool_version": env!("CARGO_PKG_VERSION")
2268 }),
2269 )?;
2270 }
2271 let phase = |name: &str, keys: Vec<String>| {
2272 checkpoint
2273 .as_ref()
2274 .zip(identity.as_deref())
2275 .map(|(checkpoint, identity)| checkpoint.begin(name, identity, keys))
2276 .transpose()
2277 };
2278 let probe_phase = |name: &str, jobs: &[Job]| -> Result<Option<Phase<'_>>> {
2279 if checkpoint.is_none() {
2280 return Ok(None);
2281 }
2282 let locations: BTreeMap<_, _> = files
2283 .iter()
2284 .flat_map(|file| {
2285 file.sites
2286 .iter()
2287 .map(|site| (site.id, (&file.display, site.line, site.column, &site.text)))
2288 })
2289 .collect();
2290 let keys = jobs
2291 .iter()
2292 .map(|job| {
2293 let tests = job
2294 .tests
2295 .iter()
2296 .map(|(bin, selected)| (&session.binaries[*bin].name, selected))
2297 .collect::<Vec<_>>();
2298 serde_json::to_string(&(locations.get(&job.site), job.mutation.encode(), tests))
2299 })
2300 .collect::<std::result::Result<Vec<_>, _>>()?;
2301 phase(name, keys)
2302 };
2303 let scratch = work.clone();
2304 let mut jobs: Vec<Job> = vec![];
2305 let mut not_evaluated: HashSet<u32> = HashSet::new();
2308 let mut site_work: Vec<SiteWork> = vec![];
2309 let mut effect_jobs: Vec<(usize, usize)> = vec![];
2311 for file in &files {
2312 let mut primitive_arith_spans: HashSet<(usize, usize)> = HashSet::new();
2315 let mut primitive_cmp_spans: HashSet<(usize, usize)> = HashSet::new();
2316 let mut cast_probe_spans: std::collections::HashMap<(usize, usize), (u32, u32)> =
2317 std::collections::HashMap::new();
2318 for other in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
2319 if matches!(other.kind, SiteKind::Cmp { .. })
2320 && session
2321 .binaries
2322 .iter()
2323 .any(|b| b.trace.bounds.contains_key(&other.id))
2324 {
2325 primitive_cmp_spans.insert((other.start, other.end));
2326 }
2327 if let SiteKind::Arith { cast_probes, .. } = &other.kind {
2328 let seen = session.merged(|t| t.arith.get(&other.id), plan::ArithObs::merge);
2329 if !seen.opaque && (seen.same || seen.differs || seen.same2 || seen.differs2) {
2330 primitive_arith_spans.insert((other.start, other.end));
2331 }
2332 for &(slot, start, end) in cast_probes {
2333 cast_probe_spans
2334 .entry((start, end))
2335 .or_insert((other.id, slot));
2336 }
2337 }
2338 }
2339 let primitive = |from: usize, to: usize| {
2340 let Some(mut text) = file.original.get(from..to) else {
2341 return false;
2342 };
2343 let mut start = from;
2344 loop {
2345 let trimmed = text.trim_start();
2346 start += text.len() - trimmed.len();
2347 text = trimmed.trim_end();
2348 if text.starts_with('(')
2349 && text.ends_with(')')
2350 && matches!(syn::parse_str::<syn::Expr>(text), Ok(syn::Expr::Paren(_)))
2351 && let Some(inner) = text
2352 .strip_prefix('(')
2353 .and_then(|inner| inner.strip_suffix(')'))
2354 {
2355 start += 1;
2356 text = inner;
2357 } else {
2358 break;
2359 }
2360 }
2361 primitive_arith_spans.contains(&(start, start + text.len()))
2362 };
2363 let cast_bounds = |from: usize, to: usize| -> Option<(i128, i128)> {
2364 let &(owner_id, slot) = cast_probe_spans.get(&(from, to))?;
2365 let mut recorded = session
2366 .binaries
2367 .iter()
2368 .filter_map(|b| b.trace.cast_bounds.get(&(owner_id, slot)));
2369 let first = recorded.next()?;
2370 if recorded.all(|other| other == first) {
2371 *first
2372 } else {
2373 None
2374 }
2375 };
2376 let primitive_cmp = |from: usize, to: usize| primitive_cmp_spans.contains(&(from, to));
2377 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
2378 let plan = match session.plan(
2379 &file.display,
2380 site,
2381 options.verify,
2382 &primitive,
2383 &primitive_cmp,
2384 &cast_bounds,
2385 ) {
2386 Planned::Unreached if beyond.contains(&site.id) => continue,
2389 Planned::Unreached => {
2390 let at = report::location(&file.display, site);
2392 if report.unreached.last() != Some(&at) {
2393 report.unreached.push(at);
2394 }
2395 continue;
2396 }
2397 Planned::Nothing => continue,
2398 Planned::NotEvaluated => {
2399 not_evaluated.insert(site.id);
2400 continue;
2401 }
2402 Planned::Plan(plan) => plan,
2403 };
2404 let mut add =
2405 |mutation: Mutation, tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>| {
2406 jobs.push(session.job(site.id, mutation, tests_of));
2407 jobs.len() - 1
2408 };
2409 let gaps = plan
2410 .gaps
2411 .into_iter()
2412 .map(
2413 |PlannedGap {
2414 finding,
2415 survivors,
2416 constant_expr,
2417 }| {
2418 let confirm = if options.verify {
2421 survivors
2422 .into_iter()
2423 .map(|m| add(m, &*plan.reaching))
2424 .collect()
2425 } else {
2426 vec![]
2427 };
2428 (finding, confirm, constant_expr)
2429 },
2430 )
2431 .collect();
2432 let infected = &plan.infected;
2433 let runs = plan
2434 .run
2435 .iter()
2436 .map(|m| (*m, add(*m, &|bin| infected(bin, *m))))
2437 .collect();
2438 site_work.push(SiteWork {
2439 file: &file.display,
2440 site,
2441 gaps,
2442 constant: plan.constant,
2443 cannot_differ: plan.cannot_differ,
2444 redundant_logic_swap: plan.redundant_logic_swap,
2445 runs,
2446 });
2447 }
2448 }
2449 session.note(&format!(
2450 "running {} mutants on {} thread(s)",
2451 jobs.len(),
2452 options.jobs.max(1)
2453 ));
2454 let probe_checkpoint = probe_phase("probe", &jobs)?;
2455 let mut results =
2456 session.run_jobs(&jobs, options.jobs, "mutants", probe_checkpoint.as_ref())?;
2457 for result in &results {
2458 report.timeout_rechecks.include(result);
2459 }
2460
2461 if let Some(wanted) = options.audit {
2464 report.audit = Some(run_audit_phase(
2465 &session,
2466 &files,
2467 &jobs,
2468 &mut results,
2469 &mut report.timeout_rechecks,
2470 &scratch,
2471 wanted,
2472 options.jobs,
2473 &probe_phase,
2474 )?);
2475 }
2476 #[derive(Clone, Copy, PartialEq, Eq)]
2480 enum EarlierVerdict {
2481 Killed,
2482 Survived,
2483 Unknown,
2484 }
2485 let mut earlier_verdict: BTreeMap<usize, EarlierVerdict> = BTreeMap::new();
2486 let asked: Vec<usize> = site_work
2487 .iter()
2488 .filter(|item| beyond.contains(&item.site.id))
2489 .flat_map(|item| {
2490 item.gaps
2491 .iter()
2492 .flat_map(|(_, confirm, _)| confirm.iter().copied())
2493 .chain(
2494 item.runs
2495 .iter()
2496 .filter(|(m, _)| !(*m == Mutation::LogicSwap && item.redundant_logic_swap))
2497 .map(|(_, job)| *job),
2498 )
2499 })
2500 .filter(|job| results[*job].survived.is_some())
2501 .collect();
2502 if !asked.is_empty() {
2503 let revision = report::short_revision(options.since.as_deref().unwrap_or_default());
2504 session.note(&format!(
2505 "running {} surviving mutants against the tests as they were at {revision}",
2506 asked.len()
2507 ));
2508 let suffix = |file: &SourceFile| {
2509 if file.path == root_file {
2510 root_suffix.as_str()
2511 } else {
2512 ""
2513 }
2514 };
2515 let earlier: Option<Vec<(&SourceFile, String)>> = tests_changed
2517 .iter()
2518 .map(|(path, hunks)| {
2519 let file = files.iter().find(|file| file.path == *path)?;
2520 let rendered = file.rendered.as_ref()?;
2521 let mut places = hunks
2522 .iter()
2523 .map(|hunk| {
2524 let (from, to) = scope::range_of(&file.original, hunk);
2525 Some((rendered.copied(from, to)?, hunk.old.as_str()))
2526 })
2527 .collect::<Option<Vec<_>>>()?;
2528 places.sort_by_key(|((from, _), _)| std::cmp::Reverse(*from));
2529 let mut text = rendered.text.clone();
2530 for ((from, to), old) in places {
2531 text.replace_range(from..to, old);
2532 }
2533 Some((file, text))
2534 })
2535 .collect();
2536 let attempted = if let Some(earlier) = earlier {
2537 let attempted = (|| -> Result<Option<Vec<JobResult>>> {
2538 for (file, text) in &earlier {
2539 state.write(&file.path, &format!("{text}{}", suffix(file)))?;
2540 }
2541 if !cargo_build()?.status.success() {
2542 session.note(
2543 "the tests as they were do not build with the code as it is: what they found out is not known",
2544 );
2545 return Ok(None);
2546 }
2547 let all: Vec<&TestBinary> = session.binaries.iter().collect();
2549 if run_source_tests(&all)? != Outcome::Pass {
2550 session.note(
2551 "the tests as they were fail on the code as it is: what they found out is not known",
2552 );
2553 return Ok(None);
2554 }
2555 let against_all: Vec<Job> = asked
2556 .iter()
2557 .map(|job| Job {
2558 site: jobs[*job].site,
2559 mutation: jobs[*job].mutation,
2560 tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
2561 })
2562 .collect();
2563 session
2564 .run_jobs(&against_all, options.jobs, "mutants, earlier tests", None)
2565 .map(Some)
2566 })();
2567 for (file, _) in &earlier {
2569 let rendered = file.rendered.as_ref().expect("rendered before building");
2570 state.write(&file.path, &format!("{}{}", rendered.text, suffix(file)))?;
2571 }
2572 if !cargo_build()?.status.success() {
2573 bail!("the crate does not build once its tests are put back as they are");
2574 }
2575 attempted
2576 } else {
2577 session.note(
2578 "not all changed test files could be restored as they were: what they found out is not known",
2579 );
2580 Ok(None)
2581 };
2582 if let Some(again) = attempted? {
2583 for (job, result) in asked.iter().zip(again) {
2584 let verdict = if result.unable || result.unconfirmed_timeout {
2585 EarlierVerdict::Unknown
2586 } else if result.survived.is_none() {
2587 EarlierVerdict::Killed
2588 } else {
2589 EarlierVerdict::Survived
2590 };
2591 earlier_verdict.insert(*job, verdict);
2592 }
2593 } else {
2594 for job in &asked {
2595 earlier_verdict.insert(*job, EarlierVerdict::Unknown);
2596 }
2597 }
2598 }
2599 let unable = results
2600 .iter()
2601 .filter(|r| r.unable || r.unconfirmed_timeout)
2602 .count();
2603 not_evaluated.extend(
2604 jobs.iter()
2605 .zip(&results)
2606 .filter(|(_, result)| result.unable || result.unconfirmed_timeout)
2607 .map(|(job, _)| job.site),
2608 );
2609 if !options.rebuild {
2610 report.mutants_not_evaluated = not_evaluated.len();
2611 }
2612 report.mutants_run = results.len() - unable;
2613 report.mutants_killed = results.iter().filter(|r| r.survived.is_none()).count() - unable;
2614 report.mutants_survived = report.mutants_run - report.mutants_killed;
2615 report.mutants_timed_out = results
2616 .iter()
2617 .filter(|r| r.timed_out && !r.unconfirmed_timeout)
2618 .count();
2619
2620 let mut finding_run_survivors: Vec<usize> = vec![];
2623
2624 let confirmed = |w: &SiteWork| {
2627 w.gaps
2628 .iter()
2629 .all(|(_, confirm, _)| confirm.iter().all(|j| results[*j].survived.is_some()))
2630 };
2631 let constants: BTreeSet<(&str, usize, usize)> = site_work
2632 .iter()
2633 .filter(|w| w.cannot_differ || (w.constant && confirmed(w)))
2634 .map(|w| (w.file, w.site.start, w.site.end))
2635 .collect();
2636 for item in &site_work {
2637 let at = report::location(item.file, item.site);
2638 for (finding, confirm, constant_expr) in &item.gaps {
2639 let repeats = constant_expr
2642 .is_some_and(|(start, end)| constants.contains(&(item.file, start, end)));
2643 let survived_count = confirm
2644 .iter()
2645 .filter(|j| results[**j].survived.is_some())
2646 .count();
2647 if beyond.contains(&item.site.id) {
2648 let confirmed = confirm.iter().all(|j| results[*j].survived.is_some());
2650 let killed_before = confirm
2651 .iter()
2652 .any(|j| earlier_verdict.get(j) == Some(&EarlierVerdict::Killed));
2653 if confirmed && !repeats && killed_before {
2654 report.weakened.push(finding.at().clone());
2655 report.findings.push(finding.clone());
2656 finding_run_survivors.push(survived_count);
2657 } else if !confirmed {
2658 report.survivor_breakdown.unconfirmed_gap += survived_count;
2659 } else if repeats {
2660 report.survivor_breakdown.redundant_constant += survived_count;
2661 } else {
2662 for job in confirm {
2663 if results[*job].survived.is_some() {
2664 if earlier_verdict.get(job) == Some(&EarlierVerdict::Survived) {
2665 report.survivor_breakdown.preexisting_unchanged += 1;
2666 } else {
2667 report.survivor_breakdown.unchanged_not_compared += 1;
2668 }
2669 }
2670 }
2671 }
2672 continue;
2673 }
2674 match Prediction::of(confirm.iter().map(|j| &results[*j])) {
2675 Prediction::Refuted => {
2676 report.unstable.push(at.clone());
2677 report.survivor_breakdown.unconfirmed_gap += survived_count;
2678 }
2679 Prediction::Confirmed if !repeats => {
2680 report.findings.push(finding.clone());
2681 finding_run_survivors.push(survived_count);
2682 }
2683 Prediction::Confirmed => {
2684 report.survivor_breakdown.redundant_constant += survived_count;
2685 }
2686 Prediction::Unknown => {
2688 report.survivor_breakdown.unconfirmed_gap += survived_count;
2689 }
2690 }
2691 }
2692 if let SiteKind::Body {
2695 sole_expr: Some((start, end)),
2696 ..
2697 } = item.site.kind
2698 && constants.contains(&(item.file, start, end))
2699 {
2700 report.survivor_breakdown.redundant_constant += item
2701 .runs
2702 .iter()
2703 .filter(|(_, job)| results[*job].survived.is_some())
2704 .count();
2705 continue;
2706 }
2707 let mut survivors = vec![];
2708 let mut passing_tests = BTreeSet::new();
2709 for (mutation, job) in &item.runs {
2710 if let Some(tests) = &results[*job].survived {
2711 if *mutation == Mutation::LogicSwap && item.redundant_logic_swap {
2712 report.survivor_breakdown.redundant_constant += 1;
2713 continue;
2714 }
2715 if beyond.contains(&item.site.id) {
2716 match earlier_verdict.get(job) {
2717 Some(EarlierVerdict::Killed) => {}
2718 Some(EarlierVerdict::Survived) => {
2719 report.survivor_breakdown.preexisting_unchanged += 1;
2720 continue;
2721 }
2722 Some(EarlierVerdict::Unknown) | None => {
2723 report.survivor_breakdown.unchanged_not_compared += 1;
2724 continue;
2725 }
2726 }
2727 }
2728 survivors.push(report::describe(item.site, *mutation));
2729 passing_tests.extend(tests.iter().cloned());
2730 }
2731 }
2732 if !survivors.is_empty() {
2733 let first = item.runs.iter().find(|(mutation, job)| {
2735 !(*mutation == Mutation::LogicSwap && item.redundant_logic_swap)
2736 && results[*job].survived.is_some()
2737 && (!beyond.contains(&item.site.id)
2738 || earlier_verdict.get(job) == Some(&EarlierVerdict::Killed))
2739 });
2740 if beyond.contains(&item.site.id) {
2741 report.weakened.push(at.clone());
2742 }
2743 effect_jobs.push((report.findings.len(), first.expect("a survivor").1));
2744 finding_run_survivors.push(survivors.len());
2745 report.findings.push(Finding::AssertionGap {
2746 at,
2747 survivors,
2748 tests: passing_tests.into_iter().collect(),
2749 effects: vec![],
2750 effects_of: None,
2751 witness: None,
2752 });
2753 }
2754 }
2755
2756 if options.effects && !effect_jobs.is_empty() {
2758 run_effects_phase(
2759 &session,
2760 &files,
2761 &jobs,
2762 &effect_jobs,
2763 &scratch,
2764 options.jobs,
2765 &mut report.findings,
2766 )?;
2767 }
2768
2769 let mut built: Vec<(&SourceFile, &Site, instrument::SourceMutant, Option<usize>)> = vec![];
2773 let build_regular_mutants = options.rebuild || options.source_only;
2774 let mut index = 0;
2775 for file in &files {
2776 let retried = file.sites.iter().filter(|site| {
2779 (disabled.contains(&site.id) && !matches!(site.kind, SiteKind::Body { .. }))
2780 || not_evaluated.contains(&site.id)
2781 });
2782 for site in file.rebuild_sites.iter().chain(retried) {
2783 let mutants = source_mutants(file, site, true);
2784 if build_regular_mutants {
2785 built.extend(mutants.into_iter().filter_map(|mutant| {
2786 let selected = in_shard(index);
2787 index += 1;
2788 selected.then_some((file, site, mutant, None))
2789 }));
2790 } else {
2791 report.mutants_not_built += mutants.len();
2792 }
2793 }
2794 }
2795 if !build_regular_mutants {
2796 report.mutants_not_built += not_built_witnesses;
2797 }
2798 if let (Some(wanted), Some(audit)) = (options.audit, report.audit.as_mut()) {
2801 let mut twins = vec![];
2802 for file in &files {
2803 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
2804 let integers = session.binaries.iter().all(|bin| {
2806 let seen = bin.trace.merged(site.id);
2807 !seen.reached() || seen.valued()
2808 });
2809 let candidates = jobs_for_site(&jobs, site.id);
2810 let job_of = |mutation: Mutation| {
2811 candidates
2812 .clone()
2813 .find(|&index| jobs[index].mutation == mutation)
2814 };
2815 let mut compared = vec![];
2816 let mut mutants = instrument::source_mutants(site);
2817 instrument::keep_line_ends(&file.original, &mut mutants);
2818 for mutant in mutants {
2819 let job = mutations_like(site, &mutant, integers)
2821 .into_iter()
2822 .find_map(job_of);
2823 if let Some(job) = job {
2824 compared.push(job);
2825 twins.push((file, site, mutant, Some(job)));
2826 }
2827 }
2828 if let (SiteKind::Cmp { op, .. }, Some(job)) =
2831 (&site.kind, job_of(Mutation::Negate))
2832 && !compared.contains(&job)
2833 {
2834 let negated = instrument::SourceMutant {
2835 start: site.start,
2836 end: site.end,
2837 replacement: format!("!({})", site.text),
2838 what: op.symbol().to_string(),
2839 into: "!".to_string(),
2840 };
2841 twins.push((file, site, negated, Some(job)));
2842 }
2843 }
2844 }
2845 let chosen = spread(twins.len(), wanted);
2846 audit.rebuilt = chosen.len();
2847 let mut twins: Vec<Option<_>> = twins.into_iter().map(Some).collect();
2848 built.extend(chosen.into_iter().filter_map(|nth| twins[nth].take()));
2849 }
2850 let mut by_speed: Vec<&TestBinary> = session.binaries.iter().collect();
2851 by_speed.sort_by_key(|bin| bin.baseline);
2852 let root_mutant_suffix = if files.iter().any(|file| {
2854 file.path != root_file
2855 && file
2856 .rendered
2857 .as_ref()
2858 .is_some_and(|rendered| rendered.text != file.original)
2859 }) {
2860 root_suffix.as_str()
2861 } else {
2862 ""
2863 };
2864 if !built.is_empty() {
2865 if options.timeout_seconds.is_some()
2866 && built
2867 .iter()
2868 .any(|(file, _, _, _)| built_sources.contains(file))
2869 {
2870 for bin in &by_speed {
2871 bin.warn_timeout_conflict(None);
2872 }
2873 }
2874 let source_checkpoint = if checkpoint.is_some() {
2875 let keys = built
2876 .iter()
2877 .map(|(file, _, mutation, twin)| {
2878 serde_json::to_string(&(
2879 &file.display,
2880 mutation.start,
2881 mutation.end,
2882 &mutation.replacement,
2883 twin,
2884 ))
2885 })
2886 .collect::<std::result::Result<Vec<_>, _>>()?;
2887 phase("source", keys)?
2888 } else {
2889 None
2890 };
2891 session.note(&format!(
2892 "building {} mutants one by one (code a probe cannot be put in, or to compare with the probe)",
2893 built.len()
2894 ));
2895 let instrumented = |file: &SourceFile, text: &str, suffix: &str| {
2896 if file.path == root_file {
2897 format!("{text}{suffix}")
2898 } else {
2899 text.to_string()
2900 }
2901 };
2902 let mut skipped_targets = BTreeSet::new();
2905 let mut left_out: BTreeMap<&PathBuf, Vec<(usize, usize)>> = BTreeMap::new();
2907 let mut survivors: Vec<(report::Location, Vec<String>)> = vec![];
2908 progress::track(
2909 options.progress,
2910 "source mutants",
2911 built.len(),
2912 |progress| -> Result<()> {
2913 for (index, (file, site, mutant, twin)) in built.iter().enumerate() {
2914 let cached = source_checkpoint
2915 .as_ref()
2916 .map(|phase| phase.get::<Option<Outcome>>(index))
2917 .transpose()?
2918 .flatten();
2919 let left_out = left_out
2920 .entry(&file.path)
2921 .or_insert_with(|| built_sources.left_out(file))
2922 .iter()
2923 .any(|(from, to)| *from <= site.start && site.end <= *to);
2924 if left_out || !built_sources.contains(file) {
2925 if let Some(phase) = source_checkpoint.as_ref().filter(|_| cached.is_none())
2926 {
2927 phase.record(index, &Some(Outcome::Unable))?;
2928 }
2929 if twin.is_none() {
2930 report.mutants_not_evaluated += 1;
2931 report.mutants_not_compiled += 1;
2932 if skipped_targets.insert((&file.path, site.start, site.end)) {
2933 report.skipped.push(report::SkippedSite::new(
2934 report::location(&file.display, site),
2935 file.lines.position(&file.original, site.end),
2936 report::SkipReason::SourceNotBuilt,
2937 left_out.then(|| {
2938 "under a `cfg` that the features of this build turn off"
2939 .to_string()
2940 }),
2941 ));
2942 }
2943 } else if let Some(audit) = report.audit.as_mut() {
2944 audit.not_compared += 1;
2945 }
2946 progress.complete(progress::Outcome::Unable);
2947 continue;
2948 }
2949 let outcome = if let Some(cached) = cached {
2950 cached
2951 } else {
2952 let mutated = format!(
2953 "{}{}{}",
2954 &file.original[..mutant.start],
2955 mutant.replacement,
2956 &file.original[mutant.end..]
2957 );
2958 let attempt = || -> Result<Option<Outcome>> {
2960 state.write(
2961 &file.path,
2962 &instrumented(file, &mutated, root_mutant_suffix),
2963 )?;
2964 match source_build(&cargo_build()?) {
2965 SourceBuild::Built => run_source_tests(&by_speed).map(Some),
2966 SourceBuild::Refused => Ok(None),
2967 SourceBuild::Failed(why) => {
2970 session.note(&format!(
2971 "a build failed without the compiler refusing the code; its mutant is not evaluated: {why}"
2972 ));
2973 Ok(Some(Outcome::Unable))
2974 }
2975 }
2976 };
2977 let attempted = attempt();
2978 let rendered = file.rendered.as_ref().expect("rendered before building");
2980 state.write(
2981 &file.path,
2982 &instrumented(file, &rendered.text, &root_suffix),
2983 )?;
2984 let outcome = attempted?;
2985 if let Some(phase) = &source_checkpoint
2988 && outcome != Some(Outcome::Unable)
2989 {
2990 phase.record(index, &outcome)?;
2991 }
2992 outcome
2993 };
2994 progress.complete(outcome.map_or(progress::Outcome::Unable, Into::into));
2995 if let Some(job) = twin {
2996 let as_probe = results[*job].survived.is_some();
2998 let Some(audit) = report.audit.as_mut() else {
2999 continue;
3000 };
3001 match audit_source_comparison(&results[*job], outcome) {
3004 Some(disagrees) => {
3005 audit.compared += 1;
3006 if disagrees {
3007 let verdict =
3008 |passes: bool| if passes { "passes" } else { "fails" };
3009 audit.source_disagreements.push(report::SourceDisagreement {
3010 at: report::location(&file.display, site),
3011 mutant: report::describe(site, mutation_of(site, mutant)),
3012 as_probe: verdict(as_probe).to_string(),
3013 built: verdict(!as_probe).to_string(),
3014 });
3015 }
3016 }
3017 None => audit.not_compared += 1,
3018 }
3019 continue;
3020 }
3021 match outcome {
3022 None => report.unviable_mutants += 1,
3023 Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
3024 Some(outcome) => {
3025 report.mutants_run += 1;
3026 report.mutants_killed += (outcome != Outcome::Pass) as usize;
3027 report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
3028 report.mutants_survived += (outcome == Outcome::Pass) as usize;
3029 }
3030 }
3031 let survived = outcome == Some(Outcome::Pass);
3032 if survived {
3033 let at = report::location(&file.display, site);
3034 let removed = mutant.replacement.trim().is_empty();
3036 let text = match (&site.kind, removed) {
3037 (SiteKind::Field { .. }, true) => {
3038 format!("without the field `{}`", report::one_line(&site.text))
3039 }
3040 (
3041 SiteKind::LiteralSet {
3042 receiver, argument, ..
3043 },
3044 true,
3045 ) => format!(
3046 "without `{}` in `{}.contains({})`",
3047 report::one_line(&mutant.into),
3048 report::one_line(receiver),
3049 report::one_line(argument)
3050 ),
3051 _ => report::describe(site, mutation_of(site, mutant)),
3052 };
3053 match survivors.last_mut() {
3054 Some((last, texts)) if *last == at => texts.push(text),
3055 _ => survivors.push((at, vec![text])),
3056 }
3057 }
3058 }
3059 Ok(())
3060 },
3061 )?;
3062 if let Some(phase) = &source_checkpoint {
3063 phase.finish_if_complete()?;
3064 }
3065 for (at, survivors) in survivors {
3066 finding_run_survivors.push(survivors.len());
3067 report.findings.push(Finding::Survivor {
3068 at,
3069 survivors,
3070 witness: None,
3071 change_since: None,
3072 advice: None,
3073 });
3074 }
3075 }
3076
3077 if let Some(revision) = options
3079 .since
3080 .as_deref()
3081 .filter(|_| !options.list && options.shard.is_none())
3082 {
3083 let hunks = scope::hunks(&since_diff(&workspace, revision)?);
3084 let not_built_changes = std::cell::Cell::new(0usize);
3085 let changed: Vec<(&SourceFile, Vec<reverts::Change>)> = files
3086 .iter()
3087 .filter(|file| built_sources.contains(file) || !options.source_only && !options.rebuild)
3088 .filter_map(|file| {
3089 let relative = file
3090 .path
3091 .strip_prefix(©)
3092 .ok()?
3093 .to_string_lossy()
3094 .replace('\\', "/");
3095 let of_file: Vec<_> = hunks
3096 .iter()
3097 .filter(|hunk| hunk.file == relative)
3098 .cloned()
3099 .collect();
3100 let mut changes = reverts::changes(&file.original, &of_file);
3101 if options.rebuild || options.source_only {
3104 for change in &mut changes {
3105 change.outside = change.undone.as_deref().is_some_and(|undone| {
3108 built_sources.same_program(file, &file.original, undone)
3109 });
3110 }
3111 not_built_changes.set(
3112 not_built_changes.get()
3113 + changes.iter().filter(|change| change.outside).count(),
3114 );
3115 }
3116 (!changes.is_empty()).then_some((file, changes))
3117 })
3118 .collect();
3119 let not_built_changes = not_built_changes.get();
3120 report.mutants_not_evaluated += not_built_changes;
3121 report.mutants_not_compiled += not_built_changes;
3122 let total: usize = changed
3124 .iter()
3125 .map(|(_, changes)| changes.iter().filter(|change| !change.outside).count())
3126 .sum();
3127 let mixed: usize = files
3130 .iter()
3131 .map(|file| {
3132 let relative = file
3133 .path
3134 .strip_prefix(©)
3135 .unwrap_or(&file.path)
3136 .to_string_lossy()
3137 .replace('\\', "/");
3138 let of_file: Vec<_> = hunks
3139 .iter()
3140 .filter(|hunk| hunk.file == relative)
3141 .cloned()
3142 .collect();
3143 reverts::mixed(&file.original, &of_file)
3144 })
3145 .sum();
3146 if mixed > 0 && (options.rebuild || options.source_only) {
3147 report.mutants_not_evaluated += mixed;
3148 session.note(&format!(
3149 "{mixed} changes are of the program and its tests in the same lines: they are not tried undone"
3150 ));
3151 }
3152 if !(options.rebuild || options.source_only) {
3153 report.mutants_not_built += not_built_reverts;
3154 } else if total > 0
3155 || changed.iter().any(|(_, changes)| {
3156 changes.iter().filter(|change| !change.is_subhunk()).count() > 1
3157 })
3158 {
3159 session.note(&format!(
3162 "building {total} changes undone, one by one (the code as it was at {})",
3163 report::short_revision(revision)
3164 ));
3165 let write = |file: &SourceFile, text: &str, suffix: &str| -> Result<()> {
3166 let suffix = if file.path == root_file { suffix } else { "" };
3167 state.write(&file.path, &format!("{text}{suffix}"))
3168 };
3169 let undone = |edits: &[(&SourceFile, &str)]| -> Result<Option<Outcome>> {
3171 let attempted = (|| -> Result<Option<Outcome>> {
3172 for (file, text) in edits {
3173 write(file, text, root_mutant_suffix)?;
3174 }
3175 Ok(match source_build(&cargo_build()?) {
3176 SourceBuild::Built => Some(run_source_tests(&by_speed)?),
3177 SourceBuild::Refused => None,
3178 SourceBuild::Failed(why) => {
3179 session.note(&format!(
3180 "a build failed without the compiler refusing the code; the change undone is not evaluated: {why}"
3181 ));
3182 Some(Outcome::Unable)
3183 }
3184 })
3185 })();
3186 for (file, _) in edits {
3188 let rendered = file.rendered.as_ref().expect("rendered before building");
3189 write(file, &rendered.text, &root_suffix)?;
3190 }
3191 attempted
3192 };
3193 let mut judged = |outcome: Option<Outcome>, at: report::Location, what: String| {
3194 match outcome {
3195 None => report.unviable_mutants += 1,
3196 Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
3197 Some(outcome) => {
3198 report.mutants_run += 1;
3199 report.mutants_killed += (outcome != Outcome::Pass) as usize;
3200 report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
3201 report.mutants_survived += (outcome == Outcome::Pass) as usize;
3202 }
3203 }
3204 if outcome == Some(Outcome::Pass) {
3205 finding_run_survivors.push(1);
3206 report.findings.push(Finding::Survivor {
3207 at,
3208 survivors: vec![what],
3209 witness: None,
3210 advice: None,
3211 change_since: Some(revision.to_string()),
3212 });
3213 }
3214 };
3215 let place = |file: &SourceFile, change: &reverts::Change| report::Location {
3216 file: file.display.clone(),
3217 line: change.line,
3218 column: 1,
3219 code: change.code.clone(),
3220 ..Default::default()
3221 };
3222 let mut stuck_files = 0;
3225 for (file, changes) in &changed {
3226 let mut stuck = false;
3227 let whole_total = changes.iter().filter(|change| !change.is_subhunk()).count();
3228 let whole_alone = changes
3229 .iter()
3230 .filter(|change| !change.is_subhunk() && !change.outside)
3231 .count();
3232 for change in changes.iter().filter(|change| !change.outside) {
3233 let outcome = match &change.undone {
3234 Some(text) => undone(&[(file, text.as_str())])?,
3235 None => None,
3236 };
3237 if !change.is_subhunk() {
3238 stuck |= outcome.is_none();
3239 }
3240 judged(outcome, place(file, change), change.describe());
3241 }
3242 let whole = reverts::all_undone(&file.original, changes);
3247 let same = |a: &str, b: &str| built_sources.same_program(file, a, b);
3248 let tried: Vec<reverts::Change> = changes
3249 .iter()
3250 .filter(|change| !change.outside)
3251 .cloned()
3252 .collect();
3253 let left_out_matter = whole_alone < whole_total
3254 && match (&whole, reverts::all_undone(&file.original, &tried)) {
3255 (Some(all), Some(without)) => !same(all, &without),
3256 _ => true,
3257 };
3258 let another = whole
3260 .as_deref()
3261 .is_none_or(|all| !same(all, &file.original));
3262 if whole_total > 1 && another && (stuck || left_out_matter) {
3263 let outcome = match &whole {
3264 Some(text) => undone(&[(file, text.as_str())])?,
3265 None => None,
3266 };
3267 stuck = outcome.is_none();
3268 let first_whole = changes
3269 .iter()
3270 .find(|change| !change.is_subhunk())
3271 .unwrap_or(&changes[0]);
3272 judged(
3273 outcome,
3274 place(file, first_whole),
3275 format!("with all {whole_total} changes to this file undone"),
3276 );
3277 }
3278 stuck_files += usize::from(stuck);
3279 }
3280 let with_left_out = changed.iter().any(|(_, changes)| {
3284 changes
3285 .iter()
3286 .any(|change| !change.is_subhunk() && change.outside)
3287 });
3288 if (stuck_files > 0 || with_left_out) && changed.len() > 1 {
3289 let whole: Option<Vec<String>> = changed
3290 .iter()
3291 .map(|(file, changes)| reverts::all_undone(&file.original, changes))
3292 .collect();
3293 let same =
3294 |file: &SourceFile, a: &str, b: &str| built_sources.same_program(file, a, b);
3295 let another = whole.as_ref().is_none_or(|texts| {
3297 changed
3298 .iter()
3299 .zip(texts)
3300 .any(|((file, _), text)| !same(file, text, &file.original))
3301 });
3302 let left_out_matter = whole.as_ref().is_none_or(|texts| {
3305 changed.iter().zip(texts).any(|((file, changes), text)| {
3306 let tried: Vec<reverts::Change> = changes
3307 .iter()
3308 .filter(|change| !change.outside)
3309 .cloned()
3310 .collect();
3311 reverts::all_undone(&file.original, &tried)
3312 .is_none_or(|without| !same(file, text, &without))
3313 })
3314 });
3315 if another && (stuck_files > 0 || (with_left_out && left_out_matter)) {
3316 let outcome = match &whole {
3317 Some(texts) => {
3318 let edits: Vec<(&SourceFile, &str)> = changed
3319 .iter()
3320 .zip(texts)
3321 .map(|((file, _), text)| (*file, text.as_str()))
3322 .collect();
3323 undone(&edits)?
3324 }
3325 None => None,
3326 };
3327 let (file, changes) = &changed[0];
3328 judged(
3329 outcome,
3330 place(file, &changes[0]),
3331 format!("with every change undone, in all {} files", changed.len()),
3332 );
3333 }
3334 }
3335 }
3336 }
3337
3338 let mut witness_files: Vec<&PathBuf> = vec![];
3341 for candidate in &witness_candidates {
3342 if !witness_files.contains(&&candidate.file) {
3343 witness_files.push(&candidate.file);
3344 }
3345 }
3346 for witness_file in witness_files {
3347 let in_root = *witness_file == root_file;
3348 let witness_candidates: Vec<&witness::Candidate> = witness_candidates
3349 .iter()
3350 .filter(|candidate| candidate.file == *witness_file)
3351 .collect();
3352 let file = files
3353 .iter()
3354 .find(|file| file.path == *witness_file)
3355 .expect("witness candidates are of files that are analysed");
3356 let rendered = file.rendered.as_ref().expect("rendered before building");
3357 let left_out_here = built_sources.left_out(file);
3358 let restore = if in_root {
3359 format!("{}{root_suffix}", rendered.text)
3360 } else {
3361 rendered.text.clone()
3362 };
3363 let library_runners: Vec<_> = session
3364 .binaries
3365 .iter()
3366 .filter(|bin| {
3367 root_exe
3368 .as_deref()
3369 .is_some_and(|exe| bin.runner.executable() == Some(exe))
3370 })
3371 .collect();
3372 let ignored = library_runners
3373 .iter()
3374 .find_map(|bin| match &bin.runner {
3375 Runner::Exe(exe) => Some(list_tests(
3376 exe,
3377 &bin.cwd,
3378 &bin.git_ceiling,
3379 true,
3380 false,
3381 bin.work_lock.as_deref(),
3382 )),
3383 _ => None,
3384 })
3385 .transpose()?
3386 .unwrap_or_default();
3387 let runner_for = |scenario: &witness::Scenario| {
3388 library_runners.iter().copied().find(|bin| {
3389 scenario
3390 .source_test
3391 .as_ref()
3392 .is_none_or(|required| match &bin.runner {
3393 Runner::Exe(_) if !in_root => {
3396 let inner = format!("::{required}");
3397 bin.tests
3398 .iter()
3399 .any(|test| test.ends_with(&inner) && !ignored.contains(test))
3400 }
3401 Runner::Exe(_) => {
3402 bin.tests.contains(required) && !ignored.contains(required)
3403 }
3404 Runner::Isolated { test, .. } if !in_root => {
3405 test.ends_with(&format!("::{required}"))
3406 }
3407 Runner::Isolated { test, .. } => test == required,
3408 Runner::Doc { .. } | Runner::Nextest { .. } => false,
3409 })
3410 })
3411 };
3412 let write_edits = |edits: &[witness::Edit]| -> Result<bool> {
3413 let Some(source) = witness::render_edits(&file.original, edits, None) else {
3414 return Ok(false);
3415 };
3416 let suffix = if in_root { root_mutant_suffix } else { "" };
3417 state.write(&file.path, &format!("{source}{suffix}"))?;
3418 Ok(true)
3419 };
3420 let suite = |edits: &[witness::Edit]| -> Result<Option<Outcome>> {
3421 if !write_edits(edits)? {
3422 return Ok(None);
3423 }
3424 Ok(match source_build(&cargo_build()?) {
3425 SourceBuild::Built => Some(run_source_tests(&by_speed)?),
3426 SourceBuild::Refused => None,
3427 SourceBuild::Failed(why) => {
3428 session.note(&format!(
3429 "a build failed without the compiler refusing the code; the mutant is not evaluated: {why}"
3430 ));
3431 Some(Outcome::Unable)
3432 }
3433 })
3434 };
3435 let compile_observer = |edits: &[witness::Edit]| -> Result<Option<PathBuf>> {
3436 if !write_edits(edits)? {
3437 return Ok(None);
3438 }
3439 let build = build_test_binaries(true)?;
3440 if !build.status.success() {
3441 return Ok(None);
3442 }
3443 let artifacts = parse_build_output(
3444 &String::from_utf8_lossy(&build.stdout),
3445 &[package.name.as_str()],
3446 );
3447 Ok(root_test_exe(&artifacts))
3448 };
3449 let observe = |scenario: &witness::Scenario,
3450 baseline: &TestBinary,
3451 edits: &[witness::Edit],
3452 field_path: Option<&str>,
3453 expected: Option<&str>|
3454 -> Result<Option<witness::Observation>> {
3455 let test = scenario.test_edit_with_field(
3456 &file.original,
3457 witness::TEST_NAME,
3458 field_path,
3459 expected,
3460 );
3461 let edits: Vec<_> = edits.iter().cloned().chain([test]).collect();
3462 let Some(exe) = compile_observer(&edits)? else {
3463 return Ok(None);
3464 };
3465 observe_witness(
3466 baseline,
3467 exe,
3468 wrapper.as_deref(),
3469 scenario,
3470 witness::TEST_NAME,
3471 expected.is_some(),
3472 in_root,
3473 )
3474 };
3475 let witness_checkpoint = if checkpoint.is_some() {
3476 let keys = witness_candidates
3477 .iter()
3478 .map(|candidate| {
3479 let edits = candidate
3480 .edits
3481 .iter()
3482 .map(|edit| (&edit.span, &edit.replacement))
3483 .collect::<Vec<_>>();
3484 serde_json::to_string(&(&candidate.description, edits))
3485 })
3486 .collect::<std::result::Result<Vec<_>, _>>()?;
3487 let name = if in_root {
3488 "witness".to_string()
3489 } else {
3490 format!("witness:{}", file.display)
3491 };
3492 phase(&name, keys)?
3493 } else {
3494 None
3495 };
3496 let mut survivors = vec![];
3497 let mut claimed = BTreeSet::new();
3498 progress::track(
3499 options.progress,
3500 "source witness mutants",
3501 witness_candidates.len(),
3502 |progress| -> Result<()> {
3503 for (index, candidate) in witness_candidates.iter().copied().enumerate() {
3504 let cached = witness_checkpoint
3505 .as_ref()
3506 .map(|phase| phase.get::<WitnessTrial>(index))
3507 .transpose()?
3508 .flatten();
3509 let at = witness_location(file, candidate);
3510 if !built_sources.contains(file)
3512 || candidate.edits.iter().any(|edit| {
3513 left_out_here
3514 .iter()
3515 .any(|(from, to)| *from <= edit.span.start && edit.span.end <= *to)
3516 })
3517 {
3518 if let Some(phase) =
3519 witness_checkpoint.as_ref().filter(|_| cached.is_none())
3520 {
3521 phase.record(index, &WitnessTrial::Inapplicable)?;
3522 }
3523 if !candidate.existing {
3524 report.mutants_not_evaluated += 1;
3525 report.mutants_not_compiled += 1;
3526 let span = &candidate.edits[0].span;
3527 report.skipped.push(report::SkippedSite::new(
3528 at,
3529 file.lines.position(&file.original, span.end),
3530 report::SkipReason::SourceNotBuilt,
3531 Some(
3532 "under a `cfg` that the features of this build turn off"
3533 .to_string(),
3534 ),
3535 ));
3536 }
3537 progress.complete(progress::Outcome::Unable);
3538 continue;
3539 }
3540 let existing = candidate
3541 .existing
3542 .then(|| {
3543 report.findings.iter().position(|finding| {
3544 let location = finding.at();
3545 location.file == at.file
3546 && location.line == at.line
3547 && location.column == at.column
3548 && finding.survivors().contains(&candidate.description)
3549 && (candidate.finding_at.is_none()
3550 || !matches!(finding, Finding::InputGap { .. }))
3551 })
3552 })
3553 .flatten();
3554 let existing = existing
3558 .filter(|index| candidate.finding_at.is_none() || !claimed.contains(index));
3559 let scenarios: Vec<_> = candidate
3560 .scenarios
3561 .iter()
3562 .filter_map(|scenario| {
3563 runner_for(scenario).map(|runner| (scenario, runner))
3564 })
3565 .take(4)
3566 .collect();
3567 let paired = candidate.edits.len() > 1;
3568 if (candidate.existing && (existing.is_none() || scenarios.is_empty()))
3569 || (paired && scenarios.is_empty())
3570 {
3571 if let Some(phase) =
3572 witness_checkpoint.as_ref().filter(|_| cached.is_none())
3573 {
3574 phase.record(index, &WitnessTrial::Inapplicable)?;
3575 }
3576 progress.complete(progress::Outcome::Unable);
3577 continue;
3578 }
3579 let trial = if let Some(cached) = cached {
3582 cached
3583 } else {
3584 let attempted = (|| -> Result<WitnessTrial> {
3585 if paired {
3586 for edit in &candidate.edits {
3587 match suite(std::slice::from_ref(edit))? {
3588 Some(Outcome::Fail) => {}
3589 Some(Outcome::Unable) => {
3590 return Ok(WitnessTrial::Evaluated(Outcome::Unable));
3591 }
3592 _ => return Ok(WitnessTrial::Inapplicable),
3593 }
3594 }
3595 }
3596 Ok(suite(&candidate.edits)?
3597 .map_or(WitnessTrial::Unviable, WitnessTrial::Evaluated))
3598 })();
3599 state.write(&file.path, &restore)?;
3600 let trial = attempted?;
3601 if let Some(phase) = &witness_checkpoint
3602 && !matches!(trial, WitnessTrial::Evaluated(Outcome::Unable))
3603 {
3604 phase.record(index, &trial)?;
3605 }
3606 trial
3607 };
3608 let outcome = match trial {
3609 WitnessTrial::Inapplicable => {
3610 progress.complete(progress::Outcome::Unable);
3611 continue;
3612 }
3613 WitnessTrial::Unviable => {
3614 progress.complete(progress::Outcome::Unable);
3615 report.unviable_mutants += usize::from(!candidate.existing);
3616 continue;
3617 }
3618 WitnessTrial::Evaluated(outcome) => outcome,
3619 };
3620 progress.complete(outcome.into());
3621 if !candidate.existing {
3622 match outcome {
3623 Outcome::Unable => report.mutants_not_evaluated += 1,
3624 Outcome::Pass => {
3625 report.mutants_run += 1;
3626 report.mutants_survived += 1;
3627 }
3628 Outcome::Fail => {
3629 report.mutants_run += 1;
3630 report.mutants_killed += 1;
3631 }
3632 Outcome::Timeout => {
3633 report.mutants_run += 1;
3634 report.mutants_killed += 1;
3635 report.mutants_timed_out += 1;
3636 }
3637 }
3638 }
3639 if outcome == Outcome::Pass {
3640 survivors.push(WitnessSurvivor {
3641 candidate,
3642 at,
3643 existing,
3644 scenarios,
3645 });
3646 }
3647 }
3648 Ok(())
3649 },
3650 )?;
3651
3652 if let Some(phase) = &witness_checkpoint {
3653 phase.finish()?;
3654 }
3655 let originals = shared_witnesses(
3656 &file.original,
3657 &survivors,
3658 wrapper.as_deref(),
3659 in_root,
3660 compile_observer,
3661 note,
3662 );
3663 if !survivors.is_empty() {
3664 state.write(&file.path, &restore)?;
3665 }
3666 let originals = originals?;
3667
3668 progress::track(
3669 options.progress,
3670 "distinguishing tests",
3671 survivors.len(),
3672 |progress| -> Result<()> {
3673 for (survivor, original) in survivors.into_iter().zip(originals) {
3674 if survivor.existing.is_some_and(|index| {
3675 survivor.candidate.finding_at.is_some() && claimed.contains(&index)
3676 }) {
3677 progress.complete(progress::Outcome::Unable);
3678 continue;
3679 }
3680 let mut evidence = None;
3681 let mut original = original;
3682 for (scenario, baseline) in survivor.scenarios {
3683 let shared = original.take();
3684 let distinction = (|| -> Result<_> {
3685 if let Some(shared) = shared {
3686 let edits: Vec<_> = survivor
3688 .candidate
3689 .edits
3690 .iter()
3691 .chain(shared.tests.iter())
3692 .cloned()
3693 .collect();
3694 if let Some(exe) = compile_observer(&edits)?
3695 && let Some(mutant) = observe_witness(
3696 baseline,
3697 exe,
3698 wrapper.as_deref(),
3699 scenario,
3700 &shared.name,
3701 true,
3702 in_root,
3703 )
3704 .ok()
3705 .flatten()
3706 && mutant.equals_expected == Some(false)
3707 && observe_witness(
3710 baseline,
3711 shared.original_exe.path.clone(),
3712 wrapper.as_deref(),
3713 scenario,
3714 &shared.name,
3715 true,
3716 in_root,
3717 )
3718 .ok()
3719 .flatten()
3720 .is_some_and(|rechecked| {
3721 rechecked.equals_expected == Some(true)
3722 && rechecked.value == shared.value
3723 })
3724 && let Some(verified) =
3725 scenario.verified(shared.value, mutant.value)
3726 {
3727 return Ok(Some(verified));
3728 }
3729 }
3732 let Some(original) = observe(scenario, baseline, &[], None, None)?
3733 else {
3734 return Ok(None);
3735 };
3736 let value = original.value;
3737 if witness::is_expected_literal(&value) {
3738 let Some(mutant) = observe(
3739 scenario,
3740 baseline,
3741 &survivor.candidate.edits,
3742 None,
3743 Some(&value),
3744 )?
3745 else {
3746 return Ok(None);
3747 };
3748 if mutant.equals_expected != Some(false) || value == mutant.value {
3749 return Ok(None);
3750 }
3751 let Some(checked) =
3752 observe(scenario, baseline, &[], None, Some(&value))?
3753 else {
3754 return Ok(None);
3755 };
3756 if checked.equals_expected != Some(true) || checked.value != value {
3757 return Ok(None);
3758 }
3759 return Ok(scenario.verified(value, mutant.value));
3760 }
3761 if witness::parse_debug_struct(&value).is_none() {
3764 return Ok(None);
3765 }
3766 let Some(raw_mutant) =
3767 observe(scenario, baseline, &survivor.candidate.edits, None, None)?
3768 else {
3769 return Ok(None);
3770 };
3771 let Some((path, field_orig, _)) =
3772 witness::narrow_struct_field(&value, &raw_mutant.value)
3773 else {
3774 return Ok(None);
3775 };
3776 if !witness::is_expected_literal(&field_orig) {
3777 return Ok(None);
3778 }
3779 let field_path = path.join(".");
3780 let Some(mutant) = observe(
3781 scenario,
3782 baseline,
3783 &survivor.candidate.edits,
3784 Some(&field_path),
3785 Some(&field_orig),
3786 )?
3787 else {
3788 return Ok(None);
3789 };
3790 if mutant.equals_expected != Some(false)
3791 || mutant.value != raw_mutant.value
3792 || value == mutant.value
3793 {
3794 return Ok(None);
3795 }
3796 let Some(checked) = observe(
3797 scenario,
3798 baseline,
3799 &[],
3800 Some(&field_path),
3801 Some(&field_orig),
3802 )?
3803 else {
3804 return Ok(None);
3805 };
3806 if checked.equals_expected != Some(true) || checked.value != value {
3807 return Ok(None);
3808 }
3809 Ok(
3810 scenario.verified_field(
3811 value,
3812 mutant.value,
3813 field_path,
3814 field_orig,
3815 ),
3816 )
3817 })();
3818 match distinction {
3819 Ok(Some(mut verified)) => {
3820 let edits = survivor.candidate.edits.len();
3821 verified.individually_killed = (edits > 1).then_some(edits);
3822 evidence = Some(verified);
3823 break;
3824 }
3825 Ok(None) => {}
3826 Err(err) => note(&format!(
3827 "could not check a distinguishing test for {}: {err:#}",
3828 scenario.expression,
3829 )),
3830 }
3831 }
3832 state.write(&file.path, &restore)?;
3833 progress.complete(Outcome::Pass.into());
3834 if let Some(index) = survivor.existing {
3835 if let Some(evidence) = evidence {
3836 report.findings[index].set_witness(evidence);
3837 if survivor.candidate.finding_at.is_some() {
3838 claimed.insert(index);
3839 }
3840 }
3841 } else {
3842 finding_run_survivors.push(1);
3843 report.findings.push(Finding::Survivor {
3844 at: survivor.at,
3845 survivors: vec![survivor.candidate.description.clone()],
3846 advice: survivor
3847 .candidate
3848 .advice
3849 .clone()
3850 .filter(|_| evidence.is_none()),
3851 witness: evidence,
3852 change_since: None,
3853 });
3854 }
3855 }
3856 Ok(())
3857 },
3858 )?;
3859 }
3860
3861 report.record_evaluation();
3862 debug_assert_eq!(report.findings.len(), finding_run_survivors.len());
3863 let mut paired_findings: Vec<(Finding, usize)> = report
3864 .findings
3865 .into_iter()
3866 .zip(finding_run_survivors)
3867 .collect();
3868 paired_findings.sort_by(|(a, _), (b, _)| {
3869 let (a, b) = (a.at(), b.at());
3870 (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column))
3871 });
3872 let (sorted_findings, finding_run_survivors): (Vec<_>, Vec<_>) =
3873 paired_findings.into_iter().unzip();
3874 report.findings = sorted_findings;
3875 let places: Vec<FilePlaces> = files
3876 .iter()
3877 .map(|file| FilePlaces {
3878 display: &file.display,
3879 source: &file.original,
3880 lines: &file.lines,
3881 places: &file.places,
3882 })
3883 .collect();
3884 name_findings(&mut report.findings, &places);
3885
3886 let partial_scope = is_partial_scope.then(|| crate::baseline::PartialScope {
3888 scope: scope.as_ref(),
3889 exclude_files: &options.exclude_files,
3890 preserve_all_existing: options.shard.is_some(),
3891 });
3892 let write_ctx = BaselineWriteContext {
3893 ws_package_prefix: &ws_package_prefix,
3894 partial_scope: partial_scope.as_ref(),
3895 single_package_run: batch.is_none(),
3896 note: ¬e,
3897 };
3898 apply_suppressions_and_finish(
3899 options,
3900 &files,
3901 &mut report,
3902 &finding_run_survivors,
3903 checkpoint.as_ref(),
3904 &write_ctx,
3905 )?;
3906 report.wrapper_grace_outcomes = wrapper_grace_counter.as_ref().map(|c| c.snapshot());
3907 debug_assert!(
3908 report.counts_reconcile(),
3909 "report counts do not reconcile: {report:#?}"
3910 );
3911 Ok(report)
3912}
3913
3914fn validate_package_options(options: &Options) -> Result<Vec<&str>> {
3915 if let Some(shard) = options.shard
3916 && (!options.source_only || shard.index >= shard.count)
3917 {
3918 bail!("shards require --source-only and a valid shard index");
3919 }
3920 let mut seen_errors = HashSet::new();
3921 let mut error_values = vec![];
3922 for expression in &options.error_values {
3923 let expression = expression.trim();
3924 if expression.chars().any(char::is_control) {
3927 bail!(
3928 "invalid --error expression {expression:?}: it has to be on one line, \
3929 without control characters"
3930 );
3931 }
3932 let parsed = syn::parse_str::<syn::Expr>(expression)
3933 .with_context(|| format!("invalid --error expression {expression:?}"))?;
3934 if seen_errors.insert(quote::ToTokens::to_token_stream(&parsed).to_string()) {
3935 error_values.push(expression);
3936 }
3937 }
3938 let selection = &options.test_selection;
3939 if options.nextest.is_some() {
3940 if !cfg!(unix) {
3941 bail!("the nextest runner is available on Unix");
3942 }
3943 if !options.source_only || options.doc || selection.enabled() {
3944 bail!(
3945 "--test-tool nextest requires --source-only; select tests through the nextest profile"
3946 );
3947 }
3948 }
3949 if options.baseline_jobs > 1 && !selection.enabled() {
3950 bail!("--baseline-jobs requires isolated tests or a test wrapper or selection");
3951 }
3952 if options.doc && selection.enabled() {
3953 bail!("--doc cannot be combined with isolated test selection");
3954 }
3955 if options.source_only && options.jobs > 1 {
3956 eprintln!(
3957 "tmt: warning: --source-only runs mutants serially in one working copy; ignoring --jobs {}",
3958 options.jobs
3959 );
3960 }
3961 Ok(error_values)
3962}
3963
3964struct PreparedWorkCopy {
3965 workspace: PathBuf,
3966 work: PathBuf,
3967 work_lock: Option<Arc<WorkLock>>,
3968 copy: PathBuf,
3969 state: WorkCopy,
3970 external_deps: BTreeSet<PathBuf>,
3971}
3972
3973fn prepare_work_copy(
3974 options: &Options,
3975 metadata: &Metadata,
3976 batch: Option<&WorkspaceBatch<'_>>,
3977 catalogue: Option<&CatalogueSnapshot>,
3978 note: &impl Fn(&str),
3979) -> Result<PreparedWorkCopy> {
3980 let workspace = metadata.workspace_root.canonicalize()?;
3981 let requested_work = catalogue
3982 .map(|catalogue| &catalogue.path)
3983 .or(options.work_dir.as_ref());
3984 let work = match requested_work {
3985 Some(dir) => {
3986 fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
3987 dir.canonicalize()?
3988 }
3989 None => metadata.target_directory.join("tmt"),
3990 };
3991 if workspace.starts_with(&work) {
3994 bail!(
3995 "the work directory {} contains the workspace; choose a directory of its own",
3996 work.display()
3997 );
3998 }
3999 fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?;
4000 let work = work.canonicalize()?;
4001 let work_lock = if catalogue.is_none() {
4002 Some(Arc::new(WorkLock::take(&work)?))
4003 } else {
4004 None
4005 };
4006 let stage_root = work.join("src");
4007 let copy_subdir = staged_copy_subdir(&workspace, &options.stage_external)?;
4008 let copy = if copy_subdir.as_os_str().is_empty() {
4009 stage_root.clone()
4010 } else {
4011 stage_root.join(©_subdir)
4012 };
4013 let marker = work.join(WORK_MARKER);
4014 if stage_root.exists() && !marker.exists() {
4015 bail!(
4016 "{} exists and was not created by tmt; refusing to delete it. \
4017 Choose another --work-dir or remove it yourself.",
4018 stage_root.display()
4019 );
4020 }
4021 fs::write(
4022 &marker,
4023 "Working directory of tmt (targeted-mutation). Safe to delete.\n",
4024 )?;
4025 let target_dir = metadata.target_directory.clone();
4026 let forbidden = |path: &Path| {
4027 path == target_dir
4028 || path == work
4029 || batch.is_some_and(|batch| path == batch.work)
4030 || path.file_name().is_some_and(|n| n == ".git")
4031 || (path.parent() == Some(workspace.as_path())
4032 && path.file_name().is_some_and(|n| n == "target"))
4033 };
4034 let state = WorkCopy::open_with_copy_root(&work, &stage_root, ©);
4035 let fixtures = options
4036 .copy_fixtures
4037 .iter()
4038 .map(|path| fixture_relative(path))
4039 .collect::<Result<Vec<_>>>()?;
4040 let excluded = fixture_exclusions(&workspace, &fixtures, &options.copy_fixture_excludes)?;
4041 let fixture_forbidden = |path: &Path| forbidden(path) || excluded.contains(path);
4042 let skip = |path: &Path| {
4043 fixture_forbidden(path) || path.file_name().is_some_and(|n| n == "node_modules")
4044 };
4045 if options.progress && !options.list {
4046 for path in &excluded {
4047 note(&format!(
4048 "excluded fixture {}",
4049 path.strip_prefix(&workspace).unwrap_or(path).display()
4050 ));
4051 }
4052 }
4053 if catalogue.is_none_or(|catalogue| !catalogue.ready.get()) {
4054 work_directory(&work, "src")?;
4055 real_dir(©, &state)?;
4056 if copy != stage_root {
4057 for ancestor in copy.ancestors() {
4058 if ancestor == stage_root || !ancestor.starts_with(&stage_root) {
4059 break;
4060 }
4061 state.kept.borrow_mut().insert(ancestor.to_path_buf());
4062 }
4063 }
4064 let visible = if options.all_files {
4065 None
4066 } else {
4067 git_visible_files(&workspace)?
4068 };
4069 match visible {
4070 Some(files) => {
4073 let copied = copy_git_visible(&workspace, ©, files, &workspace, &skip, &state)?;
4074 note(&format!(
4075 "copied {copied} files (ignored files are left out)"
4076 ));
4077 }
4078 None => copy_tree(&workspace, ©, &workspace, &skip, &state)?,
4079 }
4080 for relative in &fixtures {
4081 copy_fixture_entry(
4082 &workspace.join(relative),
4083 ©.join(relative),
4084 &workspace,
4085 &fixture_forbidden,
4086 &state,
4087 &mut BTreeSet::new(),
4088 )?;
4089 }
4090 let mut staged_destinations: Vec<PathBuf> = Vec::new();
4091 let mut folded_ancestors: BTreeMap<String, PathBuf> = BTreeMap::new();
4092 for entry in &options.stage_external {
4093 let (rel, _) = parse_external_rel(&entry.rel)?;
4094 let dst = normalize(©.join(&rel));
4095 let copy_rel_in_stage = copy.strip_prefix(&stage_root).unwrap_or(©);
4096 let dst_rel_in_stage = dst.strip_prefix(&stage_root).unwrap_or(&dst);
4097 if !dst.starts_with(&stage_root)
4098 || dst == stage_root
4099 || copy.starts_with(&dst)
4100 || dst.starts_with(©)
4101 || paths_overlap_case_insensitive(copy_rel_in_stage, dst_rel_in_stage)
4102 || staged_destinations.iter().any(|prev| {
4103 let prev_rel = prev.strip_prefix(&stage_root).unwrap_or(prev);
4104 paths_overlap_case_insensitive(prev_rel, dst_rel_in_stage)
4105 })
4106 {
4107 bail!(
4108 "--stage-external destination collides with the workspace copy or another staged path: {}",
4109 entry.rel.display()
4110 );
4111 }
4112 for ancestor in dst_rel_in_stage.ancestors() {
4113 if ancestor.as_os_str().is_empty() {
4114 continue;
4115 }
4116 let folded = ancestor.to_string_lossy().to_lowercase();
4117 if let Some(previous) = folded_ancestors.get(&folded)
4118 && previous != ancestor
4119 {
4120 bail!(
4121 "--stage-external destinations differ only by case: {} and {}",
4122 previous.display(),
4123 ancestor.display()
4124 );
4125 }
4126 folded_ancestors.insert(folded, ancestor.to_path_buf());
4127 }
4128 staged_destinations.push(dst.clone());
4129 let src = if entry.from.is_absolute() {
4130 entry.from.clone()
4131 } else {
4132 workspace.join(&entry.from)
4133 };
4134 copy_external_entry(
4135 &src,
4136 &dst,
4137 None,
4138 &work,
4139 &forbidden,
4140 &state,
4141 &mut BTreeSet::new(),
4142 )?;
4143 }
4144 prune(&stage_root, &state)?;
4145 if options.git_index {
4146 git_index::snapshot(&workspace, ©)?;
4147 }
4148 let mut external_deps = BTreeSet::new();
4149 if !options.list {
4150 let mut manifests: Vec<&Path> = metadata
4152 .packages
4153 .iter()
4154 .map(|p| p.manifest_path.as_path())
4155 .collect();
4156 let root_manifest = metadata.workspace_root.join("Cargo.toml");
4157 manifests.push(&root_manifest);
4158 for manifest in manifests {
4159 let Ok(canonical) = manifest.canonicalize() else {
4160 continue;
4161 };
4162 let (Some(manifest_dir), Ok(relative)) =
4163 (canonical.parent(), canonical.strip_prefix(&workspace))
4164 else {
4165 continue;
4166 };
4167 let text = fs::read_to_string(&canonical)?;
4168 let (rewritten, externals) = absolutize_path_dependencies_with_externals(
4169 &text,
4170 manifest_dir,
4171 &workspace,
4172 ©,
4173 )?;
4174 external_deps.extend(externals);
4175 if let Some(rewritten) = rewritten {
4176 state.write(©.join(relative), &rewritten)?;
4177 }
4178 }
4179 }
4180 if let Some(catalogue) = catalogue {
4181 state.settle(&workspace)?;
4182 catalogue.ready.set(true);
4183 }
4184 return Ok(PreparedWorkCopy {
4185 workspace,
4186 work,
4187 work_lock,
4188 copy,
4189 state,
4190 external_deps,
4191 });
4192 }
4193 Ok(PreparedWorkCopy {
4194 workspace,
4195 work,
4196 work_lock,
4197 copy,
4198 state,
4199 external_deps: BTreeSet::new(),
4200 })
4201}
4202
4203#[allow(clippy::too_many_arguments)]
4204fn run_audit_phase<'a>(
4205 session: &Session,
4206 files: &[SourceFile],
4207 jobs: &[Job],
4208 results: &mut [JobResult],
4209 timeout_rechecks: &mut report::TimeoutRechecks,
4210 scratch: &Path,
4211 wanted: usize,
4212 workers: usize,
4213 probe_phase: &impl Fn(&str, &[Job]) -> Result<Option<Phase<'a>>>,
4214) -> Result<report::Audit> {
4215 let survivors: Vec<usize> = (0..jobs.len())
4216 .filter(|job| results[*job].survived.is_some())
4217 .collect();
4218 let chosen: Vec<usize> = spread(survivors.len(), wanted)
4219 .into_iter()
4220 .map(|nth| survivors[nth])
4221 .collect();
4222 session.note(&format!(
4223 "audit: running {} of {} surviving mutants against all tests",
4224 chosen.len(),
4225 survivors.len()
4226 ));
4227 let against_all: Vec<Job> = chosen
4228 .iter()
4229 .map(|job| Job {
4230 site: jobs[*job].site,
4231 mutation: jobs[*job].mutation,
4232 tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
4233 })
4234 .collect();
4235 let mut audit = report::Audit {
4236 sampled: chosen.len(),
4237 survivors: survivors.len(),
4238 ..report::Audit::default()
4239 };
4240 let audit_checkpoint = probe_phase("audit", &against_all)?;
4241 for (job, again) in chosen.iter().zip(session.run_jobs(
4242 &against_all,
4243 workers,
4244 "audit mutants",
4245 audit_checkpoint.as_ref(),
4246 )?) {
4247 timeout_rechecks.include(&again);
4248 if again.unable || again.unconfirmed_timeout {
4249 audit.not_audited += 1;
4250 } else if audit_all_tests_disagrees(&again) {
4251 results[*job] = again;
4253 let site = files
4254 .iter()
4255 .find_map(|f| Some((f, f.sites.iter().find(|s| s.id == jobs[*job].site)?)));
4256 if let Some((file, site)) = site {
4257 audit
4258 .disagreements
4259 .push(report::location(&file.display, site));
4260 }
4261 }
4262 }
4263 session.note("audit: recording the tests once more");
4264 for (index, bin) in session.binaries.iter().enumerate() {
4265 let path = scratch.join(format!("trace-{index}-audit.tsv"));
4266 let _ = fs::remove_file(&path);
4267 let trace_env = path.to_string_lossy().into_owned();
4268 let limit = Duration::from_secs(3600);
4269 let outcome = run_binary(
4270 bin,
4271 None,
4272 &[("TMT_TRACE", &trace_env)],
4273 limit,
4274 RunOutput::Quiet,
4275 1,
4276 )?;
4277 let again = Trace::parse(&fs::read_to_string(&path).unwrap_or_default());
4278 let _ = fs::remove_file(&path);
4279 let records = bin.trace.differences(&again);
4280 if outcome != Outcome::Pass || records > 0 {
4281 audit.trace_differences.push(report::TraceDifference {
4282 binary: bin.name.clone(),
4283 records,
4284 rerun_failed: outcome != Outcome::Pass,
4285 });
4286 }
4287 }
4288 Ok(audit)
4289}
4290
4291fn run_effects_phase(
4292 session: &Session,
4293 files: &[SourceFile],
4294 jobs: &[Job],
4295 effect_jobs: &[(usize, usize)],
4296 scratch: &Path,
4297 workers: usize,
4298 findings: &mut [Finding],
4299) -> Result<()> {
4300 session.note(&format!("tracing {} surviving mutants", effect_jobs.len()));
4301 let sites: BTreeMap<u32, (&str, &Site)> = files
4302 .iter()
4303 .flat_map(|f| f.sites.iter().map(move |s| (s.id, (f.display.as_str(), s))))
4304 .collect();
4305 let traced = run_pool(effect_jobs.len(), workers, |index| {
4306 session.trace_job(
4307 &jobs[effect_jobs[index].1],
4308 scratch,
4309 workers.clamp(1, effect_jobs.len()),
4310 )
4311 })?;
4312 for ((finding, job), mut changes) in effect_jobs.iter().zip(traced) {
4313 if let Some((mutated_file, mutated)) = sites.get(&jobs[*job].site) {
4316 for found in changes.values_mut() {
4317 found.retain(|change| {
4318 sites.get(&change.site()).is_none_or(|(file, site)| {
4319 file != mutated_file
4320 || site.end <= mutated.start
4321 || mutated.end <= site.start
4322 })
4323 });
4324 }
4325 changes.retain(|_, found| !found.is_empty());
4326 }
4327 if let Finding::AssertionGap {
4328 effects,
4329 effects_of,
4330 ..
4331 } = &mut findings[*finding]
4332 {
4333 *effects = describe_effects(&changes, &sites);
4334 *effects_of = sites
4335 .get(&jobs[*job].site)
4336 .map(|(_, site)| report::describe(site, jobs[*job].mutation));
4337 }
4338 }
4339 Ok(())
4340}
4341
4342struct BaselineWriteContext<'a> {
4343 ws_package_prefix: &'a str,
4344 partial_scope: Option<&'a crate::baseline::PartialScope<'a>>,
4345 single_package_run: bool,
4346 note: &'a dyn Fn(&str),
4347}
4348
4349fn apply_suppressions_and_finish(
4350 options: &Options,
4351 files: &[SourceFile],
4352 report: &mut Report,
4353 finding_run_survivors: &[usize],
4354 checkpoint: Option<&Checkpoint>,
4355 write_ctx: &BaselineWriteContext<'_>,
4356) -> Result<()> {
4357 let parsed_ignores: BTreeMap<&str, crate::baseline::ParsedLineIgnores> = files
4358 .iter()
4359 .map(|f| {
4360 (
4361 f.display.as_str(),
4362 crate::baseline::parse_line_ignores(&f.original),
4363 )
4364 })
4365 .collect();
4366 for (file, parsed) in &parsed_ignores {
4367 for warning in &parsed.warnings {
4368 match warning {
4369 crate::baseline::IgnoreWarning::EmptyScope { line } => {
4370 eprintln!(
4371 "tmt: warning: {}:{line}: empty `tmt:ignore[]` scope suppresses nothing (supported: input_gap, assertion_gap, survivor, @COL, or kind@COL)",
4372 crate::report::sanitize_inline(file),
4373 );
4374 }
4375 crate::baseline::IgnoreWarning::InvalidToken { line, token } => {
4376 eprintln!(
4377 "tmt: warning: {}:{line}: unknown `tmt:ignore` scope `{}` (supported: input_gap, assertion_gap, survivor, @COL, or kind@COL)",
4378 crate::report::sanitize_inline(file),
4379 crate::report::sanitize_inline(token),
4380 );
4381 }
4382 }
4383 }
4384 }
4385 let known = match &options.baseline {
4386 Some(path) => {
4387 let loaded = crate::baseline::load(path)?;
4388 loaded.validate_for_package(&report.package, path)?;
4389 Some(loaded)
4390 }
4391 None => None,
4392 };
4393 let before = report.findings.len();
4394 let mut after_inline: Vec<(Finding, usize)> = Vec::with_capacity(before);
4395 let mut matched_entries: BTreeSet<(&str, usize)> = BTreeSet::new();
4396 for (finding, run_survivors) in report
4397 .findings
4398 .drain(..)
4399 .zip(finding_run_survivors.iter().copied())
4400 {
4401 let at = finding.at();
4402 if let Some((&file_key, parsed)) = parsed_ignores.get_key_value(at.file.as_str())
4403 && parsed
4404 .directives
4405 .get(&at.line)
4406 .is_some_and(|ignore| ignore.matches(finding.kind(), at.column))
4407 {
4408 for entry in &parsed.entries {
4409 if entry.matches(at.line, finding.kind(), at.column) {
4410 matched_entries.insert((file_key, entry.comment_line));
4411 }
4412 }
4413 report.survivor_breakdown.suppressed += run_survivors;
4414 } else {
4415 after_inline.push((finding, run_survivors));
4416 }
4417 }
4418 if options.shard.is_none() && report.mutants_not_evaluated == 0 {
4422 let skipped_locs: BTreeSet<(&str, usize, usize)> = report
4423 .skipped
4424 .iter()
4425 .map(|s| (s.at.file.as_str(), s.at.line, s.at.column))
4426 .collect();
4427 let unreached_locs: BTreeSet<(&str, usize, usize)> = report
4428 .unreached
4429 .iter()
4430 .map(|u| (u.file.as_str(), u.line, u.column))
4431 .collect();
4432 for file in files {
4433 let Some(parsed) = parsed_ignores.get(file.display.as_str()) else {
4434 continue;
4435 };
4436 if parsed.entries.is_empty() {
4437 continue;
4438 }
4439 let evaluated_lines: BTreeSet<usize> = file
4440 .sites
4441 .iter()
4442 .chain(&file.rebuild_sites)
4443 .filter(|site| {
4444 let key = (file.display.as_str(), site.line, site.column);
4445 !skipped_locs.contains(&key) && !unreached_locs.contains(&key)
4446 })
4447 .map(|site| site.line)
4448 .collect();
4449 for entry in &parsed.entries {
4450 if !entry.is_active() {
4451 continue;
4452 }
4453 if matched_entries.contains(&(file.display.as_str(), entry.comment_line)) {
4454 continue;
4455 }
4456 if entry
4457 .target_lines
4458 .iter()
4459 .any(|line| evaluated_lines.contains(line))
4460 {
4461 eprintln!(
4462 "tmt: warning: {}:{}: `tmt:ignore` matched no findings on an evaluated line (mutants may already be killed or selector/column may not match)",
4463 crate::report::sanitize_inline(&file.display),
4464 entry.comment_line,
4465 );
4466 }
4467 }
4468 }
4469 }
4470 if let Some(path) = &options.write_baseline {
4471 let unignored: Vec<Finding> = after_inline.iter().map(|(f, _)| f.clone()).collect();
4472 let single_pkg = write_ctx
4473 .single_package_run
4474 .then_some(report.package.as_str());
4475 let summary = crate::baseline::write_scoped(
4476 path,
4477 &report.package,
4478 write_ctx.ws_package_prefix,
4479 &unignored,
4480 write_ctx.partial_scope,
4481 single_pkg,
4482 )?;
4483 if summary.preserved > 0 || summary.removed > 0 {
4484 (write_ctx.note)(&format!(
4485 "baseline {}: {} entries written ({} preserved out of scope, {} resolved removed)",
4486 path.display(),
4487 summary.written,
4488 summary.preserved,
4489 summary.removed
4490 ));
4491 }
4492 }
4493 for (finding, run_survivors) in after_inline {
4494 if known
4495 .as_ref()
4496 .is_some_and(|known| known.knows_in_package(&report.package, &finding))
4497 {
4498 report.survivor_breakdown.suppressed += run_survivors;
4499 } else {
4500 report.survivor_breakdown.reported += run_survivors;
4501 report.findings.push(finding);
4502 }
4503 }
4504 report.suppressed = before - report.findings.len();
4505 if let Some(checkpoint) = checkpoint {
4506 checkpoint.finish_if_complete()?;
4507 }
4508 Ok(())
4509}
4510
4511fn workspace_report_prefix(relative: &Path) -> String {
4512 let parts: Vec<_> = relative
4513 .components()
4514 .filter_map(|part| match part {
4515 std::path::Component::Normal(name) => Some(name.to_string_lossy()),
4516 _ => None,
4517 })
4518 .collect();
4519 if parts.is_empty() {
4520 String::new()
4521 } else {
4522 format!("{}/", parts.join("/"))
4523 }
4524}
4525
4526fn repository_prefix(dir: &Path) -> String {
4530 let shown = Command::new("git")
4531 .arg("-C")
4532 .arg(dir)
4533 .args(["rev-parse", "--show-prefix"])
4534 .stderr(Stdio::null())
4535 .output();
4536 match shown {
4537 Ok(output) if output.status.success() => {
4538 String::from_utf8_lossy(&output.stdout).trim().to_string()
4539 }
4540 _ => String::new(),
4541 }
4542}
4543
4544fn spread(count: usize, wanted: usize) -> Vec<usize> {
4547 let wanted = wanted.min(count);
4548 (0..wanted).map(|nth| nth * count / wanted).collect()
4549}
4550
4551struct FilePlaces<'a> {
4553 display: &'a str,
4554 source: &'a str,
4555 lines: &'a scope::LineIndex,
4556 places: &'a [(usize, usize, String)],
4558}
4559
4560fn name_findings(findings: &mut [Finding], files: &[FilePlaces]) {
4565 let mut by_file: BTreeMap<String, Vec<&mut Finding>> = BTreeMap::new();
4566 for finding in findings {
4567 by_file
4568 .entry(finding.at().file.clone())
4569 .or_default()
4570 .push(finding);
4571 }
4572 for file in files {
4573 let Some(findings) = by_file.remove(file.display) else {
4574 continue;
4575 };
4576 let items = instrument::named_items(file.source);
4577 let index = instrument::ItemIndex::new(&items);
4578 let item_at = |line, column| {
4579 file.lines
4580 .offset_of(file.source, line, column)
4581 .map_or("", |offset| index.at(offset))
4582 };
4583 let mut positions: BTreeMap<(&str, &str), Vec<(usize, usize)>> = BTreeMap::new();
4584 for (line, column, code) in file.places {
4585 positions
4586 .entry((item_at(*line, *column), code))
4587 .or_default()
4588 .push((*line, *column));
4589 }
4590 for places in positions.values_mut() {
4591 places.sort_unstable();
4592 places.dedup();
4593 }
4594 for finding in findings {
4595 let kind = finding.kind();
4596 let at = finding.at_mut();
4597 let item = item_at(at.line, at.column);
4598 let nth = positions.get(&(item, &at.code)).map_or(0, |places| {
4599 places.partition_point(|&place| place < (at.line, at.column))
4600 });
4601 at.item = item.to_string();
4602 at.id = report::finding_id(kind, at, nth);
4603 }
4604 }
4605}
4606
4607fn mutation_of(site: &Site, mutant: &instrument::SourceMutant) -> Mutation {
4609 match &site.kind {
4610 SiteKind::Cmp { .. } => plan::CmpOp::ALL
4611 .into_iter()
4612 .find(|op| op.symbol() == mutant.into)
4613 .map_or(Mutation::Negate, Mutation::Op),
4614 SiteKind::Arith { op, .. } => {
4615 if mutant.into.trim_end_matches('=') == op.swapped().symbol() {
4616 Mutation::ArithSwap
4617 } else {
4618 Mutation::ArithSwap2
4619 }
4620 }
4621 SiteKind::Guard { .. } => Mutation::Const(mutant.into == "true"),
4622 SiteKind::Logic { .. } => Mutation::LogicSwap,
4623 SiteKind::Not { .. } => Mutation::DropNot,
4624 SiteKind::Range { .. } | SiteKind::RangeContains { .. } => Mutation::RangeEnd,
4625 SiteKind::SliceEnd { .. } => Mutation::OtherEnd,
4626 SiteKind::StrAffix { .. } => Mutation::StrContains,
4627 SiteKind::StrReplace { .. } => Mutation::StrReplaceMultiplicity,
4628 SiteKind::Clamp { .. } => {
4629 if mutant.into.contains("lower") {
4630 Mutation::ClampDropLower
4631 } else {
4632 Mutation::ClampDropUpper
4633 }
4634 }
4635 SiteKind::Rounding { op, .. } => {
4636 if mutant.into == op.alt1().name() {
4637 Mutation::RoundAlt1
4638 } else {
4639 Mutation::RoundAlt2
4640 }
4641 }
4642 SiteKind::Quantifier { .. } => Mutation::QuantifierSwap,
4643 SiteKind::Position { .. } => Mutation::PositionSwap,
4644 SiteKind::SaturatingArith { .. } => Mutation::SaturatingSwap,
4645 SiteKind::StrTrim { op, .. } => {
4646 if mutant.into == op.alt1().name() {
4647 Mutation::TrimAlt1
4648 } else {
4649 Mutation::TrimAlt2
4650 }
4651 }
4652 SiteKind::StrCaseEq { .. } => Mutation::StrExactEq,
4653 SiteKind::Abs { .. } => Mutation::DropAbs,
4654 SiteKind::IterLimit { .. } => Mutation::IterLimitDrop,
4655 SiteKind::EndianSwap { .. } => Mutation::EndianSwap,
4656 SiteKind::BitCount { .. } => Mutation::BitCountSwap,
4657 SiteKind::LoopCtrl { .. } => Mutation::LoopCtrlSwap,
4658 SiteKind::LiteralSet { elements, .. } => {
4659 let idx = elements
4660 .iter()
4661 .position(|(elem, _, _)| elem == &mutant.into)
4662 .unwrap_or(0);
4663 Mutation::DropLiteralElem(idx as u8)
4664 }
4665 _ => Mutation::Delete,
4668 }
4669}
4670
4671fn mutations_like(site: &Site, mutant: &instrument::SourceMutant, integers: bool) -> Vec<Mutation> {
4680 let mut all = vec![mutation_of(site, mutant)];
4681 if let (SiteKind::Cmp { op, .. }, Mutation::Op(into)) = (&site.kind, all[0]) {
4682 let an_order_is_needed = matches!(op, plan::CmpOp::Le | plan::CmpOp::Ge);
4683 if into == op.negated() && (integers || !an_order_is_needed) {
4684 all.push(Mutation::Negate);
4685 }
4686 match (op, into) {
4687 (plan::CmpOp::Lt, plan::CmpOp::Le) | (plan::CmpOp::Ge, plan::CmpOp::Gt) => {
4688 all.push(Mutation::Shift(1))
4689 }
4690 (plan::CmpOp::Gt, plan::CmpOp::Ge) | (plan::CmpOp::Le, plan::CmpOp::Lt) => {
4691 all.push(Mutation::Shift(-1))
4692 }
4693 _ => {}
4694 }
4695 }
4696 all
4697}
4698
4699fn describe_effects(
4702 changes: &BTreeMap<String, BTreeSet<Change>>,
4703 sites: &BTreeMap<u32, (&str, &Site)>,
4704) -> Vec<String> {
4705 let mut by_change: BTreeMap<&Change, Vec<&str>> = BTreeMap::new();
4706 for (test, found) in changes {
4707 for change in found {
4708 by_change.entry(change).or_default().push(test);
4709 }
4710 }
4711 if by_change.is_empty() {
4712 return vec![
4713 "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(),
4714 ];
4715 }
4716 let mut out = vec![];
4717 for (change, tests) in by_change.iter().take(3) {
4718 let Some((file, site)) = sites.get(&change.site()) else {
4719 continue;
4720 };
4721 let code = report::location(file, site).code;
4722 let at = format!("{file}:{}", site.line);
4723 let who = if tests.is_empty() {
4724 continue;
4725 } else if let Some(first) = tests
4726 .iter()
4727 .copied()
4728 .find(|test| *test != crate::trace::UNKNOWN_TEST)
4729 {
4730 if tests.len() == 1 {
4731 format!("`{first}`")
4732 } else {
4733 format!("`{first}` (and {} more)", tests.len() - 1)
4734 }
4735 } else if tests.len() == 1 {
4736 "a test".to_string()
4737 } else {
4738 format!("a test (and {} more)", tests.len() - 1)
4739 };
4740 out.push(match change {
4741 Change::Returns { value, .. } => {
4742 format!("with the mutant, {who} gets `{value}` from `{code}` ({at})")
4743 }
4744 Change::NowRuns { .. } => format!("with the mutant, {who} now runs `{code}` ({at})"),
4745 Change::NoLongerRuns { .. } => {
4746 format!("with the mutant, {who} no longer runs `{code}` ({at})")
4747 }
4748 Change::NewOutcome { .. } => {
4749 format!("with the mutant, {who} takes `{code}` ({at}) a way it did not before")
4750 }
4751 });
4752 }
4753 if by_change.len() > 3 {
4754 out.push(format!("(and {} more such changes)", by_change.len() - 3));
4755 }
4756 out
4757}
4758
4759#[cfg(test)]
4760mod tests;