Skip to main content

targeted_mutation/driver/
mod.rs

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