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 primitive_cmp_spans: HashSet<(usize, usize)> = HashSet::new();
1725        let mut cast_probe_spans: std::collections::HashMap<(usize, usize), (u32, u32)> =
1726            std::collections::HashMap::new();
1727        for other in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
1728            if matches!(other.kind, SiteKind::Cmp { .. })
1729                && session
1730                    .binaries
1731                    .iter()
1732                    .any(|b| b.trace.bounds.contains_key(&other.id))
1733            {
1734                primitive_cmp_spans.insert((other.start, other.end));
1735            }
1736            if let SiteKind::Arith { cast_probes, .. } = &other.kind {
1737                let seen = session.merged(|t| t.arith.get(&other.id), plan::ArithObs::merge);
1738                if !seen.opaque && (seen.same || seen.differs || seen.same2 || seen.differs2) {
1739                    primitive_arith_spans.insert((other.start, other.end));
1740                }
1741                for &(slot, start, end) in cast_probes {
1742                    cast_probe_spans
1743                        .entry((start, end))
1744                        .or_insert((other.id, slot));
1745                }
1746            }
1747        }
1748        let primitive = |from: usize, to: usize| {
1749            let Some(mut text) = file.original.get(from..to) else {
1750                return false;
1751            };
1752            let mut start = from;
1753            loop {
1754                let trimmed = text.trim_start();
1755                start += text.len() - trimmed.len();
1756                text = trimmed.trim_end();
1757                if text.starts_with('(')
1758                    && text.ends_with(')')
1759                    && matches!(syn::parse_str::<syn::Expr>(text), Ok(syn::Expr::Paren(_)))
1760                    && let Some(inner) = text
1761                        .strip_prefix('(')
1762                        .and_then(|inner| inner.strip_suffix(')'))
1763                {
1764                    start += 1;
1765                    text = inner;
1766                } else {
1767                    break;
1768                }
1769            }
1770            primitive_arith_spans.contains(&(start, start + text.len()))
1771        };
1772        let cast_bounds = |from: usize, to: usize| -> Option<(i128, i128)> {
1773            let &(owner_id, slot) = cast_probe_spans.get(&(from, to))?;
1774            let mut recorded = session
1775                .binaries
1776                .iter()
1777                .filter_map(|b| b.trace.cast_bounds.get(&(owner_id, slot)));
1778            let first = recorded.next()?;
1779            if recorded.all(|other| other == first) {
1780                *first
1781            } else {
1782                None
1783            }
1784        };
1785        let primitive_cmp = |from: usize, to: usize| primitive_cmp_spans.contains(&(from, to));
1786        for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
1787            let plan = match session.plan(
1788                &file.display,
1789                site,
1790                options.verify,
1791                &primitive,
1792                &primitive_cmp,
1793                &cast_bounds,
1794            ) {
1795                // Code that did not change is not said to be unreached here: that takes
1796                // a run of the whole.
1797                Planned::Unreached if beyond.contains(&site.id) => continue,
1798                Planned::Unreached => {
1799                    // A function is one place, however many sites it is.
1800                    let at = report::location(&file.display, site);
1801                    if report.unreached.last() != Some(&at) {
1802                        report.unreached.push(at);
1803                    }
1804                    continue;
1805                }
1806                Planned::Nothing => continue,
1807                Planned::NotEvaluated => {
1808                    not_evaluated.insert(site.id);
1809                    continue;
1810                }
1811                Planned::Plan(plan) => plan,
1812            };
1813            let mut add =
1814                |mutation: Mutation, tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>| {
1815                    jobs.push(session.job(site.id, mutation, tests_of));
1816                    jobs.len() - 1
1817                };
1818            let gaps = plan
1819                .gaps
1820                .into_iter()
1821                .map(
1822                    |PlannedGap {
1823                         finding,
1824                         survivors,
1825                         constant_expr,
1826                     }| {
1827                        // The trace says no test can notice. Confirm by running every test
1828                        // that reaches the site against the listed survivors.
1829                        let confirm = if options.verify {
1830                            survivors
1831                                .into_iter()
1832                                .map(|m| add(m, &*plan.reaching))
1833                                .collect()
1834                        } else {
1835                            vec![]
1836                        };
1837                        (finding, confirm, constant_expr)
1838                    },
1839                )
1840                .collect();
1841            let infected = &plan.infected;
1842            let runs = plan
1843                .run
1844                .iter()
1845                .map(|m| (*m, add(*m, &|bin| infected(bin, *m))))
1846                .collect();
1847            site_work.push(SiteWork {
1848                file: &file.display,
1849                site,
1850                gaps,
1851                constant: plan.constant,
1852                cannot_differ: plan.cannot_differ,
1853                redundant_logic_swap: plan.redundant_logic_swap,
1854                runs,
1855            });
1856        }
1857    }
1858    session.note(&format!(
1859        "running {} mutants on {} thread(s)",
1860        jobs.len(),
1861        options.jobs.max(1)
1862    ));
1863    let probe_checkpoint = probe_phase("probe", &jobs)?;
1864    let mut results =
1865        session.run_jobs(&jobs, options.jobs, "mutants", probe_checkpoint.as_ref())?;
1866    for result in &results {
1867        report.timeout_rechecks.include(result);
1868    }
1869
1870    // 6b. On request, check what the run rests on: that the tests chosen for a mutant
1871    // are the ones that could fail with it, and that the tests do the same twice.
1872    if let Some(wanted) = options.audit {
1873        report.audit = Some(run_audit_phase(
1874            &session,
1875            &files,
1876            &jobs,
1877            &mut results,
1878            &mut report.timeout_rechecks,
1879            &scratch,
1880            wanted,
1881            options.jobs,
1882            &probe_phase,
1883        )?);
1884    }
1885    // 6c. In code that did not change, a mutant that passes says something about this
1886    // change only if the tests as they were found it out. They are built once, with
1887    // the program as it is, and run against those mutants.
1888    #[derive(Clone, Copy, PartialEq, Eq)]
1889    enum EarlierVerdict {
1890        Killed,
1891        Survived,
1892        Unknown,
1893    }
1894    let mut earlier_verdict: BTreeMap<usize, EarlierVerdict> = BTreeMap::new();
1895    let asked: Vec<usize> = site_work
1896        .iter()
1897        .filter(|item| beyond.contains(&item.site.id))
1898        .flat_map(|item| {
1899            item.gaps
1900                .iter()
1901                .flat_map(|(_, confirm, _)| confirm.iter().copied())
1902                .chain(
1903                    item.runs
1904                        .iter()
1905                        .filter(|(m, _)| !(*m == Mutation::LogicSwap && item.redundant_logic_swap))
1906                        .map(|(_, job)| *job),
1907                )
1908        })
1909        .filter(|job| results[*job].survived.is_some())
1910        .collect();
1911    if !asked.is_empty() {
1912        let revision = report::short_revision(options.since.as_deref().unwrap_or_default());
1913        session.note(&format!(
1914            "running {} surviving mutants against the tests as they were at {revision}",
1915            asked.len()
1916        ));
1917        let suffix = |file: &SourceFile| {
1918            if file.path == root_file {
1919                root_suffix.as_str()
1920            } else {
1921                ""
1922            }
1923        };
1924        // The instrumented files with the old lines of their tests.
1925        let earlier: Option<Vec<(&SourceFile, String)>> = tests_changed
1926            .iter()
1927            .map(|(path, hunks)| {
1928                let file = files.iter().find(|file| file.path == *path)?;
1929                let rendered = file.rendered.as_ref()?;
1930                let mut places = hunks
1931                    .iter()
1932                    .map(|hunk| {
1933                        let (from, to) = scope::range_of(&file.original, hunk);
1934                        Some((rendered.copied(from, to)?, hunk.old.as_str()))
1935                    })
1936                    .collect::<Option<Vec<_>>>()?;
1937                places.sort_by_key(|((from, _), _)| std::cmp::Reverse(*from));
1938                let mut text = rendered.text.clone();
1939                for ((from, to), old) in places {
1940                    text.replace_range(from..to, old);
1941                }
1942                Some((file, text))
1943            })
1944            .collect();
1945        let attempted = if let Some(earlier) = earlier {
1946            let attempted = (|| -> Result<Option<Vec<JobResult>>> {
1947                for (file, text) in &earlier {
1948                    state.write(&file.path, &format!("{text}{}", suffix(file)))?;
1949                }
1950                if !cargo_build()?.status.success() {
1951                    session.note(
1952                        "the tests as they were do not build with the code as it is: what they found out is not known",
1953                    );
1954                    return Ok(None);
1955                }
1956                // They have to pass as they are, or a failure says nothing of a mutant.
1957                let all: Vec<&TestBinary> = session.binaries.iter().collect();
1958                if run_source_tests(&all)? != Outcome::Pass {
1959                    session.note(
1960                        "the tests as they were fail on the code as it is: what they found out is not known",
1961                    );
1962                    return Ok(None);
1963                }
1964                let against_all: Vec<Job> = asked
1965                    .iter()
1966                    .map(|job| Job {
1967                        site: jobs[*job].site,
1968                        mutation: jobs[*job].mutation,
1969                        tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
1970                    })
1971                    .collect();
1972                session
1973                    .run_jobs(&against_all, options.jobs, "mutants, earlier tests", None)
1974                    .map(Some)
1975            })();
1976            // The files and the binaries as they were, whatever went wrong.
1977            for (file, _) in &earlier {
1978                let rendered = file.rendered.as_ref().expect("rendered before building");
1979                state.write(&file.path, &format!("{}{}", rendered.text, suffix(file)))?;
1980            }
1981            if !cargo_build()?.status.success() {
1982                bail!("the crate does not build once its tests are put back as they are");
1983            }
1984            attempted
1985        } else {
1986            session.note(
1987                "not all changed test files could be restored as they were: what they found out is not known",
1988            );
1989            Ok(None)
1990        };
1991        if let Some(again) = attempted? {
1992            for (job, result) in asked.iter().zip(again) {
1993                let verdict = if result.unable || result.unconfirmed_timeout {
1994                    EarlierVerdict::Unknown
1995                } else if result.survived.is_none() {
1996                    EarlierVerdict::Killed
1997                } else {
1998                    EarlierVerdict::Survived
1999                };
2000                earlier_verdict.insert(*job, verdict);
2001            }
2002        } else {
2003            for job in &asked {
2004                earlier_verdict.insert(*job, EarlierVerdict::Unknown);
2005            }
2006        }
2007    }
2008    let unable = results
2009        .iter()
2010        .filter(|r| r.unable || r.unconfirmed_timeout)
2011        .count();
2012    not_evaluated.extend(
2013        jobs.iter()
2014            .zip(&results)
2015            .filter(|(_, result)| result.unable || result.unconfirmed_timeout)
2016            .map(|(job, _)| job.site),
2017    );
2018    if !options.rebuild {
2019        report.mutants_not_evaluated = not_evaluated.len();
2020    }
2021    report.mutants_run = results.len() - unable;
2022    report.mutants_killed = results.iter().filter(|r| r.survived.is_none()).count() - unable;
2023    report.mutants_survived = report.mutants_run - report.mutants_killed;
2024    report.mutants_timed_out = results
2025        .iter()
2026        .filter(|r| r.timed_out && !r.unconfirmed_timeout)
2027        .count();
2028
2029    // Parallel to `report.findings`: how many executed surviving mutants each finding
2030    // represents (`0` for unverified predicted input gaps under `--no-verify`).
2031    let mut finding_run_survivors: Vec<usize> = vec![];
2032
2033    // Expressions known to be constant in the tests: comparisons with a confirmed
2034    // one-sided gap or that cannot differ at all, and `&&` / `||` with a single value.
2035    let confirmed = |w: &SiteWork| {
2036        w.gaps
2037            .iter()
2038            .all(|(_, confirm, _)| confirm.iter().all(|j| results[*j].survived.is_some()))
2039    };
2040    let constants: BTreeSet<(&str, usize, usize)> = site_work
2041        .iter()
2042        .filter(|w| w.cannot_differ || (w.constant && confirmed(w)))
2043        .map(|w| (w.file, w.site.start, w.site.end))
2044        .collect();
2045    for item in &site_work {
2046        let at = report::location(item.file, item.site);
2047        for (finding, confirm, constant_expr) in &item.gaps {
2048            // Already said by the site of the expression itself (or, for a comparison that
2049            // cannot differ, not worth saying at all).
2050            let repeats = constant_expr
2051                .is_some_and(|(start, end)| constants.contains(&(item.file, start, end)));
2052            let survived_count = confirm
2053                .iter()
2054                .filter(|j| results[**j].survived.is_some())
2055                .count();
2056            if beyond.contains(&item.site.id) {
2057                // Said only when the tests found it out before their change.
2058                let confirmed = confirm.iter().all(|j| results[*j].survived.is_some());
2059                let killed_before = confirm
2060                    .iter()
2061                    .any(|j| earlier_verdict.get(j) == Some(&EarlierVerdict::Killed));
2062                if confirmed && !repeats && killed_before {
2063                    report.weakened.push(finding.at().clone());
2064                    report.findings.push(finding.clone());
2065                    finding_run_survivors.push(survived_count);
2066                } else if !confirmed {
2067                    report.survivor_breakdown.unconfirmed_gap += survived_count;
2068                } else if repeats {
2069                    report.survivor_breakdown.redundant_constant += survived_count;
2070                } else {
2071                    for job in confirm {
2072                        if results[*job].survived.is_some() {
2073                            if earlier_verdict.get(job) == Some(&EarlierVerdict::Survived) {
2074                                report.survivor_breakdown.preexisting_unchanged += 1;
2075                            } else {
2076                                report.survivor_breakdown.unchanged_not_compared += 1;
2077                            }
2078                        }
2079                    }
2080                }
2081                continue;
2082            }
2083            match Prediction::of(confirm.iter().map(|j| &results[*j])) {
2084                Prediction::Refuted => {
2085                    report.unstable.push(at.clone());
2086                    report.survivor_breakdown.unconfirmed_gap += survived_count;
2087                }
2088                Prediction::Confirmed if !repeats => {
2089                    report.findings.push(finding.clone());
2090                    finding_run_survivors.push(survived_count);
2091                }
2092                Prediction::Confirmed => {
2093                    report.survivor_breakdown.redundant_constant += survived_count;
2094                }
2095                // Not evaluated (counted above), or said elsewhere.
2096                Prediction::Unknown => {
2097                    report.survivor_breakdown.unconfirmed_gap += survived_count;
2098                }
2099            }
2100        }
2101        // A body that is one expression, constant in the tests: replacing the body by
2102        // that constant was said at the expression (or cannot be told apart at all).
2103        if let SiteKind::Body {
2104            sole_expr: Some((start, end)),
2105            ..
2106        } = item.site.kind
2107            && constants.contains(&(item.file, start, end))
2108        {
2109            report.survivor_breakdown.redundant_constant += item
2110                .runs
2111                .iter()
2112                .filter(|(_, job)| results[*job].survived.is_some())
2113                .count();
2114            continue;
2115        }
2116        let mut survivors = vec![];
2117        let mut passing_tests = BTreeSet::new();
2118        for (mutation, job) in &item.runs {
2119            if let Some(tests) = &results[*job].survived {
2120                if *mutation == Mutation::LogicSwap && item.redundant_logic_swap {
2121                    report.survivor_breakdown.redundant_constant += 1;
2122                    continue;
2123                }
2124                if beyond.contains(&item.site.id) {
2125                    match earlier_verdict.get(job) {
2126                        Some(EarlierVerdict::Killed) => {}
2127                        Some(EarlierVerdict::Survived) => {
2128                            report.survivor_breakdown.preexisting_unchanged += 1;
2129                            continue;
2130                        }
2131                        Some(EarlierVerdict::Unknown) | None => {
2132                            report.survivor_breakdown.unchanged_not_compared += 1;
2133                            continue;
2134                        }
2135                    }
2136                }
2137                survivors.push(report::describe(item.site, *mutation));
2138                passing_tests.extend(tests.iter().cloned());
2139            }
2140        }
2141        if !survivors.is_empty() {
2142            // The first survivor is traced below to see what it changes.
2143            let first = item.runs.iter().find(|(mutation, job)| {
2144                !(*mutation == Mutation::LogicSwap && item.redundant_logic_swap)
2145                    && results[*job].survived.is_some()
2146                    && (!beyond.contains(&item.site.id)
2147                        || earlier_verdict.get(job) == Some(&EarlierVerdict::Killed))
2148            });
2149            if beyond.contains(&item.site.id) {
2150                report.weakened.push(at.clone());
2151            }
2152            effect_jobs.push((report.findings.len(), first.expect("a survivor").1));
2153            finding_run_survivors.push(survivors.len());
2154            report.findings.push(Finding::AssertionGap {
2155                at,
2156                survivors,
2157                tests: passing_tests.into_iter().collect(),
2158                effects: vec![],
2159                effects_of: None,
2160                witness: None,
2161            });
2162        }
2163    }
2164
2165    // 7. What do the surviving mutants change in the tests that let them through?
2166    if options.effects && !effect_jobs.is_empty() {
2167        run_effects_phase(
2168            &session,
2169            &files,
2170            &jobs,
2171            &effect_jobs,
2172            &scratch,
2173            options.jobs,
2174            &mut report.findings,
2175        )?;
2176    }
2177
2178    // 7b. What a probe cannot be put in is mutated in the source, built and run: code in
2179    // a `const fn`, and the sites whose probe did not compile.
2180    // The last of the four: for an audit, the job that ran the same mutant as a probe.
2181    let mut built: Vec<(&SourceFile, &Site, instrument::SourceMutant, Option<usize>)> = vec![];
2182    let build_regular_mutants = options.rebuild || options.source_only;
2183    let mut index = 0;
2184    for file in &files {
2185        // Tried again as the source says them: what did not compile as a probe, and
2186        // what a probe could not be (a range that ends at the top of its type).
2187        let retried = file.sites.iter().filter(|site| {
2188            (disabled.contains(&site.id) && !matches!(site.kind, SiteKind::Body { .. }))
2189                || not_evaluated.contains(&site.id)
2190        });
2191        for site in file.rebuild_sites.iter().chain(retried) {
2192            let mutants = source_mutants(file, site, true);
2193            if build_regular_mutants {
2194                built.extend(mutants.into_iter().filter_map(|mutant| {
2195                    let selected = in_shard(index);
2196                    index += 1;
2197                    selected.then_some((file, site, mutant, None))
2198                }));
2199            } else {
2200                report.mutants_not_built += mutants.len();
2201            }
2202        }
2203    }
2204    // An audit also builds some of the mutants that were run as probes, from the source
2205    // as a person would write them, to see whether a probe and the real thing agree.
2206    if let (Some(wanted), Some(audit)) = (options.audit, report.audit.as_mut()) {
2207        let mut twins = vec![];
2208        for file in &files {
2209            for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
2210                // Only integers are known to always have an order.
2211                let integers = session.binaries.iter().all(|bin| {
2212                    let seen = bin.trace.merged(site.id);
2213                    !seen.reached() || seen.valued()
2214                });
2215                let candidates = jobs_for_site(&jobs, site.id);
2216                let job_of = |mutation: Mutation| {
2217                    candidates
2218                        .clone()
2219                        .find(|&index| jobs[index].mutation == mutation)
2220                };
2221                let mut compared = vec![];
2222                let mut mutants = instrument::source_mutants(site);
2223                instrument::keep_line_ends(&file.original, &mut mutants);
2224                for mutant in mutants {
2225                    // The first of the mutations that are this change and that was run.
2226                    let job = mutations_like(site, &mutant, integers)
2227                        .into_iter()
2228                        .find_map(job_of);
2229                    if let Some(job) = job {
2230                        compared.push(job);
2231                        twins.push((file, site, mutant, Some(job)));
2232                    }
2233                }
2234                // A negated comparison that no mutant of the source stands for (on
2235                // floats `<` is not "not `>=`") is compared with the negation written out.
2236                if let (SiteKind::Cmp { op, .. }, Some(job)) =
2237                    (&site.kind, job_of(Mutation::Negate))
2238                    && !compared.contains(&job)
2239                {
2240                    let negated = instrument::SourceMutant {
2241                        start: site.start,
2242                        end: site.end,
2243                        replacement: format!("!({})", site.text),
2244                        what: op.symbol().to_string(),
2245                        into: "!".to_string(),
2246                    };
2247                    twins.push((file, site, negated, Some(job)));
2248                }
2249            }
2250        }
2251        let chosen = spread(twins.len(), wanted);
2252        audit.rebuilt = chosen.len();
2253        let mut twins: Vec<Option<_>> = twins.into_iter().map(Some).collect();
2254        built.extend(chosen.into_iter().filter_map(|nth| twins[nth].take()));
2255    }
2256    let mut by_speed: Vec<&TestBinary> = session.binaries.iter().collect();
2257    by_speed.sort_by_key(|bin| bin.baseline);
2258    // A root replacement removes all of its probes. Other files may still use the runtime.
2259    let root_mutant_suffix = if files.iter().any(|file| {
2260        file.path != root_file
2261            && file
2262                .rendered
2263                .as_ref()
2264                .is_some_and(|rendered| rendered.text != file.original)
2265    }) {
2266        root_suffix.as_str()
2267    } else {
2268        ""
2269    };
2270    if !built.is_empty() {
2271        if options.timeout_seconds.is_some()
2272            && built
2273                .iter()
2274                .any(|(file, _, _, _)| built_sources.contains(file))
2275        {
2276            for bin in &by_speed {
2277                bin.warn_timeout_conflict(None);
2278            }
2279        }
2280        let source_checkpoint = if checkpoint.is_some() {
2281            let keys = built
2282                .iter()
2283                .map(|(file, _, mutation, twin)| {
2284                    serde_json::to_string(&(
2285                        &file.display,
2286                        mutation.start,
2287                        mutation.end,
2288                        &mutation.replacement,
2289                        twin,
2290                    ))
2291                })
2292                .collect::<std::result::Result<Vec<_>, _>>()?;
2293            phase("source", keys)?
2294        } else {
2295            None
2296        };
2297        session.note(&format!(
2298            "building {} mutants one by one (code a probe cannot be put in, or to compare with the probe)",
2299            built.len()
2300        ));
2301        let instrumented = |file: &SourceFile, text: &str, suffix: &str| {
2302            if file.path == root_file {
2303                format!("{text}{suffix}")
2304            } else {
2305                text.to_string()
2306            }
2307        };
2308        // All tests are run against each of them; the quick ones first, since one
2309        // failure is enough.
2310        let mut skipped_targets = BTreeSet::new();
2311        // Per file, the code its builds leave out.
2312        let mut left_out: BTreeMap<&PathBuf, Vec<(usize, usize)>> = BTreeMap::new();
2313        let mut survivors: Vec<(report::Location, Vec<String>)> = vec![];
2314        progress::track(
2315            options.progress,
2316            "source mutants",
2317            built.len(),
2318            |progress| -> Result<()> {
2319                for (index, (file, site, mutant, twin)) in built.iter().enumerate() {
2320                    let cached = source_checkpoint
2321                        .as_ref()
2322                        .map(|phase| phase.get::<Option<Outcome>>(index))
2323                        .transpose()?
2324                        .flatten();
2325                    let left_out = left_out
2326                        .entry(&file.path)
2327                        .or_insert_with(|| built_sources.left_out(file))
2328                        .iter()
2329                        .any(|(from, to)| *from <= site.start && site.end <= *to);
2330                    if left_out || !built_sources.contains(file) {
2331                        if let Some(phase) = source_checkpoint.as_ref().filter(|_| cached.is_none())
2332                        {
2333                            phase.record(index, &Some(Outcome::Unable))?;
2334                        }
2335                        if twin.is_none() {
2336                            report.mutants_not_evaluated += 1;
2337                            report.mutants_not_compiled += 1;
2338                            if skipped_targets.insert((&file.path, site.start, site.end)) {
2339                                report.skipped.push(report::SkippedSite::new(
2340                                    report::location(&file.display, site),
2341                                    file.lines.position(&file.original, site.end),
2342                                    report::SkipReason::SourceNotBuilt,
2343                                    left_out.then(|| {
2344                                        "under a `cfg` that the features of this build turn off"
2345                                            .to_string()
2346                                    }),
2347                                ));
2348                            }
2349                        } else if let Some(audit) = report.audit.as_mut() {
2350                            audit.not_compared += 1;
2351                        }
2352                        progress.complete(progress::Outcome::Unable);
2353                        continue;
2354                    }
2355                    let outcome = if let Some(cached) = cached {
2356                        cached
2357                    } else {
2358                        let mutated = format!(
2359                            "{}{}{}",
2360                            &file.original[..mutant.start],
2361                            mutant.replacement,
2362                            &file.original[mutant.end..]
2363                        );
2364                        // `None`: it does not build. Otherwise what stopped it, if anything did.
2365                        let attempt = || -> Result<Option<Outcome>> {
2366                            state.write(
2367                                &file.path,
2368                                &instrumented(file, &mutated, root_mutant_suffix),
2369                            )?;
2370                            match source_build(&cargo_build()?) {
2371                                SourceBuild::Built => run_source_tests(&by_speed).map(Some),
2372                                SourceBuild::Refused => Ok(None),
2373                                // Nothing is known of the mutant: not one that does not
2374                                // compile, and not one to remember as such.
2375                                SourceBuild::Failed(why) => {
2376                                    session.note(&format!(
2377                                        "a build failed without the compiler refusing the code; its mutant is not evaluated: {why}"
2378                                    ));
2379                                    Ok(Some(Outcome::Unable))
2380                                }
2381                            }
2382                        };
2383                        let attempted = attempt();
2384                        // The file as it was, before another one is changed and whatever went wrong.
2385                        let rendered = file.rendered.as_ref().expect("rendered before building");
2386                        state.write(
2387                            &file.path,
2388                            &instrumented(file, &rendered.text, &root_suffix),
2389                        )?;
2390                        let outcome = attempted?;
2391                        // A run that could not be judged is tried again when the campaign
2392                        // is taken up: only what was established is kept.
2393                        if let Some(phase) = &source_checkpoint
2394                            && outcome != Some(Outcome::Unable)
2395                        {
2396                            phase.record(index, &outcome)?;
2397                        }
2398                        outcome
2399                    };
2400                    progress.complete(outcome.map_or(progress::Outcome::Unable, Into::into));
2401                    if let Some(job) = twin {
2402                        // Only compared: the probe's run is the one that is counted and reported.
2403                        let as_probe = results[*job].survived.is_some();
2404                        let Some(audit) = report.audit.as_mut() else {
2405                            continue;
2406                        };
2407                        // What does not build, what could not be evaluated, and an unconfirmed
2408                        // parallel timeout say nothing about agreement between probe and source.
2409                        match audit_source_comparison(&results[*job], outcome) {
2410                            Some(disagrees) => {
2411                                audit.compared += 1;
2412                                if disagrees {
2413                                    let verdict =
2414                                        |passes: bool| if passes { "passes" } else { "fails" };
2415                                    audit.source_disagreements.push(report::SourceDisagreement {
2416                                        at: report::location(&file.display, site),
2417                                        mutant: report::describe(site, mutation_of(site, mutant)),
2418                                        as_probe: verdict(as_probe).to_string(),
2419                                        built: verdict(!as_probe).to_string(),
2420                                    });
2421                                }
2422                            }
2423                            None => audit.not_compared += 1,
2424                        }
2425                        continue;
2426                    }
2427                    match outcome {
2428                        None => report.unviable_mutants += 1,
2429                        Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
2430                        Some(outcome) => {
2431                            report.mutants_run += 1;
2432                            report.mutants_killed += (outcome != Outcome::Pass) as usize;
2433                            report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
2434                            report.mutants_survived += (outcome == Outcome::Pass) as usize;
2435                        }
2436                    }
2437                    let survived = outcome == Some(Outcome::Pass);
2438                    if survived {
2439                        let at = report::location(&file.display, site);
2440                        // Nothing but the line ends of what was there.
2441                        let removed = mutant.replacement.trim().is_empty();
2442                        let text = match (&site.kind, removed) {
2443                            (SiteKind::Field { .. }, true) => {
2444                                format!("without the field `{}`", report::one_line(&site.text))
2445                            }
2446                            (
2447                                SiteKind::LiteralSet {
2448                                    receiver, argument, ..
2449                                },
2450                                true,
2451                            ) => format!(
2452                                "without `{}` in `{}.contains({})`",
2453                                report::one_line(&mutant.into),
2454                                report::one_line(receiver),
2455                                report::one_line(argument)
2456                            ),
2457                            _ => report::describe(site, mutation_of(site, mutant)),
2458                        };
2459                        match survivors.last_mut() {
2460                            Some((last, texts)) if *last == at => texts.push(text),
2461                            _ => survivors.push((at, vec![text])),
2462                        }
2463                    }
2464                }
2465                Ok(())
2466            },
2467        )?;
2468        if let Some(phase) = &source_checkpoint {
2469            phase.finish_if_complete()?;
2470        }
2471        for (at, survivors) in survivors {
2472            finding_run_survivors.push(survivors.len());
2473            report.findings.push(Finding::Survivor {
2474                at,
2475                survivors,
2476                witness: None,
2477                change_since: None,
2478                advice: None,
2479            });
2480        }
2481    }
2482
2483    // Each change since the revision, undone: do the tests tell it from what was there?
2484    if let Some(revision) = options
2485        .since
2486        .as_deref()
2487        .filter(|_| !options.list && options.shard.is_none())
2488    {
2489        let hunks = scope::hunks(&since_diff(&workspace, revision)?);
2490        let not_built_changes = std::cell::Cell::new(0usize);
2491        let changed: Vec<(&SourceFile, Vec<reverts::Change>)> = files
2492            .iter()
2493            .filter(|file| built_sources.contains(file) || !options.source_only && !options.rebuild)
2494            .filter_map(|file| {
2495                let relative = file
2496                    .path
2497                    .strip_prefix(&copy)
2498                    .ok()?
2499                    .to_string_lossy()
2500                    .replace('\\', "/");
2501                let of_file: Vec<_> = hunks
2502                    .iter()
2503                    .filter(|hunk| hunk.file == relative)
2504                    .cloned()
2505                    .collect();
2506                let mut changes = reverts::changes(&file.original, &of_file);
2507                // Code this build leaves out (a feature that is off) is the same
2508                // program with its change undone: nothing to try.
2509                if options.rebuild || options.source_only {
2510                    for change in &mut changes {
2511                        // The same program undone, in every build: a `cfg` that
2512                        // changed may turn code on or off.
2513                        change.outside = change.undone.as_deref().is_some_and(|undone| {
2514                            built_sources.same_program(file, &file.original, undone)
2515                        });
2516                    }
2517                    not_built_changes.set(
2518                        not_built_changes.get()
2519                            + changes.iter().filter(|change| change.outside).count(),
2520                    );
2521                }
2522                (!changes.is_empty()).then_some((file, changes))
2523            })
2524            .collect();
2525        let not_built_changes = not_built_changes.get();
2526        report.mutants_not_evaluated += not_built_changes;
2527        report.mutants_not_compiled += not_built_changes;
2528        // Those are not tried alone, and still go back with the others.
2529        let total: usize = changed
2530            .iter()
2531            .map(|(_, changes)| changes.iter().filter(|change| !change.outside).count())
2532            .sum();
2533        // A change of the program and its tests in lines that cannot be told apart
2534        // would be undone with the tests: nothing is said of it.
2535        let mixed: usize = files
2536            .iter()
2537            .map(|file| {
2538                let relative = file
2539                    .path
2540                    .strip_prefix(&copy)
2541                    .unwrap_or(&file.path)
2542                    .to_string_lossy()
2543                    .replace('\\', "/");
2544                let of_file: Vec<_> = hunks
2545                    .iter()
2546                    .filter(|hunk| hunk.file == relative)
2547                    .cloned()
2548                    .collect();
2549                reverts::mixed(&file.original, &of_file)
2550            })
2551            .sum();
2552        if mixed > 0 && (options.rebuild || options.source_only) {
2553            report.mutants_not_evaluated += mixed;
2554            session.note(&format!(
2555                "{mixed} changes are of the program and its tests in the same lines: they are not tried undone"
2556            ));
2557        }
2558        if !(options.rebuild || options.source_only) {
2559            report.mutants_not_built += not_built_reverts;
2560        } else if total > 0
2561            || changed.iter().any(|(_, changes)| {
2562                changes.iter().filter(|change| !change.is_subhunk()).count() > 1
2563            })
2564        {
2565            // Also with nothing to try alone: several changes of code that is left out
2566            // may be a change of the build together.
2567            session.note(&format!(
2568                "building {total} changes undone, one by one (the code as it was at {})",
2569                report::short_revision(revision)
2570            ));
2571            let write = |file: &SourceFile, text: &str, suffix: &str| -> Result<()> {
2572                let suffix = if file.path == root_file { suffix } else { "" };
2573                state.write(&file.path, &format!("{text}{suffix}"))
2574            };
2575            // `None`: it does not build.
2576            let undone = |edits: &[(&SourceFile, &str)]| -> Result<Option<Outcome>> {
2577                let attempted = (|| -> Result<Option<Outcome>> {
2578                    for (file, text) in edits {
2579                        write(file, text, root_mutant_suffix)?;
2580                    }
2581                    Ok(match source_build(&cargo_build()?) {
2582                        SourceBuild::Built => Some(run_source_tests(&by_speed)?),
2583                        SourceBuild::Refused => None,
2584                        SourceBuild::Failed(why) => {
2585                            session.note(&format!(
2586                                "a build failed without the compiler refusing the code; the change undone is not evaluated: {why}"
2587                            ));
2588                            Some(Outcome::Unable)
2589                        }
2590                    })
2591                })();
2592                // The files as they were, whatever went wrong.
2593                for (file, _) in edits {
2594                    let rendered = file.rendered.as_ref().expect("rendered before building");
2595                    write(file, &rendered.text, &root_suffix)?;
2596                }
2597                attempted
2598            };
2599            let mut judged = |outcome: Option<Outcome>, at: report::Location, what: String| {
2600                match outcome {
2601                    None => report.unviable_mutants += 1,
2602                    Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
2603                    Some(outcome) => {
2604                        report.mutants_run += 1;
2605                        report.mutants_killed += (outcome != Outcome::Pass) as usize;
2606                        report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
2607                        report.mutants_survived += (outcome == Outcome::Pass) as usize;
2608                    }
2609                }
2610                if outcome == Some(Outcome::Pass) {
2611                    finding_run_survivors.push(1);
2612                    report.findings.push(Finding::Survivor {
2613                        at,
2614                        survivors: vec![what],
2615                        witness: None,
2616                        advice: None,
2617                        change_since: Some(revision.to_string()),
2618                    });
2619                }
2620            };
2621            let place = |file: &SourceFile, change: &reverts::Change| report::Location {
2622                file: file.display.clone(),
2623                line: change.line,
2624                column: 1,
2625                code: change.code.clone(),
2626                ..Default::default()
2627            };
2628            // A change that does not build alone may be one part of several that belong
2629            // together: then all of the file's are undone at once, and at last all of all.
2630            let mut stuck_files = 0;
2631            for (file, changes) in &changed {
2632                let mut stuck = false;
2633                let whole_total = changes.iter().filter(|change| !change.is_subhunk()).count();
2634                let whole_alone = changes
2635                    .iter()
2636                    .filter(|change| !change.is_subhunk() && !change.outside)
2637                    .count();
2638                for change in changes.iter().filter(|change| !change.outside) {
2639                    let outcome = match &change.undone {
2640                        Some(text) => undone(&[(file, text.as_str())])?,
2641                        None => None,
2642                    };
2643                    if !change.is_subhunk() {
2644                        stuck |= outcome.is_none();
2645                    }
2646                    judged(outcome, place(file, change), change.describe());
2647                }
2648                // All together: where one does not build alone, and where what is left
2649                // out now is built once the others are undone (a `cfg` that changed
2650                // along with the code under it), which shows as another program with
2651                // those changes undone too than without them.
2652                let whole = reverts::all_undone(&file.original, changes);
2653                let same = |a: &str, b: &str| built_sources.same_program(file, a, b);
2654                let tried: Vec<reverts::Change> = changes
2655                    .iter()
2656                    .filter(|change| !change.outside)
2657                    .cloned()
2658                    .collect();
2659                let left_out_matter = whole_alone < whole_total
2660                    && match (&whole, reverts::all_undone(&file.original, &tried)) {
2661                        (Some(all), Some(without)) => !same(all, &without),
2662                        _ => true,
2663                    };
2664                // And never a program that is the one that is there.
2665                let another = whole
2666                    .as_deref()
2667                    .is_none_or(|all| !same(all, &file.original));
2668                if whole_total > 1 && another && (stuck || left_out_matter) {
2669                    let outcome = match &whole {
2670                        Some(text) => undone(&[(file, text.as_str())])?,
2671                        None => None,
2672                    };
2673                    stuck = outcome.is_none();
2674                    let first_whole = changes
2675                        .iter()
2676                        .find(|change| !change.is_subhunk())
2677                        .unwrap_or(&changes[0]);
2678                    judged(
2679                        outcome,
2680                        place(file, first_whole),
2681                        format!("with all {whole_total} changes to this file undone"),
2682                    );
2683                }
2684                stuck_files += usize::from(stuck);
2685            }
2686            // All files together: where a file's changes do not build even together,
2687            // and where code that is left out changed, which may count only with the
2688            // changes of another file undone.
2689            let with_left_out = changed.iter().any(|(_, changes)| {
2690                changes
2691                    .iter()
2692                    .any(|change| !change.is_subhunk() && change.outside)
2693            });
2694            if (stuck_files > 0 || with_left_out) && changed.len() > 1 {
2695                let whole: Option<Vec<String>> = changed
2696                    .iter()
2697                    .map(|(file, changes)| reverts::all_undone(&file.original, changes))
2698                    .collect();
2699                let same =
2700                    |file: &SourceFile, a: &str, b: &str| built_sources.same_program(file, a, b);
2701                // Never the program that is there: in some file it has to be another.
2702                let another = whole.as_ref().is_none_or(|texts| {
2703                    changed
2704                        .iter()
2705                        .zip(texts)
2706                        .any(|((file, _), text)| !same(file, text, &file.original))
2707                });
2708                // And what is left out has to count: another program with it undone
2709                // too than with the other changes alone.
2710                let left_out_matter = whole.as_ref().is_none_or(|texts| {
2711                    changed.iter().zip(texts).any(|((file, changes), text)| {
2712                        let tried: Vec<reverts::Change> = changes
2713                            .iter()
2714                            .filter(|change| !change.outside)
2715                            .cloned()
2716                            .collect();
2717                        reverts::all_undone(&file.original, &tried)
2718                            .is_none_or(|without| !same(file, text, &without))
2719                    })
2720                });
2721                if another && (stuck_files > 0 || (with_left_out && left_out_matter)) {
2722                    let outcome = match &whole {
2723                        Some(texts) => {
2724                            let edits: Vec<(&SourceFile, &str)> = changed
2725                                .iter()
2726                                .zip(texts)
2727                                .map(|((file, _), text)| (*file, text.as_str()))
2728                                .collect();
2729                            undone(&edits)?
2730                        }
2731                        None => None,
2732                    };
2733                    let (file, changes) = &changed[0];
2734                    judged(
2735                        outcome,
2736                        place(file, &changes[0]),
2737                        format!("with every change undone, in all {} files", changed.len()),
2738                    );
2739                }
2740            }
2741        }
2742    }
2743
2744    // File by file: the test that shows a difference is put at the end of the file the
2745    // candidate is of, where the names of the file are in scope.
2746    let mut witness_files: Vec<&PathBuf> = vec![];
2747    for candidate in &witness_candidates {
2748        if !witness_files.contains(&&candidate.file) {
2749            witness_files.push(&candidate.file);
2750        }
2751    }
2752    for witness_file in witness_files {
2753        let in_root = *witness_file == root_file;
2754        let witness_candidates: Vec<&witness::Candidate> = witness_candidates
2755            .iter()
2756            .filter(|candidate| candidate.file == *witness_file)
2757            .collect();
2758        let file = files
2759            .iter()
2760            .find(|file| file.path == *witness_file)
2761            .expect("witness candidates are of files that are analysed");
2762        let rendered = file.rendered.as_ref().expect("rendered before building");
2763        let left_out_here = built_sources.left_out(file);
2764        let restore = if in_root {
2765            format!("{}{root_suffix}", rendered.text)
2766        } else {
2767            rendered.text.clone()
2768        };
2769        let library_runners: Vec<_> = session
2770            .binaries
2771            .iter()
2772            .filter(|bin| {
2773                root_exe
2774                    .as_deref()
2775                    .is_some_and(|exe| bin.runner.executable() == Some(exe))
2776            })
2777            .collect();
2778        let ignored = library_runners
2779            .iter()
2780            .find_map(|bin| match &bin.runner {
2781                Runner::Exe(exe) => Some(list_tests(
2782                    exe,
2783                    &bin.cwd,
2784                    &bin.git_ceiling,
2785                    true,
2786                    false,
2787                    bin.work_lock.as_deref(),
2788                )),
2789                _ => None,
2790            })
2791            .transpose()?
2792            .unwrap_or_default();
2793        let runner_for = |scenario: &witness::Scenario| {
2794            library_runners.iter().copied().find(|bin| {
2795                scenario
2796                    .source_test
2797                    .as_ref()
2798                    .is_none_or(|required| match &bin.runner {
2799                        // In a file that is a module, the test's name comes after the
2800                        // module's.
2801                        Runner::Exe(_) if !in_root => {
2802                            let inner = format!("::{required}");
2803                            bin.tests
2804                                .iter()
2805                                .any(|test| test.ends_with(&inner) && !ignored.contains(test))
2806                        }
2807                        Runner::Exe(_) => {
2808                            bin.tests.contains(required) && !ignored.contains(required)
2809                        }
2810                        Runner::Isolated { test, .. } if !in_root => {
2811                            test.ends_with(&format!("::{required}"))
2812                        }
2813                        Runner::Isolated { test, .. } => test == required,
2814                        Runner::Doc { .. } | Runner::Nextest { .. } => false,
2815                    })
2816            })
2817        };
2818        let write_edits = |edits: &[witness::Edit]| -> Result<bool> {
2819            let Some(source) = witness::render_edits(&file.original, edits, None) else {
2820                return Ok(false);
2821            };
2822            let suffix = if in_root { root_mutant_suffix } else { "" };
2823            state.write(&file.path, &format!("{source}{suffix}"))?;
2824            Ok(true)
2825        };
2826        let suite = |edits: &[witness::Edit]| -> Result<Option<Outcome>> {
2827            if !write_edits(edits)? {
2828                return Ok(None);
2829            }
2830            Ok(match source_build(&cargo_build()?) {
2831                SourceBuild::Built => Some(run_source_tests(&by_speed)?),
2832                SourceBuild::Refused => None,
2833                SourceBuild::Failed(why) => {
2834                    session.note(&format!(
2835                        "a build failed without the compiler refusing the code; the mutant is not evaluated: {why}"
2836                    ));
2837                    Some(Outcome::Unable)
2838                }
2839            })
2840        };
2841        let compile_observer = |edits: &[witness::Edit]| -> Result<Option<PathBuf>> {
2842            if !write_edits(edits)? {
2843                return Ok(None);
2844            }
2845            let build = build_test_binaries(true)?;
2846            if !build.status.success() {
2847                return Ok(None);
2848            }
2849            let artifacts = parse_build_output(
2850                &String::from_utf8_lossy(&build.stdout),
2851                &[package.name.as_str()],
2852            );
2853            Ok(root_test_exe(&artifacts))
2854        };
2855        let observe = |scenario: &witness::Scenario,
2856                       baseline: &TestBinary,
2857                       edits: &[witness::Edit],
2858                       field_path: Option<&str>,
2859                       expected: Option<&str>|
2860         -> Result<Option<witness::Observation>> {
2861            let test = scenario.test_edit_with_field(
2862                &file.original,
2863                witness::TEST_NAME,
2864                field_path,
2865                expected,
2866            );
2867            let edits: Vec<_> = edits.iter().cloned().chain([test]).collect();
2868            let Some(exe) = compile_observer(&edits)? else {
2869                return Ok(None);
2870            };
2871            observe_witness(
2872                baseline,
2873                exe,
2874                wrapper.as_deref(),
2875                scenario,
2876                witness::TEST_NAME,
2877                expected.is_some(),
2878                in_root,
2879            )
2880        };
2881        let witness_checkpoint = if checkpoint.is_some() {
2882            let keys = witness_candidates
2883                .iter()
2884                .map(|candidate| {
2885                    let edits = candidate
2886                        .edits
2887                        .iter()
2888                        .map(|edit| (&edit.span, &edit.replacement))
2889                        .collect::<Vec<_>>();
2890                    serde_json::to_string(&(&candidate.description, edits))
2891                })
2892                .collect::<std::result::Result<Vec<_>, _>>()?;
2893            let name = if in_root {
2894                "witness".to_string()
2895            } else {
2896                format!("witness:{}", file.display)
2897            };
2898            phase(&name, keys)?
2899        } else {
2900            None
2901        };
2902        let mut survivors = vec![];
2903        let mut claimed = BTreeSet::new();
2904        progress::track(
2905            options.progress,
2906            "source witness mutants",
2907            witness_candidates.len(),
2908            |progress| -> Result<()> {
2909                for (index, candidate) in witness_candidates.iter().copied().enumerate() {
2910                    let cached = witness_checkpoint
2911                        .as_ref()
2912                        .map(|phase| phase.get::<WitnessTrial>(index))
2913                        .transpose()?
2914                        .flatten();
2915                    let at = witness_location(file, candidate);
2916                    // Code this build leaves out has no mutant to run.
2917                    if !built_sources.contains(file)
2918                        || candidate.edits.iter().any(|edit| {
2919                            left_out_here
2920                                .iter()
2921                                .any(|(from, to)| *from <= edit.span.start && edit.span.end <= *to)
2922                        })
2923                    {
2924                        if let Some(phase) =
2925                            witness_checkpoint.as_ref().filter(|_| cached.is_none())
2926                        {
2927                            phase.record(index, &WitnessTrial::Inapplicable)?;
2928                        }
2929                        if !candidate.existing {
2930                            report.mutants_not_evaluated += 1;
2931                            report.mutants_not_compiled += 1;
2932                            let span = &candidate.edits[0].span;
2933                            report.skipped.push(report::SkippedSite::new(
2934                                at,
2935                                file.lines.position(&file.original, span.end),
2936                                report::SkipReason::SourceNotBuilt,
2937                                Some(
2938                                    "under a `cfg` that the features of this build turn off"
2939                                        .to_string(),
2940                                ),
2941                            ));
2942                        }
2943                        progress.complete(progress::Outcome::Unable);
2944                        continue;
2945                    }
2946                    let existing = candidate
2947                        .existing
2948                        .then(|| {
2949                            report.findings.iter().position(|finding| {
2950                                let location = finding.at();
2951                                location.file == at.file
2952                                    && location.line == at.line
2953                                    && location.column == at.column
2954                                    && finding.survivors().contains(&candidate.description)
2955                                    && (candidate.finding_at.is_none()
2956                                        || !matches!(finding, Finding::InputGap { .. }))
2957                            })
2958                        })
2959                        .flatten();
2960                    // One stronger assertion is enough for a finding, but wait until a
2961                    // witness actually verifies before claiming it so later surviving
2962                    // mutants on the same finding still get a turn if an earlier one fails.
2963                    let existing = existing
2964                        .filter(|index| candidate.finding_at.is_none() || !claimed.contains(index));
2965                    let scenarios: Vec<_> = candidate
2966                        .scenarios
2967                        .iter()
2968                        .filter_map(|scenario| {
2969                            runner_for(scenario).map(|runner| (scenario, runner))
2970                        })
2971                        .take(4)
2972                        .collect();
2973                    let paired = candidate.edits.len() > 1;
2974                    if (candidate.existing && (existing.is_none() || scenarios.is_empty()))
2975                        || (paired && scenarios.is_empty())
2976                    {
2977                        if let Some(phase) =
2978                            witness_checkpoint.as_ref().filter(|_| cached.is_none())
2979                        {
2980                            phase.record(index, &WitnessTrial::Inapplicable)?;
2981                        }
2982                        progress.complete(progress::Outcome::Unable);
2983                        continue;
2984                    }
2985                    // A compound survivor is interesting only if each component fails on
2986                    // its own. Test the source edits without any generated witness tests.
2987                    let trial = if let Some(cached) = cached {
2988                        cached
2989                    } else {
2990                        let attempted = (|| -> Result<WitnessTrial> {
2991                            if paired {
2992                                for edit in &candidate.edits {
2993                                    match suite(std::slice::from_ref(edit))? {
2994                                        Some(Outcome::Fail) => {}
2995                                        Some(Outcome::Unable) => {
2996                                            return Ok(WitnessTrial::Evaluated(Outcome::Unable));
2997                                        }
2998                                        _ => return Ok(WitnessTrial::Inapplicable),
2999                                    }
3000                                }
3001                            }
3002                            Ok(suite(&candidate.edits)?
3003                                .map_or(WitnessTrial::Unviable, WitnessTrial::Evaluated))
3004                        })();
3005                        state.write(&file.path, &restore)?;
3006                        let trial = attempted?;
3007                        if let Some(phase) = &witness_checkpoint
3008                            && !matches!(trial, WitnessTrial::Evaluated(Outcome::Unable))
3009                        {
3010                            phase.record(index, &trial)?;
3011                        }
3012                        trial
3013                    };
3014                    let outcome = match trial {
3015                        WitnessTrial::Inapplicable => {
3016                            progress.complete(progress::Outcome::Unable);
3017                            continue;
3018                        }
3019                        WitnessTrial::Unviable => {
3020                            progress.complete(progress::Outcome::Unable);
3021                            report.unviable_mutants += usize::from(!candidate.existing);
3022                            continue;
3023                        }
3024                        WitnessTrial::Evaluated(outcome) => outcome,
3025                    };
3026                    progress.complete(outcome.into());
3027                    if !candidate.existing {
3028                        match outcome {
3029                            Outcome::Unable => report.mutants_not_evaluated += 1,
3030                            Outcome::Pass => {
3031                                report.mutants_run += 1;
3032                                report.mutants_survived += 1;
3033                            }
3034                            Outcome::Fail => {
3035                                report.mutants_run += 1;
3036                                report.mutants_killed += 1;
3037                            }
3038                            Outcome::Timeout => {
3039                                report.mutants_run += 1;
3040                                report.mutants_killed += 1;
3041                                report.mutants_timed_out += 1;
3042                            }
3043                        }
3044                    }
3045                    if outcome == Outcome::Pass {
3046                        survivors.push(WitnessSurvivor {
3047                            candidate,
3048                            at,
3049                            existing,
3050                            scenarios,
3051                        });
3052                    }
3053                }
3054                Ok(())
3055            },
3056        )?;
3057
3058        if let Some(phase) = &witness_checkpoint {
3059            phase.finish()?;
3060        }
3061        let originals = shared_witnesses(
3062            &file.original,
3063            &survivors,
3064            wrapper.as_deref(),
3065            in_root,
3066            compile_observer,
3067            note,
3068        );
3069        if !survivors.is_empty() {
3070            state.write(&file.path, &restore)?;
3071        }
3072        let originals = originals?;
3073
3074        progress::track(
3075            options.progress,
3076            "distinguishing tests",
3077            survivors.len(),
3078            |progress| -> Result<()> {
3079                for (survivor, original) in survivors.into_iter().zip(originals) {
3080                    if survivor.existing.is_some_and(|index| {
3081                        survivor.candidate.finding_at.is_some() && claimed.contains(&index)
3082                    }) {
3083                        progress.complete(progress::Outcome::Unable);
3084                        continue;
3085                    }
3086                    let mut evidence = None;
3087                    let mut original = original;
3088                    for (scenario, baseline) in survivor.scenarios {
3089                        let shared = original.take();
3090                        let distinction = (|| -> Result<_> {
3091                            if let Some(shared) = shared {
3092                                // Keep the harness and test name identical on both sides.
3093                                let edits: Vec<_> = survivor
3094                                    .candidate
3095                                    .edits
3096                                    .iter()
3097                                    .chain(shared.tests.iter())
3098                                    .cloned()
3099                                    .collect();
3100                                if let Some(exe) = compile_observer(&edits)?
3101                                    && let Some(mutant) = observe_witness(
3102                                        baseline,
3103                                        exe,
3104                                        wrapper.as_deref(),
3105                                        scenario,
3106                                        &shared.name,
3107                                        true,
3108                                        in_root,
3109                                    )
3110                                    .ok()
3111                                    .flatten()
3112                                    && mutant.equals_expected == Some(false)
3113                                    // Re-check the preserved original binary after the mutant
3114                                    // run to reject monotonic external-state drift without rebuilding.
3115                                    && observe_witness(
3116                                        baseline,
3117                                        shared.original_exe.path.clone(),
3118                                        wrapper.as_deref(),
3119                                        scenario,
3120                                        &shared.name,
3121                                        true,
3122                                        in_root,
3123                                    )
3124                                    .ok()
3125                                    .flatten()
3126                                    .is_some_and(|rechecked| {
3127                                        rechecked.equals_expected == Some(true)
3128                                            && rechecked.value == shared.value
3129                                    })
3130                                    && let Some(verified) =
3131                                        scenario.verified(shared.value, mutant.value)
3132                                {
3133                                    return Ok(Some(verified));
3134                                }
3135                                // A combined build can fail or the code can depend on
3136                                // the harness. Retry the original input in isolation.
3137                            }
3138                            let Some(original) = observe(scenario, baseline, &[], None, None)?
3139                            else {
3140                                return Ok(None);
3141                            };
3142                            let value = original.value;
3143                            if witness::is_expected_literal(&value) {
3144                                let Some(mutant) = observe(
3145                                    scenario,
3146                                    baseline,
3147                                    &survivor.candidate.edits,
3148                                    None,
3149                                    Some(&value),
3150                                )?
3151                                else {
3152                                    return Ok(None);
3153                                };
3154                                if mutant.equals_expected != Some(false) || value == mutant.value {
3155                                    return Ok(None);
3156                                }
3157                                let Some(checked) =
3158                                    observe(scenario, baseline, &[], None, Some(&value))?
3159                                else {
3160                                    return Ok(None);
3161                                };
3162                                if checked.equals_expected != Some(true) || checked.value != value {
3163                                    return Ok(None);
3164                                }
3165                                return Ok(scenario.verified(value, mutant.value));
3166                            }
3167                            // Multi-field Debug struct: narrow to a single differing public
3168                            // literal field and compiler-verify `&result.<path> == &(<val>)`.
3169                            if witness::parse_debug_struct(&value).is_none() {
3170                                return Ok(None);
3171                            }
3172                            let Some(raw_mutant) =
3173                                observe(scenario, baseline, &survivor.candidate.edits, None, None)?
3174                            else {
3175                                return Ok(None);
3176                            };
3177                            let Some((path, field_orig, _)) =
3178                                witness::narrow_struct_field(&value, &raw_mutant.value)
3179                            else {
3180                                return Ok(None);
3181                            };
3182                            if !witness::is_expected_literal(&field_orig) {
3183                                return Ok(None);
3184                            }
3185                            let field_path = path.join(".");
3186                            let Some(mutant) = observe(
3187                                scenario,
3188                                baseline,
3189                                &survivor.candidate.edits,
3190                                Some(&field_path),
3191                                Some(&field_orig),
3192                            )?
3193                            else {
3194                                return Ok(None);
3195                            };
3196                            if mutant.equals_expected != Some(false)
3197                                || mutant.value != raw_mutant.value
3198                                || value == mutant.value
3199                            {
3200                                return Ok(None);
3201                            }
3202                            let Some(checked) = observe(
3203                                scenario,
3204                                baseline,
3205                                &[],
3206                                Some(&field_path),
3207                                Some(&field_orig),
3208                            )?
3209                            else {
3210                                return Ok(None);
3211                            };
3212                            if checked.equals_expected != Some(true) || checked.value != value {
3213                                return Ok(None);
3214                            }
3215                            Ok(
3216                                scenario.verified_field(
3217                                    value,
3218                                    mutant.value,
3219                                    field_path,
3220                                    field_orig,
3221                                ),
3222                            )
3223                        })();
3224                        match distinction {
3225                            Ok(Some(mut verified)) => {
3226                                let edits = survivor.candidate.edits.len();
3227                                verified.individually_killed = (edits > 1).then_some(edits);
3228                                evidence = Some(verified);
3229                                break;
3230                            }
3231                            Ok(None) => {}
3232                            Err(err) => note(&format!(
3233                                "could not check a distinguishing test for {}: {err:#}",
3234                                scenario.expression,
3235                            )),
3236                        }
3237                    }
3238                    state.write(&file.path, &restore)?;
3239                    progress.complete(Outcome::Pass.into());
3240                    if let Some(index) = survivor.existing {
3241                        if let Some(evidence) = evidence {
3242                            report.findings[index].set_witness(evidence);
3243                            if survivor.candidate.finding_at.is_some() {
3244                                claimed.insert(index);
3245                            }
3246                        }
3247                    } else {
3248                        finding_run_survivors.push(1);
3249                        report.findings.push(Finding::Survivor {
3250                            at: survivor.at,
3251                            survivors: vec![survivor.candidate.description.clone()],
3252                            advice: survivor
3253                                .candidate
3254                                .advice
3255                                .clone()
3256                                .filter(|_| evidence.is_none()),
3257                            witness: evidence,
3258                            change_since: None,
3259                        });
3260                    }
3261                }
3262                Ok(())
3263            },
3264        )?;
3265    }
3266
3267    report.record_evaluation();
3268    debug_assert_eq!(report.findings.len(), finding_run_survivors.len());
3269    let mut paired_findings: Vec<(Finding, usize)> = report
3270        .findings
3271        .into_iter()
3272        .zip(finding_run_survivors)
3273        .collect();
3274    paired_findings.sort_by(|(a, _), (b, _)| {
3275        let (a, b) = (a.at(), b.at());
3276        (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column))
3277    });
3278    let (sorted_findings, finding_run_survivors): (Vec<_>, Vec<_>) =
3279        paired_findings.into_iter().unzip();
3280    report.findings = sorted_findings;
3281    let places: Vec<FilePlaces> = files
3282        .iter()
3283        .map(|file| FilePlaces {
3284            display: &file.display,
3285            source: &file.original,
3286            lines: &file.lines,
3287            places: &file.places,
3288        })
3289        .collect();
3290    name_findings(&mut report.findings, &places);
3291
3292    // 8. Findings the user has already dealt with.
3293    apply_suppressions_and_finish(
3294        options,
3295        &files,
3296        &mut report,
3297        &finding_run_survivors,
3298        checkpoint.as_ref(),
3299    )?;
3300    debug_assert!(
3301        report.counts_reconcile(),
3302        "report counts do not reconcile: {report:#?}"
3303    );
3304    Ok(report)
3305}
3306
3307fn validate_package_options(options: &Options) -> Result<Vec<&str>> {
3308    if let Some(shard) = options.shard
3309        && (!options.source_only || shard.index >= shard.count)
3310    {
3311        bail!("shards require --source-only and a valid shard index");
3312    }
3313    let mut seen_errors = HashSet::new();
3314    let mut error_values = vec![];
3315    for expression in &options.error_values {
3316        let expression = expression.trim();
3317        // The text is written into the code of probes, each on the line of its site: it
3318        // is one line, and has nothing in it that is not to be seen.
3319        if expression.chars().any(char::is_control) {
3320            bail!(
3321                "invalid --error expression {expression:?}: it has to be on one line, \
3322                 without control characters"
3323            );
3324        }
3325        let parsed = syn::parse_str::<syn::Expr>(expression)
3326            .with_context(|| format!("invalid --error expression {expression:?}"))?;
3327        if seen_errors.insert(quote::ToTokens::to_token_stream(&parsed).to_string()) {
3328            error_values.push(expression);
3329        }
3330    }
3331    let selection = &options.test_selection;
3332    if options.nextest.is_some() {
3333        if !cfg!(unix) {
3334            bail!("the nextest runner is available on Unix");
3335        }
3336        if !options.source_only || options.doc || selection.enabled() {
3337            bail!(
3338                "--test-tool nextest requires --source-only; select tests through the nextest profile"
3339            );
3340        }
3341    }
3342    if options.baseline_jobs > 1 && !selection.enabled() {
3343        bail!("--baseline-jobs requires isolated tests or a test wrapper or selection");
3344    }
3345    if options.doc && selection.enabled() {
3346        bail!("--doc cannot be combined with isolated test selection");
3347    }
3348    if options.source_only && options.jobs > 1 {
3349        eprintln!(
3350            "tmt: warning: --source-only runs mutants serially in one working copy; ignoring --jobs {}",
3351            options.jobs
3352        );
3353    }
3354    Ok(error_values)
3355}
3356
3357struct PreparedWorkCopy {
3358    workspace: PathBuf,
3359    work: PathBuf,
3360    work_lock: Option<Arc<WorkLock>>,
3361    copy: PathBuf,
3362    state: WorkCopy,
3363    external_deps: BTreeSet<PathBuf>,
3364}
3365
3366fn prepare_work_copy(
3367    options: &Options,
3368    metadata: &Metadata,
3369    batch: Option<&WorkspaceBatch<'_>>,
3370    catalogue: Option<&CatalogueSnapshot>,
3371    note: &impl Fn(&str),
3372) -> Result<PreparedWorkCopy> {
3373    let workspace = metadata.workspace_root.canonicalize()?;
3374    let requested_work = catalogue
3375        .map(|catalogue| &catalogue.path)
3376        .or(options.work_dir.as_ref());
3377    let work = match requested_work {
3378        Some(dir) => {
3379            fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
3380            dir.canonicalize()?
3381        }
3382        None => metadata.target_directory.join("tmt"),
3383    };
3384    // The copy is brought up to date on every run, and files that are no longer wanted
3385    // are deleted from it. Make sure it is ours to delete from.
3386    if workspace.starts_with(&work) {
3387        bail!(
3388            "the work directory {} contains the workspace; choose a directory of its own",
3389            work.display()
3390        );
3391    }
3392    fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?;
3393    let work = work.canonicalize()?;
3394    let work_lock = if catalogue.is_none() {
3395        Some(Arc::new(WorkLock::take(&work)?))
3396    } else {
3397        None
3398    };
3399    let stage_root = work.join("src");
3400    let copy_subdir = staged_copy_subdir(&workspace, &options.stage_external)?;
3401    let copy = if copy_subdir.as_os_str().is_empty() {
3402        stage_root.clone()
3403    } else {
3404        stage_root.join(&copy_subdir)
3405    };
3406    let marker = work.join(WORK_MARKER);
3407    if stage_root.exists() && !marker.exists() {
3408        bail!(
3409            "{} exists and was not created by tmt; refusing to delete it. \
3410                 Choose another --work-dir or remove it yourself.",
3411            stage_root.display()
3412        );
3413    }
3414    fs::write(
3415        &marker,
3416        "Working directory of tmt (targeted-mutation). Safe to delete.\n",
3417    )?;
3418    let target_dir = metadata.target_directory.clone();
3419    let forbidden = |path: &Path| {
3420        path == target_dir
3421            || path == work
3422            || batch.is_some_and(|batch| path == batch.work)
3423            || path.file_name().is_some_and(|n| n == ".git")
3424            || (path.parent() == Some(workspace.as_path())
3425                && path.file_name().is_some_and(|n| n == "target"))
3426    };
3427    let state = WorkCopy::open_with_copy_root(&work, &stage_root, &copy);
3428    let fixtures = options
3429        .copy_fixtures
3430        .iter()
3431        .map(|path| fixture_relative(path))
3432        .collect::<Result<Vec<_>>>()?;
3433    let excluded = fixture_exclusions(&workspace, &fixtures, &options.copy_fixture_excludes)?;
3434    let fixture_forbidden = |path: &Path| forbidden(path) || excluded.contains(path);
3435    let skip = |path: &Path| {
3436        fixture_forbidden(path) || path.file_name().is_some_and(|n| n == "node_modules")
3437    };
3438    if options.progress && !options.list {
3439        for path in &excluded {
3440            note(&format!(
3441                "excluded fixture {}",
3442                path.strip_prefix(&workspace).unwrap_or(path).display()
3443            ));
3444        }
3445    }
3446    if catalogue.is_none_or(|catalogue| !catalogue.ready.get()) {
3447        work_directory(&work, "src")?;
3448        real_dir(&copy, &state)?;
3449        if copy != stage_root {
3450            for ancestor in copy.ancestors() {
3451                if ancestor == stage_root || !ancestor.starts_with(&stage_root) {
3452                    break;
3453                }
3454                state.kept.borrow_mut().insert(ancestor.to_path_buf());
3455            }
3456        }
3457        let visible = if options.all_files {
3458            None
3459        } else {
3460            git_visible_files(&workspace)?
3461        };
3462        match visible {
3463            // Only what git would not ignore: build output, caches, local notes and secrets
3464            // that are kept out of the repository stay out of the copy too.
3465            Some(files) => {
3466                let copied = copy_git_visible(&workspace, &copy, files, &workspace, &skip, &state)?;
3467                note(&format!(
3468                    "copied {copied} files (ignored files are left out)"
3469                ));
3470            }
3471            None => copy_tree(&workspace, &copy, &workspace, &skip, &state)?,
3472        }
3473        for relative in &fixtures {
3474            copy_fixture_entry(
3475                &workspace.join(relative),
3476                &copy.join(relative),
3477                &workspace,
3478                &fixture_forbidden,
3479                &state,
3480                &mut BTreeSet::new(),
3481            )?;
3482        }
3483        let mut staged_destinations: Vec<PathBuf> = Vec::new();
3484        let mut folded_ancestors: BTreeMap<String, PathBuf> = BTreeMap::new();
3485        for entry in &options.stage_external {
3486            let (rel, _) = parse_external_rel(&entry.rel)?;
3487            let dst = normalize(&copy.join(&rel));
3488            let copy_rel_in_stage = copy.strip_prefix(&stage_root).unwrap_or(&copy);
3489            let dst_rel_in_stage = dst.strip_prefix(&stage_root).unwrap_or(&dst);
3490            if !dst.starts_with(&stage_root)
3491                || dst == stage_root
3492                || copy.starts_with(&dst)
3493                || dst.starts_with(&copy)
3494                || paths_overlap_case_insensitive(copy_rel_in_stage, dst_rel_in_stage)
3495                || staged_destinations.iter().any(|prev| {
3496                    let prev_rel = prev.strip_prefix(&stage_root).unwrap_or(prev);
3497                    paths_overlap_case_insensitive(prev_rel, dst_rel_in_stage)
3498                })
3499            {
3500                bail!(
3501                    "--stage-external destination collides with the workspace copy or another staged path: {}",
3502                    entry.rel.display()
3503                );
3504            }
3505            for ancestor in dst_rel_in_stage.ancestors() {
3506                if ancestor.as_os_str().is_empty() {
3507                    continue;
3508                }
3509                let folded = ancestor.to_string_lossy().to_lowercase();
3510                if let Some(previous) = folded_ancestors.get(&folded)
3511                    && previous != ancestor
3512                {
3513                    bail!(
3514                        "--stage-external destinations differ only by case: {} and {}",
3515                        previous.display(),
3516                        ancestor.display()
3517                    );
3518                }
3519                folded_ancestors.insert(folded, ancestor.to_path_buf());
3520            }
3521            staged_destinations.push(dst.clone());
3522            let src = if entry.from.is_absolute() {
3523                entry.from.clone()
3524            } else {
3525                workspace.join(&entry.from)
3526            };
3527            copy_external_entry(
3528                &src,
3529                &dst,
3530                None,
3531                &work,
3532                &forbidden,
3533                &state,
3534                &mut BTreeSet::new(),
3535            )?;
3536        }
3537        prune(&stage_root, &state)?;
3538        if options.git_index {
3539            git_index::snapshot(&workspace, &copy)?;
3540        }
3541        let mut external_deps = BTreeSet::new();
3542        if !options.list {
3543            // Relative path dependencies that leave the workspace would point nowhere from the copy.
3544            let mut manifests: Vec<&Path> = metadata
3545                .packages
3546                .iter()
3547                .map(|p| p.manifest_path.as_path())
3548                .collect();
3549            let root_manifest = metadata.workspace_root.join("Cargo.toml");
3550            manifests.push(&root_manifest);
3551            for manifest in manifests {
3552                let Ok(canonical) = manifest.canonicalize() else {
3553                    continue;
3554                };
3555                let (Some(manifest_dir), Ok(relative)) =
3556                    (canonical.parent(), canonical.strip_prefix(&workspace))
3557                else {
3558                    continue;
3559                };
3560                let text = fs::read_to_string(&canonical)?;
3561                let (rewritten, externals) = absolutize_path_dependencies_with_externals(
3562                    &text,
3563                    manifest_dir,
3564                    &workspace,
3565                    &copy,
3566                )?;
3567                external_deps.extend(externals);
3568                if let Some(rewritten) = rewritten {
3569                    state.write(&copy.join(relative), &rewritten)?;
3570                }
3571            }
3572        }
3573        if let Some(catalogue) = catalogue {
3574            state.settle(&workspace)?;
3575            catalogue.ready.set(true);
3576        }
3577        return Ok(PreparedWorkCopy {
3578            workspace,
3579            work,
3580            work_lock,
3581            copy,
3582            state,
3583            external_deps,
3584        });
3585    }
3586    Ok(PreparedWorkCopy {
3587        workspace,
3588        work,
3589        work_lock,
3590        copy,
3591        state,
3592        external_deps: BTreeSet::new(),
3593    })
3594}
3595
3596#[allow(clippy::too_many_arguments)]
3597fn run_audit_phase<'a>(
3598    session: &Session,
3599    files: &[SourceFile],
3600    jobs: &[Job],
3601    results: &mut [JobResult],
3602    timeout_rechecks: &mut report::TimeoutRechecks,
3603    scratch: &Path,
3604    wanted: usize,
3605    workers: usize,
3606    probe_phase: &impl Fn(&str, &[Job]) -> Result<Option<Phase<'a>>>,
3607) -> Result<report::Audit> {
3608    let survivors: Vec<usize> = (0..jobs.len())
3609        .filter(|job| results[*job].survived.is_some())
3610        .collect();
3611    let chosen: Vec<usize> = spread(survivors.len(), wanted)
3612        .into_iter()
3613        .map(|nth| survivors[nth])
3614        .collect();
3615    session.note(&format!(
3616        "audit: running {} of {} surviving mutants against all tests",
3617        chosen.len(),
3618        survivors.len()
3619    ));
3620    let against_all: Vec<Job> = chosen
3621        .iter()
3622        .map(|job| Job {
3623            site: jobs[*job].site,
3624            mutation: jobs[*job].mutation,
3625            tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
3626        })
3627        .collect();
3628    let mut audit = report::Audit {
3629        sampled: chosen.len(),
3630        survivors: survivors.len(),
3631        ..report::Audit::default()
3632    };
3633    let audit_checkpoint = probe_phase("audit", &against_all)?;
3634    for (job, again) in chosen.iter().zip(session.run_jobs(
3635        &against_all,
3636        workers,
3637        "audit mutants",
3638        audit_checkpoint.as_ref(),
3639    )?) {
3640        timeout_rechecks.include(&again);
3641        if again.unable || again.unconfirmed_timeout {
3642            audit.not_audited += 1;
3643        } else if audit_all_tests_disagrees(&again) {
3644            // The verdict of all tests is the one that counts.
3645            results[*job] = again;
3646            let site = files
3647                .iter()
3648                .find_map(|f| Some((f, f.sites.iter().find(|s| s.id == jobs[*job].site)?)));
3649            if let Some((file, site)) = site {
3650                audit
3651                    .disagreements
3652                    .push(report::location(&file.display, site));
3653            }
3654        }
3655    }
3656    session.note("audit: recording the tests once more");
3657    for (index, bin) in session.binaries.iter().enumerate() {
3658        let path = scratch.join(format!("trace-{index}-audit.tsv"));
3659        let _ = fs::remove_file(&path);
3660        let trace_env = path.to_string_lossy().into_owned();
3661        let limit = Duration::from_secs(3600);
3662        let outcome = run_binary(
3663            bin,
3664            None,
3665            &[("TMT_TRACE", &trace_env)],
3666            limit,
3667            RunOutput::Quiet,
3668            1,
3669        )?;
3670        let again = Trace::parse(&fs::read_to_string(&path).unwrap_or_default());
3671        let _ = fs::remove_file(&path);
3672        let records = bin.trace.differences(&again);
3673        if outcome != Outcome::Pass || records > 0 {
3674            audit.trace_differences.push(report::TraceDifference {
3675                binary: bin.name.clone(),
3676                records,
3677                rerun_failed: outcome != Outcome::Pass,
3678            });
3679        }
3680    }
3681    Ok(audit)
3682}
3683
3684fn run_effects_phase(
3685    session: &Session,
3686    files: &[SourceFile],
3687    jobs: &[Job],
3688    effect_jobs: &[(usize, usize)],
3689    scratch: &Path,
3690    workers: usize,
3691    findings: &mut [Finding],
3692) -> Result<()> {
3693    session.note(&format!("tracing {} surviving mutants", effect_jobs.len()));
3694    let sites: BTreeMap<u32, (&str, &Site)> = files
3695        .iter()
3696        .flat_map(|f| f.sites.iter().map(move |s| (s.id, (f.display.as_str(), s))))
3697        .collect();
3698    let traced = run_pool(effect_jobs.len(), workers, |index| {
3699        session.trace_job(
3700            &jobs[effect_jobs[index].1],
3701            scratch,
3702            workers.clamp(1, effect_jobs.len()),
3703        )
3704    })?;
3705    for ((finding, job), mut changes) in effect_jobs.iter().zip(traced) {
3706        // What happens inside the mutated code itself is not an effect of it: deleting
3707        // a statement trivially stops the expressions in it from running.
3708        if let Some((mutated_file, mutated)) = sites.get(&jobs[*job].site) {
3709            for found in changes.values_mut() {
3710                found.retain(|change| {
3711                    sites.get(&change.site()).is_none_or(|(file, site)| {
3712                        file != mutated_file
3713                            || site.end <= mutated.start
3714                            || mutated.end <= site.start
3715                    })
3716                });
3717            }
3718            changes.retain(|_, found| !found.is_empty());
3719        }
3720        if let Finding::AssertionGap {
3721            effects,
3722            effects_of,
3723            ..
3724        } = &mut findings[*finding]
3725        {
3726            *effects = describe_effects(&changes, &sites);
3727            *effects_of = sites
3728                .get(&jobs[*job].site)
3729                .map(|(_, site)| report::describe(site, jobs[*job].mutation));
3730        }
3731    }
3732    Ok(())
3733}
3734
3735fn apply_suppressions_and_finish(
3736    options: &Options,
3737    files: &[SourceFile],
3738    report: &mut Report,
3739    finding_run_survivors: &[usize],
3740    checkpoint: Option<&Checkpoint>,
3741) -> Result<()> {
3742    let files_with_findings: BTreeSet<&str> = report
3743        .findings
3744        .iter()
3745        .map(|finding| finding.at().file.as_str())
3746        .collect();
3747    let ignored: BTreeMap<&str, BTreeMap<usize, String>> = files
3748        .iter()
3749        .filter(|file| files_with_findings.contains(file.display.as_str()))
3750        .map(|f| {
3751            (
3752                f.display.as_str(),
3753                crate::baseline::ignored_lines(&f.original),
3754            )
3755        })
3756        .collect();
3757    let known = match &options.baseline {
3758        Some(path) => Some(crate::baseline::load(path)?),
3759        None => None,
3760    };
3761    let before = report.findings.len();
3762    let mut after_inline: Vec<(Finding, usize)> = Vec::with_capacity(before);
3763    for (finding, run_survivors) in report
3764        .findings
3765        .drain(..)
3766        .zip(finding_run_survivors.iter().copied())
3767    {
3768        let at = finding.at();
3769        if ignored
3770            .get(at.file.as_str())
3771            .is_some_and(|lines| lines.contains_key(&at.line))
3772        {
3773            report.survivor_breakdown.suppressed += run_survivors;
3774        } else {
3775            after_inline.push((finding, run_survivors));
3776        }
3777    }
3778    if let Some(path) = &options.write_baseline {
3779        let unignored: Vec<Finding> = after_inline.iter().map(|(f, _)| f.clone()).collect();
3780        crate::baseline::write(path, &unignored)?;
3781    }
3782    for (finding, run_survivors) in after_inline {
3783        if known.as_ref().is_some_and(|known| known.knows(&finding)) {
3784            report.survivor_breakdown.suppressed += run_survivors;
3785        } else {
3786            report.survivor_breakdown.reported += run_survivors;
3787            report.findings.push(finding);
3788        }
3789    }
3790    report.suppressed = before - report.findings.len();
3791    if let Some(checkpoint) = checkpoint {
3792        checkpoint.finish_if_complete()?;
3793    }
3794    Ok(())
3795}
3796
3797fn workspace_report_prefix(relative: &Path) -> String {
3798    let parts: Vec<_> = relative
3799        .components()
3800        .filter_map(|part| match part {
3801            std::path::Component::Normal(name) => Some(name.to_string_lossy()),
3802            _ => None,
3803        })
3804        .collect();
3805    if parts.is_empty() {
3806        String::new()
3807    } else {
3808        format!("{}/", parts.join("/"))
3809    }
3810}
3811
3812/// Where a directory is in its git repository: `crates/core/`, or nothing at the top
3813/// and outside of any. The files of a report are named from the package; this in front
3814/// of them names them from the repository, as a code-scanning service wants them.
3815fn repository_prefix(dir: &Path) -> String {
3816    let shown = Command::new("git")
3817        .arg("-C")
3818        .arg(dir)
3819        .args(["rev-parse", "--show-prefix"])
3820        .stderr(Stdio::null())
3821        .output();
3822    match shown {
3823        Ok(output) if output.status.success() => {
3824            String::from_utf8_lossy(&output.stdout).trim().to_string()
3825        }
3826        _ => String::new(),
3827    }
3828}
3829
3830/// `wanted` of the numbers below `count`, spread evenly and the same every time; all of
3831/// them where there are no more.
3832fn spread(count: usize, wanted: usize) -> Vec<usize> {
3833    let wanted = wanted.min(count);
3834    (0..wanted).map(|nth| nth * count / wanted).collect()
3835}
3836
3837/// What naming the findings of a file needs to know of it.
3838struct FilePlaces<'a> {
3839    display: &'a str,
3840    source: &'a str,
3841    lines: &'a scope::LineIndex,
3842    /// Every site of the file as (line, column, code), whatever part of it was analysed.
3843    places: &'a [(usize, usize, String)],
3844}
3845
3846/// Gives every finding the item it is in and its name (`report::finding_id`). Which of
3847/// several places with the same code in one item a finding is at is counted over the
3848/// sites of the file, not over the findings: a finding keeps its number when the one
3849/// before it is closed.
3850fn name_findings(findings: &mut [Finding], files: &[FilePlaces]) {
3851    let mut by_file: BTreeMap<String, Vec<&mut Finding>> = BTreeMap::new();
3852    for finding in findings {
3853        by_file
3854            .entry(finding.at().file.clone())
3855            .or_default()
3856            .push(finding);
3857    }
3858    for file in files {
3859        let Some(findings) = by_file.remove(file.display) else {
3860            continue;
3861        };
3862        let items = instrument::named_items(file.source);
3863        let index = instrument::ItemIndex::new(&items);
3864        let item_at = |line, column| {
3865            file.lines
3866                .offset_of(file.source, line, column)
3867                .map_or("", |offset| index.at(offset))
3868        };
3869        let mut positions: BTreeMap<(&str, &str), Vec<(usize, usize)>> = BTreeMap::new();
3870        for (line, column, code) in file.places {
3871            positions
3872                .entry((item_at(*line, *column), code))
3873                .or_default()
3874                .push((*line, *column));
3875        }
3876        for places in positions.values_mut() {
3877            places.sort_unstable();
3878            places.dedup();
3879        }
3880        for finding in findings {
3881            let kind = finding.kind();
3882            let at = finding.at_mut();
3883            let item = item_at(at.line, at.column);
3884            let nth = positions.get(&(item, &at.code)).map_or(0, |places| {
3885                places.partition_point(|&place| place < (at.line, at.column))
3886            });
3887            at.item = item.to_string();
3888            at.id = report::finding_id(kind, at, nth);
3889        }
3890    }
3891}
3892
3893/// The mutation that a change of the source text is, to describe it in the same words.
3894fn mutation_of(site: &Site, mutant: &instrument::SourceMutant) -> Mutation {
3895    match &site.kind {
3896        SiteKind::Cmp { .. } => plan::CmpOp::ALL
3897            .into_iter()
3898            .find(|op| op.symbol() == mutant.into)
3899            .map_or(Mutation::Negate, Mutation::Op),
3900        SiteKind::Arith { op, .. } => {
3901            if mutant.into.trim_end_matches('=') == op.swapped().symbol() {
3902                Mutation::ArithSwap
3903            } else {
3904                Mutation::ArithSwap2
3905            }
3906        }
3907        SiteKind::Guard { .. } => Mutation::Const(mutant.into == "true"),
3908        SiteKind::Logic { .. } => Mutation::LogicSwap,
3909        SiteKind::Not { .. } => Mutation::DropNot,
3910        SiteKind::Range { .. } => Mutation::RangeEnd,
3911        SiteKind::SliceEnd { .. } => Mutation::OtherEnd,
3912        SiteKind::StrAffix { .. } => Mutation::StrContains,
3913        SiteKind::StrReplace { .. } => Mutation::StrReplaceMultiplicity,
3914        SiteKind::Clamp { .. } => {
3915            if mutant.into.contains("lower") {
3916                Mutation::ClampDropLower
3917            } else {
3918                Mutation::ClampDropUpper
3919            }
3920        }
3921        SiteKind::Rounding { op, .. } => {
3922            if mutant.into == op.alt1().name() {
3923                Mutation::RoundAlt1
3924            } else {
3925                Mutation::RoundAlt2
3926            }
3927        }
3928        SiteKind::Quantifier { .. } => Mutation::QuantifierSwap,
3929        SiteKind::SaturatingArith { .. } => Mutation::SaturatingSwap,
3930        SiteKind::StrTrim { op, .. } => {
3931            if mutant.into == op.alt1().name() {
3932                Mutation::TrimAlt1
3933            } else {
3934                Mutation::TrimAlt2
3935            }
3936        }
3937        SiteKind::StrCaseEq { .. } => Mutation::StrExactEq,
3938        SiteKind::Abs { .. } => Mutation::DropAbs,
3939        SiteKind::IterLimit { .. } => Mutation::IterLimitDrop,
3940        SiteKind::EndianSwap { .. } => Mutation::EndianSwap,
3941        SiteKind::BitCount { .. } => Mutation::BitCountSwap,
3942        SiteKind::LoopCtrl { .. } => Mutation::LoopCtrlSwap,
3943        SiteKind::LiteralSet { elements, .. } => {
3944            let idx = elements
3945                .iter()
3946                .position(|(elem, _, _)| elem == &mutant.into)
3947                .unwrap_or(0);
3948            Mutation::DropLiteralElem(idx as u8)
3949        }
3950        // The other kinds have one mutant of the source: a statement, an arm, a field or
3951        // a minus that is not there, a body that is another.
3952        _ => Mutation::Delete,
3953    }
3954}
3955
3956/// The mutations a probe may have run that are the same change as a mutant of the source,
3957/// its own name first. A comparison is planned in other words than it is written in:
3958/// `a != b` for `a == b` is run as the negation, and on integers `a <= b` for `a < b` as
3959/// the bound moved by one.
3960///
3961/// `integers`: the operands are integers, which always have an order. For anything
3962/// else (a float can be NaN) the negation of `>=` is true where `<` is false, and is
3963/// not the same change.
3964fn mutations_like(site: &Site, mutant: &instrument::SourceMutant, integers: bool) -> Vec<Mutation> {
3965    let mut all = vec![mutation_of(site, mutant)];
3966    if let (SiteKind::Cmp { op, .. }, Mutation::Op(into)) = (&site.kind, all[0]) {
3967        let an_order_is_needed = matches!(op, plan::CmpOp::Le | plan::CmpOp::Ge);
3968        if into == op.negated() && (integers || !an_order_is_needed) {
3969            all.push(Mutation::Negate);
3970        }
3971        match (op, into) {
3972            (plan::CmpOp::Lt, plan::CmpOp::Le) | (plan::CmpOp::Ge, plan::CmpOp::Gt) => {
3973                all.push(Mutation::Shift(1))
3974            }
3975            (plan::CmpOp::Gt, plan::CmpOp::Ge) | (plan::CmpOp::Le, plan::CmpOp::Lt) => {
3976                all.push(Mutation::Shift(-1))
3977            }
3978            _ => {}
3979        }
3980    }
3981    all
3982}
3983
3984/// The changes a surviving mutant causes, as up to three sentences. Changes that many
3985/// tests share are mentioned once.
3986fn describe_effects(
3987    changes: &BTreeMap<String, BTreeSet<Change>>,
3988    sites: &BTreeMap<u32, (&str, &Site)>,
3989) -> Vec<String> {
3990    let mut by_change: BTreeMap<&Change, Vec<&str>> = BTreeMap::new();
3991    for (test, found) in changes {
3992        for change in found {
3993            by_change.entry(change).or_default().push(test);
3994        }
3995    }
3996    if by_change.is_empty() {
3997        return vec![
3998            "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(),
3999        ];
4000    }
4001    let mut out = vec![];
4002    for (change, tests) in by_change.iter().take(3) {
4003        let Some((file, site)) = sites.get(&change.site()) else {
4004            continue;
4005        };
4006        let code = report::location(file, site).code;
4007        let at = format!("{file}:{}", site.line);
4008        let who = if tests.is_empty() {
4009            continue;
4010        } else if let Some(first) = tests
4011            .iter()
4012            .copied()
4013            .find(|test| *test != crate::trace::UNKNOWN_TEST)
4014        {
4015            if tests.len() == 1 {
4016                format!("`{first}`")
4017            } else {
4018                format!("`{first}` (and {} more)", tests.len() - 1)
4019            }
4020        } else if tests.len() == 1 {
4021            "a test".to_string()
4022        } else {
4023            format!("a test (and {} more)", tests.len() - 1)
4024        };
4025        out.push(match change {
4026            Change::Returns { value, .. } => {
4027                format!("with the mutant, {who} gets `{value}` from `{code}` ({at})")
4028            }
4029            Change::NowRuns { .. } => format!("with the mutant, {who} now runs `{code}` ({at})"),
4030            Change::NoLongerRuns { .. } => {
4031                format!("with the mutant, {who} no longer runs `{code}` ({at})")
4032            }
4033            Change::NewOutcome { .. } => {
4034                format!("with the mutant, {who} takes `{code}` ({at}) a way it did not before")
4035            }
4036        });
4037    }
4038    if by_change.len() > 3 {
4039        out.push(format!("(and {} more such changes)", by_change.len() - 3));
4040    }
4041    out
4042}
4043
4044#[cfg(test)]
4045mod tests;