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