Skip to main content

targeted_mutation/driver/
mod.rs

1//! Runs the whole pipeline on a cargo package:
2//! copy -> instrument -> build once -> trace run -> plan -> run the infected mutants.
3//!
4//! The user's tree is never modified: everything happens in a copy under
5//! `<target dir>/tmt/`.
6
7use std::cell::RefCell;
8use std::collections::{BTreeMap, BTreeSet, HashSet};
9use std::fs;
10use std::path::{Path, PathBuf};
11use std::process::{Command, Stdio};
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15use anyhow::{Context, Result, anyhow, bail};
16
17use crate::checkpoint::{Checkpoint, Phase};
18use crate::instrument::{self, RUNTIME_MOD, Rendered, Site, SiteKind};
19use crate::output_fixture::{self, Fixture};
20use crate::plan::{self, Mutation};
21use crate::propagation::Change;
22use crate::report::{self, Finding, Report};
23use crate::scope::{self};
24use crate::trace::Trace;
25use crate::work_lock::WorkLock;
26use crate::{git_index, leftovers, progress, reverts, witness};
27
28#[derive(Clone)]
29pub struct Options {
30    /// Directory of the package (or workspace) to analyse.
31    pub dir: PathBuf,
32    pub package: Option<String>,
33    /// Return source candidates without running a build.
34    pub list: bool,
35    /// Run every member's tests against the selected package.
36    pub test_workspace: bool,
37    /// Re-run the tests against one survivor per input gap to confirm the prediction.
38    pub verify: bool,
39    /// Where to put the copy and its build. Default: `<target dir>/tmt`.
40    pub work_dir: Option<PathBuf>,
41    /// Progress lines on stderr.
42    pub progress: bool,
43    /// Analyse only code changed since this git revision (plus untracked files).
44    pub since: Option<String>,
45    /// Analyse only these lines: `FILE:FROM-TO`, with `FILE` relative to the package.
46    pub lines: Vec<String>,
47    /// Findings listed in this file are not reported.
48    pub baseline: Option<PathBuf>,
49    /// Write the findings of this run to this file, as a baseline for later runs.
50    pub write_baseline: Option<PathBuf>,
51    /// Other workspace packages whose tests are run too.
52    pub also_test: Vec<String>,
53    /// Run the tests of every workspace package that depends on the analysed one.
54    pub dependents: bool,
55    /// Trace surviving mutants to say what they change in the tests.
56    pub effects: bool,
57    /// Build and run, one by one, the mutants that cannot be switched at run time.
58    pub rebuild: bool,
59    /// Rust expressions used as the payload of a Result error mutation.
60    pub error_values: Vec<String>,
61    pub source_only: bool,
62    pub literal_operators: bool,
63    pub shard: Option<report::Shard>,
64    pub nextest: Option<report::Nextest>,
65    pub test_selection: TestSelection,
66    /// Optimisation level to build the tests with, instead of the profile's own.
67    pub opt_level: Option<u8>,
68    /// Override the time allowed for each test runner under a mutant.
69    pub timeout_seconds: Option<u64>,
70    pub baseline_jobs: usize,
71    pub serial_timeout_rechecks: bool,
72    pub wrapper_grace: Duration,
73    /// Run this many surviving mutants against all tests and record the tests twice.
74    pub audit: Option<usize>,
75    /// Cargo's choice of features and of the lock file, the same for every cargo command.
76    pub cargo: CargoConfig,
77    /// How many mutants to run at the same time.
78    pub jobs: usize,
79    /// Copy every file of the workspace, including the ones git ignores.
80    pub all_files: bool,
81    pub git_index: bool,
82    pub copy_fixtures: Vec<PathBuf>,
83    pub copy_fixture_excludes: Vec<PathBuf>,
84    pub output_fixtures: Vec<Fixture>,
85    pub stage_external: Vec<StageExternal>,
86    pub checkpoint: bool,
87    /// Also run the doc tests (slow: rustdoc recompiles them for every mutant they reach).
88    pub doc: bool,
89}
90
91#[derive(Clone, Default)]
92pub struct TestSelection {
93    pub isolate: bool,
94    pub lib: bool,
95    pub bins: bool,
96    pub integration_tests: Vec<String>,
97    pub targets: Vec<String>,
98    pub include: Vec<String>,
99    pub filter: Vec<String>,
100    pub exclude: Vec<String>,
101    pub include_ignored: bool,
102    pub wrapper: Option<PathBuf>,
103}
104
105impl TestSelection {
106    pub(crate) fn has_target_filters(&self) -> bool {
107        self.lib || self.bins || !self.integration_tests.is_empty() || !self.targets.is_empty()
108    }
109
110    fn enabled(&self) -> bool {
111        self.isolate
112            || self.has_target_filters()
113            || !self.include.is_empty()
114            || !self.filter.is_empty()
115            || !self.exclude.is_empty()
116            || self.include_ignored
117            || self.wrapper.is_some()
118    }
119
120    pub(crate) fn matches_test(&self, test: &str, was_ignored: bool) -> bool {
121        if was_ignored && !self.include_ignored {
122            return false;
123        }
124        if self.exclude.iter().any(|name| name == test) {
125            return false;
126        }
127        if !self.include.is_empty() || !self.filter.is_empty() {
128            let exact = self.include.iter().any(|name| name == test);
129            let partial = self.filter.iter().any(|pat| test.contains(pat));
130            if !exact && !partial {
131                return false;
132            }
133        }
134        true
135    }
136}
137
138pub use crate::report::CargoConfig;
139pub use workcopy::StageExternal;
140
141impl CargoConfig {
142    /// The arguments that say the same to `cargo metadata`, `cargo test` and rustdoc.
143    pub fn flags(&self) -> Vec<String> {
144        let mut flags = vec![];
145        if !self.features.is_empty() {
146            flags.extend(["--features".to_string(), self.features.join(",")]);
147        }
148        for (on, flag) in [
149            (self.all_features, "--all-features"),
150            (self.no_default_features, "--no-default-features"),
151            (self.locked, "--locked"),
152        ] {
153            if on {
154                flags.push(flag.to_string());
155            }
156        }
157        flags
158    }
159}
160
161/// How far from an error to look for the probe that caused it (a probe can break type
162/// inference a few lines further down).
163const NEARBY_LINES: usize = 6;
164/// File that marks a directory as tmt's own working directory.
165const WORK_MARKER: &str = ".tmt-work-dir";
166/// Name under which the crate root re-declares `std` for the runtime module.
167const STD_ALIAS: &str = "__tmt_std";
168/// More rebuilds than this means the blame logic is not converging.
169const MAX_REPAIR_ROUNDS: usize = 40;
170/// Above this many tests, run the whole binary instead of passing names.
171const MAX_TEST_FILTERS: usize = 200;
172
173mod cargo;
174mod repair_cache;
175mod runner;
176mod scope_blame;
177mod session;
178mod witness_runner;
179mod workcopy;
180
181use cargo::*;
182use runner::*;
183use scope_blame::*;
184use session::*;
185use witness_runner::*;
186use workcopy::*;
187
188struct SourceFile {
189    /// Path relative to the package directory, for reports.
190    display: String,
191    /// Path inside the working copy.
192    path: PathBuf,
193    owners: BTreeSet<PathBuf>,
194    original: String,
195    lines: scope::LineIndex,
196    sites: Vec<Site>,
197    /// Sites whose mutants are built one by one.
198    rebuild_sites: Vec<Site>,
199    /// Where every site of the file is (line, column, code), also those a run of a part
200    /// leaves out: findings are numbered by these.
201    places: Vec<(usize, usize, String)>,
202    rendered: Option<Rendered>,
203}
204
205fn write_rendered(
206    file: &mut SourceFile,
207    state: &WorkCopy,
208    suffix: &str,
209    disabled: &HashSet<u32>,
210    newly_disabled: &HashSet<u32>,
211) -> Result<()> {
212    if file.rendered.is_none()
213        || file
214            .sites
215            .iter()
216            .any(|site| newly_disabled.contains(&site.id))
217    {
218        file.rendered = Some(instrument::render(&file.original, &file.sites, &|id| {
219            !disabled.contains(&id)
220        }));
221    }
222    let rendered = file.rendered.as_ref().expect("rendered before writing");
223    if suffix.is_empty() {
224        state.write(&file.path, &rendered.text)
225    } else {
226        state.write(&file.path, &format!("{}{suffix}", rendered.text))
227    }
228}
229
230#[derive(Clone, Copy)]
231struct WorkspaceShard {
232    offset: usize,
233    total: usize,
234    member_total: usize,
235}
236
237struct CatalogueSnapshot {
238    path: PathBuf,
239    ready: std::cell::Cell<bool>,
240    _lock: WorkLock,
241}
242
243struct WorkspaceBatch<'a> {
244    metadata: &'a Metadata,
245    work: &'a Path,
246    catalogue: Option<CatalogueSnapshot>,
247}
248
249/// Returns the Cargo package name that `run` would select for `dir` when no `--package`
250/// is given (including a single-member virtual workspace with glob `members`).
251pub fn select_single_package_name(dir: &Path, cargo: &CargoConfig) -> Option<String> {
252    let canon = dir.canonicalize().ok()?;
253    let metadata = cargo_metadata(&canon, cargo).ok()?;
254    metadata
255        .packages
256        .iter()
257        .find(|p| p.manifest_path.parent() == Some(canon.as_path()))
258        .or(match &metadata.packages[..] {
259            [only] => Some(only),
260            _ => None,
261        })
262        .map(|p| p.name.clone())
263}
264
265/// Collect the original aggregate report for callers that want it.
266pub fn run_packages(options: &Options, names: &[String]) -> Result<Vec<(String, Result<Report>)>> {
267    run_packages_with(options, names, |_, base| Ok(base.clone()))
268}
269
270/// Collect the aggregate report, allowing per-package option customisation (e.g. from `tmt.toml`).
271pub fn run_packages_with(
272    options: &Options,
273    names: &[String],
274    options_for_package: impl FnMut(&str, &Options) -> Result<Options>,
275) -> Result<Vec<(String, Result<Report>)>> {
276    let mut reports = vec![];
277    run_packages_each_with(options, names, options_for_package, |name, result| {
278        reports.push((name, result));
279        Ok(())
280    })?;
281    Ok(reports)
282}
283
284/// Emit each completed package before starting the next one.
285pub fn run_packages_each(
286    options: &Options,
287    names: &[String],
288    completed: impl FnMut(String, Result<Report>) -> Result<()>,
289) -> Result<()> {
290    run_packages_each_with(options, names, |_, base| Ok(base.clone()), completed)
291}
292
293/// Emit each completed package before starting the next one, resolving per-package options
294/// via `options_for_package`.
295pub fn run_packages_each_with(
296    options: &Options,
297    names: &[String],
298    mut options_for_package: impl FnMut(&str, &Options) -> Result<Options>,
299    mut completed: impl FnMut(String, Result<Report>) -> Result<()>,
300) -> Result<()> {
301    if options.baseline.is_some() || options.write_baseline.is_some() {
302        bail!("baseline files require a single package");
303    }
304    let metadata = cargo_metadata(&options.dir, &options.cargo)?;
305    let all: BTreeSet<_> = metadata.packages.iter().map(|p| p.name.clone()).collect();
306    let selected = if names.is_empty() {
307        all.clone()
308    } else {
309        names.iter().cloned().collect()
310    };
311    if let Some(unknown) = selected.difference(&all).next() {
312        bail!("no package `{unknown}` in the workspace");
313    }
314    let base = options
315        .work_dir
316        .clone()
317        .unwrap_or_else(|| metadata.target_directory.join("tmt-workspace"));
318    fs::create_dir_all(&base).with_context(|| format!("creating {}", base.display()))?;
319    let base = base.canonicalize()?;
320    let workspace_canon = metadata.workspace_root.canonicalize()?;
321    if workspace_canon.starts_with(&base) {
322        bail!(
323            "the work directory {} contains the workspace",
324            base.display()
325        );
326    }
327    let mut member_options = Vec::with_capacity(selected.len());
328    let mut used_work_dirs: Vec<(String, PathBuf)> = Vec::new();
329    for name in selected {
330        let mut member = options_for_package(&name, options)?;
331        if member.baseline.is_some() || member.write_baseline.is_some() {
332            bail!("baseline files require a single package (configured for `{name}`)");
333        }
334        member.package = Some(name.clone());
335        let custom_work = member
336            .work_dir
337            .as_ref()
338            .is_some_and(|w| options.work_dir.as_ref() != Some(w));
339        let member_work = if custom_work {
340            let custom = member.work_dir.clone().expect("custom work_dir");
341            fs::create_dir_all(&custom)
342                .with_context(|| format!("creating {}", custom.display()))?;
343            let canon = custom.canonicalize()?;
344            if workspace_canon.starts_with(&canon) {
345                bail!(
346                    "the work directory {} for `{name}` contains the workspace",
347                    canon.display()
348                );
349            }
350            canon
351        } else {
352            base.join(&name)
353        };
354        for (other_name, other_dir) in &used_work_dirs {
355            if member_work == *other_dir
356                || member_work.starts_with(other_dir)
357                || other_dir.starts_with(&member_work)
358            {
359                bail!(
360                    "overlapping work directories for `{name}` ({}) and `{other_name}` ({})",
361                    member_work.display(),
362                    other_dir.display()
363                );
364            }
365        }
366        used_work_dirs.push((name.clone(), member_work.clone()));
367        member.work_dir = Some(member_work);
368        member_options.push((name, member));
369    }
370    let uniform_copy_settings = member_options
371        .first()
372        .map(|(_, first)| {
373            member_options.iter().all(|(_, m)| {
374                m.all_files == first.all_files
375                    && m.git_index == first.git_index
376                    && m.copy_fixtures == first.copy_fixtures
377                    && m.copy_fixture_excludes == first.copy_fixture_excludes
378                    && m.stage_external == first.stage_external
379            })
380        })
381        .unwrap_or(true);
382    let catalogue_dir = base.join(".catalogue");
383    let catalogue = if uniform_copy_settings && (options.list || options.shard.is_some()) {
384        for (name, member_dir) in &used_work_dirs {
385            if *member_dir == catalogue_dir
386                || member_dir.starts_with(&catalogue_dir)
387                || catalogue_dir.starts_with(member_dir)
388            {
389                bail!(
390                    "work directory {} for `{name}` overlaps shared workspace catalogue {}",
391                    member_dir.display(),
392                    catalogue_dir.display()
393                );
394            }
395        }
396        let path = work_directory(&base, ".catalogue")?;
397        Some(CatalogueSnapshot {
398            _lock: WorkLock::take(&path)?,
399            path,
400            ready: std::cell::Cell::new(false),
401        })
402    } else {
403        None
404    };
405    let batch = WorkspaceBatch {
406        metadata: &metadata,
407        work: &base,
408        catalogue,
409    };
410    let Some(shard) = options.shard else {
411        for (name, member) in member_options {
412            let result = run_package(&member, Some(&batch), None);
413            completed(name, result)?;
414        }
415        return Ok(());
416    };
417    if shard.index >= shard.count || member_options.iter().any(|(_, m)| !m.source_only) {
418        bail!("shards require --source-only and a valid shard index");
419    }
420    // A shard needs the counts of preceding members. For an executing batch
421    // retain counts only: the entire catalogue need not stay in memory.
422    let catalogues: Vec<_> = member_options
423        .into_iter()
424        .map(|(name, member)| {
425            let mut preview = member.clone();
426            preview.list = true;
427            preview.shard = None;
428            preview.progress = false;
429            let catalogue = run_package(&preview, Some(&batch), None).map(|mut report| {
430                let count = report.mutants.as_ref().map_or(0, Vec::len);
431                if !member.list {
432                    report.mutants = None;
433                }
434                (count, report)
435            });
436            (name, member, catalogue)
437        })
438        .collect();
439    let total = catalogues
440        .iter()
441        .filter_map(|(_, _, catalogue)| catalogue.as_ref().ok())
442        .map(|(count, _)| count)
443        .sum();
444    let mut offset = 0;
445    for (name, member, catalogue) in catalogues {
446        let result = catalogue.and_then(|(member_total, mut report)| {
447            let range = WorkspaceShard {
448                offset,
449                total,
450                member_total,
451            };
452            offset += member_total;
453            if member.list {
454                report.analysis.shard = Some(shard);
455                let mut index = range.offset;
456                report
457                    .mutants
458                    .as_mut()
459                    .expect("source catalogue")
460                    .retain(|_| {
461                        let keep = shard.contains(index, total);
462                        index += 1;
463                        keep
464                    });
465                Ok(report)
466            } else {
467                run_package(&member, Some(&batch), Some(range))
468            }
469        });
470        completed(name, result)?;
471    }
472    Ok(())
473}
474
475/// Says at the end of a package, however it ends, what its runs left behind.
476struct LeftoverNote(bool);
477
478impl Drop for LeftoverNote {
479    fn drop(&mut self) {
480        use std::sync::atomic::Ordering;
481        let stopped = leftovers::STOPPED.swap(0, Ordering::Relaxed);
482        let not_stopped = leftovers::NOT_STOPPED.swap(0, Ordering::Relaxed);
483        if let Some(text) = leftover_note(stopped, not_stopped)
484            && self.0
485        {
486            eprintln!("tmt: {text}");
487        }
488    }
489}
490
491fn leftover_note(stopped: usize, not_stopped: usize) -> Option<String> {
492    let stopped = (stopped > 0).then(|| {
493        format!("stopped {stopped} processes that the tests had left running after their run")
494    });
495    let not_stopped = (not_stopped > 0).then(|| {
496        format!(
497            "after {not_stopped} runs something the tests started may still be running \
498             (it could not be found or stopped)"
499        )
500    });
501    match (stopped, not_stopped) {
502        (None, None) => None,
503        (Some(one), None) | (None, Some(one)) => Some(one),
504        (Some(stopped), Some(not_stopped)) => Some(format!("{stopped}; {not_stopped}")),
505    }
506}
507
508pub fn run(options: &Options) -> Result<Report> {
509    run_package(options, None, None)
510}
511
512fn run_package(
513    options: &Options,
514    batch: Option<&WorkspaceBatch<'_>>,
515    workspace_shard: Option<WorkspaceShard>,
516) -> Result<Report> {
517    let _leftovers = LeftoverNote(options.progress);
518    let error_values = validate_package_options(options)?;
519    let selection = &options.test_selection;
520    let effective_jobs = if options.source_only { 1 } else { options.jobs };
521    let note = |text: &str| {
522        if options.progress {
523            eprintln!("tmt: {}", report::sanitize_inline(text));
524        }
525    };
526    let dir = options
527        .dir
528        .canonicalize()
529        .with_context(|| format!("no such directory: {}", options.dir.display()))?;
530
531    let local_metadata;
532    let metadata = if let Some(batch) = batch {
533        batch.metadata
534    } else {
535        local_metadata = cargo_metadata(&dir, &options.cargo)?;
536        &local_metadata
537    };
538    let catalogue = batch
539        .and_then(|batch| batch.catalogue.as_ref())
540        .filter(|_| options.list);
541    let package = match &options.package {
542        Some(name) => metadata.packages.iter().find(|p| &p.name == name),
543        None => metadata
544            .packages
545            .iter()
546            .find(|p| p.manifest_path.parent() == Some(dir.as_path()))
547            .or(match &metadata.packages[..] {
548                [only] => Some(only),
549                _ => None,
550            }),
551    }
552    .ok_or_else(|| anyhow!("cannot tell which package to analyse; pass --package <name>"))?;
553    // The packages whose tests are built and run: the analysed one, and on request others
554    // of the workspace that use it.
555    let mut test_packages: Vec<&Package> = vec![package];
556    for name in &options.also_test {
557        let other = metadata
558            .packages
559            .iter()
560            .find(|p| &p.name == name)
561            .ok_or_else(|| anyhow!("--also-test: no package `{name}` in the workspace"))?;
562        if !test_packages.iter().any(|p| p.name == other.name) {
563            test_packages.push(other);
564        }
565    }
566    if options.test_workspace {
567        test_packages.extend(
568            metadata
569                .packages
570                .iter()
571                .filter(|other| {
572                    !test_packages
573                        .iter()
574                        .any(|selected| selected.name == other.name)
575                })
576                .collect::<Vec<_>>(),
577        );
578    }
579    if options.dependents {
580        for name in dependents_of(&package.name, &metadata.packages) {
581            if let Some(other) = metadata.packages.iter().find(|p| p.name == name)
582                && !test_packages.iter().any(|p| p.name == other.name)
583            {
584                test_packages.push(other);
585            }
586        }
587    }
588    if !options.list {
589        validate_target_selection(&test_packages, selection)?;
590    }
591    let is_kind = |t: &Target, kinds: &[&str]| t.kind.iter().any(|k| kinds.contains(&k.as_str()));
592    let root_target = package
593        .targets
594        .iter()
595        .find(|t| {
596            is_kind(
597                t,
598                &["lib", "rlib", "cdylib", "staticlib", "dylib", "proc-macro"],
599            )
600        })
601        .or_else(|| package.targets.iter().find(|t| is_kind(t, &["bin"])))
602        .ok_or_else(|| anyhow!("package `{}` has no lib or bin target", package.name))?;
603
604    // 2. Copy the workspace.
605    let PreparedWorkCopy {
606        workspace,
607        work,
608        work_lock,
609        copy,
610        state,
611        external_deps,
612    } = prepare_work_copy(options, metadata, batch, catalogue, &note)?;
613
614    let in_copy = |path: &Path| -> Result<PathBuf> {
615        let canonical = path.canonicalize()?;
616        let relative = canonical
617            .strip_prefix(&workspace)
618            .with_context(|| format!("{} is outside the workspace", path.display()))?;
619        Ok(copy.join(relative))
620    };
621    let package_dir = in_copy(
622        package
623            .manifest_path
624            .parent()
625            .expect("manifest has a parent"),
626    )?;
627    let root_file = in_copy(&root_target.src_path)?;
628    let source_dir = root_file
629        .parent()
630        .expect("source file has a parent")
631        .to_path_buf();
632
633    // 3. Walk all production roots. Other Cargo targets can include a production
634    // module by path, so record them as consumers when deciding what can be probed.
635    let mut roots = BTreeMap::new();
636    for owner in &metadata.packages {
637        for target in &owner.targets {
638            let production = owner.name == package.name && target.is_production();
639            if let Ok(path) = in_copy(&target.src_path)
640                && path.is_file()
641            {
642                let selected = roots.entry(path).or_insert(false);
643                *selected |= production;
644            }
645        }
646    }
647    let paths = source_graph(roots, &copy, |path| state.original(path, &workspace))?;
648    let scope = requested_scope(options, &workspace, &package_dir, &copy)?;
649    let mut skipped = vec![];
650    let mut files = vec![];
651    let mut next_id = 0u32;
652    let want_witnesses = (options.list || options.rebuild || options.source_only)
653        && root_target.test_build_arg() == Some(("--lib", None));
654    let mut witness_candidates = vec![];
655    for (path, owners) in paths {
656        let Some(original) = state.original(&path, &workspace)? else {
657            continue; // left by an earlier run; gone or rewritten before the build
658        };
659        let selected_file = scope.as_ref().is_none_or(|scope| {
660            let relative = path.strip_prefix(&copy).unwrap_or(&path).to_string_lossy();
661            scope.touches(&relative, 1, usize::MAX)
662        });
663        if !selected_file && path != root_file {
664            continue;
665        }
666        let display = relative_source(&path, &package_dir).display().to_string();
667        match instrument::parse_source(&original) {
668            Ok(parsed) => {
669                let mut found =
670                    instrument::discover_parsed(&original, &parsed, next_id, &error_values);
671                // A test can be put into a file that the library alone builds.
672                if want_witnesses
673                    && selected_file
674                    && owners.consumers.len() == 1
675                    && owners.consumers.contains(&root_file)
676                {
677                    witness_candidates.extend(
678                        witness::discover_parsed(&original, &parsed, !options.list)
679                            .into_iter()
680                            .map(|mut candidate| {
681                                candidate.file = path.clone();
682                                candidate
683                            }),
684                    );
685                    // With `--literal-operators` the mutant that was built is not the
686                    // one these candidates write.
687                    if !options.list && !options.literal_operators {
688                        witness_candidates.extend(
689                            // Also for what is mutated by building it only (the
690                            // product of two literals).
691                            stronger_assertions(
692                                &original,
693                                &parsed,
694                                found.sites.iter().chain(&found.rebuild_sites),
695                            )
696                            .into_iter()
697                            .map(|mut candidate| {
698                                candidate.file = path.clone();
699                                candidate
700                            }),
701                        );
702                    }
703                }
704                next_id += found.sites.len() as u32;
705                if owners.consumers.len() != 1 || !owners.consumers.contains(&root_file) {
706                    found.rebuild_sites.append(&mut found.sites);
707                }
708                let places = if options.list {
709                    vec![]
710                } else {
711                    found
712                        .sites
713                        .iter()
714                        .chain(&found.rebuild_sites)
715                        .map(|site| (site.line, site.column, report::one_line(&site.text)))
716                        .collect()
717                };
718                files.push(SourceFile {
719                    display,
720                    path,
721                    owners: owners.production,
722                    lines: scope::LineIndex::new(&original),
723                    original,
724                    places,
725                    sites: found.sites,
726                    rebuild_sites: found.rebuild_sites,
727                    rendered: None,
728                });
729            }
730            Err(err) => {
731                if selected_file {
732                    let diagnostic = format!("{err:#}");
733                    note(&format!("skipping {display}: {diagnostic}"));
734                    let end_line = scope::line_of(&original, original.len());
735                    let end_column = original.rsplit('\n').next().unwrap_or("").chars().count() + 1;
736                    skipped.push(report::SkippedSite::new(
737                        report::Location {
738                            file: display,
739                            line: 1,
740                            column: 1,
741                            ..Default::default()
742                        },
743                        (end_line, end_column),
744                        report::SkipReason::UnparseableSource,
745                        Some(diagnostic),
746                    ));
747                }
748            }
749        }
750    }
751
752    // Where the tests of a file changed and nothing else says so, the whole program of
753    // the file is looked at: what they found out before and let through now is theirs.
754    let since_hunks = match options.since.as_deref() {
755        Some(revision) if !options.list && options.shard.is_none() => {
756            scope::hunks(&since_diff(&workspace, revision)?)
757        }
758        _ => vec![],
759    };
760    let mut tests_changed: Vec<(PathBuf, Vec<scope::Hunk>)> = vec![];
761    // Files with a change that is tried undone: they are looked at even with no site.
762    let mut undo_paths: HashSet<PathBuf> = HashSet::new();
763    let mut not_built_reverts: usize = 0;
764    let mut beyond_places: HashSet<(PathBuf, usize, usize)> = HashSet::new();
765    // Only the requested lines, if any were requested.
766    if let Some(scope) = &scope {
767        for file in &mut files {
768            let relative = file
769                .path
770                .strip_prefix(&copy)
771                .unwrap_or(&file.path)
772                .to_string_lossy()
773                .into_owned();
774            let in_scope = |site: &Site| {
775                scope.touches(&relative, file.lines.line_of(site.start), file.lines.line_of(site.end))
776                    // A function is in scope by its signature line too.
777                    || scope.touches(&relative, site.line, site.line)
778            };
779            let of_file: Vec<scope::Hunk> = since_hunks
780                .iter()
781                .filter(|hunk| hunk.file == relative)
782                .cloned()
783                .collect();
784            let changes_count = reverts::changes(&file.original, &of_file).len();
785            if options.rebuild || options.source_only {
786                if changes_count > 0 || reverts::mixed(&file.original, &of_file) > 0 {
787                    undo_paths.insert(file.path.clone());
788                }
789            } else {
790                not_built_reverts += changes_count;
791            }
792            let of_tests = reverts::test_hunks(&file.original, &of_file);
793            if of_tests.is_empty() {
794                file.sites.retain(in_scope);
795            } else {
796                beyond_places.extend(
797                    file.sites
798                        .iter()
799                        .filter(|site| !in_scope(site))
800                        .map(|site| (file.path.clone(), site.start, site.end)),
801                );
802                tests_changed.push((file.path.clone(), of_tests));
803            }
804            file.rebuild_sites.retain(in_scope);
805        }
806        files.retain(|f| {
807            !f.sites.is_empty()
808                || !f.rebuild_sites.is_empty()
809                || f.path == root_file
810                || witness_candidates.iter().any(|c| c.file == f.path)
811                || undo_paths.contains(&f.path)
812        });
813    }
814    if !options.list {
815        for candidate in witness_candidates.iter().filter(|c| !c.existing) {
816            if let Some(file) = files.iter_mut().find(|file| file.path == candidate.file) {
817                let at = witness_location(file, candidate);
818                file.places.push((at.line, at.column, at.code));
819            }
820        }
821    }
822    witness_candidates.retain(|candidate| {
823        let Some(file) = files.iter().find(|file| file.path == candidate.file) else {
824            return false;
825        };
826        let relative = file
827            .path
828            .strip_prefix(&copy)
829            .unwrap_or(&file.path)
830            .to_string_lossy();
831        scope.as_ref().is_none_or(|scope| {
832            let site_in_scope = if candidate.edits.len() == 1 {
833                scope.touches(&relative, *candidate.scope.start(), *candidate.scope.end())
834            } else {
835                candidate.edits.iter().any(|edit| {
836                    scope.touches(
837                        &relative,
838                        file.lines.line_of(edit.span.start),
839                        file.lines.line_of(edit.span.end),
840                    )
841                })
842            };
843            site_in_scope
844                || candidate
845                    .signature_lines
846                    .iter()
847                    .any(|&line| scope.touches(&relative, line, line))
848        })
849    });
850    let total_sites: usize = files
851        .iter()
852        .map(|f| f.sites.len() + f.rebuild_sites.len())
853        .sum::<usize>()
854        + witness_candidates
855            .iter()
856            .filter(|candidate| !candidate.existing)
857            .count();
858    let files_with_sites = files
859        .iter()
860        .filter(|f| {
861            !f.sites.is_empty()
862                || !f.rebuild_sites.is_empty()
863                || witness_candidates
864                    .iter()
865                    .any(|c| !c.existing && c.file == f.path)
866        })
867        .count();
868    note(&format!(
869        "{total_sites} sites in {files_with_sites} {}",
870        if files_with_sites == 1 {
871            "file"
872        } else {
873            "files"
874        }
875    ));
876    if options.source_only {
877        for file in &mut files {
878            file.rebuild_sites.append(&mut file.sites);
879        }
880    }
881
882    let source_mutants = |file: &SourceFile, site: &Site, include_boundary: bool| {
883        let mut mutants = instrument::source_mutants(site);
884        if include_boundary {
885            mutants.extend(instrument::source_boundary_mutant(site));
886        }
887        if options.literal_operators {
888            instrument::literal_operator_mutants(&file.original, site, &mut mutants);
889        }
890        instrument::keep_line_ends(&file.original, &mut mutants);
891        mutants
892    };
893    let counts = options.shard.map(|_| {
894        let regular: usize = files
895            .iter()
896            .map(|file| {
897                file.rebuild_sites
898                    .iter()
899                    .map(|site| source_mutants(file, site, true).len())
900                    .sum::<usize>()
901            })
902            .sum();
903        let total = regular
904            + witness_candidates
905                .iter()
906                .filter(|candidate| !candidate.existing)
907                .count();
908        (regular, total)
909    });
910    if let (Some(range), Some((_, local_total))) = (workspace_shard, counts)
911        && range.member_total != local_total
912    {
913        bail!("package catalogue changed while preparing its workspace shard");
914    }
915    let in_shard = |index| match (options.shard, counts, workspace_shard) {
916        (Some(shard), _, Some(range)) => shard.contains(range.offset + index, range.total),
917        (Some(shard), Some((_, total)), _) => shard.contains(index, total),
918        _ => true,
919    };
920    if let Some((mut index, _)) = counts {
921        witness_candidates.retain(|candidate| {
922            if candidate.existing {
923                return true;
924            }
925            let selected = in_shard(index);
926            index += 1;
927            selected
928        });
929    }
930    let empty_shard = counts.is_some_and(|(_, total)| !(0..total).any(in_shard));
931
932    let package_path = package.manifest_path.parent().unwrap_or(Path::new("."));
933    let mut report_path = repository_prefix(package_path);
934    if report_path.is_empty()
935        && batch.is_some()
936        && let Ok(relative) = package_path.strip_prefix(&workspace)
937    {
938        report_path = workspace_report_prefix(relative);
939    }
940    let mut report = Report {
941        package: package.name.clone(),
942        sites: if empty_shard { 0 } else { total_sites },
943        analysis: report::Analysis {
944            package_path: report_path,
945            since: options.since.clone(),
946            lines: options.lines.clone(),
947            tests_of: test_packages.iter().map(|p| p.name.clone()).collect(),
948            cargo: options.cargo.clone(),
949            opt_level: options.opt_level,
950            timeout_seconds: options.timeout_seconds,
951            baseline_jobs: (options.baseline_jobs > 1).then_some(options.baseline_jobs),
952            timeout_recheck: if options.serial_timeout_rechecks {
953                "serial"
954            } else {
955                "none"
956            },
957            wrapper_grace_seconds: selection
958                .wrapper
959                .as_ref()
960                .map(|_| options.wrapper_grace.as_secs()),
961            rebuild: options.rebuild || options.source_only,
962            verified: options.verify && !options.source_only,
963            doc_tests: options.doc,
964            source_only: options.source_only,
965            literal_operators: options.literal_operators,
966            shard: options.shard,
967            nextest: options.nextest.clone(),
968            error_values: error_values
969                .iter()
970                .map(|value| (*value).to_owned())
971                .collect(),
972            test_selection: None,
973            git_index: options.git_index,
974            copy_fixtures: options.copy_fixtures.clone(),
975            copy_fixture_excludes: options.copy_fixture_excludes.clone(),
976            output_fixtures: options.output_fixtures.clone(),
977            stage_external: options.stage_external.clone(),
978            checkpoint: (options.checkpoint && !options.list)
979                .then(|| work.join("checkpoint.jsonl")),
980        },
981        skipped,
982        ..Report::default()
983    };
984    if options.list {
985        if catalogue.is_none() {
986            state.settle(&workspace)?;
987        }
988        let mut candidates = vec![];
989        let mut index = 0;
990        for file in &files {
991            let sites = file
992                .sites
993                .iter()
994                .map(|site| (site, false))
995                .chain(file.rebuild_sites.iter().map(|site| (site, true)));
996            for (site, requires_rebuild) in sites {
997                for mutant in source_mutants(file, site, true) {
998                    if in_shard(index) {
999                        candidates.push(report::Candidate {
1000                            what: mutant.what,
1001                            into: mutant.into,
1002                            requires_rebuild,
1003                            edits: vec![candidate_edit(
1004                                file,
1005                                mutant.start,
1006                                mutant.end,
1007                                mutant.replacement,
1008                            )],
1009                        });
1010                    }
1011                    index += 1;
1012                }
1013            }
1014        }
1015        candidates.extend(
1016            witness_candidates
1017                .iter()
1018                .filter(|candidate| !candidate.existing)
1019                .filter_map(|candidate| {
1020                    let file = files.iter().find(|file| file.path == candidate.file)?;
1021                    Some(report::Candidate {
1022                        what: "witness".into(),
1023                        into: candidate.description.clone(),
1024                        requires_rebuild: true,
1025                        edits: candidate
1026                            .edits
1027                            .iter()
1028                            .map(|edit| {
1029                                candidate_edit(
1030                                    file,
1031                                    edit.span.start,
1032                                    edit.span.end,
1033                                    edit.replacement.clone(),
1034                                )
1035                            })
1036                            .collect(),
1037                    })
1038                }),
1039        );
1040        report.mutants = Some(candidates);
1041        return Ok(report);
1042    }
1043    if empty_shard || (scope.is_some() && total_sites == 0 && undo_paths.is_empty()) {
1044        // Restore files changed by a previous run before reporting a selection with no work.
1045        state.settle(&workspace)?;
1046        if let Some(path) = &options.baseline {
1047            crate::baseline::load(path)?;
1048        }
1049        if let Some(path) = &options.write_baseline {
1050            crate::baseline::write(path, &[])?;
1051        }
1052        if !empty_shard {
1053            report.mutants_not_built += not_built_reverts;
1054        }
1055        report.record_evaluation();
1056        if let Some(path) = report.analysis.checkpoint.as_deref() {
1057            let checkpoint = Checkpoint::open(path)?;
1058            let settings =
1059                serde_json::json!({"analysis": &report.analysis, "package": &package.name});
1060            let identity = crate::campaign_identity::compute(&copy, &settings, [], false)?;
1061            checkpoint.start(&identity, settings)?;
1062            checkpoint.finish()?;
1063        }
1064        return Ok(report);
1065    }
1066
1067    // The injected runtime indexes its per-thread arrays by probe ID. Number the
1068    // retained probes together so a narrow scope does not allocate slots for omitted sites.
1069    for (id, site) in files
1070        .iter_mut()
1071        .flat_map(|file| &mut file.sites)
1072        .enumerate()
1073    {
1074        site.id = id as u32;
1075    }
1076    // The sites outside of what changed, looked at for the sake of the tests that did.
1077    let beyond: HashSet<u32> = files
1078        .iter()
1079        .flat_map(|file| {
1080            file.sites
1081                .iter()
1082                .filter(|site| beyond_places.contains(&(file.path.clone(), site.start, site.end)))
1083                .map(|site| site.id)
1084        })
1085        .collect();
1086
1087    let root_source = state
1088        .original(&root_file, &workspace)?
1089        .with_context(|| format!("{} is missing", root_target.src_path.display()))?;
1090    let root_suffix = if options.source_only || files.iter().all(|file| file.sites.is_empty()) {
1091        String::new()
1092    } else {
1093        state.write(
1094            &source_dir.join(format!("{RUNTIME_MOD}.rs")),
1095            crate::RUNTIME_SOURCE,
1096        )?;
1097        let std_alias = format!("extern crate std as {STD_ALIAS};");
1098        if root_source.contains(&std_alias) {
1099            format!("\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
1100        } else {
1101            format!("\n#[doc(hidden)]\n{std_alias}\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
1102        }
1103    };
1104
1105    // 4. Build, disabling the sites whose probe does not compile (formal/tla/RepairLoop.tla).
1106    let mut disabled: HashSet<u32> = HashSet::new();
1107    let mut repairs = BTreeMap::new();
1108    let build_target = work_directory(&work, "target")?;
1109    let target_flags = test_build_flags(&test_packages, selection, &workspace, &options.cargo);
1110    let build_scope = if target_flags.is_some() {
1111        report::TestBuildScope::SelectedTargets
1112    } else {
1113        report::TestBuildScope::PackageWide
1114    };
1115    let build_note = if selection.has_target_filters() && target_flags.is_none() {
1116        "Cargo is using a package-wide build because the selected test targets cannot be expressed exactly.\n"
1117    } else {
1118        ""
1119    };
1120    if !build_note.is_empty() {
1121        note(build_note.trim_end());
1122    }
1123    // An observation uses only the library's unit-test artifact. The baseline and
1124    // source mutants still need the normal library build to check cfg(not(test)).
1125    let can_build_only_observer = !options.doc
1126        && target_flags.is_none()
1127        && test_packages.len() == 1
1128        && package.targets.len() == 1
1129        && root_target.test
1130        && root_target.test_build_arg() == Some(("--lib", None));
1131    let build_test_binaries = |observer: bool| {
1132        let mut command = Command::new("cargo");
1133        isolate_copy_command(&mut command, &work);
1134        if let Some(lock) = &work_lock {
1135            lock.retain_for(&mut command);
1136        }
1137        command
1138            .args(["test", "--no-run", "--message-format=json"])
1139            .args(test_packages.iter().flat_map(|p| ["-p", p.name.as_str()]))
1140            .args(target_flags.as_deref().unwrap_or_default())
1141            .args((observer && can_build_only_observer).then_some("--lib"))
1142            .args(options.cargo.flags())
1143            .current_dir(&copy)
1144            .env("CARGO_TARGET_DIR", &build_target)
1145            .env("CARGO_BUILD_BUILD_DIR", &build_target)
1146            .envs(profile_env(options.opt_level));
1147        run_cargo_with_progress(&mut command, options.progress && !observer)
1148    };
1149    let cargo_build = || build_test_binaries(false);
1150    let has_probe_sites = !options.source_only && files.iter().any(|f| !f.sites.is_empty());
1151    let repair_fingerprint = has_probe_sites.then(|| {
1152        let test_pkg_names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
1153        repair_cache::compute_fingerprint(
1154            &state.root,
1155            &copy,
1156            &workspace,
1157            &state,
1158            &external_deps,
1159            &package.name,
1160            &test_pkg_names,
1161            &options.cargo,
1162            options.opt_level,
1163            target_flags.as_deref(),
1164            &error_values,
1165            options.doc,
1166            &files,
1167        )
1168    });
1169    if let Some(fingerprint) = &repair_fingerprint {
1170        let cached = repair_cache::load(&work, fingerprint);
1171        if !cached.is_empty() {
1172            for entry in cached {
1173                if let Some(file) = files.iter().find(|f| f.display == entry.file)
1174                    && let Some(site) = file.sites.get(entry.site_index)
1175                    && site.start == entry.start
1176                    && site.end == entry.end
1177                    && site.text == entry.text
1178                    && format!("{:?}", site.kind) == entry.kind
1179                {
1180                    disabled.insert(site.id);
1181                    repairs.entry(site.id).or_insert(entry.reason);
1182                }
1183            }
1184            if !disabled.is_empty() {
1185                note(&format!(
1186                    "reusing {} cached repair exclusion(s)",
1187                    disabled.len()
1188                ));
1189            }
1190        }
1191    }
1192    let mut rounds = 0;
1193    let mut newly_disabled = HashSet::new();
1194    let build = loop {
1195        for file in &mut files {
1196            let suffix = if file.path == root_file {
1197                root_suffix.as_str()
1198            } else {
1199                ""
1200            };
1201            write_rendered(file, &state, suffix, &disabled, &newly_disabled)?;
1202        }
1203        if !files.iter().any(|f| f.path == root_file) {
1204            state.write(&root_file, &format!("{root_source}{root_suffix}"))?;
1205        }
1206        if rounds == 0 {
1207            state.settle(&workspace)?;
1208        }
1209        note(if rounds == 0 {
1210            "building the instrumented crate"
1211        } else {
1212            "rebuilding without the sites that failed to compile"
1213        });
1214        let output = cargo_build()?;
1215        let names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
1216        let build = parse_build_output(&String::from_utf8_lossy(&output.stdout), &names);
1217        if output.status.success() {
1218            if let Some(fingerprint) = &repair_fingerprint {
1219                let cached_entries: Vec<repair_cache::CachedSite> = files
1220                    .iter()
1221                    .flat_map(|file| {
1222                        file.sites
1223                            .iter()
1224                            .enumerate()
1225                            .filter(|(_, site)| disabled.contains(&site.id))
1226                            .map(|(site_index, site)| repair_cache::CachedSite {
1227                                file: file.display.clone(),
1228                                site_index,
1229                                start: site.start,
1230                                end: site.end,
1231                                text: site.text.clone(),
1232                                kind: format!("{:?}", site.kind),
1233                                reason: repairs.get(&site.id).cloned().unwrap_or_default(),
1234                            })
1235                    })
1236                    .collect();
1237                let _ = repair_cache::save(&work, fingerprint, &cached_entries);
1238            }
1239            break build;
1240        }
1241        let diagnostics = || {
1242            [
1243                build.diagnostics.join("\n"),
1244                String::from_utf8_lossy(&output.stderr).into_owned(),
1245            ]
1246            .into_iter()
1247            .filter(|part| !part.trim().is_empty())
1248            .collect::<Vec<_>>()
1249            .join("\n")
1250        };
1251        if build.errors.is_empty() {
1252            bail!("the build failed:\n{build_note}{}", diagnostics());
1253        }
1254        if build
1255            .errors
1256            .iter()
1257            .any(|error| is_non_probe_error(error, &files, &copy))
1258        {
1259            bail!(
1260                "the build failed with an error unrelated to instrumentation:\n{build_note}{}",
1261                diagnostics()
1262            );
1263        }
1264        rounds += 1;
1265        let before = disabled.len();
1266        let mut blamed_now: HashSet<u32> = HashSet::new();
1267        for error in &build.errors {
1268            let blamed = blame_error(error, &files, &copy, &disabled);
1269            if std::env::var_os("TMT_DEBUG").is_some() {
1270                eprintln!(
1271                    "tmt: debug: blaming {blamed:?} for\n{}",
1272                    report::sanitize_terminal(&error.rendered)
1273                );
1274            }
1275            for id in blamed {
1276                repairs
1277                    .entry(id)
1278                    .or_insert_with(|| error.rendered.lines().next().unwrap_or("").to_string());
1279                blamed_now.insert(id);
1280            }
1281        }
1282        disabled.extend(blamed_now.iter().copied());
1283        newly_disabled = blamed_now;
1284        if disabled.len() == before || rounds > MAX_REPAIR_ROUNDS {
1285            bail!(
1286                "the crate does not build after instrumentation.\n\
1287                 {build_note}Does `cargo test --no-run` pass on the original for the same targets?\n{}",
1288                diagnostics()
1289            );
1290        }
1291    };
1292    let built_sources = if options.rebuild || options.source_only || options.audit.is_some() {
1293        // A feature can also be turned on behind cargo's back: by compiler flags (in
1294        // the environment or a configuration file) and by a build script.
1295        // Every variable of flags for the compiler: also those of one target
1296        // (`CARGO_TARGET_<TRIPLE>_RUSTFLAGS`).
1297        let behind_cargo = features_from_flags(
1298            std::env::vars_os()
1299                .filter(|(name, _)| name.to_string_lossy().ends_with("RUSTFLAGS"))
1300                .map(|(_, value)| Some(value)),
1301        ) || build.build_scripts.iter().any(|script| {
1302            script["cfgs"].as_array().is_some_and(|cfgs| {
1303                cfgs.iter()
1304                    .any(|cfg| cfg.as_str().is_some_and(|cfg| cfg.contains("feature")))
1305            })
1306        }) || configuration_names_a_feature(
1307            &copy,
1308            std::env::var_os("CARGO_HOME").map(PathBuf::from),
1309        );
1310        BuiltSources::from_artifacts(&build.artifacts, &build.features, !behind_cargo, &copy)
1311    } else {
1312        BuiltSources::default()
1313    };
1314    output_fixture::stage(&workspace, &work, &build_target, &options.output_fixtures)?;
1315    let checkpoint_path = report.analysis.checkpoint.as_deref();
1316    let checkpoint = checkpoint_path.map(Checkpoint::open).transpose()?;
1317    let doc_packages = test_packages
1318        .iter()
1319        .filter(|p| options.doc && p.targets.iter().any(|target| target.doctest));
1320    if build.test_binaries.is_empty() && doc_packages.clone().next().is_none() {
1321        bail!("{build_note}`{}` has no test binaries", package.name);
1322    }
1323
1324    // 5. Trace run: what does each test observe?
1325    let mut session = Session {
1326        progress: options.progress,
1327        serial_timeout_rechecks: options.serial_timeout_rechecks,
1328        package_dir,
1329        binaries: vec![],
1330    };
1331    let wrapper = selection
1332        .wrapper
1333        .as_ref()
1334        .map(|path| {
1335            let relative = wrapper_relative(path)?;
1336            let copied = copy.join(&relative);
1337            if !copied.is_file() {
1338                bail!(
1339                    "test wrapper is missing from the work copy: {}",
1340                    copied.display()
1341                );
1342            }
1343            Ok(copied)
1344        })
1345        .transpose()?;
1346    let mut runners: Vec<(String, Runner, PathBuf)> = vec![];
1347    let root_test_exe = |built: &BuildOutput| {
1348        built
1349            .test_binaries
1350            .iter()
1351            .find(|(name, _, owner, kind)| {
1352                *name == root_target.name && *owner == package.name && *kind == root_target.kind
1353            })
1354            .map(|(_, exe, _, _)| exe.clone())
1355    };
1356    let root_exe = (!witness_candidates.is_empty())
1357        .then(|| root_test_exe(&build))
1358        .flatten();
1359    let mut discovered_tests: Vec<String> = vec![];
1360    let mut empty_bin_targets: Vec<(String, String)> = vec![];
1361    if let Some(nextest) = &options.nextest {
1362        let mut flags: Vec<_> = test_packages
1363            .iter()
1364            .flat_map(|p| ["-p".to_owned(), p.name.clone()])
1365            .collect();
1366        flags.extend(options.cargo.flags());
1367        runners.push((
1368            "nextest".to_owned(),
1369            Runner::Nextest {
1370                copy: copy.clone(),
1371                target_dir: build_target.clone(),
1372                profile: nextest.profile.clone(),
1373                opt_level: options.opt_level,
1374                flags,
1375            },
1376            session.package_dir.clone(),
1377        ));
1378    } else {
1379        for (name, exe, owner, kind) in build.test_binaries {
1380            if !artifact_target_selected(&name, &kind, selection) {
1381                continue;
1382            }
1383            let owner_package = test_packages
1384                .iter()
1385                .find(|p| p.name == owner)
1386                .expect("binaries are filtered by these packages");
1387            let cwd = in_copy(
1388                owner_package
1389                    .manifest_path
1390                    .parent()
1391                    .expect("manifest has a parent"),
1392            )?;
1393            if selection.enabled() {
1394                let all = list_tests(&exe, &cwd, &work, false, true, work_lock.as_deref())?;
1395                if all.is_empty() && kind.first().map(String::as_str) == Some("bin") {
1396                    empty_bin_targets.push((owner.clone(), name.clone()));
1397                }
1398                let ignored = list_tests(&exe, &cwd, &work, true, true, work_lock.as_deref())?;
1399                for test in all {
1400                    let was_ignored = ignored.contains(&test);
1401                    if (!was_ignored || selection.include_ignored)
1402                        && !selection.exclude.iter().any(|name| name == &test)
1403                    {
1404                        discovered_tests.push(test.clone());
1405                    }
1406                    if !selection.matches_test(&test, was_ignored) {
1407                        continue;
1408                    }
1409                    runners.push((
1410                        format!("{owner}::{}::{name}::{test}", kind.join("+")),
1411                        Runner::Isolated {
1412                            exe: exe.clone(),
1413                            test,
1414                            ignored: was_ignored,
1415                            wrapper: wrapper.clone(),
1416                        },
1417                        cwd.clone(),
1418                    ));
1419                }
1420                continue;
1421            }
1422            // Tests of other packages are named after their package.
1423            let name = if owner == package.name {
1424                name
1425            } else {
1426                format!("{owner}::{name}")
1427            };
1428            runners.push((name, Runner::Exe(exe), cwd));
1429        }
1430    }
1431    if selection.enabled() && runners.is_empty() {
1432        let hint = no_tests_matched_hint(
1433            &test_packages,
1434            selection,
1435            &empty_bin_targets,
1436            &discovered_tests,
1437        );
1438        bail!("{build_note}no tests matched the requested selection{hint}");
1439    }
1440    let selected_tests = selection.enabled().then(|| report::TestSelection {
1441        build_scope,
1442        wrapper: selection
1443            .wrapper
1444            .as_ref()
1445            .map(|path| path.display().to_string()),
1446        tests: runners.iter().map(|(name, _, _)| name.clone()).collect(),
1447    });
1448    for owner in doc_packages {
1449        let doc = Runner::Doc {
1450            copy: copy.clone(),
1451            target_dir: build_target.clone(),
1452            package: owner.name.clone(),
1453            opt_level: options.opt_level,
1454            flags: options.cargo.flags(),
1455        };
1456        let name = if owner.name == package.name {
1457            "doc tests".to_owned()
1458        } else {
1459            format!("{}::doc tests", owner.name)
1460        };
1461        let cwd = in_copy(owner.manifest_path.parent().expect("manifest has a parent"))?;
1462        runners.push((name, doc, cwd));
1463    }
1464    report.analysis.test_selection = selected_tests;
1465    let identity = if checkpoint.is_some() {
1466        let mut build_inputs: Vec<_> = build
1467            .build_scripts
1468            .iter()
1469            .map(serde_json::Value::to_string)
1470            .collect();
1471        build_inputs.sort();
1472        // Build script outputs can contain secrets. Only their digest enters
1473        // the checkpoint, never the Cargo event payload.
1474        let settings = serde_json::json!({
1475            "build_scripts": build_inputs,
1476            "analysis": &report.analysis, "package": &package.name, "jobs": effective_jobs,
1477            "verify": options.verify, "audit": options.audit, "effects": options.effects,
1478            "all_files": options.all_files, "build_scope": build_scope,
1479            "runners": runners.iter().map(|(name, runner, cwd)| (name, runner.executable(), cwd)).collect::<Vec<_>>()
1480        });
1481        let mut inputs = BTreeSet::new();
1482        for (root, artifacts) in &build.artifacts {
1483            inputs.insert(root.clone());
1484            if let Some(dependencies) = artifacts
1485                .iter()
1486                .map(|artifact| artifact_inputs(artifact, root, &copy))
1487                .find(|deps| !deps.is_empty())
1488            {
1489                inputs.extend(dependencies);
1490            } else {
1491                // An unfamiliar Cargo output layout cannot hide changed
1492                // compilation inputs behind a stable artifact name.
1493                inputs.extend(artifacts.iter().cloned());
1494            }
1495        }
1496        inputs.extend(
1497            build
1498                .build_scripts
1499                .iter()
1500                .filter_map(|script| script.get("out_dir")?.as_str().map(PathBuf::from)),
1501        );
1502        // The snapshot is already included. The paths outside it include
1503        // dependency sources, generated build inputs, and staged fixtures.
1504        inputs.retain(|path| !path.starts_with(&copy));
1505        inputs.extend(
1506            options
1507                .output_fixtures
1508                .iter()
1509                .map(|fixture| build_target.join(&fixture.to)),
1510        );
1511        inputs.extend(
1512            options
1513                .stage_external
1514                .iter()
1515                .map(|entry| normalize(&copy.join(&entry.rel))),
1516        );
1517        Some(crate::campaign_identity::compute(
1518            &copy,
1519            &settings,
1520            inputs,
1521            options.nextest.is_some(),
1522        )?)
1523    } else {
1524        None
1525    };
1526    // The marks by which a run says that it gave up are made where nothing else makes
1527    // files: the working directory is this analysis's alone while it is locked. A
1528    // directory shared with others (the temporary one, between containers that count
1529    // their processes alike) could hand one run's mark to another.
1530    let marks = marks_dir(&work)?;
1531    let baseline_jobs = if selection.enabled() {
1532        options.baseline_jobs
1533    } else {
1534        1
1535    };
1536    if options.progress {
1537        eprintln!(
1538            "tmt: baselines: 0/{} completed ({} workers)",
1539            runners.len(),
1540            baseline_jobs
1541        );
1542    }
1543
1544    session.binaries = progress::track_baselines(options.progress, runners.len(), |progress| {
1545        run_pool(runners.len(), baseline_jobs, |slot| {
1546            let index = slot;
1547            let (name, runner, cwd) = runners[index].clone();
1548            let result = (|| {
1549                let trace_path = work.join(format!("trace-{index}.tsv"));
1550                let _ = fs::remove_file(&trace_path);
1551                let mut bin = TestBinary {
1552                    name,
1553                    cwd,
1554                    marks: marks.clone(),
1555                    git_ceiling: work.clone(),
1556                    work_lock: work_lock.clone(),
1557                    tests: BTreeSet::new(),
1558                    runner,
1559                    baseline: Duration::ZERO,
1560                    untraced_baseline: None,
1561                    timeout_diagnostic: std::sync::Once::new(),
1562                    traced: Duration::ZERO,
1563                    timeout: options.timeout_seconds.map(Duration::from_secs),
1564                    wrapper_grace: options.wrapper_grace,
1565                    report_slow: options.progress,
1566                    filtered_timings: Default::default(),
1567                    trace: Trace::default(),
1568                    effects_baseline: std::sync::OnceLock::new(),
1569                };
1570                session.note(&format!("tracing `{}`", bin.name));
1571                let started = Instant::now();
1572                let trace_env = trace_path.to_string_lossy().into_owned();
1573                let trace = [("TMT_TRACE", trace_env.as_str())];
1574                run_baseline(
1575                    &bin,
1576                    if options.source_only { &[] } else { &trace },
1577                    Duration::from_secs(3600),
1578                    &work.join(format!("baseline-{index}.log")),
1579                    false,
1580                )?;
1581                bin.traced = started.elapsed();
1582                bin.baseline = bin.traced;
1583                if options.source_only {
1584                    bin.untraced_baseline = Some(BaselineTiming::Completed(bin.baseline));
1585                }
1586                // Recording slows code in loops down a lot, and the time limit of every mutant
1587                // is a multiple of this: where it matters, time the tests as the mutants run them.
1588                if !options.source_only && bin.traced > SLOW_TRACE {
1589                    let started = Instant::now();
1590                    let passed = run_baseline(
1591                        &bin,
1592                        &[],
1593                        bin.traced,
1594                        &work.join(format!("baseline-{index}-untraced.log")),
1595                        true,
1596                    )?;
1597                    let elapsed = started.elapsed();
1598                    if passed {
1599                        bin.untraced_baseline = Some(BaselineTiming::Completed(elapsed));
1600                        bin.baseline = elapsed;
1601                    } else {
1602                        bin.untraced_baseline = Some(BaselineTiming::StillRunning(bin.traced));
1603                    }
1604                }
1605                // No file means no probe was reached. Anything else unreadable or malformed means
1606                // the evidence is incomplete, and conclusions drawn from it would be wrong.
1607                let text = match fs::read_to_string(&trace_path) {
1608                    Ok(text) => text,
1609                    Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
1610                    Err(err) => bail!("cannot read the trace of `{}`: {err}", bin.name),
1611                };
1612                bin.trace = Trace::parse(&text);
1613                if bin.trace.malformed_lines > 0 {
1614                    bail!(
1615                        "the trace of `{}` has {} malformed lines; not drawing conclusions from it",
1616                        bin.name,
1617                        bin.trace.malformed_lines
1618                    );
1619                }
1620                if let Runner::Exe(exe) = &bin.runner {
1621                    bin.tests =
1622                        list_tests(exe, &bin.cwd, &work, false, false, work_lock.as_deref())?;
1623                }
1624                Ok(bin)
1625            })();
1626            progress.complete(if result.is_ok() {
1627                progress::Outcome::Survived
1628            } else {
1629                progress::Outcome::Failed
1630            });
1631            result
1632        })
1633    })?;
1634
1635    // 6. Plan every site, run the mutants, and put the findings together.
1636    for file in &files {
1637        for site in &file.sites {
1638            if disabled.contains(&site.id) {
1639                let fallback = options.rebuild
1640                    && !matches!(site.kind, SiteKind::Body { .. })
1641                    && !instrument::source_mutants(site).is_empty();
1642                match site.kind {
1643                    SiteKind::Body { .. } => report.unviable_mutants += 1,
1644                    _ if fallback => {}
1645                    _ => report.skipped_sites += 1,
1646                }
1647                report.skipped.push(report::SkippedSite::new(
1648                    report::location(&file.display, site),
1649                    file.lines.position(&file.original, site.end),
1650                    if fallback {
1651                        report::SkipReason::ProbeReplacedBySourceRebuild
1652                    } else {
1653                        report::SkipReason::ProbeCompileError
1654                    },
1655                    repairs.get(&site.id).cloned(),
1656                ));
1657            }
1658        }
1659        if !options.rebuild && !options.source_only {
1660            report.skipped.extend(file.rebuild_sites.iter().map(|site| {
1661                report::SkippedSite::new(
1662                    report::location(&file.display, site),
1663                    file.lines.position(&file.original, site.end),
1664                    report::SkipReason::RequiresSourceRebuild,
1665                    None,
1666                )
1667            }));
1668        }
1669    }
1670    if let (Some(checkpoint), Some(identity)) = (&checkpoint, &identity) {
1671        checkpoint.start(
1672            identity,
1673            serde_json::json!({
1674                "package": &package.name, "analysis": &report.analysis,
1675                "runners": session.binaries.iter().map(|bin| &bin.name).collect::<Vec<_>>(),
1676                "jobs": effective_jobs, "tool_version": env!("CARGO_PKG_VERSION")
1677            }),
1678        )?;
1679    }
1680    let phase = |name: &str, keys: Vec<String>| {
1681        checkpoint
1682            .as_ref()
1683            .zip(identity.as_deref())
1684            .map(|(checkpoint, identity)| checkpoint.begin(name, identity, keys))
1685            .transpose()
1686    };
1687    let probe_phase = |name: &str, jobs: &[Job]| -> Result<Option<Phase<'_>>> {
1688        if checkpoint.is_none() {
1689            return Ok(None);
1690        }
1691        let locations: BTreeMap<_, _> = files
1692            .iter()
1693            .flat_map(|file| {
1694                file.sites
1695                    .iter()
1696                    .map(|site| (site.id, (&file.display, site.line, site.column, &site.text)))
1697            })
1698            .collect();
1699        let keys = jobs
1700            .iter()
1701            .map(|job| {
1702                let tests = job
1703                    .tests
1704                    .iter()
1705                    .map(|(bin, selected)| (&session.binaries[*bin].name, selected))
1706                    .collect::<Vec<_>>();
1707                serde_json::to_string(&(locations.get(&job.site), job.mutation.encode(), tests))
1708            })
1709            .collect::<std::result::Result<Vec<_>, _>>()?;
1710        phase(name, keys)
1711    };
1712    let scratch = work.clone();
1713    let mut jobs: Vec<Job> = vec![];
1714    // Sites whose mutant could not be run as a probe for what it is. With `--rebuild`
1715    // they are built from the source instead; without, they are counted.
1716    let mut not_evaluated: HashSet<u32> = HashSet::new();
1717    let mut site_work: Vec<SiteWork> = vec![];
1718    // `(index of the finding, job of its first surviving mutant)`.
1719    let mut effect_jobs: Vec<(usize, usize)> = vec![];
1720    for file in &files {
1721        // Pre-index active arithmetic and cast-probe spans once per file to avoid O(sites^2)
1722        // linear scans and repeated `syn::parse_str` during site planning.
1723        let mut primitive_arith_spans: HashSet<(usize, usize)> = HashSet::new();
1724        let mut cast_probe_spans: std::collections::HashMap<(usize, usize), (u32, u32)> =
1725            std::collections::HashMap::new();
1726        for other in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
1727            if let SiteKind::Arith { cast_probes, .. } = &other.kind {
1728                let seen = session.merged(|t| t.arith.get(&other.id), plan::ArithObs::merge);
1729                if !seen.opaque && (seen.same || seen.differs || seen.same2 || seen.differs2) {
1730                    primitive_arith_spans.insert((other.start, other.end));
1731                }
1732                for &(slot, start, end) in cast_probes {
1733                    cast_probe_spans
1734                        .entry((start, end))
1735                        .or_insert((other.id, slot));
1736                }
1737            }
1738        }
1739        let primitive = |from: usize, to: usize| {
1740            let Some(mut text) = file.original.get(from..to) else {
1741                return false;
1742            };
1743            let mut start = from;
1744            loop {
1745                let trimmed = text.trim_start();
1746                start += text.len() - trimmed.len();
1747                text = trimmed.trim_end();
1748                if text.starts_with('(')
1749                    && text.ends_with(')')
1750                    && matches!(syn::parse_str::<syn::Expr>(text), Ok(syn::Expr::Paren(_)))
1751                    && let Some(inner) = text
1752                        .strip_prefix('(')
1753                        .and_then(|inner| inner.strip_suffix(')'))
1754                {
1755                    start += 1;
1756                    text = inner;
1757                } else {
1758                    break;
1759                }
1760            }
1761            primitive_arith_spans.contains(&(start, start + text.len()))
1762        };
1763        let cast_bounds = |from: usize, to: usize| -> Option<(i128, i128)> {
1764            let &(owner_id, slot) = cast_probe_spans.get(&(from, to))?;
1765            let mut recorded = session
1766                .binaries
1767                .iter()
1768                .filter_map(|b| b.trace.cast_bounds.get(&(owner_id, slot)));
1769            let first = recorded.next()?;
1770            if recorded.all(|other| other == first) {
1771                *first
1772            } else {
1773                None
1774            }
1775        };
1776        for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
1777            let plan = match session.plan(
1778                &file.display,
1779                site,
1780                options.verify,
1781                &primitive,
1782                &cast_bounds,
1783            ) {
1784                // Code that did not change is not said to be unreached here: that takes
1785                // a run of the whole.
1786                Planned::Unreached if beyond.contains(&site.id) => continue,
1787                Planned::Unreached => {
1788                    // A function is one place, however many sites it is.
1789                    let at = report::location(&file.display, site);
1790                    if report.unreached.last() != Some(&at) {
1791                        report.unreached.push(at);
1792                    }
1793                    continue;
1794                }
1795                Planned::Nothing => continue,
1796                Planned::NotEvaluated => {
1797                    not_evaluated.insert(site.id);
1798                    continue;
1799                }
1800                Planned::Plan(plan) => plan,
1801            };
1802            let mut add =
1803                |mutation: Mutation, tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>| {
1804                    jobs.push(session.job(site.id, mutation, tests_of));
1805                    jobs.len() - 1
1806                };
1807            let gaps = plan
1808                .gaps
1809                .into_iter()
1810                .map(
1811                    |PlannedGap {
1812                         finding,
1813                         survivors,
1814                         constant_expr,
1815                     }| {
1816                        // The trace says no test can notice. Confirm by running every test
1817                        // that reaches the site against the listed survivors.
1818                        let confirm = if options.verify {
1819                            survivors
1820                                .into_iter()
1821                                .map(|m| add(m, &*plan.reaching))
1822                                .collect()
1823                        } else {
1824                            vec![]
1825                        };
1826                        (finding, confirm, constant_expr)
1827                    },
1828                )
1829                .collect();
1830            let infected = &plan.infected;
1831            let runs = plan
1832                .run
1833                .iter()
1834                .map(|m| (*m, add(*m, &|bin| infected(bin, *m))))
1835                .collect();
1836            site_work.push(SiteWork {
1837                file: &file.display,
1838                site,
1839                gaps,
1840                constant: plan.constant,
1841                cannot_differ: plan.cannot_differ,
1842                redundant_logic_swap: plan.redundant_logic_swap,
1843                runs,
1844            });
1845        }
1846    }
1847    session.note(&format!(
1848        "running {} mutants on {} thread(s)",
1849        jobs.len(),
1850        options.jobs.max(1)
1851    ));
1852    let probe_checkpoint = probe_phase("probe", &jobs)?;
1853    let mut results =
1854        session.run_jobs(&jobs, options.jobs, "mutants", probe_checkpoint.as_ref())?;
1855    for result in &results {
1856        report.timeout_rechecks.include(result);
1857    }
1858
1859    // 6b. On request, check what the run rests on: that the tests chosen for a mutant
1860    // are the ones that could fail with it, and that the tests do the same twice.
1861    if let Some(wanted) = options.audit {
1862        report.audit = Some(run_audit_phase(
1863            &session,
1864            &files,
1865            &jobs,
1866            &mut results,
1867            &mut report.timeout_rechecks,
1868            &scratch,
1869            wanted,
1870            options.jobs,
1871            &probe_phase,
1872        )?);
1873    }
1874    // 6c. In code that did not change, a mutant that passes says something about this
1875    // change only if the tests as they were found it out. They are built once, with
1876    // the program as it is, and run against those mutants.
1877    #[derive(Clone, Copy, PartialEq, Eq)]
1878    enum EarlierVerdict {
1879        Killed,
1880        Survived,
1881        Unknown,
1882    }
1883    let mut earlier_verdict: BTreeMap<usize, EarlierVerdict> = BTreeMap::new();
1884    let asked: Vec<usize> = site_work
1885        .iter()
1886        .filter(|item| beyond.contains(&item.site.id))
1887        .flat_map(|item| {
1888            item.gaps
1889                .iter()
1890                .flat_map(|(_, confirm, _)| confirm.iter().copied())
1891                .chain(
1892                    item.runs
1893                        .iter()
1894                        .filter(|(m, _)| !(*m == Mutation::LogicSwap && item.redundant_logic_swap))
1895                        .map(|(_, job)| *job),
1896                )
1897        })
1898        .filter(|job| results[*job].survived.is_some())
1899        .collect();
1900    if !asked.is_empty() {
1901        let revision = report::short_revision(options.since.as_deref().unwrap_or_default());
1902        session.note(&format!(
1903            "running {} surviving mutants against the tests as they were at {revision}",
1904            asked.len()
1905        ));
1906        let suffix = |file: &SourceFile| {
1907            if file.path == root_file {
1908                root_suffix.as_str()
1909            } else {
1910                ""
1911            }
1912        };
1913        // The instrumented files with the old lines of their tests.
1914        let earlier: Option<Vec<(&SourceFile, String)>> = tests_changed
1915            .iter()
1916            .map(|(path, hunks)| {
1917                let file = files.iter().find(|file| file.path == *path)?;
1918                let rendered = file.rendered.as_ref()?;
1919                let mut places = hunks
1920                    .iter()
1921                    .map(|hunk| {
1922                        let (from, to) = scope::range_of(&file.original, hunk);
1923                        Some((rendered.copied(from, to)?, hunk.old.as_str()))
1924                    })
1925                    .collect::<Option<Vec<_>>>()?;
1926                places.sort_by_key(|((from, _), _)| std::cmp::Reverse(*from));
1927                let mut text = rendered.text.clone();
1928                for ((from, to), old) in places {
1929                    text.replace_range(from..to, old);
1930                }
1931                Some((file, text))
1932            })
1933            .collect();
1934        let attempted = if let Some(earlier) = earlier {
1935            let attempted = (|| -> Result<Option<Vec<JobResult>>> {
1936                for (file, text) in &earlier {
1937                    state.write(&file.path, &format!("{text}{}", suffix(file)))?;
1938                }
1939                if !cargo_build()?.status.success() {
1940                    session.note(
1941                        "the tests as they were do not build with the code as it is: what they found out is not known",
1942                    );
1943                    return Ok(None);
1944                }
1945                // They have to pass as they are, or a failure says nothing of a mutant.
1946                let all: Vec<&TestBinary> = session.binaries.iter().collect();
1947                if run_source_tests(&all)? != Outcome::Pass {
1948                    session.note(
1949                        "the tests as they were fail on the code as it is: what they found out is not known",
1950                    );
1951                    return Ok(None);
1952                }
1953                let against_all: Vec<Job> = asked
1954                    .iter()
1955                    .map(|job| Job {
1956                        site: jobs[*job].site,
1957                        mutation: jobs[*job].mutation,
1958                        tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
1959                    })
1960                    .collect();
1961                session
1962                    .run_jobs(&against_all, options.jobs, "mutants, earlier tests", None)
1963                    .map(Some)
1964            })();
1965            // The files and the binaries as they were, whatever went wrong.
1966            for (file, _) in &earlier {
1967                let rendered = file.rendered.as_ref().expect("rendered before building");
1968                state.write(&file.path, &format!("{}{}", rendered.text, suffix(file)))?;
1969            }
1970            if !cargo_build()?.status.success() {
1971                bail!("the crate does not build once its tests are put back as they are");
1972            }
1973            attempted
1974        } else {
1975            session.note(
1976                "not all changed test files could be restored as they were: what they found out is not known",
1977            );
1978            Ok(None)
1979        };
1980        if let Some(again) = attempted? {
1981            for (job, result) in asked.iter().zip(again) {
1982                let verdict = if result.unable || result.unconfirmed_timeout {
1983                    EarlierVerdict::Unknown
1984                } else if result.survived.is_none() {
1985                    EarlierVerdict::Killed
1986                } else {
1987                    EarlierVerdict::Survived
1988                };
1989                earlier_verdict.insert(*job, verdict);
1990            }
1991        } else {
1992            for job in &asked {
1993                earlier_verdict.insert(*job, EarlierVerdict::Unknown);
1994            }
1995        }
1996    }
1997    let unable = results
1998        .iter()
1999        .filter(|r| r.unable || r.unconfirmed_timeout)
2000        .count();
2001    not_evaluated.extend(
2002        jobs.iter()
2003            .zip(&results)
2004            .filter(|(_, result)| result.unable || result.unconfirmed_timeout)
2005            .map(|(job, _)| job.site),
2006    );
2007    if !options.rebuild {
2008        report.mutants_not_evaluated = not_evaluated.len();
2009    }
2010    report.mutants_run = results.len() - unable;
2011    report.mutants_killed = results.iter().filter(|r| r.survived.is_none()).count() - unable;
2012    report.mutants_survived = report.mutants_run - report.mutants_killed;
2013    report.mutants_timed_out = results
2014        .iter()
2015        .filter(|r| r.timed_out && !r.unconfirmed_timeout)
2016        .count();
2017
2018    // Parallel to `report.findings`: how many executed surviving mutants each finding
2019    // represents (`0` for unverified predicted input gaps under `--no-verify`).
2020    let mut finding_run_survivors: Vec<usize> = vec![];
2021
2022    // Expressions known to be constant in the tests: comparisons with a confirmed
2023    // one-sided gap or that cannot differ at all, and `&&` / `||` with a single value.
2024    let confirmed = |w: &SiteWork| {
2025        w.gaps
2026            .iter()
2027            .all(|(_, confirm, _)| confirm.iter().all(|j| results[*j].survived.is_some()))
2028    };
2029    let constants: BTreeSet<(&str, usize, usize)> = site_work
2030        .iter()
2031        .filter(|w| w.cannot_differ || (w.constant && confirmed(w)))
2032        .map(|w| (w.file, w.site.start, w.site.end))
2033        .collect();
2034    for item in &site_work {
2035        let at = report::location(item.file, item.site);
2036        for (finding, confirm, constant_expr) in &item.gaps {
2037            // Already said by the site of the expression itself (or, for a comparison that
2038            // cannot differ, not worth saying at all).
2039            let repeats = constant_expr
2040                .is_some_and(|(start, end)| constants.contains(&(item.file, start, end)));
2041            let survived_count = confirm
2042                .iter()
2043                .filter(|j| results[**j].survived.is_some())
2044                .count();
2045            if beyond.contains(&item.site.id) {
2046                // Said only when the tests found it out before their change.
2047                let confirmed = confirm.iter().all(|j| results[*j].survived.is_some());
2048                let killed_before = confirm
2049                    .iter()
2050                    .any(|j| earlier_verdict.get(j) == Some(&EarlierVerdict::Killed));
2051                if confirmed && !repeats && killed_before {
2052                    report.weakened.push(finding.at().clone());
2053                    report.findings.push(finding.clone());
2054                    finding_run_survivors.push(survived_count);
2055                } else if !confirmed {
2056                    report.survivor_breakdown.unconfirmed_gap += survived_count;
2057                } else if repeats {
2058                    report.survivor_breakdown.redundant_constant += survived_count;
2059                } else {
2060                    for job in confirm {
2061                        if results[*job].survived.is_some() {
2062                            if earlier_verdict.get(job) == Some(&EarlierVerdict::Survived) {
2063                                report.survivor_breakdown.preexisting_unchanged += 1;
2064                            } else {
2065                                report.survivor_breakdown.unchanged_not_compared += 1;
2066                            }
2067                        }
2068                    }
2069                }
2070                continue;
2071            }
2072            match Prediction::of(confirm.iter().map(|j| &results[*j])) {
2073                Prediction::Refuted => {
2074                    report.unstable.push(at.clone());
2075                    report.survivor_breakdown.unconfirmed_gap += survived_count;
2076                }
2077                Prediction::Confirmed if !repeats => {
2078                    report.findings.push(finding.clone());
2079                    finding_run_survivors.push(survived_count);
2080                }
2081                Prediction::Confirmed => {
2082                    report.survivor_breakdown.redundant_constant += survived_count;
2083                }
2084                // Not evaluated (counted above), or said elsewhere.
2085                Prediction::Unknown => {
2086                    report.survivor_breakdown.unconfirmed_gap += survived_count;
2087                }
2088            }
2089        }
2090        // A body that is one expression, constant in the tests: replacing the body by
2091        // that constant was said at the expression (or cannot be told apart at all).
2092        if let SiteKind::Body {
2093            sole_expr: Some((start, end)),
2094            ..
2095        } = item.site.kind
2096            && constants.contains(&(item.file, start, end))
2097        {
2098            report.survivor_breakdown.redundant_constant += item
2099                .runs
2100                .iter()
2101                .filter(|(_, job)| results[*job].survived.is_some())
2102                .count();
2103            continue;
2104        }
2105        let mut survivors = vec![];
2106        let mut passing_tests = BTreeSet::new();
2107        for (mutation, job) in &item.runs {
2108            if let Some(tests) = &results[*job].survived {
2109                if *mutation == Mutation::LogicSwap && item.redundant_logic_swap {
2110                    report.survivor_breakdown.redundant_constant += 1;
2111                    continue;
2112                }
2113                if beyond.contains(&item.site.id) {
2114                    match earlier_verdict.get(job) {
2115                        Some(EarlierVerdict::Killed) => {}
2116                        Some(EarlierVerdict::Survived) => {
2117                            report.survivor_breakdown.preexisting_unchanged += 1;
2118                            continue;
2119                        }
2120                        Some(EarlierVerdict::Unknown) | None => {
2121                            report.survivor_breakdown.unchanged_not_compared += 1;
2122                            continue;
2123                        }
2124                    }
2125                }
2126                survivors.push(report::describe(item.site, *mutation));
2127                passing_tests.extend(tests.iter().cloned());
2128            }
2129        }
2130        if !survivors.is_empty() {
2131            // The first survivor is traced below to see what it changes.
2132            let first = item.runs.iter().find(|(mutation, job)| {
2133                !(*mutation == Mutation::LogicSwap && item.redundant_logic_swap)
2134                    && results[*job].survived.is_some()
2135                    && (!beyond.contains(&item.site.id)
2136                        || earlier_verdict.get(job) == Some(&EarlierVerdict::Killed))
2137            });
2138            if beyond.contains(&item.site.id) {
2139                report.weakened.push(at.clone());
2140            }
2141            effect_jobs.push((report.findings.len(), first.expect("a survivor").1));
2142            finding_run_survivors.push(survivors.len());
2143            report.findings.push(Finding::AssertionGap {
2144                at,
2145                survivors,
2146                tests: passing_tests.into_iter().collect(),
2147                effects: vec![],
2148                effects_of: None,
2149                witness: None,
2150            });
2151        }
2152    }
2153
2154    // 7. What do the surviving mutants change in the tests that let them through?
2155    if options.effects && !effect_jobs.is_empty() {
2156        run_effects_phase(
2157            &session,
2158            &files,
2159            &jobs,
2160            &effect_jobs,
2161            &scratch,
2162            options.jobs,
2163            &mut report.findings,
2164        )?;
2165    }
2166
2167    // 7b. What a probe cannot be put in is mutated in the source, built and run: code in
2168    // a `const fn`, and the sites whose probe did not compile.
2169    // The last of the four: for an audit, the job that ran the same mutant as a probe.
2170    let mut built: Vec<(&SourceFile, &Site, instrument::SourceMutant, Option<usize>)> = vec![];
2171    let build_regular_mutants = options.rebuild || options.source_only;
2172    let mut index = 0;
2173    for file in &files {
2174        // Tried again as the source says them: what did not compile as a probe, and
2175        // what a probe could not be (a range that ends at the top of its type).
2176        let retried = file.sites.iter().filter(|site| {
2177            (disabled.contains(&site.id) && !matches!(site.kind, SiteKind::Body { .. }))
2178                || not_evaluated.contains(&site.id)
2179        });
2180        for site in file.rebuild_sites.iter().chain(retried) {
2181            let mutants = source_mutants(file, site, true);
2182            if build_regular_mutants {
2183                built.extend(mutants.into_iter().filter_map(|mutant| {
2184                    let selected = in_shard(index);
2185                    index += 1;
2186                    selected.then_some((file, site, mutant, None))
2187                }));
2188            } else {
2189                report.mutants_not_built += mutants.len();
2190            }
2191        }
2192    }
2193    // An audit also builds some of the mutants that were run as probes, from the source
2194    // as a person would write them, to see whether a probe and the real thing agree.
2195    if let (Some(wanted), Some(audit)) = (options.audit, report.audit.as_mut()) {
2196        let mut twins = vec![];
2197        for file in &files {
2198            for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
2199                // Only integers are known to always have an order.
2200                let integers = session.binaries.iter().all(|bin| {
2201                    let seen = bin.trace.merged(site.id);
2202                    !seen.reached() || seen.valued()
2203                });
2204                let candidates = jobs_for_site(&jobs, site.id);
2205                let job_of = |mutation: Mutation| {
2206                    candidates
2207                        .clone()
2208                        .find(|&index| jobs[index].mutation == mutation)
2209                };
2210                let mut compared = vec![];
2211                let mut mutants = instrument::source_mutants(site);
2212                instrument::keep_line_ends(&file.original, &mut mutants);
2213                for mutant in mutants {
2214                    // The first of the mutations that are this change and that was run.
2215                    let job = mutations_like(site, &mutant, integers)
2216                        .into_iter()
2217                        .find_map(job_of);
2218                    if let Some(job) = job {
2219                        compared.push(job);
2220                        twins.push((file, site, mutant, Some(job)));
2221                    }
2222                }
2223                // A negated comparison that no mutant of the source stands for (on
2224                // floats `<` is not "not `>=`") is compared with the negation written out.
2225                if let (SiteKind::Cmp { op, .. }, Some(job)) =
2226                    (&site.kind, job_of(Mutation::Negate))
2227                    && !compared.contains(&job)
2228                {
2229                    let negated = instrument::SourceMutant {
2230                        start: site.start,
2231                        end: site.end,
2232                        replacement: format!("!({})", site.text),
2233                        what: op.symbol().to_string(),
2234                        into: "!".to_string(),
2235                    };
2236                    twins.push((file, site, negated, Some(job)));
2237                }
2238            }
2239        }
2240        let chosen = spread(twins.len(), wanted);
2241        audit.rebuilt = chosen.len();
2242        let mut twins: Vec<Option<_>> = twins.into_iter().map(Some).collect();
2243        built.extend(chosen.into_iter().filter_map(|nth| twins[nth].take()));
2244    }
2245    let mut by_speed: Vec<&TestBinary> = session.binaries.iter().collect();
2246    by_speed.sort_by_key(|bin| bin.baseline);
2247    // A root replacement removes all of its probes. Other files may still use the runtime.
2248    let root_mutant_suffix = if files.iter().any(|file| {
2249        file.path != root_file
2250            && file
2251                .rendered
2252                .as_ref()
2253                .is_some_and(|rendered| rendered.text != file.original)
2254    }) {
2255        root_suffix.as_str()
2256    } else {
2257        ""
2258    };
2259    if !built.is_empty() {
2260        if options.timeout_seconds.is_some()
2261            && built
2262                .iter()
2263                .any(|(file, _, _, _)| built_sources.contains(file))
2264        {
2265            for bin in &by_speed {
2266                bin.warn_timeout_conflict(None);
2267            }
2268        }
2269        let source_checkpoint = if checkpoint.is_some() {
2270            let keys = built
2271                .iter()
2272                .map(|(file, _, mutation, twin)| {
2273                    serde_json::to_string(&(
2274                        &file.display,
2275                        mutation.start,
2276                        mutation.end,
2277                        &mutation.replacement,
2278                        twin,
2279                    ))
2280                })
2281                .collect::<std::result::Result<Vec<_>, _>>()?;
2282            phase("source", keys)?
2283        } else {
2284            None
2285        };
2286        session.note(&format!(
2287            "building {} mutants one by one (code a probe cannot be put in, or to compare with the probe)",
2288            built.len()
2289        ));
2290        let instrumented = |file: &SourceFile, text: &str, suffix: &str| {
2291            if file.path == root_file {
2292                format!("{text}{suffix}")
2293            } else {
2294                text.to_string()
2295            }
2296        };
2297        // All tests are run against each of them; the quick ones first, since one
2298        // failure is enough.
2299        let mut skipped_targets = BTreeSet::new();
2300        // Per file, the code its builds leave out.
2301        let mut left_out: BTreeMap<&PathBuf, Vec<(usize, usize)>> = BTreeMap::new();
2302        let mut survivors: Vec<(report::Location, Vec<String>)> = vec![];
2303        progress::track(
2304            options.progress,
2305            "source mutants",
2306            built.len(),
2307            |progress| -> Result<()> {
2308                for (index, (file, site, mutant, twin)) in built.iter().enumerate() {
2309                    let cached = source_checkpoint
2310                        .as_ref()
2311                        .map(|phase| phase.get::<Option<Outcome>>(index))
2312                        .transpose()?
2313                        .flatten();
2314                    let left_out = left_out
2315                        .entry(&file.path)
2316                        .or_insert_with(|| built_sources.left_out(file))
2317                        .iter()
2318                        .any(|(from, to)| *from <= site.start && site.end <= *to);
2319                    if left_out || !built_sources.contains(file) {
2320                        if let Some(phase) = source_checkpoint.as_ref().filter(|_| cached.is_none())
2321                        {
2322                            phase.record(index, &Some(Outcome::Unable))?;
2323                        }
2324                        if twin.is_none() {
2325                            report.mutants_not_evaluated += 1;
2326                            report.mutants_not_compiled += 1;
2327                            if skipped_targets.insert((&file.path, site.start, site.end)) {
2328                                report.skipped.push(report::SkippedSite::new(
2329                                    report::location(&file.display, site),
2330                                    file.lines.position(&file.original, site.end),
2331                                    report::SkipReason::SourceNotBuilt,
2332                                    left_out.then(|| {
2333                                        "under a `cfg` that the features of this build turn off"
2334                                            .to_string()
2335                                    }),
2336                                ));
2337                            }
2338                        } else if let Some(audit) = report.audit.as_mut() {
2339                            audit.not_compared += 1;
2340                        }
2341                        progress.complete(progress::Outcome::Unable);
2342                        continue;
2343                    }
2344                    let outcome = if let Some(cached) = cached {
2345                        cached
2346                    } else {
2347                        let mutated = format!(
2348                            "{}{}{}",
2349                            &file.original[..mutant.start],
2350                            mutant.replacement,
2351                            &file.original[mutant.end..]
2352                        );
2353                        // `None`: it does not build. Otherwise what stopped it, if anything did.
2354                        let attempt = || -> Result<Option<Outcome>> {
2355                            state.write(
2356                                &file.path,
2357                                &instrumented(file, &mutated, root_mutant_suffix),
2358                            )?;
2359                            match source_build(&cargo_build()?) {
2360                                SourceBuild::Built => run_source_tests(&by_speed).map(Some),
2361                                SourceBuild::Refused => Ok(None),
2362                                // Nothing is known of the mutant: not one that does not
2363                                // compile, and not one to remember as such.
2364                                SourceBuild::Failed(why) => {
2365                                    session.note(&format!(
2366                                        "a build failed without the compiler refusing the code; its mutant is not evaluated: {why}"
2367                                    ));
2368                                    Ok(Some(Outcome::Unable))
2369                                }
2370                            }
2371                        };
2372                        let attempted = attempt();
2373                        // The file as it was, before another one is changed and whatever went wrong.
2374                        let rendered = file.rendered.as_ref().expect("rendered before building");
2375                        state.write(
2376                            &file.path,
2377                            &instrumented(file, &rendered.text, &root_suffix),
2378                        )?;
2379                        let outcome = attempted?;
2380                        // A run that could not be judged is tried again when the campaign
2381                        // is taken up: only what was established is kept.
2382                        if let Some(phase) = &source_checkpoint
2383                            && outcome != Some(Outcome::Unable)
2384                        {
2385                            phase.record(index, &outcome)?;
2386                        }
2387                        outcome
2388                    };
2389                    progress.complete(outcome.map_or(progress::Outcome::Unable, Into::into));
2390                    if let Some(job) = twin {
2391                        // Only compared: the probe's run is the one that is counted and reported.
2392                        let as_probe = results[*job].survived.is_some();
2393                        let Some(audit) = report.audit.as_mut() else {
2394                            continue;
2395                        };
2396                        // What does not build, what could not be evaluated, and an unconfirmed
2397                        // parallel timeout say nothing about agreement between probe and source.
2398                        match audit_source_comparison(&results[*job], outcome) {
2399                            Some(disagrees) => {
2400                                audit.compared += 1;
2401                                if disagrees {
2402                                    let verdict =
2403                                        |passes: bool| if passes { "passes" } else { "fails" };
2404                                    audit.source_disagreements.push(report::SourceDisagreement {
2405                                        at: report::location(&file.display, site),
2406                                        mutant: report::describe(site, mutation_of(site, mutant)),
2407                                        as_probe: verdict(as_probe).to_string(),
2408                                        built: verdict(!as_probe).to_string(),
2409                                    });
2410                                }
2411                            }
2412                            None => audit.not_compared += 1,
2413                        }
2414                        continue;
2415                    }
2416                    match outcome {
2417                        None => report.unviable_mutants += 1,
2418                        Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
2419                        Some(outcome) => {
2420                            report.mutants_run += 1;
2421                            report.mutants_killed += (outcome != Outcome::Pass) as usize;
2422                            report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
2423                            report.mutants_survived += (outcome == Outcome::Pass) as usize;
2424                        }
2425                    }
2426                    let survived = outcome == Some(Outcome::Pass);
2427                    if survived {
2428                        let at = report::location(&file.display, site);
2429                        // Nothing but the line ends of what was there.
2430                        let removed = mutant.replacement.trim().is_empty();
2431                        let text = match (&site.kind, removed) {
2432                            (SiteKind::Field { .. }, true) => {
2433                                format!("without the field `{}`", report::one_line(&site.text))
2434                            }
2435                            (
2436                                SiteKind::LiteralSet {
2437                                    receiver, argument, ..
2438                                },
2439                                true,
2440                            ) => format!(
2441                                "without `{}` in `{}.contains({})`",
2442                                report::one_line(&mutant.into),
2443                                report::one_line(receiver),
2444                                report::one_line(argument)
2445                            ),
2446                            _ => report::describe(site, mutation_of(site, mutant)),
2447                        };
2448                        match survivors.last_mut() {
2449                            Some((last, texts)) if *last == at => texts.push(text),
2450                            _ => survivors.push((at, vec![text])),
2451                        }
2452                    }
2453                }
2454                Ok(())
2455            },
2456        )?;
2457        if let Some(phase) = &source_checkpoint {
2458            phase.finish_if_complete()?;
2459        }
2460        for (at, survivors) in survivors {
2461            finding_run_survivors.push(survivors.len());
2462            report.findings.push(Finding::Survivor {
2463                at,
2464                survivors,
2465                witness: None,
2466                change_since: None,
2467                advice: None,
2468            });
2469        }
2470    }
2471
2472    // Each change since the revision, undone: do the tests tell it from what was there?
2473    if let Some(revision) = options
2474        .since
2475        .as_deref()
2476        .filter(|_| !options.list && options.shard.is_none())
2477    {
2478        let hunks = scope::hunks(&since_diff(&workspace, revision)?);
2479        let not_built_changes = std::cell::Cell::new(0usize);
2480        let changed: Vec<(&SourceFile, Vec<reverts::Change>)> = files
2481            .iter()
2482            .filter(|file| built_sources.contains(file) || !options.source_only && !options.rebuild)
2483            .filter_map(|file| {
2484                let relative = file
2485                    .path
2486                    .strip_prefix(&copy)
2487                    .ok()?
2488                    .to_string_lossy()
2489                    .replace('\\', "/");
2490                let of_file: Vec<_> = hunks
2491                    .iter()
2492                    .filter(|hunk| hunk.file == relative)
2493                    .cloned()
2494                    .collect();
2495                let mut changes = reverts::changes(&file.original, &of_file);
2496                // Code this build leaves out (a feature that is off) is the same
2497                // program with its change undone: nothing to try.
2498                if options.rebuild || options.source_only {
2499                    for change in &mut changes {
2500                        // The same program undone, in every build: a `cfg` that
2501                        // changed may turn code on or off.
2502                        change.outside = change.undone.as_deref().is_some_and(|undone| {
2503                            built_sources.same_program(file, &file.original, undone)
2504                        });
2505                    }
2506                    not_built_changes.set(
2507                        not_built_changes.get()
2508                            + changes.iter().filter(|change| change.outside).count(),
2509                    );
2510                }
2511                (!changes.is_empty()).then_some((file, changes))
2512            })
2513            .collect();
2514        let not_built_changes = not_built_changes.get();
2515        report.mutants_not_evaluated += not_built_changes;
2516        report.mutants_not_compiled += not_built_changes;
2517        // Those are not tried alone, and still go back with the others.
2518        let total: usize = changed
2519            .iter()
2520            .map(|(_, changes)| changes.iter().filter(|change| !change.outside).count())
2521            .sum();
2522        // A change of the program and its tests in lines that cannot be told apart
2523        // would be undone with the tests: nothing is said of it.
2524        let mixed: usize = files
2525            .iter()
2526            .map(|file| {
2527                let relative = file
2528                    .path
2529                    .strip_prefix(&copy)
2530                    .unwrap_or(&file.path)
2531                    .to_string_lossy()
2532                    .replace('\\', "/");
2533                let of_file: Vec<_> = hunks
2534                    .iter()
2535                    .filter(|hunk| hunk.file == relative)
2536                    .cloned()
2537                    .collect();
2538                reverts::mixed(&file.original, &of_file)
2539            })
2540            .sum();
2541        if mixed > 0 && (options.rebuild || options.source_only) {
2542            report.mutants_not_evaluated += mixed;
2543            session.note(&format!(
2544                "{mixed} changes are of the program and its tests in the same lines: they are not tried undone"
2545            ));
2546        }
2547        if !(options.rebuild || options.source_only) {
2548            report.mutants_not_built += not_built_reverts;
2549        } else if total > 0
2550            || changed.iter().any(|(_, changes)| {
2551                changes.iter().filter(|change| !change.is_subhunk()).count() > 1
2552            })
2553        {
2554            // Also with nothing to try alone: several changes of code that is left out
2555            // may be a change of the build together.
2556            session.note(&format!(
2557                "building {total} changes undone, one by one (the code as it was at {})",
2558                report::short_revision(revision)
2559            ));
2560            let write = |file: &SourceFile, text: &str, suffix: &str| -> Result<()> {
2561                let suffix = if file.path == root_file { suffix } else { "" };
2562                state.write(&file.path, &format!("{text}{suffix}"))
2563            };
2564            // `None`: it does not build.
2565            let undone = |edits: &[(&SourceFile, &str)]| -> Result<Option<Outcome>> {
2566                let attempted = (|| -> Result<Option<Outcome>> {
2567                    for (file, text) in edits {
2568                        write(file, text, root_mutant_suffix)?;
2569                    }
2570                    Ok(match source_build(&cargo_build()?) {
2571                        SourceBuild::Built => Some(run_source_tests(&by_speed)?),
2572                        SourceBuild::Refused => None,
2573                        SourceBuild::Failed(why) => {
2574                            session.note(&format!(
2575                                "a build failed without the compiler refusing the code; the change undone is not evaluated: {why}"
2576                            ));
2577                            Some(Outcome::Unable)
2578                        }
2579                    })
2580                })();
2581                // The files as they were, whatever went wrong.
2582                for (file, _) in edits {
2583                    let rendered = file.rendered.as_ref().expect("rendered before building");
2584                    write(file, &rendered.text, &root_suffix)?;
2585                }
2586                attempted
2587            };
2588            let mut judged = |outcome: Option<Outcome>, at: report::Location, what: String| {
2589                match outcome {
2590                    None => report.unviable_mutants += 1,
2591                    Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
2592                    Some(outcome) => {
2593                        report.mutants_run += 1;
2594                        report.mutants_killed += (outcome != Outcome::Pass) as usize;
2595                        report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
2596                        report.mutants_survived += (outcome == Outcome::Pass) as usize;
2597                    }
2598                }
2599                if outcome == Some(Outcome::Pass) {
2600                    finding_run_survivors.push(1);
2601                    report.findings.push(Finding::Survivor {
2602                        at,
2603                        survivors: vec![what],
2604                        witness: None,
2605                        advice: None,
2606                        change_since: Some(revision.to_string()),
2607                    });
2608                }
2609            };
2610            let place = |file: &SourceFile, change: &reverts::Change| report::Location {
2611                file: file.display.clone(),
2612                line: change.line,
2613                column: 1,
2614                code: change.code.clone(),
2615                ..Default::default()
2616            };
2617            // A change that does not build alone may be one part of several that belong
2618            // together: then all of the file's are undone at once, and at last all of all.
2619            let mut stuck_files = 0;
2620            for (file, changes) in &changed {
2621                let mut stuck = false;
2622                let whole_total = changes.iter().filter(|change| !change.is_subhunk()).count();
2623                let whole_alone = changes
2624                    .iter()
2625                    .filter(|change| !change.is_subhunk() && !change.outside)
2626                    .count();
2627                for change in changes.iter().filter(|change| !change.outside) {
2628                    let outcome = match &change.undone {
2629                        Some(text) => undone(&[(file, text.as_str())])?,
2630                        None => None,
2631                    };
2632                    if !change.is_subhunk() {
2633                        stuck |= outcome.is_none();
2634                    }
2635                    judged(outcome, place(file, change), change.describe());
2636                }
2637                // All together: where one does not build alone, and where what is left
2638                // out now is built once the others are undone (a `cfg` that changed
2639                // along with the code under it), which shows as another program with
2640                // those changes undone too than without them.
2641                let whole = reverts::all_undone(&file.original, changes);
2642                let same = |a: &str, b: &str| built_sources.same_program(file, a, b);
2643                let tried: Vec<reverts::Change> = changes
2644                    .iter()
2645                    .filter(|change| !change.outside)
2646                    .cloned()
2647                    .collect();
2648                let left_out_matter = whole_alone < whole_total
2649                    && match (&whole, reverts::all_undone(&file.original, &tried)) {
2650                        (Some(all), Some(without)) => !same(all, &without),
2651                        _ => true,
2652                    };
2653                // And never a program that is the one that is there.
2654                let another = whole
2655                    .as_deref()
2656                    .is_none_or(|all| !same(all, &file.original));
2657                if whole_total > 1 && another && (stuck || left_out_matter) {
2658                    let outcome = match &whole {
2659                        Some(text) => undone(&[(file, text.as_str())])?,
2660                        None => None,
2661                    };
2662                    stuck = outcome.is_none();
2663                    let first_whole = changes
2664                        .iter()
2665                        .find(|change| !change.is_subhunk())
2666                        .unwrap_or(&changes[0]);
2667                    judged(
2668                        outcome,
2669                        place(file, first_whole),
2670                        format!("with all {whole_total} changes to this file undone"),
2671                    );
2672                }
2673                stuck_files += usize::from(stuck);
2674            }
2675            // All files together: where a file's changes do not build even together,
2676            // and where code that is left out changed, which may count only with the
2677            // changes of another file undone.
2678            let with_left_out = changed.iter().any(|(_, changes)| {
2679                changes
2680                    .iter()
2681                    .any(|change| !change.is_subhunk() && change.outside)
2682            });
2683            if (stuck_files > 0 || with_left_out) && changed.len() > 1 {
2684                let whole: Option<Vec<String>> = changed
2685                    .iter()
2686                    .map(|(file, changes)| reverts::all_undone(&file.original, changes))
2687                    .collect();
2688                let same =
2689                    |file: &SourceFile, a: &str, b: &str| built_sources.same_program(file, a, b);
2690                // Never the program that is there: in some file it has to be another.
2691                let another = whole.as_ref().is_none_or(|texts| {
2692                    changed
2693                        .iter()
2694                        .zip(texts)
2695                        .any(|((file, _), text)| !same(file, text, &file.original))
2696                });
2697                // And what is left out has to count: another program with it undone
2698                // too than with the other changes alone.
2699                let left_out_matter = whole.as_ref().is_none_or(|texts| {
2700                    changed.iter().zip(texts).any(|((file, changes), text)| {
2701                        let tried: Vec<reverts::Change> = changes
2702                            .iter()
2703                            .filter(|change| !change.outside)
2704                            .cloned()
2705                            .collect();
2706                        reverts::all_undone(&file.original, &tried)
2707                            .is_none_or(|without| !same(file, text, &without))
2708                    })
2709                });
2710                if another && (stuck_files > 0 || (with_left_out && left_out_matter)) {
2711                    let outcome = match &whole {
2712                        Some(texts) => {
2713                            let edits: Vec<(&SourceFile, &str)> = changed
2714                                .iter()
2715                                .zip(texts)
2716                                .map(|((file, _), text)| (*file, text.as_str()))
2717                                .collect();
2718                            undone(&edits)?
2719                        }
2720                        None => None,
2721                    };
2722                    let (file, changes) = &changed[0];
2723                    judged(
2724                        outcome,
2725                        place(file, &changes[0]),
2726                        format!("with every change undone, in all {} files", changed.len()),
2727                    );
2728                }
2729            }
2730        }
2731    }
2732
2733    // File by file: the test that shows a difference is put at the end of the file the
2734    // candidate is of, where the names of the file are in scope.
2735    let mut witness_files: Vec<&PathBuf> = vec![];
2736    for candidate in &witness_candidates {
2737        if !witness_files.contains(&&candidate.file) {
2738            witness_files.push(&candidate.file);
2739        }
2740    }
2741    for witness_file in witness_files {
2742        let in_root = *witness_file == root_file;
2743        let witness_candidates: Vec<&witness::Candidate> = witness_candidates
2744            .iter()
2745            .filter(|candidate| candidate.file == *witness_file)
2746            .collect();
2747        let file = files
2748            .iter()
2749            .find(|file| file.path == *witness_file)
2750            .expect("witness candidates are of files that are analysed");
2751        let rendered = file.rendered.as_ref().expect("rendered before building");
2752        let left_out_here = built_sources.left_out(file);
2753        let restore = if in_root {
2754            format!("{}{root_suffix}", rendered.text)
2755        } else {
2756            rendered.text.clone()
2757        };
2758        let library_runners: Vec<_> = session
2759            .binaries
2760            .iter()
2761            .filter(|bin| {
2762                root_exe
2763                    .as_deref()
2764                    .is_some_and(|exe| bin.runner.executable() == Some(exe))
2765            })
2766            .collect();
2767        let ignored = library_runners
2768            .iter()
2769            .find_map(|bin| match &bin.runner {
2770                Runner::Exe(exe) => Some(list_tests(
2771                    exe,
2772                    &bin.cwd,
2773                    &bin.git_ceiling,
2774                    true,
2775                    false,
2776                    bin.work_lock.as_deref(),
2777                )),
2778                _ => None,
2779            })
2780            .transpose()?
2781            .unwrap_or_default();
2782        let runner_for = |scenario: &witness::Scenario| {
2783            library_runners.iter().copied().find(|bin| {
2784                scenario
2785                    .source_test
2786                    .as_ref()
2787                    .is_none_or(|required| match &bin.runner {
2788                        // In a file that is a module, the test's name comes after the
2789                        // module's.
2790                        Runner::Exe(_) if !in_root => {
2791                            let inner = format!("::{required}");
2792                            bin.tests
2793                                .iter()
2794                                .any(|test| test.ends_with(&inner) && !ignored.contains(test))
2795                        }
2796                        Runner::Exe(_) => {
2797                            bin.tests.contains(required) && !ignored.contains(required)
2798                        }
2799                        Runner::Isolated { test, .. } if !in_root => {
2800                            test.ends_with(&format!("::{required}"))
2801                        }
2802                        Runner::Isolated { test, .. } => test == required,
2803                        Runner::Doc { .. } | Runner::Nextest { .. } => false,
2804                    })
2805            })
2806        };
2807        let write_edits = |edits: &[witness::Edit]| -> Result<bool> {
2808            let Some(source) = witness::render_edits(&file.original, edits, None) else {
2809                return Ok(false);
2810            };
2811            let suffix = if in_root { root_mutant_suffix } else { "" };
2812            state.write(&file.path, &format!("{source}{suffix}"))?;
2813            Ok(true)
2814        };
2815        let suite = |edits: &[witness::Edit]| -> Result<Option<Outcome>> {
2816            if !write_edits(edits)? {
2817                return Ok(None);
2818            }
2819            Ok(match source_build(&cargo_build()?) {
2820                SourceBuild::Built => Some(run_source_tests(&by_speed)?),
2821                SourceBuild::Refused => None,
2822                SourceBuild::Failed(why) => {
2823                    session.note(&format!(
2824                        "a build failed without the compiler refusing the code; the mutant is not evaluated: {why}"
2825                    ));
2826                    Some(Outcome::Unable)
2827                }
2828            })
2829        };
2830        let compile_observer = |edits: &[witness::Edit]| -> Result<Option<PathBuf>> {
2831            if !write_edits(edits)? {
2832                return Ok(None);
2833            }
2834            let build = build_test_binaries(true)?;
2835            if !build.status.success() {
2836                return Ok(None);
2837            }
2838            let artifacts = parse_build_output(
2839                &String::from_utf8_lossy(&build.stdout),
2840                &[package.name.as_str()],
2841            );
2842            Ok(root_test_exe(&artifacts))
2843        };
2844        let observe = |scenario: &witness::Scenario,
2845                       baseline: &TestBinary,
2846                       edits: &[witness::Edit],
2847                       field_path: Option<&str>,
2848                       expected: Option<&str>|
2849         -> Result<Option<witness::Observation>> {
2850            let test = scenario.test_edit_with_field(
2851                &file.original,
2852                witness::TEST_NAME,
2853                field_path,
2854                expected,
2855            );
2856            let edits: Vec<_> = edits.iter().cloned().chain([test]).collect();
2857            let Some(exe) = compile_observer(&edits)? else {
2858                return Ok(None);
2859            };
2860            observe_witness(
2861                baseline,
2862                exe,
2863                wrapper.as_deref(),
2864                scenario,
2865                witness::TEST_NAME,
2866                expected.is_some(),
2867                in_root,
2868            )
2869        };
2870        let witness_checkpoint = if checkpoint.is_some() {
2871            let keys = witness_candidates
2872                .iter()
2873                .map(|candidate| {
2874                    let edits = candidate
2875                        .edits
2876                        .iter()
2877                        .map(|edit| (&edit.span, &edit.replacement))
2878                        .collect::<Vec<_>>();
2879                    serde_json::to_string(&(&candidate.description, edits))
2880                })
2881                .collect::<std::result::Result<Vec<_>, _>>()?;
2882            let name = if in_root {
2883                "witness".to_string()
2884            } else {
2885                format!("witness:{}", file.display)
2886            };
2887            phase(&name, keys)?
2888        } else {
2889            None
2890        };
2891        let mut survivors = vec![];
2892        let mut claimed = BTreeSet::new();
2893        progress::track(
2894            options.progress,
2895            "source witness mutants",
2896            witness_candidates.len(),
2897            |progress| -> Result<()> {
2898                for (index, candidate) in witness_candidates.iter().copied().enumerate() {
2899                    let cached = witness_checkpoint
2900                        .as_ref()
2901                        .map(|phase| phase.get::<WitnessTrial>(index))
2902                        .transpose()?
2903                        .flatten();
2904                    let at = witness_location(file, candidate);
2905                    // Code this build leaves out has no mutant to run.
2906                    if !built_sources.contains(file)
2907                        || candidate.edits.iter().any(|edit| {
2908                            left_out_here
2909                                .iter()
2910                                .any(|(from, to)| *from <= edit.span.start && edit.span.end <= *to)
2911                        })
2912                    {
2913                        if let Some(phase) =
2914                            witness_checkpoint.as_ref().filter(|_| cached.is_none())
2915                        {
2916                            phase.record(index, &WitnessTrial::Inapplicable)?;
2917                        }
2918                        if !candidate.existing {
2919                            report.mutants_not_evaluated += 1;
2920                            report.mutants_not_compiled += 1;
2921                            let span = &candidate.edits[0].span;
2922                            report.skipped.push(report::SkippedSite::new(
2923                                at,
2924                                file.lines.position(&file.original, span.end),
2925                                report::SkipReason::SourceNotBuilt,
2926                                Some(
2927                                    "under a `cfg` that the features of this build turn off"
2928                                        .to_string(),
2929                                ),
2930                            ));
2931                        }
2932                        progress.complete(progress::Outcome::Unable);
2933                        continue;
2934                    }
2935                    let existing = candidate
2936                        .existing
2937                        .then(|| {
2938                            report.findings.iter().position(|finding| {
2939                                let location = finding.at();
2940                                location.file == at.file
2941                                    && location.line == at.line
2942                                    && location.column == at.column
2943                                    && finding.survivors().contains(&candidate.description)
2944                                    && (candidate.finding_at.is_none()
2945                                        || !matches!(finding, Finding::InputGap { .. }))
2946                            })
2947                        })
2948                        .flatten();
2949                    // One stronger assertion is enough for a finding, but wait until a
2950                    // witness actually verifies before claiming it so later surviving
2951                    // mutants on the same finding still get a turn if an earlier one fails.
2952                    let existing = existing
2953                        .filter(|index| candidate.finding_at.is_none() || !claimed.contains(index));
2954                    let scenarios: Vec<_> = candidate
2955                        .scenarios
2956                        .iter()
2957                        .filter_map(|scenario| {
2958                            runner_for(scenario).map(|runner| (scenario, runner))
2959                        })
2960                        .take(4)
2961                        .collect();
2962                    let paired = candidate.edits.len() > 1;
2963                    if (candidate.existing && (existing.is_none() || scenarios.is_empty()))
2964                        || (paired && scenarios.is_empty())
2965                    {
2966                        if let Some(phase) =
2967                            witness_checkpoint.as_ref().filter(|_| cached.is_none())
2968                        {
2969                            phase.record(index, &WitnessTrial::Inapplicable)?;
2970                        }
2971                        progress.complete(progress::Outcome::Unable);
2972                        continue;
2973                    }
2974                    // A compound survivor is interesting only if each component fails on
2975                    // its own. Test the source edits without any generated witness tests.
2976                    let trial = if let Some(cached) = cached {
2977                        cached
2978                    } else {
2979                        let attempted = (|| -> Result<WitnessTrial> {
2980                            if paired {
2981                                for edit in &candidate.edits {
2982                                    match suite(std::slice::from_ref(edit))? {
2983                                        Some(Outcome::Fail) => {}
2984                                        Some(Outcome::Unable) => {
2985                                            return Ok(WitnessTrial::Evaluated(Outcome::Unable));
2986                                        }
2987                                        _ => return Ok(WitnessTrial::Inapplicable),
2988                                    }
2989                                }
2990                            }
2991                            Ok(suite(&candidate.edits)?
2992                                .map_or(WitnessTrial::Unviable, WitnessTrial::Evaluated))
2993                        })();
2994                        state.write(&file.path, &restore)?;
2995                        let trial = attempted?;
2996                        if let Some(phase) = &witness_checkpoint
2997                            && !matches!(trial, WitnessTrial::Evaluated(Outcome::Unable))
2998                        {
2999                            phase.record(index, &trial)?;
3000                        }
3001                        trial
3002                    };
3003                    let outcome = match trial {
3004                        WitnessTrial::Inapplicable => {
3005                            progress.complete(progress::Outcome::Unable);
3006                            continue;
3007                        }
3008                        WitnessTrial::Unviable => {
3009                            progress.complete(progress::Outcome::Unable);
3010                            report.unviable_mutants += usize::from(!candidate.existing);
3011                            continue;
3012                        }
3013                        WitnessTrial::Evaluated(outcome) => outcome,
3014                    };
3015                    progress.complete(outcome.into());
3016                    if !candidate.existing {
3017                        match outcome {
3018                            Outcome::Unable => report.mutants_not_evaluated += 1,
3019                            Outcome::Pass => {
3020                                report.mutants_run += 1;
3021                                report.mutants_survived += 1;
3022                            }
3023                            Outcome::Fail => {
3024                                report.mutants_run += 1;
3025                                report.mutants_killed += 1;
3026                            }
3027                            Outcome::Timeout => {
3028                                report.mutants_run += 1;
3029                                report.mutants_killed += 1;
3030                                report.mutants_timed_out += 1;
3031                            }
3032                        }
3033                    }
3034                    if outcome == Outcome::Pass {
3035                        survivors.push(WitnessSurvivor {
3036                            candidate,
3037                            at,
3038                            existing,
3039                            scenarios,
3040                        });
3041                    }
3042                }
3043                Ok(())
3044            },
3045        )?;
3046
3047        if let Some(phase) = &witness_checkpoint {
3048            phase.finish()?;
3049        }
3050        let originals = shared_witnesses(
3051            &file.original,
3052            &survivors,
3053            wrapper.as_deref(),
3054            in_root,
3055            compile_observer,
3056            note,
3057        );
3058        if !survivors.is_empty() {
3059            state.write(&file.path, &restore)?;
3060        }
3061        let originals = originals?;
3062
3063        progress::track(
3064            options.progress,
3065            "distinguishing tests",
3066            survivors.len(),
3067            |progress| -> Result<()> {
3068                for (survivor, original) in survivors.into_iter().zip(originals) {
3069                    if survivor.existing.is_some_and(|index| {
3070                        survivor.candidate.finding_at.is_some() && claimed.contains(&index)
3071                    }) {
3072                        progress.complete(progress::Outcome::Unable);
3073                        continue;
3074                    }
3075                    let mut evidence = None;
3076                    let mut original = original;
3077                    for (scenario, baseline) in survivor.scenarios {
3078                        let shared = original.take();
3079                        let distinction = (|| -> Result<_> {
3080                            if let Some(shared) = shared {
3081                                // Keep the harness and test name identical on both sides.
3082                                let edits: Vec<_> = survivor
3083                                    .candidate
3084                                    .edits
3085                                    .iter()
3086                                    .chain(shared.tests.iter())
3087                                    .cloned()
3088                                    .collect();
3089                                if let Some(exe) = compile_observer(&edits)?
3090                                    && let Some(mutant) = observe_witness(
3091                                        baseline,
3092                                        exe,
3093                                        wrapper.as_deref(),
3094                                        scenario,
3095                                        &shared.name,
3096                                        true,
3097                                        in_root,
3098                                    )
3099                                    .ok()
3100                                    .flatten()
3101                                    && mutant.equals_expected == Some(false)
3102                                    // Re-check the preserved original binary after the mutant
3103                                    // run to reject monotonic external-state drift without rebuilding.
3104                                    && observe_witness(
3105                                        baseline,
3106                                        shared.original_exe.path.clone(),
3107                                        wrapper.as_deref(),
3108                                        scenario,
3109                                        &shared.name,
3110                                        true,
3111                                        in_root,
3112                                    )
3113                                    .ok()
3114                                    .flatten()
3115                                    .is_some_and(|rechecked| {
3116                                        rechecked.equals_expected == Some(true)
3117                                            && rechecked.value == shared.value
3118                                    })
3119                                    && let Some(verified) =
3120                                        scenario.verified(shared.value, mutant.value)
3121                                {
3122                                    return Ok(Some(verified));
3123                                }
3124                                // A combined build can fail or the code can depend on
3125                                // the harness. Retry the original input in isolation.
3126                            }
3127                            let Some(original) = observe(scenario, baseline, &[], None, None)?
3128                            else {
3129                                return Ok(None);
3130                            };
3131                            let value = original.value;
3132                            if witness::is_expected_literal(&value) {
3133                                let Some(mutant) = observe(
3134                                    scenario,
3135                                    baseline,
3136                                    &survivor.candidate.edits,
3137                                    None,
3138                                    Some(&value),
3139                                )?
3140                                else {
3141                                    return Ok(None);
3142                                };
3143                                if mutant.equals_expected != Some(false) || value == mutant.value {
3144                                    return Ok(None);
3145                                }
3146                                let Some(checked) =
3147                                    observe(scenario, baseline, &[], None, Some(&value))?
3148                                else {
3149                                    return Ok(None);
3150                                };
3151                                if checked.equals_expected != Some(true) || checked.value != value {
3152                                    return Ok(None);
3153                                }
3154                                return Ok(scenario.verified(value, mutant.value));
3155                            }
3156                            // Multi-field Debug struct: narrow to a single differing public
3157                            // literal field and compiler-verify `&result.<path> == &(<val>)`.
3158                            if witness::parse_debug_struct(&value).is_none() {
3159                                return Ok(None);
3160                            }
3161                            let Some(raw_mutant) =
3162                                observe(scenario, baseline, &survivor.candidate.edits, None, None)?
3163                            else {
3164                                return Ok(None);
3165                            };
3166                            let Some((path, field_orig, _)) =
3167                                witness::narrow_struct_field(&value, &raw_mutant.value)
3168                            else {
3169                                return Ok(None);
3170                            };
3171                            if !witness::is_expected_literal(&field_orig) {
3172                                return Ok(None);
3173                            }
3174                            let field_path = path.join(".");
3175                            let Some(mutant) = observe(
3176                                scenario,
3177                                baseline,
3178                                &survivor.candidate.edits,
3179                                Some(&field_path),
3180                                Some(&field_orig),
3181                            )?
3182                            else {
3183                                return Ok(None);
3184                            };
3185                            if mutant.equals_expected != Some(false)
3186                                || mutant.value != raw_mutant.value
3187                                || value == mutant.value
3188                            {
3189                                return Ok(None);
3190                            }
3191                            let Some(checked) = observe(
3192                                scenario,
3193                                baseline,
3194                                &[],
3195                                Some(&field_path),
3196                                Some(&field_orig),
3197                            )?
3198                            else {
3199                                return Ok(None);
3200                            };
3201                            if checked.equals_expected != Some(true) || checked.value != value {
3202                                return Ok(None);
3203                            }
3204                            Ok(
3205                                scenario.verified_field(
3206                                    value,
3207                                    mutant.value,
3208                                    field_path,
3209                                    field_orig,
3210                                ),
3211                            )
3212                        })();
3213                        match distinction {
3214                            Ok(Some(mut verified)) => {
3215                                let edits = survivor.candidate.edits.len();
3216                                verified.individually_killed = (edits > 1).then_some(edits);
3217                                evidence = Some(verified);
3218                                break;
3219                            }
3220                            Ok(None) => {}
3221                            Err(err) => note(&format!(
3222                                "could not check a distinguishing test for {}: {err:#}",
3223                                scenario.expression,
3224                            )),
3225                        }
3226                    }
3227                    state.write(&file.path, &restore)?;
3228                    progress.complete(Outcome::Pass.into());
3229                    if let Some(index) = survivor.existing {
3230                        if let Some(evidence) = evidence {
3231                            report.findings[index].set_witness(evidence);
3232                            if survivor.candidate.finding_at.is_some() {
3233                                claimed.insert(index);
3234                            }
3235                        }
3236                    } else {
3237                        finding_run_survivors.push(1);
3238                        report.findings.push(Finding::Survivor {
3239                            at: survivor.at,
3240                            survivors: vec![survivor.candidate.description.clone()],
3241                            advice: survivor
3242                                .candidate
3243                                .advice
3244                                .clone()
3245                                .filter(|_| evidence.is_none()),
3246                            witness: evidence,
3247                            change_since: None,
3248                        });
3249                    }
3250                }
3251                Ok(())
3252            },
3253        )?;
3254    }
3255
3256    report.record_evaluation();
3257    debug_assert_eq!(report.findings.len(), finding_run_survivors.len());
3258    let mut paired_findings: Vec<(Finding, usize)> = report
3259        .findings
3260        .into_iter()
3261        .zip(finding_run_survivors)
3262        .collect();
3263    paired_findings.sort_by(|(a, _), (b, _)| {
3264        let (a, b) = (a.at(), b.at());
3265        (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column))
3266    });
3267    let (sorted_findings, finding_run_survivors): (Vec<_>, Vec<_>) =
3268        paired_findings.into_iter().unzip();
3269    report.findings = sorted_findings;
3270    let places: Vec<FilePlaces> = files
3271        .iter()
3272        .map(|file| FilePlaces {
3273            display: &file.display,
3274            source: &file.original,
3275            lines: &file.lines,
3276            places: &file.places,
3277        })
3278        .collect();
3279    name_findings(&mut report.findings, &places);
3280
3281    // 8. Findings the user has already dealt with.
3282    apply_suppressions_and_finish(
3283        options,
3284        &files,
3285        &mut report,
3286        &finding_run_survivors,
3287        checkpoint.as_ref(),
3288    )?;
3289    debug_assert!(
3290        report.counts_reconcile(),
3291        "report counts do not reconcile: {report:#?}"
3292    );
3293    Ok(report)
3294}
3295
3296fn validate_package_options(options: &Options) -> Result<Vec<&str>> {
3297    if let Some(shard) = options.shard
3298        && (!options.source_only || shard.index >= shard.count)
3299    {
3300        bail!("shards require --source-only and a valid shard index");
3301    }
3302    let mut seen_errors = HashSet::new();
3303    let mut error_values = vec![];
3304    for expression in &options.error_values {
3305        let expression = expression.trim();
3306        // The text is written into the code of probes, each on the line of its site: it
3307        // is one line, and has nothing in it that is not to be seen.
3308        if expression.chars().any(char::is_control) {
3309            bail!(
3310                "invalid --error expression {expression:?}: it has to be on one line, \
3311                 without control characters"
3312            );
3313        }
3314        let parsed = syn::parse_str::<syn::Expr>(expression)
3315            .with_context(|| format!("invalid --error expression {expression:?}"))?;
3316        if seen_errors.insert(quote::ToTokens::to_token_stream(&parsed).to_string()) {
3317            error_values.push(expression);
3318        }
3319    }
3320    let selection = &options.test_selection;
3321    if options.nextest.is_some() {
3322        if !cfg!(unix) {
3323            bail!("the nextest runner is available on Unix");
3324        }
3325        if !options.source_only || options.doc || selection.enabled() {
3326            bail!(
3327                "--test-tool nextest requires --source-only; select tests through the nextest profile"
3328            );
3329        }
3330    }
3331    if options.baseline_jobs > 1 && !selection.enabled() {
3332        bail!("--baseline-jobs requires isolated tests or a test wrapper or selection");
3333    }
3334    if options.doc && selection.enabled() {
3335        bail!("--doc cannot be combined with isolated test selection");
3336    }
3337    if options.source_only && options.jobs > 1 {
3338        eprintln!(
3339            "tmt: warning: --source-only runs mutants serially in one working copy; ignoring --jobs {}",
3340            options.jobs
3341        );
3342    }
3343    Ok(error_values)
3344}
3345
3346struct PreparedWorkCopy {
3347    workspace: PathBuf,
3348    work: PathBuf,
3349    work_lock: Option<Arc<WorkLock>>,
3350    copy: PathBuf,
3351    state: WorkCopy,
3352    external_deps: BTreeSet<PathBuf>,
3353}
3354
3355fn prepare_work_copy(
3356    options: &Options,
3357    metadata: &Metadata,
3358    batch: Option<&WorkspaceBatch<'_>>,
3359    catalogue: Option<&CatalogueSnapshot>,
3360    note: &impl Fn(&str),
3361) -> Result<PreparedWorkCopy> {
3362    let workspace = metadata.workspace_root.canonicalize()?;
3363    let requested_work = catalogue
3364        .map(|catalogue| &catalogue.path)
3365        .or(options.work_dir.as_ref());
3366    let work = match requested_work {
3367        Some(dir) => {
3368            fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
3369            dir.canonicalize()?
3370        }
3371        None => metadata.target_directory.join("tmt"),
3372    };
3373    // The copy is brought up to date on every run, and files that are no longer wanted
3374    // are deleted from it. Make sure it is ours to delete from.
3375    if workspace.starts_with(&work) {
3376        bail!(
3377            "the work directory {} contains the workspace; choose a directory of its own",
3378            work.display()
3379        );
3380    }
3381    fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?;
3382    let work = work.canonicalize()?;
3383    let work_lock = if catalogue.is_none() {
3384        Some(Arc::new(WorkLock::take(&work)?))
3385    } else {
3386        None
3387    };
3388    let stage_root = work.join("src");
3389    let copy_subdir = staged_copy_subdir(&workspace, &options.stage_external)?;
3390    let copy = if copy_subdir.as_os_str().is_empty() {
3391        stage_root.clone()
3392    } else {
3393        stage_root.join(&copy_subdir)
3394    };
3395    let marker = work.join(WORK_MARKER);
3396    if stage_root.exists() && !marker.exists() {
3397        bail!(
3398            "{} exists and was not created by tmt; refusing to delete it. \
3399                 Choose another --work-dir or remove it yourself.",
3400            stage_root.display()
3401        );
3402    }
3403    fs::write(
3404        &marker,
3405        "Working directory of tmt (targeted-mutation). Safe to delete.\n",
3406    )?;
3407    let target_dir = metadata.target_directory.clone();
3408    let forbidden = |path: &Path| {
3409        path == target_dir
3410            || path == work
3411            || batch.is_some_and(|batch| path == batch.work)
3412            || path.file_name().is_some_and(|n| n == ".git")
3413            || (path.parent() == Some(workspace.as_path())
3414                && path.file_name().is_some_and(|n| n == "target"))
3415    };
3416    let state = WorkCopy::open_with_copy_root(&work, &stage_root, &copy);
3417    let fixtures = options
3418        .copy_fixtures
3419        .iter()
3420        .map(|path| fixture_relative(path))
3421        .collect::<Result<Vec<_>>>()?;
3422    let excluded = fixture_exclusions(&workspace, &fixtures, &options.copy_fixture_excludes)?;
3423    let fixture_forbidden = |path: &Path| forbidden(path) || excluded.contains(path);
3424    let skip = |path: &Path| {
3425        fixture_forbidden(path) || path.file_name().is_some_and(|n| n == "node_modules")
3426    };
3427    if options.progress && !options.list {
3428        for path in &excluded {
3429            note(&format!(
3430                "excluded fixture {}",
3431                path.strip_prefix(&workspace).unwrap_or(path).display()
3432            ));
3433        }
3434    }
3435    if catalogue.is_none_or(|catalogue| !catalogue.ready.get()) {
3436        work_directory(&work, "src")?;
3437        real_dir(&copy, &state)?;
3438        if copy != stage_root {
3439            for ancestor in copy.ancestors() {
3440                if ancestor == stage_root || !ancestor.starts_with(&stage_root) {
3441                    break;
3442                }
3443                state.kept.borrow_mut().insert(ancestor.to_path_buf());
3444            }
3445        }
3446        let visible = if options.all_files {
3447            None
3448        } else {
3449            git_visible_files(&workspace)?
3450        };
3451        match visible {
3452            // Only what git would not ignore: build output, caches, local notes and secrets
3453            // that are kept out of the repository stay out of the copy too.
3454            Some(files) => {
3455                let copied = copy_git_visible(&workspace, &copy, files, &workspace, &skip, &state)?;
3456                note(&format!(
3457                    "copied {copied} files (ignored files are left out)"
3458                ));
3459            }
3460            None => copy_tree(&workspace, &copy, &workspace, &skip, &state)?,
3461        }
3462        for relative in &fixtures {
3463            copy_fixture_entry(
3464                &workspace.join(relative),
3465                &copy.join(relative),
3466                &workspace,
3467                &fixture_forbidden,
3468                &state,
3469                &mut BTreeSet::new(),
3470            )?;
3471        }
3472        let mut staged_destinations: Vec<PathBuf> = Vec::new();
3473        let mut folded_ancestors: BTreeMap<String, PathBuf> = BTreeMap::new();
3474        for entry in &options.stage_external {
3475            let (rel, _) = parse_external_rel(&entry.rel)?;
3476            let dst = normalize(&copy.join(&rel));
3477            let copy_rel_in_stage = copy.strip_prefix(&stage_root).unwrap_or(&copy);
3478            let dst_rel_in_stage = dst.strip_prefix(&stage_root).unwrap_or(&dst);
3479            if !dst.starts_with(&stage_root)
3480                || dst == stage_root
3481                || copy.starts_with(&dst)
3482                || dst.starts_with(&copy)
3483                || paths_overlap_case_insensitive(copy_rel_in_stage, dst_rel_in_stage)
3484                || staged_destinations.iter().any(|prev| {
3485                    let prev_rel = prev.strip_prefix(&stage_root).unwrap_or(prev);
3486                    paths_overlap_case_insensitive(prev_rel, dst_rel_in_stage)
3487                })
3488            {
3489                bail!(
3490                    "--stage-external destination collides with the workspace copy or another staged path: {}",
3491                    entry.rel.display()
3492                );
3493            }
3494            for ancestor in dst_rel_in_stage.ancestors() {
3495                if ancestor.as_os_str().is_empty() {
3496                    continue;
3497                }
3498                let folded = ancestor.to_string_lossy().to_lowercase();
3499                if let Some(previous) = folded_ancestors.get(&folded)
3500                    && previous != ancestor
3501                {
3502                    bail!(
3503                        "--stage-external destinations differ only by case: {} and {}",
3504                        previous.display(),
3505                        ancestor.display()
3506                    );
3507                }
3508                folded_ancestors.insert(folded, ancestor.to_path_buf());
3509            }
3510            staged_destinations.push(dst.clone());
3511            let src = if entry.from.is_absolute() {
3512                entry.from.clone()
3513            } else {
3514                workspace.join(&entry.from)
3515            };
3516            copy_external_entry(
3517                &src,
3518                &dst,
3519                None,
3520                &work,
3521                &forbidden,
3522                &state,
3523                &mut BTreeSet::new(),
3524            )?;
3525        }
3526        prune(&stage_root, &state)?;
3527        if options.git_index {
3528            git_index::snapshot(&workspace, &copy)?;
3529        }
3530        let mut external_deps = BTreeSet::new();
3531        if !options.list {
3532            // Relative path dependencies that leave the workspace would point nowhere from the copy.
3533            let mut manifests: Vec<&Path> = metadata
3534                .packages
3535                .iter()
3536                .map(|p| p.manifest_path.as_path())
3537                .collect();
3538            let root_manifest = metadata.workspace_root.join("Cargo.toml");
3539            manifests.push(&root_manifest);
3540            for manifest in manifests {
3541                let Ok(canonical) = manifest.canonicalize() else {
3542                    continue;
3543                };
3544                let (Some(manifest_dir), Ok(relative)) =
3545                    (canonical.parent(), canonical.strip_prefix(&workspace))
3546                else {
3547                    continue;
3548                };
3549                let text = fs::read_to_string(&canonical)?;
3550                let (rewritten, externals) = absolutize_path_dependencies_with_externals(
3551                    &text,
3552                    manifest_dir,
3553                    &workspace,
3554                    &copy,
3555                )?;
3556                external_deps.extend(externals);
3557                if let Some(rewritten) = rewritten {
3558                    state.write(&copy.join(relative), &rewritten)?;
3559                }
3560            }
3561        }
3562        if let Some(catalogue) = catalogue {
3563            state.settle(&workspace)?;
3564            catalogue.ready.set(true);
3565        }
3566        return Ok(PreparedWorkCopy {
3567            workspace,
3568            work,
3569            work_lock,
3570            copy,
3571            state,
3572            external_deps,
3573        });
3574    }
3575    Ok(PreparedWorkCopy {
3576        workspace,
3577        work,
3578        work_lock,
3579        copy,
3580        state,
3581        external_deps: BTreeSet::new(),
3582    })
3583}
3584
3585#[allow(clippy::too_many_arguments)]
3586fn run_audit_phase<'a>(
3587    session: &Session,
3588    files: &[SourceFile],
3589    jobs: &[Job],
3590    results: &mut [JobResult],
3591    timeout_rechecks: &mut report::TimeoutRechecks,
3592    scratch: &Path,
3593    wanted: usize,
3594    workers: usize,
3595    probe_phase: &impl Fn(&str, &[Job]) -> Result<Option<Phase<'a>>>,
3596) -> Result<report::Audit> {
3597    let survivors: Vec<usize> = (0..jobs.len())
3598        .filter(|job| results[*job].survived.is_some())
3599        .collect();
3600    let chosen: Vec<usize> = spread(survivors.len(), wanted)
3601        .into_iter()
3602        .map(|nth| survivors[nth])
3603        .collect();
3604    session.note(&format!(
3605        "audit: running {} of {} surviving mutants against all tests",
3606        chosen.len(),
3607        survivors.len()
3608    ));
3609    let against_all: Vec<Job> = chosen
3610        .iter()
3611        .map(|job| Job {
3612            site: jobs[*job].site,
3613            mutation: jobs[*job].mutation,
3614            tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
3615        })
3616        .collect();
3617    let mut audit = report::Audit {
3618        sampled: chosen.len(),
3619        survivors: survivors.len(),
3620        ..report::Audit::default()
3621    };
3622    let audit_checkpoint = probe_phase("audit", &against_all)?;
3623    for (job, again) in chosen.iter().zip(session.run_jobs(
3624        &against_all,
3625        workers,
3626        "audit mutants",
3627        audit_checkpoint.as_ref(),
3628    )?) {
3629        timeout_rechecks.include(&again);
3630        if again.unable || again.unconfirmed_timeout {
3631            audit.not_audited += 1;
3632        } else if audit_all_tests_disagrees(&again) {
3633            // The verdict of all tests is the one that counts.
3634            results[*job] = again;
3635            let site = files
3636                .iter()
3637                .find_map(|f| Some((f, f.sites.iter().find(|s| s.id == jobs[*job].site)?)));
3638            if let Some((file, site)) = site {
3639                audit
3640                    .disagreements
3641                    .push(report::location(&file.display, site));
3642            }
3643        }
3644    }
3645    session.note("audit: recording the tests once more");
3646    for (index, bin) in session.binaries.iter().enumerate() {
3647        let path = scratch.join(format!("trace-{index}-audit.tsv"));
3648        let _ = fs::remove_file(&path);
3649        let trace_env = path.to_string_lossy().into_owned();
3650        let limit = Duration::from_secs(3600);
3651        let outcome = run_binary(
3652            bin,
3653            None,
3654            &[("TMT_TRACE", &trace_env)],
3655            limit,
3656            RunOutput::Quiet,
3657            1,
3658        )?;
3659        let again = Trace::parse(&fs::read_to_string(&path).unwrap_or_default());
3660        let _ = fs::remove_file(&path);
3661        let records = bin.trace.differences(&again);
3662        if outcome != Outcome::Pass || records > 0 {
3663            audit.trace_differences.push(report::TraceDifference {
3664                binary: bin.name.clone(),
3665                records,
3666                rerun_failed: outcome != Outcome::Pass,
3667            });
3668        }
3669    }
3670    Ok(audit)
3671}
3672
3673fn run_effects_phase(
3674    session: &Session,
3675    files: &[SourceFile],
3676    jobs: &[Job],
3677    effect_jobs: &[(usize, usize)],
3678    scratch: &Path,
3679    workers: usize,
3680    findings: &mut [Finding],
3681) -> Result<()> {
3682    session.note(&format!("tracing {} surviving mutants", effect_jobs.len()));
3683    let sites: BTreeMap<u32, (&str, &Site)> = files
3684        .iter()
3685        .flat_map(|f| f.sites.iter().map(move |s| (s.id, (f.display.as_str(), s))))
3686        .collect();
3687    let traced = run_pool(effect_jobs.len(), workers, |index| {
3688        session.trace_job(
3689            &jobs[effect_jobs[index].1],
3690            scratch,
3691            workers.clamp(1, effect_jobs.len()),
3692        )
3693    })?;
3694    for ((finding, job), mut changes) in effect_jobs.iter().zip(traced) {
3695        // What happens inside the mutated code itself is not an effect of it: deleting
3696        // a statement trivially stops the expressions in it from running.
3697        if let Some((mutated_file, mutated)) = sites.get(&jobs[*job].site) {
3698            for found in changes.values_mut() {
3699                found.retain(|change| {
3700                    sites.get(&change.site()).is_none_or(|(file, site)| {
3701                        file != mutated_file
3702                            || site.end <= mutated.start
3703                            || mutated.end <= site.start
3704                    })
3705                });
3706            }
3707            changes.retain(|_, found| !found.is_empty());
3708        }
3709        if let Finding::AssertionGap {
3710            effects,
3711            effects_of,
3712            ..
3713        } = &mut findings[*finding]
3714        {
3715            *effects = describe_effects(&changes, &sites);
3716            *effects_of = sites
3717                .get(&jobs[*job].site)
3718                .map(|(_, site)| report::describe(site, jobs[*job].mutation));
3719        }
3720    }
3721    Ok(())
3722}
3723
3724fn apply_suppressions_and_finish(
3725    options: &Options,
3726    files: &[SourceFile],
3727    report: &mut Report,
3728    finding_run_survivors: &[usize],
3729    checkpoint: Option<&Checkpoint>,
3730) -> Result<()> {
3731    let files_with_findings: BTreeSet<&str> = report
3732        .findings
3733        .iter()
3734        .map(|finding| finding.at().file.as_str())
3735        .collect();
3736    let ignored: BTreeMap<&str, BTreeMap<usize, String>> = files
3737        .iter()
3738        .filter(|file| files_with_findings.contains(file.display.as_str()))
3739        .map(|f| {
3740            (
3741                f.display.as_str(),
3742                crate::baseline::ignored_lines(&f.original),
3743            )
3744        })
3745        .collect();
3746    let known = match &options.baseline {
3747        Some(path) => Some(crate::baseline::load(path)?),
3748        None => None,
3749    };
3750    let before = report.findings.len();
3751    let mut after_inline: Vec<(Finding, usize)> = Vec::with_capacity(before);
3752    for (finding, run_survivors) in report
3753        .findings
3754        .drain(..)
3755        .zip(finding_run_survivors.iter().copied())
3756    {
3757        let at = finding.at();
3758        if ignored
3759            .get(at.file.as_str())
3760            .is_some_and(|lines| lines.contains_key(&at.line))
3761        {
3762            report.survivor_breakdown.suppressed += run_survivors;
3763        } else {
3764            after_inline.push((finding, run_survivors));
3765        }
3766    }
3767    if let Some(path) = &options.write_baseline {
3768        let unignored: Vec<Finding> = after_inline.iter().map(|(f, _)| f.clone()).collect();
3769        crate::baseline::write(path, &unignored)?;
3770    }
3771    for (finding, run_survivors) in after_inline {
3772        if known.as_ref().is_some_and(|known| known.knows(&finding)) {
3773            report.survivor_breakdown.suppressed += run_survivors;
3774        } else {
3775            report.survivor_breakdown.reported += run_survivors;
3776            report.findings.push(finding);
3777        }
3778    }
3779    report.suppressed = before - report.findings.len();
3780    if let Some(checkpoint) = checkpoint {
3781        checkpoint.finish_if_complete()?;
3782    }
3783    Ok(())
3784}
3785
3786fn workspace_report_prefix(relative: &Path) -> String {
3787    let parts: Vec<_> = relative
3788        .components()
3789        .filter_map(|part| match part {
3790            std::path::Component::Normal(name) => Some(name.to_string_lossy()),
3791            _ => None,
3792        })
3793        .collect();
3794    if parts.is_empty() {
3795        String::new()
3796    } else {
3797        format!("{}/", parts.join("/"))
3798    }
3799}
3800
3801/// Where a directory is in its git repository: `crates/core/`, or nothing at the top
3802/// and outside of any. The files of a report are named from the package; this in front
3803/// of them names them from the repository, as a code-scanning service wants them.
3804fn repository_prefix(dir: &Path) -> String {
3805    let shown = Command::new("git")
3806        .arg("-C")
3807        .arg(dir)
3808        .args(["rev-parse", "--show-prefix"])
3809        .stderr(Stdio::null())
3810        .output();
3811    match shown {
3812        Ok(output) if output.status.success() => {
3813            String::from_utf8_lossy(&output.stdout).trim().to_string()
3814        }
3815        _ => String::new(),
3816    }
3817}
3818
3819/// `wanted` of the numbers below `count`, spread evenly and the same every time; all of
3820/// them where there are no more.
3821fn spread(count: usize, wanted: usize) -> Vec<usize> {
3822    let wanted = wanted.min(count);
3823    (0..wanted).map(|nth| nth * count / wanted).collect()
3824}
3825
3826/// What naming the findings of a file needs to know of it.
3827struct FilePlaces<'a> {
3828    display: &'a str,
3829    source: &'a str,
3830    lines: &'a scope::LineIndex,
3831    /// Every site of the file as (line, column, code), whatever part of it was analysed.
3832    places: &'a [(usize, usize, String)],
3833}
3834
3835/// Gives every finding the item it is in and its name (`report::finding_id`). Which of
3836/// several places with the same code in one item a finding is at is counted over the
3837/// sites of the file, not over the findings: a finding keeps its number when the one
3838/// before it is closed.
3839fn name_findings(findings: &mut [Finding], files: &[FilePlaces]) {
3840    let mut by_file: BTreeMap<String, Vec<&mut Finding>> = BTreeMap::new();
3841    for finding in findings {
3842        by_file
3843            .entry(finding.at().file.clone())
3844            .or_default()
3845            .push(finding);
3846    }
3847    for file in files {
3848        let Some(findings) = by_file.remove(file.display) else {
3849            continue;
3850        };
3851        let items = instrument::named_items(file.source);
3852        let index = instrument::ItemIndex::new(&items);
3853        let item_at = |line, column| {
3854            file.lines
3855                .offset_of(file.source, line, column)
3856                .map_or("", |offset| index.at(offset))
3857        };
3858        let mut positions: BTreeMap<(&str, &str), Vec<(usize, usize)>> = BTreeMap::new();
3859        for (line, column, code) in file.places {
3860            positions
3861                .entry((item_at(*line, *column), code))
3862                .or_default()
3863                .push((*line, *column));
3864        }
3865        for places in positions.values_mut() {
3866            places.sort_unstable();
3867            places.dedup();
3868        }
3869        for finding in findings {
3870            let kind = finding.kind();
3871            let at = finding.at_mut();
3872            let item = item_at(at.line, at.column);
3873            let nth = positions.get(&(item, &at.code)).map_or(0, |places| {
3874                places.partition_point(|&place| place < (at.line, at.column))
3875            });
3876            at.item = item.to_string();
3877            at.id = report::finding_id(kind, at, nth);
3878        }
3879    }
3880}
3881
3882/// The mutation that a change of the source text is, to describe it in the same words.
3883fn mutation_of(site: &Site, mutant: &instrument::SourceMutant) -> Mutation {
3884    match &site.kind {
3885        SiteKind::Cmp { .. } => plan::CmpOp::ALL
3886            .into_iter()
3887            .find(|op| op.symbol() == mutant.into)
3888            .map_or(Mutation::Negate, Mutation::Op),
3889        SiteKind::Arith { op, .. } => {
3890            if mutant.into.trim_end_matches('=') == op.swapped().symbol() {
3891                Mutation::ArithSwap
3892            } else {
3893                Mutation::ArithSwap2
3894            }
3895        }
3896        SiteKind::Guard { .. } => Mutation::Const(mutant.into == "true"),
3897        SiteKind::Logic { .. } => Mutation::LogicSwap,
3898        SiteKind::Not { .. } => Mutation::DropNot,
3899        SiteKind::Range { .. } => Mutation::RangeEnd,
3900        SiteKind::SliceEnd { .. } => Mutation::OtherEnd,
3901        SiteKind::StrAffix { .. } => Mutation::StrContains,
3902        SiteKind::StrReplace { .. } => Mutation::StrReplaceMultiplicity,
3903        SiteKind::Clamp { .. } => {
3904            if mutant.into.contains("lower") {
3905                Mutation::ClampDropLower
3906            } else {
3907                Mutation::ClampDropUpper
3908            }
3909        }
3910        SiteKind::Rounding { op, .. } => {
3911            if mutant.into == op.alt1().name() {
3912                Mutation::RoundAlt1
3913            } else {
3914                Mutation::RoundAlt2
3915            }
3916        }
3917        SiteKind::Quantifier { .. } => Mutation::QuantifierSwap,
3918        SiteKind::SaturatingArith { .. } => Mutation::SaturatingSwap,
3919        SiteKind::StrTrim { op, .. } => {
3920            if mutant.into == op.alt1().name() {
3921                Mutation::TrimAlt1
3922            } else {
3923                Mutation::TrimAlt2
3924            }
3925        }
3926        SiteKind::StrCaseEq { .. } => Mutation::StrExactEq,
3927        SiteKind::Abs { .. } => Mutation::DropAbs,
3928        SiteKind::IterLimit { .. } => Mutation::IterLimitDrop,
3929        SiteKind::EndianSwap { .. } => Mutation::EndianSwap,
3930        SiteKind::BitCount { .. } => Mutation::BitCountSwap,
3931        SiteKind::LoopCtrl { .. } => Mutation::LoopCtrlSwap,
3932        // The other kinds have one mutant of the source: a statement, an arm, a field or
3933        // a minus that is not there, a body that is another.
3934        _ => Mutation::Delete,
3935    }
3936}
3937
3938/// The mutations a probe may have run that are the same change as a mutant of the source,
3939/// its own name first. A comparison is planned in other words than it is written in:
3940/// `a != b` for `a == b` is run as the negation, and on integers `a <= b` for `a < b` as
3941/// the bound moved by one.
3942///
3943/// `integers`: the operands are integers, which always have an order. For anything
3944/// else (a float can be NaN) the negation of `>=` is true where `<` is false, and is
3945/// not the same change.
3946fn mutations_like(site: &Site, mutant: &instrument::SourceMutant, integers: bool) -> Vec<Mutation> {
3947    let mut all = vec![mutation_of(site, mutant)];
3948    if let (SiteKind::Cmp { op, .. }, Mutation::Op(into)) = (&site.kind, all[0]) {
3949        let an_order_is_needed = matches!(op, plan::CmpOp::Le | plan::CmpOp::Ge);
3950        if into == op.negated() && (integers || !an_order_is_needed) {
3951            all.push(Mutation::Negate);
3952        }
3953        match (op, into) {
3954            (plan::CmpOp::Lt, plan::CmpOp::Le) | (plan::CmpOp::Ge, plan::CmpOp::Gt) => {
3955                all.push(Mutation::Shift(1))
3956            }
3957            (plan::CmpOp::Gt, plan::CmpOp::Ge) | (plan::CmpOp::Le, plan::CmpOp::Lt) => {
3958                all.push(Mutation::Shift(-1))
3959            }
3960            _ => {}
3961        }
3962    }
3963    all
3964}
3965
3966/// The changes a surviving mutant causes, as up to three sentences. Changes that many
3967/// tests share are mentioned once.
3968fn describe_effects(
3969    changes: &BTreeMap<String, BTreeSet<Change>>,
3970    sites: &BTreeMap<u32, (&str, &Site)>,
3971) -> Vec<String> {
3972    let mut by_change: BTreeMap<&Change, Vec<&str>> = BTreeMap::new();
3973    for (test, found) in changes {
3974        for change in found {
3975            by_change.entry(change).or_default().push(test);
3976        }
3977    }
3978    if by_change.is_empty() {
3979        return vec![
3980            "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(),
3981        ];
3982    }
3983    let mut out = vec![];
3984    for (change, tests) in by_change.iter().take(3) {
3985        let Some((file, site)) = sites.get(&change.site()) else {
3986            continue;
3987        };
3988        let code = report::location(file, site).code;
3989        let at = format!("{file}:{}", site.line);
3990        let who = if tests.is_empty() {
3991            continue;
3992        } else if let Some(first) = tests
3993            .iter()
3994            .copied()
3995            .find(|test| *test != crate::trace::UNKNOWN_TEST)
3996        {
3997            if tests.len() == 1 {
3998                format!("`{first}`")
3999            } else {
4000                format!("`{first}` (and {} more)", tests.len() - 1)
4001            }
4002        } else if tests.len() == 1 {
4003            "a test".to_string()
4004        } else {
4005            format!("a test (and {} more)", tests.len() - 1)
4006        };
4007        out.push(match change {
4008            Change::Returns { value, .. } => {
4009                format!("with the mutant, {who} gets `{value}` from `{code}` ({at})")
4010            }
4011            Change::NowRuns { .. } => format!("with the mutant, {who} now runs `{code}` ({at})"),
4012            Change::NoLongerRuns { .. } => {
4013                format!("with the mutant, {who} no longer runs `{code}` ({at})")
4014            }
4015            Change::NewOutcome { .. } => {
4016                format!("with the mutant, {who} takes `{code}` ({at}) a way it did not before")
4017            }
4018        });
4019    }
4020    if by_change.len() > 3 {
4021        out.push(format!("(and {} more such changes)", by_change.len() - 3));
4022    }
4023    out
4024}
4025
4026#[cfg(test)]
4027mod tests;