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