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