use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::{Duration, Instant};
use anyhow::{Context, Result, anyhow, bail};
use crate::checkpoint::{Checkpoint, Phase};
use crate::instrument::{self, RUNTIME_MOD, Rendered, Site, SiteKind};
use crate::output_fixture::{self, Fixture};
use crate::plan::{self, Mutation};
use crate::propagation::Change;
use crate::report::{self, Finding, Report};
use crate::scope::{self};
use crate::trace::Trace;
use crate::work_lock::WorkLock;
use crate::{git_index, leftovers, progress, reverts, witness};
pub use runner::summarize_baseline_log;
#[derive(Debug)]
pub enum BaselineError {
Timeout {
diagnostic: Box<report::BaselineTimeoutDiagnostic>,
wrapper_grace_outcomes: Option<report::WrapperGraceOutcomes>,
message: String,
},
Failed {
diagnostic: Box<report::BaselineFailureDiagnostic>,
wrapper_grace_outcomes: Option<report::WrapperGraceOutcomes>,
message: String,
},
}
impl BaselineError {
pub fn to_report(&self) -> report::BaselineErrorReport {
match self {
Self::Timeout {
diagnostic,
wrapper_grace_outcomes,
message,
} => report::BaselineErrorReport {
schema_version: report::SCHEMA_VERSION,
package: diagnostic.package.clone(),
evaluation: report::Evaluation::BaselineFailed,
error: message.clone(),
wrapper_grace_outcomes: *wrapper_grace_outcomes,
baseline_timeout: Some((**diagnostic).clone()),
baseline_failure: None,
},
Self::Failed {
diagnostic,
wrapper_grace_outcomes,
message,
} => report::BaselineErrorReport {
schema_version: report::SCHEMA_VERSION,
package: diagnostic.package.clone(),
evaluation: report::Evaluation::BaselineFailed,
error: message.clone(),
wrapper_grace_outcomes: *wrapper_grace_outcomes,
baseline_timeout: None,
baseline_failure: Some((**diagnostic).clone()),
},
}
}
}
impl std::fmt::Display for BaselineError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Timeout { message, .. } | Self::Failed { message, .. } => f.write_str(message),
}
}
}
impl std::error::Error for BaselineError {}
fn round_millis(d: Duration) -> f64 {
(d.as_secs_f64() * 1000.0).round() / 1000.0
}
fn format_baseline_timings_section(
completed: &[report::BaselineTimingEntry],
failed_runner: &str,
failed_elapsed: f64,
failed_label: &str,
total: usize,
) -> String {
if completed.is_empty() && total <= 1 {
return String::new();
}
const MAX_DISPLAY: usize = 10;
let mut out = format!(
"\nbaseline timings ({}/{} completed):",
completed.len(),
total
);
for entry in completed.iter().take(MAX_DISPLAY) {
out.push_str(&format!(
"\n {}: {:.3}s",
entry.runner, entry.elapsed_seconds
));
}
if completed.len() > MAX_DISPLAY {
out.push_str(&format!(
"\n ... and {} more completed",
completed.len() - MAX_DISPLAY
));
}
let prefix = if failed_label == "timed out" { ">" } else { "" };
out.push_str(&format!(
"\n {failed_runner}: {prefix}{failed_elapsed:.3}s ({failed_label})"
));
out
}
fn format_log_summary_section(summary: &[String]) -> String {
if summary.is_empty() {
return String::new();
}
let mut out = String::from("\nlog summary:");
for line in summary {
out.push_str("\n ");
out.push_str(line);
}
out
}
#[derive(Clone)]
pub struct Options {
pub dir: PathBuf,
pub package: Option<String>,
pub list: bool,
pub test_workspace: bool,
pub verify: bool,
pub work_dir: Option<PathBuf>,
pub progress: bool,
pub since: Option<String>,
pub lines: Vec<String>,
pub exclude_files: Vec<String>,
pub baseline: Option<PathBuf>,
pub write_baseline: Option<PathBuf>,
pub also_test: Vec<String>,
pub dependents: bool,
pub effects: bool,
pub rebuild: bool,
pub error_values: Vec<String>,
pub source_only: bool,
pub literal_operators: bool,
pub shard: Option<report::Shard>,
pub nextest: Option<report::Nextest>,
pub test_selection: TestSelection,
pub opt_level: Option<u8>,
pub timeout_seconds: Option<u64>,
pub baseline_timeout_seconds: Option<u64>,
pub baseline_jobs: usize,
pub serial_timeout_rechecks: bool,
pub wrapper_grace: Duration,
pub audit: Option<usize>,
pub cargo: CargoConfig,
pub jobs: usize,
pub all_files: bool,
pub git_index: bool,
pub copy_fixtures: Vec<PathBuf>,
pub copy_fixture_excludes: Vec<PathBuf>,
pub output_fixtures: Vec<Fixture>,
pub stage_external: Vec<StageExternal>,
pub checkpoint: bool,
pub doc: bool,
}
#[derive(Clone, Default)]
pub struct TestSelection {
pub isolate: bool,
pub lib: bool,
pub bins: bool,
pub integration_tests: Vec<String>,
pub targets: Vec<String>,
pub include: Vec<String>,
pub filter: Vec<String>,
pub exclude: Vec<String>,
pub include_ignored: bool,
pub wrapper: Option<PathBuf>,
}
impl TestSelection {
pub(crate) fn has_target_filters(&self) -> bool {
self.lib || self.bins || !self.integration_tests.is_empty() || !self.targets.is_empty()
}
fn enabled(&self) -> bool {
self.isolate
|| self.has_target_filters()
|| !self.include.is_empty()
|| !self.filter.is_empty()
|| !self.exclude.is_empty()
|| self.include_ignored
|| self.wrapper.is_some()
}
pub(crate) fn matches_test(&self, test: &str, was_ignored: bool) -> bool {
if was_ignored && !self.include_ignored {
return false;
}
if self.exclude.iter().any(|name| name == test) {
return false;
}
if !self.include.is_empty() || !self.filter.is_empty() {
let exact = self.include.iter().any(|name| name == test);
let partial = self.filter.iter().any(|pat| test.contains(pat));
if !exact && !partial {
return false;
}
}
true
}
}
pub use crate::report::CargoConfig;
pub use workcopy::StageExternal;
impl CargoConfig {
pub fn flags(&self) -> Vec<String> {
let mut flags = vec![];
if !self.features.is_empty() {
flags.extend(["--features".to_string(), self.features.join(",")]);
}
for (on, flag) in [
(self.all_features, "--all-features"),
(self.no_default_features, "--no-default-features"),
(self.locked, "--locked"),
] {
if on {
flags.push(flag.to_string());
}
}
flags
}
}
const NEARBY_LINES: usize = 6;
const WORK_MARKER: &str = ".tmt-work-dir";
const STD_ALIAS: &str = "__tmt_std";
const MAX_REPAIR_ROUNDS: usize = 40;
const MAX_TEST_FILTERS: usize = 200;
mod cargo;
mod repair_cache;
mod runner;
mod scope_blame;
mod session;
mod witness_runner;
mod workcopy;
use cargo::*;
use runner::*;
use scope_blame::*;
use session::*;
use witness_runner::*;
use workcopy::*;
struct SourceFile {
display: String,
path: PathBuf,
owners: BTreeSet<PathBuf>,
original: String,
lines: scope::LineIndex,
sites: Vec<Site>,
rebuild_sites: Vec<Site>,
places: Vec<(usize, usize, String)>,
rendered: Option<Rendered>,
}
fn write_rendered(
file: &mut SourceFile,
state: &WorkCopy,
suffix: &str,
disabled: &HashSet<u32>,
newly_disabled: &HashSet<u32>,
) -> Result<()> {
if file.rendered.is_none()
|| file
.sites
.iter()
.any(|site| newly_disabled.contains(&site.id))
{
file.rendered = Some(instrument::render(&file.original, &file.sites, &|id| {
!disabled.contains(&id)
}));
}
let rendered = file.rendered.as_ref().expect("rendered before writing");
if suffix.is_empty() {
state.write(&file.path, &rendered.text)
} else {
state.write(&file.path, &format!("{}{suffix}", rendered.text))
}
}
#[derive(Clone, Copy)]
struct WorkspaceShard {
offset: usize,
total: usize,
member_total: usize,
}
struct CatalogueSnapshot {
path: PathBuf,
ready: std::cell::Cell<bool>,
_lock: WorkLock,
}
struct WorkspaceBatch<'a> {
metadata: &'a Metadata,
work: &'a Path,
catalogue: Option<CatalogueSnapshot>,
}
pub fn select_single_package_name(dir: &Path, cargo: &CargoConfig) -> Option<String> {
let canon = dir.canonicalize().ok()?;
let metadata = cargo_metadata(&canon, cargo).ok()?;
metadata
.packages
.iter()
.find(|p| p.manifest_path.parent() == Some(canon.as_path()))
.or(match &metadata.packages[..] {
[only] => Some(only),
_ => None,
})
.map(|p| p.name.clone())
}
pub fn run_packages(options: &Options, names: &[String]) -> Result<Vec<(String, Result<Report>)>> {
run_packages_with(options, names, |_, base| Ok(base.clone()))
}
pub fn run_packages_with(
options: &Options,
names: &[String],
options_for_package: impl FnMut(&str, &Options) -> Result<Options>,
) -> Result<Vec<(String, Result<Report>)>> {
let mut reports = vec![];
run_packages_each_with(options, names, options_for_package, |name, result| {
reports.push((name, result));
Ok(())
})?;
Ok(reports)
}
pub fn run_packages_each(
options: &Options,
names: &[String],
completed: impl FnMut(String, Result<Report>) -> Result<()>,
) -> Result<()> {
run_packages_each_with(options, names, |_, base| Ok(base.clone()), completed)
}
fn ensure_package_dir(given: &Path, canonical: &Path, workspace_mode: bool) -> Result<()> {
if !canonical.is_file() {
return Ok(());
}
let given_text = crate::report::sanitize_inline(&given.display().to_string());
let manifest_name = std::ffi::OsStr::new("Cargo.toml");
let manifest_path = if given.file_name() == Some(manifest_name) {
Some(given)
} else if canonical.file_name() == Some(manifest_name) {
Some(canonical)
} else {
None
};
if let Some(manifest) = manifest_path {
let parent = manifest
.parent()
.filter(|p| !p.as_os_str().is_empty())
.map(|p| p.display().to_string())
.unwrap_or_else(|| ".".to_string());
let parent_text = crate::report::sanitize_inline(&parent);
bail!(
"`{given_text}` is a Cargo manifest file, not a directory; pass its parent directory `{parent_text}` instead"
);
}
let target_kind = if workspace_mode {
"workspace/package directory"
} else {
"package directory"
};
bail!(
"`{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"
);
}
pub fn run_packages_each_with(
options: &Options,
names: &[String],
mut options_for_package: impl FnMut(&str, &Options) -> Result<Options>,
mut completed: impl FnMut(String, Result<Report>) -> Result<()>,
) -> Result<()> {
let dir = options
.dir
.canonicalize()
.with_context(|| format!("no such directory: {}", options.dir.display()))?;
ensure_package_dir(&options.dir, &dir, true)?;
let metadata = cargo_metadata(&dir, &options.cargo)?;
let all: BTreeSet<_> = metadata.packages.iter().map(|p| p.name.clone()).collect();
let selected = if names.is_empty() {
all.clone()
} else {
names.iter().cloned().collect()
};
if let Some(unknown) = selected.difference(&all).next() {
bail!("no package `{unknown}` in the workspace");
}
if !options.lines.is_empty() {
let selected_pkgs: Vec<&Package> = metadata
.packages
.iter()
.filter(|p| selected.contains(&p.name))
.collect();
validate_workspace_lines(&options.lines, &metadata.workspace_root, &selected_pkgs)?;
}
let base = options
.work_dir
.clone()
.unwrap_or_else(|| metadata.target_directory.join("tmt-workspace"));
fs::create_dir_all(&base).with_context(|| format!("creating {}", base.display()))?;
let base = base.canonicalize()?;
let workspace_canon = metadata.workspace_root.canonicalize()?;
if workspace_canon.starts_with(&base) {
bail!(
"the work directory {} contains the workspace",
base.display()
);
}
let mut member_options = Vec::with_capacity(selected.len());
let mut used_work_dirs: Vec<(String, PathBuf)> = Vec::new();
for name in selected {
let mut member = options_for_package(&name, options)?;
member.package = Some(name.clone());
let custom_work = member
.work_dir
.as_ref()
.is_some_and(|w| options.work_dir.as_ref() != Some(w));
let member_work = if custom_work {
let custom = member.work_dir.clone().expect("custom work_dir");
fs::create_dir_all(&custom)
.with_context(|| format!("creating {}", custom.display()))?;
let canon = custom.canonicalize()?;
if workspace_canon.starts_with(&canon) {
bail!(
"the work directory {} for `{name}` contains the workspace",
canon.display()
);
}
canon
} else {
base.join(&name)
};
for (other_name, other_dir) in &used_work_dirs {
if member_work == *other_dir
|| member_work.starts_with(other_dir)
|| other_dir.starts_with(&member_work)
{
bail!(
"overlapping work directories for `{name}` ({}) and `{other_name}` ({})",
member_work.display(),
other_dir.display()
);
}
}
used_work_dirs.push((name.clone(), member_work.clone()));
member.work_dir = Some(member_work);
member_options.push((name, member));
}
let uniform_copy_settings = member_options
.first()
.map(|(_, first)| {
member_options.iter().all(|(_, m)| {
m.all_files == first.all_files
&& m.git_index == first.git_index
&& m.copy_fixtures == first.copy_fixtures
&& m.copy_fixture_excludes == first.copy_fixture_excludes
&& m.stage_external == first.stage_external
})
})
.unwrap_or(true);
let catalogue_dir = base.join(".catalogue");
let catalogue = if uniform_copy_settings && (options.list || options.shard.is_some()) {
for (name, member_dir) in &used_work_dirs {
if *member_dir == catalogue_dir
|| member_dir.starts_with(&catalogue_dir)
|| catalogue_dir.starts_with(member_dir)
{
bail!(
"work directory {} for `{name}` overlaps shared workspace catalogue {}",
member_dir.display(),
catalogue_dir.display()
);
}
}
let path = work_directory(&base, ".catalogue")?;
Some(CatalogueSnapshot {
_lock: WorkLock::take(&path)?,
path,
ready: std::cell::Cell::new(false),
})
} else {
None
};
let batch = WorkspaceBatch {
metadata: &metadata,
work: &base,
catalogue,
};
let Some(shard) = options.shard else {
for (name, member) in member_options {
if crate::interrupt::is_interrupted() {
return Ok(());
}
let result = run_package(&member, Some(&batch), None);
if let Err(err) = &result
&& crate::interrupt::is_interrupted_err(err)
{
return Err(crate::interrupt::Interrupted.into());
}
let interrupted = result.as_ref().is_ok_and(|report| report.interrupted);
completed(name, result)?;
if interrupted || crate::interrupt::is_interrupted() {
return Ok(());
}
}
return Ok(());
};
if shard.index >= shard.count || member_options.iter().any(|(_, m)| !m.source_only) {
bail!("shards require --source-only and a valid shard index");
}
let mut catalogues = Vec::with_capacity(member_options.len());
for (name, member) in member_options {
if crate::interrupt::is_interrupted() {
return Err(crate::interrupt::Interrupted.into());
}
let mut preview = member.clone();
preview.list = true;
preview.shard = None;
preview.progress = false;
let catalogue = run_package(&preview, Some(&batch), None).map(|mut report| {
let count = report.mutants.as_ref().map_or(0, Vec::len);
if !member.list {
report.mutants = None;
}
(count, report)
});
if catalogue
.as_ref()
.is_ok_and(|(_, report)| report.interrupted)
|| crate::interrupt::is_interrupted()
{
return Err(crate::interrupt::Interrupted.into());
}
catalogues.push((name, member, catalogue));
}
let total = catalogues
.iter()
.filter_map(|(_, _, catalogue)| catalogue.as_ref().ok())
.map(|(count, _)| count)
.sum();
let mut offset = 0;
for (name, member, catalogue) in catalogues {
if crate::interrupt::is_interrupted() {
return Ok(());
}
let result = catalogue.and_then(|(member_total, mut report)| {
let range = WorkspaceShard {
offset,
total,
member_total,
};
offset += member_total;
if member.list {
report.analysis.shard = Some(shard);
let mut index = range.offset;
if let Some(mutants) = report.mutants.as_mut() {
mutants.retain(|_| {
let keep = shard.contains(index, total);
index += 1;
keep
});
}
Ok(report)
} else {
run_package(&member, Some(&batch), Some(range))
}
});
let interrupted = result.as_ref().is_ok_and(|report| report.interrupted);
completed(name, result)?;
if interrupted || crate::interrupt::is_interrupted() {
return Ok(());
}
}
Ok(())
}
struct LeftoverNote(bool);
impl Drop for LeftoverNote {
fn drop(&mut self) {
use std::sync::atomic::Ordering;
let stopped = leftovers::STOPPED.swap(0, Ordering::Relaxed);
let not_stopped = leftovers::NOT_STOPPED.swap(0, Ordering::Relaxed);
if let Some(text) = leftover_note(stopped, not_stopped)
&& self.0
{
eprintln!("tmt: {text}");
}
}
}
fn leftover_note(stopped: usize, not_stopped: usize) -> Option<String> {
let stopped = (stopped > 0).then(|| {
format!("stopped {stopped} processes that the tests had left running after their run")
});
let not_stopped = (not_stopped > 0).then(|| {
format!(
"after {not_stopped} runs something the tests started may still be running \
(it could not be found or stopped)"
)
});
match (stopped, not_stopped) {
(None, None) => None,
(Some(one), None) | (None, Some(one)) => Some(one),
(Some(stopped), Some(not_stopped)) => Some(format!("{stopped}; {not_stopped}")),
}
}
pub fn run(options: &Options) -> Result<Report> {
run_package(options, None, None)
}
fn interrupted_stub_report(options: &Options, package: Option<String>) -> Report {
let mut report = Report {
package: package
.or_else(|| options.package.clone())
.unwrap_or_default(),
interrupted: true,
wrapper_grace_outcomes: options
.test_selection
.wrapper
.as_ref()
.map(|_| report::WrapperGraceOutcomes::default()),
..Report::default()
};
if crate::interrupt::is_interrupted() {
report.interrupted = true;
}
report.record_evaluation();
report
}
fn run_package(
options: &Options,
batch: Option<&WorkspaceBatch<'_>>,
workspace_shard: Option<WorkspaceShard>,
) -> Result<Report> {
let mut resolved_package: Option<String> = options.package.clone();
match run_package_inner(options, batch, workspace_shard, &mut resolved_package) {
Ok(report) => Ok(report),
Err(err)
if crate::interrupt::is_interrupted() || crate::interrupt::is_interrupted_err(&err) =>
{
Ok(interrupted_stub_report(options, resolved_package))
}
Err(err) => Err(err),
}
}
fn run_package_inner(
options: &Options,
batch: Option<&WorkspaceBatch<'_>>,
workspace_shard: Option<WorkspaceShard>,
resolved_package: &mut Option<String>,
) -> Result<Report> {
let _leftovers = LeftoverNote(options.progress);
let error_values = validate_package_options(options)?;
let selection = &options.test_selection;
let effective_jobs = if options.source_only { 1 } else { options.jobs };
let note = |text: &str| {
if options.progress {
eprintln!("tmt: {}", report::sanitize_inline(text));
}
};
let dir = options
.dir
.canonicalize()
.with_context(|| format!("no such directory: {}", options.dir.display()))?;
ensure_package_dir(&options.dir, &dir, false)?;
let local_metadata;
let metadata = if let Some(batch) = batch {
batch.metadata
} else {
local_metadata = cargo_metadata(&dir, &options.cargo)?;
&local_metadata
};
let catalogue = batch
.and_then(|batch| batch.catalogue.as_ref())
.filter(|_| options.list);
let enclosing_package = metadata
.packages
.iter()
.filter(|p| {
p.manifest_path
.parent()
.is_some_and(|root| dir != root && dir.starts_with(root))
})
.max_by_key(|p| {
p.manifest_path
.parent()
.map_or(0, |root| root.as_os_str().len())
});
let package = match &options.package {
Some(name) => metadata.packages.iter().find(|p| &p.name == name),
None => metadata
.packages
.iter()
.find(|p| p.manifest_path.parent() == Some(dir.as_path()))
.or(match &metadata.packages[..] {
[only] => Some(only),
_ => None,
}),
}
.ok_or_else(|| {
if let Some(name) = &options.package {
anyhow!(
"no package `{}` in workspace",
crate::report::sanitize_inline(name)
)
} else if let Some(owner) = enclosing_package {
anyhow!(
"`{}` 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)",
crate::report::sanitize_inline(&options.dir.display().to_string()),
crate::report::sanitize_inline(&owner.name),
crate::report::sanitize_inline(&owner.name),
)
} else {
anyhow!("cannot tell which package to analyse; pass --package <name>")
}
})?;
*resolved_package = Some(package.name.clone());
if options.package.is_none()
&& !dir.join("Cargo.toml").is_file()
&& package.manifest_path.parent() != Some(dir.as_path())
&& options.progress
{
eprintln!(
"tmt: note: `{}` has no Cargo.toml; analysing package `{}` (use `--lines <file>` to scope to specific files)",
crate::report::sanitize_inline(&options.dir.display().to_string()),
crate::report::sanitize_inline(&package.name),
);
}
let mut test_packages: Vec<&Package> = vec![package];
for name in &options.also_test {
let other = metadata
.packages
.iter()
.find(|p| &p.name == name)
.ok_or_else(|| anyhow!("--also-test: no package `{name}` in the workspace"))?;
if !test_packages.iter().any(|p| p.name == other.name) {
test_packages.push(other);
}
}
if options.test_workspace {
test_packages.extend(
metadata
.packages
.iter()
.filter(|other| {
!test_packages
.iter()
.any(|selected| selected.name == other.name)
})
.collect::<Vec<_>>(),
);
}
if options.dependents {
for name in dependents_of(&package.name, &metadata.packages) {
if let Some(other) = metadata.packages.iter().find(|p| p.name == name)
&& !test_packages.iter().any(|p| p.name == other.name)
{
test_packages.push(other);
}
}
}
if !options.list {
validate_target_selection(&test_packages, selection)?;
}
let is_kind = |t: &Target, kinds: &[&str]| t.kind.iter().any(|k| kinds.contains(&k.as_str()));
let root_target = package
.targets
.iter()
.find(|t| {
is_kind(
t,
&["lib", "rlib", "cdylib", "staticlib", "dylib", "proc-macro"],
)
})
.or_else(|| package.targets.iter().find(|t| is_kind(t, &["bin"])))
.ok_or_else(|| anyhow!("package `{}` has no lib or bin target", package.name))?;
let PreparedWorkCopy {
workspace,
work,
work_lock,
copy,
state,
external_deps,
} = prepare_work_copy(options, metadata, batch, catalogue, ¬e)?;
let in_copy = |path: &Path| -> Result<PathBuf> {
let canonical = path.canonicalize()?;
let relative = canonical
.strip_prefix(&workspace)
.with_context(|| format!("{} is outside the workspace", path.display()))?;
Ok(copy.join(relative))
};
let package_dir = in_copy(
package
.manifest_path
.parent()
.expect("manifest has a parent"),
)?;
let root_file = in_copy(&root_target.src_path)?;
let source_dir = root_file
.parent()
.expect("source file has a parent")
.to_path_buf();
let mut roots = BTreeMap::new();
for owner in &metadata.packages {
for target in &owner.targets {
let production = owner.name == package.name && target.is_production();
if let Ok(path) = in_copy(&target.src_path)
&& path.is_file()
{
let selected = roots.entry(path).or_insert(false);
*selected |= production;
}
}
}
let paths = source_graph(roots, ©, |path| state.original(path, &workspace))?;
let package_orig_dir = package
.manifest_path
.parent()
.expect("manifest has a parent");
let scope = requested_scope(
options,
&workspace,
package_orig_dir,
&package.name,
batch.is_some(),
)?;
let mut skipped = vec![];
let mut files = vec![];
let mut excluded_any = false;
let mut next_id = 0u32;
let want_witnesses = (options.list || options.rebuild || options.source_only)
&& root_target.test_build_arg() == Some(("--lib", None));
let count_rebuild_witnesses =
!want_witnesses && root_target.test_build_arg() == Some(("--lib", None));
let mut witness_candidates = vec![];
let mut unbuilt_witness_candidates = vec![];
for (path, owners) in paths {
let Some(original) = state.original(&path, &workspace)? else {
continue; };
let display = relative_source(&path, &package_dir).display().to_string();
if scope::matches_any_glob(&options.exclude_files, &display) {
excluded_any = true;
continue;
}
let selected_file = scope.as_ref().is_none_or(|scope| {
let relative = path.strip_prefix(©).unwrap_or(&path).to_string_lossy();
scope.touches(&relative, 1, usize::MAX)
});
if !selected_file && path != root_file {
continue;
}
match instrument::parse_source(&original) {
Ok(parsed) => {
let mut found =
instrument::discover_parsed(&original, &parsed, next_id, &error_values);
if (want_witnesses || count_rebuild_witnesses)
&& selected_file
&& owners.consumers.len() == 1
&& owners.consumers.contains(&root_file)
{
let discovered = witness::discover_parsed(
&original,
&parsed,
want_witnesses && !options.list,
)
.into_iter()
.map(|mut candidate| {
candidate.file = path.clone();
candidate
});
if want_witnesses {
witness_candidates.extend(discovered);
} else {
unbuilt_witness_candidates.extend(discovered);
}
if want_witnesses && !options.list && !options.literal_operators {
witness_candidates.extend(
stronger_assertions(
&original,
&parsed,
found.sites.iter().chain(&found.rebuild_sites),
)
.into_iter()
.map(|mut candidate| {
candidate.file = path.clone();
candidate
}),
);
}
}
next_id += found.sites.len() as u32;
if owners.consumers.len() != 1 || !owners.consumers.contains(&root_file) {
found.rebuild_sites.append(&mut found.sites);
}
let places = if options.list {
vec![]
} else {
found
.sites
.iter()
.chain(&found.rebuild_sites)
.map(|site| (site.line, site.column, report::one_line(&site.text)))
.collect()
};
files.push(SourceFile {
display,
path,
owners: owners.production,
lines: scope::LineIndex::new(&original),
original,
places,
sites: found.sites,
rebuild_sites: found.rebuild_sites,
rendered: None,
});
}
Err(err) => {
if selected_file {
let diagnostic = format!("{err:#}");
note(&format!("skipping {display}: {diagnostic}"));
let end_line = scope::line_of(&original, original.len());
let end_column = original.rsplit('\n').next().unwrap_or("").chars().count() + 1;
skipped.push(report::SkippedSite::new(
report::Location {
file: display,
line: 1,
column: 1,
..Default::default()
},
(end_line, end_column),
report::SkipReason::UnparseableSource,
Some(diagnostic),
));
}
}
}
}
let since_hunks = match options.since.as_deref() {
Some(revision) if !options.list && options.shard.is_none() => {
scope::hunks(&since_diff(&workspace, revision)?)
}
_ => vec![],
};
let mut tests_changed: Vec<(PathBuf, Vec<scope::Hunk>)> = vec![];
let mut undo_paths: HashSet<PathBuf> = HashSet::new();
let mut not_built_reverts: usize = 0;
let mut beyond_places: HashSet<(PathBuf, usize, usize)> = HashSet::new();
if let Some(scope) = &scope {
for file in &mut files {
let relative = file
.path
.strip_prefix(©)
.unwrap_or(&file.path)
.to_string_lossy()
.into_owned();
let in_scope = |site: &Site| {
scope.touches(&relative, file.lines.line_of(site.start), file.lines.line_of(site.end))
|| scope.touches(&relative, site.line, site.line)
};
let of_file: Vec<scope::Hunk> = since_hunks
.iter()
.filter(|hunk| hunk.file == relative)
.cloned()
.collect();
let changes_count = reverts::changes(&file.original, &of_file).len();
if options.rebuild || options.source_only {
if changes_count > 0 || reverts::mixed(&file.original, &of_file) > 0 {
undo_paths.insert(file.path.clone());
}
} else {
not_built_reverts += changes_count;
}
let of_tests = reverts::test_hunks(&file.original, &of_file);
if of_tests.is_empty() {
file.sites.retain(in_scope);
} else {
beyond_places.extend(
file.sites
.iter()
.filter(|site| !in_scope(site))
.map(|site| (file.path.clone(), site.start, site.end)),
);
tests_changed.push((file.path.clone(), of_tests));
}
file.rebuild_sites.retain(in_scope);
}
files.retain(|f| {
!f.sites.is_empty()
|| !f.rebuild_sites.is_empty()
|| f.path == root_file
|| witness_candidates.iter().any(|c| c.file == f.path)
|| unbuilt_witness_candidates.iter().any(|c| c.file == f.path)
|| undo_paths.contains(&f.path)
});
}
if !options.list {
for candidate in witness_candidates.iter().filter(|c| !c.existing) {
if let Some(file) = files.iter_mut().find(|file| file.path == candidate.file) {
let at = witness_location(file, candidate);
file.places.push((at.line, at.column, at.code));
}
}
}
let witness_in_scope = |candidate: &witness::Candidate| {
let Some(file) = files.iter().find(|file| file.path == candidate.file) else {
return false;
};
let relative = file
.path
.strip_prefix(©)
.unwrap_or(&file.path)
.to_string_lossy();
scope.as_ref().is_none_or(|scope| {
let site_in_scope = if candidate.edits.len() == 1 {
scope.touches(&relative, *candidate.scope.start(), *candidate.scope.end())
} else {
candidate.edits.iter().any(|edit| {
scope.touches(
&relative,
file.lines.line_of(edit.span.start),
file.lines.line_of(edit.span.end),
)
})
};
site_in_scope
|| candidate
.signature_lines
.iter()
.any(|&line| scope.touches(&relative, line, line))
})
};
witness_candidates.retain(&witness_in_scope);
unbuilt_witness_candidates.retain(&witness_in_scope);
let not_built_witnesses = unbuilt_witness_candidates
.iter()
.filter(|candidate| !candidate.existing)
.count();
let unassessed_test_changes: Vec<String> = if let Some(revision) = options.since.as_deref()
&& !options.list
{
let integration_prefixes: Vec<String> = test_packages
.iter()
.flat_map(|pkg| {
let pkg_dir = pkg.manifest_path.parent().unwrap_or(&workspace);
let pkg_rel = pkg_dir.strip_prefix(&workspace).ok();
let pkg_tests_dir = pkg_rel.map(|rel| {
let s = rel.join("tests").to_string_lossy().replace('\\', "/");
format!("{s}/")
});
let workspace_ref = &workspace;
let explicit_targets = pkg.targets.iter().flat_map(move |t| {
if !t.kind.iter().any(|k| k == "test") {
return vec![];
}
let Ok(rel) = t.src_path.strip_prefix(workspace_ref) else {
return vec![];
};
let mut out = vec![rel.to_string_lossy().replace('\\', "/")];
if let (Some(parent), Some(pkg_r)) = (rel.parent(), pkg_rel) {
let is_pkg_root = parent == pkg_r;
let is_src = parent == pkg_r.join("src");
if !is_pkg_root && !is_src && !parent.as_os_str().is_empty() {
out.push(format!("{}/", parent.to_string_lossy().replace('\\', "/")));
}
}
out
});
pkg_tests_dir.into_iter().chain(explicit_targets)
})
.collect();
let is_integration_test = |ws_rel: &str| {
ws_rel.ends_with(".rs")
&& integration_prefixes.iter().any(|prefix| {
if prefix.ends_with('/') {
ws_rel.starts_with(prefix)
} else {
ws_rel == prefix
}
})
};
since_changed_files(&workspace, revision)?
.into_iter()
.filter(|f| is_integration_test(f))
.collect()
} else {
vec![]
};
let total_sites: usize = files
.iter()
.map(|f| f.sites.len() + f.rebuild_sites.len())
.sum::<usize>()
+ witness_candidates
.iter()
.filter(|candidate| !candidate.existing)
.count();
let files_with_sites = files
.iter()
.filter(|f| {
!f.sites.is_empty()
|| !f.rebuild_sites.is_empty()
|| witness_candidates
.iter()
.any(|c| !c.existing && c.file == f.path)
})
.count();
note(&format!(
"{total_sites} sites in {files_with_sites} {}",
if files_with_sites == 1 {
"file"
} else {
"files"
}
));
if options.source_only {
for file in &mut files {
file.rebuild_sites.append(&mut file.sites);
}
}
let source_mutants = |file: &SourceFile, site: &Site, include_boundary: bool| {
let mut mutants = instrument::source_mutants(site);
if include_boundary {
mutants.extend(instrument::source_boundary_mutant(site));
}
if options.literal_operators {
instrument::literal_operator_mutants(&file.original, site, &mut mutants);
}
instrument::keep_line_ends(&file.original, &mut mutants);
mutants
};
let counts = options.shard.map(|_| {
let regular: usize = files
.iter()
.map(|file| {
file.rebuild_sites
.iter()
.map(|site| source_mutants(file, site, true).len())
.sum::<usize>()
})
.sum();
let total = regular
+ witness_candidates
.iter()
.filter(|candidate| !candidate.existing)
.count();
(regular, total)
});
if let (Some(range), Some((_, local_total))) = (workspace_shard, counts)
&& range.member_total != local_total
{
bail!("package catalogue changed while preparing its workspace shard");
}
let in_shard = |index| match (options.shard, counts, workspace_shard) {
(Some(shard), _, Some(range)) => shard.contains(range.offset + index, range.total),
(Some(shard), Some((_, total)), _) => shard.contains(index, total),
_ => true,
};
if let Some((mut index, _)) = counts {
witness_candidates.retain(|candidate| {
if candidate.existing {
return true;
}
let selected = in_shard(index);
index += 1;
selected
});
}
let empty_shard = counts.is_some_and(|(_, total)| !(0..total).any(in_shard));
let package_path = package.manifest_path.parent().unwrap_or(Path::new("."));
let mut report_path = repository_prefix(package_path);
if report_path.is_empty()
&& batch.is_some()
&& let Ok(relative) = package_path.strip_prefix(&workspace)
{
report_path = workspace_report_prefix(relative);
}
let mut report = Report {
package: package.name.clone(),
sites: if empty_shard { 0 } else { total_sites },
analysis: report::Analysis {
package_path: report_path,
since: options.since.clone(),
lines: options.lines.clone(),
exclude_files: options.exclude_files.clone(),
tests_of: test_packages.iter().map(|p| p.name.clone()).collect(),
cargo: options.cargo.clone(),
opt_level: options.opt_level,
timeout_seconds: options.timeout_seconds,
baseline_timeout_seconds: options.baseline_timeout_seconds,
baseline_jobs: (options.baseline_jobs > 1).then_some(options.baseline_jobs),
timeout_recheck: if options.serial_timeout_rechecks {
"serial"
} else {
"none"
},
wrapper_grace_seconds: selection
.wrapper
.as_ref()
.map(|_| options.wrapper_grace.as_secs()),
rebuild: options.rebuild || options.source_only,
verified: options.verify && !options.source_only,
doc_tests: options.doc,
source_only: options.source_only,
literal_operators: options.literal_operators,
shard: options.shard,
nextest: options.nextest.clone(),
error_values: error_values
.iter()
.map(|value| (*value).to_owned())
.collect(),
test_selection: None,
git_index: options.git_index,
copy_fixtures: options.copy_fixtures.clone(),
copy_fixture_excludes: options.copy_fixture_excludes.clone(),
output_fixtures: options.output_fixtures.clone(),
stage_external: options.stage_external.clone(),
checkpoint: (options.checkpoint && !options.list)
.then(|| work.join("checkpoint.jsonl")),
},
skipped,
wrapper_grace_outcomes: if options.list {
None
} else {
selection
.wrapper
.as_ref()
.map(|_| report::WrapperGraceOutcomes::default())
},
baseline: if options.list {
None
} else {
options.baseline.clone()
},
unassessed_test_changes,
..Report::default()
};
if options.list {
if catalogue.is_none() {
state.settle(&workspace)?;
}
let mut candidates = vec![];
let mut index = 0;
for file in &files {
let sites = file
.sites
.iter()
.map(|site| (site, false))
.chain(file.rebuild_sites.iter().map(|site| (site, true)));
for (site, requires_rebuild) in sites {
for mutant in source_mutants(file, site, true) {
if in_shard(index) {
candidates.push(report::Candidate {
what: mutant.what,
into: mutant.into,
requires_rebuild,
edits: vec![candidate_edit(
file,
mutant.start,
mutant.end,
mutant.replacement,
)],
});
}
index += 1;
}
}
}
candidates.extend(
witness_candidates
.iter()
.filter(|candidate| !candidate.existing)
.filter_map(|candidate| {
let file = files.iter().find(|file| file.path == candidate.file)?;
Some(report::Candidate {
what: "witness".into(),
into: candidate.description.clone(),
requires_rebuild: true,
edits: candidate
.edits
.iter()
.map(|edit| {
candidate_edit(
file,
edit.span.start,
edit.span.end,
edit.replacement.clone(),
)
})
.collect(),
})
}),
);
report.mutants = Some(candidates);
return Ok(report);
}
let ws_package_prefix = package_dir
.strip_prefix(©)
.unwrap_or(Path::new(""))
.to_string_lossy()
.replace('\\', "/");
let all_files_excluded = excluded_any && files.is_empty();
let is_partial_scope =
scope.is_some() || !options.exclude_files.is_empty() || options.shard.is_some();
if empty_shard
|| ((scope.is_some() || all_files_excluded) && total_sites == 0 && undo_paths.is_empty())
{
state.settle(&workspace)?;
if let Some(path) = &options.baseline {
let loaded = crate::baseline::load(path)?;
loaded.validate_for_package(&package.name, path)?;
}
if crate::interrupt::is_interrupted() {
report.interrupted = true;
}
if !report.interrupted
&& let Some(path) = &options.write_baseline
{
let partial = crate::baseline::PartialScope {
scope: scope.as_ref(),
exclude_files: &options.exclude_files,
preserve_all_existing: true,
};
let single_pkg = batch.is_none().then_some(package.name.as_str());
let summary = crate::baseline::write_scoped(
path,
&package.name,
&ws_package_prefix,
&[],
Some(&partial),
single_pkg,
)?;
if summary.preserved > 0 {
note(&format!(
"baseline {}: preserved {} out-of-scope entries (no sites evaluated)",
path.display(),
summary.preserved
));
}
}
if !empty_shard {
report.mutants_not_built += not_built_reverts + not_built_witnesses;
}
if crate::interrupt::is_interrupted() {
report.interrupted = true;
}
report.record_evaluation();
if let Some(path) = report.analysis.checkpoint.as_deref() {
let checkpoint = Checkpoint::open(path)?;
let settings =
serde_json::json!({"analysis": &report.analysis, "package": &package.name});
let identity = crate::campaign_identity::compute(©, &settings, [], false)?;
checkpoint.start(&identity, settings)?;
checkpoint.finish()?;
}
return Ok(report);
}
for (id, site) in files
.iter_mut()
.flat_map(|file| &mut file.sites)
.enumerate()
{
site.id = id as u32;
}
let beyond: HashSet<u32> = files
.iter()
.flat_map(|file| {
file.sites
.iter()
.filter(|site| beyond_places.contains(&(file.path.clone(), site.start, site.end)))
.map(|site| site.id)
})
.collect();
let root_source = state
.original(&root_file, &workspace)?
.with_context(|| format!("{} is missing", root_target.src_path.display()))?;
let root_suffix = if options.source_only || files.iter().all(|file| file.sites.is_empty()) {
String::new()
} else {
state.write(
&source_dir.join(format!("{RUNTIME_MOD}.rs")),
crate::RUNTIME_SOURCE,
)?;
let std_alias = format!("extern crate std as {STD_ALIAS};");
if root_source.contains(&std_alias) {
format!("\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
} else {
format!("\n#[doc(hidden)]\n{std_alias}\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
}
};
let mut disabled: HashSet<u32> = HashSet::new();
let mut repairs = BTreeMap::new();
let build_target = work_directory(&work, "target")?;
let target_flags = test_build_flags(&test_packages, selection, &workspace, &options.cargo);
let build_scope = if target_flags.is_some() {
report::TestBuildScope::SelectedTargets
} else {
report::TestBuildScope::PackageWide
};
let build_note = if selection.has_target_filters() && target_flags.is_none() {
"Cargo is using a package-wide build because the selected test targets cannot be expressed exactly.\n"
} else {
""
};
if !build_note.is_empty() {
note(build_note.trim_end());
}
let can_build_only_observer = !options.doc
&& target_flags.is_none()
&& test_packages.len() == 1
&& package.targets.len() == 1
&& root_target.test
&& root_target.test_build_arg() == Some(("--lib", None));
let build_test_binaries = |observer: bool| {
let mut command = Command::new("cargo");
isolate_copy_command(&mut command, &work);
if let Some(lock) = &work_lock {
lock.retain_for(&mut command);
}
command
.args(["test", "--no-run", "--message-format=json"])
.args(test_packages.iter().flat_map(|p| ["-p", p.name.as_str()]))
.args(target_flags.as_deref().unwrap_or_default())
.args((observer && can_build_only_observer).then_some("--lib"))
.args(options.cargo.flags())
.current_dir(©)
.env("CARGO_TARGET_DIR", &build_target)
.env("CARGO_BUILD_BUILD_DIR", &build_target)
.envs(profile_env(options.opt_level));
run_cargo_with_progress(&mut command, options.progress && !observer)
};
let cargo_build = || build_test_binaries(false);
let has_probe_sites = !options.source_only && files.iter().any(|f| !f.sites.is_empty());
let repair_fingerprint = has_probe_sites.then(|| {
let test_pkg_names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
repair_cache::compute_fingerprint(
&state.root,
©,
&workspace,
&state,
&external_deps,
&package.name,
&test_pkg_names,
&options.cargo,
options.opt_level,
target_flags.as_deref(),
&error_values,
options.doc,
&files,
)
});
if let Some(fingerprint) = &repair_fingerprint {
let cached = repair_cache::load(&work, fingerprint);
if !cached.is_empty() {
for entry in cached {
if let Some(file) = files.iter().find(|f| f.display == entry.file)
&& let Some(site) = file.sites.get(entry.site_index)
&& site.start == entry.start
&& site.end == entry.end
&& site.text == entry.text
&& format!("{:?}", site.kind) == entry.kind
{
disabled.insert(site.id);
repairs.entry(site.id).or_insert(entry.reason);
}
}
if !disabled.is_empty() {
note(&format!(
"reusing {} cached repair exclusion(s)",
disabled.len()
));
}
}
}
let mut rounds = 0;
let mut newly_disabled = HashSet::new();
let build = loop {
for file in &mut files {
let suffix = if file.path == root_file {
root_suffix.as_str()
} else {
""
};
write_rendered(file, &state, suffix, &disabled, &newly_disabled)?;
}
if !files.iter().any(|f| f.path == root_file) {
state.write(&root_file, &format!("{root_source}{root_suffix}"))?;
}
if rounds == 0 {
state.settle(&workspace)?;
}
note(if rounds == 0 {
"building the instrumented crate"
} else {
"rebuilding without the sites that failed to compile"
});
let output = cargo_build()?;
let names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
let build = parse_build_output(&String::from_utf8_lossy(&output.stdout), &names);
if output.status.success() {
if let Some(fingerprint) = &repair_fingerprint {
let cached_entries: Vec<repair_cache::CachedSite> = files
.iter()
.flat_map(|file| {
file.sites
.iter()
.enumerate()
.filter(|(_, site)| disabled.contains(&site.id))
.map(|(site_index, site)| repair_cache::CachedSite {
file: file.display.clone(),
site_index,
start: site.start,
end: site.end,
text: site.text.clone(),
kind: format!("{:?}", site.kind),
reason: repairs.get(&site.id).cloned().unwrap_or_default(),
})
})
.collect();
let _ = repair_cache::save(&work, fingerprint, &cached_entries);
}
break build;
}
let diagnostics = || {
[
build.diagnostics.join("\n"),
String::from_utf8_lossy(&output.stderr).into_owned(),
]
.into_iter()
.filter(|part| !part.trim().is_empty())
.collect::<Vec<_>>()
.join("\n")
};
if build.errors.is_empty() {
bail!("the build failed:\n{build_note}{}", diagnostics());
}
if build
.errors
.iter()
.any(|error| is_non_probe_error(error, &files, ©))
{
bail!(
"the build failed with an error unrelated to instrumentation:\n{build_note}{}",
diagnostics()
);
}
rounds += 1;
let before = disabled.len();
let mut blamed_now: HashSet<u32> = HashSet::new();
for error in &build.errors {
let blamed = blame_error(error, &files, ©, &disabled);
if std::env::var_os("TMT_DEBUG").is_some() {
eprintln!(
"tmt: debug: blaming {blamed:?} for\n{}",
report::sanitize_terminal(&error.rendered)
);
}
for id in blamed {
repairs
.entry(id)
.or_insert_with(|| error.rendered.lines().next().unwrap_or("").to_string());
blamed_now.insert(id);
}
}
disabled.extend(blamed_now.iter().copied());
newly_disabled = blamed_now;
if disabled.len() == before || rounds > MAX_REPAIR_ROUNDS {
bail!(
"the crate does not build after instrumentation.\n\
{build_note}Does `cargo test --no-run` pass on the original for the same targets?\n{}",
diagnostics()
);
}
};
let built_sources = if options.rebuild || options.source_only || options.audit.is_some() {
let behind_cargo = features_from_flags(
std::env::vars_os()
.filter(|(name, _)| name.to_string_lossy().ends_with("RUSTFLAGS"))
.map(|(_, value)| Some(value)),
) || build.build_scripts.iter().any(|script| {
script["cfgs"].as_array().is_some_and(|cfgs| {
cfgs.iter()
.any(|cfg| cfg.as_str().is_some_and(|cfg| cfg.contains("feature")))
})
}) || configuration_names_a_feature(
©,
std::env::var_os("CARGO_HOME").map(PathBuf::from),
);
BuiltSources::from_artifacts(&build.artifacts, &build.features, !behind_cargo, ©)
} else {
BuiltSources::default()
};
output_fixture::stage(&workspace, &work, &build_target, &options.output_fixtures)?;
let checkpoint_path = report.analysis.checkpoint.as_deref();
let checkpoint = checkpoint_path.map(Checkpoint::open).transpose()?;
let doc_packages = test_packages
.iter()
.filter(|p| options.doc && p.targets.iter().any(|target| target.doctest));
if build.test_binaries.is_empty() && doc_packages.clone().next().is_none() {
bail!("{build_note}`{}` has no test binaries", package.name);
}
let mut session = Session {
progress: options.progress,
serial_timeout_rechecks: options.serial_timeout_rechecks,
package_dir,
binaries: vec![],
};
let wrapper = selection
.wrapper
.as_ref()
.map(|path| {
let relative = wrapper_relative(path)?;
let copied = copy.join(&relative);
if !copied.is_file() {
bail!(
"test wrapper is missing from the work copy: {}",
copied.display()
);
}
Ok(copied)
})
.transpose()?;
let mut runners: Vec<(String, Runner, PathBuf)> = vec![];
let root_test_exe = |built: &BuildOutput| {
built
.test_binaries
.iter()
.find(|(name, _, owner, kind)| {
*name == root_target.name && *owner == package.name && *kind == root_target.kind
})
.map(|(_, exe, _, _)| exe.clone())
};
let root_exe = (!witness_candidates.is_empty())
.then(|| root_test_exe(&build))
.flatten();
let mut discovered_tests: Vec<String> = vec![];
let mut empty_bin_targets: Vec<(String, String)> = vec![];
if let Some(nextest) = &options.nextest {
let mut flags: Vec<_> = test_packages
.iter()
.flat_map(|p| ["-p".to_owned(), p.name.clone()])
.collect();
flags.extend(options.cargo.flags());
runners.push((
"nextest".to_owned(),
Runner::Nextest {
copy: copy.clone(),
target_dir: build_target.clone(),
profile: nextest.profile.clone(),
opt_level: options.opt_level,
flags,
},
session.package_dir.clone(),
));
} else {
for (name, exe, owner, kind) in build.test_binaries {
if !artifact_target_selected(&name, &kind, selection) {
continue;
}
let owner_package = test_packages
.iter()
.find(|p| p.name == owner)
.expect("binaries are filtered by these packages");
let cwd = in_copy(
owner_package
.manifest_path
.parent()
.expect("manifest has a parent"),
)?;
if selection.enabled() {
let all = list_tests(&exe, &cwd, &work, false, true, work_lock.as_deref())?;
if all.is_empty() && kind.first().map(String::as_str) == Some("bin") {
empty_bin_targets.push((owner.clone(), name.clone()));
}
let ignored = list_tests(&exe, &cwd, &work, true, true, work_lock.as_deref())?;
for test in all {
let was_ignored = ignored.contains(&test);
if (!was_ignored || selection.include_ignored)
&& !selection.exclude.iter().any(|name| name == &test)
{
discovered_tests.push(test.clone());
}
if !selection.matches_test(&test, was_ignored) {
continue;
}
runners.push((
format!("{owner}::{}::{name}::{test}", kind.join("+")),
Runner::Isolated {
exe: exe.clone(),
test,
ignored: was_ignored,
wrapper: wrapper.clone(),
},
cwd.clone(),
));
}
continue;
}
let name = if owner == package.name {
name
} else {
format!("{owner}::{name}")
};
runners.push((name, Runner::Exe(exe), cwd));
}
}
if selection.enabled() && runners.is_empty() {
let hint = no_tests_matched_hint(
&test_packages,
selection,
&empty_bin_targets,
&discovered_tests,
);
bail!("{build_note}no tests matched the requested selection{hint}");
}
let selected_tests = selection.enabled().then(|| report::TestSelection {
build_scope,
wrapper: selection
.wrapper
.as_ref()
.map(|path| path.display().to_string()),
tests: runners.iter().map(|(name, _, _)| name.clone()).collect(),
});
for owner in doc_packages {
let doc = Runner::Doc {
copy: copy.clone(),
target_dir: build_target.clone(),
package: owner.name.clone(),
opt_level: options.opt_level,
flags: options.cargo.flags(),
};
let name = if owner.name == package.name {
"doc tests".to_owned()
} else {
format!("{}::doc tests", owner.name)
};
let cwd = in_copy(owner.manifest_path.parent().expect("manifest has a parent"))?;
runners.push((name, doc, cwd));
}
report.analysis.test_selection = selected_tests;
let identity = if checkpoint.is_some() {
let mut build_inputs: Vec<_> = build
.build_scripts
.iter()
.map(serde_json::Value::to_string)
.collect();
build_inputs.sort();
let settings = serde_json::json!({
"build_scripts": build_inputs,
"analysis": &report.analysis, "package": &package.name, "jobs": effective_jobs,
"verify": options.verify, "audit": options.audit, "effects": options.effects,
"all_files": options.all_files, "build_scope": build_scope,
"runners": runners.iter().map(|(name, runner, cwd)| (name, runner.executable(), cwd)).collect::<Vec<_>>()
});
let mut inputs = BTreeSet::new();
for (root, artifacts) in &build.artifacts {
inputs.insert(root.clone());
if let Some(dependencies) = artifacts
.iter()
.map(|artifact| artifact_inputs(artifact, root, ©))
.find(|deps| !deps.is_empty())
{
inputs.extend(dependencies);
} else {
inputs.extend(artifacts.iter().cloned());
}
}
inputs.extend(
build
.build_scripts
.iter()
.filter_map(|script| script.get("out_dir")?.as_str().map(PathBuf::from)),
);
inputs.retain(|path| !path.starts_with(©));
inputs.extend(
options
.output_fixtures
.iter()
.map(|fixture| build_target.join(&fixture.to)),
);
inputs.extend(
options
.stage_external
.iter()
.map(|entry| normalize(©.join(&entry.rel))),
);
Some(crate::campaign_identity::compute(
©,
&settings,
inputs,
options.nextest.is_some(),
)?)
} else {
None
};
let marks = marks_dir(&work)?;
let baseline_jobs = if selection.enabled() {
options.baseline_jobs
} else {
1
};
if options.progress {
eprintln!(
"tmt: baselines: 0/{} completed ({} workers)",
runners.len(),
baseline_jobs
);
}
let baseline_budget = options
.baseline_timeout_seconds
.map(Duration::from_secs)
.unwrap_or(DEFAULT_BASELINE_TIMEOUT);
let baseline_stage = if options.source_only {
"baseline_untraced"
} else {
"baseline_trace"
};
let diagnostic_path = work.join("baseline-timeout.json");
let _ = fs::remove_file(&diagnostic_path);
let completed_baselines = std::sync::atomic::AtomicUsize::new(0);
let completed_timings = std::sync::Mutex::new(Vec::<report::BaselineTimingEntry>::new());
let total_baselines = runners.len();
let wrapper_grace_counter = selection
.wrapper
.as_ref()
.map(|_| Arc::new(runner::WrapperGraceCounter::default()));
#[derive(Debug)]
enum BaselinePoolError {
Timeout(Box<report::BaselineTimeoutDiagnostic>),
Failed(Box<report::BaselineFailureDiagnostic>),
}
impl std::fmt::Display for BaselinePoolError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Timeout(diag) => write!(
f,
"baseline timeout in stage `{}` for `{}`",
diag.stage, diag.runner
),
Self::Failed(diag) => write!(f, "the tests in `{}` {}", diag.runner, diag.reason),
}
}
}
impl std::error::Error for BaselinePoolError {}
let disable_proptest_persistence = should_disable_proptest_persistence(
copy_has_proptest_regressions(©),
std::env::var_os(PROPTEST_DISABLE_ENV).is_some(),
keep_proptest_persistence_requested(std::env::var_os(TMT_KEEP_PROPTEST_PERSISTENCE_ENV)),
);
let baseline_result = progress::track_baselines(options.progress, runners.len(), |progress| {
run_pool(runners.len(), baseline_jobs, |slot| {
let index = slot;
let (name, runner, cwd) = runners[index].clone();
let result = (|| {
let trace_path = work.join(format!("trace-{index}.tsv"));
let _ = fs::remove_file(&trace_path);
let mut bin = TestBinary {
name,
cwd,
marks: marks.clone(),
git_ceiling: work.clone(),
work_lock: work_lock.clone(),
tests: BTreeSet::new(),
runner,
baseline: Duration::ZERO,
untraced_baseline: None,
timeout_diagnostic: std::sync::Once::new(),
traced: Duration::ZERO,
timeout: options.timeout_seconds.map(Duration::from_secs),
wrapper_grace: options.wrapper_grace,
wrapper_grace_counter: wrapper_grace_counter.clone(),
report_slow: options.progress,
disable_proptest_persistence,
filtered_timings: Default::default(),
trace: Trace::default(),
effects_baseline: std::sync::OnceLock::new(),
};
session.note(&format!("tracing `{}`", bin.name));
let started = Instant::now();
let trace_env = trace_path.to_string_lossy().into_owned();
let trace = [("TMT_TRACE", trace_env.as_str())];
let isolated_test = match &bin.runner {
Runner::Isolated { test, .. } => Some(test.clone()),
_ => None,
};
match run_baseline(
&bin,
if options.source_only { &[] } else { &trace },
baseline_budget,
&work.join(format!("baseline-{index}.log")),
false,
)? {
BaselineRun::Passed => {}
BaselineRun::TimedOut {
elapsed,
log,
log_summary,
} => {
let log_path =
log.unwrap_or_else(|| work.join(format!("baseline-{index}.log")));
let (rerun_args, exclude_args) = match &bin.runner {
Runner::Isolated { test, .. } => (
vec!["--include-test".to_string(), test.clone()],
vec!["--exclude-test".to_string(), test.clone()],
),
Runner::Exe(_) => {
let target = bin
.name
.rsplit_once("::")
.map_or(bin.name.as_str(), |(_, t)| t)
.to_string();
(vec!["--test-target".to_string(), target], vec![])
}
Runner::Nextest { .. } | Runner::Doc { .. } => (vec![], vec![]),
};
let completed =
completed_baselines.load(std::sync::atomic::Ordering::Acquire);
let diagnostic = report::BaselineTimeoutDiagnostic {
schema_version: report::SCHEMA_VERSION,
package: package.name.clone(),
stage: baseline_stage,
runner: bin.name.clone(),
test: isolated_test,
elapsed_seconds: round_millis(elapsed),
budget_seconds: baseline_budget.as_secs(),
completed_baselines: completed,
total_baselines,
partial_baseline: true,
log: log_path,
lines: options.lines.clone(),
rerun_args,
exclude_args,
completed_timings: Vec::new(),
log_summary,
};
return Err(BaselinePoolError::Timeout(Box::new(diagnostic)).into());
}
BaselineRun::Failed {
reason,
elapsed,
log,
log_summary,
} => {
let completed =
completed_baselines.load(std::sync::atomic::Ordering::Acquire);
let diagnostic = report::BaselineFailureDiagnostic {
schema_version: report::SCHEMA_VERSION,
package: package.name.clone(),
stage: baseline_stage,
runner: bin.name.clone(),
test: isolated_test,
reason,
elapsed_seconds: round_millis(elapsed),
completed_baselines: completed,
total_baselines,
log,
completed_timings: Vec::new(),
log_summary,
};
return Err(BaselinePoolError::Failed(Box::new(diagnostic)).into());
}
}
bin.traced = started.elapsed();
bin.baseline = bin.traced;
if options.source_only {
bin.untraced_baseline = Some(BaselineTiming::Completed(bin.baseline));
}
if !options.source_only && bin.traced > SLOW_TRACE {
let started = Instant::now();
match run_baseline(
&bin,
&[],
bin.traced,
&work.join(format!("baseline-{index}-untraced.log")),
true,
)? {
BaselineRun::Passed => {
let elapsed = started.elapsed();
bin.untraced_baseline = Some(BaselineTiming::Completed(elapsed));
bin.baseline = elapsed;
}
BaselineRun::TimedOut { .. } => {
bin.untraced_baseline = Some(BaselineTiming::StillRunning(bin.traced));
}
BaselineRun::Failed {
reason,
elapsed,
log,
log_summary,
} => {
let completed =
completed_baselines.load(std::sync::atomic::Ordering::Acquire);
let diagnostic = report::BaselineFailureDiagnostic {
schema_version: report::SCHEMA_VERSION,
package: package.name.clone(),
stage: "baseline_untraced",
runner: bin.name.clone(),
test: isolated_test,
reason,
elapsed_seconds: round_millis(elapsed),
completed_baselines: completed,
total_baselines,
log,
completed_timings: Vec::new(),
log_summary,
};
return Err(BaselinePoolError::Failed(Box::new(diagnostic)).into());
}
}
}
let make_baseline_failure =
|stage: &'static str, reason: &'static str, log: PathBuf, detail: String| {
let completed =
completed_baselines.load(std::sync::atomic::Ordering::Acquire);
BaselinePoolError::Failed(Box::new(report::BaselineFailureDiagnostic {
schema_version: report::SCHEMA_VERSION,
package: package.name.clone(),
stage,
runner: bin.name.clone(),
test: isolated_test.clone(),
reason,
elapsed_seconds: round_millis(bin.baseline),
completed_baselines: completed,
total_baselines,
log,
completed_timings: Vec::new(),
log_summary: vec![detail],
}))
};
let text = match fs::read_to_string(&trace_path) {
Ok(text) => text,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(err) => {
return Err(make_baseline_failure(
baseline_stage,
"failed to read baseline trace",
trace_path.clone(),
format!("cannot read the trace of `{}`: {err}", bin.name),
)
.into());
}
};
bin.trace = Trace::parse(&text);
if bin.trace.malformed_lines > 0 {
return Err(make_baseline_failure(
baseline_stage,
"produced a malformed baseline trace",
trace_path.clone(),
format!(
"the trace of `{}` has {} malformed lines; not drawing conclusions from it",
bin.name, bin.trace.malformed_lines
),
)
.into());
}
if let Runner::Exe(exe) = &bin.runner {
bin.tests = match list_tests(
exe,
&bin.cwd,
&work,
false,
false,
work_lock.as_deref(),
) {
Ok(tests) => tests,
Err(err)
if crate::interrupt::is_interrupted()
|| crate::interrupt::is_interrupted_err(&err) =>
{
return Err(err);
}
Err(err) => {
return Err(make_baseline_failure(
baseline_stage,
"failed to list baseline tests",
exe.clone(),
format!("{err:#}"),
)
.into());
}
};
}
if let Ok(mut timings) = completed_timings.lock() {
timings.push(report::BaselineTimingEntry {
runner: bin.name.clone(),
test: isolated_test,
elapsed_seconds: round_millis(bin.baseline),
});
}
completed_baselines.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
Ok(bin)
})();
progress.complete(if result.is_ok() {
progress::Outcome::Survived
} else {
progress::Outcome::Failed
});
result
})
});
let collect_completed_timings = || -> Vec<report::BaselineTimingEntry> {
let mut timings = completed_timings
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
timings.sort_by(|a, b| {
b.elapsed_seconds
.total_cmp(&a.elapsed_seconds)
.then_with(|| a.runner.cmp(&b.runner))
});
timings
};
session.binaries = match baseline_result {
Ok(binaries) => binaries,
Err(err) => match err.downcast::<BaselinePoolError>() {
Ok(BaselinePoolError::Timeout(mut diagnostic)) => {
diagnostic.completed_baselines =
completed_baselines.load(std::sync::atomic::Ordering::Acquire);
diagnostic.completed_timings = collect_completed_timings();
let write_status = serde_json::to_string_pretty(&diagnostic)
.map_err(anyhow::Error::from)
.and_then(|json| {
use std::io::Write as _;
static NEXT_DIAG_TMP: std::sync::atomic::AtomicUsize =
std::sync::atomic::AtomicUsize::new(0);
let seq = NEXT_DIAG_TMP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let tmp = work.join(format!(
".baseline-timeout.{}.{seq}.tmp",
std::process::id()
));
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp)?;
if let Err(err) = file
.write_all(format!("{json}\n").as_bytes())
.and_then(|()| file.flush())
{
drop(file);
let _ = fs::remove_file(&tmp);
return Err(err.into());
}
drop(file);
if let Err(rename_err) = fs::rename(&tmp, &diagnostic_path) {
let _ = fs::remove_file(&tmp);
return Err(rename_err.into());
}
Ok(())
});
let diag_note = match write_status {
Ok(()) => format!("diagnostic: {}", diagnostic_path.display()),
Err(write_err) => format!(
"failed to write diagnostic {}: {write_err}",
diagnostic_path.display()
),
};
let subject = match &diagnostic.test {
Some(test) => format!("`{}` (test `{test}`)", diagnostic.runner),
None => format!("`{}`", diagnostic.runner),
};
let hint =
if !diagnostic.rerun_args.is_empty() && !diagnostic.exclude_args.is_empty() {
format!(
"; rerun separately with `{}` or exclude with `{}`",
diagnostic.rerun_args.join(" "),
diagnostic.exclude_args.join(" ")
)
} else if !diagnostic.rerun_args.is_empty() {
format!(
"; rerun separately with `{}`",
diagnostic.rerun_args.join(" ")
)
} else {
String::new()
};
let timings_section = format_baseline_timings_section(
&diagnostic.completed_timings,
&diagnostic.runner,
diagnostic.elapsed_seconds,
"timed out",
diagnostic.total_baselines,
);
let summary_section = format_log_summary_section(&diagnostic.log_summary);
let message = format!(
"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}",
diagnostic.stage,
diagnostic.elapsed_seconds,
diagnostic.budget_seconds,
diagnostic.completed_baselines,
diagnostic.total_baselines,
diagnostic.log.display()
);
return Err(BaselineError::Timeout {
diagnostic,
wrapper_grace_outcomes: wrapper_grace_counter.as_ref().map(|c| c.snapshot()),
message,
}
.into());
}
Ok(BaselinePoolError::Failed(mut diagnostic)) => {
diagnostic.completed_baselines =
completed_baselines.load(std::sync::atomic::Ordering::Acquire);
diagnostic.completed_timings = collect_completed_timings();
let timings_section = format_baseline_timings_section(
&diagnostic.completed_timings,
&diagnostic.runner,
diagnostic.elapsed_seconds,
"failed",
diagnostic.total_baselines,
);
let summary_section = format_log_summary_section(&diagnostic.log_summary);
let message = format!(
"the tests in `{}` {}; full output: {}{timings_section}{summary_section}",
diagnostic.runner,
diagnostic.reason,
diagnostic.log.display()
);
return Err(BaselineError::Failed {
diagnostic,
wrapper_grace_outcomes: wrapper_grace_counter.as_ref().map(|c| c.snapshot()),
message,
}
.into());
}
Err(other) => return Err(other),
},
};
for file in &files {
for site in &file.sites {
if disabled.contains(&site.id) {
let fallback = options.rebuild
&& !matches!(site.kind, SiteKind::Body { .. })
&& !instrument::source_mutants(site).is_empty();
match site.kind {
SiteKind::Body { .. } => report.unviable_mutants += 1,
_ if fallback => {}
_ => report.skipped_sites += 1,
}
report.skipped.push(report::SkippedSite::new(
report::location(&file.display, site),
file.lines.position(&file.original, site.end),
if fallback {
report::SkipReason::ProbeReplacedBySourceRebuild
} else {
report::SkipReason::ProbeCompileError
},
repairs.get(&site.id).cloned(),
));
}
}
if !options.rebuild && !options.source_only {
report.skipped.extend(file.rebuild_sites.iter().map(|site| {
report::SkippedSite::new(
report::location(&file.display, site),
file.lines.position(&file.original, site.end),
report::SkipReason::RequiresSourceRebuild,
None,
)
}));
}
}
if let (Some(checkpoint), Some(identity)) = (&checkpoint, &identity) {
checkpoint.start(
identity,
serde_json::json!({
"package": &package.name, "analysis": &report.analysis,
"runners": session.binaries.iter().map(|bin| &bin.name).collect::<Vec<_>>(),
"jobs": effective_jobs, "tool_version": env!("CARGO_PKG_VERSION")
}),
)?;
}
let phase = |name: &str, keys: Vec<String>| -> Result<Option<Phase<'_>>> {
let total = keys.len();
let started = checkpoint
.as_ref()
.zip(identity.as_deref())
.map(|(checkpoint, identity)| checkpoint.begin(name, identity, keys))
.transpose()?;
if let Some(phase) = &started
&& phase.reused() > 0
&& options.progress
{
eprintln!(
"tmt: checkpoint: reused {}/{total} cached results for {name} ({} remaining)",
phase.reused(),
phase.pending()
);
}
Ok(started)
};
let probe_phase = |name: &str, jobs: &[Job]| -> Result<Option<Phase<'_>>> {
if checkpoint.is_none() {
return Ok(None);
}
let locations: BTreeMap<_, _> = files
.iter()
.flat_map(|file| {
file.sites
.iter()
.map(|site| (site.id, (&file.display, site.line, site.column, &site.text)))
})
.collect();
let keys = jobs
.iter()
.map(|job| {
let tests = job
.tests
.iter()
.map(|(bin, selected)| (&session.binaries[*bin].name, selected))
.collect::<Vec<_>>();
serde_json::to_string(&(locations.get(&job.site), job.mutation.encode(), tests))
})
.collect::<std::result::Result<Vec<_>, _>>()?;
phase(name, keys)
};
let scratch = work.clone();
let mut jobs: Vec<Job> = vec![];
let mut not_evaluated: HashSet<u32> = HashSet::new();
let mut site_work: Vec<SiteWork> = vec![];
let mut effect_jobs: Vec<(usize, usize)> = vec![];
for file in &files {
let mut primitive_arith_spans: HashSet<(usize, usize)> = HashSet::new();
let mut primitive_cmp_spans: HashSet<(usize, usize)> = HashSet::new();
let mut cast_probe_spans: std::collections::HashMap<(usize, usize), (u32, u32)> =
std::collections::HashMap::new();
for other in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
if matches!(other.kind, SiteKind::Cmp { .. })
&& session
.binaries
.iter()
.any(|b| b.trace.bounds.contains_key(&other.id))
{
primitive_cmp_spans.insert((other.start, other.end));
}
if let SiteKind::Arith { cast_probes, .. } = &other.kind {
let seen = session.merged(|t| t.arith.get(&other.id), plan::ArithObs::merge);
if !seen.opaque && (seen.same || seen.differs || seen.same2 || seen.differs2) {
primitive_arith_spans.insert((other.start, other.end));
}
for &(slot, start, end) in cast_probes {
cast_probe_spans
.entry((start, end))
.or_insert((other.id, slot));
}
}
}
let primitive = |from: usize, to: usize| {
let Some(mut text) = file.original.get(from..to) else {
return false;
};
let mut start = from;
loop {
let trimmed = text.trim_start();
start += text.len() - trimmed.len();
text = trimmed.trim_end();
if text.starts_with('(')
&& text.ends_with(')')
&& matches!(syn::parse_str::<syn::Expr>(text), Ok(syn::Expr::Paren(_)))
&& let Some(inner) = text
.strip_prefix('(')
.and_then(|inner| inner.strip_suffix(')'))
{
start += 1;
text = inner;
} else {
break;
}
}
primitive_arith_spans.contains(&(start, start + text.len()))
};
let cast_bounds = |from: usize, to: usize| -> Option<(i128, i128)> {
let &(owner_id, slot) = cast_probe_spans.get(&(from, to))?;
let mut recorded = session
.binaries
.iter()
.filter_map(|b| b.trace.cast_bounds.get(&(owner_id, slot)));
let first = recorded.next()?;
if recorded.all(|other| other == first) {
*first
} else {
None
}
};
let primitive_cmp = |from: usize, to: usize| primitive_cmp_spans.contains(&(from, to));
for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
let plan = match session.plan(
&file.display,
site,
options.verify,
&primitive,
&primitive_cmp,
&cast_bounds,
) {
Planned::Unreached if beyond.contains(&site.id) => continue,
Planned::Unreached => {
let at = report::location(&file.display, site);
if report.unreached.last() != Some(&at) {
report.unreached.push(at);
}
continue;
}
Planned::Nothing => continue,
Planned::NotEvaluated => {
not_evaluated.insert(site.id);
continue;
}
Planned::Plan(plan) => plan,
};
let mut add =
|mutation: Mutation, tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>| {
jobs.push(session.job(site.id, mutation, tests_of));
jobs.len() - 1
};
let gaps = plan
.gaps
.into_iter()
.map(
|PlannedGap {
finding,
survivors,
constant_expr,
}| {
let confirm = if options.verify {
survivors
.into_iter()
.map(|m| add(m, &*plan.reaching))
.collect()
} else {
vec![]
};
(finding, confirm, constant_expr)
},
)
.collect();
let infected = &plan.infected;
let runs = plan
.run
.iter()
.map(|m| (*m, add(*m, &|bin| infected(bin, *m))))
.collect();
site_work.push(SiteWork {
file: &file.display,
site,
gaps,
constant: plan.constant,
cannot_differ: plan.cannot_differ,
redundant_logic_swap: plan.redundant_logic_swap,
runs,
});
}
}
session.note(&format!(
"running {} mutants on {} thread(s)",
jobs.len(),
options.jobs.max(1)
));
let probe_checkpoint = probe_phase("probe", &jobs)?;
let mut results =
session.run_jobs(&jobs, options.jobs, "mutants", probe_checkpoint.as_ref())?;
if crate::interrupt::is_interrupted() {
report.interrupted = true;
}
for result in &results {
report.timeout_rechecks.include(result);
}
if !report.interrupted
&& let Some(wanted) = options.audit
{
match run_audit_phase(
&session,
&files,
&jobs,
&mut results,
&mut report.timeout_rechecks,
&scratch,
wanted,
options.jobs,
&probe_phase,
) {
Ok(audit) => report.audit = Some(audit),
Err(err)
if crate::interrupt::is_interrupted()
|| crate::interrupt::is_interrupted_err(&err) =>
{
report.interrupted = true;
}
Err(err) => return Err(err),
}
if crate::interrupt::is_interrupted() {
report.interrupted = true;
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum EarlierVerdict {
Killed,
Survived,
Unknown,
}
let mut earlier_verdict: BTreeMap<usize, EarlierVerdict> = BTreeMap::new();
let asked: Vec<usize> = site_work
.iter()
.filter(|item| beyond.contains(&item.site.id))
.flat_map(|item| {
item.gaps
.iter()
.flat_map(|(_, confirm, _)| confirm.iter().copied())
.chain(
item.runs
.iter()
.filter(|(m, _)| !(*m == Mutation::LogicSwap && item.redundant_logic_swap))
.map(|(_, job)| *job),
)
})
.filter(|job| results[*job].survived.is_some())
.collect();
if !report.interrupted && !asked.is_empty() {
let revision = report::short_revision(options.since.as_deref().unwrap_or_default());
session.note(&format!(
"running {} surviving mutants against the tests as they were at {revision}",
asked.len()
));
let suffix = |file: &SourceFile| {
if file.path == root_file {
root_suffix.as_str()
} else {
""
}
};
let earlier: Option<Vec<(&SourceFile, String)>> = tests_changed
.iter()
.map(|(path, hunks)| {
let file = files.iter().find(|file| file.path == *path)?;
let rendered = file.rendered.as_ref()?;
let mut places = hunks
.iter()
.map(|hunk| {
let (from, to) = scope::range_of(&file.original, hunk);
Some((rendered.copied(from, to)?, hunk.old.as_str()))
})
.collect::<Option<Vec<_>>>()?;
places.sort_by_key(|((from, _), _)| std::cmp::Reverse(*from));
let mut text = rendered.text.clone();
for ((from, to), old) in places {
text.replace_range(from..to, old);
}
Some((file, text))
})
.collect();
let attempted = if let Some(earlier) = earlier {
let attempted = (|| -> Result<Option<Vec<JobResult>>> {
for (file, text) in &earlier {
state.write(&file.path, &format!("{text}{}", suffix(file)))?;
}
if !cargo_build()?.status.success() {
session.note(
"the tests as they were do not build with the code as it is: what they found out is not known",
);
return Ok(None);
}
let all: Vec<&TestBinary> = session.binaries.iter().collect();
if run_source_tests(&all)? != Outcome::Pass {
session.note(
"the tests as they were fail on the code as it is: what they found out is not known",
);
return Ok(None);
}
let against_all: Vec<Job> = asked
.iter()
.map(|job| Job {
site: jobs[*job].site,
mutation: jobs[*job].mutation,
tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
})
.collect();
session
.run_jobs(&against_all, options.jobs, "mutants, earlier tests", None)
.map(Some)
})();
for (file, _) in &earlier {
let rendered = file.rendered.as_ref().expect("rendered before building");
state.write(&file.path, &format!("{}{}", rendered.text, suffix(file)))?;
}
if !crate::interrupt::is_interrupted() {
match cargo_build() {
Ok(output) if output.status.success() => {}
Ok(_) => {
bail!("the crate does not build once its tests are put back as they are");
}
Err(err)
if crate::interrupt::is_interrupted()
|| crate::interrupt::is_interrupted_err(&err) =>
{
report.interrupted = true;
}
Err(err) => return Err(err),
}
} else {
report.interrupted = true;
}
attempted
} else {
session.note(
"not all changed test files could be restored as they were: what they found out is not known",
);
Ok(None)
};
match attempted {
Ok(Some(again)) => {
for (job, result) in asked.iter().zip(again) {
let verdict = if result.unable || result.unconfirmed_timeout {
EarlierVerdict::Unknown
} else if result.survived.is_none() {
EarlierVerdict::Killed
} else {
EarlierVerdict::Survived
};
earlier_verdict.insert(*job, verdict);
}
}
Ok(None) => {
for job in &asked {
earlier_verdict.insert(*job, EarlierVerdict::Unknown);
}
}
Err(err)
if crate::interrupt::is_interrupted()
|| crate::interrupt::is_interrupted_err(&err) =>
{
report.interrupted = true;
for job in &asked {
earlier_verdict.insert(*job, EarlierVerdict::Unknown);
}
}
Err(err) => return Err(err),
}
if crate::interrupt::is_interrupted() {
report.interrupted = true;
}
}
let pre_job_not_evaluated = not_evaluated.len();
let unable = results
.iter()
.filter(|r| r.unable || r.unconfirmed_timeout)
.count();
not_evaluated.extend(
jobs.iter()
.zip(&results)
.filter(|(_, result)| result.unable || result.unconfirmed_timeout)
.map(|(job, _)| job.site),
);
if !options.rebuild || report.interrupted {
report.mutants_not_evaluated = pre_job_not_evaluated + unable;
}
report.mutants_run = results.len() - unable;
report.mutants_killed = results.iter().filter(|r| r.survived.is_none()).count() - unable;
report.mutants_survived = report.mutants_run - report.mutants_killed;
report.mutants_timed_out = results
.iter()
.filter(|r| r.timed_out && !r.unconfirmed_timeout)
.count();
let mut finding_run_survivors: Vec<usize> = vec![];
let mut killed_by_loc: BTreeMap<(String, usize, usize, &'static str), usize> = BTreeMap::new();
let confirmed = |w: &SiteWork| {
w.gaps
.iter()
.all(|(_, confirm, _)| confirm.iter().all(|j| results[*j].survived.is_some()))
};
let constants: BTreeSet<(&str, usize, usize)> = site_work
.iter()
.filter(|w| w.cannot_differ || (w.constant && confirmed(w)))
.map(|w| (w.file, w.site.start, w.site.end))
.collect();
for item in &site_work {
let at = report::location(item.file, item.site);
for (finding, confirm, constant_expr) in &item.gaps {
let repeats = constant_expr
.is_some_and(|(start, end)| constants.contains(&(item.file, start, end)));
let survived_count = confirm
.iter()
.filter(|j| results[**j].survived.is_some())
.count();
if beyond.contains(&item.site.id) {
let confirmed = confirm.iter().all(|j| results[*j].survived.is_some());
let killed_before = confirm
.iter()
.any(|j| earlier_verdict.get(j) == Some(&EarlierVerdict::Killed));
if confirmed && !repeats && killed_before {
report.weakened.push(finding.at().clone());
report.findings.push(finding.clone());
finding_run_survivors.push(survived_count);
} else if !confirmed {
report.survivor_breakdown.unconfirmed_gap += survived_count;
} else if repeats {
report.survivor_breakdown.redundant_constant += survived_count;
} else {
for job in confirm {
if results[*job].survived.is_some() {
if earlier_verdict.get(job) == Some(&EarlierVerdict::Survived) {
report.survivor_breakdown.preexisting_unchanged += 1;
} else {
report.survivor_breakdown.unchanged_not_compared += 1;
}
}
}
}
continue;
}
match Prediction::of(confirm.iter().map(|j| &results[*j])) {
Prediction::Refuted => {
report.unstable.push(at.clone());
report.survivor_breakdown.unconfirmed_gap += survived_count;
}
Prediction::Confirmed if !repeats => {
report.findings.push(finding.clone());
finding_run_survivors.push(survived_count);
}
Prediction::Confirmed => {
report.survivor_breakdown.redundant_constant += survived_count;
}
Prediction::Unknown => {
report.survivor_breakdown.unconfirmed_gap += survived_count;
}
}
}
if let SiteKind::Body {
sole_expr: Some((start, end)),
..
} = item.site.kind
&& constants.contains(&(item.file, start, end))
{
report.survivor_breakdown.redundant_constant += item
.runs
.iter()
.filter(|(_, job)| results[*job].survived.is_some())
.count();
continue;
}
let mut survivors = vec![];
let mut passing_tests = BTreeSet::new();
for (mutation, job) in &item.runs {
let res = &results[*job];
if !res.unable && !res.unconfirmed_timeout && res.survived.is_none() {
*killed_by_loc
.entry((
item.file.to_string(),
item.site.line,
item.site.column,
"assertion_gap",
))
.or_insert(0) += 1;
}
if let Some(tests) = &res.survived {
if *mutation == Mutation::LogicSwap && item.redundant_logic_swap {
report.survivor_breakdown.redundant_constant += 1;
continue;
}
if beyond.contains(&item.site.id) {
match earlier_verdict.get(job) {
Some(EarlierVerdict::Killed) => {}
Some(EarlierVerdict::Survived) => {
report.survivor_breakdown.preexisting_unchanged += 1;
continue;
}
Some(EarlierVerdict::Unknown) | None => {
report.survivor_breakdown.unchanged_not_compared += 1;
continue;
}
}
}
survivors.push(report::describe(item.site, *mutation));
passing_tests.extend(tests.iter().cloned());
}
}
if !survivors.is_empty() {
let first = item.runs.iter().find(|(mutation, job)| {
!(*mutation == Mutation::LogicSwap && item.redundant_logic_swap)
&& results[*job].survived.is_some()
&& (!beyond.contains(&item.site.id)
|| earlier_verdict.get(job) == Some(&EarlierVerdict::Killed))
});
if beyond.contains(&item.site.id) {
report.weakened.push(at.clone());
}
effect_jobs.push((report.findings.len(), first.expect("a survivor").1));
finding_run_survivors.push(survivors.len());
report.findings.push(Finding::AssertionGap {
at,
survivors,
tests: passing_tests.into_iter().collect(),
effects: vec![],
effects_of: None,
witness: None,
likely_equivalent: None,
});
}
}
if !report.interrupted && options.effects && !effect_jobs.is_empty() {
match run_effects_phase(
&session,
&files,
&jobs,
&effect_jobs,
&scratch,
options.jobs,
&mut report.findings,
) {
Ok(()) => {}
Err(err)
if crate::interrupt::is_interrupted()
|| crate::interrupt::is_interrupted_err(&err) =>
{
report.interrupted = true;
}
Err(err) => return Err(err),
}
if crate::interrupt::is_interrupted() {
report.interrupted = true;
}
}
let mut built: Vec<(&SourceFile, &Site, instrument::SourceMutant, Option<usize>)> = vec![];
let build_regular_mutants = options.rebuild || options.source_only;
let mut index = 0;
for file in &files {
let retried = file.sites.iter().filter(|site| {
(disabled.contains(&site.id) && !matches!(site.kind, SiteKind::Body { .. }))
|| not_evaluated.contains(&site.id)
});
for site in file.rebuild_sites.iter().chain(retried) {
let mutants = source_mutants(file, site, true);
if build_regular_mutants {
built.extend(mutants.into_iter().filter_map(|mutant| {
let selected = in_shard(index);
index += 1;
selected.then_some((file, site, mutant, None))
}));
} else {
report.mutants_not_built += mutants.len();
}
}
}
if !build_regular_mutants {
report.mutants_not_built += not_built_witnesses;
}
if !report.interrupted
&& let (Some(wanted), Some(audit)) = (options.audit, report.audit.as_mut())
{
let mut twins = vec![];
for file in &files {
for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
let integers = session.binaries.iter().all(|bin| {
let seen = bin.trace.merged(site.id);
!seen.reached() || seen.valued()
});
let candidates = jobs_for_site(&jobs, site.id);
let job_of = |mutation: Mutation| {
candidates
.clone()
.find(|&index| jobs[index].mutation == mutation)
};
let mut compared = vec![];
let mut mutants = instrument::source_mutants(site);
instrument::keep_line_ends(&file.original, &mut mutants);
for mutant in mutants {
let job = mutations_like(site, &mutant, integers)
.into_iter()
.find_map(job_of);
if let Some(job) = job {
compared.push(job);
twins.push((file, site, mutant, Some(job)));
}
}
if let (SiteKind::Cmp { op, .. }, Some(job)) =
(&site.kind, job_of(Mutation::Negate))
&& !compared.contains(&job)
{
let negated = instrument::SourceMutant {
start: site.start,
end: site.end,
replacement: format!("!({})", site.text),
what: op.symbol().to_string(),
into: "!".to_string(),
};
twins.push((file, site, negated, Some(job)));
}
}
}
let chosen = spread(twins.len(), wanted);
audit.rebuilt = chosen.len();
let mut twins: Vec<Option<_>> = twins.into_iter().map(Some).collect();
built.extend(chosen.into_iter().filter_map(|nth| twins[nth].take()));
}
let mut by_speed: Vec<&TestBinary> = session.binaries.iter().collect();
by_speed.sort_by_key(|bin| bin.baseline);
let root_mutant_suffix = if files.iter().any(|file| {
file.path != root_file
&& file
.rendered
.as_ref()
.is_some_and(|rendered| rendered.text != file.original)
}) {
root_suffix.as_str()
} else {
""
};
if !built.is_empty() && report.interrupted {
report.mutants_not_evaluated += built
.iter()
.filter(|(_, _, _, twin)| twin.is_none())
.count();
if let Some(audit) = report.audit.as_mut() {
audit.not_compared += built
.iter()
.filter(|(_, _, _, twin)| twin.is_some())
.count();
}
} else if !built.is_empty() {
if options.timeout_seconds.is_some()
&& built
.iter()
.any(|(file, _, _, _)| built_sources.contains(file))
{
for bin in &by_speed {
bin.warn_timeout_conflict(None);
}
}
let source_checkpoint = if checkpoint.is_some() {
let keys = built
.iter()
.map(|(file, _, mutation, twin)| {
serde_json::to_string(&(
&file.display,
mutation.start,
mutation.end,
&mutation.replacement,
twin,
))
})
.collect::<std::result::Result<Vec<_>, _>>()?;
phase("source", keys)?
} else {
None
};
session.note(&format!(
"building {} mutants one by one (code a probe cannot be put in, or to compare with the probe)",
built.len()
));
let instrumented = |file: &SourceFile, text: &str, suffix: &str| {
if file.path == root_file {
format!("{text}{suffix}")
} else {
text.to_string()
}
};
let mut skipped_targets = BTreeSet::new();
let mut left_out: BTreeMap<&PathBuf, Vec<(usize, usize)>> = BTreeMap::new();
let mut survivors: Vec<(report::Location, Vec<String>)> = vec![];
progress::track(
options.progress,
"source mutants",
built.len(),
|progress| -> Result<()> {
for (index, (file, site, mutant, twin)) in built.iter().enumerate() {
if crate::interrupt::is_interrupted() {
report.mutants_not_evaluated += built[index..]
.iter()
.filter(|(_, _, _, t)| t.is_none())
.count();
if let Some(audit) = report.audit.as_mut() {
audit.not_compared += built[index..]
.iter()
.filter(|(_, _, _, t)| t.is_some())
.count();
}
report.interrupted = true;
break;
}
let cached = source_checkpoint
.as_ref()
.map(|phase| phase.get::<Option<Outcome>>(index))
.transpose()?
.flatten();
let was_cached = cached.is_some();
if was_cached && let Some(phase) = source_checkpoint.as_ref() {
phase.mark_reused();
}
let left_out = left_out
.entry(&file.path)
.or_insert_with(|| built_sources.left_out(file))
.iter()
.any(|(from, to)| *from <= site.start && site.end <= *to);
if left_out || !built_sources.contains(file) {
if let Some(phase) = source_checkpoint.as_ref().filter(|_| cached.is_none())
{
phase.record(index, &Some(Outcome::Unable))?;
}
if twin.is_none() {
report.mutants_not_evaluated += 1;
report.mutants_not_compiled += 1;
if skipped_targets.insert((&file.path, site.start, site.end)) {
report.skipped.push(report::SkippedSite::new(
report::location(&file.display, site),
file.lines.position(&file.original, site.end),
report::SkipReason::SourceNotBuilt,
left_out.then(|| {
"under a `cfg` that the features of this build turn off"
.to_string()
}),
));
}
} else if let Some(audit) = report.audit.as_mut() {
audit.not_compared += 1;
}
if was_cached {
progress.complete_cached(progress::Outcome::Unable);
} else {
progress.complete(progress::Outcome::Unable);
}
continue;
}
let outcome = if let Some(cached) = cached {
cached
} else {
let mutated = format!(
"{}{}{}",
&file.original[..mutant.start],
mutant.replacement,
&file.original[mutant.end..]
);
let attempt = || -> Result<Option<Outcome>> {
state.write(
&file.path,
&instrumented(file, &mutated, root_mutant_suffix),
)?;
match source_build(&cargo_build()?) {
SourceBuild::Built => run_source_tests(&by_speed).map(Some),
SourceBuild::Refused => Ok(None),
SourceBuild::Failed(why) => {
session.note(&format!(
"a build failed without the compiler refusing the code; its mutant is not evaluated: {why}"
));
Ok(Some(Outcome::Unable))
}
}
};
let attempted = attempt();
let rendered = file.rendered.as_ref().expect("rendered before building");
state.write(
&file.path,
&instrumented(file, &rendered.text, &root_suffix),
)?;
let outcome = match attempted {
Ok(outcome) => outcome,
Err(err)
if crate::interrupt::is_interrupted()
|| crate::interrupt::is_interrupted_err(&err) =>
{
report.mutants_not_evaluated += built[index..]
.iter()
.filter(|(_, _, _, t)| t.is_none())
.count();
if let Some(audit) = report.audit.as_mut() {
audit.not_compared += built[index..]
.iter()
.filter(|(_, _, _, t)| t.is_some())
.count();
}
report.interrupted = true;
break;
}
Err(err) => return Err(err),
};
if let Some(phase) = &source_checkpoint
&& outcome != Some(Outcome::Unable)
{
phase.record(index, &outcome)?;
}
outcome
};
let progress_outcome = outcome.map_or(progress::Outcome::Unable, Into::into);
if was_cached {
progress.complete_cached(progress_outcome);
} else {
progress.complete(progress_outcome);
}
if let Some(job) = twin {
let as_probe = results[*job].survived.is_some();
let Some(audit) = report.audit.as_mut() else {
continue;
};
match audit_source_comparison(&results[*job], outcome) {
Some(disagrees) => {
audit.compared += 1;
if disagrees {
let verdict =
|passes: bool| if passes { "passes" } else { "fails" };
audit.source_disagreements.push(report::SourceDisagreement {
at: report::location(&file.display, site),
mutant: report::describe(site, mutation_of(site, mutant)),
as_probe: verdict(as_probe).to_string(),
built: verdict(!as_probe).to_string(),
});
}
}
None => audit.not_compared += 1,
}
continue;
}
match outcome {
None => report.unviable_mutants += 1,
Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
Some(outcome) => {
report.mutants_run += 1;
if outcome != Outcome::Pass {
report.mutants_killed += 1;
*killed_by_loc
.entry((
file.display.clone(),
site.line,
site.column,
"survivor",
))
.or_insert(0) += 1;
}
report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
report.mutants_survived += (outcome == Outcome::Pass) as usize;
}
}
let survived = outcome == Some(Outcome::Pass);
if survived {
let at = report::location(&file.display, site);
let removed = mutant.replacement.trim().is_empty();
let text = match (&site.kind, removed) {
(SiteKind::Field { .. }, true) => {
format!("without the field `{}`", report::one_line(&site.text))
}
(
SiteKind::LiteralSet {
receiver, argument, ..
},
true,
) => format!(
"without `{}` in `{}.contains({})`",
report::one_line(&mutant.into),
report::one_line(receiver),
report::one_line(argument)
),
_ => report::describe(site, mutation_of(site, mutant)),
};
match survivors.last_mut() {
Some((last, texts)) if *last == at => texts.push(text),
_ => survivors.push((at, vec![text])),
}
}
}
Ok(())
},
)?;
if !report.interrupted
&& let Some(phase) = &source_checkpoint
{
phase.finish_if_complete()?;
}
for (at, survivors) in survivors {
finding_run_survivors.push(survivors.len());
report.findings.push(Finding::Survivor {
at,
survivors,
witness: None,
change_since: None,
advice: None,
likely_equivalent: None,
});
}
}
if !report.interrupted
&& let Some(revision) = options
.since
.as_deref()
.filter(|_| !options.list && options.shard.is_none())
{
let hunks = scope::hunks(&since_diff(&workspace, revision)?);
let not_built_changes = std::cell::Cell::new(0usize);
let changed: Vec<(&SourceFile, Vec<reverts::Change>)> = files
.iter()
.filter(|file| built_sources.contains(file) || !options.source_only && !options.rebuild)
.filter_map(|file| {
let relative = file
.path
.strip_prefix(©)
.ok()?
.to_string_lossy()
.replace('\\', "/");
let of_file: Vec<_> = hunks
.iter()
.filter(|hunk| hunk.file == relative)
.cloned()
.collect();
let mut changes = reverts::changes(&file.original, &of_file);
if options.rebuild || options.source_only {
for change in &mut changes {
change.outside = change.undone.as_deref().is_some_and(|undone| {
built_sources.same_program(file, &file.original, undone)
});
}
not_built_changes.set(
not_built_changes.get()
+ changes.iter().filter(|change| change.outside).count(),
);
}
(!changes.is_empty()).then_some((file, changes))
})
.collect();
let not_built_changes = not_built_changes.get();
report.mutants_not_evaluated += not_built_changes;
report.mutants_not_compiled += not_built_changes;
let total: usize = changed
.iter()
.map(|(_, changes)| changes.iter().filter(|change| !change.outside).count())
.sum();
let mixed: usize = files
.iter()
.map(|file| {
let relative = file
.path
.strip_prefix(©)
.unwrap_or(&file.path)
.to_string_lossy()
.replace('\\', "/");
let of_file: Vec<_> = hunks
.iter()
.filter(|hunk| hunk.file == relative)
.cloned()
.collect();
reverts::mixed(&file.original, &of_file)
})
.sum();
if mixed > 0 && (options.rebuild || options.source_only) {
report.mutants_not_evaluated += mixed;
session.note(&format!(
"{mixed} changes are of the program and its tests in the same lines: they are not tried undone"
));
}
if !(options.rebuild || options.source_only) {
report.mutants_not_built += not_built_reverts;
} else if total > 0
|| changed.iter().any(|(_, changes)| {
changes.iter().filter(|change| !change.is_subhunk()).count() > 1
})
{
let reverts_result = (|| -> Result<()> {
session.note(&format!(
"building {total} changes undone, one by one (the code as it was at {})",
report::short_revision(revision)
));
let write = |file: &SourceFile, text: &str, suffix: &str| -> Result<()> {
let suffix = if file.path == root_file { suffix } else { "" };
state.write(&file.path, &format!("{text}{suffix}"))
};
let undone = |edits: &[(&SourceFile, &str)]| -> Result<Option<Outcome>> {
let attempted = (|| -> Result<Option<Outcome>> {
for (file, text) in edits {
write(file, text, root_mutant_suffix)?;
}
Ok(match source_build(&cargo_build()?) {
SourceBuild::Built => Some(run_source_tests(&by_speed)?),
SourceBuild::Refused => None,
SourceBuild::Failed(why) => {
session.note(&format!(
"a build failed without the compiler refusing the code; the change undone is not evaluated: {why}"
));
Some(Outcome::Unable)
}
})
})();
for (file, _) in edits {
let rendered = file.rendered.as_ref().expect("rendered before building");
write(file, &rendered.text, &root_suffix)?;
}
attempted
};
let mut judged = |outcome: Option<Outcome>, at: report::Location, what: String| {
match outcome {
None => report.unviable_mutants += 1,
Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
Some(outcome) => {
report.mutants_run += 1;
report.mutants_killed += (outcome != Outcome::Pass) as usize;
report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
report.mutants_survived += (outcome == Outcome::Pass) as usize;
}
}
if outcome == Some(Outcome::Pass) {
finding_run_survivors.push(1);
report.findings.push(Finding::Survivor {
at,
survivors: vec![what],
witness: None,
advice: None,
change_since: Some(revision.to_string()),
likely_equivalent: None,
});
}
};
let place = |file: &SourceFile, change: &reverts::Change| report::Location {
file: file.display.clone(),
line: change.line,
column: 1,
code: change.code.clone(),
..Default::default()
};
let mut stuck_files = 0;
for (file, changes) in &changed {
let mut stuck = false;
let whole_total = changes.iter().filter(|change| !change.is_subhunk()).count();
let whole_alone = changes
.iter()
.filter(|change| !change.is_subhunk() && !change.outside)
.count();
for change in changes.iter().filter(|change| !change.outside) {
let outcome = match &change.undone {
Some(text) => undone(&[(file, text.as_str())])?,
None => None,
};
if !change.is_subhunk() {
stuck |= outcome.is_none();
}
judged(outcome, place(file, change), change.describe());
}
let whole = reverts::all_undone(&file.original, changes);
let same = |a: &str, b: &str| built_sources.same_program(file, a, b);
let tried: Vec<reverts::Change> = changes
.iter()
.filter(|change| !change.outside)
.cloned()
.collect();
let left_out_matter = whole_alone < whole_total
&& match (&whole, reverts::all_undone(&file.original, &tried)) {
(Some(all), Some(without)) => !same(all, &without),
_ => true,
};
let another = whole
.as_deref()
.is_none_or(|all| !same(all, &file.original));
if whole_total > 1 && another && (stuck || left_out_matter) {
let outcome = match &whole {
Some(text) => undone(&[(file, text.as_str())])?,
None => None,
};
stuck = outcome.is_none();
let first_whole = changes
.iter()
.find(|change| !change.is_subhunk())
.unwrap_or(&changes[0]);
judged(
outcome,
place(file, first_whole),
format!("with all {whole_total} changes to this file undone"),
);
}
stuck_files += usize::from(stuck);
}
let with_left_out = changed.iter().any(|(_, changes)| {
changes
.iter()
.any(|change| !change.is_subhunk() && change.outside)
});
if (stuck_files > 0 || with_left_out) && changed.len() > 1 {
let whole: Option<Vec<String>> = changed
.iter()
.map(|(file, changes)| reverts::all_undone(&file.original, changes))
.collect();
let same = |file: &SourceFile, a: &str, b: &str| {
built_sources.same_program(file, a, b)
};
let another = whole.as_ref().is_none_or(|texts| {
changed
.iter()
.zip(texts)
.any(|((file, _), text)| !same(file, text, &file.original))
});
let left_out_matter = whole.as_ref().is_none_or(|texts| {
changed.iter().zip(texts).any(|((file, changes), text)| {
let tried: Vec<reverts::Change> = changes
.iter()
.filter(|change| !change.outside)
.cloned()
.collect();
reverts::all_undone(&file.original, &tried)
.is_none_or(|without| !same(file, text, &without))
})
});
if another && (stuck_files > 0 || (with_left_out && left_out_matter)) {
let outcome = match &whole {
Some(texts) => {
let edits: Vec<(&SourceFile, &str)> = changed
.iter()
.zip(texts)
.map(|((file, _), text)| (*file, text.as_str()))
.collect();
undone(&edits)?
}
None => None,
};
let (file, changes) = &changed[0];
judged(
outcome,
place(file, &changes[0]),
format!("with every change undone, in all {} files", changed.len()),
);
}
}
Ok(())
})();
match reverts_result {
Ok(()) => {}
Err(err)
if crate::interrupt::is_interrupted()
|| crate::interrupt::is_interrupted_err(&err) =>
{
report.interrupted = true;
}
Err(err) => return Err(err),
}
}
}
let mut witness_files: Vec<&PathBuf> = vec![];
for candidate in &witness_candidates {
if !witness_files.contains(&&candidate.file) {
witness_files.push(&candidate.file);
}
}
let witness_result = (|| -> Result<()> {
for (file_idx, witness_file) in witness_files.iter().enumerate() {
if report.interrupted || crate::interrupt::is_interrupted() {
report.interrupted = true;
for remaining_file in &witness_files[file_idx..] {
report.mutants_not_evaluated += witness_candidates
.iter()
.filter(|candidate| {
candidate.file == **remaining_file && !candidate.existing
})
.count();
}
break;
}
let in_root = **witness_file == root_file;
let file = files
.iter()
.find(|file| file.path == **witness_file)
.expect("witness candidates are of files that are analysed");
let rendered = file.rendered.as_ref().expect("rendered before building");
let left_out_here = built_sources.left_out(file);
let restore = if in_root {
format!("{}{root_suffix}", rendered.text)
} else {
rendered.text.clone()
};
let library_runners: Vec<_> = session
.binaries
.iter()
.filter(|bin| {
root_exe
.as_deref()
.is_some_and(|exe| bin.runner.executable() == Some(exe))
})
.collect();
let ignored = match library_runners
.iter()
.find_map(|bin| match &bin.runner {
Runner::Exe(exe) => Some(list_tests(
exe,
&bin.cwd,
&bin.git_ceiling,
true,
false,
bin.work_lock.as_deref(),
)),
_ => None,
})
.transpose()
{
Ok(ignored) => ignored.unwrap_or_default(),
Err(err)
if crate::interrupt::is_interrupted()
|| crate::interrupt::is_interrupted_err(&err) =>
{
report.interrupted = true;
for remaining_file in &witness_files[file_idx..] {
report.mutants_not_evaluated += witness_candidates
.iter()
.filter(|candidate| {
candidate.file == **remaining_file && !candidate.existing
})
.count();
}
break;
}
Err(err) => return Err(err),
};
let witness_candidates: Vec<&witness::Candidate> = witness_candidates
.iter()
.filter(|candidate| candidate.file == **witness_file)
.collect();
let runner_for = |scenario: &witness::Scenario| {
library_runners.iter().copied().find(|bin| {
scenario
.source_test
.as_ref()
.is_none_or(|required| match &bin.runner {
Runner::Exe(_) if !in_root => {
let inner = format!("::{required}");
bin.tests
.iter()
.any(|test| test.ends_with(&inner) && !ignored.contains(test))
}
Runner::Exe(_) => {
bin.tests.contains(required) && !ignored.contains(required)
}
Runner::Isolated { test, .. } if !in_root => {
test.ends_with(&format!("::{required}"))
}
Runner::Isolated { test, .. } => test == required,
Runner::Doc { .. } | Runner::Nextest { .. } => false,
})
})
};
let write_edits = |edits: &[witness::Edit]| -> Result<bool> {
let Some(source) = witness::render_edits(&file.original, edits, None) else {
return Ok(false);
};
let suffix = if in_root { root_mutant_suffix } else { "" };
state.write(&file.path, &format!("{source}{suffix}"))?;
Ok(true)
};
let suite = |edits: &[witness::Edit]| -> Result<Option<Outcome>> {
if !write_edits(edits)? {
return Ok(None);
}
Ok(match source_build(&cargo_build()?) {
SourceBuild::Built => Some(run_source_tests(&by_speed)?),
SourceBuild::Refused => None,
SourceBuild::Failed(why) => {
session.note(&format!(
"a build failed without the compiler refusing the code; the mutant is not evaluated: {why}"
));
Some(Outcome::Unable)
}
})
};
let compile_observer = |edits: &[witness::Edit]| -> Result<Option<PathBuf>> {
if !write_edits(edits)? {
return Ok(None);
}
let build = build_test_binaries(true)?;
if !build.status.success() {
return Ok(None);
}
let artifacts = parse_build_output(
&String::from_utf8_lossy(&build.stdout),
&[package.name.as_str()],
);
Ok(root_test_exe(&artifacts))
};
let observe = |scenario: &witness::Scenario,
baseline: &TestBinary,
edits: &[witness::Edit],
field_path: Option<&str>,
expected: Option<&str>|
-> Result<Option<witness::Observation>> {
let test = scenario.test_edit_with_field(
&file.original,
witness::TEST_NAME,
field_path,
expected,
);
let edits: Vec<_> = edits.iter().cloned().chain([test]).collect();
let Some(exe) = compile_observer(&edits)? else {
return Ok(None);
};
observe_witness(
baseline,
exe,
wrapper.as_deref(),
scenario,
witness::TEST_NAME,
expected.is_some(),
in_root,
)
};
let witness_checkpoint = if checkpoint.is_some() {
let keys = witness_candidates
.iter()
.map(|candidate| {
let edits = candidate
.edits
.iter()
.map(|edit| (&edit.span, &edit.replacement))
.collect::<Vec<_>>();
serde_json::to_string(&(&candidate.description, edits))
})
.collect::<std::result::Result<Vec<_>, _>>()?;
let name = if in_root {
"witness".to_string()
} else {
format!("witness:{}", file.display)
};
phase(&name, keys)?
} else {
None
};
let mut survivors = vec![];
let mut claimed = BTreeSet::new();
let mut witness_loop_interrupted = false;
progress::track(
options.progress,
"source witness mutants",
witness_candidates.len(),
|progress| -> Result<()> {
for (index, candidate) in witness_candidates.iter().copied().enumerate() {
if crate::interrupt::is_interrupted() {
report.mutants_not_evaluated += witness_candidates[index..]
.iter()
.filter(|c| !c.existing)
.count();
report.interrupted = true;
witness_loop_interrupted = true;
break;
}
let cached = witness_checkpoint
.as_ref()
.map(|phase| phase.get::<WitnessTrial>(index))
.transpose()?
.flatten();
let was_cached = cached.is_some();
if was_cached && let Some(phase) = witness_checkpoint.as_ref() {
phase.mark_reused();
}
let at = witness_location(file, candidate);
if !built_sources.contains(file)
|| candidate.edits.iter().any(|edit| {
left_out_here.iter().any(|(from, to)| {
*from <= edit.span.start && edit.span.end <= *to
})
})
{
if let Some(phase) =
witness_checkpoint.as_ref().filter(|_| cached.is_none())
{
phase.record(index, &WitnessTrial::Inapplicable)?;
}
if !candidate.existing {
report.mutants_not_evaluated += 1;
report.mutants_not_compiled += 1;
let span = &candidate.edits[0].span;
report.skipped.push(report::SkippedSite::new(
at,
file.lines.position(&file.original, span.end),
report::SkipReason::SourceNotBuilt,
Some(
"under a `cfg` that the features of this build turn off"
.to_string(),
),
));
}
if was_cached {
progress.complete_cached(progress::Outcome::Unable);
} else {
progress.complete(progress::Outcome::Unable);
}
continue;
}
let existing = candidate
.existing
.then(|| {
report.findings.iter().position(|finding| {
let location = finding.at();
location.file == at.file
&& location.line == at.line
&& location.column == at.column
&& finding.survivors().contains(&candidate.description)
&& (candidate.finding_at.is_none()
|| !matches!(finding, Finding::InputGap { .. }))
})
})
.flatten();
let existing = existing.filter(|index| {
candidate.finding_at.is_none() || !claimed.contains(index)
});
let scenarios: Vec<_> = candidate
.scenarios
.iter()
.filter_map(|scenario| {
runner_for(scenario).map(|runner| (scenario, runner))
})
.take(4)
.collect();
let paired = candidate.edits.len() > 1;
if (candidate.existing && (existing.is_none() || scenarios.is_empty()))
|| (paired && scenarios.is_empty())
{
if let Some(phase) =
witness_checkpoint.as_ref().filter(|_| cached.is_none())
{
phase.record(index, &WitnessTrial::Inapplicable)?;
}
if was_cached {
progress.complete_cached(progress::Outcome::Unable);
} else {
progress.complete(progress::Outcome::Unable);
}
continue;
}
let trial = if let Some(cached) = cached {
cached
} else {
let attempted = (|| -> Result<WitnessTrial> {
if paired {
for edit in &candidate.edits {
match suite(std::slice::from_ref(edit))? {
Some(Outcome::Fail) => {}
Some(Outcome::Unable) => {
return Ok(WitnessTrial::Evaluated(
Outcome::Unable,
));
}
_ => return Ok(WitnessTrial::Inapplicable),
}
}
}
Ok(suite(&candidate.edits)?
.map_or(WitnessTrial::Unviable, WitnessTrial::Evaluated))
})();
state.write(&file.path, &restore)?;
let trial = match attempted {
Ok(trial) => trial,
Err(err)
if crate::interrupt::is_interrupted()
|| crate::interrupt::is_interrupted_err(&err) =>
{
report.mutants_not_evaluated += witness_candidates[index..]
.iter()
.filter(|c| !c.existing)
.count();
report.interrupted = true;
witness_loop_interrupted = true;
break;
}
Err(err) => return Err(err),
};
if let Some(phase) = &witness_checkpoint
&& !matches!(trial, WitnessTrial::Evaluated(Outcome::Unable))
{
phase.record(index, &trial)?;
}
trial
};
let outcome = match trial {
WitnessTrial::Inapplicable => {
if was_cached {
progress.complete_cached(progress::Outcome::Unable);
} else {
progress.complete(progress::Outcome::Unable);
}
continue;
}
WitnessTrial::Unviable => {
if was_cached {
progress.complete_cached(progress::Outcome::Unable);
} else {
progress.complete(progress::Outcome::Unable);
}
report.unviable_mutants += usize::from(!candidate.existing);
continue;
}
WitnessTrial::Evaluated(outcome) => outcome,
};
if was_cached {
progress.complete_cached(outcome.into());
} else {
progress.complete(outcome.into());
}
if !candidate.existing {
match outcome {
Outcome::Unable => report.mutants_not_evaluated += 1,
Outcome::Pass => {
report.mutants_run += 1;
report.mutants_survived += 1;
}
Outcome::Fail => {
report.mutants_run += 1;
report.mutants_killed += 1;
}
Outcome::Timeout => {
report.mutants_run += 1;
report.mutants_killed += 1;
report.mutants_timed_out += 1;
}
}
}
if outcome == Outcome::Pass {
survivors.push(WitnessSurvivor {
candidate,
at,
existing,
scenarios,
});
}
}
Ok(())
},
)?;
if !witness_loop_interrupted
&& !crate::interrupt::is_interrupted()
&& let Some(phase) = &witness_checkpoint
{
phase.finish_if_complete()?;
}
let record_unwitnessed_survivors =
|survivors: Vec<WitnessSurvivor<'_>>,
report: &mut Report,
finding_run_survivors: &mut Vec<usize>| {
for survivor in survivors {
if survivor.existing.is_none() {
finding_run_survivors.push(1);
report.findings.push(Finding::Survivor {
at: survivor.at,
survivors: vec![survivor.candidate.description.clone()],
advice: survivor.candidate.advice.clone(),
witness: None,
change_since: None,
likely_equivalent: None,
});
}
}
};
if witness_loop_interrupted || crate::interrupt::is_interrupted() {
report.interrupted = true;
record_unwitnessed_survivors(survivors, &mut report, &mut finding_run_survivors);
continue;
}
let originals = shared_witnesses(
&file.original,
&survivors,
wrapper.as_deref(),
in_root,
compile_observer,
note,
);
if !survivors.is_empty() {
state.write(&file.path, &restore)?;
}
let originals = match originals {
Ok(originals) => originals,
Err(err)
if crate::interrupt::is_interrupted()
|| crate::interrupt::is_interrupted_err(&err) =>
{
report.interrupted = true;
record_unwitnessed_survivors(
survivors,
&mut report,
&mut finding_run_survivors,
);
continue;
}
Err(err) => return Err(err),
};
progress::track(
options.progress,
"distinguishing tests",
survivors.len(),
|progress| -> Result<()> {
for (survivor, original) in survivors.into_iter().zip(originals) {
if report.interrupted || crate::interrupt::is_interrupted() {
report.interrupted = true;
if survivor.existing.is_none() {
finding_run_survivors.push(1);
report.findings.push(Finding::Survivor {
at: survivor.at,
survivors: vec![survivor.candidate.description.clone()],
advice: survivor.candidate.advice.clone(),
witness: None,
change_since: None,
likely_equivalent: None,
});
}
continue;
}
if survivor.existing.is_some_and(|index| {
survivor.candidate.finding_at.is_some() && claimed.contains(&index)
}) {
progress.complete(progress::Outcome::Unable);
continue;
}
let mut evidence = None;
let mut original = original;
for (scenario, baseline) in survivor.scenarios {
if report.interrupted || crate::interrupt::is_interrupted() {
report.interrupted = true;
break;
}
let shared = original.take();
let distinction = (|| -> Result<_> {
if let Some(shared) = shared {
let edits: Vec<_> = survivor
.candidate
.edits
.iter()
.chain(shared.tests.iter())
.cloned()
.collect();
if let Some(exe) = compile_observer(&edits)? {
let mutant = match observe_witness(
baseline,
exe,
wrapper.as_deref(),
scenario,
&shared.name,
true,
in_root,
) {
Ok(obs) => obs,
Err(err)
if crate::interrupt::is_interrupted()
|| crate::interrupt::is_interrupted_err(
&err,
) =>
{
return Err(err);
}
Err(_) => None,
};
if let Some(mutant) = mutant
&& mutant.equals_expected == Some(false)
{
let rechecked = match observe_witness(
baseline,
shared.original_exe.path.clone(),
wrapper.as_deref(),
scenario,
&shared.name,
true,
in_root,
) {
Ok(obs) => obs,
Err(err)
if crate::interrupt::is_interrupted()
|| crate::interrupt::is_interrupted_err(
&err,
) =>
{
return Err(err);
}
Err(_) => None,
};
if rechecked.is_some_and(|rechecked| {
rechecked.equals_expected == Some(true)
&& rechecked.value == shared.value
}) && let Some(verified) =
scenario.verified(shared.value, mutant.value)
{
return Ok(Some(verified));
}
}
}
}
let Some(original) = observe(scenario, baseline, &[], None, None)?
else {
return Ok(None);
};
let value = original.value;
if witness::is_expected_literal(&value) {
let Some(mutant) = observe(
scenario,
baseline,
&survivor.candidate.edits,
None,
Some(&value),
)?
else {
return Ok(None);
};
if mutant.equals_expected != Some(false)
|| value == mutant.value
{
return Ok(None);
}
let Some(checked) =
observe(scenario, baseline, &[], None, Some(&value))?
else {
return Ok(None);
};
if checked.equals_expected != Some(true)
|| checked.value != value
{
return Ok(None);
}
return Ok(scenario.verified(value, mutant.value));
}
if witness::parse_debug_struct(&value).is_none() {
return Ok(None);
}
let Some(raw_mutant) = observe(
scenario,
baseline,
&survivor.candidate.edits,
None,
None,
)?
else {
return Ok(None);
};
let Some((path, field_orig, _)) =
witness::narrow_struct_field(&value, &raw_mutant.value)
else {
return Ok(None);
};
if !witness::is_expected_literal(&field_orig) {
return Ok(None);
}
let field_path = path.join(".");
let Some(mutant) = observe(
scenario,
baseline,
&survivor.candidate.edits,
Some(&field_path),
Some(&field_orig),
)?
else {
return Ok(None);
};
if mutant.equals_expected != Some(false)
|| mutant.value != raw_mutant.value
|| value == mutant.value
{
return Ok(None);
}
let Some(checked) = observe(
scenario,
baseline,
&[],
Some(&field_path),
Some(&field_orig),
)?
else {
return Ok(None);
};
if checked.equals_expected != Some(true) || checked.value != value {
return Ok(None);
}
Ok(scenario.verified_field(
value,
mutant.value,
field_path,
field_orig,
))
})();
match distinction {
Ok(Some(mut verified)) => {
let edits = survivor.candidate.edits.len();
verified.individually_killed = (edits > 1).then_some(edits);
evidence = Some(verified);
break;
}
Ok(None) => {}
Err(err)
if crate::interrupt::is_interrupted()
|| crate::interrupt::is_interrupted_err(&err) =>
{
report.interrupted = true;
break;
}
Err(err) => note(&format!(
"could not check a distinguishing test for {}: {err:#}",
scenario.expression,
)),
}
}
state.write(&file.path, &restore)?;
progress.complete(Outcome::Pass.into());
if let Some(index) = survivor.existing {
if let Some(evidence) = evidence {
report.findings[index].set_witness(evidence);
if survivor.candidate.finding_at.is_some() {
claimed.insert(index);
}
}
} else {
finding_run_survivors.push(1);
report.findings.push(Finding::Survivor {
at: survivor.at,
survivors: vec![survivor.candidate.description.clone()],
advice: survivor
.candidate
.advice
.clone()
.filter(|_| evidence.is_none()),
witness: evidence,
change_since: None,
likely_equivalent: None,
});
}
}
Ok(())
},
)?;
}
Ok(())
})();
match witness_result {
Ok(()) => {}
Err(err)
if crate::interrupt::is_interrupted() || crate::interrupt::is_interrupted_err(&err) =>
{
report.interrupted = true;
}
Err(err) => return Err(err),
}
if crate::interrupt::is_interrupted() {
report.interrupted = true;
}
report.record_evaluation();
debug_assert_eq!(report.findings.len(), finding_run_survivors.len());
let mut paired_findings: Vec<(Finding, usize)> = report
.findings
.into_iter()
.zip(finding_run_survivors)
.collect();
paired_findings.sort_by(|(a, _), (b, _)| {
let (a, b) = (a.at(), b.at());
(&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column))
});
let (sorted_findings, finding_run_survivors): (Vec<_>, Vec<_>) =
paired_findings.into_iter().unzip();
report.findings = sorted_findings;
let places: Vec<FilePlaces> = files
.iter()
.map(|file| FilePlaces {
display: &file.display,
source: &file.original,
lines: &file.lines,
places: &file.places,
})
.collect();
name_findings(&mut report.findings, &places);
let partial_scope = is_partial_scope.then(|| crate::baseline::PartialScope {
scope: scope.as_ref(),
exclude_files: &options.exclude_files,
preserve_all_existing: options.shard.is_some(),
});
let write_ctx = BaselineWriteContext {
ws_package_prefix: &ws_package_prefix,
partial_scope: partial_scope.as_ref(),
single_package_run: batch.is_none(),
note: ¬e,
};
apply_suppressions_and_finish(
options,
&files,
&mut report,
&finding_run_survivors,
&killed_by_loc,
checkpoint.as_ref(),
&write_ctx,
)?;
report.checkpoint_reused = checkpoint.as_ref().map_or(0, Checkpoint::applied);
report.wrapper_grace_outcomes = wrapper_grace_counter.as_ref().map(|c| c.snapshot());
debug_assert!(
report.counts_reconcile(),
"report counts do not reconcile: {report:#?}"
);
Ok(report)
}
fn validate_package_options(options: &Options) -> Result<Vec<&str>> {
if let Some(shard) = options.shard
&& (!options.source_only || shard.index >= shard.count)
{
bail!("shards require --source-only and a valid shard index");
}
let mut seen_errors = HashSet::new();
let mut error_values = vec![];
for expression in &options.error_values {
let expression = expression.trim();
if expression.chars().any(char::is_control) {
bail!(
"invalid --error expression {expression:?}: it has to be on one line, \
without control characters"
);
}
let parsed = syn::parse_str::<syn::Expr>(expression)
.with_context(|| format!("invalid --error expression {expression:?}"))?;
if seen_errors.insert(quote::ToTokens::to_token_stream(&parsed).to_string()) {
error_values.push(expression);
}
}
let selection = &options.test_selection;
if options.nextest.is_some() {
if !cfg!(unix) {
bail!("the nextest runner is available on Unix");
}
if !options.source_only || options.doc || selection.enabled() {
bail!(
"--test-tool nextest requires --source-only; select tests through the nextest profile"
);
}
}
if options.baseline_jobs > 1 && !selection.enabled() {
bail!("--baseline-jobs requires isolated tests or a test wrapper or selection");
}
if options.doc && selection.enabled() {
bail!("--doc cannot be combined with isolated test selection");
}
if options.source_only && options.jobs > 1 {
eprintln!(
"tmt: warning: --source-only runs mutants serially in one working copy; ignoring --jobs {}",
options.jobs
);
}
Ok(error_values)
}
struct PreparedWorkCopy {
workspace: PathBuf,
work: PathBuf,
work_lock: Option<Arc<WorkLock>>,
copy: PathBuf,
state: WorkCopy,
external_deps: BTreeSet<PathBuf>,
}
fn prepare_work_copy(
options: &Options,
metadata: &Metadata,
batch: Option<&WorkspaceBatch<'_>>,
catalogue: Option<&CatalogueSnapshot>,
note: &impl Fn(&str),
) -> Result<PreparedWorkCopy> {
let workspace = metadata.workspace_root.canonicalize()?;
let requested_work = catalogue
.map(|catalogue| &catalogue.path)
.or(options.work_dir.as_ref());
let work = match requested_work {
Some(dir) => {
fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
dir.canonicalize()?
}
None => metadata.target_directory.join("tmt"),
};
if workspace.starts_with(&work) {
bail!(
"the work directory {} contains the workspace; choose a directory of its own",
work.display()
);
}
fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?;
let work = work.canonicalize()?;
let work_lock = if catalogue.is_none() {
Some(Arc::new(WorkLock::take(&work)?))
} else {
None
};
let stage_root = work.join("src");
let copy_subdir = staged_copy_subdir(&workspace, &options.stage_external)?;
let copy = if copy_subdir.as_os_str().is_empty() {
stage_root.clone()
} else {
stage_root.join(©_subdir)
};
let marker = work.join(WORK_MARKER);
if stage_root.exists() && !marker.exists() {
bail!(
"{} exists and was not created by tmt; refusing to delete it. \
Choose another --work-dir or remove it yourself.",
stage_root.display()
);
}
fs::write(
&marker,
"Working directory of tmt (targeted-mutation). Safe to delete.\n",
)?;
let target_dir = metadata.target_directory.clone();
let forbidden = |path: &Path| {
path == target_dir
|| path == work
|| batch.is_some_and(|batch| path == batch.work)
|| path.file_name().is_some_and(|n| n == ".git")
|| (path.parent() == Some(workspace.as_path())
&& path.file_name().is_some_and(|n| n == "target"))
};
let state = WorkCopy::open_with_copy_root(&work, &stage_root, ©);
let fixtures = options
.copy_fixtures
.iter()
.map(|path| fixture_relative(path))
.collect::<Result<Vec<_>>>()?;
let excluded = fixture_exclusions(&workspace, &fixtures, &options.copy_fixture_excludes)?;
let fixture_forbidden = |path: &Path| forbidden(path) || excluded.contains(path);
let skip = |path: &Path| {
fixture_forbidden(path) || path.file_name().is_some_and(|n| n == "node_modules")
};
if options.progress && !options.list {
for path in &excluded {
note(&format!(
"excluded fixture {}",
path.strip_prefix(&workspace).unwrap_or(path).display()
));
}
}
if catalogue.is_none_or(|catalogue| !catalogue.ready.get()) {
work_directory(&work, "src")?;
real_dir(©, &state)?;
if copy != stage_root {
for ancestor in copy.ancestors() {
if ancestor == stage_root || !ancestor.starts_with(&stage_root) {
break;
}
state.kept.borrow_mut().insert(ancestor.to_path_buf());
}
}
let visible = if options.all_files {
None
} else {
git_visible_files(&workspace)?
};
match visible {
Some(files) => {
let copied = copy_git_visible(&workspace, ©, files, &workspace, &skip, &state)?;
note(&format!(
"copied {copied} files (ignored files are left out)"
));
}
None => copy_tree(&workspace, ©, &workspace, &skip, &state)?,
}
for relative in &fixtures {
copy_fixture_entry(
&workspace.join(relative),
©.join(relative),
&workspace,
&fixture_forbidden,
&state,
&mut BTreeSet::new(),
)?;
}
let mut staged_destinations: Vec<PathBuf> = Vec::new();
let mut folded_ancestors: BTreeMap<String, PathBuf> = BTreeMap::new();
for entry in &options.stage_external {
let (rel, _) = parse_external_rel(&entry.rel)?;
let dst = normalize(©.join(&rel));
let copy_rel_in_stage = copy.strip_prefix(&stage_root).unwrap_or(©);
let dst_rel_in_stage = dst.strip_prefix(&stage_root).unwrap_or(&dst);
if !dst.starts_with(&stage_root)
|| dst == stage_root
|| copy.starts_with(&dst)
|| dst.starts_with(©)
|| paths_overlap_case_insensitive(copy_rel_in_stage, dst_rel_in_stage)
|| staged_destinations.iter().any(|prev| {
let prev_rel = prev.strip_prefix(&stage_root).unwrap_or(prev);
paths_overlap_case_insensitive(prev_rel, dst_rel_in_stage)
})
{
bail!(
"--stage-external destination collides with the workspace copy or another staged path: {}",
entry.rel.display()
);
}
for ancestor in dst_rel_in_stage.ancestors() {
if ancestor.as_os_str().is_empty() {
continue;
}
let folded = ancestor.to_string_lossy().to_lowercase();
if let Some(previous) = folded_ancestors.get(&folded)
&& previous != ancestor
{
bail!(
"--stage-external destinations differ only by case: {} and {}",
previous.display(),
ancestor.display()
);
}
folded_ancestors.insert(folded, ancestor.to_path_buf());
}
staged_destinations.push(dst.clone());
let src = if entry.from.is_absolute() {
entry.from.clone()
} else {
workspace.join(&entry.from)
};
copy_external_entry(
&src,
&dst,
None,
&work,
&forbidden,
&state,
&mut BTreeSet::new(),
)?;
}
prune(&stage_root, &state)?;
if options.git_index {
git_index::snapshot(&workspace, ©)?;
}
let mut external_deps = BTreeSet::new();
if !options.list {
let mut manifests: Vec<&Path> = metadata
.packages
.iter()
.map(|p| p.manifest_path.as_path())
.collect();
let root_manifest = metadata.workspace_root.join("Cargo.toml");
manifests.push(&root_manifest);
for manifest in manifests {
let Ok(canonical) = manifest.canonicalize() else {
continue;
};
let (Some(manifest_dir), Ok(relative)) =
(canonical.parent(), canonical.strip_prefix(&workspace))
else {
continue;
};
let text = fs::read_to_string(&canonical)?;
let (rewritten, externals) = absolutize_path_dependencies_with_externals(
&text,
manifest_dir,
&workspace,
©,
)?;
external_deps.extend(externals);
if let Some(rewritten) = rewritten {
state.write(©.join(relative), &rewritten)?;
}
}
}
if let Some(catalogue) = catalogue {
state.settle(&workspace)?;
catalogue.ready.set(true);
}
return Ok(PreparedWorkCopy {
workspace,
work,
work_lock,
copy,
state,
external_deps,
});
}
Ok(PreparedWorkCopy {
workspace,
work,
work_lock,
copy,
state,
external_deps: BTreeSet::new(),
})
}
#[allow(clippy::too_many_arguments)]
fn run_audit_phase<'a>(
session: &Session,
files: &[SourceFile],
jobs: &[Job],
results: &mut [JobResult],
timeout_rechecks: &mut report::TimeoutRechecks,
scratch: &Path,
wanted: usize,
workers: usize,
probe_phase: &impl Fn(&str, &[Job]) -> Result<Option<Phase<'a>>>,
) -> Result<report::Audit> {
let survivors: Vec<usize> = (0..jobs.len())
.filter(|job| results[*job].survived.is_some())
.collect();
let chosen: Vec<usize> = spread(survivors.len(), wanted)
.into_iter()
.map(|nth| survivors[nth])
.collect();
session.note(&format!(
"audit: running {} of {} surviving mutants against all tests",
chosen.len(),
survivors.len()
));
let against_all: Vec<Job> = chosen
.iter()
.map(|job| Job {
site: jobs[*job].site,
mutation: jobs[*job].mutation,
tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
})
.collect();
let mut audit = report::Audit {
sampled: chosen.len(),
survivors: survivors.len(),
..report::Audit::default()
};
let audit_checkpoint = probe_phase("audit", &against_all)?;
for (job, again) in chosen.iter().zip(session.run_jobs(
&against_all,
workers,
"audit mutants",
audit_checkpoint.as_ref(),
)?) {
timeout_rechecks.include(&again);
if again.unable || again.unconfirmed_timeout {
audit.not_audited += 1;
} else if audit_all_tests_disagrees(&again) {
results[*job] = again;
let site = files
.iter()
.find_map(|f| Some((f, f.sites.iter().find(|s| s.id == jobs[*job].site)?)));
if let Some((file, site)) = site {
audit
.disagreements
.push(report::location(&file.display, site));
}
}
}
if crate::interrupt::is_interrupted() {
audit.trace_rerun_incomplete = true;
return Ok(audit);
}
session.note("audit: recording the tests once more");
for (index, bin) in session.binaries.iter().enumerate() {
if crate::interrupt::is_interrupted() {
audit.trace_rerun_incomplete = true;
break;
}
let path = scratch.join(format!("trace-{index}-audit.tsv"));
let _ = fs::remove_file(&path);
let trace_env = path.to_string_lossy().into_owned();
let limit = Duration::from_secs(3600);
let outcome = match run_binary(
bin,
None,
&[("TMT_TRACE", &trace_env)],
limit,
RunOutput::Quiet,
1,
) {
Ok(outcome) => outcome,
Err(err)
if crate::interrupt::is_interrupted()
|| crate::interrupt::is_interrupted_err(&err) =>
{
let _ = fs::remove_file(&path);
audit.trace_rerun_incomplete = true;
break;
}
Err(err) => return Err(err),
};
let again = Trace::parse(&fs::read_to_string(&path).unwrap_or_default());
let _ = fs::remove_file(&path);
let records = bin.trace.differences(&again);
if outcome != Outcome::Pass || records > 0 {
audit.trace_differences.push(report::TraceDifference {
binary: bin.name.clone(),
records,
rerun_failed: outcome != Outcome::Pass,
});
}
}
Ok(audit)
}
fn run_effects_phase(
session: &Session,
files: &[SourceFile],
jobs: &[Job],
effect_jobs: &[(usize, usize)],
scratch: &Path,
workers: usize,
findings: &mut [Finding],
) -> Result<()> {
session.note(&format!("tracing {} surviving mutants", effect_jobs.len()));
let sites: BTreeMap<u32, (&str, &Site)> = files
.iter()
.flat_map(|f| f.sites.iter().map(move |s| (s.id, (f.display.as_str(), s))))
.collect();
let traced = run_pool(effect_jobs.len(), workers, |index| {
session.trace_job(
&jobs[effect_jobs[index].1],
scratch,
workers.clamp(1, effect_jobs.len()),
)
})?;
for ((finding, job), mut changes) in effect_jobs.iter().zip(traced) {
if let Some((mutated_file, mutated)) = sites.get(&jobs[*job].site) {
for found in changes.values_mut() {
found.retain(|change| {
sites.get(&change.site()).is_none_or(|(file, site)| {
file != mutated_file
|| site.end <= mutated.start
|| mutated.end <= site.start
})
});
}
changes.retain(|_, found| !found.is_empty());
}
if let Finding::AssertionGap {
effects,
effects_of,
..
} = &mut findings[*finding]
{
*effects = describe_effects(&changes, &sites);
*effects_of = sites
.get(&jobs[*job].site)
.map(|(_, site)| report::describe(site, jobs[*job].mutation));
}
}
Ok(())
}
struct BaselineWriteContext<'a> {
ws_package_prefix: &'a str,
partial_scope: Option<&'a crate::baseline::PartialScope<'a>>,
single_package_run: bool,
note: &'a dyn Fn(&str),
}
fn apply_suppressions_and_finish(
options: &Options,
files: &[SourceFile],
report: &mut Report,
finding_run_survivors: &[usize],
killed_by_loc: &BTreeMap<(String, usize, usize, &'static str), usize>,
checkpoint: Option<&Checkpoint>,
write_ctx: &BaselineWriteContext<'_>,
) -> Result<()> {
if crate::interrupt::is_interrupted() {
report.interrupted = true;
report.record_evaluation();
}
if !report.interrupted && !report.unreached.is_empty() {
let unreached_locs: BTreeSet<(&str, usize, usize)> = report
.unreached
.iter()
.map(|u| (u.file.as_str(), u.line, u.column))
.collect();
let skipped_locs: BTreeSet<(&str, usize, usize)> = report
.skipped
.iter()
.map(|s| (s.at.file.as_str(), s.at.line, s.at.column))
.collect();
let files_with_findings: BTreeSet<&str> = report
.findings
.iter()
.map(|f| f.at().file.as_str())
.collect();
for file in files {
if file.sites.is_empty() || files_with_findings.contains(file.display.as_str()) {
continue;
}
let mut unreached_in_file = 0usize;
let mut all_unreached = true;
for site in &file.sites {
let key = (file.display.as_str(), site.line, site.column);
if skipped_locs.contains(&key) {
continue;
}
if unreached_locs.contains(&key) {
unreached_in_file += 1;
} else {
all_unreached = false;
break;
}
}
if all_unreached && unreached_in_file > 0 {
report.unreached_files.push(file.display.clone());
}
}
}
let parsed_ignores: BTreeMap<&str, crate::baseline::ParsedLineIgnores> = files
.iter()
.map(|f| {
(
f.display.as_str(),
crate::baseline::parse_line_ignores(&f.original),
)
})
.collect();
for (file, parsed) in &parsed_ignores {
for warning in &parsed.warnings {
match warning {
crate::baseline::IgnoreWarning::EmptyScope { line } => {
eprintln!(
"tmt: warning: {}:{line}: empty `tmt:ignore[]` scope suppresses nothing (supported: input_gap, assertion_gap, survivor, @COL, or kind@COL)",
crate::report::sanitize_inline(file),
);
}
crate::baseline::IgnoreWarning::InvalidToken { line, token } => {
let hint = crate::baseline::suggest_ignore_scope(token)
.map(|s| {
format!("; did you mean `{}`?", crate::report::sanitize_inline(&s))
})
.unwrap_or_default();
eprintln!(
"tmt: warning: {}:{line}: unknown `tmt:ignore` scope `{}`{hint} (supported: input_gap, assertion_gap, survivor, @COL, or kind@COL)",
crate::report::sanitize_inline(file),
crate::report::sanitize_inline(token),
);
}
}
}
}
let known = match &options.baseline {
Some(path) => {
let loaded = crate::baseline::load(path)?;
loaded.validate_for_package(&report.package, path)?;
Some(loaded)
}
None => None,
};
let before = report.findings.len();
let mut after_inline: Vec<(Finding, usize)> = Vec::with_capacity(before);
let mut matched_entries: BTreeMap<(&str, usize), BTreeSet<(usize, usize)>> = BTreeMap::new();
for (finding, run_survivors) in report
.findings
.drain(..)
.zip(finding_run_survivors.iter().copied())
{
let at = finding.at();
if let Some((&file_key, parsed)) = parsed_ignores.get_key_value(at.file.as_str())
&& parsed.directives.get(&at.line).is_some_and(|ignore| {
ignore.matches_finding(finding.kind(), at.column, finding.survivors())
})
{
for entry in &parsed.entries {
if entry.matches_finding(at.line, finding.kind(), at.column, finding.survivors()) {
matched_entries
.entry((file_key, entry.comment_line))
.or_default()
.insert((at.line, at.column));
}
}
report.survivor_breakdown.suppressed += run_survivors;
} else {
after_inline.push((finding, run_survivors));
}
}
if !report.interrupted && options.shard.is_none() && report.mutants_not_evaluated == 0 {
let mut available_by_line: BTreeMap<(&str, usize), BTreeSet<String>> = BTreeMap::new();
for (finding, _) in &after_inline {
let at = finding.at();
available_by_line
.entry((at.file.as_str(), at.line))
.or_default()
.insert(format!("{}@{}", finding.kind(), at.column));
}
let skipped_locs: BTreeSet<(&str, usize, usize)> = report
.skipped
.iter()
.map(|s| (s.at.file.as_str(), s.at.line, s.at.column))
.collect();
let unreached_locs: BTreeSet<(&str, usize, usize)> = report
.unreached
.iter()
.map(|u| (u.file.as_str(), u.line, u.column))
.collect();
for file in files {
let Some(parsed) = parsed_ignores.get(file.display.as_str()) else {
continue;
};
if parsed.entries.is_empty() {
continue;
}
let evaluated_lines: BTreeSet<usize> = file
.sites
.iter()
.chain(&file.rebuild_sites)
.filter(|site| {
let key = (file.display.as_str(), site.line, site.column);
!skipped_locs.contains(&key) && !unreached_locs.contains(&key)
})
.map(|site| site.line)
.collect();
for entry in &parsed.entries {
if !entry.is_active() {
continue;
}
if let Some(matched_cols) =
matched_entries.get(&(file.display.as_str(), entry.comment_line))
{
let other_killed: usize = killed_by_loc
.iter()
.filter(|((f, line, col, kind), _)| {
f == &file.display
&& entry.matches(*line, kind, *col)
&& !matched_cols.contains(&(*line, *col))
})
.map(|(_, count)| *count)
.sum();
if other_killed > 0 {
eprintln!(
"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)",
crate::report::sanitize_inline(&file.display),
entry.comment_line,
);
}
continue;
}
if entry
.target_lines
.iter()
.any(|line| evaluated_lines.contains(line))
{
let covered_killed: usize = killed_by_loc
.iter()
.filter(|((f, line, col, kind), _)| {
f == &file.display && entry.matches(*line, kind, *col)
})
.map(|(_, count)| *count)
.sum();
let available_hint = entry
.target_lines
.iter()
.find_map(|line| {
available_by_line
.get(&(file.display.as_str(), *line))
.filter(|s| !s.is_empty())
.map(|selectors| {
let list: Vec<&str> =
selectors.iter().map(String::as_str).collect();
format!("; available on line {line}: {}", list.join(", "))
})
})
.unwrap_or_default();
if covered_killed > 0 {
eprintln!(
"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})",
crate::report::sanitize_inline(&file.display),
entry.comment_line,
);
} else {
eprintln!(
"tmt: warning: {}:{}: `tmt:ignore` matched no findings on an evaluated line (mutants may already be killed or selector/column may not match{available_hint})",
crate::report::sanitize_inline(&file.display),
entry.comment_line,
);
}
}
}
}
}
if crate::interrupt::is_interrupted() {
report.interrupted = true;
report.record_evaluation();
}
if !report.interrupted
&& let Some(path) = &options.write_baseline
{
let unignored: Vec<Finding> = after_inline.iter().map(|(f, _)| f.clone()).collect();
let single_pkg = write_ctx
.single_package_run
.then_some(report.package.as_str());
let summary = crate::baseline::write_scoped(
path,
&report.package,
write_ctx.ws_package_prefix,
&unignored,
write_ctx.partial_scope,
single_pkg,
)?;
if summary.preserved > 0 || summary.removed > 0 {
(write_ctx.note)(&format!(
"baseline {}: {} entries written ({} preserved out of scope, {} resolved removed)",
path.display(),
summary.written,
summary.preserved,
summary.removed
));
}
}
for (finding, run_survivors) in after_inline {
if known
.as_ref()
.is_some_and(|known| known.knows_in_package(&report.package, &finding))
{
report.survivor_breakdown.suppressed += run_survivors;
} else {
report.survivor_breakdown.reported += run_survivors;
report.findings.push(finding);
}
}
report.suppressed = before - report.findings.len();
if crate::interrupt::is_interrupted() {
report.interrupted = true;
report.record_evaluation();
}
if !report.interrupted
&& let Some(checkpoint) = checkpoint
{
checkpoint.finish_if_complete()?;
}
Ok(())
}
fn workspace_report_prefix(relative: &Path) -> String {
let parts: Vec<_> = relative
.components()
.filter_map(|part| match part {
std::path::Component::Normal(name) => Some(name.to_string_lossy()),
_ => None,
})
.collect();
if parts.is_empty() {
String::new()
} else {
format!("{}/", parts.join("/"))
}
}
fn repository_prefix(dir: &Path) -> String {
let shown = Command::new("git")
.arg("-C")
.arg(dir)
.args(["rev-parse", "--show-prefix"])
.stderr(Stdio::null())
.output();
match shown {
Ok(output) if output.status.success() => {
String::from_utf8_lossy(&output.stdout).trim().to_string()
}
_ => String::new(),
}
}
fn spread(count: usize, wanted: usize) -> Vec<usize> {
let wanted = wanted.min(count);
(0..wanted).map(|nth| nth * count / wanted).collect()
}
struct FilePlaces<'a> {
display: &'a str,
source: &'a str,
lines: &'a scope::LineIndex,
places: &'a [(usize, usize, String)],
}
fn name_findings(findings: &mut [Finding], files: &[FilePlaces]) {
let mut by_file: BTreeMap<String, Vec<&mut Finding>> = BTreeMap::new();
for finding in findings {
by_file
.entry(finding.at().file.clone())
.or_default()
.push(finding);
}
for file in files {
let Some(findings) = by_file.remove(file.display) else {
continue;
};
let items = instrument::named_items(file.source);
let index = instrument::ItemIndex::new(&items);
let item_at = |line, column| {
file.lines
.offset_of(file.source, line, column)
.map_or("", |offset| index.at(offset))
};
let mut positions: BTreeMap<(&str, &str), Vec<(usize, usize)>> = BTreeMap::new();
for (line, column, code) in file.places {
positions
.entry((item_at(*line, *column), code))
.or_default()
.push((*line, *column));
}
for places in positions.values_mut() {
places.sort_unstable();
places.dedup();
}
for finding in findings {
let kind = finding.kind();
let at = finding.at_mut();
let item = item_at(at.line, at.column);
let nth = positions.get(&(item, &at.code)).map_or(0, |places| {
places.partition_point(|&place| place < (at.line, at.column))
});
at.item = item.to_string();
at.id = report::finding_id(kind, at, nth);
}
}
}
fn mutation_of(site: &Site, mutant: &instrument::SourceMutant) -> Mutation {
match &site.kind {
SiteKind::Cmp { .. } => plan::CmpOp::ALL
.into_iter()
.find(|op| op.symbol() == mutant.into)
.map_or(Mutation::Negate, Mutation::Op),
SiteKind::Arith { op, .. } => {
if mutant.into.trim_end_matches('=') == op.swapped().symbol() {
Mutation::ArithSwap
} else {
Mutation::ArithSwap2
}
}
SiteKind::Guard { .. } => Mutation::Const(mutant.into == "true"),
SiteKind::Logic { .. } => Mutation::LogicSwap,
SiteKind::Not { .. } => Mutation::DropNot,
SiteKind::Range { .. } | SiteKind::RangeContains { .. } => Mutation::RangeEnd,
SiteKind::SliceEnd { .. } => Mutation::OtherEnd,
SiteKind::StrAffix { .. } => Mutation::StrContains,
SiteKind::StrReplace { .. } => Mutation::StrReplaceMultiplicity,
SiteKind::Clamp { .. } => {
if mutant.into.contains("lower") {
Mutation::ClampDropLower
} else {
Mutation::ClampDropUpper
}
}
SiteKind::Rounding { op, .. } => {
if mutant.into == op.alt1().name() {
Mutation::RoundAlt1
} else {
Mutation::RoundAlt2
}
}
SiteKind::Quantifier { .. } => Mutation::QuantifierSwap,
SiteKind::Position { .. } => Mutation::PositionSwap,
SiteKind::SaturatingArith { .. } => Mutation::SaturatingSwap,
SiteKind::StrTrim { op, .. } => {
if mutant.into == op.alt1().name() {
Mutation::TrimAlt1
} else {
Mutation::TrimAlt2
}
}
SiteKind::StrCaseEq { .. } => Mutation::StrExactEq,
SiteKind::Abs { .. } => Mutation::DropAbs,
SiteKind::IterLimit { .. } => Mutation::IterLimitDrop,
SiteKind::EndianSwap { .. } => Mutation::EndianSwap,
SiteKind::BitCount { .. } => Mutation::BitCountSwap,
SiteKind::LoopCtrl { .. } => Mutation::LoopCtrlSwap,
SiteKind::LiteralSet { elements, .. } => {
let idx = elements
.iter()
.position(|(elem, _, _)| elem == &mutant.into)
.unwrap_or(0);
Mutation::DropLiteralElem(idx as u8)
}
_ => Mutation::Delete,
}
}
fn mutations_like(site: &Site, mutant: &instrument::SourceMutant, integers: bool) -> Vec<Mutation> {
let mut all = vec![mutation_of(site, mutant)];
if let (SiteKind::Cmp { op, .. }, Mutation::Op(into)) = (&site.kind, all[0]) {
let an_order_is_needed = matches!(op, plan::CmpOp::Le | plan::CmpOp::Ge);
if into == op.negated() && (integers || !an_order_is_needed) {
all.push(Mutation::Negate);
}
match (op, into) {
(plan::CmpOp::Lt, plan::CmpOp::Le) | (plan::CmpOp::Ge, plan::CmpOp::Gt) => {
all.push(Mutation::Shift(1))
}
(plan::CmpOp::Gt, plan::CmpOp::Ge) | (plan::CmpOp::Le, plan::CmpOp::Lt) => {
all.push(Mutation::Shift(-1))
}
_ => {}
}
}
all
}
fn describe_effects(
changes: &BTreeMap<String, BTreeSet<Change>>,
sites: &BTreeMap<u32, (&str, &Site)>,
) -> Vec<String> {
let mut by_change: BTreeMap<&Change, Vec<&str>> = BTreeMap::new();
for (test, found) in changes {
for change in found {
by_change.entry(change).or_default().push(test);
}
}
if by_change.is_empty() {
return vec![
"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(),
];
}
let mut out = vec![];
for (change, tests) in by_change.iter().take(3) {
let Some((file, site)) = sites.get(&change.site()) else {
continue;
};
let code = report::location(file, site).code;
let at = format!("{file}:{}", site.line);
let who = if tests.is_empty() {
continue;
} else if let Some(first) = tests
.iter()
.copied()
.find(|test| *test != crate::trace::UNKNOWN_TEST)
{
if tests.len() == 1 {
format!("`{first}`")
} else {
format!("`{first}` (and {} more)", tests.len() - 1)
}
} else if tests.len() == 1 {
"a test".to_string()
} else {
format!("a test (and {} more)", tests.len() - 1)
};
out.push(match change {
Change::Returns { value, .. } => {
format!("with the mutant, {who} gets `{value}` from `{code}` ({at})")
}
Change::NowRuns { .. } => format!("with the mutant, {who} now runs `{code}` ({at})"),
Change::NoLongerRuns { .. } => {
format!("with the mutant, {who} no longer runs `{code}` ({at})")
}
Change::NewOutcome { .. } => {
format!("with the mutant, {who} takes `{code}` ({at}) a way it did not before")
}
});
}
if by_change.len() > 3 {
out.push(format!("(and {} more such changes)", by_change.len() - 3));
}
out
}
#[cfg(test)]
mod tests;